code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-}
module Bot.Types where
import Text.JSON
import Control.Applicative
type ChatId = (String, Int)
data Config = Config
{ cfgToken :: String
, cfgGroup :: Int
, cfgDoor :: String
, cfgGate :: String
, cfgTimeout :: Int -- Seconds
} deriving Show
newtype BotResponse a =
BotResponse { result :: a } deriving Show
instance JSON a => JSON (BotResponse a) where
readJSON (JSObject v) = BotResponse <$> valFromObj "result" v
readJSON _ = empty
newtype UpdateId = UpdateId Int deriving (Show, Num)
data Update = Update
{ updateId :: UpdateId
, updateMessage :: Message
} deriving (Show)
instance JSON Update where
readJSON (JSObject v) =
Update <$> (UpdateId <$> valFromObj "update_id" v)
<*> valFromObj "message" v
readJSON _ = empty
data Message = Message
{ messageId :: Int
, messageFrom :: Maybe User
, messageDate :: Int -- PosixTime
, messageChat :: Chat
, messageText :: Maybe String
} deriving (Show)
instance JSON Message where
readJSON (JSObject v) =
Message <$> valFromObj "message_id" v
<*> maybeFromObj "from" v
<*> valFromObj "date" v
<*> valFromObj "chat" v
<*> maybeFromObj "text" v
readJSON _ = empty
data User = User
{ userId :: Int
, userFirstName :: String
, userLastName :: Maybe String
, username :: Maybe String
} deriving (Show)
instance JSON User where
readJSON (JSObject v) =
User <$> valFromObj "id" v
<*> valFromObj "first_name" v
<*> maybeFromObj "last_name" v
<*> maybeFromObj "username" v
readJSON _ = empty
data Chat = Chat
{ chatId :: Int
, chatType :: String
, chatTitle :: Maybe String
, chatUsername :: Maybe String
, chatFirstName :: Maybe String
, chatLastName :: Maybe String
} deriving (Show)
instance JSON Chat where
readJSON (JSObject v) =
Chat <$> valFromObj "id" v
<*> valFromObj "type" v
<*> maybeFromObj "title" v
<*> maybeFromObj "username" v
<*> maybeFromObj "first_name" v
<*> maybeFromObj "last_name" v
readJSON _ = empty
maybeFromObj :: JSON a => String -> JSObject JSValue -> Result (Maybe a)
maybeFromObj k o = maybe (Ok Nothing)
(\js -> Just <$> readJSON js) (lookup k (fromJSObject o))
|
house4hack/h4h-bot
|
src/Bot/Types.hs
|
gpl-3.0
| 2,396 | 0 | 12 | 647 | 715 | 381 | 334 | 75 | 1 |
module SerializerSpec (spec) where
import Test.Hspec
import Language.Mulang.Serializer (brace, bracket)
import Language.Mulang.Parsers.JavaScript (js)
spec :: Spec
spec = do
describe "Serializer" $ do
it "Serializes non empty asts" $ do
(brace (js "if (c) 1 else 2")) `shouldBe` "{If{Reference{c}}{MuNumber{1.0}}{MuNumber{2.0}}}"
(brace (js "({x: true, z: null})")) `shouldBe` "{MuObject{Sequence{Variable{x}{MuBool{True}}}{Variable{z}{MuNil}}}}"
(brace (js "function f(y) {return x + y}")) `shouldBe` "{Function{f}{Equation{VariablePattern{y}}{UnguardedBody{Return{Application{Primitive{Plus}}{Reference{x}}{Reference{y}}}}}}}"
(brace (js "function f(y) {return y * x}")) `shouldBe` "{Function{f}{Equation{VariablePattern{y}}{UnguardedBody{Return{Application{Primitive{Multiply}}{Reference{y}}{Reference{x}}}}}}}"
it "Serializes non empty asts with brackets" $ do
(bracket (js "if (c) 1 else 2")) `shouldBe` "[If[Reference[c]][MuNumber[1.0]][MuNumber[2.0]]]"
it "Serializes empty asts" $ do
(brace (js "")) `shouldBe` "{None}"
|
mumuki/mulang
|
spec/SerializerSpec.hs
|
gpl-3.0
| 1,112 | 0 | 17 | 180 | 216 | 114 | 102 | 16 | 1 |
-- inspired by Dimensional library
module Maths.Unsafe where
import Prelude
data UPosn
data USpan
data UDiff
data UFree
class ShowType a where
showType :: a -> String
showsType :: (ShowType a) => a -> ShowS
showsType dum = (showType dum ++)
instance ShowType UPosn where
showType _ = "posn"
instance ShowType USpan where
showType _ = "span"
instance ShowType UDiff where
showType _ = "diff"
instance ShowType UFree where
showType _ = "free"
newtype Qty u t x = Qty Int deriving (Enum, Eq, Ord)
instance (ShowType u, ShowType t, ShowType x) => Show (Qty u t x) where
showsPrec p (Qty n) =
('<' :)
. showsType (dum :: t) . spc
. showsType (dum :: x) . spc
. showsType (dum :: u) . spc
. showsPrec p n
. ('>' :)
where
spc = (' ' :)
dum = undefined
class Add a b c | a b -> c
class Sub a b c | a b -> c
class Mul a b c | a b -> c
class Div a b c | a b -> c
{-
- posn + posn -> invalid
- posn - posn -> diff
- posn + span -> posn
- posn - span -> posn
- span + span -> span
- span - span -> diff
- diff + diff -> invalid for now (could be diff)
- diff - diff -> invalid for now (could be diff)
- span * free -> span
- span / span -> free
- span / free -> span
- span % span -> free
- span % free -> span
- abs diff -> span
-}
instance Sub UPosn UPosn UDiff
instance Add UPosn USpan UPosn
instance Sub UPosn USpan UPosn
instance Add USpan USpan USpan
instance Sub USpan USpan UDiff
instance Add UFree UFree UFree
instance Sub UFree UFree UFree
instance Mul USpan UFree USpan
instance Mul UFree UFree UFree
instance Div USpan USpan UFree
instance Div USpan UFree USpan
instance Div UFree UFree UFree
wrap :: (Integral i) => i -> Qty u t x
wrap = Qty . fromIntegral
posn :: (Integral i) => i -> Qty UPosn t x
posn = wrap . fromIntegral
span :: (Integral i) => i -> Qty USpan t x
span n = if n < 0 then error "Negative span" else wrap $ fromIntegral n
diff :: (Integral i) => i -> Qty UDiff t x
diff = wrap
free :: (Integral i) => i -> Qty UFree t x
free = wrap
unwrap :: (Num n) => Qty u t x -> n
unwrap (Qty n) = fromIntegral n
convert :: Qty u1 t1 x1 -> Qty u2 t2 x2
convert = fix1 id
fix1 :: (Int -> Int) -> Qty u1 t1 x1 -> Qty u2 t2 x2
fix1 f = wrap . f . unwrap
fix2 :: (Int -> Int -> Int) -> Qty u1 t1 x1 -> Qty u2 t2 x2 -> Qty u3 t3 x3
fix2 f a b = wrap $ f (unwrap a) (unwrap b)
fix22 :: (Int -> Int -> (Int, Int)) -> Qty u1 t1 x1 -> Qty u2 t2 x2
-> (Qty u3 t3 x3, Qty u3 t3 x3)
fix22 f a b = case f (unwrap a) (unwrap b) of (a, b) -> (wrap a, wrap b)
infixl 6 +., -.
infix 7 /%.
infixl 7 *., /., %.
(+.) :: (Add a b c) => Qty a t x -> Qty b t x -> Qty c t x
(+.) = fix2 (+)
(-.) :: (Sub a b c) => Qty a t x -> Qty b t x -> Qty c t x
(-.) = fix2 (-)
(*.) :: (Mul a b c) => Qty a t x -> Qty b t x -> Qty c t x
(*.) = fix2 (*)
(/%.) :: (Div a b c) => Qty a t x -> Qty b t x -> (Qty c t x, Qty c t x)
(/%.) = fix22 divMod
(/.) :: (Div a b c) => Qty a t x -> Qty b t x -> Qty c t x
(/.) a b = fst $ a /%. b
(%.) :: (Div a b c) => Qty a t x -> Qty b t x -> Qty c t x
(%.) a b = snd $ a /%. b
sum' :: (Add u u u) => [Qty u t x] -> Qty u t x
sum' = foldr (+.) $ wrap 0
abs' :: Diff t x -> Span t x
abs' = fix1 abs
type Posn t x = Qty UPosn t x
type Span t x = Qty USpan t x
type Diff t x = Qty UDiff t x
type Free t x = Qty UFree t x
data X
data Y
instance ShowType X where
showType _ = "x"
instance ShowType Y where
showType _ = "y"
type XY u t = (Qty u t X, Qty u t Y)
type XYPosn t = XY UPosn t
type XYSpan t = XY USpan t
type XYDiff t = XY UDiff t
wrapXY :: (Integral i) => i -> i -> XY u t
wrapXY x y = (wrap x, wrap y)
posnXY :: (Integral i) => i -> i -> XYPosn t
posnXY = wrapXY
spanXY :: (Integral i) => i -> i -> XYSpan t
spanXY x y = wrapXY (abs x) (abs y)
diffXY :: (Integral i) => i -> i -> XYDiff t
diffXY = wrapXY
instance (ShowType t, ShowType x) => Num (Free t x) where
(+) = fix2 (+)
(*) = fix2 (*)
(-) = fix2 (-)
abs = fix1 abs
signum = fix1 signum
fromInteger = wrap . fromInteger
instance (ShowType t, ShowType x) => Real (Free t x) where
toRational = toRational . unwrap
instance (ShowType t, ShowType x) => Integral (Free t x) where
quotRem = fix22 quotRem
divMod = fix22 divMod
toInteger = toInteger . unwrap
|
ktvoelker/argon
|
src/Maths/Unsafe.hs
|
gpl-3.0
| 4,273 | 0 | 15 | 1,153 | 2,035 | 1,074 | 961 | -1 | -1 |
{-
This file is part of the Haskell Qlogic Library.
The Haskell Qlogic Library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Haskell Qlogic Library 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the Haskell Qlogic Library. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE DeriveDataTypeable #-}
module Qlogic.ArcSat where
import Prelude hiding ((+), max, not, (&&), (||))
import qualified Prelude as Prelude
import qualified Data.List as List
import Data.Typeable
import qualified Qlogic.Assign as A
import Qlogic.Arctic hiding ((<), (<=))
import Qlogic.Boolean
import Qlogic.Formula
import qualified Qlogic.NatSat as N
import Qlogic.PropositionalFormula
import qualified Qlogic.SatSolver as Sat
type ArcFormula l = (PropFormula l, [PropFormula l])
data ArcBZVec a = InfBit a | BZVec a Int
deriving (Eq, Ord, Show, Typeable)
instance (Eq a, Ord a, Show a, Typeable a) => PropAtom (ArcBZVec a)
data Size = Bits Int
| Bound ArcInt
deriving (Show, Typeable)
instance Eq Size where
a == b = bound a == bound b
instance Ord Size where
compare a b = compare (bound a) (bound b)
arcToBits :: ArcInt -> Int
arcToBits MinusInf = 1
arcToBits (Fin n) | n <= 1 = 1
| otherwise = succ $ arcToBits $ Fin $ n `div` 2
bitsToArc :: Int -> ArcInt
bitsToArc n = Fin $ (2 ^ n) - 1
arcToFormula :: Eq l => ArcInt -> ArcFormula l
arcToFormula MinusInf = (Top, [Bot])
arcToFormula (Fin x) = (Bot, N.natToFormula x)
bits :: Size -> Int
bits (Bits n) = n
bits (Bound n) = arcToBits n
bound :: Size -> ArcInt
bound (Bits n) = bitsToArc n
bound (Bound n) = n
intbound :: Size -> Int
intbound = arcToInt . bound
increment :: Size -> Size
increment (Bits n) = Bits $ n Prelude.+ 1
increment (Bound MinusInf) = Bound $ Fin 1
increment (Bound (Fin n)) = Bound $ Fin $ 2 * n Prelude.+ 1
padBots :: Int -> ArcFormula l -> ArcFormula l
padBots n (b, xs) = (b, N.padBots n xs)
-- truncFront :: Eq l => ArcFormula l -> ArcFormula l
-- truncFront (b, xs) = (b, truncFront' xs)
--
-- truncFront' :: Eq l => [PropFormula l] -> [PropFormula l]
-- truncFront' xs | length xs <= 2 = xs
-- | otherwise = if x1 == x2 then truncFront' (x1 : xs') else xs
-- where x1 = head xs
-- x2 = head $ tail xs
-- xs' = tail $ tail xs
truncTo :: Int -> ArcFormula l -> ArcFormula l
truncTo n (b, xs) = (b, N.truncTo n xs)
mTruncTo :: (Ord l, Sat.Solver s l) => Int -> ArcFormula l -> N.NatMonad s l (ArcFormula l)
mTruncTo n (b, xs) = do xs' <- N.mTruncTo n xs
return (b, xs')
mAdd :: (Eq l, Sat.Solver s l) => ArcFormula l -> ArcFormula l -> N.NatMonad s l (ArcFormula l)
mAdd p@(a, xs) q@(b, ys) | lengthdiff > 0 = mAdd (padBots lengthdiff p) q
| lengthdiff < 0 = mAdd q p
| otherwise = do c1 <- N.maybeFreshVar $ p `mGeq` q
c2 <- N.maybeFreshVar $ return $ a && b
cs <- mapM (N.maybeFreshVar . return) $ zipWith (ite c1) xs ys
return (c2, cs)
where lengthdiff = length ys - length xs
mTimes :: (Ord l, Sat.Solver s l) => ArcFormula l -> ArcFormula l -> N.NatMonad s l (ArcFormula l)
mTimes p@(a, xs) q@(b, ys) | lengthdiff > 0 = mTimes (padBots lengthdiff p) q
| lengthdiff < 0 = mTimes q p
| otherwise = do c <- N.maybeFreshVar $ return $ (a || b)
uress' <- N.mAdd xs ys
uress <- mapM (N.maybeFreshVar . return . (not c &&)) uress'
return (c, uress)
where lengthdiff = length ys - length xs
mGrt :: (Eq l, Sat.Solver s l) => ArcFormula l -> ArcFormula l -> N.NatMonad s l (PropFormula l)
p@(a, xs) `mGrt` q@(b, ys) | lengthdiff > 0 = padBots lengthdiff p `mGrt` q
| lengthdiff < 0 = p `mGrt` padBots (abs lengthdiff) q
| otherwise = do subresult <- xs `N.mGrt` ys
return $ b || (not a && subresult)
where lengthdiff = length ys - length xs
mGeq :: (Eq l, Sat.Solver s l) => ArcFormula l -> ArcFormula l -> N.NatMonad s l (PropFormula l)
p@(a, xs) `mGeq` q@(b, ys) | lengthdiff > 0 = padBots lengthdiff p `mGeq` q
| lengthdiff < 0 = do p `mGeq` padBots (abs lengthdiff) q
| otherwise = do subresult <- xs `N.mGeq` ys
return $ b || (not a && subresult)
where lengthdiff = length ys - length xs
mEqu :: (Eq l, Sat.Solver s l) => ArcFormula l -> ArcFormula l -> N.NatMonad s l (PropFormula l)
(a, xs) `mEqu` (b, ys) = do subresult <- xs `N.mEqu` ys
return $ (a <-> b) && subresult
soundInf :: (Eq l, PropAtom a) => Size -> a -> PropFormula l
soundInf n v = soundInf' (bits n) v
soundInf' :: (Eq l, PropAtom a) => Int -> a -> PropFormula l
soundInf' n v = propAtom (InfBit v) --> bigAnd (map (not . propAtom . BZVec v) [1..n])
-- arcAtom :: (Eq l, PropAtom a) => N.Size -> a -> ArcFormula l
-- arcAtom size a = nBitVar (N.bits size) a
arcAtom :: (Eq l, PropAtom a) => Size -> a -> ArcFormula l
arcAtom n v = (propAtom $ InfBit v, arcAtom' 1 (bits n) v)
arcAtomM :: (Eq l, Sat.Solver s l, PropAtom a) => Size -> a -> N.NatMonad s l (ArcFormula l)
arcAtomM n v = do N.enforce [soundInf n v]
return $ arcAtom n v
arcAtom' :: (Eq l, PropAtom a) => Int -> Int -> a -> [PropFormula l]
arcAtom' i n v | i <= n = propAtom (BZVec v i) : arcAtom' (i Prelude.+ 1) n v
| otherwise = []
baseFromVec :: (Ord a, Show a, Typeable a) => ArcBZVec a -> a
baseFromVec (InfBit x) = x
baseFromVec (BZVec x _) = x
eval :: Ord l => ArcFormula l -> A.Assign l -> ArcInt
eval (f, fs) ass = boolsToInt $ (A.eval f ass, map (flip A.eval ass) fs)
boolsToInt :: (Bool, [Bool]) -> ArcInt
boolsToInt (True, ps) = if any id ps then error "Qlogic.ArcSat.boolsToInt: Incorrect Encoding of MinusInf" else MinusInf
boolsToInt (False, ps) = Fin $ boolsToInt' ps
boolsToInt' :: [Bool] -> Int
boolsToInt' = List.foldl' f 0
where f n True = 2 * n Prelude.+ 1
f n False = 2 * n
|
mzini/qlogic
|
Qlogic/ArcSat.hs
|
gpl-3.0
| 7,035 | 0 | 13 | 2,250 | 2,486 | 1,286 | 1,200 | 107 | 2 |
module Language.SMTLib2.Boolector (BoolectorBackend(),boolectorBackend,withBoolector) where
import Language.SMTLib2
import Language.SMTLib2.Internals
import Language.SMTLib2.Internals.Operators
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Fix
import Data.Bits
import Data.Typeable
import Data.Proxy
import Data.Foldable (foldlM)
import Data.List (genericIndex)
import Foreign.Ptr
import Foreign.C
import Foreign.Marshal
import Foreign.Storable
data BoolectorBackend = BoolectorBackend { boolectorInstance :: Btor
, boolectorNextVar :: Integer
, boolectorNameCount :: Map String Integer
, boolectorVars :: Map Integer (BtorNode,String)
, boolectorAssumeState :: Bool
}
withBoolector :: SMT' IO a -> IO a
withBoolector act = do
b <- boolectorBackend
withSMTBackend b act
boolectorBackend :: IO BoolectorBackend
boolectorBackend = do
btor <- boolectorNew
return $ BoolectorBackend { boolectorInstance = btor
, boolectorNextVar = 0
, boolectorNameCount = Map.empty
, boolectorVars = Map.empty
, boolectorAssumeState = False }
instance SMTBackend BoolectorBackend IO where
smtGetNames btor = return $ \i -> case Map.lookup i (boolectorVars btor) of
Just (_,name) -> name
smtNextName btor = return $ \name -> case name of
Nothing -> escapeName (Right $ boolectorNextVar btor)
Just name' -> escapeName $ Left
(name',
Map.findWithDefault 0 name'
(boolectorNameCount btor))
smtHandle btor (SMTSetLogic _) = return ((),btor)
smtHandle btor (SMTGetInfo SMTSolverName) = return ("boolector",btor)
smtHandle btor (SMTGetInfo SMTSolverVersion) = return ("unknown",btor)
smtHandle btor (SMTSetOption (ProduceModels True)) = do
boolectorEnableModelGen (boolectorInstance btor)
return ((),btor)
smtHandle btor (SMTSetOption _) = return ((),btor)
smtHandle btor SMTDeclaredDataTypes = return (emptyDataTypeInfo,btor)
smtHandle btor (SMTDeclareFun name) = do
case funInfoArgSorts name of
[] -> return ()
_ -> error "smtlib2-boolector: No support for uninterpreted functions."
mkVar btor name (funInfoSort name)
smtHandle btor (SMTAssert expr Nothing Nothing) = do
nd <- exprToNode [] Map.empty btor expr
if boolectorAssumeState btor
then boolectorAssume (boolectorInstance btor) nd
else boolectorAssert (boolectorInstance btor) nd
return ((),btor)
smtHandle btor (SMTCheckSat _ _) = do
res <- boolectorSat (boolectorInstance btor)
return (if res
then Sat
else Unsat,btor)
smtHandle _ (SMTDeclareDataTypes _) = error "smtlib2-boolector: No support for data-types."
smtHandle _ (SMTDeclareSort _ _) = error "smtlib2-boolector: No support for sorts."
smtHandle btor SMTPush
= if boolectorAssumeState btor
then error $ "smtlib2-boolector: Only one stack level is supported"
else return ((),btor { boolectorAssumeState = True })
smtHandle btor SMTPop = return ((),btor { boolectorAssumeState = False })
smtHandle btor (SMTDefineFun name (_::Proxy arg) ann expr) = do
nd <- case getTypes (undefined::arg) ann of
[] -> exprToNode [] Map.empty btor expr
argTps -> do
params <- mapM (\(ProxyArg u ann,i) -> do
let w = case getSort u ann of
Fix BoolSort -> 1
Fix (BVSort { bvSortWidth = w' }) -> w'
sort -> error $ "smtlib2-boolector: Parameter type "++show sort++" not supported."
res <- boolectorParam (boolectorInstance btor) (fromIntegral w)
("farg_"++show i)
return res
) (zip argTps [0..])
nd <- exprToNode params Map.empty btor expr
boolectorFun (boolectorInstance btor) params nd
return (vid,btor { boolectorNextVar = vid+1
, boolectorNameCount = ncs
, boolectorVars = Map.insert vid (nd,rname)
(boolectorVars btor) })
where
vid = boolectorNextVar btor
(rname,ncs) = case name of
Nothing -> (escapeName (Right vid),boolectorNameCount btor)
Just name' -> let (nc,ncs) = case Map.insertLookupWithKey (const (+)) name' 1
(boolectorNameCount btor) of
(Just nc,ncs) -> (nc,ncs)
(Nothing,ncs) -> (0,ncs)
in (escapeName (Left (name',nc)),ncs)
smtHandle btor (SMTGetValue (expr :: SMTExpr t)) = do
nd <- exprToNode [] Map.empty btor expr
let sort = getSort (undefined::t) (extractAnnotation expr)
case sort of
Fix (BVSort { bvSortWidth = w
, bvSortUntyped = unt }) -> do
assign <- boolectorBVAssignment (boolectorInstance btor) nd
let res = foldl
(\cval n -> (shiftL cval 1) +
(case n of
One -> 1
Zero -> 0
DontCare -> 0)) 0 assign
if unt
then (case cast (BitVector res :: BitVector BVUntyped) of
Just r -> return (r,btor))
else (reifyNat w (\(_::Proxy bw) -> case cast (BitVector res :: BitVector (BVTyped bw)) of
Just r -> return (r,btor)))
Fix BoolSort -> do
[assign] <- boolectorBVAssignment (boolectorInstance btor) nd
let res = case assign of
One -> True
Zero -> False
DontCare -> False
case cast res of
Just r -> return (r,btor)
_ -> error $ "smtlib2-boolector: Getting values of sort "++show sort++" not supported."
smtHandle _ SMTGetProof = error "smtlib2-boolector: Proof extraction not supported."
smtHandle _ SMTGetUnsatCore = error "smtlib2-boolector: Unsat core extraction not supported."
smtHandle btor (SMTSimplify expr) = return (expr,btor)
smtHandle _ (SMTGetInterpolant _) = error "smtlib2-boolector: Interpolant extraction not supported."
smtHandle btor (SMTComment _) = return ((),btor)
smtHandle btor SMTExit = do
boolectorDelete (boolectorInstance btor)
return ((),btor)
exprToNode :: SMTType a => [BtorNode] -> Map Integer (Map Integer BtorNode) -> BoolectorBackend
-> SMTExpr a -> IO BtorNode
exprToNode _ _ btor (Var name ann) = do
case Map.lookup name (boolectorVars btor) of
Just (nd,_) -> return nd
exprToNode _ qmp btor (QVar p q ann) = case Map.lookup p qmp of
Just mp' -> case Map.lookup q mp' of
Just nd -> return nd
exprToNode args _ _ (FunArg i _) = return $ args `genericIndex` i
exprToNode _ _ btor e@(Const c ann) = do
case mangle of
PrimitiveMangling f -> do
let val = f c ann
case val of
BoolValue True -> boolectorTrue (boolectorInstance btor)
BoolValue False -> boolectorFalse (boolectorInstance btor)
BVValue { bvValueWidth = w
, bvValueValue = v }
-> if v < 0
then boolectorInt (boolectorInstance btor) (fromIntegral v) (fromIntegral w)
else boolectorUnsignedInt (boolectorInstance btor) (fromIntegral v) (fromIntegral w)
_ -> error $ "smtlib2-boolector: Boolector backend doesn't support value "++show val
_ -> error $ "smtlib2-boolector: Boolector backend doesn't support constant "++show e
exprToNode args qmp btor (Let lvl defs body) = do
nqmp <- foldlM (\cmp (i,expr) -> do
nd <- exprToNode args cmp btor expr
return $ Map.insertWith Map.union lvl (Map.singleton i nd) cmp
) qmp (zip [0..] defs)
exprToNode args nqmp btor body
exprToNode mp qmp btor (App SMTEq [x,y]) = do
ndx <- exprToNode mp qmp btor x
ndy <- exprToNode mp qmp btor y
boolectorEq (boolectorInstance btor) ndx ndy
exprToNode mp qmp btor (App (SMTFun fun _) args) = do
funNd <- case Map.lookup fun (boolectorVars btor) of
Just (nd,_) -> return nd
let (argLst,_) = unpackArgs (\arg _ _ -> (exprToNode mp qmp btor arg,())) args (extractArgAnnotation args) ()
argNds <- sequence argLst
boolectorApply (boolectorInstance btor) argNds funNd
exprToNode mp qmp btor (App (SMTLogic op) args) = do
nd:nds <- mapM (exprToNode mp qmp btor) args
let rop = case op of
And -> boolectorAnd
Or -> boolectorOr
XOr -> boolectorXOr
Implies -> boolectorImplies
foldlM (rop (boolectorInstance btor)) nd nds
exprToNode mp qmp btor (App SMTNot e) = do
nd <- exprToNode mp qmp btor e
boolectorNot (boolectorInstance btor) nd
exprToNode mp qmp btor (App SMTDistinct [x,y]) = do
ndx <- exprToNode mp qmp btor x
ndy <- exprToNode mp qmp btor y
res <- boolectorEq (boolectorInstance btor) ndx ndy
boolectorNot (boolectorInstance btor) res
exprToNode mp qmp btor (App SMTITE (c,ifT,ifF)) = do
ndC <- exprToNode mp qmp btor c
ndIfT <- exprToNode mp qmp btor ifT
ndIfF <- exprToNode mp qmp btor ifF
boolectorCond (boolectorInstance btor) ndC ndIfT ndIfF
exprToNode mp qmp btor (App (SMTBVComp op) (e1,e2)) = do
n1 <- exprToNode mp qmp btor e1
n2 <- exprToNode mp qmp btor e2
(case op of
BVULE -> boolectorULte
BVULT -> boolectorULt
BVUGE -> boolectorUGte
BVUGT -> boolectorUGt
BVSLE -> boolectorSLte
BVSLT -> boolectorSLt
BVSGE -> boolectorSGte
BVSGT -> boolectorSGt
) (boolectorInstance btor) n1 n2
exprToNode mp qmp btor (App (SMTBVBin op) (e1::SMTExpr (BitVector a),e2)) = do
n1 <- exprToNode mp qmp btor e1
n2 <- exprToNode mp qmp btor e2
n2' <- if (case op of
BVSHL -> True
BVLSHR -> True
BVASHR -> True
_ -> False)
then (do
let bw1 = getBVSize (Proxy::Proxy a) (extractAnnotation e1)
bw2 = getBVSize (Proxy::Proxy a) (extractAnnotation e2)
tw = ceiling $ logBase 2 (fromInteger bw1)
case compare bw2 tw of
EQ -> return n2
GT -> boolectorSlice (boolectorInstance btor) n2 (fromIntegral $ tw-1) 0)
else return n2
(case op of
BVAdd -> boolectorAdd
BVSub -> boolectorSub
BVMul -> boolectorMul
BVURem -> boolectorURem
BVSRem -> boolectorSRem
BVUDiv -> boolectorUDiv
BVSDiv -> boolectorSDiv
BVSHL -> boolectorSLL
BVLSHR -> boolectorSRL
BVASHR -> boolectorSRA
BVXor -> boolectorXOr
BVAnd -> boolectorAnd
BVOr -> boolectorOr) (boolectorInstance btor) n1 n2'
exprToNode mp qmp btor (App (SMTBVUn op) e) = do
n <- exprToNode mp qmp btor e
(case op of
BVNot -> boolectorNot
BVNeg -> boolectorNeg) (boolectorInstance btor) n
exprToNode mp qmp btor (App SMTSelect (arr,i)) = do
ndArr <- exprToNode mp qmp btor arr
let (argLst,_) = unpackArgs (\arg _ _ -> (exprToNode mp qmp btor arg,())) i (extractArgAnnotation i) ()
[ndI] <- sequence argLst
boolectorRead (boolectorInstance btor) ndArr ndI
exprToNode mp qmp btor (App SMTStore (arr,i,v)) = do
ndArr <- exprToNode mp qmp btor arr
let (argLst,_) = unpackArgs (\arg _ _ -> (exprToNode mp qmp btor arg,())) i (extractArgAnnotation i) ()
[ndI] <- sequence argLst
ndV <- exprToNode mp qmp btor v
boolectorWrite (boolectorInstance btor) ndArr ndI ndV
exprToNode mp qmp btor (App SMTConcat (e1,e2)) = do
n1 <- exprToNode mp qmp btor e1
n2 <- exprToNode mp qmp btor e2
boolectorConcat (boolectorInstance btor) n1 n2
exprToNode mp qmp btor (App (SMTExtract prStart prLen) e) = do
n <- exprToNode mp qmp btor e
let start = reflectNat prStart 0
len = reflectNat prLen 0
boolectorSlice (boolectorInstance btor) n (fromIntegral $ start+len-1) (fromIntegral start)
exprToNode mp qmp btor (UntypedExpr e) = exprToNode mp qmp btor e
exprToNode mp qmp btor (UntypedExprValue e) = exprToNode mp qmp btor e
exprToNode _ _ _ e = error $ "smtlib2-boolector: No support for expression: "++show e
mkVar :: BoolectorBackend -> FunInfo -> Sort -> IO (Integer,BoolectorBackend)
mkVar btor info sort = do
let vid = boolectorNextVar btor
(name,ncs) = case funInfoName info of
Nothing -> (escapeName (Right vid),
boolectorNameCount btor)
Just name' -> case Map.lookup name' (boolectorNameCount btor) of
Nothing -> (escapeName (Left (name',0)),
Map.insert name' 1 (boolectorNameCount btor))
Just nc -> (escapeName (Left (name',nc)),
Map.insert name' (nc+1) (boolectorNameCount btor))
nd <- case sort of
Fix BoolSort -> boolectorVar (boolectorInstance btor) 1 name
Fix (BVSort { bvSortWidth = w }) -> boolectorVar (boolectorInstance btor) (fromIntegral w) name
Fix (ArraySort [Fix (BVSort { bvSortWidth = idx_w })] (Fix (BVSort { bvSortWidth = el_w })))
-> boolectorArray (boolectorInstance btor) (fromIntegral el_w) (fromIntegral idx_w) name
_ -> error $ "smtlib2-boolector: Boolector backend doesn't support sort "++show sort
return (vid,btor { boolectorNextVar = vid+1
, boolectorNameCount = ncs
, boolectorVars = Map.insert vid (nd,name) (boolectorVars btor)
})
newtype BtorNode = BtorNode (Ptr BtorNode) deriving (Storable)
newtype BtorSort = BtorSort (Ptr BtorSort) deriving (Storable)
newtype Btor = Btor (Ptr Btor) deriving (Storable)
foreign import capi "boolector.h boolector_new"
boolectorNew :: IO Btor
foreign import capi "boolector.h boolector_clone"
boolectorClone :: Btor -> IO Btor
foreign import capi "boolector.h boolector_enable_model_gen"
boolectorEnableModelGen :: Btor -> IO ()
foreign import capi "boolector.h boolector_generate_model_for_all_reads"
boolectorEnableModelForAllReads :: Btor -> IO ()
foreign import capi "boolector.h boolector_enable_inc_usage"
boolectorEnableIncUsage :: Btor -> IO ()
boolectorSetSatSolver :: Btor -> String -> IO ()
boolectorSetSatSolver btor name
= withCString name (\name' -> boolectorSetSatSolver_ btor name')
foreign import capi "boolector.h boolector_set_sat_solver"
boolectorSetSatSolver_ :: Btor -> CString -> IO ()
foreign import capi "boolector.h boolector_set_rewrite_level"
boolectorSetRewriteLevel :: Btor -> CInt -> IO ()
foreign import capi "boolector.h boolector_get_refs"
boolectorGetRefs :: Btor -> IO CInt
foreign import capi "boolector.h boolector_delete"
boolectorDelete :: Btor -> IO ()
foreign import capi "boolector.h boolector_const"
boolectorConst :: Btor -> CString -> IO BtorNode
foreign import capi "boolector.h boolector_zero"
boolectorZero :: Btor -> CInt -> IO BtorNode
foreign import capi "boolector.h boolector_false"
boolectorFalse :: Btor -> IO BtorNode
foreign import capi "boolector.h boolector_ones"
boolectorOnes :: Btor -> CInt -> IO BtorNode
foreign import capi "boolector.h boolector_true"
boolectorTrue :: Btor -> IO BtorNode
foreign import capi "boolector.h boolector_one"
boolectorOne :: Btor -> CInt -> IO BtorNode
foreign import capi "boolector.h boolector_unsigned_int"
boolectorUnsignedInt :: Btor -> CUInt -> CInt -> IO BtorNode
foreign import capi "boolector.h boolector_int"
boolectorInt :: Btor -> CInt -> CInt -> IO BtorNode
boolectorVar :: Btor -> CInt -> String -> IO BtorNode
boolectorVar btor w name
= withCString name $
\name' -> boolectorVar_ btor w name'
foreign import capi "boolector.h boolector_var"
boolectorVar_ :: Btor -> CInt -> CString -> IO BtorNode
boolectorArray :: Btor -> CInt -> CInt -> String -> IO BtorNode
boolectorArray btor wi we name
= withCString name $
\name' -> boolectorArray_ btor wi we name'
foreign import capi "boolector.h boolector_array"
boolectorArray_ :: Btor -> CInt -> CInt -> CString -> IO BtorNode
foreign import capi "boolector.h boolector_not"
boolectorNot :: Btor -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_neg"
boolectorNeg :: Btor -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_redor"
boolectorRedOr :: Btor -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_redand"
boolectorRedAnd :: Btor -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_slice"
boolectorSlice :: Btor -> BtorNode -> CInt -> CInt -> IO BtorNode
foreign import capi "boolector.h boolector_uext"
boolectorUExt :: Btor -> BtorNode -> CInt -> IO BtorNode
foreign import capi "boolector.h boolector_sext"
boolectorSExt :: Btor -> BtorNode -> CInt -> IO BtorNode
foreign import capi "boolector.h boolector_implies"
boolectorImplies :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_iff"
boolectorIff :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_xor"
boolectorXOr :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_xnor"
boolectorXNOr :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_and"
boolectorAnd :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_nand"
boolectorNAnd :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_or"
boolectorOr :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_nor"
boolectorNOr :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_eq"
boolectorEq :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_ne"
boolectorNE :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_add"
boolectorAdd :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_uaddo"
boolectorUAddO :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_saddo"
boolectorSAddO :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_mul"
boolectorMul :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_umulo"
boolectorUMulO :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_smulo"
boolectorSMulO :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_ult"
boolectorULt :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_slt"
boolectorSLt :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_ulte"
boolectorULte :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_slte"
boolectorSLte :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_ugt"
boolectorUGt :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_sgt"
boolectorSGt :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_ugte"
boolectorUGte :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_sgte"
boolectorSGte :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_sll"
boolectorSLL :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_srl"
boolectorSRL :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_sra"
boolectorSRA :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_rol"
boolectorRoL :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_ror"
boolectorRoR :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_sub"
boolectorSub :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_usubo"
boolectorUSubO :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_ssubo"
boolectorSSubO :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_udiv"
boolectorUDiv :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_sdiv"
boolectorSDiv :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_sdivo"
boolectorSDivO :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_urem"
boolectorURem :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_srem"
boolectorSRem :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_smod"
boolectorSMod :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_concat"
boolectorConcat :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_read"
boolectorRead :: Btor -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_write"
boolectorWrite :: Btor -> BtorNode -> BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_cond"
boolectorCond :: Btor -> BtorNode -> BtorNode -> BtorNode -> IO BtorNode
boolectorParam :: Btor -> CInt -> String -> IO BtorNode
boolectorParam btor width name
= withCString name $
\name' -> boolectorParam_ btor width name'
foreign import capi "boolector.h boolector_param"
boolectorParam_ :: Btor -> CInt -> CString -> IO BtorNode
boolectorFun :: Btor -> [BtorNode] -> BtorNode -> IO BtorNode
boolectorFun btor args expr
= withArrayLen args $
\len arr -> boolectorFun_ btor (fromIntegral len) arr expr
foreign import capi "boolector.h boolector_fun"
boolectorFun_ :: Btor -> CInt -> Ptr BtorNode -> BtorNode -> IO BtorNode
boolectorApply :: Btor -> [BtorNode] -> BtorNode -> IO BtorNode
boolectorApply btor args fun
= withArrayLen args $
\len arr -> boolectorApply_ btor (fromIntegral len) arr fun
foreign import capi "boolector.h boolector_apply"
boolectorApply_ :: Btor -> CInt -> Ptr BtorNode -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_inc"
boolectorInc :: Btor -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_dec"
boolectorDec :: Btor -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_is_array"
boolectorIsArray :: Btor -> BtorNode -> IO Bool
foreign import capi "boolector.h boolector_is_fun"
boolectorIsFun :: Btor -> BtorNode -> IO Bool
foreign import capi "boolector.h boolector_get_fun_arity"
boolectorGetFunArity :: Btor -> BtorNode -> IO CInt
foreign import capi "boolector.h boolector_get_width"
boolectorGetWidth :: Btor -> BtorNode -> IO CInt
foreign import capi "boolector.h boolector_get_index_width"
boolectorGetIndexWidth :: Btor -> BtorNode -> IO CInt
boolectorFunSortCheck :: Btor -> [BtorNode] -> BtorNode -> IO Bool
boolectorFunSortCheck btor args fun
= withArrayLen args $
\len arr -> boolectorFunSortCheck_ btor (fromIntegral len) arr fun
foreign import capi "boolector.h boolector_fun_sort_check"
boolectorFunSortCheck_ :: Btor -> CInt -> Ptr BtorNode -> BtorNode -> IO Bool
boolectorGetSymbolOfVar :: Btor -> BtorNode -> IO String
boolectorGetSymbolOfVar btor node = do
res <- boolectorGetSymbolOfVar_ btor node
peekCString res
foreign import capi "boolector.h boolector_get_symbol_of_var"
boolectorGetSymbolOfVar_ :: Btor -> BtorNode -> IO CString
foreign import capi "boolector.h boolector_copy"
boolectorCopy :: Btor -> BtorNode -> IO BtorNode
foreign import capi "boolector.h boolector_release"
boolectorRelease :: Btor -> BtorNode -> IO ()
foreign import capi "boolector.h boolector_assert"
boolectorAssert :: Btor -> BtorNode -> IO ()
foreign import capi "boolector.h boolector_assume"
boolectorAssume :: Btor -> BtorNode -> IO ()
boolectorSat :: Btor -> IO Bool
boolectorSat btor = do
res <- boolectorSat_ btor
return $ res==10
foreign import capi "boolector.h boolector_sat"
boolectorSat_ :: Btor -> IO CInt
data BitAssignment = One
| Zero
| DontCare
deriving (Eq,Ord,Show)
boolectorBVAssignment :: Btor -> BtorNode -> IO [BitAssignment]
boolectorBVAssignment btor node = do
assignment <- boolectorBVAssignment_ btor node
strAssignment <- peekCString assignment
boolectorFreeBVAssignment_ btor assignment
return $ fmap (\c -> case c of
'0' -> Zero
'1' -> One
'x' -> DontCare) strAssignment
foreign import capi "boolector.h boolector_bv_assignment"
boolectorBVAssignment_ :: Btor -> BtorNode -> IO CString
foreign import capi "boolector.h boolector_free_bv_assignment"
boolectorFreeBVAssignment_ :: Btor -> CString -> IO ()
|
hguenther/smtlib2
|
backends/boolector/Language/SMTLib2/Boolector.hs
|
gpl-3.0
| 25,519 | 552 | 29 | 6,204 | 7,430 | 3,801 | 3,629 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
module Lamdu.Expr.UniqueId
( ToGuid(..), UniqueId(..)
) where
import Prelude.Compat
import Control.MonadA (MonadA)
import Data.Store.Guid (Guid)
import qualified Data.Store.Guid as Guid
import Data.Store.IRef (IRef)
import qualified Data.Store.IRef as IRef
import Data.Store.Transaction (Transaction)
import qualified Data.Store.Transaction as Transaction
import Lamdu.Expr.IRef (ValI(..))
import qualified Lamdu.Expr.IRef as ExprIRef
import Lamdu.Expr.Identifier (Identifier(..))
import qualified Lamdu.Expr.Type as T
import qualified Lamdu.Expr.Val as V
guidOfIdentifier :: Identifier -> Guid
guidOfIdentifier (Identifier bs) = Guid.make bs
identifierOfGuid :: Guid -> Identifier
identifierOfGuid = Identifier . Guid.bs
class ToGuid a where toGuid :: a -> Guid
instance ToGuid V.Var where toGuid = guidOfIdentifier . V.vvName
instance ToGuid T.Tag where toGuid = guidOfIdentifier . T.tagName
instance ToGuid T.Id where toGuid = guidOfIdentifier . T.typeId
instance ToGuid T.ParamId where toGuid = guidOfIdentifier . T.typeParamId
instance ToGuid (IRef m a) where toGuid = IRef.guid
instance ToGuid (ValI m) where toGuid = toGuid . ExprIRef.unValI
-- TODO: Remove this when all code uses more descritive types than Guid
instance ToGuid Guid where toGuid = id
mkNew :: MonadA m => (Identifier -> a) -> Transaction m a
mkNew f = f . identifierOfGuid <$> Transaction.newKey
-- NOTE: No other code in Lamdu should be creating var or tag ids!
class ToGuid a => UniqueId a where new :: MonadA m => Transaction m a
instance UniqueId V.Var where new = mkNew V.Var
instance UniqueId T.Tag where new = mkNew T.Tag
instance UniqueId T.Id where new = mkNew T.Id
|
rvion/lamdu
|
Lamdu/Expr/UniqueId.hs
|
gpl-3.0
| 1,836 | 0 | 8 | 389 | 508 | 289 | 219 | 34 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# OPTIONS_GHC -fno-warn-overlapping-patterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Handler.DB.RouteUsergroupsUserGroup where
import Handler.DB.Enums
import Handler.DB.Esqueleto
import Handler.DB.Internal
import Handler.DB.Validation
import qualified Handler.DB.FilterSort as FS
import qualified Handler.DB.PathPieces as PP
import Prelude
import Database.Esqueleto
import Database.Esqueleto.Internal.Sql (unsafeSqlBinOp)
import qualified Database.Persist as P
import Database.Persist.TH
import Yesod.Auth (requireAuth, requireAuthId, YesodAuth, AuthId, YesodAuthPersist, AuthEntity)
import Yesod.Core hiding (fileName, fileContentType)
import Yesod.Persist (runDB, YesodPersist, YesodPersistBackend)
import Control.Monad (when)
import Data.Aeson ((.:), (.:?), (.!=), FromJSON, parseJSON, decode)
import Data.Aeson.TH
import Data.Int
import Data.Word
import Data.Time
import Data.Text.Encoding (encodeUtf8)
import Data.Typeable (Typeable)
import qualified Data.Attoparsec as AP
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as AT
import qualified Data.ByteString.Lazy as LBS
import Data.Maybe
import qualified Data.Text.Read
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.List as DL
import Control.Monad (mzero, forM_)
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Network.HTTP.Conduit as C
import qualified Network.Wai as W
import Data.Conduit.Lazy (lazyConsume)
import Network.HTTP.Types (status200, status400, status403, status404)
import Blaze.ByteString.Builder.ByteString (fromByteString)
import Control.Applicative ((<$>), (<*>))
import qualified Data.HashMap.Lazy as HML
import qualified Data.HashMap.Strict as HMS
import Handler.Utils (nonEmpty)
import Handler.Utils (prepareNewUser,hasWritePerm,hasReadPermMaybe,hasReadPerm)
putUsergroupsUserGroupIdR :: forall master. (
YesodAuthPersist master,
AuthEntity master ~ User,
AuthId master ~ Key User,
YesodPersistBackend master ~ SqlBackend)
=> UserGroupId -> HandlerT DB (HandlerT master IO) A.Value
putUsergroupsUserGroupIdR p1 = lift $ runDB $ do
authId <- lift $ requireAuthId
jsonResult <- parseJsonBody
jsonBody <- case jsonResult of
A.Error err -> sendResponseStatus status400 $ A.object [ "message" .= ( "Could not decode JSON object from request body : " ++ err) ]
A.Success o -> return o
jsonBodyObj <- case jsonBody of
A.Object o -> return o
v -> sendResponseStatus status400 $ A.object [ "message" .= ("Expected JSON object in the request body, got: " ++ show v) ]
attr_mailChimpListName <- case HML.lookup "mailChimpListName" jsonBodyObj of
Just v -> case A.fromJSON v of
A.Success v' -> return v'
A.Error err -> sendResponseStatus status400 $ A.object [
"message" .= ("Could not parse value from attribute mailChimpListName in the JSON object in request body" :: Text),
"error" .= err
]
Nothing -> sendResponseStatus status400 $ A.object [
"message" .= ("Expected attribute mailChimpListName in the JSON object in request body" :: Text)
]
attr_mailChimpApiKey <- case HML.lookup "mailChimpApiKey" jsonBodyObj of
Just v -> case A.fromJSON v of
A.Success v' -> return v'
A.Error err -> sendResponseStatus status400 $ A.object [
"message" .= ("Could not parse value from attribute mailChimpApiKey in the JSON object in request body" :: Text),
"error" .= err
]
Nothing -> sendResponseStatus status400 $ A.object [
"message" .= ("Expected attribute mailChimpApiKey in the JSON object in request body" :: Text)
]
attr_email <- case HML.lookup "email" jsonBodyObj of
Just v -> case A.fromJSON v of
A.Success v' -> return v'
A.Error err -> sendResponseStatus status400 $ A.object [
"message" .= ("Could not parse value from attribute email in the JSON object in request body" :: Text),
"error" .= err
]
Nothing -> sendResponseStatus status400 $ A.object [
"message" .= ("Expected attribute email in the JSON object in request body" :: Text)
]
attr_name <- case HML.lookup "name" jsonBodyObj of
Just v -> case A.fromJSON v of
A.Success v' -> return v'
A.Error err -> sendResponseStatus status400 $ A.object [
"message" .= ("Could not parse value from attribute name in the JSON object in request body" :: Text),
"error" .= err
]
Nothing -> sendResponseStatus status400 $ A.object [
"message" .= ("Expected attribute name in the JSON object in request body" :: Text)
]
__currentTime <- liftIO $ getCurrentTime
_ <- do
result <- select $ from $ \(ug ) -> do
let ugId' = ug ^. UserGroupId
where_ (((ug ^. UserGroupId) ==. (val p1)) &&. (hasWritePerm (val authId) (ug ^. UserGroupId)))
limit 1
return ug
case result of
((Entity _ _):_) -> return ()
_ -> sendResponseStatus status403 (A.object [
"message" .= ("require condition #1 failed" :: Text)
])
runDB_result <- do
e2 <- do
return $ Version {
versionTime = __currentTime
,
versionUserId = (Just authId)
}
vErrors <- lift $ validate e2
case vErrors of
xs@(_:_) -> sendResponseStatus status400 (A.object [
"message" .= ("Entity validation failed" :: Text),
"errors" .= toJSON xs
])
_ -> return ()
result_versionId <- P.insert (e2 :: Version)
result_ug <- do
r <- get $ ((p1) :: UserGroupId)
case r of
Just e -> return e
_ -> sendResponseStatus status400 $ A.object [
"message" .= ("Could not get entity UserGroup" :: Text)
]
e4 <- do
let e = result_ug
return $ e {
userGroupCurrent = Inactive
,
userGroupActiveId = (Just p1)
,
userGroupActiveEndTime = (Just __currentTime)
,
userGroupDeletedVersionId = (Just result_versionId)
}
vErrors <- lift $ validate e4
case vErrors of
xs@(_:_) -> sendResponseStatus status400 (A.object [
"message" .= ("Entity validation failed" :: Text),
"errors" .= toJSON xs
])
_ -> return ()
P.insert (e4 :: UserGroup)
e5 <- do
es <- select $ from $ \o -> do
where_ (o ^. UserGroupId ==. (val p1))
limit 1
return o
e <- case es of
[(Entity _ e')] -> return e'
_ -> sendResponseStatus status404 $ A.object [
"message" .= ("Could not update a non-existing UserGroup" :: Text)
]
return $ e {
userGroupEmail = attr_email
,
userGroupMailChimpApiKey = attr_mailChimpApiKey
,
userGroupMailChimpListName = attr_mailChimpListName
,
userGroupName = attr_name
,
userGroupActiveStartTime = __currentTime
}
vErrors <- lift $ validate e5
case vErrors of
xs@(_:_) -> sendResponseStatus status400 (A.object [
"message" .= ("Entity validation failed" :: Text),
"errors" .= toJSON xs
])
_ -> P.repsert p1 (e5 :: UserGroup)
return AT.emptyObject
return $ runDB_result
deleteUsergroupsUserGroupIdR :: forall master. (
YesodAuthPersist master,
AuthEntity master ~ User,
AuthId master ~ Key User,
YesodPersistBackend master ~ SqlBackend)
=> UserGroupId -> HandlerT DB (HandlerT master IO) A.Value
deleteUsergroupsUserGroupIdR p1 = lift $ runDB $ do
authId <- lift $ requireAuthId
__currentTime <- liftIO $ getCurrentTime
_ <- do
result <- select $ from $ \(ug ) -> do
let ugId' = ug ^. UserGroupId
where_ (((ug ^. UserGroupId) ==. (val p1)) &&. (hasWritePerm (val authId) (ug ^. UserGroupId)))
limit 1
return ug
case result of
((Entity _ _):_) -> return ()
_ -> sendResponseStatus status403 (A.object [
"message" .= ("require condition #1 failed" :: Text)
])
runDB_result <- do
e2 <- do
return $ Version {
versionTime = __currentTime
,
versionUserId = (Just authId)
}
vErrors <- lift $ validate e2
case vErrors of
xs@(_:_) -> sendResponseStatus status400 (A.object [
"message" .= ("Entity validation failed" :: Text),
"errors" .= toJSON xs
])
_ -> return ()
result_versionId <- P.insert (e2 :: Version)
e3 <- do
es <- select $ from $ \o -> do
where_ (o ^. UserGroupId ==. (val p1))
limit 1
return o
e <- case es of
[(Entity _ e')] -> return e'
_ -> sendResponseStatus status404 $ A.object [
"message" .= ("Could not update a non-existing UserGroup" :: Text)
]
return $ e {
userGroupCurrent = Inactive
,
userGroupActiveEndTime = (Just __currentTime)
,
userGroupDeletedVersionId = (Just result_versionId)
}
vErrors <- lift $ validate e3
case vErrors of
xs@(_:_) -> sendResponseStatus status400 (A.object [
"message" .= ("Entity validation failed" :: Text),
"errors" .= toJSON xs
])
_ -> P.repsert p1 (e3 :: UserGroup)
return AT.emptyObject
return $ runDB_result
|
tlaitinen/sms
|
backend/Handler/DB/RouteUsergroupsUserGroup.hs
|
gpl-3.0
| 11,538 | 0 | 23 | 4,078 | 2,746 | 1,450 | 1,296 | 229 | 17 |
{-# LANGUAGE DeriveDataTypeable #-}
module StearnsWharf.CmdLine where
import System.Console.CmdArgs (Data,Typeable,typ,def,groupname,(&=))
data CmdLine =
CmdLine {
host :: String,
dbname :: String,
user :: String,
system :: Int,
loadcase :: Int } deriving (Show, Data, Typeable)
cmdLine = CmdLine {
host = "192.168.56.63" &= groupname "Database",
dbname = "engineer" &= groupname "Database",
user = "engineer" &= groupname "Database",
system = 15 &= groupname "System",
loadcase = 1 &= groupname "System"}
|
baalbek/stearnswharf
|
src/StearnsWharf/CmdLine.hs
|
lgpl-3.0
| 615 | 0 | 8 | 178 | 161 | 96 | 65 | 16 | 1 |
{-# LANGUAGE TypeSynonymInstances, TypeOperators, ViewPatterns, FlexibleInstances, RecordWildCards, FlexibleContexts, OverlappingInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses, DeriveDataTypeable, UndecidableInstances, TypeFamilies, ScopedTypeVariables, OverloadedStrings #-}
module Language.Pascal.JVM.Builtin where
import Control.Monad.Exception
import qualified Data.ByteString as B ()
import qualified Data.Map as M
import qualified JVM.Builder as J
import JVM.Builder.Instructions
import JVM.ClassFile
import qualified Java.Lang
import qualified Java.IO
import Language.Pascal.Types
import Language.Pascal.JVM.Types
-- | List of builtin functions
builtinFunctions :: (CodeGen args, Throws (Located GeneratorError) e) =>
[(Id, args -> GenerateJvm e ())]
builtinFunctions =
[("write", write),
("writeln", writeln),
("readln", readln) ]
builtinTypes :: [(Id, Type)]
builtinTypes =
[("write", TFunction [TInteger] TVoid),
("writeln", TFunction [TInteger] TVoid),
("readln", TFunction [] TAny) ]
-- | If named symbol is builtin, return it's definition
-- lookupBuiltin :: Id -> Maybe ([Expression :~ TypeAnn] -> GenerateJvm e ())
lookupBuiltin name = lookup name builtinFunctions
readln _ = undefined
write args = do
liftG $ getStaticField Java.Lang.system Java.IO.out
generate args
liftG $ invokeVirtual Java.IO.printStream printInt
writeln args = do
liftG $ getStaticField Java.Lang.system Java.IO.out
generate args
liftG $ invokeVirtual Java.IO.printStream printlnInt
printInt :: NameType (Method Direct)
printInt = NameType "print" $ MethodSignature [IntType] ReturnsVoid
printlnInt :: NameType (Method Direct)
printlnInt = NameType "println" $ MethodSignature [IntType] ReturnsVoid
-- | Symbol table of builtin symbols
builtinSymbols :: M.Map Id Symbol
builtinSymbols = M.fromList $ map pair builtinTypes
where
pair (name, tp) = (name, Symbol {
symbolName = name,
symbolType = tp,
symbolConstValue = Nothing,
symbolContext = Outside,
symbolIndex = 0,
symbolDefLine = 0,
symbolDefCol = 0 })
|
portnov/simple-pascal-compiler
|
spc-jvm/Language/Pascal/JVM/Builtin.hs
|
lgpl-3.0
| 2,315 | 0 | 10 | 547 | 508 | 291 | 217 | 47 | 1 |
{-
- This file is part of Bilder.
-
- Bilder is free software: you can redistribute it and/or modify
- it under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Bilder 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 Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with Bilder. If not, see <http://www.gnu.org/licenses/>.
-
- Copyright © 2012-2013 Filip Lundborg
- Copyright © 2012-2013 Ingemar Ådahl
-
-}
{-# LANGUAGE UnicodeSyntax #-}
module Compiler.Desugar.Extract where
import Control.Applicative
import Control.Monad.State
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Traversable as Trav (mapM)
import Compiler.Utils
import TypeChecker.Utils
import TypeChecker.Types
import FrontEnd.AbsGrammar
import Text.Printf
data Ids = Ids {
unused ∷ [Int],
pending ∷ [Stm],
funs ∷ Map.Map String Function
}
newVar ∷ State Ids Exp
newVar = do
e ← gets (printf "_l%03d" . head . unused)
modify (\st → st { unused = tail (unused st) })
return $ EVar (CIdent ((0,0), e))
putDec ∷ Stm → State Ids ()
putDec stm = modify (\st → st { pending = pending st ++ [stm] })
getPendings ∷ State Ids [Stm]
getPendings = do
p ← gets pending
modify (\st → st { pending = []})
return p
getFun ∷ String → State Ids Function
getFun s = do
fs ← gets funs
return $ fromJust $ Map.lookup s fs
expandSource ∷ Source → Source
expandSource src = src { functions = evalState (Trav.mapM expandFun (functions src)) (Ids [1..] [] (functions src))}
expandFun ∷ Function → State Ids Function
expandFun fun = do
stms ← expand (statements fun)
return $ fun { statements = stms}
expand ∷ [Stm] → State Ids [Stm]
expand (SDecl (Dec qs (DecAss cids tk e)):ss) = do
(e', sdecs) ← case e of
(EPartCall cid es ts) → do
exs ← mapM expandExp es
let (es', sds) = foldr (\(x,ds) (px,pds) → (x:px,ds++pds)) ([],[]) exs
return (EPartCall cid es' ts, sds)
ex → expandExp ex
ss' ← expand ss
return $ sdecs ++ [SDecl (Dec qs (DecAss cids tk e'))] ++ ss'
expand (SExp e:ss) = do
(e', sdecs) ← expandExp e
ss' ← expand ss
return $ sdecs ++ [SExp e'] ++ ss'
expand (SWhile tkw e stm:ss) = do
e' ← extractCalls e
sdecs ← getPendings
stm' ← liftM makeBlock $ expand [stm]
ss' ← expand ss
return $ sdecs ++ [SWhile tkw e' stm'] ++ ss'
expand (SDoWhile tkd stm tkw e:ss) = do
stms ← expand [stm]
e' ← extractCalls e
sdecs ← getPendings
let stm' = makeBlock $ stms ++ sdecs
ss' ← expand ss
return $ SDoWhile tkd stm' tkw e':ss'
expand (SFor tkf fds els ers stm:ss) = do
fds' ← mapM extractForDecl fds
els' ← mapM extractCalls els
ers' ← mapM extractCalls ers
sdecs ← getPendings
stm' ← liftM makeBlock $ expand [stm]
ss' ← expand ss
return $ sdecs ++ [SFor tkf fds' els' ers' stm'] ++ ss'
expand (SIf tk e stm:ss) = do
(e', sdecs) ← expandExp e
stm' ← liftM makeBlock $ expand [stm]
ss' ← expand ss
return $ sdecs ++ [SIf tk e' stm'] ++ ss'
expand (SIfElse tki e strue tke sfalse:ss) = do
(e', sdecs) ← expandExp e
strue' ← liftM makeBlock $ expand [strue]
sfalse' ← liftM makeBlock $ expand [sfalse]
ss' ← expand ss
return $ sdecs ++ [SIfElse tki e' strue' tke sfalse'] ++ ss'
expand (SReturn tkr e:ss) = do
(e',sdecs) ← expandExp e
ss' ← expand ss
return $ sdecs ++ [SReturn tkr e'] ++ ss'
expand ss = expandStmM expand ss
expandExp ∷ Exp → State Ids (Exp,[Stm])
expandExp e = (,) <$> extractCalls e <*> getPendings
extractForDecl ∷ ForDecl → State Ids ForDecl
extractForDecl (FDecl (Dec qs (DecAss cds tk e))) =
FDecl <$> Dec qs <$> DecAss cds tk <$> extractCalls e
extractForDecl (FExp e) = FExp <$> extractCalls e
-- DecFun is not allowed here - no need to handle it.
-- TODO: Structs.
extractForDecl fd = return fd
extractCalls ∷ Exp → State Ids Exp
extractCalls (EAss el tk (EPartCall cid es ts)) = do
es' ← mapM extractCalls es
return $ EAss el tk (EPartCall cid es' ts)
extractCalls ecall@(ECall cid es) = do
es' ← mapM extractCalls es
var@(EVar varCid) ← newVar
fs ← gets funs
case Map.lookup (cIdentToString cid) fs of
Nothing → return ecall
Just fun → if retType fun /= TVoid
then putDec (makeDec varCid (retType fun) (ECall cid es')) >> return var
else return ecall
extractCalls (EPartCall cid es ts) = do
es' ← mapM extractCalls es
var@(EVar varCid) ← newVar
f ← getFun (cIdentToString cid)
let typ = TFun (retType f) $ map varType $ drop (length ts) (paramVars f)
putDec $ makeDec varCid typ (EPartCall cid es' ts)
return var
extractCalls e = mapExpM extractCalls e
makeDec ∷ CIdent → Type → Exp → Stm
makeDec cid typ e = SDecl (Dec [QType typ]
(DecAss [cid] tkass e))
where
tkass = TkAss ((0,0), "=")
|
ingemaradahl/bilder
|
src/Compiler/Desugar/Extract.hs
|
lgpl-3.0
| 5,247 | 0 | 20 | 1,158 | 2,026 | 998 | 1,028 | 121 | 3 |
module JSON2RDF
( module JSON2RDF.Types
, module JSON2RDF.Parser.Text
) where
import JSON2RDF.Types
import JSON2RDF.Parser.Text
|
markborkum/json2rdf-hs
|
src/JSON2RDF.hs
|
unlicense
| 129 | 0 | 5 | 15 | 30 | 20 | 10 | 5 | 0 |
module FactorialMaybe where
import Data.Maybe (fromJust)
factorial :: (Integral a) => a -> Maybe a
factorial n
| n < 0 = Nothing
| n == 0 = Just 1
| otherwise = Just $ (*n) . fromJust . factorial $ (n-1)
|
OCExercise/haskellbook-solutions
|
chapters/chapter08/scratch/factorial-maybe.hs
|
bsd-2-clause
| 225 | 0 | 10 | 63 | 105 | 54 | 51 | 7 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QAction.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QAction (
MenuRole, eTextHeuristicRole, eApplicationSpecificRole, eAboutQtRole, eAboutRole, ePreferencesRole, eQuitRole
, ActionEvent, eHover
)
where
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CMenuRole a = CMenuRole a
type MenuRole = QEnum(CMenuRole Int)
ieMenuRole :: Int -> MenuRole
ieMenuRole x = QEnum (CMenuRole x)
instance QEnumC (CMenuRole Int) where
qEnum_toInt (QEnum (CMenuRole x)) = x
qEnum_fromInt x = QEnum (CMenuRole x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> MenuRole -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeNoRole MenuRole where
eNoRole
= ieMenuRole $ 0
eTextHeuristicRole :: MenuRole
eTextHeuristicRole
= ieMenuRole $ 1
eApplicationSpecificRole :: MenuRole
eApplicationSpecificRole
= ieMenuRole $ 2
eAboutQtRole :: MenuRole
eAboutQtRole
= ieMenuRole $ 3
eAboutRole :: MenuRole
eAboutRole
= ieMenuRole $ 4
ePreferencesRole :: MenuRole
ePreferencesRole
= ieMenuRole $ 5
eQuitRole :: MenuRole
eQuitRole
= ieMenuRole $ 6
data CActionEvent a = CActionEvent a
type ActionEvent = QEnum(CActionEvent Int)
ieActionEvent :: Int -> ActionEvent
ieActionEvent x = QEnum (CActionEvent x)
instance QEnumC (CActionEvent Int) where
qEnum_toInt (QEnum (CActionEvent x)) = x
qEnum_fromInt x = QEnum (CActionEvent x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> ActionEvent -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeTrigger ActionEvent where
eTrigger
= ieActionEvent $ 0
eHover :: ActionEvent
eHover
= ieActionEvent $ 1
|
uduki/hsQt
|
Qtc/Enums/Gui/QAction.hs
|
bsd-2-clause
| 4,381 | 0 | 18 | 996 | 1,193 | 598 | 595 | 110 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
module Drive.Intercom.API
where
import Control.Monad.Free
import Control.Monad.Free.TH
import Drive.Intercom.Types
makeFree ''IntercomF
type IntercomP = Free IntercomF
|
palf/free-driver
|
packages/drive-intercom/lib/Drive/Intercom/API.hs
|
bsd-3-clause
| 274 | 0 | 6 | 63 | 45 | 28 | 17 | 8 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Control.DeepSeq
import Control.Exception (evaluate)
import qualified Control.Monad as M
import qualified Data.Attoparsec.Text as Atto
import qualified Data.Char as C
import qualified Data.Text as T
import Data.Time
import System.CPUTime
import qualified System.Environment as E
data JSON_VAL = JSON_Bool Bool |
JSON_Double Double |
JSON_Null () |
JSON_String String |
JSON_Array [JSON_VAL] |
JSON_Object [(String, JSON_VAL)] deriving (Show)
instance NFData JSON_VAL where
rnf (JSON_Bool a) = rnf a
rnf (JSON_Double a) = rnf a
rnf (JSON_Null a) = rnf a
rnf (JSON_String a) = rnf a
rnf (JSON_Array a) = rnf a
rnf (JSON_Object a) = rnf a
parse_separator x = parse_ws >> Atto.char x >> parse_ws >> return ()
parse_ws = (Atto.many' $ Atto.satisfy is_ws) >> return ()
where is_ws c | c == '\x20' = True
| c == '\x09' = True
| c == '\x0a' = True
| c == '\x0d' = True
| otherwise = False
parse_false = Atto.string "false" >> (return $ JSON_Bool False)
parse_true = Atto.string "true" >> (return $ JSON_Bool True)
parse_null = Atto.string "null" >> (return $ JSON_Null ())
parse_value =
do
val <- (Atto.try parse_false) <|>
(Atto.try parse_null) <|>
(Atto.try parse_true) <|>
(Atto.try parse_object) <|>
(Atto.try parse_array) <|>
(Atto.try parse_number) <|>
do
str <- parse_string
return $ JSON_String str
return val
parse_object =
do
_ <- parse_separator '{'
mems <- Atto.try parse_members <|> (return $ JSON_Object [])
_ <- parse_separator '}'
return mems
parse_members =
do
h <- parse_member
_ <- parse_ws
t <- (Atto.try $ Atto.many' parse_sp_member) <|> return []
return $ JSON_Object $ h:t
parse_member =
do
key <- parse_string
_ <- parse_separator ':'
val <- parse_value
return $ (key, val)
parse_sp_member = parse_ws >> Atto.char ',' >> parse_ws >> parse_member
parse_array =
do
_ <- parse_separator '['
vals <- Atto.try parse_values <|> (return $ JSON_Array [])
_ <- parse_separator ']'
return vals
parse_values =
do
h <- parse_value
_ <- parse_ws
t <- (Atto.try $ Atto.many' parse_sp_value) <|> return []
return $ JSON_Array $ h:t
parse_sp_value = parse_ws >> Atto.char ',' >> parse_ws >> parse_value
parse_number =
do
n <- Atto.double
return $ JSON_Double n
parse_string =
do
_ <- Atto.char '"'
str <- Atto.many' parse_char
_ <- Atto.char '"'
return str
parse_char =
do
c <- (Atto.try $ Atto.satisfy is_unescaped) <|> parse_escaped
return c
where is_unescaped x | x == '\x20' = True
| x == '\x21' = True
| '\x23' <= x && x <= '\x5b' = True
| '\x5d' <= x && x <= '\x10ffff' = True
| otherwise = False
parse_escaped =
do
s <- Atto.char '\\'
c <- Atto.try $ Atto.satisfy is_esc <|> parse_4hexdig
return c
where is_esc c | c == '"' = True
| c == '\\' = True
| c == '/' = True
| c == 'b' = True
| c == 'f' = True
| c == 'n' = True
| c == 'r' = True
| c == 't' = True
| otherwise = False
hexdig2char h1 h2 h3 h4 =
C.chr $ x1 + x2 + x3 + x4 where
x1 = 16 * 16 * 16 * (C.ord h1)
x2 = 16 * 16 * (C.ord h2)
x3 = 16 * (C.ord h3)
x4 = C.ord h4
parse_4hexdig =
do
u <- Atto.char 'u'
h1 <- Atto.satisfy is_hexdig
h2 <- Atto.satisfy is_hexdig
h3 <- Atto.satisfy is_hexdig
h4 <- Atto.satisfy is_hexdig
return $ hexdig2char h1 h2 h3 h4
where is_hexdig x | '0' <= x && x <= '9' = True
| 'a' <= x && x <= 'f' = True
| 'A' <= x && x <= 'F' = True
| otherwise = False
print_result (Atto.Partial p) = print_result $ p ""
print_result x = x
run_parser linesOfFiles = [print_result y | x <- linesOfFiles, let y = Atto.parse parse_value $ T.pack x]
benchmarkForce :: NFData a => String -> IO a -> IO a
benchmarkForce msg action = do
before <- getCurrentTime
-- Force the first time to measure computation + forcing
result <- evaluate . force =<< action
after <- getCurrentTime
-- Force again to see how long forcing itself takes
_ <- evaluate . force $ result
afterAgain <- getCurrentTime
putStrLn $ msg ++ ": " ++ show (diffTimeMs before after) ++ " ms"
++ " (force time: " ++ show (diffTimeMs after afterAgain) ++ " ms)"
return result
where
-- Time difference `t2 - t1` in milliseconds
diffTimeMs t1 t2 = realToFrac (t2 `diffUTCTime` t1) * 1000.0 :: Double
main :: IO ()
main = do
args <- E.getArgs
content <- readFile (args !! 0)
let linesOfFiles = lines content
let objs = run_parser linesOfFiles
benchmarkForce "split" $ return linesOfFiles
benchmarkForce "parse" $ return objs
return ()
|
ytakano/tsukuyomi
|
tests/json/json_haskell_atto.hs
|
bsd-3-clause
| 5,437 | 0 | 16 | 1,852 | 1,857 | 893 | 964 | 153 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators #-}
module SAWScript.Heapster.CrucibleTranslation (
JudgmentTranslate'(..),
translateCFG,
) where
import qualified Control.Lens as Lens
import Data.Functor.Const
import Data.List
import Data.Maybe
import Data.Parameterized.TraversableFC
import Data.Parameterized.Context
import Lang.Crucible.LLVM.MemModel
import Lang.Crucible.Types
import SAWScript.Heapster.Permissions
import SAWScript.Heapster.JudgmentTranslation
import SAWScript.Heapster.TypedCrucible
import SAWScript.Heapster.TypeTranslation
import SAWScript.Heapster.ValueTranslation
import SAWScript.TopLevel
import Verifier.SAW.OpenTerm
-- TODO: I'm not sure this combinator can be written, because the `args` might
-- be escaping its scope. Anyway, there's a way of inverting the flow of the
-- code so as to get something morally equivalent.
letRec ::
TypedBlockMap ext blocks ret ->
(ResolveEntryIDs blocks -> TypedEntry ext blocks ret args -> OpenTerm) ->
(ResolveEntryIDs blocks -> OpenTerm) ->
OpenTerm
letRec = error "TODO"
-- letRec'
-- [(SomeTypedEntryID blocks, ([(SomeTypedEntryID blocks, OpenTerm)] -> OpenTerm))] ->
-- -- ^ This is a list of mappings [(fun1, mkCode1), (fun2, mkCode2), ...], where
-- -- at index N, mkCodeN must construct the code for function funN, given as input
-- -- a list of mappings [(fun1, var1), (fun2, var2)] of mappings from entries to
-- -- a SAW variable that said function will be bound to (in a recursive let
-- -- form). Therefore, if `mkCode2` wants to call `fun1`, it should use `var1`.
-- -- It can also perform recursive calls by using `var2`.
-- ([(SomeTypedEntryID blocks, OpenTerm)] -> OpenTerm) ->
-- -- ^ This builds the body of the `let rec`, usually calling in one of the
-- -- mutually-bound functions, whichever one is considered the "entry point".
-- -- It is given a mapping from entry IDs to the SAW variable that implements
-- -- the function with that ID.
-- OpenTerm
-- letRec' = error "Will exist"
translateCFG :: TypedCFG ext blocks ghosts init ret -> OpenTerm
translateCFG (TypedCFG {..}) =
let initCtxRepr = permSetCtx tpcfgInputPerms in
let typArgs = typeTranslate'' initCtxRepr in
let typPerms = typeTranslate' (error "TODO") tpcfgInputPerms in
lambdaOpenTerm "inputs" (pairTypeOpenTerm typArgs typPerms)
-- lambdaPermSet (typedCFGInputTypes cfg) tpcfgInputPerms
(\ inputs ->
let mkBlockCode blockBinders entry =
let info = BlocksInfo { entryPoints = blockBinders } in
translateTypedEntry info entry
in
letRec tpcfgBlockMap mkBlockCode
(\ blockBinders ->
let entryPoint = lookupBlock blockBinders tpcfgEntryBlockID in
applyOpenTerm entryPoint inputs
)
)
getTypedEntryID :: TypedEntry ext blocks ret args -> SomeTypedEntryID blocks
getTypedEntryID (TypedEntry i _ _ _) = SomeTypedEntryID i
getTypedBlockEntries :: TypedBlock ext blocks ret args -> [TypedEntry ext blocks ret args]
getTypedBlockEntries (TypedBlock entries) = entries
-- translateBlock :: BlocksInfo blocks -> TypedEntry ext blocks ret args -> (SomeTypedEntryID blocks, OpenTerm)
-- translateBlock info e = (getTypedEntryID e, translateTypedEntry info e)
translateTypedEntry :: BlocksInfo blocks -> TypedEntry ext blocks ret args -> OpenTerm
translateTypedEntry info (TypedEntry id types perms stmtSeq) =
-- needs
let ghostsCtxtRepr = entryGhosts id in
let ctxtRepr = ghostsCtxtRepr <++> types in
-- fold-right over the `fst` of t creating lambdas binding each term
let typArgs = error "TODO" in
let typPerms = error "TODO" in
lambdaOpenTerm "inputs" (pairTypeOpenTerm typArgs typPerms)
(\ inputs ->
buildLambdaAsgn (fmapFC (Const . typeTranslate'') ctxtRepr) inputs
(\ typeEnvironment ->
buildLambdaAsgn (fmapFC (Const . typeTranslate typeEnvironment) $ permSetAsgn perms) inputs
(\ permissionMap ->
let jctx = JudgmentContext
{ typeEnvironment
, permissionSet = perms
, permissionMap
, catchHandler = Nothing
}
in
let t = judgmentTranslate' info jctx (error "TODO") stmtSeq in
error "TODO"
)
)
)
buildLambdaAsgn ::
Assignment (Const OpenTerm) ctx -> -- ^ types
OpenTerm -> -- ^ nested tuple of said types
(Assignment (Const OpenTerm) ctx -> OpenTerm) -> -- ^ body
OpenTerm
buildLambdaAsgn = error "TODO"
-- (\ inputs ->
-- elimPair typArgs typPerms (\ _ -> error "TODO") inputs
-- (\ types perms ->
--
-- )
-- )
instance JudgmentTranslate' blocks (TypedStmtSeq ext blocks ret) where
judgmentTranslate' info jctx outputType (TypedElimStmt perms elim) =
let elim' = judgmentTranslate' info jctx outputType elim in
elim'
judgmentTranslate' info jctx outputType (TypedConsStmt _ stmt stmtSeq) =
let typeBefore = error "TODO" in
let typeBetween = error "TODO" in
let typeAfter = outputType in
let stmt' = translateTypedStmt jctx stmt in -- probably want to also pass [[typeBetween]]
let jctx' = error "TODO" in -- should this come from `translateTypedStmt`?
let stmtSeq' = judgmentTranslate' info jctx' outputType stmtSeq in
-- composeM : (a b c: sort 0) -> (a -> CompM b) -> (b -> CompM c) -> a -> CompM c;
applyOpenTermMulti (globalOpenTerm "Prelude.composeM")
[ typeBefore
, typeBetween
, typeAfter
, stmt'
, stmtSeq'
]
judgmentTranslate' info jctx outputType (TypedTermStmt _ termStmt) =
judgmentTranslate' info jctx outputType termStmt
-- Should this function help in building a `JudgmentContext ctx'`?
translateTypedStmt :: JudgmentContext ctx -> TypedStmt ext ctx ctx' -> OpenTerm
translateTypedStmt jctx (TypedStmt pIn pOut stmt) = error "TODO"
translateTypedStmt jctx (DestructLLVMPtr w index) = error "TODO"
instance JudgmentTranslate' blocks (TypedTermStmt blocks ret) where
judgmentTranslate' info jctx outputType (TypedJump tgt) =
translateTypedJumpTarget info jctx tgt
judgmentTranslate' info jctx outputType (TypedBr cond tgt1 tgt2) =
let thenBranch = translateTypedJumpTarget info jctx tgt1 in
let elseBranch = translateTypedJumpTarget info jctx tgt2 in
error "TODO"
judgmentTranslate' info jctx outputType (TypedReturn ret intros) =
error "TODO"
judgmentTranslate' info jctx outputType (TypedErrorStmt err) =
error "TODO"
translateTypedJumpTarget ::
BlocksInfo blocks ->
JudgmentContext ctx ->
TypedJumpTarget blocks ctx ->
OpenTerm
translateTypedJumpTarget info jctx (TypedJumpTarget entryID args) =
let targetFunction = lookupBlock (entryPoints info) entryID in
let (TranslatedTypedArgs {..}) = translateTypedArgs jctx args in
error "TODO"
data TranslatedTypedArgs ctx = TranslatedTypedArgs
{ argsCtxt :: Assignment (Const OpenTerm) ctx
, argsVars :: [OpenTerm]
, argsPerms :: [OpenTerm]
, argsIntro :: OpenTerm
}
translateTypedArgs ::
JudgmentContext ctx ->
TypedArgs ghostsAndArgs ctx ->
TranslatedTypedArgs ghostsAndArgs
translateTypedArgs jctx (TypedArgs ctxRepr perms intros) =
TranslatedTypedArgs
{ argsCtxt = fmapFC (Const . typeTranslate'') ctxRepr
, argsVars = toListFC (valueTranslate (typeEnvironment jctx)) perms
, argsPerms = toListFC (valueTranslate (permissionMap jctx)) perms
, argsIntro = introJudgmentTranslate' jctx intros
}
-- TODO: For `Stmt`, for now, only need to deal with `SetReg`
lambdaPermSet ::
CtxRepr ctx ->
PermSet ctx ->
(JudgmentContext ctx -> OpenTerm) ->
OpenTerm
lambdaPermSet = error "Will exist"
lookupBlock :: [(SomeTypedEntryID blocks, OpenTerm)] -> TypedEntryID blocks ghosts args -> OpenTerm
lookupBlock = error "Will exist"
|
GaloisInc/saw-script
|
heapster-saw/src/Verifier/SAW/Heapster/archival/CrucibleTranslation.hs
|
bsd-3-clause
| 8,364 | 0 | 30 | 1,794 | 1,616 | 839 | 777 | 146 | 1 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Cryptol.Symbolic.BitVector where
import Data.Bits
import Control.Monad (replicateM)
import Control.Monad.IO.Class
import Control.Monad.Reader (MonadReader, ReaderT, ask, runReaderT)
import Data.Bits
import Data.IORef
import System.Random
import Test.QuickCheck (quickCheck)
import Data.SBV.Bridge.Yices
import Data.SBV.Internals
import Data.SBV.BitVectors.Data
-- BitVector type --------------------------------------------------------------
data BitVector = BV { width :: !Int, val :: !Integer }
deriving (Eq, Ord, Show)
-- ^ Invariant: BV w x requires that 0 <= w and 0 <= x < 2^w.
bitMask :: Int -> Integer
bitMask w = bit w - 1
-- | Smart constructor for bitvectors.
bv :: Int -> Integer -> BitVector
bv w x = BV w (x .&. bitMask w)
unsigned :: BitVector -> Integer
unsigned = val
signed :: BitVector -> Integer
signed (BV w x)
| w > 0 && testBit x (w - 1) = x - bit w
| otherwise = x
same :: Int -> Int -> Int
same m n = if m == n then m else error $ "BitVector size mismatch: " ++ show (m, n)
instance Num BitVector where
fromInteger n = error $ "fromInteger " ++ show n ++ " :: BitVector"
BV m x + BV n y = bv (same m n) (x + y)
BV m x - BV n y = bv (same m n) (x - y)
BV m x * BV n y = bv (same m n) (x * y)
negate (BV m x) = bv m (- x)
abs = id
signum (BV m _) = bv m 1
instance Bits BitVector where
BV m x .&. BV n y = BV (same m n) (x .&. y)
BV m x .|. BV n y = BV (same m n) (x .|. y)
BV m x `xor` BV n y = BV (same m n) (x `xor` y)
complement (BV m x) = BV m (x `xor` bitMask m)
shift (BV m x) i = bv m (shift x i)
rotate (BV m x) i = bv m (shift x j .|. shift x (j - m))
where j = i `mod` m
bit _i = error "bit: can't determine width"
setBit (BV m x) i = BV m (setBit x i)
clearBit (BV m x) i = BV m (clearBit x i)
complementBit (BV m x) i = BV m (complementBit x i)
testBit (BV _ x) i = testBit x i
bitSize (BV m _) = m
isSigned _ = False
popCount (BV _ x) = popCount x
--------------------------------------------------------------------------------
-- SBV class instances
type SWord = SBV BitVector
instance HasKind BitVector where
kindOf (BV w _) = KBounded False w
instance SymWord BitVector where
literal (BV w x) = SBV k (Left (mkConstCW k x))
where k = KBounded False w
fromCW c@(CW (KBounded False w) _) = BV w (fromCW c)
fromCW c = error $ "fromCW: Unsupported non-integral value: " ++ show c
mkSymWord _ _ = error "mkSymWord unimplemented for type BitVector"
instance SIntegral BitVector where
instance FromBits (SBV BitVector) where
fromBitsLE bs = go (literal (bv (length bs) 0)) 0 bs
where go !acc _ [] = acc
go !acc !i (x:xs) = go (ite x (setBit acc i) acc) (i+1) xs
instance SDivisible BitVector where
sQuotRem (BV m x) (BV n y) = (BV w q, BV w r)
where (q, r) = quotRem x y
w = same m n
sDivMod (BV m x) (BV n y) = (BV w q, BV w r)
where (q, r) = divMod x y
w = same m n
instance SDivisible (SBV BitVector) where
sQuotRem = liftQRem
sDivMod = liftDMod
extract :: Int -> Int -> SWord -> SWord
extract i j x =
case x of
SBV _ (Left cw) ->
case cw of
CW _ (CWInteger v) -> SBV k (Left (normCW (CW k (CWInteger (v `shiftR` j)))))
_ -> error "extract"
_ -> SBV k (Right (cache y))
where y st = do sw <- sbvToSW st x
newExpr st k (SBVApp (Extract i j) [sw])
where
k = KBounded False (i - j + 1)
cat :: SWord -> SWord -> SWord
cat x y | bitSize x == 0 = y
| bitSize y == 0 = x
cat x@(SBV _ (Left a)) y@(SBV _ (Left b)) =
case (a, b) of
(CW _ (CWInteger m), CW _ (CWInteger n)) ->
SBV k (Left (CW k (CWInteger ((m `shiftL` (bitSize y) .|. n)))))
_ -> error "cat"
where k = KBounded False (bitSize x + bitSize y)
cat x y = SBV k (Right (cache z))
where k = KBounded False (bitSize x + bitSize y)
z st = do xsw <- sbvToSW st x
ysw <- sbvToSW st y
newExpr st k (SBVApp Join [xsw, ysw])
randomSBVBitVector :: Int -> IO (SBV BitVector)
randomSBVBitVector width = do
bs <- replicateM width randomIO
let x = sum [ bit i | (i, b) <- zip [0..] bs, b ]
return (literal (bv width x))
mkSymBitVector :: Maybe Quantifier -> Maybe String -> Int -> Symbolic (SBV BitVector)
mkSymBitVector mbQ mbNm width =
mkSymSBVWithRandom (randomSBVBitVector width) mbQ (KBounded False width) mbNm
forallBV :: String -> Int -> Symbolic (SBV BitVector)
forallBV name width = mkSymBitVector (Just ALL) (Just name) width
forallBV_ :: Int -> Symbolic (SBV BitVector)
forallBV_ width = mkSymBitVector (Just ALL) Nothing width
existsBV :: String -> Int -> Symbolic (SBV BitVector)
existsBV name width = mkSymBitVector (Just EX) (Just name) width
existsBV_ :: Int -> Symbolic (SBV BitVector)
existsBV_ width = mkSymBitVector (Just EX) Nothing width
|
dylanmc/cryptol
|
src/Cryptol/Symbolic/BitVector.hs
|
bsd-3-clause
| 5,289 | 0 | 21 | 1,430 | 2,336 | 1,173 | 1,163 | 122 | 3 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- | Templates.
module HL.V.Template where
import HL.Types
import HL.V hiding (item)
import Data.Monoid
import Yesod.Static (Static)
-- | Render a template.
template
:: [Route App]
-> Text
-> ((Route App -> AttributeValue) -> Html)
-> FromSenza App
template crumbs ptitle inner =
skeleton
ptitle
(\_ _ -> return ())
(\cur url ->
div [class_ "template"]
(do navigation True cur url
container (bread url crumbs)
inner url))
-- | Render the basic site skeleton.
skeleton
:: Text
-> FromSenza App
-> FromSenza App
-> FromSenza App
skeleton ptitle innerhead innerbody mroute url =
docTypeHtml
(do head [] headinner
body (maybe []
(\route -> [class_ (toValue ("page-" <> toSlug route))])
mroute)
(do bodyinner
analytics)
)
where
headinner =
do headtitle (toHtml ptitle)
meta [charset "utf-8"]
meta [httpEquiv "X-UA-Compatible",content "IE edge"]
meta [name "viewport",content "width=device-width, initial-scale=1"]
linkcss "http://fonts.googleapis.com/css?family=Open+Sans"
styles url
[StaticR css_bootstrap_min_css
,StaticR css_haskell_font_css
,StaticR css_hscolour_css
,StaticR css_hl_css]
innerhead mroute url
bodyinner =
do div [class_ "wrap"]
(innerbody mroute url)
footer mroute
scripts url
[js_jquery_js
,js_bootstrap_min_js]
-- TODO: pop this in a config file later.
analytics =
script []
"(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n\
\ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n\
\ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n\
\ })(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\
\\n\
\ ga('create', 'UA-51440536-1', 'haskell-lang.org');\n\
\ ga('send', 'pageview');"
-- | Make a list of scripts.
scripts :: (Route App -> AttributeValue) -> [Route Static] -> Senza
scripts url =
mapM_ (\route ->
script [src (url (StaticR route))]
(return ()))
-- | Make a list of style links.
styles :: (a -> AttributeValue) -> [a] -> Senza
styles url =
mapM_ (\route ->
linkcss (url route))
-- | A link to CSSxs
linkcss :: AttributeValue -> Senza
linkcss uri =
link [rel "stylesheet"
,type_ "text/css"
,href uri]
-- | Main navigation.
navigation :: Bool -> FromSenza App
navigation showBrand mroute url =
nav [class_ "navbar navbar-default"]
(div [class_ "container"]
(do when showBrand brand
items))
where
items =
div [class_ "collapse navbar-collapse"]
(ul [class_ "nav navbar-nav"]
(mapM_ item
[DownloadsR
,CommunityR
,DocumentationR
,NewsR]))
where item route =
li theclass
(a [href (url route)]
(toHtml (toHuman route)))
where theclass
| Just route == mroute = [class_ "active"]
| otherwise = []
brand =
div [class_ "navbar-header"]
(do a [class_ "navbar-brand"
,href (url HomeR)]
(do logo
"Haskell"))
-- | The logo character in the right font. Style it with an additional
-- class or wrapper as you wish.
logo :: Senza
logo =
span [class_ "logo"]
"\xe000"
-- | Breadcrumb.
bread :: (Route App -> AttributeValue) -> [Route App] -> Html
bread url crumbs =
ol [class_ "breadcrumb"]
(forM_ crumbs
(\route ->
li []
(a [href (url route)]
(toHtml (toHuman route)))))
-- | Set the background image for an element.
background :: (Route App -> AttributeValue) -> Route Static -> Attribute
background url route =
style ("background-image: url(" <> url (StaticR route) <> ")")
-- | Footer across the whole site.
footer :: Maybe (Route App) -> Senza
footer r =
div [class_ "footer"]
(div [class_ "container"]
(p [] (do case r of
Just (WikiR page) -> wikiLicense (Just page)
Just (WikiHomeR{}) -> wikiLicense (Nothing :: Maybe Text)
_ -> hlCopy
"")))
where
hlCopy = do span [class_ "item"]
"Copyright © 2014 haskell-lang.org"
span [class_ "item footer-contribute"]
(do "Got changes to contribute? "
a [href "https://github.com/chrisdone/hl"]
"Fork on Github" )
wikiLicense page =
do span [class_ "item"]
wikiLink
span [class_ "item"]
(do "Wiki content is available under "
a [href "http://www.haskell.org/haskellwiki/HaskellWiki:Copyrights"]
"a simple permissive license.")
where
wikiLink =
case page of
Nothing ->
a [href "http://www.haskell.org/haskellwiki/"]
"Go to haskell.org wiki"
Just pn ->
a [href (toValue ("http://www.haskell.org/haskellwiki/index.php?title=" <>
pn <>
"&action=edit"))]
"Edit this page"
|
yogsototh/hl
|
src/HL/V/Template.hs
|
bsd-3-clause
| 5,811 | 0 | 25 | 2,066 | 1,390 | 687 | 703 | 145 | 4 |
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
-- |
-- Module : Data.UUID.Quasi
-- Copyright : (c) 2011 Lars Petersen
--
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
--
-- This library supplies quasiquotation of 'U.UUID's. You should use this in
-- case you want to hardcode 'U.UUID's in your sourcecode with compile-time
-- checking for syntax errors.
module Data.UUID.Quasi (uuid) where
import qualified Data.UUID.Types as U
import Language.Haskell.TH.Lib
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax
uuidWords :: String -> Q [Lit]
uuidWords uuidStr =
case U.fromString uuidStr of
Nothing -> fail "not a valid UUID"
Just u ->
case U.toWords u of
(w1,w2,w3,w4) ->
return $ map (IntegerL . toInteger) [w1,w2,w3,w4]
expUUID :: String -> Q Exp
expUUID uuidStr = do
wds <- uuidWords uuidStr
let litNums = map LitE wds
fromExp <- varE 'U.fromWords
return $ foldl AppE fromExp litNums
patUUID :: String -> Q Pat
patUUID uuidStr = do
wds <- uuidWords uuidStr
let patNums = map LitP wds
patTup = TupP patNums
toExp <- varE 'U.toWords
return $ ViewP toExp patTup
{- | The quasiquoter for expressions and patterns of 'U.UUID'. Make sure to enable '-XQuasiQuotes'.
> > let a = [uuid|550e8400-e29b-41d4-a716-446655440000|]
> > :type a
> a :: UUID
> > case a of { [uuid|550e8400-e29b-41d4-a716-446655440000|] -> True; _ -> False; }
> True
Pattern matching requires '-XViewPatterns'.
-}
uuid :: QuasiQuoter
uuid = QuasiQuoter
{ quoteExp = expUUID
, quotePat = patUUID
}
|
lpeterse/uuid-quasi
|
Data/UUID/Quasi.hs
|
bsd-3-clause
| 1,687 | 0 | 14 | 377 | 335 | 183 | 152 | -1 | -1 |
------------------------------------------------------------------------
-- |
-- Module : Data.Minecraft.Classic.Protocol
-- Copyright : (c) 2016 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <[email protected]>
-- Stability : experimental
-- Portability : portable
--
------------------------------------------------------------------------
module Data.Minecraft.Internal.Builder
( buildWord8
, buildWord16
, buildWord32
, buildWord64
, buildInt8
, buildInt16
, buildInt32
, buildInt64
, buildFloat
, buildDouble
, buildBool
, buildText
, buildByteString
) where
import Data.ByteString as B
import Data.ByteString.Builder
import Data.Int
import Data.Text as T
import Data.Word
buildWord8 :: Word8 -> Builder
buildWord8 = word8
{-# INLINE buildWord8 #-}
buildWord16 :: Word16 -> Builder
buildWord16 = word16BE
{-# INLINE buildWord16 #-}
buildWord32 :: Word32 -> Builder
buildWord32 = word32BE
{-# INLINE buildWord32 #-}
buildWord64 :: Word64 -> Builder
buildWord64 = word64BE
{-# INLINE buildWord64 #-}
buildFloat :: Float -> Builder
buildFloat = floatBE
{-# INLINE buildFloat #-}
buildDouble :: Double -> Builder
buildDouble = doubleBE
{-# INLINE buildDouble #-}
buildInt8 :: Int8 -> Builder
buildInt8 = int8
{-# INLINE buildInt8 #-}
buildInt16 :: Int16 -> Builder
buildInt16 = int16BE
{-# INLINE buildInt16 #-}
buildInt32 :: Int32 -> Builder
buildInt32 = int32BE
{-# INLINE buildInt32 #-}
buildInt64 :: Int64 -> Builder
buildInt64 = int64BE
{-# INLINE buildInt64 #-}
buildBool :: Bool -> Builder
buildBool = word8 . toEnum . fromEnum
{-# INLINE buildBool #-}
buildText :: Text -> Builder
buildText = undefined
buildByteString :: ByteString -> Builder
buildByteString = byteString
|
oldmanmike/hs-minecraft-protocol
|
src/Data/Minecraft/Internal/Builder.hs
|
bsd-3-clause
| 1,859 | 0 | 6 | 376 | 290 | 182 | 108 | 56 | 1 |
-- |
-- Module : Network.TLS.Crypto.IES
-- License : BSD-style
-- Maintainer : Kazu Yamamoto <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
module Network.TLS.Crypto.IES
(
GroupPublic
, GroupPrivate
, GroupKey
-- * Group methods
, groupGenerateKeyPair
, groupGetPubShared
, groupGetShared
, encodeGroupPublic
, decodeGroupPublic
) where
import Control.Arrow
import Crypto.ECC
import Crypto.Error
import Crypto.PubKey.DH
import Crypto.PubKey.ECIES
import Data.Proxy
import Network.TLS.Crypto.Types
import Network.TLS.Extra.FFDHE
import Network.TLS.Imports
import Network.TLS.RNG
import Network.TLS.Util.Serialization (os2ip,i2ospOf_)
data GroupPrivate = GroupPri_P256 (Scalar Curve_P256R1)
| GroupPri_P384 (Scalar Curve_P384R1)
| GroupPri_P521 (Scalar Curve_P521R1)
| GroupPri_X255 (Scalar Curve_X25519)
| GroupPri_X448 (Scalar Curve_X448)
| GroupPri_FFDHE2048 PrivateNumber
| GroupPri_FFDHE3072 PrivateNumber
| GroupPri_FFDHE4096 PrivateNumber
| GroupPri_FFDHE6144 PrivateNumber
| GroupPri_FFDHE8192 PrivateNumber
deriving (Eq, Show)
data GroupPublic = GroupPub_P256 (Point Curve_P256R1)
| GroupPub_P384 (Point Curve_P384R1)
| GroupPub_P521 (Point Curve_P521R1)
| GroupPub_X255 (Point Curve_X25519)
| GroupPub_X448 (Point Curve_X448)
| GroupPub_FFDHE2048 PublicNumber
| GroupPub_FFDHE3072 PublicNumber
| GroupPub_FFDHE4096 PublicNumber
| GroupPub_FFDHE6144 PublicNumber
| GroupPub_FFDHE8192 PublicNumber
deriving (Eq, Show)
type GroupKey = SharedSecret
p256 :: Proxy Curve_P256R1
p256 = Proxy
p384 :: Proxy Curve_P384R1
p384 = Proxy
p521 :: Proxy Curve_P521R1
p521 = Proxy
x25519 :: Proxy Curve_X25519
x25519 = Proxy
x448 :: Proxy Curve_X448
x448 = Proxy
groupGenerateKeyPair :: MonadRandom r => Group -> r (GroupPrivate, GroupPublic)
groupGenerateKeyPair P256 =
(GroupPri_P256,GroupPub_P256) `fs` curveGenerateKeyPair p256
groupGenerateKeyPair P384 =
(GroupPri_P384,GroupPub_P384) `fs` curveGenerateKeyPair p384
groupGenerateKeyPair P521 =
(GroupPri_P521,GroupPub_P521) `fs` curveGenerateKeyPair p521
groupGenerateKeyPair X25519 =
(GroupPri_X255,GroupPub_X255) `fs` curveGenerateKeyPair x25519
groupGenerateKeyPair X448 =
(GroupPri_X448,GroupPub_X448) `fs` curveGenerateKeyPair x448
groupGenerateKeyPair FFDHE2048 = gen ffdhe2048 GroupPri_FFDHE2048 GroupPub_FFDHE2048
groupGenerateKeyPair FFDHE3072 = gen ffdhe3072 GroupPri_FFDHE3072 GroupPub_FFDHE3072
groupGenerateKeyPair FFDHE4096 = gen ffdhe4096 GroupPri_FFDHE4096 GroupPub_FFDHE4096
groupGenerateKeyPair FFDHE6144 = gen ffdhe6144 GroupPri_FFDHE6144 GroupPub_FFDHE6144
groupGenerateKeyPair FFDHE8192 = gen ffdhe8192 GroupPri_FFDHE8192 GroupPub_FFDHE8192
fs :: MonadRandom r
=> (Scalar a -> GroupPrivate, Point a -> GroupPublic)
-> r (KeyPair a)
-> r (GroupPrivate, GroupPublic)
(t1, t2) `fs` action = do
keypair <- action
let pub = keypairGetPublic keypair
pri = keypairGetPrivate keypair
return (t1 pri, t2 pub)
gen :: MonadRandom r
=> Params
-> (PrivateNumber -> GroupPrivate)
-> (PublicNumber -> GroupPublic)
-> r (GroupPrivate, GroupPublic)
gen params priTag pubTag = do
pri <- generatePrivate params
let pub = calculatePublic params pri
return (priTag pri, pubTag pub)
groupGetPubShared :: MonadRandom r => GroupPublic -> r (GroupPublic, GroupKey)
groupGetPubShared (GroupPub_P256 pub) =
first GroupPub_P256 <$> deriveEncrypt p256 pub
groupGetPubShared (GroupPub_P384 pub) =
first GroupPub_P384 <$> deriveEncrypt p384 pub
groupGetPubShared (GroupPub_P521 pub) =
first GroupPub_P521 <$> deriveEncrypt p521 pub
groupGetPubShared (GroupPub_X255 pub) =
first GroupPub_X255 <$> deriveEncrypt x25519 pub
groupGetPubShared (GroupPub_X448 pub) =
first GroupPub_X448 <$> deriveEncrypt x448 pub
groupGetPubShared (GroupPub_FFDHE2048 pub) = getPubShared ffdhe2048 pub GroupPub_FFDHE2048
groupGetPubShared (GroupPub_FFDHE3072 pub) = getPubShared ffdhe3072 pub GroupPub_FFDHE3072
groupGetPubShared (GroupPub_FFDHE4096 pub) = getPubShared ffdhe4096 pub GroupPub_FFDHE4096
groupGetPubShared (GroupPub_FFDHE6144 pub) = getPubShared ffdhe6144 pub GroupPub_FFDHE6144
groupGetPubShared (GroupPub_FFDHE8192 pub) = getPubShared ffdhe8192 pub GroupPub_FFDHE8192
getPubShared :: MonadRandom r
=> Params
-> PublicNumber
-> (PublicNumber -> GroupPublic)
-> r (GroupPublic, GroupKey)
getPubShared params pub pubTag = do
mypri <- generatePrivate params
let mypub = calculatePublic params mypri
let SharedKey share = getShared params mypri pub
return (pubTag mypub, SharedSecret share)
groupGetShared :: GroupPublic -> GroupPrivate -> Maybe GroupKey
groupGetShared (GroupPub_P256 pub) (GroupPri_P256 pri) = Just $ deriveDecrypt p256 pub pri
groupGetShared (GroupPub_P384 pub) (GroupPri_P384 pri) = Just $ deriveDecrypt p384 pub pri
groupGetShared (GroupPub_P521 pub) (GroupPri_P521 pri) = Just $ deriveDecrypt p521 pub pri
groupGetShared (GroupPub_X255 pub) (GroupPri_X255 pri) = Just $ deriveDecrypt x25519 pub pri
groupGetShared (GroupPub_X448 pub) (GroupPri_X448 pri) = Just $ deriveDecrypt x448 pub pri
groupGetShared (GroupPub_FFDHE2048 pub) (GroupPri_FFDHE2048 pri) = Just $ calcShared ffdhe2048 pub pri
groupGetShared (GroupPub_FFDHE3072 pub) (GroupPri_FFDHE3072 pri) = Just $ calcShared ffdhe3072 pub pri
groupGetShared (GroupPub_FFDHE4096 pub) (GroupPri_FFDHE4096 pri) = Just $ calcShared ffdhe4096 pub pri
groupGetShared (GroupPub_FFDHE6144 pub) (GroupPri_FFDHE6144 pri) = Just $ calcShared ffdhe6144 pub pri
groupGetShared (GroupPub_FFDHE8192 pub) (GroupPri_FFDHE8192 pri) = Just $ calcShared ffdhe8192 pub pri
groupGetShared _ _ = Nothing
calcShared :: Params -> PublicNumber -> PrivateNumber -> SharedSecret
calcShared params pub pri = SharedSecret share
where
SharedKey share = getShared params pri pub
encodeGroupPublic :: GroupPublic -> ByteString
encodeGroupPublic (GroupPub_P256 p) = encodePoint p256 p
encodeGroupPublic (GroupPub_P384 p) = encodePoint p384 p
encodeGroupPublic (GroupPub_P521 p) = encodePoint p521 p
encodeGroupPublic (GroupPub_X255 p) = encodePoint x25519 p
encodeGroupPublic (GroupPub_X448 p) = encodePoint x448 p
encodeGroupPublic (GroupPub_FFDHE2048 p) = enc ffdhe2048 p
encodeGroupPublic (GroupPub_FFDHE3072 p) = enc ffdhe3072 p
encodeGroupPublic (GroupPub_FFDHE4096 p) = enc ffdhe4096 p
encodeGroupPublic (GroupPub_FFDHE6144 p) = enc ffdhe6144 p
encodeGroupPublic (GroupPub_FFDHE8192 p) = enc ffdhe8192 p
enc :: Params -> PublicNumber -> ByteString
enc params (PublicNumber p) = i2ospOf_ ((params_bits params + 7) `div` 8) p
decodeGroupPublic :: Group -> ByteString -> Either CryptoError GroupPublic
decodeGroupPublic P256 bs = eitherCryptoError $ GroupPub_P256 <$> decodePoint p256 bs
decodeGroupPublic P384 bs = eitherCryptoError $ GroupPub_P384 <$> decodePoint p384 bs
decodeGroupPublic P521 bs = eitherCryptoError $ GroupPub_P521 <$> decodePoint p521 bs
decodeGroupPublic X25519 bs = eitherCryptoError $ GroupPub_X255 <$> decodePoint x25519 bs
decodeGroupPublic X448 bs = eitherCryptoError $ GroupPub_X448 <$> decodePoint x448 bs
decodeGroupPublic FFDHE2048 bs = Right . GroupPub_FFDHE2048 . PublicNumber $ os2ip bs
decodeGroupPublic FFDHE3072 bs = Right . GroupPub_FFDHE3072 . PublicNumber $ os2ip bs
decodeGroupPublic FFDHE4096 bs = Right . GroupPub_FFDHE4096 . PublicNumber $ os2ip bs
decodeGroupPublic FFDHE6144 bs = Right . GroupPub_FFDHE6144 . PublicNumber $ os2ip bs
decodeGroupPublic FFDHE8192 bs = Right . GroupPub_FFDHE8192 . PublicNumber $ os2ip bs
|
erikd/hs-tls
|
core/Network/TLS/Crypto/IES.hs
|
bsd-3-clause
| 7,974 | 0 | 10 | 1,486 | 2,104 | 1,066 | 1,038 | 153 | 1 |
-- |
module Graphics.BothGL.Instances.GHC where
instance MonadIO gl => GL gl where
createShader t = fmap (fmap Shader . zeroNothing) glCreateShader t
shaderSource (Shader s) bs =
allocaArray (length chunks) $ \ps ->
allocaArray (length chunks) $ \pl ->
go 0 chunks ps pl
where
chunks = Lazy.toChunks bs
go :: Int -> [Strict.ByteString] -> Ptr (Ptr GLchar) -> Ptr GLint -> IO ()
go i (Strict.PS fp o l:cs) ps pl = do
pokeElemOff pl i (fromIntegral l)
withForeignPtr fp $ \p -> do
pokeElemOff ps i (castPtr p `plusPtr` o)
go (i+1) cs ps pl
go i [] ps pl = glShaderSource sh (fromIntegral i) ps pl
compileShader (Shader s) = glCompileShader s
attachShader (Program p) (Shader s) = glAttachShader p s
linkProgram (Program p) = glLinkProgram
useProgram (Program p) = glUseProgram p
attributeLocation (Program p) s =
liftIO $ check <$> withCString s (glGetAttribLocation p . castPtr) where
check n
| n < 0 = Nothing
| otherwise = Just $ fromIntegral n
enableVertexAttribArray = glEnableVertexAttribArray
vertexAttribPointer loc comp ty toNorm stride offPtr =
liftIO $ glVertexAttribPointer loc (fromIntegral comp) ty (if toNorm then GL_TRUE else GL_FALSE) (fromIntegral stride) offPtr
drawArrays mode p size = liftIO $ glDrawArrays mode p size
clear = glClear
createBuffer
bindBuffer
bufferData t d = withRawData v $ \ptr ->
glBufferData t (fromIntegral $ sizeOfData v) ptr (coerce u)
|
bergey/bothgl
|
src/Graphics/BothGL/Instances/GHC.hs
|
bsd-3-clause
| 1,514 | 36 | 9 | 362 | 562 | 288 | 274 | -1 | -1 |
-----------------------------------------------------------------------------
--
-- Module : MFlow.Hack.XHtml
-- Copyright :
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
{-
Instantiations necessary for "MFlow.Hack" to use "Text.XHtml" as format for generating output
-}
{-# OPTIONS -XMultiParamTypeClasses #-}
module MFlow.Hack.XHtml (
) where
import MFlow
import Hack
import MFlow.Hack.Response
import Text.XHtml
import Data.Typeable
import Data.ByteString.Lazy.Char8 as B(pack,unpack, length, ByteString)
instance ToResponse Html where
toResponse x= Response{ status=200, headers=[]
, Hack.body= pack $ showHtml x}
--
--instance Typeable Html where
-- typeOf = \_ -> mkTyConApp (mkTyCon "Text.XHtml.Strict.Html") []
--
--instance ConvertTo Html TResp where
-- convert = TResp
|
agocorona/MFlow
|
src/MFlow/Hack/XHtml.hs
|
bsd-3-clause
| 983 | 0 | 9 | 167 | 123 | 84 | 39 | 11 | 0 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Volume.HR.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Resolve
import Duckling.Testing.Types
import Duckling.Volume.Types
corpus :: Corpus
corpus = (testContext {lang = HR}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (VolumeValue Millilitre 250)
[ "250 mililitara"
, "250ml"
, "250 ml"
]
, examples (VolumeValue Litre 2)
[ "2 litre"
]
, examples (VolumeValue Gallon 3)
[ "3 galona"
, "3 gal"
]
, examples (VolumeValue Hectolitre 3)
[ "3 hektolitra"
]
, examples (VolumeValue Litre 0.5)
[ "pola litre"
]
]
|
rfranek/duckling
|
Duckling/Volume/HR/Corpus.hs
|
bsd-3-clause
| 1,123 | 0 | 9 | 334 | 194 | 115 | 79 | 26 | 1 |
module Module5.Task1 where
-- system code
data Point3D a = Point3D a a a deriving Show
-- solution code
instance Functor Point3D where
fmap f (Point3D a b c) = Point3D (f a) (f b) (f c)
|
dstarcev/stepic-haskell
|
src/Module5/Task1.hs
|
bsd-3-clause
| 190 | 0 | 8 | 41 | 78 | 42 | 36 | 4 | 0 |
-- Copyright (c) 2012-2016, Christoph Pohl
-- BSD License (see http://www.opensource.org/licenses/BSD-3-Clause)
-------------------------------------------------------------------------------
--
-- Project Euler Problem 21
--
-- Let d(n) be defined as the sum of proper divisors of n (numbers less than n
-- which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a
-- and b are an amicable pair and each of a and b are called amicable numbers.
--
-- For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44,
-- 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4,
-- 71 and 142; so d(284) = 220.
--
-- Evaluate the sum of all the amicable numbers under 10000.
module Main where
main :: IO ()
main = print result
result = sum $ amicable
divisors n = [x | x <- [1..n-1], n `mod` x == 0]
d = sum . divisors
amicable = [x | x <- [1..9999], x == d (d x), x /= d x]
|
Psirus/euler
|
src/euler021.hs
|
bsd-3-clause
| 930 | 0 | 10 | 188 | 146 | 85 | 61 | 7 | 1 |
module MsgDiagram.Parser where
import Text.Parsec
import Data.Maybe
import Data.List
import MsgDiagram.Lexer
import MsgDiagram.Model
-- | Wrapper function.
parseMsgDiagram :: String -> Either ParseError MsgDiagram
parseMsgDiagram input = runParser (runLex doParse) 1 "" input
doParse :: Parser MsgDiagram
doParse = do steps <- many parseStep
eof
return $ steps
<?> "Parse Protocol"
parseStep :: Parser MsgDiagramStep
parseStep = do from <- identifier
reservedOp "->"
to <- identifier
colon
msgs <- commaSep1 parseMSG
no <- getState
updateState (+1)
return $ MsgDiagramStep no from to msgs
<?> "Protocol Step"
parseMSG :: Parser Message
parseMSG = do stringLiteral
<?> "Message"
-- --------------------------------------------------------------------- [ EOF ]
|
jfdm/hUML
|
src/MsgDiagram/Parser.hs
|
bsd-3-clause
| 953 | 0 | 9 | 295 | 210 | 103 | 107 | 26 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
-----------------------------------------------------------------
-- Auto-generated by regenClassifiers
--
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ranking.Classifiers.ZH_TW (classifiers) where
import Data.String
import Prelude
import qualified Data.HashMap.Strict as HashMap
import Duckling.Ranking.Types
classifiers :: Classifiers
classifiers
= HashMap.fromList
[("\25490\28783\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\19996\27491\25945\26837\26525\20027\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("number of 5 minutes after|past <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = -0.2231435513142097, unseen = -3.332204510175204,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)integer (0..10)",
-0.8979415932059586),
("hour", -0.7308875085427924),
("<integer> (latent time-of-day)<number>\20010/\20491",
-2.1972245773362196)],
n = 12},
koData =
ClassData{prior = -1.6094379124341003,
unseen = -2.3025850929940455,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)integer (0..10)",
-0.8109302162163288),
("hour", -0.8109302162163288)],
n = 3}}),
("\21360\24230\20016\25910\33410\31532\22235\22825",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> timezone",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("<time-of-day> am|pm", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("Thursday",
Classifier{okData =
ClassData{prior = -0.4700036292457356,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -0.9808292530117262,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3}}),
("integer (numeric)",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -4.23410650459726,
likelihoods = HashMap.fromList [("", 0.0)], n = 67},
koData =
ClassData{prior = -0.6931471805599453, unseen = -4.23410650459726,
likelihoods = HashMap.fromList [("", 0.0)], n = 67}}),
("\21355\22622\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("the day before yesterday",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22269\38469\28040\36153\32773\26435\30410\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\24314\20891\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\29369\22826\26032\24180",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("today",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("mm/dd",
Classifier{okData =
ClassData{prior = -1.6094379124341003,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -0.2231435513142097, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4}}),
("absorption of , after named day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453), ("Sunday", -0.6931471805599453)],
n = 7},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("September",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("tonight",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("October",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("month (grain)",
Classifier{okData =
ClassData{prior = -0.963437510299857, unseen = -3.4339872044851463,
likelihoods = HashMap.fromList [("", 0.0)], n = 29},
koData =
ClassData{prior = -0.48058573857627246,
unseen = -3.891820298110627,
likelihoods = HashMap.fromList [("", 0.0)], n = 47}}),
("<time-of-day> o'clock",
Classifier{okData =
ClassData{prior = -1.466337068793427, unseen = -3.044522437723423,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 9},
koData =
ClassData{prior = -0.262364264467491, unseen = -4.143134726391533,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 30}}),
("national day",
Classifier{okData =
ClassData{prior = -0.2231435513142097,
unseen = -2.3025850929940455,
likelihoods = HashMap.fromList [("", 0.0)], n = 8},
koData =
ClassData{prior = -1.6094379124341003,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("integer (20,30,40)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("Wednesday",
Classifier{okData =
ClassData{prior = -5.715841383994864e-2,
unseen = -2.9444389791664407,
likelihoods = HashMap.fromList [("", 0.0)], n = 17},
koData =
ClassData{prior = -2.890371757896165, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("\21360\24230\20016\25910\33410\31532\19977\22825",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("hour (grain)",
Classifier{okData =
ClassData{prior = -9.53101798043249e-2,
unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [("", 0.0)], n = 20},
koData =
ClassData{prior = -2.3978952727983707,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("\22307\20250\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\20803\26086",
Classifier{okData =
ClassData{prior = -1.0986122886681098, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -0.40546510810816444,
unseen = -2.3025850929940455,
likelihoods = HashMap.fromList [("", 0.0)], n = 8}}),
("\32654\22269\29420\31435\26085",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("intersect",
Classifier{okData =
ClassData{prior = -5.694137640013845e-2,
unseen = -6.329720905522696,
likelihoods =
HashMap.fromList
[("\20799\31461\33410<part-of-day> <dim time>",
-4.718498871295094),
("year (numeric with year symbol)\20809\26126\33410",
-4.248495242049359),
("xxxx year<named-month> <day-of-month>", -4.941642422609305),
("daymonth", -4.248495242049359),
("monthday", -1.9459101490553135),
("next yearSeptember", -5.2293244950610855),
("year (numeric with year symbol)\25995\26376",
-4.941642422609305),
("year (numeric with year symbol)\20061\22812\33410",
-4.941642422609305),
("year (numeric with year symbol)February", -4.718498871295094),
("xxxx yearintersect", -4.941642422609305),
("March<time> <day-of-month>", -3.7629874262676584),
("year (numeric with year symbol)<named-month> <day-of-month>",
-3.494723439672979),
("monthhour", -3.7629874262676584),
("year (numeric with year symbol)\22320\29699\19968\23567\26102",
-5.2293244950610855),
("year (numeric with year symbol)April", -5.2293244950610855),
("dayday", -2.284885515894645),
("hourhour", -4.718498871295094),
("xxxx yearFebruary", -5.634789603169249),
("year (numeric with year symbol)March", -4.1307122063929755),
("February<dim time> <part-of-day>", -3.7629874262676584),
("hourminute", -4.718498871295094),
("April<time> <day-of-month>", -5.2293244950610855),
("February<time> <day-of-month>", -2.614364717024887),
("absorption of , after named day<named-month> <day-of-month>",
-3.619886582626985),
("year (numeric with year symbol)\22823\25995\26399",
-4.941642422609305),
("this <cycle><time> <day-of-month>", -4.941642422609305),
("year (numeric with year symbol)\22235\26092\33410",
-5.2293244950610855),
("yearmonth", -3.332204510175204),
("year (numeric with year symbol)\20303\26842\33410",
-5.2293244950610855),
("dayminute", -4.718498871295094),
("next <cycle>September", -5.634789603169249),
("intersect by \",\"<time> <day-of-month>", -3.619886582626985),
("xxxx yearMarch", -5.634789603169249),
("absorption of , after named dayintersect",
-3.619886582626985),
("intersect<time> <day-of-month>", -2.8015762591130335),
("next <cycle><time> <day-of-month>", -4.941642422609305),
("tonight<time-of-day> o'clock", -4.718498871295094),
("year (numeric with year symbol)intersect",
-3.494723439672979),
("yearday", -2.0794415416798357),
("absorption of , after named dayFebruary", -4.248495242049359),
("year (numeric with year symbol)\19971\19971\33410",
-4.248495242049359),
("year (numeric with year symbol)\36926\36234\33410",
-5.2293244950610855),
("year (numeric with year symbol)\29369\22826\26032\24180",
-5.2293244950610855),
("yearminute", -5.2293244950610855),
("<dim time> <part-of-day>relative (10-59) minutes after|past <integer> (hour-of-day)",
-4.718498871295094)],
n = 256},
koData =
ClassData{prior = -2.894068619777491, unseen = -4.3694478524670215,
likelihoods =
HashMap.fromList
[("\20799\31461\33410<part-of-day> <dim time>",
-2.159484249353372),
("dayhour", -2.7472709142554916),
("year (numeric with year symbol)Sunday", -3.6635616461296463),
("<dim time> <part-of-day><time-of-day> o'clock",
-3.258096538021482),
("hourhour", -3.258096538021482),
("hourminute", -2.7472709142554916),
("dayminute", -2.7472709142554916),
("yearday", -3.6635616461296463),
("<dim time> <part-of-day>relative (10-59) minutes after|past <integer> (hour-of-day)",
-2.7472709142554916)],
n = 15}}),
("half after|past <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 5},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\20399\20029\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("year (grain)",
Classifier{okData =
ClassData{prior = -1.625967214385311, unseen = -2.639057329615259,
likelihoods = HashMap.fromList [("", 0.0)], n = 12},
koData =
ClassData{prior = -0.21905356606268464,
unseen = -3.9318256327243257,
likelihoods = HashMap.fromList [("", 0.0)], n = 49}}),
("Saturday",
Classifier{okData =
ClassData{prior = -0.8754687373538999,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -0.5389965007326869,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7}}),
("next <cycle>",
Classifier{okData =
ClassData{prior = -0.570544858467613, unseen = -3.4965075614664802,
likelihoods =
HashMap.fromList
[("week", -1.6739764335716716),
("month (grain)", -1.5198257537444133),
("year (grain)", -2.367123614131617),
("week (grain)", -1.6739764335716716),
("year", -2.367123614131617), ("month", -1.5198257537444133)],
n = 13},
koData =
ClassData{prior = -0.832909122935104, unseen = -3.295836866004329,
likelihoods =
HashMap.fromList
[("week", -0.8602012652231115),
("week (grain)", -0.8602012652231115)],
n = 10}}),
("last year",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22307\27583\34987\27585\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("this <day-of-week>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.970291913552122,
likelihoods =
HashMap.fromList
[("Wednesday", -1.8718021769015913),
("Monday", -1.8718021769015913), ("day", -0.7323678937132265),
("Tuesday", -1.5533484457830569)],
n = 24},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("\35199\36203\25176\25289\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3025850929940455,
likelihoods = HashMap.fromList [("", 0.0)], n = 8},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("yyyy-mm-dd",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("mm/dd/yyyy",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\20811\21704\29305\26222\36838\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\21313\32988\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("evening|night",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\20303\26842\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22307\19977\19968\20027\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\30331\38660\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("Monday",
Classifier{okData =
ClassData{prior = -0.15415067982725836,
unseen = -3.258096538021482,
likelihoods = HashMap.fromList [("", 0.0)], n = 24},
koData =
ClassData{prior = -1.9459101490553135, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4}}),
("\19971\19971\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("yesterday",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("next year",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> <day-of-month>",
Classifier{okData =
ClassData{prior = -0.24946085963158313,
unseen = -4.204692619390966,
likelihoods =
HashMap.fromList
[("integer (numeric)", -1.3564413979702095),
("integer (20,30,40)", -3.0910424533583156),
("integer with consecutive unit modifiers", -1.245215762859985),
("integer (0..10)", -1.4170660197866443),
("number suffix: \21313|\25342", -2.1102132003465894),
("compose by multiplication", -3.0910424533583156)],
n = 60},
koData =
ClassData{prior = -1.5105920777974677,
unseen = -3.1780538303479458,
likelihoods =
HashMap.fromList
[("integer (0..10)", -0.3629054936893685),
("number suffix: \21313|\25342", -2.03688192726104)],
n = 17}}),
("\19996\27491\25945\22797\27963\33410",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3}}),
("hh:mm (time-of-day)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.833213344056216,
likelihoods = HashMap.fromList [("", 0.0)], n = 15},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("relative (1-9) minutes after|past <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.044522437723423,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)integer (0..10)",
-0.6931471805599453),
("hour", -0.6931471805599453)],
n = 9},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("<integer> (latent time-of-day)",
Classifier{okData =
ClassData{prior = -0.2754119798599665,
unseen = -3.8066624897703196,
likelihoods =
HashMap.fromList
[("integer (numeric)", -2.174751721484161),
("integer (0..10)", -0.1466034741918754)],
n = 41},
koData =
ClassData{prior = -1.4240346891027378, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("integer (numeric)", -0.4700036292457356),
("one point 2", -1.1631508098056809)],
n = 13}}),
("\36926\36234\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("nth <time> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("Octoberordinal (digits)Monday", -0.6931471805599453),
("monthday", -0.6931471805599453)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\22235\26092\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\19996\27491\25945\22307\21608\20845",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("April",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\21360\24230\20016\25910\33410",
Classifier{okData =
ClassData{prior = -0.5108256237659907,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -0.916290731874155, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("\20809\26126\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("week (grain)",
Classifier{okData =
ClassData{prior = -0.8434293836092833,
unseen = -3.6635616461296463,
likelihoods = HashMap.fromList [("", 0.0)], n = 37},
koData =
ClassData{prior = -0.5625269981428811,
unseen = -3.9318256327243257,
likelihoods = HashMap.fromList [("", 0.0)], n = 49}}),
("relative (10-59) minutes after|past <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = -0.45198512374305727,
unseen = -4.127134385045092,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)compose by multiplication",
-2.164963715117998),
("<integer> (latent time-of-day)integer with consecutive unit modifiers",
-0.9753796482441617),
("hour", -0.7435780341868373)],
n = 28},
koData =
ClassData{prior = -1.0116009116784799,
unseen = -3.6375861597263857,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)number suffix: \21313|\25342",
-1.413693335308005),
("<integer> (latent time-of-day)integer (0..10)",
-1.413693335308005),
("hour", -0.7777045685880083)],
n = 16}}),
("year (numeric with year symbol)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.891820298110627,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 47},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("now",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22823\25995\26399",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\24858\20154\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\29369\22826\26893\26641\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\19996\27491\25945\22797\27963\33410\26143\26399\19968",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22307\28789\33410\24198\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("numbers prefix with -, negative or minus",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 4}}),
("Friday",
Classifier{okData =
ClassData{prior = -0.6931471805599453,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -0.6931471805599453,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5}}),
("tomorrow",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("this year",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22522\30563\22307\20307\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\28595\38376\22238\24402\32426\24565\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\21360\24230\20804\22969\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("next <day-of-week>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1780538303479458,
likelihoods =
HashMap.fromList
[("Wednesday", -1.3437347467010947),
("day", -0.7375989431307791), ("Tuesday", -1.3437347467010947)],
n = 10},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("fractional number",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5}}),
("Sunday",
Classifier{okData =
ClassData{prior = -4.8790164169432056e-2,
unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [("", 0.0)], n = 20},
koData =
ClassData{prior = -3.044522437723423, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("afternoon",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.6375861597263857,
likelihoods = HashMap.fromList [("", 0.0)], n = 36},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> from now",
Classifier{okData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.891820298110627,
likelihoods =
HashMap.fromList
[("week", -2.2617630984737906), ("second", -2.772588722239781),
("day", -2.2617630984737906), ("year", -2.772588722239781),
("<integer> <unit-of-duration>", -0.8266785731844679),
("hour", -2.2617630984737906), ("month", -2.772588722239781),
("minute", -2.772588722239781)],
n = 20}}),
("\36174\32618\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("February",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.258096538021482,
likelihoods = HashMap.fromList [("", 0.0)], n = 24},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("this <cycle>",
Classifier{okData =
ClassData{prior = -0.8909729238898653,
unseen = -3.6635616461296463,
likelihoods =
HashMap.fromList
[("week", -1.1526795099383855),
("month (grain)", -2.2512917986064953),
("year (grain)", -2.538973871058276),
("week (grain)", -1.1526795099383855),
("year", -2.538973871058276), ("month", -2.2512917986064953)],
n = 16},
koData =
ClassData{prior = -0.5280674302004967, unseen = -3.970291913552122,
likelihoods =
HashMap.fromList
[("week", -0.7731898882334817),
("week (grain)", -0.7731898882334817)],
n = 23}}),
("minute (grain)",
Classifier{okData =
ClassData{prior = -0.4462871026284195, unseen = -2.890371757896165,
likelihoods = HashMap.fromList [("", 0.0)], n = 16},
koData =
ClassData{prior = -1.0216512475319814,
unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9}}),
("xxxx year",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods =
HashMap.fromList
[("integer (0..10)integer (0..10)integer (0..10)integer (0..10)",
0.0)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<dim time> <part-of-day>",
Classifier{okData =
ClassData{prior = -7.696104113612832e-2,
unseen = -4.6913478822291435,
likelihoods =
HashMap.fromList
[("dayhour", -0.750305594399894),
("national dayevening|night", -3.58351893845611),
("<named-month> <day-of-month>morning", -2.117181869662683),
("\24773\20154\33410evening|night", -3.58351893845611),
("\20799\31461\33410afternoon", -3.58351893845611),
("intersectmorning", -2.117181869662683),
("<time> <day-of-month>morning", -2.117181869662683),
("Mondaymorning", -2.4849066497880004)],
n = 50},
koData =
ClassData{prior = -2.6026896854443837, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("dayhour", -1.1631508098056809),
("<time> <day-of-month>morning", -1.1631508098056809)],
n = 4}}),
("<part-of-day> <dim time>",
Classifier{okData =
ClassData{prior = -0.7935659283069926,
unseen = -5.0369526024136295,
likelihoods =
HashMap.fromList
[("tonight<integer> (latent time-of-day)", -3.4210000089583352),
("afternoonrelative (10-59) minutes after|past <integer> (hour-of-day)",
-1.6631420914059614),
("hourhour", -2.322387720290225),
("afternoon<time-of-day> o'clock", -3.644143560272545),
("hourminute", -0.9699949108460162),
("afternoon<integer> (latent time-of-day)", -3.644143560272545),
("afternoonrelative (1-9) minutes after|past <integer> (hour-of-day)",
-2.72785282839839),
("afternoonhh:mm (time-of-day)", -3.644143560272545),
("tonight<time-of-day> o'clock", -3.4210000089583352),
("afternoonnumber of 5 minutes after|past <integer> (hour-of-day)",
-2.4654885639308985),
("afternoonhalf after|past <integer> (hour-of-day)",
-3.2386784521643803)],
n = 71},
koData =
ClassData{prior = -0.6018985090948004, unseen = -5.214935757608986,
likelihoods =
HashMap.fromList
[("afternoonrelative (10-59) minutes after|past <integer> (hour-of-day)",
-2.3762728087852047),
("hourhour", -0.9899784476653142),
("afternoon<time-of-day> o'clock", -1.7754989483562746),
("hourminute", -2.21375387928743),
("afternoon<integer> (latent time-of-day)", -1.571899993115035),
("afternoonnumber of 5 minutes after|past <integer> (hour-of-day)",
-3.82319179172153)],
n = 86}}),
("<integer> <unit-of-duration>",
Classifier{okData =
ClassData{prior = -infinity, unseen = -3.1354942159291497,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -6.244166900663736,
likelihoods =
HashMap.fromList
[("number suffix: \21313|\25342month (grain)",
-4.632785353021065),
("week", -3.0233474405869645),
("integer (0..10)month (grain)", -2.745715703988685),
("integer (0..10)hour (grain)", -3.1067290495260154),
("<number>\20010/\20491week (grain)", -3.8443279926567944),
("compose by multiplicationminute (grain)", -4.45046379622711),
("second", -3.6031659358399066),
("integer (0..10)day (grain)", -3.1067290495260154),
("integer (0..10)year (grain)", -3.7573166156671647),
("<number>\20010/\20491month (grain)", -3.469634543215384),
("integer (numeric)year (grain)", -2.3710222545472743),
("integer (0..10)second (grain)", -3.6031659358399066),
("day", -3.1067290495260154), ("year", -2.1646858215494458),
("integer (0..10)minute (grain)", -2.984126727433683),
("number suffix: \21313|\25342minute (grain)",
-4.855928904335275),
("hour", -3.1067290495260154),
("integer (0..10)week (grain)", -3.534173064352955),
("month", -2.008116760857906),
("integer (numeric)month (grain)", -3.3518515075590005),
("integer with consecutive unit modifiersminute (grain)",
-4.296313116399852),
("minute", -2.553343811341229)],
n = 246}}),
("\32769\26495\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\31709\28779\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time-of-day> am|pm",
Classifier{okData =
ClassData{prior = -0.4353180712578455, unseen = -3.295836866004329,
likelihoods =
HashMap.fromList
[("hh:mm (time-of-day)", -0.9555114450274363),
("<integer> (latent time-of-day)", -2.159484249353372),
("hour", -2.159484249353372), ("minute", -0.9555114450274363)],
n = 11},
koData =
ClassData{prior = -1.041453874828161, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)", -0.8266785731844679),
("hour", -0.8266785731844679)],
n = 6}}),
("one point 2",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("integer (0..10)integer (0..10)", -0.9650808960435872),
("integer (0..10)number suffix: \21313|\25342",
-1.9459101490553135),
("integer (0..10)integer with consecutive unit modifiers",
-1.3397743454849977),
("integer (0..10)<number>\20010/\20491", -2.639057329615259),
("integer (0..10)compose by multiplication",
-2.639057329615259),
("integer (0..10)half", -2.639057329615259)],
n = 36}}),
("intersect by \",\"",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.330733340286331,
likelihoods =
HashMap.fromList
[("daymonth", -2.2380465718564744),
("Sunday<named-month> <day-of-month>", -1.6094379124341003),
("SundayFebruary", -2.2380465718564744),
("dayday", -0.9501922835498364),
("Sundayintersect", -1.6094379124341003)],
n = 35},
koData =
ClassData{prior = -infinity, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [], n = 0}}),
("\26837\26525\20027\26085",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4}}),
("\38463\33298\25289\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("integer with consecutive unit modifiers",
Classifier{okData =
ClassData{prior = -5.715841383994864e-2,
unseen = -3.6109179126442243,
likelihoods =
HashMap.fromList
[("number suffix: \21313|\25342integer (0..10)",
-0.6931471805599453),
("integer (0..10)integer (0..10)", -0.6931471805599453)],
n = 34},
koData =
ClassData{prior = -2.890371757896165, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("integer (0..10)integer (0..10)", -0.2876820724517809)],
n = 2}}),
("second (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.70805020110221,
likelihoods = HashMap.fromList [("", 0.0)], n = 13},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\19996\27491\25945\32822\31267\21463\38590\26085",
Classifier{okData =
ClassData{prior = -0.3364722366212129,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -1.252762968495368, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("\25289\25746\36335\22307\21608\20845",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> ago",
Classifier{okData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.891820298110627,
likelihoods =
HashMap.fromList
[("week", -2.2617630984737906), ("second", -2.772588722239781),
("day", -2.2617630984737906), ("year", -2.772588722239781),
("<integer> <unit-of-duration>", -0.8266785731844679),
("hour", -2.2617630984737906), ("month", -2.772588722239781),
("minute", -2.772588722239781)],
n = 20}}),
("\22307\35806\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.332204510175204,
likelihoods =
HashMap.fromList
[("day", -0.7308875085427924), ("Sunday", -1.2163953243244932),
("Tuesday", -1.5040773967762742)],
n = 12},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("\20234\26031\20848\26032\24180",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("March",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.833213344056216,
likelihoods = HashMap.fromList [("", 0.0)], n = 15},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\24320\25995\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("the day after tomorrow",
Classifier{okData =
ClassData{prior = -0.5108256237659907,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -0.916290731874155, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("\22307\21608\20845",
Classifier{okData =
ClassData{prior = -0.6931471805599453,
unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -0.6931471805599453,
unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6}}),
("\22919\22899\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\20840\29699\38738\24180\26381\21153\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\27431\21335\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\20061\22812\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("next <time>",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("day", -0.7731898882334817), ("Tuesday", -0.7731898882334817)],
n = 5},
koData =
ClassData{prior = -0.6931471805599453, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("Wednesday", -0.7731898882334817),
("day", -0.7731898882334817)],
n = 5}}),
("last <cycle>",
Classifier{okData =
ClassData{prior = -0.8472978603872037,
unseen = -3.2188758248682006,
likelihoods =
HashMap.fromList
[("week", -1.3862943611198906),
("month (grain)", -1.791759469228055),
("year (grain)", -2.4849066497880004),
("week (grain)", -1.3862943611198906),
("year", -2.4849066497880004), ("month", -1.791759469228055)],
n = 9},
koData =
ClassData{prior = -0.5596157879354228,
unseen = -3.4339872044851463,
likelihoods =
HashMap.fromList
[("week", -0.8362480242006186),
("week (grain)", -0.8362480242006186)],
n = 12}}),
("\20197\33394\21015\29420\31435\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("next n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.605170185988091,
likelihoods =
HashMap.fromList
[("week", -2.3978952727983707),
("integer (0..10)hour (grain)", -2.3978952727983707),
("<number>\20010/\20491week (grain)", -2.9856819377004897),
("second", -2.803360380906535),
("integer (0..10)day (grain)", -2.515678308454754),
("integer (0..10)year (grain)", -3.2088254890146994),
("<number>\20010/\20491month (grain)", -2.803360380906535),
("integer (0..10)second (grain)", -2.803360380906535),
("day", -2.515678308454754), ("year", -3.2088254890146994),
("integer (0..10)minute (grain)", -2.649209701079277),
("hour", -2.3978952727983707),
("integer (0..10)week (grain)", -2.9856819377004897),
("month", -2.803360380906535), ("minute", -2.649209701079277)],
n = 42},
koData =
ClassData{prior = -infinity, unseen = -2.772588722239781,
likelihoods = HashMap.fromList [], n = 0}}),
("\19975\22307\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\21476\23572\37030\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("number of five minutes",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("integer (0..10)", 0.0)],
n = 2}}),
("\20799\31461\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("Tuesday",
Classifier{okData =
ClassData{prior = -3.922071315328127e-2,
unseen = -3.295836866004329,
likelihoods = HashMap.fromList [("", 0.0)], n = 25},
koData =
ClassData{prior = -3.258096538021482, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("\26149\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("number.number minutes",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -2.772588722239781,
likelihoods =
HashMap.fromList
[("integer (0..10)integer with consecutive unit modifiersminute (grain)",
-1.0986122886681098),
("integer (0..10)compose by multiplicationminute (grain)",
-1.6094379124341003),
("minute", -0.7621400520468967)],
n = 6}}),
("\32822\31267\21463\38590\26085",
Classifier{okData =
ClassData{prior = -1.0296194171811581,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -0.4418327522790392,
unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9}}),
("<named-month> <day-of-month>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.762173934797756,
likelihoods =
HashMap.fromList
[("Marchinteger (0..10)", -2.5563656137701454),
("Marchinteger (numeric)", -3.144152278672264),
("Aprilinteger (numeric)", -3.654977902438255),
("Februaryinteger (0..10)", -2.6741486494265287),
("Februarynumber suffix: \21313|\25342", -2.6741486494265287),
("month", -0.7462570058738938),
("Februaryinteger (numeric)", -2.5563656137701454),
("Februaryinteger with consecutive unit modifiers",
-1.8091512119399242)],
n = 54},
koData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0}}),
("\21171\21160\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22797\27963\33410\26143\26399\19968",
Classifier{okData =
ClassData{prior = -0.6931471805599453,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -0.6931471805599453,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("number suffix: \19975|\33836",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3}}),
("\22823\25995\39318\26085",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("half",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5}}),
("two days after tomorrow",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("integer (0..10)",
Classifier{okData =
ClassData{prior = -0.5957987257888164, unseen = -5.407171771460119,
likelihoods = HashMap.fromList [("", 0.0)], n = 221},
koData =
ClassData{prior = -0.8010045764163588, unseen = -5.204006687076795,
likelihoods = HashMap.fromList [("", 0.0)], n = 180}}),
("last n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.605170185988091,
likelihoods =
HashMap.fromList
[("week", -2.9856819377004897),
("integer (0..10)month (grain)", -3.4965075614664802),
("integer (0..10)hour (grain)", -2.3978952727983707),
("second", -2.649209701079277),
("integer (0..10)day (grain)", -2.9856819377004897),
("integer (0..10)year (grain)", -3.4965075614664802),
("<number>\20010/\20491month (grain)", -2.3978952727983707),
("integer (0..10)second (grain)", -2.649209701079277),
("day", -2.9856819377004897), ("year", -3.4965075614664802),
("integer (0..10)minute (grain)", -2.3978952727983707),
("hour", -2.3978952727983707),
("integer (0..10)week (grain)", -2.9856819377004897),
("month", -2.1972245773362196),
("minute", -2.3978952727983707)],
n = 42},
koData =
ClassData{prior = -infinity, unseen = -2.772588722239781,
likelihoods = HashMap.fromList [], n = 0}}),
("last <duration>",
Classifier{okData =
ClassData{prior = -infinity, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.912023005428146,
likelihoods =
HashMap.fromList
[("week", -2.2823823856765264), ("second", -2.505525936990736),
("day", -2.793208009442517),
("<integer> <unit-of-duration>", -0.8007778447523107),
("hour", -2.2823823856765264), ("month", -2.2823823856765264),
("minute", -2.2823823856765264)],
n = 21}}),
("ordinal (digits)",
Classifier{okData =
ClassData{prior = -1.252762968495368, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList [("<number>\20010/\20491", -0.1823215567939546)],
n = 4},
koData =
ClassData{prior = -0.3364722366212129,
unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList [("integer (0..10)", -8.701137698962981e-2)],
n = 10}}),
("n <cycle> last",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.02535169073515,
likelihoods =
HashMap.fromList
[("week", -2.3978952727983707),
("integer (0..10)hour (grain)", -2.3978952727983707),
("<number>\20010/\20491week (grain)", -2.908720896564361),
("second", -2.908720896564361),
("integer (0..10)day (grain)", -2.3978952727983707),
("integer (0..10)year (grain)", -2.908720896564361),
("<number>\20010/\20491month (grain)", -2.908720896564361),
("integer (0..10)second (grain)", -2.908720896564361),
("day", -2.3978952727983707), ("year", -2.908720896564361),
("integer (0..10)minute (grain)", -2.908720896564361),
("hour", -2.3978952727983707),
("integer (0..10)week (grain)", -2.908720896564361),
("month", -2.908720896564361), ("minute", -2.908720896564361)],
n = 20},
koData =
ClassData{prior = -infinity, unseen = -2.772588722239781,
likelihoods = HashMap.fromList [], n = 0}}),
("\24527\24724\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("morning",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.890371757896165,
likelihoods = HashMap.fromList [("", 0.0)], n = 16},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("week-end",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("number suffix: \21313|\25342",
Classifier{okData =
ClassData{prior = -0.1590646946296874,
unseen = -3.4339872044851463,
likelihoods = HashMap.fromList [("", 0.0)], n = 29},
koData =
ClassData{prior = -1.916922612182061, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5}}),
("\22320\29699\19968\23567\26102",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("day (grain)",
Classifier{okData =
ClassData{prior = -0.38299225225610584,
unseen = -2.833213344056216,
likelihoods = HashMap.fromList [("", 0.0)], n = 15},
koData =
ClassData{prior = -1.1451323043030026,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7}}),
("\22307\32426\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\22797\27963\33410",
Classifier{okData =
ClassData{prior = -1.0986122886681098,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -0.40546510810816444,
unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6}}),
("<number>\20010/\20491",
Classifier{okData =
ClassData{prior = -0.2006706954621511,
unseen = -3.4011973816621555,
likelihoods =
HashMap.fromList [("integer (0..10)", -3.509131981127006e-2)],
n = 27},
koData =
ClassData{prior = -1.7047480922384253,
unseen = -2.1972245773362196,
likelihoods =
HashMap.fromList
[("one point 2", -0.9808292530117262),
("integer (0..10)", -0.4700036292457356)],
n = 6}}),
("compose by multiplication",
Classifier{okData =
ClassData{prior = -0.3364722366212129,
unseen = -2.0794415416798357,
likelihoods =
HashMap.fromList
[("integer (0..10)number suffix: \21313|\25342",
-0.15415067982725836)],
n = 5},
koData =
ClassData{prior = -1.252762968495368, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("one point 2number suffix: \21313|\25342",
-0.2876820724517809)],
n = 2}}),
("\24773\20154\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\20116\26092\33410",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\31070\22307\26143\26399\22235",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\25995\26376",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\27861\20196\20043\22812",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("this <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.07753744390572,
likelihoods =
HashMap.fromList
[("Wednesday", -1.9810014688665833),
("Monday", -1.9810014688665833), ("day", -0.8415671856782186),
("hour", -2.9618307218783095), ("Tuesday", -1.6625477377480489),
("week-end", -2.9618307218783095)],
n = 26},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}})]
|
facebookincubator/duckling
|
Duckling/Ranking/Classifiers/ZH_TW.hs
|
bsd-3-clause
| 93,989 | 0 | 15 | 43,638 | 18,872 | 11,718 | 7,154 | 1,561 | 1 |
-- | Effects
module Csound.Air.Fx(
-- * Reverbs
reverbsc1, rever1, rever2, reverTime,
smallRoom, smallHall, largeHall, magicCave,
smallRoom2, smallHall2, largeHall2, magicCave2,
-- * Delays
MaxDelayTime, DelayTime, Feedback, Balance,
echo, fdelay, fvdelay, fvdelays, funDelays, tabDelay,
PingPongSpec(..), pingPong, pingPong', csdPingPong,
-- * Distortion
distortion,
-- * Chorus
DepthSig, RateSig, WidthSig, ToneSig,
chorus,
-- * Flanger
flange,
-- * Phase
phase1, harmPhase, powerPhase,
-- * Effects with unit parameters
fxDistort, fxDistort2, stChorus2, fxPhaser, fxPhaser2,
fxFlanger, fxFlanger2, analogDelay, analogDelay2, fxEcho, fxEcho2,
fxFilter, fxFilter2,
fxWhite, fxWhite2, fxPink, fxPink2, equalizer, equalizer2, eq4, eq7,
fxGain,
-- * Misc
trackerSplice
) where
import Data.Boolean
import Data.Default
import Csound.Typed
import Csound.Tab(sines4, startEnds, setSize, elins, newTab, tabSizeSecondsPower2, tablewa, sec2rel)
import Csound.Typed.Opcode
import Csound.SigSpace
import Csound.Air.Wave(Lfo, unipolar, oscBy, utri, white, pink)
import Csound.Air.Filter
-- | Mono version of the cool reverberation opcode reverbsc.
--
-- > reverbsc1 asig feedbackLevel cutOffFreq
reverbsc1 :: Sig -> Feedback -> ToneSig -> Sig
reverbsc1 x k co = 0.5 * (a + b)
where (a, b) = ar2 $ reverbsc x x k co
---------------------------------------------------------------------------
-- Reverbs
-- | Reverb with given time.
reverTime :: DelayTime -> Sig -> Sig
reverTime dt a = nreverb a dt 0.3
-- | Mono reverb (based on reverbsc)
--
-- > rever1 feedback asig
rever1 :: Feedback -> Sig -> (Sig, Sig)
rever1 fbk a = reverbsc a a fbk 12000
-- | Mono reverb (based on reverbsc)
--
-- > rever2 feedback (asigLeft, asigRight)
rever2 :: Feedback -> Sig2 -> Sig2
rever2 fbk (a1, a2) = (a1 + wa1, a2 + wa2)
where (wa1, wa2) = reverbsc a1 a2 fbk 12000
-- | Mono reverb for small room.
smallRoom :: Sig -> (Sig, Sig)
smallRoom = rever1 0.6
-- | Mono reverb for small hall.
smallHall :: Sig -> (Sig, Sig)
smallHall = rever1 0.8
-- | Mono reverb for large hall.
largeHall :: Sig -> (Sig, Sig)
largeHall = rever1 0.9
-- | The magic cave reverb (mono).
magicCave :: Sig -> (Sig, Sig)
magicCave = rever1 0.99
-- | Stereo reverb for small room.
smallRoom2 :: Sig2 -> Sig2
smallRoom2 = rever2 0.6
-- | Stereo reverb for small hall.
smallHall2 :: Sig2 -> Sig2
smallHall2 = rever2 0.8
-- | Stereo reverb for large hall.
largeHall2 :: Sig2 -> Sig2
largeHall2 = rever2 0.9
-- | The magic cave reverb (stereo).
magicCave2 :: Sig2 -> Sig2
magicCave2 = rever2 0.99
---------------------------------------------------------------------------------
-- Delays
-- | The maximum delay time.
type MaxDelayTime = D
-- | The delaya time
type DelayTime = Sig
-- | Feedback for delay
type Feedback = Sig
-- | Dry/Wet mix value (ranges from 0 to 1). The 0 is all dry. The 1 is all wet.
type Balance = Sig
-- | The simplest delay with feedback. Arguments are: delay length and decay ratio.
--
-- > echo delayLength ratio
echo :: MaxDelayTime -> Feedback -> Sig -> SE Sig
echo len fb = fdelay len fb 1
-- | Delay with feedback.
--
-- > fdelay delayLength decayRatio balance
fdelay :: MaxDelayTime -> Feedback -> Balance -> Sig -> SE Sig
fdelay len = fvdelay len (sig len)
-- | Delay with feedback.
--
-- > fdelay maxDelayLength delayLength feedback balance
fvdelay :: MaxDelayTime -> DelayTime -> Feedback -> Balance -> Sig -> SE Sig
fvdelay len dt fb mx a = do
_ <- delayr len
aDel <- deltap3 dt
delayw $ a + fb * aDel
return $ a + (aDel * mx)
-- | Multitap delay. Arguments are: max delay length, list of pairs @(delayLength, decayRatio)@,
-- balance of mixed signal with processed signal.
--
-- > fdelay maxDelayLength delays balance asig
fvdelays :: MaxDelayTime -> [(DelayTime, Feedback)] -> Balance -> Sig -> SE Sig
fvdelays len dtArgs mx a = funDelays len (zip dts fs) mx a
where
(dts, fbks) = unzip dtArgs
fs = map (*) fbks
-- | Generic multitap delay. It's just like @fvdelays@ but instead of constant feedbackLevel
-- it expects a function for processing a delayed signal on the tap.
--
-- > fdelay maxDelayLength delays balance asig
funDelays :: MaxDelayTime -> [(DelayTime, Sig -> Sig)] -> Balance -> Sig -> SE Sig
funDelays len dtArgs mx a = do
_ <- delayr len
aDels <- mapM deltap3 dts
delayw $ a + sum (zipWith ($) fs aDels)
return $ a + mx * sum aDels
where (dts, fs) = unzip dtArgs
-- | Delay for functions that use some table (as a buffer). As granular synth or mincer.
--
-- > tabDelay fn maxDelayTime delayTime feedback balance asig
tabDelay :: (Tab -> Sig -> SE Sig) -> MaxDelayTime -> DelayTime -> Feedback -> Balance -> Sig -> SE Sig
tabDelay go maxLength delTim kfeed kbalance asig = do
buf <- newTab tabLen
ptrRef <- newRef (0 :: Sig)
aresRef <- newRef (0 :: Sig)
ptr <- readRef ptrRef
when1 (ptr >=* sig tabLen) $ do
writeRef ptrRef 0
ptr <- readRef ptrRef
let kphs = (ptr / sig tabLen) - (delTim/(sig $ tabLen / getSampleRate))
awet <-go buf (wrap kphs 0 1)
writeRef aresRef $ asig + kfeed * awet
ares <- readRef aresRef
writeRef ptrRef =<< tablewa buf ares 0
return $ (1 - kbalance) * asig + kbalance * awet
where
tabLen = tabSizeSecondsPower2 maxLength
-- | Aux parameters for ping pong delay.
-- They are maximum delay time, low pass filter center frequency and Pan width.
-- The defaults are @(5 sec, 3500, 0.3)@.
data PingPongSpec = PingPongSpec {
pingPongMaxTime :: MaxDelayTime,
pingPongDamp :: Sig,
pingPongWidth :: Sig
}
instance Default PingPongSpec where
def = PingPongSpec {
pingPongMaxTime = 5,
pingPongDamp = 3500,
pingPongWidth = 0.3
}
-- | Ping-pong delay.
--
-- > pingPong delayTime feedback mixLevel
pingPong :: DelayTime -> Feedback -> Balance -> Sig2 -> SE Sig2
pingPong delTime feedback mixLevel (ainL, ainR) = pingPong' def delTime feedback mixLevel (ainL, ainR)
-- | Ping-pong delay with miscellaneous arguments.
--
-- > pingPong' spec delayTime feedback mixLevel
pingPong' :: PingPongSpec -> DelayTime -> Feedback -> Balance -> Sig2 -> SE Sig2
pingPong' (PingPongSpec maxTime damp width) delTime feedback mixLevel (ainL, ainR) =
csdPingPong maxTime delTime damp feedback width mixLevel (ainL, ainR)
-- | Ping-pong delay defined in csound style. All arguments are present (nothing is hidden).
--
-- > csdPingPong maxTime delTime damp feedback width mixLevel (ainL, ainR)
csdPingPong :: MaxDelayTime -> DelayTime -> Sig -> Feedback -> Sig -> Balance -> Sig2 -> SE Sig2
csdPingPong maxTime delTime damp feedback width mixLevel (ainL, ainR) = do
afirst <- offsetDelay ainL
atapL <- channelDelay afirst
atapR <- channelDelay ainR
return $ mixControl $ widthControl afirst (atapL, atapR)
where
offsetDelay ain = do
abuf <- delayr maxTime
afirst <- deltap3 delTime
let afirst1 = tone afirst damp
delayw ain
return afirst1
channelDelay ain = do
abuf <- delayr (2 * maxTime)
atap <- deltap3 (2 * delTime)
let atap1 = tone atap damp
delayw (ain + atap1 * feedback)
return atap1
widthControl afirst (atapL, atapR) = (afirst + atapL + (1 - width) * atapR, atapR + (1 - width) * atapL)
mixControl (atapL ,atapR) = (cfd mixLevel ainL atapL, cfd mixLevel ainR atapR)
type DepthSig = Sig
type RateSig = Sig
type WidthSig = Sig
type ToneSig = Sig
-- Distortion
-- | Distortion.
--
-- > distort distLevel asig
distortion :: Sig -> Sig -> Sig
distortion pre asig = distort1 asig pre 0.5 0 0 `withD` 1
-- Chorus
-- | Chorus.
--
-- > chorus depth rate balance asig
chorus :: DepthSig -> RateSig -> Balance -> Sig -> SE Sig
chorus depth rate mx asig = do
_ <- delayr 1.2
adelSig <- deltap3 (0.03 * depth * oscBy fn (3 * rate) + 0.01)
delayw asig
return $ ntrpol asig adelSig mx
where fn = sines4 [(0.5, 1, 180, 1)] -- U-shape parabola
-- Flanger
-- | Flanger. Lfo depth ranges in 0 to 1.
--
-- flanger lfo feedback balance asig
flange :: Lfo -> Feedback -> Balance -> Sig -> Sig
flange alfo fbk mx asig = ntrpol asig (flanger asig ulfo fbk) mx
where ulfo = 0.0001 + 0.02 * unipolar alfo
-- Phaser
-- | First order phaser.
phase1 :: Sig -> Lfo -> Feedback -> Balance -> Sig -> Sig
phase1 ord alfo fbk mx asig = ntrpol asig (phaser1 asig (20 + unipolar alfo) ord fbk) mx
-- | Second order phaser. Sweeping gaps in the timbre are placed harmonicaly
harmPhase :: Sig -> Lfo -> Sig -> Sig -> Feedback -> Balance -> Sig -> Sig
harmPhase ord alfo q sep fbk mx asig = ntrpol asig (phaser2 asig (20 + unipolar alfo) q ord 1 sep fbk) mx
-- | Second order phaser. Sweeping gaps in the timbre are placed by powers of the base frequency.
powerPhase :: Sig -> Lfo -> Sig -> Sig -> Feedback -> Balance -> Sig -> Sig
powerPhase ord alfo q sep fbk mx asig = ntrpol asig (phaser2 asig (20 + unipolar alfo) q ord 2 sep fbk) mx
-----------------------------------------------------------------
-- new effects
expScale :: Sig -> (Sig, Sig) -> Sig -> Sig
expScale steep (min, max) a = scale (expcurve a steep) max min
logScale :: Sig -> (Sig, Sig) -> Sig -> Sig
logScale steep (min, max) a = scale (logcurve a steep) max min
dryWetMix :: Sig -> (Sig, Sig)
dryWetMix kmix = (kDry, kWet)
where
iWet = setSize 1024 $ elins [0, 1, 1]
iDry = setSize 1024 $ elins [1, 1, 0]
kWet = kr $ table kmix iWet `withD` 1
kDry = kr $ table kmix iDry `withD` 1
fxWet :: (Num a, SigSpace a) => Sig -> a -> a -> a
fxWet mix ain aout = mul dry ain + mul wet aout
where (dry, wet) = dryWetMix mix
-- Distortion
-- | Distortion
--
-- > fxDistort level drive tone sigIn
fxDistort :: Feedback -> Sig -> ToneSig -> Sig -> Sig
fxDistort klevel kdrive ktone ain = aout * (scale klevel 0.8 0) * kGainComp1
where
aout = blp kLPF $ distort1 ain kpregain kpostgain 0 0
drive = expScale 8 (0.01, 0.4) kdrive
kGainComp1 = logScale 700 (5,1) ktone
kpregain = 100 * drive
kpostgain = 0.5 * ((1 - drive) * 0.4 + 0.6)
kLPF = logScale 700 (200, 12000) ktone
-- | Stereo distortion.
fxDistort2 :: Feedback -> Sig -> ToneSig -> Sig2 -> Sig2
fxDistort2 klevel kdrive ktone (al, ar) = (fx al, fx ar)
where fx = fxDistort klevel kdrive ktone
-- Stereo chorus
-- | Stereo chorus.
--
-- > stChorus2 mix rate depth width sigIn
stChorus2 :: Balance -> RateSig -> DepthSig -> WidthSig -> Sig2 -> Sig2
stChorus2 kmix krate' kdepth kwidth (al, ar) = fxWet kmix (al, ar) (aoutL, aoutR)
where
krate = expScale 20 (0.001, 7) krate'
ilfoshape = setSize 131072 $ sines4 [(1, 0.5, 0, 0.5)]
kporttime = linseg [0, 0.001, 0.02]
kChoDepth = interp $ portk (kdepth*0.01) kporttime
amodL = osciliktp krate ilfoshape 0
amodR = osciliktp krate ilfoshape (kwidth*0.5)
vdel mod x = vdelay x (mod * kChoDepth * 1000) (1.2 * 1000)
aChoL = vdel amodL al
aChoR = vdel amodR ar
aoutL = 0.6 * (aChoL + al)
aoutR = 0.6 * (aChoR + ar)
-- Phaser
-- | Phaser
--
-- > fxPhaser mix rate depth freq feedback sigIn
fxPhaser ::Balance -> Feedback -> RateSig -> DepthSig -> Sig -> Sig -> Sig
fxPhaser kmix fb krate' kdepth kfreq ain = fxWet kmix ain aout
where
krate = expScale 10 (0.01, 14) krate'
klfo = kdepth * utri krate
aout = phaser1 ain (cpsoct $ klfo + kfreq) 8 fb
-- | Stereo phaser.
fxPhaser2 :: Balance -> Feedback -> RateSig -> DepthSig -> Sig -> Sig2 -> Sig2
fxPhaser2 kmix fb krate kdepth kfreq (al, ar) = (fx al, fx ar)
where fx = fxPhaser kmix fb krate kdepth kfreq
-- Flanger
-- | Flanger
--
-- > fxFlanger mix feedback rate depth delay sigIn
fxFlanger :: Balance -> Feedback -> RateSig -> DepthSig -> DelayTime -> Sig -> Sig
fxFlanger kmix kfback krate' kdepth kdelay' ain = fxWet kmix ain aout
where
krate = expScale 50 (0.001, 14) krate'
kdelay = expScale 200 (0.0001, 0.1) kdelay'
ilfoshape = setSize 131072 $ sines4 [(0.5, 1, 180, 1)]
kporttime = linseg [0, 0.001, 0.1]
adlt = interp $ portk kdelay kporttime
kdep = portk (kdepth*0.01) kporttime
amod = oscili kdep krate ilfoshape
adelsig = flanger ain (adlt + amod) kfback `withD` 1.2
aout = mean [ain, adelsig]
-- | Stereo flanger
fxFlanger2 :: Balance -> Feedback -> RateSig -> DepthSig -> DelayTime -> Sig2 -> Sig2
fxFlanger2 kmix kfback krate kdepth kdelay (al ,ar) = (fx al, fx ar)
where fx = fxFlanger kmix kfback krate kdepth kdelay
-- Analog delay
-- | Analog delay.
--
-- > analogDelay mix feedback time tone sigIn
analogDelay :: Balance -> Feedback -> DelayTime -> ToneSig -> Sig -> SE Sig
analogDelay kmix kfback ktime ktone' ain = do
aBuffer <- delayr 5
atap <- deltap3 aTime
let atap1 = tone (clip atap 0 1) kTone
delayw $ ain + atap1*kfback
return $ ain*kDry + atap1 * kWet
where
ktone = expScale 4 (100, 12000) ktone'
(kDry, kWet) = dryWetMix kmix
kporttime = linseg [0,0.001,0.1]
kTime = portk ktime (kporttime*3)
kTone = portk ktone kporttime
aTime = interp kTime
-- | Stereo analog delay.
analogDelay2 :: Balance -> Feedback -> DelayTime -> ToneSig -> Sig2 -> SE Sig2
analogDelay2 kmix kfback ktime ktone = bindSig fx
where fx = analogDelay kmix kfback ktime ktone
-- Filter
-- | Filter effect (a pair of butterworth low and high pass filters).
--
-- > fxFilter lowPassfFreq highPassFreq gain
fxFilter :: Sig -> Sig -> Sig -> Sig -> Sig
fxFilter kLPF' kHPF' kgain' ain = mul kgain $ app (blp kLPF) $ app (bhp kHPF) $ ain
where
app f = f . f
kLPF = scaleFreq kLPF'
kHPF = scaleFreq kHPF'
kgain = scale kgain' 20 0
scaleFreq x = expScale 4 (20, 20000) x
-- | Stereo filter effect (a pair of butterworth low and high pass filters).
fxFilter2 :: Sig -> Sig -> Sig -> Sig2 -> Sig2
fxFilter2 kLPF kHPF kgain (al, ar) = (fx al, fx ar)
where fx = fxFilter kLPF kHPF kgain
-- Equalizer
-- | Equalizer
--
-- > equalizer gainsAndFrequencies gain sigIn
equalizer :: [(Sig, Sig)] -> Sig -> Sig -> Sig
equalizer fs gain ain0 = case fs of
[] -> ain
x:[] -> g 0 x ain
x:y:[] -> mean [g 1 x ain, g 2 y ain]
x:xs -> mean $ (g 1 x ain : ) $ (fmap (\y -> g 0 y ain) (init xs)) ++ [g 2 (last xs) ain]
where
iQ = 1
iEQcurve = skipNorm $ setSize 4096 $ startEnds [1/64,4096,7.9,64]
iGainCurve = skipNorm $ setSize 4096 $ startEnds [0.5,4096,3,4]
g ty (gain, freq) asig = pareq asig freq (table gain iEQcurve `withD` 1) iQ `withD` ty
kgain = table gain iGainCurve `withD` 1
ain = kgain * ain0
-- | Stereo equalizer.
equalizer2 :: [(Sig, Sig)] -> Sig -> Sig2 -> Sig2
equalizer2 fs gain (al, ar) = (fx al, fx ar)
where fx = equalizer fs gain
-- | Equalizer with frequencies: 100, 200, 400, 800, 1600, 3200, 6400
eq7 :: [Sig] -> Sig -> Sig2 -> Sig2
eq7 gs = equalizer2 (zip gs $ fmap (100 * ) [1, 2, 4, 8, 16, 32, 64])
-- | Equalizer with frequencies: 100, 400, 1600, 6400
eq4 :: [Sig] -> Sig -> Sig2 -> Sig2
eq4 gs = equalizer2 (zip gs $ fmap (100 * ) [1, 4, 16, 64])
-- | Gain
--
-- > fxGain gain sigIn
fxGain :: Sig -> Sig2 -> Sig2
fxGain = mul
-- Noise
-- | Adds filtered white noize to the signal
--
-- > fxWhite lfoFreq depth sigIn
fxWhite :: Sig -> Sig -> Sig -> SE Sig
fxWhite freq depth ain = do
noise <- white
return $ ain + 0.5 * depth * blp cps noise
where cps = expScale 4 (20, 20000) freq
-- | Adds filtered white noize to the stereo signal
fxWhite2 ::Sig -> Sig -> Sig2 -> SE Sig2
fxWhite2 freq depth = bindSig fx
where fx = fxWhite freq depth
-- | Adds filtered pink noize to the signal
--
-- > fxWhite lfoFreq depth sigIn
fxPink :: Sig -> Sig -> Sig -> SE Sig
fxPink freq depth ain = do
noise <- pink
return $ ain + 0.5 * depth * blp cps noise
where cps = expScale 4 (20, 20000) freq
-- | Adds filtered pink noize to the stereo signal
fxPink2 ::Sig -> Sig -> Sig2 -> SE Sig2
fxPink2 freq depth = bindSig fx
where fx = fxPink freq depth
-- Echo
-- | Simplified delay
--
-- > fxEcho maxDelayLength delTime feedback sigIn
fxEcho :: D -> Sig -> Sig -> Sig -> SE Sig
fxEcho maxLen ktime fback = fvdelay (5 * maxLen) (sig maxLen * 0.95 * kTime) fback 1
where
kporttime = linseg [0,0.001,0.1]
kTime = portk ktime (kporttime*3)
-- | Simplified stereo delay.
fxEcho2 :: D -> Sig -> Sig -> Sig2 -> SE Sig2
fxEcho2 maxLen ktime fback = bindSig fx
where fx = fxEcho maxLen ktime fback
-- | Instrument plays an input signal in different modes.
-- The segments of signal can be played back and forth.
--
-- > trackerSplice maxLength segLength mode
--
-- * @maxLength@ -- the maximum length of the played segment (in seconds)
--
-- * @segLength@ -- the segment length in seconds
--
-- * @mode@ -- mode of the playing. If it's 1 - only a part of the sample is plyaed and
-- it's played forward. The portion of the signal starts from the current playback point.
-- It lasts for segLength. If it's 2 - the segment is played in reverse.
-- Other values produce the normal input signal.
--
-- Original author: Rory Walsh
--
-- Example:
--
-- > main = dac $ do
-- > let ev ch1 ch2 dt = fmap (\x -> (x, dt)) $ mconcat [
-- > fmap (const 1.5) $ charOn ch1
-- > , fmap (const 2.5) $ charOn ch2
-- > , fmap (const 0) $ charOff ch1 <> charOff ch2]
-- >
-- > (k, dt) <- stepper (0, 0.1) $ ev 'q' 'w' 0.1 <> ev 'a' 's' 0.2 <> ev 'z' 'x' 0.4
-- > mul 1.3 $ trackerSplice 0.8 dt (int' k) $ fst $ loopWav 1 "drumLoop.wav"
trackerSplice :: D -> Sig -> Sig -> Sig -> SE Sig
trackerSplice maxLength segLengthSeconds kmode asig = do
setksmps 1
kindxRef <- newRef (0 :: Sig)
ksampRef <- newRef (1 :: D)
aoutRef <- newRef (0 :: Sig)
buf <- newTab (tabSizeSecondsPower2 maxLength)
let segLength = segLengthSeconds * sig getSampleRate
andx = phasor (sig $ getSampleRate / ftlen buf)
andx1 = delay andx 1
tabw asig (andx * sig (ftlen buf)) buf
ksamp <- readRef ksampRef
let apos = samphold (andx1 * sig (ftlen buf)) (sig ksamp)
whens [
(kmode >=* 1 &&* kmode `lessThan` 2, do
kindx <- readRef kindxRef
writeRef kindxRef $ ifB (kindx >* segLength) 0 (kindx + 1)
kindx <- readRef kindxRef
when1 (kindx + apos >* sig (ftlen buf)) $ do
writeRef kindxRef $ (-segLength)
kindx <- readRef kindxRef
writeRef aoutRef $ table (apos + kindx) buf `withDs` [0, 1]
writeRef ksampRef 0
), (kmode >=* 2 &&* kmode `lessThan` 3, do
kindx <- readRef kindxRef
writeRef kindxRef $ ifB ((kindx+apos) <=* 0) (sig (ftlen buf) - apos) (kindx-1)
kindx <- readRef kindxRef
writeRef aoutRef $ table (apos+kindx) buf `withDs` [0, 1]
writeRef ksampRef 0
)] (do
writeRef ksampRef 1
writeRef aoutRef asig)
aout <-readRef aoutRef
return aout
-- | Mean value.
mean :: Fractional a => [a] -> a
mean xs = sum xs / (fromIntegral $ length xs)
|
silky/csound-expression
|
src/Csound/Air/Fx.hs
|
bsd-3-clause
| 19,678 | 0 | 18 | 5,077 | 5,948 | 3,165 | 2,783 | 314 | 4 |
{-# LANGUAGE ScopedTypeVariables #-}
----------------------------------------------------------------------
-- |
-- Module : Network.HaskellNet.SMTP
-- Copyright : (c) Jun Mukai 2006
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-- SMTP client implementation
--
module Network.HaskellNet.SMTP
( -- * Types
Command(..)
, Response(..)
, SMTPConnection
-- * Establishing Connection
, connectSMTPPort
, connectSMTP
, connectStream
-- * Operation to a Connection
, sendCommand
, closeSMTP
-- * Other Useful Operations
, sendMail
, doSMTPPort
, doSMTP
, doSMTPStream
, sendMimeMail
)
where
import Network.HaskellNet.BSStream
import Data.ByteString (ByteString, append)
import qualified Data.ByteString.Char8 as BS
import Network.BSD (getHostName)
import Network
import Control.Exception
import Control.Monad (unless)
import Data.List (intersperse)
import Data.Char (chr, ord, isSpace, isDigit)
import Network.HaskellNet.Auth
import System.IO
import Network.Mail.Mime
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString as S
import Data.Text (Text)
import qualified Data.Text.Lazy as LT
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Prelude hiding (catch)
data (BSStream s) => SMTPConnection s = SMTPC !s ![ByteString]
data Command = HELO String
| EHLO String
| MAIL String
| RCPT String
| DATA ByteString
| EXPN String
| VRFY String
| HELP String
| AUTH AuthType UserName Password
| NOOP
| RSET
| QUIT
deriving (Show, Eq)
type ReplyCode = Int
data Response = Ok
| SystemStatus
| HelpMessage
| ServiceReady
| ServiceClosing
| UserNotLocal
| CannotVerify
| StartMailInput
| ServiceNotAvailable
| MailboxUnavailable
| ErrorInProcessing
| InsufficientSystemStorage
| SyntaxError
| ParameterError
| CommandNotImplemented
| BadSequence
| ParameterNotImplemented
| MailboxUnavailableError
| UserNotLocalError
| ExceededStorage
| MailboxNotAllowed
| TransactionFailed
deriving (Show, Eq)
codeToResponse :: Num a => a -> Response
codeToResponse 211 = SystemStatus
codeToResponse 214 = HelpMessage
codeToResponse 220 = ServiceReady
codeToResponse 221 = ServiceClosing
codeToResponse 250 = Ok
codeToResponse 251 = UserNotLocal
codeToResponse 252 = CannotVerify
codeToResponse 354 = StartMailInput
codeToResponse 421 = ServiceNotAvailable
codeToResponse 450 = MailboxUnavailable
codeToResponse 451 = ErrorInProcessing
codeToResponse 452 = InsufficientSystemStorage
codeToResponse 500 = SyntaxError
codeToResponse 501 = ParameterError
codeToResponse 502 = CommandNotImplemented
codeToResponse 503 = BadSequence
codeToResponse 504 = ParameterNotImplemented
codeToResponse 550 = MailboxUnavailableError
codeToResponse 551 = UserNotLocalError
codeToResponse 552 = ExceededStorage
codeToResponse 553 = MailboxNotAllowed
codeToResponse 554 = TransactionFailed
crlf = BS.pack "\r\n"
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
-- | connecting SMTP server with the specified name and port number.
connectSMTPPort :: String -- ^ name of the server
-> PortNumber -- ^ port number
-> IO (SMTPConnection Handle)
connectSMTPPort hostname port = connectTo hostname (PortNumber port) >>= connectStream
-- | connecting SMTP server with the specified name and port 25.
connectSMTP :: String -- ^ name of the server
-> IO (SMTPConnection Handle)
connectSMTP = flip connectSMTPPort 25
-- | create SMTPConnection from already connected Stream
connectStream :: BSStream s => s -> IO (SMTPConnection s)
connectStream st =
do (code, msg) <- parseResponse st
unless (code == 220) $
do bsClose st
fail "cannot connect to the server"
senderHost <- getHostName
(code, msg) <- sendCommand (SMTPC st []) (EHLO senderHost)
unless (code == 250) $
do (code, msg) <- sendCommand (SMTPC st []) (HELO senderHost)
unless (code == 250) $
do bsClose st
fail "cannot connect to the server"
return (SMTPC st (tail $ BS.lines msg))
parseResponse :: BSStream s => s -> IO (ReplyCode, ByteString)
parseResponse st =
do (code, bdy) <- readLines
return (read $ BS.unpack code, BS.unlines bdy)
where readLines =
do l <- bsGetLine st
let (c, bdy) = BS.span isDigit l
if not (BS.null bdy) && BS.head bdy == '-'
then do (c, ls) <- readLines
return (c, (BS.tail bdy:ls))
else return (c, [BS.tail bdy])
-- | send a method to a server
sendCommand :: BSStream s => SMTPConnection s -> Command -> IO (ReplyCode, ByteString)
sendCommand (SMTPC conn _) (DATA dat) =
do bsPutCrLf conn $ BS.pack "DATA"
(code, msg) <- parseResponse conn
unless (code == 354) $ fail "this server cannot accept any data."
mapM_ sendLine $ BS.lines dat ++ [BS.pack "."]
parseResponse conn
where sendLine l = bsPutCrLf conn l
sendCommand (SMTPC conn _) (AUTH LOGIN username password) =
do bsPutCrLf conn command
(code, msg) <- parseResponse conn
bsPutCrLf conn $ BS.pack userB64
(code, msg) <- parseResponse conn
bsPutCrLf conn $ BS.pack passB64
parseResponse conn
where command = BS.pack $ "AUTH LOGIN"
(userB64, passB64) = login username password
sendCommand (SMTPC conn _) (AUTH at username password) =
do bsPutCrLf conn command
(code, msg) <- parseResponse conn
unless (code == 334) $ fail "authentication failed."
bsPutCrLf conn $ BS.pack $ auth at (BS.unpack msg) username password
parseResponse conn
where command = BS.pack $ unwords ["AUTH", show at]
sendCommand (SMTPC conn _) meth =
do bsPutCrLf conn $ BS.pack command
parseResponse conn
where command = case meth of
(HELO param) -> "HELO " ++ param
(EHLO param) -> "EHLO " ++ param
(MAIL param) -> "MAIL FROM:<" ++ param ++ ">"
(RCPT param) -> "RCPT TO:<" ++ param ++ ">"
(EXPN param) -> "EXPN " ++ param
(VRFY param) -> "VRFY " ++ param
(HELP msg) -> if null msg
then "HELP\r\n"
else "HELP " ++ msg
NOOP -> "NOOP"
RSET -> "RSET"
QUIT -> "QUIT"
-- |
-- close the connection. This function send the QUIT method, so you
-- do not have to QUIT method explicitly.
closeSMTP :: BSStream s => SMTPConnection s -> IO ()
closeSMTP c@(SMTPC conn _) = do bsClose conn
{-
I must be being stupid here
I can't seem to be able to catch the exception arising from the connection already being closed
this would be the correct way to do it but instead we're being naughty above by just closes the
connection without first sending QUIT
closeSMTP c@(SMTPC conn _) = do sendCommand c QUIT
bsClose conn `catch` \(_ :: IOException) -> return ()
-}
-- |
-- sending a mail to a server. This is achieved by sendMessage. If
-- something is wrong, it raises an IOexception.
sendMail :: BSStream s =>
String -- ^ sender mail
-> [String] -- ^ receivers
-> ByteString -- ^ data
-> SMTPConnection s
-> IO ()
sendMail sender receivers dat conn =
catcher `handle` mainProc
where mainProc = do (250, _) <- sendCommand conn (MAIL sender)
vals <- mapM (sendCommand conn . RCPT) receivers
unless (all ((==250) . fst) vals) $ fail "sendMail error"
(250, _) <- sendCommand conn (DATA dat)
return ()
catcher e@(PatternMatchFail _) = throwIO e
-- catcher e@(PatternMatchFail _) = fail "sendMail error"
-- catcher e = throwIO e
-- |
-- doSMTPPort open a connection, and do an IO action with the
-- connection, and then close it.
doSMTPPort :: String -> PortNumber -> (SMTPConnection Handle -> IO a) -> IO a
doSMTPPort host port execution =
bracket (connectSMTPPort host port) closeSMTP execution
-- |
-- doSMTP is similar to doSMTPPort, except that it does not
-- require port number but connects to the server with port 25.
doSMTP :: String -> (SMTPConnection Handle -> IO a) -> IO a
doSMTP host execution = doSMTPPort host 25 execution
-- |
-- doSMTPStream is similar to doSMTPPort, except that its argument is
-- a Stream data instead of hostname and port number.
doSMTPStream :: BSStream s => s -> (SMTPConnection s -> IO a) -> IO a
doSMTPStream s execution = bracket (connectStream s) closeSMTP execution
--sendMimeMail :: BSStream s => String -> String -> String -> LT.Text -> LT.Text -> [(String, FilePath)] -> SMTPConnection s -> IO ()
--sendMimeMail to from subject plainBody htmlBody attachments con =
-- sendMimeMail (LT.pack to) (LT.pack from) (LT.pack subject) plainBody htmlBody (map (\x -> ((LT.pack . fst) x, (snd x))) attachments) con
sendMimeMail :: BSStream s => String -> String -> String -> LT.Text -> LT.Text -> [(T.Text, FilePath)] -> SMTPConnection s -> IO ()
--sendMimeMail :: BSStream s => T.Text -> T.Text -> T.Text -> LT.Text -> LT.Text -> [(T.Text, FilePath)] -> SMTPConnection s -> IO ()
sendMimeMail to from subject plainBody htmlBody attachments con = do
myMail <- simpleMail (T.pack to) (T.pack from) (T.pack subject) plainBody htmlBody attachments
renderedMail <- renderMail' myMail
sendMail from [to] (lazyToStrict renderedMail) con
closeSMTP con
-- haskellNet uses strict bytestrings
-- TODO: look at making haskellnet lazy
lazyToStrict = S.concat . B.toChunks
|
d3zd3z/HaskellNet-old
|
Network/HaskellNet/SMTP.hs
|
bsd-3-clause
| 10,485 | 0 | 17 | 3,058 | 2,407 | 1,255 | 1,152 | 206 | 11 |
module LiveJournal.Entity where
import LiveJournal.Error
import Control.Monad.Error
import Data.Int
import Data.DateTime
import Data.Map
import Data.Array
type Result m a = ErrorT LJError m a
type IOResult a = Result IO a
type Community = String
makeErrorStr :: String -> IOResult a
makeErrorStr = ErrorT . return . Left . SimpleError
makeError :: (Monad m) => LJError -> Result m a
makeError = ErrorT . return . Left
makeResult :: (Monad m) => a -> Result m a
makeResult = ErrorT . return . Right
data LJFriendKind = AFriend | AFriendOf deriving (Show)
data LJFriendType = Community | Syndicated | News | Shared | Identity | User deriving (Show, Enum, Bounded)
data LJFriendStatus = Deleted | Suspended | Purged | Active deriving (Show, Enum, Bounded)
data ResponseData = Mood { moodId, moodParent :: Int, moodName :: String } |
Group { groupName :: String, groupSortOrder :: Int, groupPublic :: Bool } |
Menu { menuId :: Int, menuItems :: Map Int ResponseData } |
MenuItem { menuItem, menuSub :: Int, menuUrl, menuText :: String } |
Friend {
friendKind :: LJFriendKind,
friendUsername, friendName, bgColor, fgColor :: String,
groupmask :: Int32,
friendType :: LJFriendType,
identityDisplay, identityType, identityValue :: Maybe String,
friendStatus :: LJFriendStatus,
birthday :: Maybe DateTime } |
Pickw { pickwUrl :: String, pickwKeyword :: [String] }
deriving (Show)
data SelectType = Day { year, month, day :: Int } |
Sync { lastSync :: String } |
LastN { howMany :: Int,
beforeDate :: Maybe String } |
One { itemId :: String }
data LJLineEndings = Unix | PC | Mac | Space | Dots deriving ( Show, Eq, Ord, Enum, Bounded, Ix )
lineEndingMapping = listArray ( minBound, maxBound ) ["unix", "pc", "mac", "space", "dots"] :: Array LJLineEndings String
data LJEventSecurity = Public | Private | UserMask { userMask :: Int } deriving ( Show )
data LJEventProperty = EventProperty { eventPropName, eventPropValue :: String } deriving ( Show )
data LJEvent = Event { eventId :: String,
eventTime :: DateTime,
eventText :: String,
eventSecurity :: LJEventSecurity,
eventSubject :: String,
eventPoster :: String,
eventANum :: String,
eventUrl :: String,
eventProperties :: [LJEventProperty]
} |
PropertyContainer { pItemId, pName, pValue :: String } deriving ( Show )
data LJMetaData = AdminContentFlag String |
AdultContent String |
CommentAlter Int |
CurrentCoordinates Double Double |
CurrentLocation String |
CurrentMood String |
CurrentMoodId (Maybe Int) |
CurrentMusic String |
HasScreenedComments Bool |
BackDatedPost Bool |
NoComments Bool |
NoEmailComments Bool |
Preformatted Bool |
CommentScreening Char |
PersonifiLang String |
PersonifiTags String |
PersonifiWordCount Int |
PictureKeyword String |
RevisionNum Int |
RevisionTime Int |
SMSMessageId String |
Visibility Char |
SyndicatedId String |
SyndicatedUrl String |
Tags [String] |
NonUTF8Text Bool |
UnsuspendRequestId Int |
ComposeInRTE Bool |
UserAgent String |
VerticalsList [String]
|
jdevelop/hslj
|
LiveJournal/Entity.hs
|
bsd-3-clause
| 4,139 | 0 | 9 | 1,649 | 889 | 542 | 347 | 82 | 1 |
module BowlingGame.Kata (score, roll, startGame, Game) where
type Game = [Int]
startGame :: Game
startGame = []
roll :: Int -> Game -> Game
roll pin game = pin : game
score :: Game -> Int
score = score' 1
where
score' :: Int -> Game -> Int
score' frameIndex game
| frameIndex == 11 = 0
| isStrike = 10 + strikeBonus + score' nextFrameIndex nextFrame
| isSpare = 10 + spareBonus + score' nextFrameIndex nextFrame
| otherwise = framePoints + score' nextFrameIndex nextFrame
where
isStrike :: Bool
isStrike = sum (take 1 game) == 10
strikeBonus :: Int
strikeBonus = sum (take 2 $ drop 1 game)
isSpare :: Bool
isSpare = sum (take 2 game) == 10
spareBonus :: Int
spareBonus = sum $ take 1 $ drop 2 game
framePoints :: Int
framePoints =
case game of (rollOne:rollTwo:_) -> rollOne + rollTwo
_ -> 0
nextFrameIndex = frameIndex + 1
nextFrame :: Game
nextFrame =
case game of (10:rest) -> rest
(_:_:rest) -> rest
_ -> []
|
Alex-Diez/haskell-tdd-kata
|
BowlingGameKata/BowlingGameDay06/src/BowlingGame/Kata.hs
|
bsd-3-clause
| 1,555 | 0 | 14 | 814 | 390 | 203 | 187 | 32 | 4 |
{-# LANGUAGE PatternGuards #-}
{-# OPTIONS_GHC -fomit-interface-pragmas #-}
module Distribution.Franchise.AutoHeader ( autoHeader ) where
import Distribution.Franchise.SplitFile
import Distribution.Franchise.ConfigureState
import Distribution.Franchise.GhcState ( getDefinitions )
import Distribution.Franchise.ListUtils ( stripPrefix )
-- |This is the split function for @splitFile@. We need to provide
-- the output filename explicitly since it's not in the file, and we
-- also need to provide the list of all definitions since it's a pure
-- function.
ahSplit :: FilePath -> [(String,String)] -> String -> [(FilePath,String)]
ahSplit outfile subs content = [(outfile,unlines $ map repl $ lines content)]
where repl s = maybe s id $
do ss <- stripPrefix "#undef " s
v <- lookup ss subs
Just $ "#define " ++ ss ++ if null v
then ""
else " " ++ v
autoHeader :: FilePath -> C ()
autoHeader target = do defs <- getDefinitions
splitFile (target++".in") (ahSplit target defs)
return ()
|
droundy/franchise
|
Distribution/Franchise/AutoHeader.hs
|
bsd-3-clause
| 1,199 | 0 | 12 | 363 | 255 | 137 | 118 | 19 | 2 |
-- Ninety-Nine Haskell Problems
-- link: http://www.haskell.org/haskellwiki/99_questions/
module Problems where
-- 1 Find the last element of a list
myLast :: [a] -> a
myLast (x:[]) = x
myLast (_:xs) = myLast xs
-- 2 Find the last but one element of a list
myButLast :: [a] -> a
myButLast (x:_:[]) = x
myButLast (_:xs) = myButLast xs
-- 3 Find the K'th element of a list. The first element in the list is number 1.
myElementAt :: [a] -> Int -> a
myElementAt (x:_) 1 = x
myElementAt (_:xs) i = myElementAt xs (i-1)
-- 4 Find the number of elements of a list
myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = (myLength xs) + 1
-- 5 Reverse a list
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = (myReverse xs) ++ [x]
-- 6 Find out whether a list is a palindrome
myIsPalindrome :: (Eq a) => [a] -> Bool
myIsPalindrome [] = True
myIsPalindrome [_] = True
myIsPalindrome (x:xs) = (myIsPalindrome (init xs)) && (x == (last xs))
-- 7 Flatten a nested list structure
data NestedList a = Elem a | List [NestedList a]
myFlatten :: NestedList a -> [a]
myFlatten (Elem a) = [a]
myFlatten (List []) = []
myFlatten (List (x:xs)) = (myFlatten x) ++ (myFlatten (List xs))
-- 8 Eliminate consecutive duplicates of list elements
myCompress :: (Eq a) => [a] -> [a]
myCompress [] = []
myCompress [x] = [x]
myCompress (x:ys@(y:zs))
| x == y = myCompress ys
| otherwise = x : myCompress ys
-- 9 Pack consecutive duplicates of list elements into sublists
myPack :: (Eq a) => [a] -> [[a]]
myPack [] = []
myPack [x] = [[x]]
myPack xs = packer [] xs where
packer zs [] = zs : myPack []
packer [] (x:xs) = packer [x] xs
packer zs@(z:zzs) xs@(x:xxs)
| z == x = packer (x:zs) xxs
| otherwise = zs : myPack xs
-- 10 Run-length encoding of a list
myRLEncode :: (Eq a) => [a] -> [(Int,a)]
myRLEncode [] = []
myRLEncode xs = zip (map length pack) (map head pack) where
pack = (myPack xs)
-- 11 Modified run-length encoding
data RLEList a = Single a | Multiple Int a deriving (Show, Eq)
myRLEncodeMod :: (Eq a) => [a] -> [RLEList a]
myRLEncodeMod = (map encoder) . myRLEncode where
encoder (1, a) = Single a
encoder (n, a) = Multiple n a
-- 12 Decode a run-length encoded list
myDecodeRLEMod :: (Eq a) => [RLEList a] -> [a]
myDecodeRLEMod [] = []
myDecodeRLEMod (x:xs) = (decoder x) ++ myDecodeRLEMod xs where
decoder (Single a) = [a]
decoder (Multiple n a)
| n > 1 = [a] ++ decoder (Multiple (n-1) a)
| otherwise = decoder (Single a)
-- 13 Run-length encoding of a list (direct solution)
myRLEncodeDirect :: (Eq a) => [a] -> [RLEList a]
myRLEncodeDirect [] = []
myRLEncodeDirect (x:xs) = helpRLE 1 x xs where
helpRLE n a [] = [makeRLE n a]
helpRLE n a (x:xs)
| a == x = helpRLE (n+1) a xs
| otherwise = (makeRLE n a) : (helpRLE 1 x xs)
makeRLE 1 a = Single a
makeRLE n a = Multiple n a
-- 14 Duplicate the elements of a list
myDuplicate :: [a] -> [a]
myDuplicate = (`myReplicate` 2)
-- 15 Replicate the elements of a list a given number of times
myReplicate :: [a] -> Int -> [a]
myReplicate xs n = foldr (repli n) [] xs where
repli n = (\ z -> replin n z)
replin 0 _ z = z
replin n x z = replin (n-1) x (x:z)
-- 16 Drop every N'th element from a list
myDropEvery :: [a] -> Int -> [a]
myDropEvery xs interval = helpDrop xs interval where
helpDrop [] _ = []
helpDrop (x:xs) 1 = helpDrop xs interval
helpDrop (x:xs) n = x : helpDrop xs (n - 1)
-- 17 Split a list into two parts, given the length of the first part
mySplit :: [a] -> Int -> ([a],[a])
mySplit xs n = (take n xs, drop n xs)
-- 18 Extract a slice from a list
mySlice :: [a] -> Int -> Int -> [a]
mySlice xs lo up = slicer xs where
slicer = drop (lo-1) . take (up)
-- 19 Rotate a list N places to the left
myRotate :: [a] -> Int -> [a]
myRotate [] _ = []
myRotate xs n = listify $ mySplit xs $ pos `mod` length xs where
pos = if n < 0 then (length xs) + n else n
listify (xs,ys) = ys ++ xs
-- 20 Remove the K'th element from a list
myRemoveAt :: Int -> [a] -> (a,[a])
myRemoveAt k xs = ((xs !! (k-1)), (take (k-1) xs) ++ (drop k xs))
|
nadirs/99problems
|
Problems.hs
|
bsd-3-clause
| 4,163 | 0 | 13 | 991 | 1,869 | 996 | 873 | 89 | 3 |
module Network.Api.Pin.Tests
(
main
, test
) where
import Test.Framework
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Network.Api.Pin
main ::
IO ()
main =
defaultMain [test]
test ::
Test
test =
testGroup "Pin"
[
testProperty "Identity" prop_identity
]
prop_identity ::
Int
-> Bool
prop_identity n =
bletch n == n
|
markhibberd/pin
|
test/Network/Api/Pin/Tests.hs
|
bsd-3-clause
| 384 | 0 | 7 | 97 | 107 | 61 | 46 | 22 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Nano.Typecheck.Subst (
-- * Substitutions
RSubst (..)
, Subst
, toList
, fromList
-- * Free Type Variables
, Free (..)
-- * Type-class with operations
, Substitutable (..)
-- * Unification
, unifys
) where
import Text.PrettyPrint.HughesPJ
import Language.ECMAScript3.PrettyPrint
import Language.Fixpoint.Misc
import qualified Language.Fixpoint.Types as F
import Language.Nano.Errors
import Language.Nano.Typecheck.Types
import Control.Applicative ((<$>))
import qualified Data.HashSet as S
import qualified Data.HashMap.Strict as M
import Data.Monoid
-- import Text.Printf
---------------------------------------------------------------------------
-- | Substitutions --------------------------------------------------------
---------------------------------------------------------------------------
-- | Type alias for Map from @TVar@ to @Type@. Hidden
data RSubst r = Su (M.HashMap TVar (RType r))
type Subst = RSubst ()
toList :: RSubst r -> [(TVar, RType r)]
toList (Su m) = M.toList m
fromList :: [(TVar, RType r)] -> RSubst r
fromList = Su . M.fromList
-- | Substitutions form a monoid; not commutative
instance (F.Reftable r, Substitutable r (RType r)) => Monoid (RSubst r) where
mempty = Su M.empty
mappend (Su m) θ'@(Su m') = Su $ (apply θ' <$> m) `M.union` m'
instance (F.Reftable r, PP r) => PP (RSubst r) where
pp (Su m) = if M.null m then text "empty" else vcat $ (ppBind <$>) $ M.toList m
ppBind (x, t) = pp x <+> text ":=" <+> pp t
---------------------------------------------------------------------------
-- | Substitutions --------------------------------------------------------
---------------------------------------------------------------------------
class Free a where
free :: a -> S.HashSet TVar
class Substitutable r a where
apply :: (RSubst r) -> a -> a
instance Free a => Free [a] where
free = S.unions . map free
instance Substitutable r a => Substitutable r [a] where
apply = map . apply
instance (PP r, F.Reftable r) => Substitutable r (RType r) where
apply θ t = appTy θ t
-- where
-- msg = printf "apply [θ = %s] [t = %s]" (ppshow θ) (ppshow t)
instance (PP r, F.Reftable r) => Substitutable r (Bind r) where
apply θ (B z t) = B z $ appTy θ t
instance Free (RType r) where
free (TApp _ ts _) = S.unions $ free <$> ts
free (TVar α _) = S.singleton α
free (TFun xts t _) = S.unions $ free <$> t:ts where ts = b_type <$> xts
free (TAll α t) = S.delete α $ free t
instance Substitutable () Fact where
apply _ x@(PhiVar _) = x
apply θ (TypInst ts) = TypInst $ apply θ ts
instance Free Fact where
free (PhiVar _) = S.empty
free (TypInst ts) = free ts
------------------------------------------------------------------------
-- appTy :: RSubst r -> RType r -> RType r
------------------------------------------------------------------------
appTy θ (TApp c ts z) = TApp c (apply θ ts) z
appTy (Su m) t@(TVar α r) = (M.lookupDefault t α m) `strengthen` r
appTy θ (TFun ts t r) = TFun (apply θ ts) (apply θ t) r
appTy (Su m) (TAll α t) = apply (Su $ M.delete α m) t
-----------------------------------------------------------------------------
unify :: Subst -> Type -> Type -> Either String Subst
-----------------------------------------------------------------------------
unify θ (TFun xts t _) (TFun xts' t' _) = unifys θ (t: (b_type <$> xts)) (t': (b_type <$> xts'))
unify θ (TVar α _) (TVar β _) = varEql θ α β
unify θ (TVar α _) t = varAsn θ α t
unify θ t (TVar α _) = varAsn θ α t
unify θ (TApp c ts _) (TApp c' ts' _)
| c == c' = unifys θ ts ts'
unify θ t t'
| t == t' = return θ
| otherwise = Left $ errorUnification t t'
unifys :: Subst -> [Type] -> [Type] -> Either String Subst
unifys θ xs ys = {- tracePP msg $ -} unifys' θ xs ys
-- where
-- msg = printf "unifys: [xs = %s] [ys = %s]" (ppshow xs) (ppshow ys)
unifys' θ ts ts'
| nTs == nTs' = go θ (ts, ts')
| otherwise = Left $ errorUnification ts ts'
where
nTs = length ts
nTs' = length ts'
go θ (t:ts , t':ts') = unify θ t t' >>= \θ' -> go θ' (mapPair (apply θ') (ts, ts'))
go θ (_ , _ ) = return θ
varEql θ α β = case varAsn θ α (tVar β) of
z@(Right _) -> z
(Left e1) -> case varAsn θ β (tVar α) of
z@(Right _) -> z
(Left e2) -> Left (e1 ++ "\n OR \n" ++ e2)
varAsn θ α t
| t == tVar α = Right $ θ
| α `S.member` free t = Left $ errorOccursCheck α t
| unassigned α θ = Right $ θ `mappend` (Su $ M.singleton α t)
| otherwise = Left $ errorRigidUnify α t
unassigned α (Su m) = M.lookup α m == Just (tVar α)
|
UCSD-PL/nano-js
|
Language/Nano/Typecheck/Subst.hs
|
bsd-3-clause
| 5,348 | 0 | 14 | 1,507 | 1,822 | 945 | 877 | 91 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Exception (SomeException, try)
import qualified Data.Text as T
import Snap.Http.Server
import Snap.Snaplet
import Snap.Core
import System.IO
import Application
#ifdef DEVELOPMENT
import Snap.Loader.Devel
#else
import Snap.Loader.Prod
#endif
main :: IO ()
main = do
-- depending on the version of loadSnapTH in scope, this either
-- enables dynamic reloading, or compiles it without. The last
-- argument to loadSnapTH is a list of additional directories to
-- watch for changes to trigger reloads in development mode. It
-- doesn't need to include source directories, those are picked up
-- automatically by the splice.
(conf, site, cleanup) <- $(loadSnapTH [| getConf |]
'getActions
["resources/templates"])
_ <- try $ httpServe conf $ site :: IO (Either SomeException ())
cleanup
-- | This action loads the config used by this application. The
-- loaded config is returned as the first element of the tuple
-- produced by the loadSnapTH Splice. The type is not solidly fixed,
-- though it must be an IO action that produces the same type as
-- 'getActions' takes. It also must be an instance of Typeable. If
-- the type of this is changed, a full recompile will be needed to
-- pick up the change, even in development mode.
--
-- This action is only run once, regardless of whether development or
-- production mode is in use.
getConf :: IO (Config Snap ())
getConf = commandLineConfig defaultConfig
-- | This function generates the the site handler and cleanup action
-- from the configuration. In production mode, this action is only
-- run once. In development mode, this action is run whenever the
-- application is reloaded.
--
-- Development mode also makes sure that the cleanup actions are run
-- appropriately before shutdown. The cleanup action returned from
-- loadSnapTH should still be used after the server has stopped
-- handling requests, as the cleanup actions are only automatically
-- run when a reload is triggered.
--
-- This sample doesn't actually use the config passed in, but more
-- sophisticated code might.
getActions :: Config Snap () -> IO (Snap (), IO ())
getActions _ = do
(msgs, site, cleanup) <- runSnaplet appInit
hPutStrLn stderr $ T.unpack msgs
return (site, cleanup)
|
dzhus/snap-metaforms
|
src/Main.hs
|
bsd-3-clause
| 2,529 | 0 | 11 | 612 | 290 | 171 | 119 | 25 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Notebook where
import Data.Default (def)
import qualified Data.Default as D
import Data.Text (Text, unpack)
import qualified Data.ByteString.Lazy as B
import qualified Data.HashMap.Lazy as H
import Control.Lens hiding ((.:))
import qualified Text.Pandoc as P
import qualified Text.Pandoc.Builder as P
data Notebook = N { _nName :: Text
, _nCommands :: [Command] }
deriving (Eq, Show)
data Command = C { _cLanguage :: Text
, _cCommand :: Text
, _cState :: Maybe Result
, _cResultHidden :: Bool
, _cCommandHidden :: Bool }
deriving (Eq, Show)
data Result = RSuccess P.Blocks
| RError Text
deriving (Eq, Show)
makeLenses ''Notebook
makeLenses ''Command
success :: Command -> Maybe P.Blocks
success (C _ _ (Just (RSuccess p)) _ _) = Just p
success _ = Nothing
-- data Language = Java
-- | R
-- | Scala
-- | Python
-- | Haskell
-- | Other Text
-- deriving (Eq, Show)
|
TiloWiklund/pinot
|
src/Notebook.hs
|
bsd-3-clause
| 1,126 | 0 | 11 | 374 | 281 | 170 | 111 | 27 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[HsBinds]{Abstract syntax: top-level bindings and signatures}
Datatype for: @BindGroup@, @Bind@, @Sig@, @Bind@.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE BangPatterns #-}
module HsBinds where
import {-# SOURCE #-} HsExpr ( pprExpr, LHsExpr,
MatchGroup, pprFunBind,
GRHSs, pprPatBind )
import {-# SOURCE #-} HsPat ( LPat )
import PlaceHolder ( PostTc,PostRn,DataId )
import HsTypes
import PprCore ()
import CoreSyn
import TcEvidence
import Type
import Name
import NameSet
import BasicTypes
import Outputable
import SrcLoc
import Var
import Bag
import FastString
import BooleanFormula (LBooleanFormula)
import DynFlags
import Data.Data hiding ( Fixity )
import Data.List hiding ( foldr )
import Data.Ord
import Data.Foldable ( Foldable(..) )
{-
************************************************************************
* *
\subsection{Bindings: @BindGroup@}
* *
************************************************************************
Global bindings (where clauses)
-}
-- During renaming, we need bindings where the left-hand sides
-- have been renamed but the the right-hand sides have not.
-- the ...LR datatypes are parametrized by two id types,
-- one for the left and one for the right.
-- Other than during renaming, these will be the same.
type HsLocalBinds id = HsLocalBindsLR id id
-- | Bindings in a 'let' expression
-- or a 'where' clause
data HsLocalBindsLR idL idR
= HsValBinds (HsValBindsLR idL idR)
-- There should be no pattern synonyms in the HsValBindsLR
-- These are *local* (not top level) bindings
-- The parser accepts them, however, leaving the the
-- renamer to report them
| HsIPBinds (HsIPBinds idR)
| EmptyLocalBinds
deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (HsLocalBindsLR idL idR)
type HsValBinds id = HsValBindsLR id id
-- | Value bindings (not implicit parameters)
-- Used for both top level and nested bindings
-- May contain pattern synonym bindings
data HsValBindsLR idL idR
= -- | Before renaming RHS; idR is always RdrName
-- Not dependency analysed
-- Recursive by default
ValBindsIn
(LHsBindsLR idL idR) [LSig idR]
-- | After renaming RHS; idR can be Name or Id
-- Dependency analysed,
-- later bindings in the list may depend on earlier
-- ones.
| ValBindsOut
[(RecFlag, LHsBinds idL)]
[LSig Name]
deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (HsValBindsLR idL idR)
type LHsBind id = LHsBindLR id id
type LHsBinds id = LHsBindsLR id id
type HsBind id = HsBindLR id id
type LHsBindsLR idL idR = Bag (LHsBindLR idL idR)
type LHsBindLR idL idR = Located (HsBindLR idL idR)
data HsBindLR idL idR
= -- | FunBind is used for both functions @f x = e@
-- and variables @f = \x -> e@
--
-- Reason 1: Special case for type inference: see 'TcBinds.tcMonoBinds'.
--
-- Reason 2: Instance decls can only have FunBinds, which is convenient.
-- If you change this, you'll need to change e.g. rnMethodBinds
--
-- But note that the form @f :: a->a = ...@
-- parses as a pattern binding, just like
-- @(f :: a -> a) = ... @
--
-- 'ApiAnnotation.AnnKeywordId's
--
-- - 'ApiAnnotation.AnnFunId', attached to each element of fun_matches
--
-- - 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
FunBind {
fun_id :: Located idL, -- Note [fun_id in Match] in HsExpr
fun_matches :: MatchGroup idR (LHsExpr idR), -- ^ The payload
fun_co_fn :: HsWrapper, -- ^ Coercion from the type of the MatchGroup to the type of
-- the Id. Example:
--
-- @
-- f :: Int -> forall a. a -> a
-- f x y = y
-- @
--
-- Then the MatchGroup will have type (Int -> a' -> a')
-- (with a free type variable a'). The coercion will take
-- a CoreExpr of this type and convert it to a CoreExpr of
-- type Int -> forall a'. a' -> a'
-- Notice that the coercion captures the free a'.
bind_fvs :: PostRn idL NameSet, -- ^ After the renamer, this contains
-- the locally-bound
-- free variables of this defn.
-- See Note [Bind free vars]
fun_tick :: [Tickish Id] -- ^ Ticks to put on the rhs, if any
}
-- | The pattern is never a simple variable;
-- That case is done by FunBind
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
| PatBind {
pat_lhs :: LPat idL,
pat_rhs :: GRHSs idR (LHsExpr idR),
pat_rhs_ty :: PostTc idR Type, -- ^ Type of the GRHSs
bind_fvs :: PostRn idL NameSet, -- ^ See Note [Bind free vars]
pat_ticks :: ([Tickish Id], [[Tickish Id]])
-- ^ Ticks to put on the rhs, if any, and ticks to put on
-- the bound variables.
}
-- | Dictionary binding and suchlike.
-- All VarBinds are introduced by the type checker
| VarBind {
var_id :: idL,
var_rhs :: LHsExpr idR, -- ^ Located only for consistency
var_inline :: Bool -- ^ True <=> inline this binding regardless
-- (used for implication constraints only)
}
| AbsBinds { -- Binds abstraction; TRANSLATION
abs_tvs :: [TyVar],
abs_ev_vars :: [EvVar], -- ^ Includes equality constraints
-- | AbsBinds only gets used when idL = idR after renaming,
-- but these need to be idL's for the collect... code in HsUtil
-- to have the right type
abs_exports :: [ABExport idL],
-- | Evidence bindings
-- Why a list? See TcInstDcls
-- Note [Typechecking plan for instance declarations]
abs_ev_binds :: [TcEvBinds],
-- | Typechecked user bindings
abs_binds :: LHsBinds idL
}
| AbsBindsSig { -- Simpler form of AbsBinds, used with a type sig
-- in tcPolyCheck. Produces simpler desugaring and
-- is necessary to avoid #11405, comment:3.
abs_tvs :: [TyVar],
abs_ev_vars :: [EvVar],
abs_sig_export :: idL, -- like abe_poly
abs_sig_prags :: TcSpecPrags,
abs_sig_ev_bind :: TcEvBinds, -- no list needed here
abs_sig_bind :: LHsBind idL -- always only one, and it's always a
-- FunBind
}
| PatSynBind (PatSynBind idL idR)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnLarrow','ApiAnnotation.AnnEqual',
-- 'ApiAnnotation.AnnWhere'
-- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (HsBindLR idL idR)
-- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds]
--
-- Creates bindings for (polymorphic, overloaded) poly_f
-- in terms of monomorphic, non-overloaded mono_f
--
-- Invariants:
-- 1. 'binds' binds mono_f
-- 2. ftvs is a subset of tvs
-- 3. ftvs includes all tyvars free in ds
--
-- See Note [AbsBinds]
data ABExport id
= ABE { abe_poly :: id -- ^ Any INLINE pragmas is attached to this Id
, abe_mono :: id
, abe_wrap :: HsWrapper -- ^ See Note [ABExport wrapper]
-- Shape: (forall abs_tvs. abs_ev_vars => abe_mono) ~ abe_poly
, abe_prags :: TcSpecPrags -- ^ SPECIALISE pragmas
} deriving (Data, Typeable)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnLarrow'
-- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,
-- For details on above see note [Api annotations] in ApiAnnotation
data PatSynBind idL idR
= PSB { psb_id :: Located idL, -- ^ Name of the pattern synonym
psb_fvs :: PostRn idR NameSet, -- ^ See Note [Bind free vars]
psb_args :: HsPatSynDetails (Located idR), -- ^ Formal parameter names
psb_def :: LPat idR, -- ^ Right-hand side
psb_dir :: HsPatSynDir idR -- ^ Directionality
} deriving (Typeable)
deriving instance (DataId idL, DataId idR)
=> Data (PatSynBind idL idR)
{-
Note [AbsBinds]
~~~~~~~~~~~~~~~
The AbsBinds constructor is used in the output of the type checker, to record
*typechecked* and *generalised* bindings. Consider a module M, with this
top-level binding, where there is no type signature for M.reverse,
M.reverse [] = []
M.reverse (x:xs) = M.reverse xs ++ [x]
In Hindley-Milner, a recursive binding is typechecked with the *recursive* uses
being *monomorphic*. So after typechecking *and* desugaring we will get something
like this
M.reverse :: forall a. [a] -> [a]
= /\a. letrec
reverse :: [a] -> [a] = \xs -> case xs of
[] -> []
(x:xs) -> reverse xs ++ [x]
in reverse
Notice that 'M.reverse' is polymorphic as expected, but there is a local
definition for plain 'reverse' which is *monomorphic*. The type variable
'a' scopes over the entire letrec.
That's after desugaring. What about after type checking but before
desugaring? That's where AbsBinds comes in. It looks like this:
AbsBinds { abs_tvs = [a]
, abs_exports = [ABE { abe_poly = M.reverse :: forall a. [a] -> [a],
, abe_mono = reverse :: [a] -> [a]}]
, abs_binds = { reverse :: [a] -> [a]
= \xs -> case xs of
[] -> []
(x:xs) -> reverse xs ++ [x] } }
Here,
* abs_tvs says what type variables are abstracted over the binding group,
just 'a' in this case.
* abs_binds is the *monomorphic* bindings of the group
* abs_exports describes how to get the polymorphic Id 'M.reverse' from the
monomorphic one 'reverse'
Notice that the *original* function (the polymorphic one you thought
you were defining) appears in the abe_poly field of the
abs_exports. The bindings in abs_binds are for fresh, local, Ids with
a *monomorphic* Id.
If there is a group of mutually recursive (see Note [Polymorphic
recursion]) functions without type signatures, we get one AbsBinds
with the monomorphic versions of the bindings in abs_binds, and one
element of abe_exports for each variable bound in the mutually
recursive group. This is true even for pattern bindings. Example:
(f,g) = (\x -> x, f)
After type checking we get
AbsBinds { abs_tvs = [a]
, abs_exports = [ ABE { abe_poly = M.f :: forall a. a -> a
, abe_mono = f :: a -> a }
, ABE { abe_poly = M.g :: forall a. a -> a
, abe_mono = g :: a -> a }]
, abs_binds = { (f,g) = (\x -> x, f) }
Note [Polymorphic recursion]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
Rec { f x = ...(g ef)...
; g :: forall a. [a] -> [a]
; g y = ...(f eg)... }
These bindings /are/ mutually recursive (f calls g, and g calls f).
But we can use the type signature for g to break the recursion,
like this:
1. Add g :: forall a. [a] -> [a] to the type environment
2. Typecheck the definition of f, all by itself,
including generalising it to find its most general
type, say f :: forall b. b -> b -> [b]
3. Extend the type environment with that type for f
4. Typecheck the definition of g, all by itself,
checking that it has the type claimed by its signature
Steps 2 and 4 each generate a separate AbsBinds, so we end
up with
Rec { AbsBinds { ...for f ... }
; AbsBinds { ...for g ... } }
This approach allows both f and to call each other
polymorphically, even though only g has a signature.
We get an AbsBinds that encompasses multiple source-program
bindings only when
* Each binding in the group has at least one binder that
lacks a user type signature
* The group forms a strongly connected component
Note [ABExport wrapper]
~~~~~~~~~~~~~~~~~~~~~~~
Consider
(f,g) = (\x.x, \y.y)
This ultimately desugars to something like this:
tup :: forall a b. (a->a, b->b)
tup = /\a b. (\x:a.x, \y:b.y)
f :: forall a. a -> a
f = /\a. case tup a Any of
(fm::a->a,gm:Any->Any) -> fm
...similarly for g...
The abe_wrap field deals with impedance-matching between
(/\a b. case tup a b of { (f,g) -> f })
and the thing we really want, which may have fewer type
variables. The action happens in TcBinds.mkExport.
Note [Bind free vars]
~~~~~~~~~~~~~~~~~~~~~
The bind_fvs field of FunBind and PatBind records the free variables
of the definition. It is used for two purposes
a) Dependency analysis prior to type checking
(see TcBinds.tc_group)
b) Deciding whether we can do generalisation of the binding
(see TcBinds.decideGeneralisationPlan)
Specifically,
* bind_fvs includes all free vars that are defined in this module
(including top-level things and lexically scoped type variables)
* bind_fvs excludes imported vars; this is just to keep the set smaller
* Before renaming, and after typechecking, the field is unused;
it's just an error thunk
-}
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsLocalBindsLR idL idR) where
ppr (HsValBinds bs) = ppr bs
ppr (HsIPBinds bs) = ppr bs
ppr EmptyLocalBinds = empty
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsValBindsLR idL idR) where
ppr (ValBindsIn binds sigs)
= pprDeclList (pprLHsBindsForUser binds sigs)
ppr (ValBindsOut sccs sigs)
= getPprStyle $ \ sty ->
if debugStyle sty then -- Print with sccs showing
vcat (map ppr sigs) $$ vcat (map ppr_scc sccs)
else
pprDeclList (pprLHsBindsForUser (unionManyBags (map snd sccs)) sigs)
where
ppr_scc (rec_flag, binds) = pp_rec rec_flag <+> pprLHsBinds binds
pp_rec Recursive = text "rec"
pp_rec NonRecursive = text "nonrec"
pprLHsBinds :: (OutputableBndr idL, OutputableBndr idR) => LHsBindsLR idL idR -> SDoc
pprLHsBinds binds
| isEmptyLHsBinds binds = empty
| otherwise = pprDeclList (map ppr (bagToList binds))
pprLHsBindsForUser :: (OutputableBndr idL, OutputableBndr idR, OutputableBndr id2)
=> LHsBindsLR idL idR -> [LSig id2] -> [SDoc]
-- pprLHsBindsForUser is different to pprLHsBinds because
-- a) No braces: 'let' and 'where' include a list of HsBindGroups
-- and we don't want several groups of bindings each
-- with braces around
-- b) Sort by location before printing
-- c) Include signatures
pprLHsBindsForUser binds sigs
= map snd (sort_by_loc decls)
where
decls :: [(SrcSpan, SDoc)]
decls = [(loc, ppr sig) | L loc sig <- sigs] ++
[(loc, ppr bind) | L loc bind <- bagToList binds]
sort_by_loc decls = sortBy (comparing fst) decls
pprDeclList :: [SDoc] -> SDoc -- Braces with a space
-- Print a bunch of declarations
-- One could choose { d1; d2; ... }, using 'sep'
-- or d1
-- d2
-- ..
-- using vcat
-- At the moment we chose the latter
-- Also we do the 'pprDeeperList' thing.
pprDeclList ds = pprDeeperList vcat ds
------------
emptyLocalBinds :: HsLocalBindsLR a b
emptyLocalBinds = EmptyLocalBinds
isEmptyLocalBinds :: HsLocalBindsLR a b -> Bool
isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds
isEmptyLocalBinds (HsIPBinds ds) = isEmptyIPBinds ds
isEmptyLocalBinds EmptyLocalBinds = True
isEmptyValBinds :: HsValBindsLR a b -> Bool
isEmptyValBinds (ValBindsIn ds sigs) = isEmptyLHsBinds ds && null sigs
isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs
emptyValBindsIn, emptyValBindsOut :: HsValBindsLR a b
emptyValBindsIn = ValBindsIn emptyBag []
emptyValBindsOut = ValBindsOut [] []
emptyLHsBinds :: LHsBindsLR idL idR
emptyLHsBinds = emptyBag
isEmptyLHsBinds :: LHsBindsLR idL idR -> Bool
isEmptyLHsBinds = isEmptyBag
------------
plusHsValBinds :: HsValBinds a -> HsValBinds a -> HsValBinds a
plusHsValBinds (ValBindsIn ds1 sigs1) (ValBindsIn ds2 sigs2)
= ValBindsIn (ds1 `unionBags` ds2) (sigs1 ++ sigs2)
plusHsValBinds (ValBindsOut ds1 sigs1) (ValBindsOut ds2 sigs2)
= ValBindsOut (ds1 ++ ds2) (sigs1 ++ sigs2)
plusHsValBinds _ _
= panic "HsBinds.plusHsValBinds"
{-
What AbsBinds means
~~~~~~~~~~~~~~~~~~~
AbsBinds tvs
[d1,d2]
[(tvs1, f1p, f1m),
(tvs2, f2p, f2m)]
BIND
means
f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND
in fm
gp = ...same again, with gm instead of fm
This is a pretty bad translation, because it duplicates all the bindings.
So the desugarer tries to do a better job:
fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of
(fm,gm) -> fm
..ditto for gp..
tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND
in (fm,gm)
-}
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsBindLR idL idR) where
ppr mbind = ppr_monobind mbind
ppr_monobind :: (OutputableBndr idL, OutputableBndr idR) => HsBindLR idL idR -> SDoc
ppr_monobind (PatBind { pat_lhs = pat, pat_rhs = grhss })
= pprPatBind pat grhss
ppr_monobind (VarBind { var_id = var, var_rhs = rhs })
= sep [pprBndr CasePatBind var, nest 2 $ equals <+> pprExpr (unLoc rhs)]
ppr_monobind (FunBind { fun_id = fun,
fun_co_fn = wrap,
fun_matches = matches,
fun_tick = ticks })
= pprTicks empty (if null ticks then empty
else text "-- ticks = " <> ppr ticks)
$$ ifPprDebug (pprBndr LetBind (unLoc fun))
$$ pprFunBind (unLoc fun) matches
$$ ifPprDebug (ppr wrap)
ppr_monobind (PatSynBind psb) = ppr psb
ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dictvars
, abs_exports = exports, abs_binds = val_binds
, abs_ev_binds = ev_binds })
= sdocWithDynFlags $ \ dflags ->
if gopt Opt_PrintTypecheckerElaboration dflags then
-- Show extra information (bug number: #10662)
hang (text "AbsBinds" <+> brackets (interpp'SP tyvars)
<+> brackets (interpp'SP dictvars))
2 $ braces $ vcat
[ text "Exports:" <+>
brackets (sep (punctuate comma (map ppr exports)))
, text "Exported types:" <+>
vcat [pprBndr LetBind (abe_poly ex) | ex <- exports]
, text "Binds:" <+> pprLHsBinds val_binds
, text "Evidence:" <+> ppr ev_binds ]
else
pprLHsBinds val_binds
ppr_monobind (AbsBindsSig { abs_tvs = tyvars
, abs_ev_vars = dictvars
, abs_sig_ev_bind = ev_bind
, abs_sig_bind = bind })
= sdocWithDynFlags $ \ dflags ->
if gopt Opt_PrintTypecheckerElaboration dflags then
hang (text "AbsBindsSig" <+> brackets (interpp'SP tyvars)
<+> brackets (interpp'SP dictvars))
2 $ braces $ vcat
[ text "Bind:" <+> ppr bind
, text "Evidence:" <+> ppr ev_bind ]
else
ppr bind
instance (OutputableBndr id) => Outputable (ABExport id) where
ppr (ABE { abe_wrap = wrap, abe_poly = gbl, abe_mono = lcl, abe_prags = prags })
= vcat [ ppr gbl <+> text "<=" <+> ppr lcl
, nest 2 (pprTcSpecPrags prags)
, nest 2 (text "wrap:" <+> ppr wrap)]
instance (OutputableBndr idL, OutputableBndr idR) => Outputable (PatSynBind idL idR) where
ppr (PSB{ psb_id = L _ psyn, psb_args = details, psb_def = pat, psb_dir = dir })
= ppr_lhs <+> ppr_rhs
where
ppr_lhs = text "pattern" <+> ppr_details
ppr_simple syntax = syntax <+> ppr pat
ppr_details = case details of
InfixPatSyn v1 v2 -> hsep [ppr v1, pprInfixOcc psyn, ppr v2]
PrefixPatSyn vs -> hsep (pprPrefixOcc psyn : map ppr vs)
RecordPatSyn vs ->
pprPrefixOcc psyn
<> braces (sep (punctuate comma (map ppr vs)))
ppr_rhs = case dir of
Unidirectional -> ppr_simple (text "<-")
ImplicitBidirectional -> ppr_simple equals
ExplicitBidirectional mg -> ppr_simple (text "<-") <+> ptext (sLit "where") $$
(nest 2 $ pprFunBind psyn mg)
pprTicks :: SDoc -> SDoc -> SDoc
-- Print stuff about ticks only when -dppr-debug is on, to avoid
-- them appearing in error messages (from the desugarer); see Trac # 3263
-- Also print ticks in dumpStyle, so that -ddump-hpc actually does
-- something useful.
pprTicks pp_no_debug pp_when_debug
= getPprStyle (\ sty -> if debugStyle sty || dumpStyle sty
then pp_when_debug
else pp_no_debug)
{-
************************************************************************
* *
Implicit parameter bindings
* *
************************************************************************
-}
data HsIPBinds id
= IPBinds
[LIPBind id]
TcEvBinds -- Only in typechecker output; binds
-- uses of the implicit parameters
deriving (Typeable)
deriving instance (DataId id) => Data (HsIPBinds id)
isEmptyIPBinds :: HsIPBinds id -> Bool
isEmptyIPBinds (IPBinds is ds) = null is && isEmptyTcEvBinds ds
type LIPBind id = Located (IPBind id)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
-- list
-- For details on above see note [Api annotations] in ApiAnnotation
-- | Implicit parameter bindings.
--
-- These bindings start off as (Left "x") in the parser and stay
-- that way until after type-checking when they are replaced with
-- (Right d), where "d" is the name of the dictionary holding the
-- evidence for the implicit parameter.
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual'
-- For details on above see note [Api annotations] in ApiAnnotation
data IPBind id
= IPBind (Either (Located HsIPName) id) (LHsExpr id)
deriving (Typeable)
deriving instance (DataId name) => Data (IPBind name)
instance (OutputableBndr id) => Outputable (HsIPBinds id) where
ppr (IPBinds bs ds) = pprDeeperList vcat (map ppr bs)
$$ ifPprDebug (ppr ds)
instance (OutputableBndr id) => Outputable (IPBind id) where
ppr (IPBind lr rhs) = name <+> equals <+> pprExpr (unLoc rhs)
where name = case lr of
Left (L _ ip) -> pprBndr LetBind ip
Right id -> pprBndr LetBind id
{-
************************************************************************
* *
\subsection{@Sig@: type signatures and value-modifying user pragmas}
* *
************************************************************************
It is convenient to lump ``value-modifying'' user-pragmas (e.g.,
``specialise this function to these four types...'') in with type
signatures. Then all the machinery to move them into place, etc.,
serves for both.
-}
type LSig name = Located (Sig name)
-- | Signatures and pragmas
data Sig name
= -- | An ordinary type signature
--
-- > f :: Num a => a -> a
--
-- After renaming, this list of Names contains the named and unnamed
-- wildcards brought into scope by this signature. For a signature
-- @_ -> _a -> Bool@, the renamer will give the unnamed wildcard @_@
-- a freshly generated name, e.g. @_w@. @_w@ and the named wildcard @_a@
-- are then both replaced with fresh meta vars in the type. Their names
-- are stored in the type signature that brought them into scope, in
-- this third field to be more specific.
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon',
-- 'ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
TypeSig
[Located name] -- LHS of the signature; e.g. f,g,h :: blah
(LHsSigWcType name) -- RHS of the signature; can have wildcards
-- | A pattern synonym type signature
--
-- > pattern Single :: () => (Show a) => a -> [a]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnForall'
-- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| PatSynSig (Located name) (LHsSigType name)
-- P :: forall a b. Req => Prov => ty
-- | A signature for a class method
-- False: ordinary class-method signature
-- True: default class method signature
-- e.g. class C a where
-- op :: a -> a -- Ordinary
-- default op :: Eq a => a -> a -- Generic default
-- No wildcards allowed here
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDefault',
-- 'ApiAnnotation.AnnDcolon'
| ClassOpSig Bool [Located name] (LHsSigType name)
-- | A type signature in generated code, notably the code
-- generated for record selectors. We simply record
-- the desired Id itself, replete with its name, type
-- and IdDetails. Otherwise it's just like a type
-- signature: there should be an accompanying binding
| IdSig Id
-- | An ordinary fixity declaration
--
-- > infixl 8 ***
--
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnInfix',
-- 'ApiAnnotation.AnnVal'
-- For details on above see note [Api annotations] in ApiAnnotation
| FixSig (FixitySig name)
-- | An inline pragma
--
-- > {#- INLINE f #-}
--
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnOpen' @'{-\# INLINE'@ and @'['@,
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTilde',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| InlineSig (Located name) -- Function name
InlinePragma -- Never defaultInlinePragma
-- | A specialisation pragma
--
-- > {-# SPECIALISE f :: Int -> Int #-}
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpen' @'{-\# SPECIALISE'@ and @'['@,
-- 'ApiAnnotation.AnnTilde',
-- 'ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnClose' @']'@ and @'\#-}'@,
-- 'ApiAnnotation.AnnDcolon'
-- For details on above see note [Api annotations] in ApiAnnotation
| SpecSig (Located name) -- Specialise a function or datatype ...
[LHsSigType name] -- ... to these types
InlinePragma -- The pragma on SPECIALISE_INLINE form.
-- If it's just defaultInlinePragma, then we said
-- SPECIALISE, not SPECIALISE_INLINE
-- | A specialisation pragma for instance declarations only
--
-- > {-# SPECIALISE instance Eq [Int] #-}
--
-- (Class tys); should be a specialisation of the
-- current instance declaration
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnInstance','ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| SpecInstSig SourceText (LHsSigType name)
-- Note [Pragma source text] in BasicTypes
-- | A minimal complete definition pragma
--
-- > {-# MINIMAL a | (b, c | (d | e)) #-}
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnVbar','ApiAnnotation.AnnComma',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| MinimalSig SourceText (LBooleanFormula (Located name))
-- Note [Pragma source text] in BasicTypes
deriving (Typeable)
deriving instance (DataId name) => Data (Sig name)
type LFixitySig name = Located (FixitySig name)
data FixitySig name = FixitySig [Located name] Fixity
deriving (Data, Typeable)
-- | TsSpecPrags conveys pragmas from the type checker to the desugarer
data TcSpecPrags
= IsDefaultMethod -- ^ Super-specialised: a default method should
-- be macro-expanded at every call site
| SpecPrags [LTcSpecPrag]
deriving (Data, Typeable)
type LTcSpecPrag = Located TcSpecPrag
data TcSpecPrag
= SpecPrag
Id
HsWrapper
InlinePragma
-- ^ The Id to be specialised, an wrapper that specialises the
-- polymorphic function, and inlining spec for the specialised function
deriving (Data, Typeable)
noSpecPrags :: TcSpecPrags
noSpecPrags = SpecPrags []
hasSpecPrags :: TcSpecPrags -> Bool
hasSpecPrags (SpecPrags ps) = not (null ps)
hasSpecPrags IsDefaultMethod = False
isDefaultMethod :: TcSpecPrags -> Bool
isDefaultMethod IsDefaultMethod = True
isDefaultMethod (SpecPrags {}) = False
isFixityLSig :: LSig name -> Bool
isFixityLSig (L _ (FixSig {})) = True
isFixityLSig _ = False
isTypeLSig :: LSig name -> Bool -- Type signatures
isTypeLSig (L _(TypeSig {})) = True
isTypeLSig (L _(ClassOpSig {})) = True
isTypeLSig (L _(IdSig {})) = True
isTypeLSig _ = False
isSpecLSig :: LSig name -> Bool
isSpecLSig (L _(SpecSig {})) = True
isSpecLSig _ = False
isSpecInstLSig :: LSig name -> Bool
isSpecInstLSig (L _ (SpecInstSig {})) = True
isSpecInstLSig _ = False
isPragLSig :: LSig name -> Bool
-- Identifies pragmas
isPragLSig (L _ (SpecSig {})) = True
isPragLSig (L _ (InlineSig {})) = True
isPragLSig _ = False
isInlineLSig :: LSig name -> Bool
-- Identifies inline pragmas
isInlineLSig (L _ (InlineSig {})) = True
isInlineLSig _ = False
isMinimalLSig :: LSig name -> Bool
isMinimalLSig (L _ (MinimalSig {})) = True
isMinimalLSig _ = False
hsSigDoc :: Sig name -> SDoc
hsSigDoc (TypeSig {}) = text "type signature"
hsSigDoc (PatSynSig {}) = text "pattern synonym signature"
hsSigDoc (ClassOpSig is_deflt _ _)
| is_deflt = text "default type signature"
| otherwise = text "class method signature"
hsSigDoc (IdSig {}) = text "id signature"
hsSigDoc (SpecSig {}) = text "SPECIALISE pragma"
hsSigDoc (InlineSig _ prag) = ppr (inlinePragmaSpec prag) <+> text "pragma"
hsSigDoc (SpecInstSig {}) = text "SPECIALISE instance pragma"
hsSigDoc (FixSig {}) = text "fixity declaration"
hsSigDoc (MinimalSig {}) = text "MINIMAL pragma"
{-
Check if signatures overlap; this is used when checking for duplicate
signatures. Since some of the signatures contain a list of names, testing for
equality is not enough -- we have to check if they overlap.
-}
instance (OutputableBndr name) => Outputable (Sig name) where
ppr sig = ppr_sig sig
ppr_sig :: OutputableBndr name => Sig name -> SDoc
ppr_sig (TypeSig vars ty) = pprVarSig (map unLoc vars) (ppr ty)
ppr_sig (ClassOpSig is_deflt vars ty)
| is_deflt = text "default" <+> pprVarSig (map unLoc vars) (ppr ty)
| otherwise = pprVarSig (map unLoc vars) (ppr ty)
ppr_sig (IdSig id) = pprVarSig [id] (ppr (varType id))
ppr_sig (FixSig fix_sig) = ppr fix_sig
ppr_sig (SpecSig var ty inl)
= pragBrackets (pprSpec (unLoc var) (interpp'SP ty) inl)
ppr_sig (InlineSig var inl) = pragBrackets (ppr inl <+> pprPrefixOcc (unLoc var))
ppr_sig (SpecInstSig _ ty)
= pragBrackets (text "SPECIALIZE instance" <+> ppr ty)
ppr_sig (MinimalSig _ bf) = pragBrackets (pprMinimalSig bf)
ppr_sig (PatSynSig name sig_ty)
= text "pattern" <+> pprPrefixOcc (unLoc name) <+> dcolon
<+> ppr sig_ty
instance OutputableBndr name => Outputable (FixitySig name) where
ppr (FixitySig names fixity) = sep [ppr fixity, pprops]
where
pprops = hsep $ punctuate comma (map (pprInfixOcc . unLoc) names)
pragBrackets :: SDoc -> SDoc
pragBrackets doc = text "{-#" <+> doc <+> ptext (sLit "#-}")
pprVarSig :: (OutputableBndr id) => [id] -> SDoc -> SDoc
pprVarSig vars pp_ty = sep [pprvars <+> dcolon, nest 2 pp_ty]
where
pprvars = hsep $ punctuate comma (map pprPrefixOcc vars)
pprSpec :: (OutputableBndr id) => id -> SDoc -> InlinePragma -> SDoc
pprSpec var pp_ty inl = text "SPECIALIZE" <+> pp_inl <+> pprVarSig [var] pp_ty
where
pp_inl | isDefaultInlinePragma inl = empty
| otherwise = ppr inl
pprTcSpecPrags :: TcSpecPrags -> SDoc
pprTcSpecPrags IsDefaultMethod = text "<default method>"
pprTcSpecPrags (SpecPrags ps) = vcat (map (ppr . unLoc) ps)
instance Outputable TcSpecPrag where
ppr (SpecPrag var _ inl) = pprSpec var (text "<type>") inl
pprMinimalSig :: OutputableBndr name => LBooleanFormula (Located name) -> SDoc
pprMinimalSig (L _ bf) = text "MINIMAL" <+> ppr (fmap unLoc bf)
{-
************************************************************************
* *
\subsection[PatSynBind]{A pattern synonym definition}
* *
************************************************************************
-}
data HsPatSynDetails a
= InfixPatSyn a a
| PrefixPatSyn [a]
| RecordPatSyn [RecordPatSynField a]
deriving (Typeable, Data)
-- See Note [Record PatSyn Fields]
data RecordPatSynField a
= RecordPatSynField {
recordPatSynSelectorId :: a -- Selector name visible in rest of the file
, recordPatSynPatVar :: a
-- Filled in by renamer, the name used internally
-- by the pattern
} deriving (Typeable, Data)
{-
Note [Record PatSyn Fields]
Consider the following two pattern synonyms.
pattern P x y = ([x,True], [y,'v'])
pattern Q{ x, y } =([x,True], [y,'v'])
In P, we just have two local binders, x and y.
In Q, we have local binders but also top-level record selectors
x :: ([Bool], [Char]) -> Bool and similarly for y.
It would make sense to support record-like syntax
pattern Q{ x=x1, y=y1 } = ([x1,True], [y1,'v'])
when we have a different name for the local and top-level binder
the distinction between the two names clear
-}
instance Functor RecordPatSynField where
fmap f (RecordPatSynField visible hidden) =
RecordPatSynField (f visible) (f hidden)
instance Outputable a => Outputable (RecordPatSynField a) where
ppr (RecordPatSynField v _) = ppr v
instance Foldable RecordPatSynField where
foldMap f (RecordPatSynField visible hidden) =
f visible `mappend` f hidden
instance Traversable RecordPatSynField where
traverse f (RecordPatSynField visible hidden) =
RecordPatSynField <$> f visible <*> f hidden
instance Functor HsPatSynDetails where
fmap f (InfixPatSyn left right) = InfixPatSyn (f left) (f right)
fmap f (PrefixPatSyn args) = PrefixPatSyn (fmap f args)
fmap f (RecordPatSyn args) = RecordPatSyn (map (fmap f) args)
instance Foldable HsPatSynDetails where
foldMap f (InfixPatSyn left right) = f left `mappend` f right
foldMap f (PrefixPatSyn args) = foldMap f args
foldMap f (RecordPatSyn args) = foldMap (foldMap f) args
foldl1 f (InfixPatSyn left right) = left `f` right
foldl1 f (PrefixPatSyn args) = Data.List.foldl1 f args
foldl1 f (RecordPatSyn args) =
Data.List.foldl1 f (map (Data.Foldable.foldl1 f) args)
foldr1 f (InfixPatSyn left right) = left `f` right
foldr1 f (PrefixPatSyn args) = Data.List.foldr1 f args
foldr1 f (RecordPatSyn args) =
Data.List.foldr1 f (map (Data.Foldable.foldr1 f) args)
length (InfixPatSyn _ _) = 2
length (PrefixPatSyn args) = Data.List.length args
length (RecordPatSyn args) = Data.List.length args
null (InfixPatSyn _ _) = False
null (PrefixPatSyn args) = Data.List.null args
null (RecordPatSyn args) = Data.List.null args
toList (InfixPatSyn left right) = [left, right]
toList (PrefixPatSyn args) = args
toList (RecordPatSyn args) = foldMap toList args
instance Traversable HsPatSynDetails where
traverse f (InfixPatSyn left right) = InfixPatSyn <$> f left <*> f right
traverse f (PrefixPatSyn args) = PrefixPatSyn <$> traverse f args
traverse f (RecordPatSyn args) = RecordPatSyn <$> traverse (traverse f) args
data HsPatSynDir id
= Unidirectional
| ImplicitBidirectional
| ExplicitBidirectional (MatchGroup id (LHsExpr id))
deriving (Typeable)
deriving instance (DataId id) => Data (HsPatSynDir id)
|
tjakway/ghcjvm
|
compiler/hsSyn/HsBinds.hs
|
bsd-3-clause
| 39,011 | 0 | 18 | 11,260 | 6,190 | 3,335 | 2,855 | 415 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Text.PDDL.PP (
module Text.PDDL.PP
, module Text.PrettyPrint.HughesPJ
) where
import qualified Data.Text as S
import Text.PrettyPrint.HughesPJ
class PP a where
pp :: a -> Doc
instance PP Int where
pp = int
instance PP Double where
pp = double
instance PP Doc where
pp = id
instance PP Char where
pp = char
instance PP S.Text where
pp s = text (S.unpack s)
|
elliottt/pddl
|
src/Text/PDDL/PP.hs
|
bsd-3-clause
| 519 | 0 | 9 | 115 | 139 | 80 | 59 | 20 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
#endif
module Text.RE.PCRE.Sequence
(
-- * Tutorial
-- $tutorial
-- * The Match Operators
(*=~)
, (?=~)
, (=~)
, (=~~)
-- * The Toolkit
-- $toolkit
, module Text.RE
-- * The 'RE' Type
-- $re
, module Text.RE.PCRE.RE
) where
import Prelude.Compat
import qualified Data.Sequence as S
import Data.Typeable
import Text.Regex.Base
import Text.RE
import Text.RE.Internal.AddCaptureNames
import Text.RE.PCRE.RE
import qualified Text.Regex.PCRE as PCRE
-- | find all matches in text
(*=~) :: (S.Seq Char)
-> RE
-> Matches (S.Seq Char)
(*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs
-- | find first match in text
(?=~) :: (S.Seq Char)
-> RE
-> Match (S.Seq Char)
(?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base polymorphic match operator
(=~) :: ( Typeable a
, RegexContext PCRE.Regex (S.Seq Char) a
, RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String
)
=> (S.Seq Char)
-> RE
-> a
(=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base monadic, polymorphic match operator
(=~~) :: ( Monad m
, Functor m
, Typeable a
, RegexContext PCRE.Regex (S.Seq Char) a
, RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String
)
=> (S.Seq Char)
-> RE
-> m a
(=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs
instance IsRegex RE (S.Seq Char) where
matchOnce = flip (?=~)
matchMany = flip (*=~)
regexSource = reSource
-- $tutorial
-- We have a regex tutorial at <http://tutorial.regex.uk>. These API
-- docs are mainly for reference.
-- $toolkit
--
-- Beyond the above match operators and the regular expression type
-- below, "Text.RE" contains the toolkit for replacing captures,
-- specifying options, etc.
-- $re
--
-- "Text.RE.PCRE.RE" contains the toolkit specific to the 'RE' type,
-- the type generated by the gegex compiler.
|
cdornan/idiot
|
Text/RE/PCRE/Sequence.hs
|
bsd-3-clause
| 2,514 | 0 | 10 | 669 | 538 | 314 | 224 | 50 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Polynome where
import qualified Data.List as L
import qualified Data.Map as M
import Genetic
-- import Debug.Trace
data Term' var = X var
| Const Double
| Minus (Term' var)
| (Term' var) :+ (Term' var)
| (Term' var) :* (Term' var) deriving (Eq, Ord, Show)
type Term = Term' Int
data Dir = L | R | S deriving (Show)
type Path = [Dir]
type VarMap = M.Map Int Double
paths :: Term -> [Path]
paths (X _) = [[]]
paths (Const _) = [[]]
paths (Minus t) = [[]] ++ map (S:) (paths t)
paths (s :+ t) = [[]] ++ map (L:) (paths s) ++ map (R:) (paths t)
paths (s :* t) = [[]] ++ map (L:) (paths s) ++ map (R:) (paths t)
subterm :: Term -> Path -> Term
subterm (Minus t) (S:ps) = subterm t ps
subterm (s :+ _) (L:ps) = subterm s ps
subterm (_ :+ t) (R:ps) = subterm t ps
subterm (s :* _) (L:ps) = subterm s ps
subterm (_ :* t) (R:ps) = subterm t ps
subterm t _ = t
replaceSubterm :: Term -> Path -> Term -> Term
replaceSubterm (Minus t) (S:ps) q = Minus (replaceSubterm t ps q)
replaceSubterm (s :+ t) (L:ps) q = (replaceSubterm s ps q) :+ t
replaceSubterm (s :+ t) (R:ps) q = s :+ (replaceSubterm t ps q)
replaceSubterm (s :* t) (L:ps) q = (replaceSubterm s ps q) :* t
replaceSubterm (s :* t) (R:ps) q = s :* (replaceSubterm t ps q)
replaceSubterm _ _ q = q
interpret :: Term -> VarMap -> Double
interpret t m = interpret' t
where interpret' (X v) = m M.! v
interpret' (Const c) = c
interpret' (Minus q) = - (interpret' q)
interpret' (s :+ q) = interpret' s + interpret' q
interpret' (s :* q) = interpret' s * interpret' q
var :: Int
var = 0
mkLinearTerm :: (Double, Double) -> Term
mkLinearTerm (a, m) = (a' :* x') :+ m'
where a' = if a < 0 then Minus (Const (-a)) else Const a
m' = if m < 0 then Minus (Const (-m)) else Const m
x' = X var
mkQuadraticTerm :: (Double, Double, Double) -> Term
mkQuadraticTerm (a, b, m) = (a' :* x' :* x') :+ (b' :* x') :+ m'
where a' = if a < 0 then Minus (Const (-a)) else Const a
b' = if b < 0 then Minus (Const (-b)) else Const b
m' = if m < 0 then Minus (Const (-m)) else Const m
x' = X var
mkPairs :: [Double] -> [(Double, Double)]
mkPairs [] = []
mkPairs [_] = []
mkPairs (x:y:xs) = (x, y):(mkPairs xs)
mkTripplets :: [Double] -> [(Double, Double, Double)]
mkTripplets (x:y:z:xs) = (x, y, z):(mkTripplets xs)
mkTripplets [_, _] = []
mkTripplets [_] = []
mkTripplets [] = []
mkInitGen :: Int -> IO [Term]
mkInitGen n = do
lcoeffs <- shuf n
qcoeffs <- shuf (n + n `div` 2)
let lts = map mkLinearTerm (mkPairs $ adjust (n `div` 2) lcoeffs)
qts = map mkQuadraticTerm (mkTripplets $ adjust ((n + n `div` 2) `div` 2) qcoeffs)
adjust y = map ((/ fromIntegral (y `div` 2)) . fromIntegral . (y -))
ts = concat $ zipWith f lts qts
f x y = [x, y]
return ts
haveSexAndDie :: (Int, Term) -> (Int, Term) -> [Term]
haveSexAndDie (x, t) (y, s) = [t', s']
where tps = paths t
tp = tps !! (x `mod` length tps)
sps = paths s
sp = sps !! (y `mod` length sps)
t' = replaceSubterm t tp (subterm s sp)
s' = replaceSubterm s sp (subterm t tp)
eucdist :: [Int] -> [([Double], Double)] -> Term -> Double
eucdist vs ys t = val
where (cs, ds) = unzip ys
envs = map (M.fromList . zip vs) cs
val = L.foldl' f 0 (zip ds envs)
f acc (d, env) = acc + (d - (interpret t env))^(2 :: Int)
refs :: [([Double], Double)]
refs = [([-9], -0.7), ([-6.2], 6.2), ([-2.1], -12.9), ([1.0], 0.1), ([2.3], -15.2), ([5.0], 10.1), ([8.9], -0.9)]
instance Genetic Term' Int where
mkInitGeneration = mkInitGen (2^(10 :: Int))
crossover = haveSexAndDie
distance = eucdist [var] refs
|
energyflowanalysis/efa-2.1
|
sandbox/genetic_programming/Polynome.hs
|
bsd-3-clause
| 3,871 | 0 | 18 | 1,018 | 2,068 | 1,128 | 940 | 95 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module Tell (tellAll) where
import Core
import Data.List
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Set as S
tellAll :: M.Map User (Maybe UserMessage) -> M.Map User [UserMessage]
-> ([IRCAction], M.Map User [UserMessage])
tellAll onlineUsers messages = M.foldlWithKey f ([],messages) onlineUsers
where
f acc _ (Just _) = acc
f (acts, msgs) user _ =
let (newActs, newMessages) = tell user msgs
in (newActs++acts, newMessages)
tell :: User -> M.Map User [UserMessage]
-> ([IRCAction], M.Map User [UserMessage])
tell recipient usrMessages =
case M.lookup recipient usrMessages of
Just msgs -> ( tellMessages recipient msgs
, M.delete recipient usrMessages)
Nothing -> ([], usrMessages)
tellMessages :: User -> [UserMessage] -> [IRCAction]
tellMessages recipient usrMessages =
[PrivMsg $ T.concat [ "Hey ", recipient, " you have "
, tShow $ length usrMessages
, " messages:" ]]
++
zipWith (curry makeMessage) [1..] (reverse usrMessages)
where
makeMessage (n, UserMessage
(txt, MessageContext nick _ chan time)) =
PrivMsg $ T.concat [ tShow n, ": ", nick, " said \""
, txt, "\" in ", chan, " at "
, tShow time ]
tShow :: Show a => a -> T.Text
tShow = T.pack . show
|
jchmrt/btjchm
|
Tell.hs
|
mit
| 1,500 | 0 | 11 | 460 | 493 | 269 | 224 | 35 | 2 |
{- |
Module : ./TPTP/Prover/EProver.hs
Description : Interface for the E Theorem Prover.
Copyright : (c) Eugen Kuksa University of Magdeburg 2017
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Eugen Kuksa <[email protected]>
Stability : provisional
Portability : non-portable (imports Logic)
-}
module TPTP.Prover.Darwin (darwin) where
import TPTP.Prover.Common
-- The relevant output of Darwin is the same as the output of EProver.
import TPTP.Prover.EProver.ProofParser (parseTimeUsed)
import TPTP.Prover.ProofParser
import TPTP.Prover.ProverState
import TPTP.Morphism
import TPTP.Sign
import TPTP.Sublogic
import Common.AS_Annotation
import Common.ProofTree
import Interfaces.GenericATPState hiding (proverState)
import Logic.Prover hiding (proofLines)
import Data.Time.LocalTime
import Data.Time.Clock
darwin :: Prover Sign Sentence Morphism Sublogic ProofTree
darwin = mkProver binary_name prover_name sublogics runTheProver
binary_name :: String
binary_name = "darwin"
prover_name :: String
prover_name = "Darwin"
sublogics :: Sublogic
sublogics = FOF
runTheProver :: ProverState
{- ^ logical part containing the input Sign and axioms and possibly
goals that have been proved earlier as additional axioms -}
-> GenericConfig ProofTree -- ^ configuration to use
-> Bool -- ^ True means save TPTP file
-> String -- ^ name of the theory in the DevGraph
-> Named Sentence -- ^ goal to prove
-> IO (ATPRetval, GenericConfig ProofTree)
-- ^ (retval, configuration with proof status and complete output)
runTheProver proverState cfg saveTPTPFile theoryName namedGoal = do
let proverTimeLimitS = show $ getTimeLimit cfg
allOptions = [ "--print-configuration", "false"
, "--print-statistics", "true"
, "--input-format", "tptp"
, "--timeout-cpu", proverTimeLimitS
, "--memory-limit", show (4096 :: Int)
]
problemFileName <-
prepareProverInput proverState cfg saveTPTPFile theoryName namedGoal prover_name
(_, out, wallTimeUsed) <-
executeTheProver binary_name (allOptions ++ [problemFileName])
let szsStatusLine = findSZS out
let reportedTimeUsed = parseTimeUsed out
let resultedTimeUsed =
if reportedTimeUsed == -1
then wallTimeUsed
else timeToTimeOfDay $ secondsToDiffTime $ toInteger reportedTimeUsed
let axiomsUsed = getAxioms proverState
let (atpRetval, resultedProofStatus) =
atpRetValAndProofStatus cfg namedGoal resultedTimeUsed axiomsUsed
szsStatusLine prover_name
return (atpRetval, cfg { proofStatus = resultedProofStatus
, resultOutput = out
, timeUsed = resultedTimeUsed })
|
spechub/Hets
|
TPTP/Prover/Darwin.hs
|
gpl-2.0
| 2,861 | 0 | 12 | 679 | 470 | 261 | 209 | 52 | 2 |
{-# LANGUAGE ForeignFunctionInterface #-}
-- | FreeBSD system-dependent code for 'sendfile'.
module Network.Socket.SendFile.FreeBSD (_sendFile, sendFileIter, sendfile) where
import Data.Int (Int64)
import Foreign.C.Error (eAGAIN, eINTR, getErrno, throwErrno)
import Foreign.C.Types (CInt(..), CSize(..))
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable (peek)
import Network.Socket.SendFile.Iter (Iter(..), runIter)
import System.Posix.Types (COff(..), Fd(..))
-- | automatically loop and send everything
_sendFile :: Fd -> Fd -> Int64 -> Int64 -> IO ()
_sendFile out_fd in_fd off count =
do _ <- runIter (sendFileIter out_fd in_fd (fromIntegral count) (fromIntegral off) (fromIntegral count)) -- set blockSize == count. ie. send it all if we can.
return ()
sendFileIter :: Fd -- ^ file descriptor corresponding to network socket
-> Fd -- ^ file descriptor corresponding to file
-> Int64 -- ^ maximum number of bytes to send at once
-> Int64 -- ^ offset into file
-> Int64 -- ^ total number of bytes to send
-> IO Iter
sendFileIter out_fd in_fd blockSize off count =
sendFileIterI out_fd in_fd (min (fromIntegral blockSize) maxBytes) (fromIntegral off) (fromIntegral count)
sendFileIterI :: Fd -- ^ file descriptor corresponding to network socket
-> Fd -- ^ file descriptor corresponding to file
-> CSize -- ^ maximum number of bytes to send at once
-> COff -- ^ offset into file
-> CSize -- ^ total number of bytes to send
-> IO Iter
sendFileIterI _out_fd _in_fd _blockSize _off 0 = return (Done 0)
sendFileIterI out_fd in_fd blockSize off remaining =
do let bytes = min remaining blockSize
(wouldBlock, nsent) <- alloca $ \sbytes -> sendfileI out_fd in_fd off bytes sbytes
let cont = sendFileIterI out_fd in_fd blockSize (off + nsent) (remaining `safeMinus` (fromIntegral nsent))
case wouldBlock of
True -> return (WouldBlock (fromIntegral nsent) out_fd cont)
False -> return (Sent (fromIntegral nsent) cont)
-- | low-level wrapper around sendfile
-- non-blocking
-- returns number of bytes written and if EAGAIN
-- does not call 'threadWaitWrite'
sendfile :: Fd -> Fd -> Int64 -> Int64 -> IO (Bool, Int64)
sendfile out_fd in_fd off count =
alloca $ \sbytes ->
do (wb, sent) <- sendfileI out_fd in_fd (fromIntegral off) (fromIntegral count) sbytes
return (wb, fromIntegral sent)
-- NOTE: should we retry automatically on EINTR (but not EAGAIN)
sendfileI :: Fd -> Fd -> COff -> CSize -> Ptr COff -> IO (Bool, COff)
sendfileI out_fd in_fd off count sbytes =
do status <- c_sendfile out_fd in_fd off count sbytes
if (status == 0)
then do nsent <- peek sbytes
return (False, nsent)
else do errno <- getErrno
if (errno == eAGAIN) || (errno == eINTR)
then do nsent <- peek sbytes
return (True, nsent)
else throwErrno "Network.Socket.SendFile.FreeBSD.sendfileI"
safeMinus :: (Ord a, Num a) => a -> a -> a
safeMinus x y
| y >= x = 0
| otherwise = x - y
-- max num of bytes in one send
maxBytes :: CSize
maxBytes = maxBound :: CSize
foreign import ccall unsafe "sys/uio.h sendfile" c_sendfile_freebsd
:: Fd -> Fd -> COff -> CSize -> Ptr () -> Ptr COff -> CInt -> IO CInt
c_sendfile :: Fd -> Fd -> COff -> CSize -> Ptr COff -> IO CInt
c_sendfile out_fd in_fd off count sbytes = c_sendfile_freebsd in_fd out_fd off count nullPtr sbytes 0
|
christinem/courseography
|
vendor/sendfile-0.7.9/src/Network/Socket/SendFile/FreeBSD.hs
|
gpl-3.0
| 3,666 | 0 | 14 | 922 | 1,015 | 536 | 479 | 62 | 3 |
---------------------------------------------------------------------------------
--
-- https://github.storm.gatech.edu/NetASM
--
-- File:
-- Hub/Run.hs
--
-- Project:
-- NetASM: A Network Assembly for Orchestrating Programmable Network Devices
--
-- Author:
-- Muhammad Shahbaz
--
-- Copyright notice:
-- Copyright (C) 2014 Georgia Institute of Technology
-- Network Operations and Internet Security Lab
--
-- Licence:
-- This file is a part of the NetASM development base package.
--
-- This file is free code: you can redistribute it and/or modify it under
-- the terms of the GNU Lesser General Public License version 2.1 as
-- published by the Free Software Foundation.
--
-- This package 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
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with the NetASM source package. If not, see
-- http://www.gnu.org/licenses/.
module Apps.Hub.Run where
import Utils.Map
import Core.Language
import Core.PacketParser
import Apps.Hub.Code
----------
-- Hub ---
----------
-- Test header (a.k.a packet) stream
h0 = genHdr([("inport", 1), ("outport", 0)])
h1 = genHdr([("inport", 2), ("outport", 0)])
-- Input sequence
is = [HDR(h0),
HDR(h1)]
-- Emulate the code
emulateEx :: [Hdr]
emulateEx = emulate([], is, c)
-- Profile the code
profileEx :: String
profileEx = profile([], is, c)
-- Main
main = do
putStrLn $ prettyPrint $ emulateEx
putStrLn profileEx
|
8l/NetASM-haskell
|
Apps/Hub/Run.hs
|
gpl-3.0
| 1,792 | 0 | 8 | 417 | 222 | 147 | 75 | 16 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Test.AWS.Support.Internal
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Test.AWS.Support.Internal where
import Test.AWS.Prelude
|
fmapfmapfmap/amazonka
|
amazonka-support/test/Test/AWS/Support/Internal.hs
|
mpl-2.0
| 621 | 0 | 4 | 140 | 25 | 21 | 4 | 4 | 0 |
module PTS.Syntax.Parser.Tests where
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit (assertEqual, assertFailure)
import PTS.Error
import PTS.Syntax
parse text = parseTerm "PTS.Syntax.Parser.Tests" text :: Either [PTSError] PTS.Syntax.Term
testParser :: String -> Term -> Test
testParser text term = testCase text $ case parse text of
Right parsedTerm -> assertEqual "Unexpected parse result." (showPretty term) (showPretty parsedTerm)
Left error -> assertFailure $ "Unexpected parse error: " ++ show error
x :: Name
x = read "x"
y :: Name
y = read "y"
z :: Name
z = read "z"
e :: Name
e = read "e"
f :: Name
f = read "f"
tests
= testGroup "PTS.Parser"
[ testParser "Int" (mkConst int)
, testParser "*" (mkConst star)
, testParser "**" (mkConst box)
, testParser "x" (mkVar x)
, testParser "y" (mkVar y)
, testParser "z" (mkVar z)
, testParser "x y" (mkApp (mkVar x) (mkVar y))
, testParser "x y z" (mkApp (mkApp (mkVar x) (mkVar y)) (mkVar z))
, testParser "x (y z)" (mkApp (mkVar x) (mkApp (mkVar y) (mkVar z)))
, testParser "x -> y" (mkPi x (mkVar x) (mkVar y))
, testParser "x -> y -> z" (mkPi x (mkVar x) (mkPi y (mkVar y) (mkVar z)))
, testParser "x y -> z" (mkPi x (mkApp (mkVar x) (mkVar y)) (mkVar z))
, testParser "x (y -> z)" (mkApp (mkVar x) (mkPi y (mkVar y) (mkVar z)))
, testParser "Pi x : x . x" (mkPi x (mkVar x) (mkVar x))
, testParser "Pi x : y . x" (mkPi x (mkVar y) (mkVar x))
, testParser "Pi x : y . Pi y : x . y" (mkPi x (mkVar y) (mkPi y (mkVar x) (mkVar y)))
, testParser "x -> Pi x : y . x" (mkPi x (mkVar x) (mkPi x (mkVar y) (mkVar x)))
, testParser "Pi x : y . x -> z" (mkPi x (mkVar y) (mkPi y (mkVar x) (mkVar z)))
, testParser "(Pi x : y . x) -> z" (mkPi x (mkPi x (mkVar y) (mkVar x)) (mkVar z))
, testParser "lambda x : x . x" (mkLam x (mkVar x) (mkVar x))
, testParser "lambda x : y . x" (mkLam x (mkVar y) (mkVar x))
, testParser "lambda x : y . lambda y : x . y" (mkLam x (mkVar y) (mkLam y (mkVar x) (mkVar y)))
, testParser "Pi (x : y) (y : x) . y" (mkPi x (mkVar y) (mkPi y (mkVar x) (mkVar y)))
, testParser "lambda (x : y) (y : x) . y" (mkLam x (mkVar y) (mkLam y (mkVar x) (mkVar y)))
, testParser "lambda (x : e) (y z : f) . x" (mkLam x (mkVar e) (mkLam y (mkVar f) (mkLam z (mkVar f) (mkVar x))))
, testParser "_" (mkInfer 0)
, testParser "_1" (mkInfer 1)
, testParser "lambda x : _ . x" (mkLam x (mkInfer 0) (mkVar x))
, testParser "lambda x . x" (mkLam x (mkInfer 0) (mkVar x))
, testParser "lambda x y : _ . x" (mkLam x (mkInfer 0) (mkLam y (mkInfer 0) (mkVar x)))
, testParser "lambda (x y : _) . x" (mkLam x (mkInfer 0) (mkLam y (mkInfer 0) (mkVar x)))
, testParser "lambda (x y) . x" (mkLam x (mkInfer 0) (mkLam y (mkInfer 0) (mkVar x)))
, testParser "lambda x (y) . x" (mkLam x (mkInfer 0) (mkLam y (mkInfer 1) (mkVar x)))
, testParser "lambda (x) y . x" (mkLam x (mkInfer 0) (mkLam y (mkInfer 1) (mkVar x)))
, testParser "lambda x (y : _) . x" (mkLam x (mkInfer 0) (mkLam y (mkInfer 1) (mkVar x)))
, testParser "lambda (x : _) y . x" (mkLam x (mkInfer 0) (mkLam y (mkInfer 1) (mkVar x)))
, testParser "_ _" (mkApp (mkInfer 0) (mkInfer 1))
, testParser "_1 _" (mkApp (mkInfer 1) (mkInfer 0))
, testParser "_ _2 _ _ _3 _700 _" (mkApp (mkApp (mkApp (mkApp (mkApp (mkApp (mkInfer 0) (mkInfer 2)) (mkInfer 1)) (mkInfer 4)) (mkInfer 3)) (mkInfer 700)) (mkInfer 5))
, testParser "_2 _2" (mkApp (mkInfer 2) (mkInfer 2))
]
|
Blaisorblade/pts
|
src-test/PTS/Syntax/Parser/Tests.hs
|
bsd-3-clause
| 3,678 | 0 | 21 | 942 | 1,694 | 855 | 839 | 63 | 2 |
module B1.Program.Chart.Colors
( black4
, blue4
, darkBlue3
, lightBlue4
, lighterBlue4
, gray4
, green3
, green4
, red3
, red4
, purple3
, purple4
, white3
, white4
, yellow3
, yellow4
, color3ToList
, outlineColor
) where
import Graphics.Rendering.OpenGL
import Graphics.UI.GLFW
import B1.Graphics.Rendering.OpenGL.Box
import B1.Graphics.Rendering.OpenGL.Utils
import B1.Program.Chart.Resources
black4 :: GLfloat -> Color4 GLfloat
black4 = color4 0 0 0
blue4 :: GLfloat -> Color4 GLfloat
blue4 = color4 0 0.25 0.5
darkBlue3 :: Color3 GLfloat
darkBlue3 = color3 0 0.05 0.15
lightBlue4 :: GLfloat -> Color4 GLfloat
lightBlue4 = color4 0 0.25 0.75
lighterBlue4 :: GLfloat -> Color4 GLfloat
lighterBlue4 = color4 0 0.25 1
gray4 :: GLfloat -> Color4 GLfloat
gray4 = color4 0.5 0.5 0.5
green3 :: Color3 GLfloat
green3 = color3 0.25 1 0
green4 :: GLfloat -> Color4 GLfloat
green4 = color4 0.25 1 0
red3 :: Color3 GLfloat
red3 = color3 1 0.3 0
red4 :: GLfloat -> Color4 GLfloat
red4 = color4 1 0.3 0
purple3 :: Color3 GLfloat
purple3 = color3 0.5 0 1
purple4 :: GLfloat -> Color4 GLfloat
purple4 = color4 0.5 0 1
white3 :: Color3 GLfloat
white3 = color3 1 1 1
white4 :: GLfloat -> Color4 GLfloat
white4 = color4 1 1 1
yellow3 :: Color3 GLfloat
yellow3 = color3 1 1 0
yellow4 :: GLfloat -> Color4 GLfloat
yellow4 = color4 1 1 0
color3ToList :: Color3 GLfloat -> [GLfloat]
color3ToList (Color3 r g b) = r:g:b:[]
outlineColor :: Resources -> Box -> GLfloat -> Color4 GLfloat
outlineColor resources@Resources { mousePosition = mousePosition } bounds
| clicked = lighterBlue4
| hover = lightBlue4
| otherwise = blue4
where
-- TODO: Make helper method for hover and click states.
hover = boxContains bounds mousePosition
clicked = hover && isMouseButtonClicked resources ButtonLeft
|
madjestic/b1
|
src/B1/Program/Chart/Colors.hs
|
bsd-3-clause
| 1,852 | 0 | 9 | 378 | 599 | 318 | 281 | 65 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE RoleAnnotations #-}
#endif
-- |
-- Module : System.Random.PCG.Fast
-- Copyright : Copyright (c) 2014-2015, Christopher Chalmers <[email protected]>
-- License : BSD3
-- Maintainer : Christopher Chalmers <[email protected]>
-- Stability : experimental
-- Portability: CPP, FFI
--
-- Fast variant of the PCG random number generator. This module performs
-- around 20% faster than the multiple streams version but produces slightly
-- lower quality (still good) random numbers.
--
-- See <http://www.pcg-random.org> for details.
--
-- @
-- import Control.Monad.ST
-- import System.Random.PCG.Fast
--
-- three :: [Double]
-- three = runST $ do
-- g <- create
-- a <- uniform g
-- b <- uniform g
-- c <- uniform g
-- return [a,b,c]
-- @
module System.Random.PCG.Fast
( -- * Gen
Gen, GenIO, GenST
, create, createSystemRandom, initialize
, withSystemRandom, withFrozen
-- * Getting random numbers
, Variate (..)
, advance, retract
-- * Seeds
, FrozenGen, save, restore, seed, initFrozen
-- * Type restricted versions
-- ** uniform
, uniformW8, uniformW16, uniformW32, uniformW64
, uniformI8, uniformI16, uniformI32, uniformI64
, uniformF, uniformD, uniformBool
-- ** uniformR
, uniformRW8, uniformRW16, uniformRW32, uniformRW64
, uniformRI8, uniformRI16, uniformRI32, uniformRI64
, uniformRF, uniformRD, uniformRBool
-- ** uniformB
, uniformBW8, uniformBW16, uniformBW32, uniformBW64
, uniformBI8, uniformBI16, uniformBI32, uniformBI64
, uniformBF, uniformBD, uniformBBool
) where
import Control.Applicative
import Control.Monad.Primitive
import Control.Monad.ST
import Data.Data
import Foreign
import GHC.Generics
import System.IO.Unsafe
import System.Random
import System.Random.PCG.Class
-- $setup
-- >>> import System.Random.PCG.Fast
-- >>> import System.Random.PCG.Class
-- >>> import Control.Monad
------------------------------------------------------------------------
-- Seed
------------------------------------------------------------------------
-- | Immutable state of a random number generator. Suitable for storing
-- for later use.
newtype FrozenGen = FrozenGen Word64
deriving (Show, Eq, Ord, Storable, Data, Typeable, Generic)
-- | Save the state of a 'Gen' in a 'Seed'.
save :: PrimMonad m => Gen (PrimState m) -> m FrozenGen
save (Gen p) = unsafePrimToPrim (peek p)
{-# INLINE save #-}
-- | Restore a 'Gen' from a 'Seed'.
restore :: PrimMonad m => FrozenGen -> m (Gen (PrimState m))
restore s = unsafePrimToPrim $ do
p <- malloc
poke p s
return (Gen p)
{-# INLINE restore #-}
-- | Generate a new seed using single 'Word64'.
--
-- >>> initFrozen 0
-- FrozenGen 1
initFrozen :: Word64 -> FrozenGen
initFrozen w = unsafeDupablePerformIO $ do
p <- malloc
pcg32f_srandom_r p w
peek p <* free p
{-# INLINE initFrozen #-}
-- | Standard initial seed.
seed :: FrozenGen
seed = FrozenGen 0xcafef00dd15ea5e5
-- | Create a 'Gen' from a fixed initial seed.
create :: PrimMonad m => m (Gen (PrimState m))
create = restore seed
------------------------------------------------------------------------
-- Gen
------------------------------------------------------------------------
-- | State of the random number generator
newtype Gen s = Gen (Ptr FrozenGen)
deriving (Eq, Ord)
#if __GLASGOW_HASKELL__ >= 707
type role Gen representational
#endif
type GenIO = Gen RealWorld
type GenST = Gen
-- | Initialize a generator a single word.
--
-- >>> initialize 0 >>= save
-- FrozenGen 1
initialize :: PrimMonad m => Word64 -> m (Gen (PrimState m))
initialize a = unsafePrimToPrim $ do
p <- malloc
pcg32f_srandom_r p a
return (Gen p)
-- | Seed with system random number. (@\/dev\/urandom@ on Unix-like
-- systems and CryptAPI on Windows).
withSystemRandom :: (GenIO -> IO a) -> IO a
withSystemRandom f = do
w <- sysRandom
initialize w >>= f
-- | Run an action with a frozen generator, returning the result and the
-- new frozen generator.
withFrozen :: FrozenGen -> (forall s. Gen s -> ST s a) -> (a, FrozenGen)
withFrozen s f = runST $ restore s >>= \g -> liftA2 (,) (f g) (save g)
-- | Seed a PRNG with data from the system's fast source of pseudo-random
-- numbers. All the caveats of 'withSystemRandom' apply here as well.
createSystemRandom :: IO GenIO
createSystemRandom = withSystemRandom (return :: GenIO -> IO GenIO)
-- | Advance the given generator n steps in log(n) time. (Note that a
-- \"step\" is a single random 32-bit (or less) 'Variate'. Data types
-- such as 'Double' or 'Word64' require two \"steps\".)
--
-- >>> create >>= \g -> replicateM_ 1000 (uniformW32 g) >> uniformW32 g
-- 3725702568
-- >>> create >>= \g -> replicateM_ 500 (uniformD g) >> uniformW32 g
-- 3725702568
-- >>> create >>= \g -> advance 1000 g >> uniformW32 g
-- 3725702568
advance :: PrimMonad m => Word64 -> Gen (PrimState m) -> m ()
advance u (Gen p) = unsafePrimToPrim $ pcg32f_advance_r p u
{-# INLINE advance #-}
-- | Retract the given generator n steps in log(2^64-n) time. This
-- is just @advance (-n)@.
--
-- >>> create >>= \g -> replicateM 3 (uniformW32 g)
-- [2951688802,2698927131,361549788]
-- >>> create >>= \g -> retract 1 g >> replicateM 3 (uniformW32 g)
-- [954135925,2951688802,2698927131]
retract :: PrimMonad m => Word64 -> Gen (PrimState m) -> m ()
retract u g = advance (-u) g
{-# INLINE retract #-}
------------------------------------------------------------------------
-- Foreign calls
------------------------------------------------------------------------
foreign import ccall unsafe "pcg_mcg_64_srandom_r"
pcg32f_srandom_r :: Ptr FrozenGen -> Word64 -> IO ()
foreign import ccall unsafe "pcg_mcg_64_xsh_rs_32_random_r"
pcg32f_random_r :: Ptr FrozenGen -> IO Word32
foreign import ccall unsafe "pcg_mcg_64_xsh_rs_32_boundedrand_r"
pcg32f_boundedrand_r :: Ptr FrozenGen -> Word32 -> IO Word32
foreign import ccall unsafe "pcg_mcg_64_advance_r"
pcg32f_advance_r :: Ptr FrozenGen -> Word64 -> IO ()
------------------------------------------------------------------------
-- Instances
------------------------------------------------------------------------
instance (PrimMonad m, s ~ PrimState m) => Generator (Gen s) m where
uniform1 f (Gen p) = unsafePrimToPrim $ f <$> pcg32f_random_r p
{-# INLINE uniform1 #-}
uniform2 f (Gen p) = unsafePrimToPrim $ do
w1 <- pcg32f_random_r p
w2 <- pcg32f_random_r p
return $ f w1 w2
{-# INLINE uniform2 #-}
uniform1B f b (Gen p) = unsafePrimToPrim $ f <$> pcg32f_boundedrand_r p b
{-# INLINE uniform1B #-}
instance RandomGen FrozenGen where
next s = unsafeDupablePerformIO $ do
p <- malloc
poke p s
w1 <- pcg32f_random_r p
w2 <- pcg32f_random_r p
s' <- peek p
free p
return (wordsTo64Bit w1 w2, s')
{-# INLINE next #-}
split s = unsafeDupablePerformIO $ do
p <- malloc
poke p s
w1 <- pcg32f_random_r p
w2 <- pcg32f_random_r p
w3 <- pcg32f_random_r p
w4 <- pcg32f_random_r p
pcg32f_srandom_r p (wordsTo64Bit w1 w2)
s1 <- peek p
pcg32f_srandom_r p (wordsTo64Bit w3 w4)
s2 <- peek p
free p
return (s1,s2)
|
rrnewton/pcg-random
|
src/System/Random/PCG/Fast.hs
|
bsd-3-clause
| 7,598 | 0 | 11 | 1,473 | 1,452 | 789 | 663 | 120 | 1 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnliftedFFITypes #-}
module Foundation.System.Bindings.Hs
where
import GHC.IO
import Basement.Compat.C.Types
foreign import ccall unsafe "HsBase.h __hscore_get_errno" sysHsCoreGetErrno :: IO CInt
|
vincenthz/hs-foundation
|
foundation/Foundation/System/Bindings/Hs.hs
|
bsd-3-clause
| 271 | 0 | 6 | 35 | 40 | 26 | 14 | 7 | 0 |
module Fay.Types.ModulePath
( ModulePath (..)
, mkModulePath
, mkModulePaths
, mkModulePathFromQName
) where
import Fay.Compiler.QName
import qualified Fay.Exts as F
import Data.List
import Data.List.Split
import Language.Haskell.Exts.Annotated
-- | The name of a module split into a list for code generation.
newtype ModulePath = ModulePath { unModulePath :: [String] }
deriving (Eq, Ord, Show)
-- | Construct the complete ModulePath from a ModuleName.
mkModulePath :: ModuleName a -> ModulePath
mkModulePath (ModuleName _ m) = ModulePath . splitOn "." $ m
-- | Construct intermediate module paths from a ModuleName.
-- mkModulePaths "A.B" => [["A"], ["A","B"]]
mkModulePaths :: ModuleName a -> [ModulePath]
mkModulePaths (ModuleName _ m) = map ModulePath . tail . inits . splitOn "." $ m
-- | Converting a QName to a ModulePath is only relevant for constructors since
-- they can conflict with module names.
mkModulePathFromQName :: QName a -> ModulePath
mkModulePathFromQName (Qual _ (ModuleName _ m) n) = mkModulePath $ ModuleName F.noI $ m ++ "." ++ unname n
mkModulePathFromQName _ = error "mkModulePathFromQName: Not a qualified name"
|
beni55/fay
|
src/Fay/Types/ModulePath.hs
|
bsd-3-clause
| 1,223 | 0 | 10 | 252 | 259 | 144 | 115 | 19 | 1 |
{-----------------------------------------------------------------------------
A LIBRARY OF MONADIC PARSER COMBINATORS
29th July 1996
Graham Hutton Erik Meijer
University of Nottingham University of Utrecht
This Haskell 1.3 script defines a library of parser combinators, and is taken
from sections 1-6 of our article "Monadic Parser Combinators". Some changes
to the library have been made in the move from Gofer to Haskell:
* Do notation is used in place of monad comprehension notation;
* The parser datatype is defined using "newtype", to avoid the overhead
of tagging and untagging parsers with the P constructor.
------------------------------------------------------------------------------
** Extended to allow a symbol table/state to be threaded through the monad.
** Extended to allow a parameterised token type, rather than just strings.
** Extended to allow error-reporting.
(Extensions: 1998-2000 [email protected])
(More extensions: 2004 [email protected])
------------------------------------------------------------------------------}
-- | This library of monadic parser combinators is based on the ones
-- defined by Graham Hutton and Erik Meijer. It has been extended by
-- Malcolm Wallace to use an abstract token type (no longer just a
-- string) as input, and to incorporate a State Transformer monad, useful
-- for symbol tables, macros, and so on. Basic facilities for error
-- reporting have also been added, and later extended by Graham Klyne
-- to return the errors through an @Either@ type, rather than just
-- calling @error@.
module Text.ParserCombinators.HuttonMeijerWallace
(
-- * The parser monad
Parser(..)
-- * Primitive parser combinators
, item, eof, papply, papply'
-- * Derived combinators
, (+++), {-sat,-} tok, nottok, many, many1
, sepby, sepby1, chainl, chainl1, chainr, chainr1, ops, bracket
, toEOF
-- * Error handling
, elserror
-- * State handling
, stupd, stquery, stget
-- * Re-parsing
, reparse
) where
import Char
import Monad
infixr 5 +++
--- The parser monad ---------------------------------------------------------
type ParseResult s t e a = Either e [(a,s,[Either e t])]
newtype Parser s t e a = P ( s -> [Either e t] -> ParseResult s t e a )
-- ^ The parser type is parametrised on the types of the state @s@,
-- the input tokens @t@, error-type @e@, and the result value @a@.
-- The state and remaining input are threaded through the monad.
instance Functor (Parser s t e) where
-- fmap :: (a -> b) -> (Parser s t e a -> Parser s t e b)
fmap f (P p) = P (\st inp -> case p st inp of
Right res -> Right [(f v, s, out) | (v,s,out) <- res]
Left err -> Left err
)
instance Monad (Parser s t e) where
-- return :: a -> Parser s t e a
return v = P (\st inp -> Right [(v,st,inp)])
-- >>= :: Parser s t e a -> (a -> Parser s t e b) -> Parser s t e b
(P p) >>= f = P (\st inp -> case p st inp of
Right res -> foldr joinresults (Right [])
[ papply' (f v) s out | (v,s,out) <- res ]
Left err -> Left err
)
-- fail :: String -> Parser s t e a
fail err = P (\st inp -> Right [])
-- I know it's counterintuitive, but we want no-parse, not an error.
instance MonadPlus (Parser s t e) where
-- mzero :: Parser s t e a
mzero = P (\st inp -> Right [])
-- mplus :: Parser s t e a -> Parser s t e a -> Parser s t e a
(P p) `mplus` (P q) = P (\st inp -> joinresults (p st inp) (q st inp))
-- joinresults ensures that explicitly raised errors are dominant,
-- provided no parse has yet been found. The commented out code is
-- a slightly stricter specification of the real code.
joinresults :: ParseResult s t e a -> ParseResult s t e a -> ParseResult s t e a
{-
joinresults (Left p) (Left q) = Left p
joinresults (Left p) (Right _) = Left p
joinresults (Right []) (Left q) = Left q
joinresults (Right p) (Left q) = Right p
joinresults (Right p) (Right q) = Right (p++q)
-}
joinresults (Left p) q = Left p
joinresults (Right []) q = q
joinresults (Right p) q = Right (p++ case q of Left _ -> []
Right r -> r)
--- Primitive parser combinators ---------------------------------------------
-- | Deliver the first remaining token.
item :: Parser s t e t
item = P (\st inp -> case inp of
[] -> Right []
(Left e: _) -> Left e
(Right x: xs) -> Right [(x,st,xs)]
)
-- | Fail if end of input is not reached
eof :: Show p => Parser s (p,t) String ()
eof = P (\st inp -> case inp of
[] -> Right [((),st,[])]
(Left e:_) -> Left e
(Right (p,_):_) -> Left ("End of input expected at "
++show p++"\n but found text")
)
{-
-- | Ensure the value delivered by the parser is evaluated to WHNF.
force :: Parser s t e a -> Parser s t e a
force (P p) = P (\st inp -> let Right xs = p st inp
h = head xs in
h `seq` Right (h: tail xs)
)
-- [[[GK]]] ^^^^^^
-- WHNF = Weak Head Normal Form, meaning that it has no top-level redex.
-- In this case, I think that means that the first element of the list
-- is fully evaluated.
--
-- NOTE: the original form of this function fails if there is no parse
-- result for p st inp (head xs fails if xs is null), so the modified
-- form can assume a Right value only.
--
-- Why is this needed?
-- It's not exported, and the only use of this I see is commented out.
---------------------------------------
-}
-- | Deliver the first parse result only, eliminating any backtracking.
first :: Parser s t e a -> Parser s t e a
first (P p) = P (\st inp -> case p st inp of
Right (x:xs) -> Right [x]
otherwise -> otherwise
)
-- | Apply the parser to some real input, given an initial state value.
-- If the parser fails, raise 'error' to halt the program.
-- (This is the original exported behaviour - to allow the caller to
-- deal with the error differently, see @papply'@.)
papply :: Parser s t String a -> s -> [Either String t]
-> [(a,s,[Either String t])]
papply (P p) st inp = either error id (p st inp)
-- | Apply the parser to some real input, given an initial state value.
-- If the parser fails, return a diagnostic message to the caller.
papply' :: Parser s t e a -> s -> [Either e t]
-> Either e [(a,s,[Either e t])]
papply' (P p) st inp = p st inp
--- Derived combinators ------------------------------------------------------
-- | A choice between parsers. Keep only the first success.
(+++) :: Parser s t e a -> Parser s t e a -> Parser s t e a
p +++ q = first (p `mplus` q)
-- | Deliver the first token if it satisfies a predicate.
sat :: (t -> Bool) -> Parser s (p,t) e t
sat p = do {(_,x) <- item; if p x then return x else mzero}
-- | Deliver the first token if it equals the argument.
tok :: Eq t => t -> Parser s (p,t) e t
tok t = do {(_,x) <- item; if x==t then return t else mzero}
-- | Deliver the first token if it does not equal the argument.
nottok :: Eq t => [t] -> Parser s (p,t) e t
nottok ts = do {(_,x) <- item; if x `notElem` ts then return x
else mzero}
-- | Deliver zero or more values of @a@.
many :: Parser s t e a -> Parser s t e [a]
many p = many1 p +++ return []
--many p = force (many1 p +++ return [])
-- | Deliver one or more values of @a@.
many1 :: Parser s t e a -> Parser s t e [a]
many1 p = do {x <- p; xs <- many p; return (x:xs)}
-- | Deliver zero or more values of @a@ separated by @b@'s.
sepby :: Parser s t e a -> Parser s t e b -> Parser s t e [a]
p `sepby` sep = (p `sepby1` sep) +++ return []
-- | Deliver one or more values of @a@ separated by @b@'s.
sepby1 :: Parser s t e a -> Parser s t e b -> Parser s t e [a]
p `sepby1` sep = do {x <- p; xs <- many (do {sep; p}); return (x:xs)}
chainl :: Parser s t e a -> Parser s t e (a->a->a) -> a
-> Parser s t e a
chainl p op v = (p `chainl1` op) +++ return v
chainl1 :: Parser s t e a -> Parser s t e (a->a->a) -> Parser s t e a
p `chainl1` op = do {x <- p; rest x}
where
rest x = do {f <- op; y <- p; rest (f x y)}
+++ return x
chainr :: Parser s t e a -> Parser s t e (a->a->a) -> a
-> Parser s t e a
chainr p op v = (p `chainr1` op) +++ return v
chainr1 :: Parser s t e a -> Parser s t e (a->a->a) -> Parser s t e a
p `chainr1` op = do {x <- p; rest x}
where
rest x = do { f <- op
; y <- p `chainr1` op
; return (f x y)
}
+++ return x
ops :: [(Parser s t e a, b)] -> Parser s t e b
ops xs = foldr1 (+++) [do {p; return op} | (p,op) <- xs]
bracket :: (Show p,Show t) =>
Parser s (p,t) e a -> Parser s (p,t) e b ->
Parser s (p,t) e c -> Parser s (p,t) e b
bracket open p close = do { open
; x <- p
; close -- `elserror` "improperly matched construct";
; return x
}
-- | Accept a complete parse of the input only, no partial parses.
toEOF :: Show p =>
Parser s (p,t) String a -> Parser s (p,t) String a
toEOF p = do { x <- p; eof; return x }
--- Error handling -----------------------------------------------------------
-- | Return an error using the supplied diagnostic string, and a token type
-- which includes position information.
parseerror :: (Show p,Show t) => String -> Parser s (p,t) String a
parseerror err = P (\st inp ->
case inp of
[] -> Left "Parse error: unexpected EOF\n"
(Left e:_) -> Left ("Lexical error: "++e)
(Right (p,t):_) ->
Left ("Parse error: in "++show p++"\n "
++err++"\n "++"Found "++show t)
)
-- | If the parser fails, generate an error message.
elserror :: (Show p,Show t) => Parser s (p,t) String a -> String
-> Parser s (p,t) String a
p `elserror` s = p +++ parseerror s
--- State handling -----------------------------------------------------------
-- | Update the internal state.
stupd :: (s->s) -> Parser s t e ()
stupd f = P (\st inp-> {-let newst = f st in newst `seq`-}
Right [((), f st, inp)])
-- | Query the internal state.
stquery :: (s->a) -> Parser s t e a
stquery f = P (\st inp-> Right [(f st, st, inp)])
-- | Deliver the entire internal state.
stget :: Parser s t e s
stget = P (\st inp-> Right [(st, st, inp)])
--- Push some tokens back onto the input stream and reparse ------------------
-- | This is useful for recursively expanding macros. When the
-- user-parser recognises a macro use, it can lookup the macro
-- expansion from the parse state, lex it, and then stuff the
-- lexed expansion back down into the parser.
reparse :: [Either e t] -> Parser s t e ()
reparse ts = P (\st inp-> Right [((), st, ts++inp)])
------------------------------------------------------------------------------
|
FranklinChen/hugs98-plus-Sep2006
|
packages/HaXml/src/Text/ParserCombinators/HuttonMeijerWallace.hs
|
bsd-3-clause
| 12,608 | 0 | 19 | 4,517 | 3,048 | 1,621 | 1,427 | 120 | 3 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "dist/dist-sandbox-261cd265/build/System/Posix/ByteString/FilePath.hs" #-}
{-# LINE 1 "System/Posix/ByteString/FilePath.hsc" #-}
{-# LINE 2 "System/Posix/ByteString/FilePath.hsc" #-}
{-# LANGUAGE Safe #-}
{-# LINE 6 "System/Posix/ByteString/FilePath.hsc" #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Posix.ByteString.FilePath
-- Copyright : (c) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : non-portable (requires POSIX)
--
-- Internal stuff: support for ByteString FilePaths
--
-----------------------------------------------------------------------------
module System.Posix.ByteString.FilePath (
RawFilePath, withFilePath, peekFilePath, peekFilePathLen,
throwErrnoPathIfMinus1Retry,
throwErrnoPathIfMinus1Retry_,
throwErrnoPathIfNullRetry,
throwErrnoPathIfRetry,
throwErrnoPath,
throwErrnoPathIf,
throwErrnoPathIf_,
throwErrnoPathIfNull,
throwErrnoPathIfMinus1,
throwErrnoPathIfMinus1_
) where
import Foreign hiding ( void )
import Foreign.C hiding (
throwErrnoPath,
throwErrnoPathIf,
throwErrnoPathIf_,
throwErrnoPathIfNull,
throwErrnoPathIfMinus1,
throwErrnoPathIfMinus1_ )
import Control.Monad
import Data.ByteString
import Data.ByteString.Char8 as BC
import Prelude hiding (FilePath)
-- | A literal POSIX file path
type RawFilePath = ByteString
withFilePath :: RawFilePath -> (CString -> IO a) -> IO a
withFilePath = useAsCString
peekFilePath :: CString -> IO RawFilePath
peekFilePath = packCString
peekFilePathLen :: CStringLen -> IO RawFilePath
peekFilePathLen = packCStringLen
throwErrnoPathIfMinus1Retry :: (Eq a, Num a)
=> String -> RawFilePath -> IO a -> IO a
throwErrnoPathIfMinus1Retry loc path f = do
throwErrnoPathIfRetry (== -1) loc path f
throwErrnoPathIfMinus1Retry_ :: (Eq a, Num a)
=> String -> RawFilePath -> IO a -> IO ()
throwErrnoPathIfMinus1Retry_ loc path f =
void $ throwErrnoPathIfRetry (== -1) loc path f
throwErrnoPathIfNullRetry :: String -> RawFilePath -> IO (Ptr a) -> IO (Ptr a)
throwErrnoPathIfNullRetry loc path f =
throwErrnoPathIfRetry (== nullPtr) loc path f
throwErrnoPathIfRetry :: (a -> Bool) -> String -> RawFilePath -> IO a -> IO a
throwErrnoPathIfRetry pr loc rpath f =
do
res <- f
if pr res
then do
err <- getErrno
if err == eINTR
then throwErrnoPathIfRetry pr loc rpath f
else throwErrnoPath loc rpath
else return res
-- | as 'throwErrno', but exceptions include the given path when appropriate.
--
throwErrnoPath :: String -> RawFilePath -> IO a
throwErrnoPath loc path =
do
errno <- getErrno
ioError (errnoToIOError loc errno Nothing (Just (BC.unpack path)))
-- | as 'throwErrnoIf', but exceptions include the given path when
-- appropriate.
--
throwErrnoPathIf :: (a -> Bool) -> String -> RawFilePath -> IO a -> IO a
throwErrnoPathIf cond loc path f =
do
res <- f
if cond res then throwErrnoPath loc path else return res
-- | as 'throwErrnoIf_', but exceptions include the given path when
-- appropriate.
--
throwErrnoPathIf_ :: (a -> Bool) -> String -> RawFilePath -> IO a -> IO ()
throwErrnoPathIf_ cond loc path f = void $ throwErrnoPathIf cond loc path f
-- | as 'throwErrnoIfNull', but exceptions include the given path when
-- appropriate.
--
throwErrnoPathIfNull :: String -> RawFilePath -> IO (Ptr a) -> IO (Ptr a)
throwErrnoPathIfNull = throwErrnoPathIf (== nullPtr)
-- | as 'throwErrnoIfMinus1', but exceptions include the given path when
-- appropriate.
--
throwErrnoPathIfMinus1 :: (Eq a, Num a) => String -> RawFilePath -> IO a -> IO a
throwErrnoPathIfMinus1 = throwErrnoPathIf (== -1)
-- | as 'throwErrnoIfMinus1_', but exceptions include the given path when
-- appropriate.
--
throwErrnoPathIfMinus1_ :: (Eq a, Num a) => String -> RawFilePath -> IO a -> IO ()
throwErrnoPathIfMinus1_ = throwErrnoPathIf_ (== -1)
|
phischu/fragnix
|
tests/packages/scotty/System.Posix.ByteString.FilePath.hs
|
bsd-3-clause
| 4,193 | 0 | 14 | 811 | 887 | 481 | 406 | 74 | 3 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Hints
-- Copyright : (c) Sven Panne 2002-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- This module corresponds to section 5.6 (Hints) of the OpenGL 2.1 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Hints (
HintTarget(..), HintMode(..), hint
) where
import Graphics.Rendering.OpenGL.GL.QueryUtils
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.Raw
--------------------------------------------------------------------------------
data HintTarget =
PerspectiveCorrection
| PointSmooth
| LineSmooth
| PolygonSmooth
| Fog
| GenerateMipmap
| TextureCompression
| PackCMYK
| UnpackCMYK
deriving ( Eq, Ord, Show )
marshalHintTarget :: HintTarget -> GLenum
marshalHintTarget x = case x of
PerspectiveCorrection -> gl_PERSPECTIVE_CORRECTION_HINT
PointSmooth -> gl_POINT_SMOOTH_HINT
LineSmooth -> gl_LINE_SMOOTH_HINT
PolygonSmooth -> gl_POLYGON_SMOOTH_HINT
Fog -> gl_FOG_HINT
GenerateMipmap -> gl_GENERATE_MIPMAP_HINT
TextureCompression -> gl_TEXTURE_COMPRESSION_HINT
PackCMYK -> gl_PACK_CMYK_HINT
UnpackCMYK -> gl_UNPACK_CMYK_HINT
hintTargetToGetPName :: HintTarget -> PName1I
hintTargetToGetPName x = case x of
PerspectiveCorrection -> GetPerspectiveCorrectionHint
PointSmooth -> GetPointSmoothHint
LineSmooth -> GetLineSmoothHint
PolygonSmooth -> GetPolygonSmoothHint
Fog -> GetFogHint
GenerateMipmap -> GetGenerateMipmapHint
TextureCompression -> GetTextureCompressionHint
PackCMYK -> GetPackCMYKHint
UnpackCMYK -> GetUnpackCMYKHint
--------------------------------------------------------------------------------
data HintMode =
DontCare
| Fastest
| Nicest
deriving ( Eq, Ord, Show )
marshalHintMode :: HintMode -> GLenum
marshalHintMode x = case x of
DontCare -> gl_DONT_CARE
Fastest -> gl_FASTEST
Nicest -> gl_NICEST
unmarshalHintMode :: GLenum -> HintMode
unmarshalHintMode x
| x == gl_DONT_CARE = DontCare
| x == gl_FASTEST = Fastest
| x == gl_NICEST = Nicest
| otherwise = error ("unmarshalHintMode: illegal value " ++ show x)
--------------------------------------------------------------------------------
hint :: HintTarget -> StateVar HintMode
hint t =
makeStateVar
(getEnum1 unmarshalHintMode (hintTargetToGetPName t))
(glHint (marshalHintTarget t) . marshalHintMode)
|
IreneKnapp/direct-opengl
|
Graphics/Rendering/OpenGL/GL/Hints.hs
|
bsd-3-clause
| 2,666 | 0 | 10 | 429 | 460 | 255 | 205 | 59 | 9 |
{-# LANGUAGE CPP #-}
{- |
Module : $Header$
Description : creating Isabelle thoeries via translations
Copyright : (c) C. Maeder, Uni Bremen 2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(Logic)
dumping a LibEnv to Isabelle theory files
-}
module Isabelle.CreateTheories where
import Common.Result
import Common.AS_Annotation
import Logic.Coerce
import Logic.Comorphism
import Static.GTheory
import Logic.Prover
import Common.ExtSign
import Common.ProofUtils
import Isabelle.IsaSign
import Isabelle.Translate
import Isabelle.Logic_Isabelle
import CASL.Logic_CASL
import HasCASL.Logic_HasCASL
import Comorphisms.CASL2PCFOL
import Comorphisms.CASL2HasCASL
import Comorphisms.PCoClTyConsHOL2PairsInIsaHOL
import Comorphisms.HasCASL2PCoClTyConsHOL
#ifdef PROGRAMATICA
import Comorphisms.Haskell2IsabelleHOLCF
import Haskell.Logic_Haskell
#endif
createIsaTheory :: G_theory -> Result (Sign, [Named Sentence])
createIsaTheory (G_theory lid _ (ExtSign sign0 _) _ sens0 _) = do
let th = (sign0, toNamedList sens0)
r1 = coerceBasicTheory lid CASL "" th
r1' = do
th0 <- r1
th1 <- wrapMapTheory CASL2PCFOL th0
th2 <- wrapMapTheory CASL2HasCASL th1
wrapMapTheory PCoClTyConsHOL2PairsInIsaHOL th2
#ifdef PROGRAMATICA
r2 = coerceBasicTheory lid Haskell "" th
r2' = do
th0 <- r2
wrapMapTheory Haskell2IsabelleHOLCF th0
#else
r2 = r1
r2' = r1'
#endif
r4 = coerceBasicTheory lid HasCASL "" th
r4' = do
th0 <- r4
th1 <- wrapMapTheory HasCASL2PCoClTyConsHOL th0
wrapMapTheory PCoClTyConsHOL2PairsInIsaHOL th1
r5 = coerceBasicTheory lid Isabelle "" th
r3 = case maybeResult r1 of
Nothing -> case maybeResult r2 of
Nothing -> case maybeResult r4 of
Nothing -> r5
_ -> r4'
_ -> r2'
_ -> r1'
(sign, sens) <- r3
return (sign, prepareSenNames transString $ toNamedList $ toThSens sens)
|
nevrenato/HetsAlloy
|
Isabelle/CreateTheories.hs
|
gpl-2.0
| 2,176 | 0 | 18 | 567 | 435 | 225 | 210 | 45 | 4 |
module Main where
{ import Data.Graph.Inductive;
import Data.Graph.Inductive.Example;
main :: IO ();
main = return ();
myTleer :: Gr String String;
myTleer = empty;
myT1 :: Gr String String;
myT1 = mkGraph [(1,"Eins"),(2,"Zwei"),(3,"Drei")] [(1,2,"Kante1"),(3,1,"Kante2")];
myT2 :: Gr String String;
myT2 = mkGraph [(1,"Eins"),(2,"Zwei"),(3,"Drei"),(4,"Vier")] [(1,2,"12"),(3,1,"31"),(2,4,"24"),(4,1,"41"),(3,2,"32")];
myFunk :: Context a b -> Int -> Int;
myFunk (_,x,_,_) y = x + y ;-- zur Verwendung mit ufold; addiert alle Knoten
myT3 :: Gr Char ();
myT3 = mkGraph (genLNodes 'a' 5) (labUEdges [(1,2),(2,3),(3,4),(4,5),(5,2),(3,1)])
}
|
ckaestne/CIDE
|
other/CaseStudies/fgl/CIDEfgl/test/mytest.hs
|
gpl-3.0
| 711 | 0 | 9 | 155 | 389 | 242 | 147 | 15 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
A ``lint'' pass to check for Core correctness
-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fprof-auto #-}
module ETA.Core.CoreLint (
lintCoreBindings, lintUnfolding,
lintPassResult, lintInteractiveExpr, lintExpr,
lintAnnots,
-- ** Debug output
ETA.Core.CoreLint.showPass, showPassIO, endPass, endPassIO,
dumpPassResult,
ETA.Core.CoreLint.dumpIfSet,
) where
#include "HsVersions.h"
import ETA.Core.CoreSyn
import ETA.Core.CoreFVs
import ETA.Core.CoreUtils
import ETA.SimplCore.CoreMonad
import qualified ETA.SimplCore.CoreMonad as CoreMonad
import ETA.Utils.Bag
import ETA.BasicTypes.Literal
import ETA.BasicTypes.DataCon
import ETA.Prelude.TysWiredIn
import ETA.Prelude.TysPrim
import ETA.TypeCheck.TcType ( isFloatingTy )
import ETA.BasicTypes.Var
import qualified ETA.BasicTypes.Var as Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.Name
import ETA.BasicTypes.Id
import ETA.Core.PprCore
import ETA.Main.ErrUtils
import ETA.Types.Coercion
import ETA.BasicTypes.SrcLoc
import ETA.Types.Kind
import ETA.Types.Type
import qualified ETA.Types.Type as Type
import ETA.Types.TypeRep
import ETA.Types.TyCon
import ETA.Types.CoAxiom
import ETA.BasicTypes.BasicTypes
import ETA.Main.ErrUtils as Err
import ETA.Main.StaticFlags
import ETA.Utils.ListSetOps
import ETA.Prelude.PrelNames
import ETA.Utils.Outputable
import qualified ETA.Utils.Outputable as Outputable
import ETA.Utils.FastString
import ETA.Utils.Util
import ETA.Types.InstEnv ( instanceDFunId )
import ETA.Types.OptCoercion ( checkAxInstCo )
import ETA.BasicTypes.UniqSupply
import ETA.Main.HscTypes
import ETA.Main.DynFlags
import Control.Monad
import ETA.Utils.MonadUtils
import Data.Maybe
import ETA.Utils.Pair
{-
Note [GHC Formalism]
~~~~~~~~~~~~~~~~~~~~
This file implements the type-checking algorithm for System FC, the "official"
name of the Core language. Type safety of FC is heart of the claim that
executables produced by GHC do not have segmentation faults. Thus, it is
useful to be able to reason about System FC independently of reading the code.
To this purpose, there is a document ghc.pdf built in docs/core-spec that
contains a formalism of the types and functions dealt with here. If you change
just about anything in this file or you change other types/functions throughout
the Core language (all signposted to this note), you should update that
formalism. See docs/core-spec/README for more info about how to do so.
Summary of checks
~~~~~~~~~~~~~~~~~
Checks that a set of core bindings is well-formed. The PprStyle and String
just control what we print in the event of an error. The Bool value
indicates whether we have done any specialisation yet (in which case we do
some extra checks).
We check for
(a) type errors
(b) Out-of-scope type variables
(c) Out-of-scope local variables
(d) Ill-kinded types
If we have done specialisation the we check that there are
(a) No top-level bindings of primitive (unboxed type)
Outstanding issues:
-- Things are *not* OK if:
--
-- * Unsaturated type app before specialisation has been done;
--
-- * Oversaturated type app after specialisation (eta reduction
-- may well be happening...);
Note [Linting type lets]
~~~~~~~~~~~~~~~~~~~~~~~~
In the desugarer, it's very very convenient to be able to say (in effect)
let a = Type Int in <body>
That is, use a type let. See Note [Type let] in CoreSyn.
However, when linting <body> we need to remember that a=Int, else we might
reject a correct program. So we carry a type substitution (in this example
[a -> Int]) and apply this substitution before comparing types. The functin
lintInTy :: Type -> LintM Type
returns a substituted type; that's the only reason it returns anything.
When we encounter a binder (like x::a) we must apply the substitution
to the type of the binding variable. lintBinders does this.
For Ids, the type-substituted Id is added to the in_scope set (which
itself is part of the TvSubst we are carrying down), and when we
find an occurrence of an Id, we fetch it from the in-scope set.
************************************************************************
* *
Beginning and ending passes
* *
************************************************************************
These functions are not CoreM monad stuff, but they probably ought to
be, and it makes a conveneint place. place for them. They print out
stuff before and after core passes, and do Core Lint when necessary.
-}
showPass :: CoreToDo -> CoreM ()
showPass pass = do { dflags <- getDynFlags
; liftIO $ showPassIO dflags pass }
showPassIO :: DynFlags -> CoreToDo -> IO ()
showPassIO dflags pass = Err.showPass dflags (showPpr dflags pass)
endPass :: CoreToDo -> CoreProgram -> [CoreRule] -> CoreM ()
endPass pass binds rules
= do { hsc_env <- getHscEnv
; print_unqual <- getPrintUnqualified
; liftIO $ endPassIO hsc_env print_unqual pass binds rules }
endPassIO :: HscEnv -> PrintUnqualified
-> CoreToDo -> CoreProgram -> [CoreRule] -> IO ()
-- Used by the IO-is CorePrep too
endPassIO hsc_env print_unqual pass binds rules
= do { dumpPassResult dflags print_unqual mb_flag
(ppr pass) (pprPassDetails pass) binds rules
; lintPassResult hsc_env pass binds }
where
dflags = hsc_dflags hsc_env
mb_flag = case coreDumpFlag pass of
Just flag | dopt flag dflags -> Just flag
| dopt Opt_D_verbose_core2core dflags -> Just flag
_ -> Nothing
dumpIfSet :: DynFlags -> Bool -> CoreToDo -> SDoc -> SDoc -> IO ()
dumpIfSet dflags dump_me pass extra_info doc
= Err.dumpIfSet dflags dump_me (showSDoc dflags (ppr pass <+> extra_info)) doc
dumpPassResult :: DynFlags
-> PrintUnqualified
-> Maybe DumpFlag -- Just df => show details in a file whose
-- name is specified by df
-> SDoc -- Header
-> SDoc -- Extra info to appear after header
-> CoreProgram -> [CoreRule]
-> IO ()
dumpPassResult dflags unqual mb_flag hdr extra_info binds rules
| Just flag <- mb_flag
= Err.dumpSDoc dflags unqual flag (showSDoc dflags hdr) dump_doc
| otherwise
= Err.debugTraceMsg dflags 2 size_doc
-- Report result size
-- This has the side effect of forcing the intermediate to be evaluated
where
size_doc = sep [text "Result size of" <+> hdr, nest 2 (equals <+> ppr (coreBindsStats binds))]
dump_doc = vcat [ nest 2 extra_info
, size_doc
, blankLine
, pprCoreBindings binds
, ppUnless (null rules) pp_rules ]
pp_rules = vcat [ blankLine
, ptext (sLit "------ Local rules for imported ids --------")
, pprRules rules ]
coreDumpFlag :: CoreToDo -> Maybe DumpFlag
coreDumpFlag (CoreDoSimplify {}) = Just Opt_D_verbose_core2core
coreDumpFlag (CoreDoPluginPass {}) = Just Opt_D_verbose_core2core
coreDumpFlag CoreDoFloatInwards = Just Opt_D_verbose_core2core
coreDumpFlag (CoreDoFloatOutwards {}) = Just Opt_D_verbose_core2core
coreDumpFlag CoreLiberateCase = Just Opt_D_verbose_core2core
coreDumpFlag CoreDoStaticArgs = Just Opt_D_verbose_core2core
coreDumpFlag CoreDoCallArity = Just Opt_D_dump_call_arity
coreDumpFlag CoreDoStrictness = Just Opt_D_dump_stranal
coreDumpFlag CoreDoWorkerWrapper = Just Opt_D_dump_worker_wrapper
coreDumpFlag CoreDoSpecialising = Just Opt_D_dump_spec
coreDumpFlag CoreDoSpecConstr = Just Opt_D_dump_spec
coreDumpFlag CoreCSE = Just Opt_D_dump_cse
coreDumpFlag CoreDoVectorisation = Just Opt_D_dump_vect
coreDumpFlag CoreDesugar = Just Opt_D_dump_ds
coreDumpFlag CoreDesugarOpt = Just Opt_D_dump_ds
coreDumpFlag CoreTidy = Just Opt_D_dump_simpl
coreDumpFlag CorePrep = Just Opt_D_dump_prep
coreDumpFlag CoreDoPrintCore = Nothing
coreDumpFlag (CoreDoRuleCheck {}) = Nothing
coreDumpFlag CoreDoNothing = Nothing
coreDumpFlag (CoreDoPasses {}) = Nothing
{-
************************************************************************
* *
Top-level interfaces
* *
************************************************************************
-}
lintPassResult :: HscEnv -> CoreToDo -> CoreProgram -> IO ()
lintPassResult hsc_env pass binds
| not (gopt Opt_DoCoreLinting dflags)
= return ()
| otherwise
= do { let (warns, errs) = lintCoreBindings pass (interactiveInScope hsc_env) binds
; Err.showPass dflags ("Core Linted result of " ++ showPpr dflags pass)
; displayLintResults dflags pass warns errs binds }
where
dflags = hsc_dflags hsc_env
displayLintResults :: DynFlags -> CoreToDo
-> Bag Err.MsgDoc -> Bag Err.MsgDoc -> CoreProgram
-> IO ()
displayLintResults dflags pass warns errs binds
| not (isEmptyBag errs)
= do { log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
(vcat [ lint_banner "errors" (ppr pass), Err.pprMessageBag errs
, ptext (sLit "*** Offending Program ***")
, pprCoreBindings binds
, ptext (sLit "*** End of Offense ***") ])
; Err.ghcExit dflags 1 }
| not (isEmptyBag warns)
, not opt_NoDebugOutput
, showLintWarnings pass
= log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
(lint_banner "warnings" (ppr pass) $$ Err.pprMessageBag warns)
| otherwise = return ()
where
lint_banner :: String -> SDoc -> SDoc
lint_banner string pass = ptext (sLit "*** Core Lint") <+> text string
<+> ptext (sLit ": in result of") <+> pass
<+> ptext (sLit "***")
showLintWarnings :: CoreToDo -> Bool
-- Disable Lint warnings on the first simplifier pass, because
-- there may be some INLINE knots still tied, which is tiresomely noisy
showLintWarnings (CoreDoSimplify _ (SimplMode { sm_phase = InitialPhase })) = False
showLintWarnings _ = True
lintInteractiveExpr :: String -> HscEnv -> CoreExpr -> IO ()
lintInteractiveExpr what hsc_env expr
| not (gopt Opt_DoCoreLinting dflags)
= return ()
| Just err <- lintExpr (interactiveInScope hsc_env) expr
= do { display_lint_err err
; Err.ghcExit dflags 1 }
| otherwise
= return ()
where
dflags = hsc_dflags hsc_env
display_lint_err err
= do { log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
(vcat [ lint_banner "errors" (text what)
, err
, ptext (sLit "*** Offending Program ***")
, pprCoreExpr expr
, ptext (sLit "*** End of Offense ***") ])
; Err.ghcExit dflags 1 }
interactiveInScope :: HscEnv -> [Var]
-- In GHCi we may lint expressions, or bindings arising from 'deriving'
-- clauses, that mention variables bound in the interactive context.
-- These are Local things (see Note [Interactively-bound Ids in GHCi] in HscTypes).
-- So we have to tell Lint about them, lest it reports them as out of scope.
--
-- We do this by find local-named things that may appear free in interactive
-- context. This function is pretty revolting and quite possibly not quite right.
-- When we are not in GHCi, the interactive context (hsc_IC hsc_env) is empty
-- so this is a (cheap) no-op.
--
-- See Trac #8215 for an example
interactiveInScope hsc_env
= varSetElems tyvars ++ ids
where
-- C.f. TcRnDriver.setInteractiveContext, Desugar.deSugarExpr
ictxt = hsc_IC hsc_env
(cls_insts, _fam_insts) = ic_instances ictxt
te1 = mkTypeEnvWithImplicits (ic_tythings ictxt)
te = extendTypeEnvWithIds te1 (map instanceDFunId cls_insts)
ids = typeEnvIds te
tyvars = mapUnionVarSet (tyVarsOfType . idType) ids
-- Why the type variables? How can the top level envt have free tyvars?
-- I think it's because of the GHCi debugger, which can bind variables
-- f :: [t] -> [t]
-- where t is a RuntimeUnk (see TcType)
lintCoreBindings :: CoreToDo -> [Var] -> CoreProgram -> (Bag MsgDoc, Bag MsgDoc)
-- Returns (warnings, errors)
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintCoreBindings pass local_in_scope binds
= initL flags $
addLoc TopLevelBindings $
addInScopeVars local_in_scope $
addInScopeVars binders $
-- Put all the top-level binders in scope at the start
-- This is because transformation rules can bring something
-- into use 'unexpectedly'
do { checkL (null dups) (dupVars dups)
; checkL (null ext_dups) (dupExtVars ext_dups)
; mapM lint_bind binds }
where
flags = LF { lf_check_global_ids = check_globals
, lf_check_inline_loop_breakers = check_lbs }
-- See Note [Checking for global Ids]
check_globals = case pass of
CoreTidy -> False
CorePrep -> False
_ -> True
-- See Note [Checking for INLINE loop breakers]
check_lbs = case pass of
CoreDesugar -> False
CoreDesugarOpt -> False
_ -> True
binders = bindersOfBinds binds
(_, dups) = removeDups compare binders
-- dups_ext checks for names with different uniques
-- but but the same External name M.n. We don't
-- allow this at top level:
-- M.n{r3} = ...
-- M.n{r29} = ...
-- because they both get the same linker symbol
ext_dups = snd (removeDups ord_ext (map Var.varName binders))
ord_ext n1 n2 | Just m1 <- nameModule_maybe n1
, Just m2 <- nameModule_maybe n2
= compare (m1, nameOccName n1) (m2, nameOccName n2)
| otherwise = LT
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lint_bind (Rec prs) = mapM_ (lintSingleBinding TopLevel Recursive) prs
lint_bind (NonRec bndr rhs) = lintSingleBinding TopLevel NonRecursive (bndr,rhs)
{-
************************************************************************
* *
\subsection[lintUnfolding]{lintUnfolding}
* *
************************************************************************
We use this to check all unfoldings that come in from interfaces
(it is very painful to catch errors otherwise):
-}
lintUnfolding :: SrcLoc
-> [Var] -- Treat these as in scope
-> CoreExpr
-> Maybe MsgDoc -- Nothing => OK
lintUnfolding locn vars expr
| isEmptyBag errs = Nothing
| otherwise = Just (pprMessageBag errs)
where
(_warns, errs) = initL defaultLintFlags linter
linter = addLoc (ImportedUnfolding locn) $
addInScopeVars vars $
lintCoreExpr expr
lintExpr :: [Var] -- Treat these as in scope
-> CoreExpr
-> Maybe MsgDoc -- Nothing => OK
lintExpr vars expr
| isEmptyBag errs = Nothing
| otherwise = Just (pprMessageBag errs)
where
(_warns, errs) = initL defaultLintFlags linter
linter = addLoc TopLevelBindings $
addInScopeVars vars $
lintCoreExpr expr
{-
************************************************************************
* *
\subsection[lintCoreBinding]{lintCoreBinding}
* *
************************************************************************
Check a core binding, returning the list of variables bound.
-}
lintSingleBinding :: TopLevelFlag -> RecFlag -> (Id, CoreExpr) -> LintM ()
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintSingleBinding top_lvl_flag rec_flag (binder,rhs)
= addLoc (RhsOf binder) $
-- Check the rhs
do { ty <- lintCoreExpr rhs
; lintBinder binder -- Check match to RHS type
; binder_ty <- applySubstTy binder_ty
; checkTys binder_ty ty (mkRhsMsg binder (ptext (sLit "RHS")) ty)
-- Check the let/app invariant
-- See Note [CoreSyn let/app invariant] in CoreSyn
; checkL (not (isUnLiftedType binder_ty)
|| (isNonRec rec_flag && exprOkForSpeculation rhs))
(mkRhsPrimMsg binder rhs)
-- Check that if the binder is top-level or recursive, it's not demanded
; checkL (not (isStrictId binder)
|| (isNonRec rec_flag && not (isTopLevel top_lvl_flag)))
(mkStrictMsg binder)
-- Check that if the binder is local, it is not marked as exported
; checkL (not (isExportedId binder) || isTopLevel top_lvl_flag)
(mkNonTopExportedMsg binder)
-- Check that if the binder is local, it does not have an external name
; checkL (not (isExternalName (Var.varName binder)) || isTopLevel top_lvl_flag)
(mkNonTopExternalNameMsg binder)
-- Check whether binder's specialisations contain any out-of-scope variables
; mapM_ (checkBndrIdInScope binder) bndr_vars
; flags <- getLintFlags
; when (lf_check_inline_loop_breakers flags
&& isStrongLoopBreaker (idOccInfo binder)
&& isInlinePragma (idInlinePragma binder))
(addWarnL (ptext (sLit "INLINE binder is (non-rule) loop breaker:") <+> ppr binder))
-- Only non-rule loop breakers inhibit inlining
-- Check whether arity and demand type are consistent (only if demand analysis
-- already happened)
--
-- Note (Apr 2014): this is actually ok. See Note [Demand analysis for trivial right-hand sides]
-- in DmdAnal. After eta-expansion in CorePrep the rhs is no longer trivial.
-- ; let dmdTy = idStrictness binder
-- ; checkL (case dmdTy of
-- StrictSig dmd_ty -> idArity binder >= dmdTypeDepth dmd_ty || exprIsTrivial rhs)
-- (mkArityMsg binder)
; lintIdUnfolding binder binder_ty (idUnfolding binder) }
-- We should check the unfolding, if any, but this is tricky because
-- the unfolding is a SimplifiableCoreExpr. Give up for now.
where
binder_ty = idType binder
bndr_vars = varSetElems (idFreeVars binder)
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintBinder var | isId var = lintIdBndr var $ \_ -> (return ())
| otherwise = return ()
lintIdUnfolding :: Id -> Type -> Unfolding -> LintM ()
lintIdUnfolding bndr bndr_ty (CoreUnfolding { uf_tmpl = rhs, uf_src = src })
| isStableSource src
= do { ty <- lintCoreExpr rhs
; checkTys bndr_ty ty (mkRhsMsg bndr (ptext (sLit "unfolding")) ty) }
lintIdUnfolding _ _ _
= return () -- We could check more
{-
Note [Checking for INLINE loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's very suspicious if a strong loop breaker is marked INLINE.
However, the desugarer generates instance methods with INLINE pragmas
that form a mutually recursive group. Only after a round of
simplification are they unravelled. So we suppress the test for
the desugarer.
************************************************************************
* *
\subsection[lintCoreExpr]{lintCoreExpr}
* *
************************************************************************
-}
--type InKind = Kind -- Substitution not yet applied
type InType = Type
type InCoercion = Coercion
type InVar = Var
type InTyVar = TyVar
type OutKind = Kind -- Substitution has been applied to this,
-- but has not been linted yet
type LintedKind = Kind -- Substitution applied, and type is linted
type OutType = Type -- Substitution has been applied to this,
-- but has not been linted yet
type LintedType = Type -- Substitution applied, and type is linted
type OutCoercion = Coercion
type OutVar = Var
type OutTyVar = TyVar
lintCoreExpr :: CoreExpr -> LintM OutType
-- The returned type has the substitution from the monad
-- already applied to it:
-- lintCoreExpr e subst = exprType (subst e)
--
-- The returned "type" can be a kind, if the expression is (Type ty)
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintCoreExpr (Var var)
= do { checkL (not (var == oneTupleDataConId))
(ptext (sLit "Illegal one-tuple"))
; checkL (isId var && not (isCoVar var))
(ptext (sLit "Non term variable") <+> ppr var)
; checkDeadIdOcc var
; var' <- lookupIdInScope var
; return (idType var') }
lintCoreExpr (Lit lit)
= return (literalType lit)
lintCoreExpr (Cast expr co)
= do { expr_ty <- lintCoreExpr expr
; co' <- applySubstCo co
; (_, from_ty, to_ty, r) <- lintCoercion co'
; checkRole co' Representational r
; checkTys from_ty expr_ty (mkCastErr expr co' from_ty expr_ty)
; return to_ty }
lintCoreExpr (Tick (Breakpoint _ ids) expr)
= do forM_ ids $ \id -> do
checkDeadIdOcc id
lookupIdInScope id
lintCoreExpr expr
lintCoreExpr (Tick _other_tickish expr)
= lintCoreExpr expr
lintCoreExpr (Let (NonRec tv (Type ty)) body)
| isTyVar tv
= -- See Note [Linting type lets]
do { ty' <- applySubstTy ty
; lintTyBndr tv $ \ tv' ->
do { addLoc (RhsOf tv) $ checkTyKind tv' ty'
-- Now extend the substitution so we
-- take advantage of it in the body
; extendSubstL tv' ty' $
addLoc (BodyOfLetRec [tv]) $
lintCoreExpr body } }
lintCoreExpr (Let (NonRec bndr rhs) body)
| isId bndr
= do { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs)
; addLoc (BodyOfLetRec [bndr])
(lintAndScopeId bndr $ \_ -> (lintCoreExpr body)) }
| otherwise
= failWithL (mkLetErr bndr rhs) -- Not quite accurate
lintCoreExpr (Let (Rec pairs) body)
= lintAndScopeIds bndrs $ \_ ->
do { checkL (null dups) (dupVars dups)
; mapM_ (lintSingleBinding NotTopLevel Recursive) pairs
; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
where
bndrs = map fst pairs
(_, dups) = removeDups compare bndrs
lintCoreExpr e@(App _ _)
= do { fun_ty <- lintCoreExpr fun
; addLoc (AnExpr e) $ foldM lintCoreArg fun_ty args }
where
(fun, args) = collectArgs e
lintCoreExpr (Lam var expr)
= addLoc (LambdaBodyOf var) $
lintBinder var $ \ var' ->
do { body_ty <- lintCoreExpr expr
; if isId var' then
return (mkFunTy (idType var') body_ty)
else
return (mkForAllTy var' body_ty)
}
-- The applySubstTy is needed to apply the subst to var
lintCoreExpr e@(Case scrut var alt_ty alts) =
-- Check the scrutinee
do { scrut_ty <- lintCoreExpr scrut
; alt_ty <- lintInTy alt_ty
; var_ty <- lintInTy (idType var)
-- See Note [Rules for floating-point comparisons] in PrelRules
; let isLitPat (LitAlt _, _ , _) = True
isLitPat _ = False
; checkL (not $ isFloatingTy scrut_ty && any isLitPat alts)
(ptext (sLit $ "Lint warning: Scrutinising floating-point " ++
"expression with literal pattern in case " ++
"analysis (see Trac #9238).")
$$ text "scrut" <+> ppr scrut)
; case tyConAppTyCon_maybe (idType var) of
Just tycon
| debugIsOn &&
isAlgTyCon tycon &&
not (isFamilyTyCon tycon || isAbstractTyCon tycon) &&
null (tyConDataCons tycon) ->
pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var))
-- This can legitimately happen for type families
$ return ()
_otherwise -> return ()
-- Don't use lintIdBndr on var, because unboxed tuple is legitimate
; subst <- getTvSubst
; checkTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
; lintAndScopeId var $ \_ ->
do { -- Check the alternatives
mapM_ (lintCoreAlt scrut_ty alt_ty) alts
; checkCaseAlts e scrut_ty alts
; return alt_ty } }
-- This case can't happen; linting types in expressions gets routed through
-- lintCoreArgs
lintCoreExpr (Type ty)
= pprPanic "lintCoreExpr" (ppr ty)
lintCoreExpr (Coercion co)
= do { (_kind, ty1, ty2, role) <- lintInCo co
; return (mkCoercionType role ty1 ty2) }
{-
Note [Kind instantiation in coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following coercion axiom:
ax_co [(k_ag :: BOX), (f_aa :: k_ag -> Constraint)] :: T k_ag f_aa ~ f_aa
Consider the following instantiation:
ax_co <* -> *> <Monad>
We need to split the co_ax_tvs into kind and type variables in order
to find out the coercion kind instantiations. Those can only be Refl
since we don't have kind coercions. This is just a way to represent
kind instantiation.
We use the number of kind variables to know how to split the coercions
instantiations between kind coercions and type coercions. We lint the
kind coercions and produce the following substitution which is to be
applied in the type variables:
k_ag ~~> * -> *
Note [No alternatives lint check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Case expressions with no alternatives are odd beasts, and worth looking at
in the linter (cf Trac #10180). We check two things:
* exprIsHNF is false: certainly, it would be terribly wrong if the
scrutinee was already in head normal form.
* exprIsBottom is true: we should be able to see why GHC believes the
scrutinee is diverging for sure.
In principle, the first check is redundant: exprIsBottom == True will
always imply exprIsHNF == False. But the first check is reliable: If
exprIsHNF == True, then there definitely is a problem (exprIsHNF errs
on the right side). If the second check triggers then it may be the
case that the compiler got smarter elsewhere, and the empty case is
correct, but that exprIsBottom is unable to see it. In particular, the
empty-type check in exprIsBottom is an approximation. Therefore, this
check is not fully reliable, and we keep both around.
************************************************************************
* *
\subsection[lintCoreArgs]{lintCoreArgs}
* *
************************************************************************
The basic version of these functions checks that the argument is a
subtype of the required type, as one would expect.
-}
lintCoreArg :: OutType -> CoreArg -> LintM OutType
lintCoreArg fun_ty (Type arg_ty)
= do { arg_ty' <- applySubstTy arg_ty
; lintTyApp fun_ty arg_ty' }
lintCoreArg fun_ty arg
= do { arg_ty <- lintCoreExpr arg
; checkL (not (isUnLiftedType arg_ty) || exprOkForSpeculation arg)
(mkLetAppMsg arg)
; lintValApp arg fun_ty arg_ty }
-----------------
lintAltBinders :: OutType -- Scrutinee type
-> OutType -- Constructor type
-> [OutVar] -- Binders
-> LintM ()
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintAltBinders scrut_ty con_ty []
= checkTys con_ty scrut_ty (mkBadPatMsg con_ty scrut_ty)
lintAltBinders scrut_ty con_ty (bndr:bndrs)
| isTyVar bndr
= do { con_ty' <- lintTyApp con_ty (mkTyVarTy bndr)
; lintAltBinders scrut_ty con_ty' bndrs }
| otherwise
= do { con_ty' <- lintValApp (Var bndr) con_ty (idType bndr)
; lintAltBinders scrut_ty con_ty' bndrs }
-----------------
lintTyApp :: OutType -> OutType -> LintM OutType
lintTyApp fun_ty arg_ty
| Just (tyvar,body_ty) <- splitForAllTy_maybe fun_ty
, isTyVar tyvar
= do { checkTyKind tyvar arg_ty
; return (substTyWith [tyvar] [arg_ty] body_ty) }
| otherwise
= failWithL (mkTyAppMsg fun_ty arg_ty)
-----------------
lintValApp :: CoreExpr -> OutType -> OutType -> LintM OutType
lintValApp arg fun_ty arg_ty
| Just (arg,res) <- splitFunTy_maybe fun_ty
= do { checkTys arg arg_ty err1
; return res }
| otherwise
= failWithL err2
where
err1 = mkAppMsg fun_ty arg_ty arg
err2 = mkNonFunAppMsg fun_ty arg_ty arg
checkTyKind :: OutTyVar -> OutType -> LintM ()
-- Both args have had substitution applied
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
checkTyKind tyvar arg_ty
| isSuperKind tyvar_kind -- kind forall
= lintKind arg_ty
-- Arg type might be boxed for a function with an uncommitted
-- tyvar; notably this is used so that we can give
-- error :: forall a:*. String -> a
-- and then apply it to both boxed and unboxed types.
| otherwise -- type forall
= do { arg_kind <- lintType arg_ty
; unless (arg_kind `isSubKind` tyvar_kind)
(addErrL (mkKindErrMsg tyvar arg_ty $$ (text "xx" <+> ppr arg_kind))) }
where
tyvar_kind = tyVarKind tyvar
checkDeadIdOcc :: Id -> LintM ()
-- Occurrences of an Id should never be dead....
-- except when we are checking a case pattern
checkDeadIdOcc id
| isDeadOcc (idOccInfo id)
= do { in_case <- inCasePat
; checkL in_case
(ptext (sLit "Occurrence of a dead Id") <+> ppr id) }
| otherwise
= return ()
{-
************************************************************************
* *
\subsection[lintCoreAlts]{lintCoreAlts}
* *
************************************************************************
-}
checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
-- a) Check that the alts are non-empty
-- b1) Check that the DEFAULT comes first, if it exists
-- b2) Check that the others are in increasing order
-- c) Check that there's a default for infinite types
-- NB: Algebraic cases are not necessarily exhaustive, because
-- the simplifer correctly eliminates case that can't
-- possibly match.
checkCaseAlts e ty alts =
do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
-- For types Int#, Word# with an infinite (well, large!) number of
-- possible values, there should usually be a DEFAULT case
-- But (see Note [Empty case alternatives] in CoreSyn) it's ok to
-- have *no* case alternatives.
-- In effect, this is a kind of partial test. I suppose it's possible
-- that we might *know* that 'x' was 1 or 2, in which case
-- case x of { 1 -> e1; 2 -> e2 }
-- would be fine.
; checkL (isJust maybe_deflt || not is_infinite_ty || null alts)
(nonExhaustiveAltsMsg e) }
where
(con_alts, maybe_deflt) = findDefault alts
-- Check that successive alternatives have increasing tags
increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
increasing_tag _ = True
non_deflt (DEFAULT, _, _) = False
non_deflt _ = True
is_infinite_ty = case tyConAppTyCon_maybe ty of
Nothing -> False
Just tycon -> isPrimTyCon tycon
checkAltExpr :: CoreExpr -> OutType -> LintM ()
checkAltExpr expr ann_ty
= do { actual_ty <- lintCoreExpr expr
; checkTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
lintCoreAlt :: OutType -- Type of scrutinee
-> OutType -- Type of the alternative
-> CoreAlt
-> LintM ()
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
do { checkL (null args) (mkDefaultArgsMsg args)
; checkAltExpr rhs alt_ty }
lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs)
| litIsLifted lit
= failWithL integerScrutinisedMsg
| otherwise
= do { checkL (null args) (mkDefaultArgsMsg args)
; checkTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)
; checkAltExpr rhs alt_ty }
where
lit_ty = literalType lit
lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
| isNewTyCon (dataConTyCon con)
= addErrL (mkNewTyDataConAltMsg scrut_ty alt)
| Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
= addLoc (CaseAlt alt) $ do
{ -- First instantiate the universally quantified
-- type variables of the data constructor
-- We've already check
checkL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
; let con_payload_ty = applyTys (dataConRepType con) tycon_arg_tys
-- And now bring the new binders into scope
; lintBinders args $ \ args' -> do
{ addLoc (CasePat alt) (lintAltBinders scrut_ty con_payload_ty args')
; checkAltExpr rhs alt_ty } }
| otherwise -- Scrut-ty is wrong shape
= addErrL (mkBadAltMsg scrut_ty alt)
{-
************************************************************************
* *
\subsection[lint-types]{Types}
* *
************************************************************************
-}
-- When we lint binders, we (one at a time and in order):
-- 1. Lint var types or kinds (possibly substituting)
-- 2. Add the binder to the in scope set, and if its a coercion var,
-- we may extend the substitution to reflect its (possibly) new kind
lintBinders :: [Var] -> ([Var] -> LintM a) -> LintM a
lintBinders [] linterF = linterF []
lintBinders (var:vars) linterF = lintBinder var $ \var' ->
lintBinders vars $ \ vars' ->
linterF (var':vars')
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintBinder :: Var -> (Var -> LintM a) -> LintM a
lintBinder var linterF
| isId var = lintIdBndr var linterF
| otherwise = lintTyBndr var linterF
lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a
lintTyBndr tv thing_inside
= do { subst <- getTvSubst
; let (subst', tv') = Type.substTyVarBndr subst tv
; lintTyBndrKind tv'
; updateTvSubst subst' (thing_inside tv') }
lintIdBndr :: Id -> (Id -> LintM a) -> LintM a
-- Do substitution on the type of a binder and add the var with this
-- new type to the in-scope set of the second argument
-- ToDo: lint its rules
lintIdBndr id linterF
= do { lintAndScopeId id $ \id' -> linterF id' }
lintAndScopeIds :: [Var] -> ([Var] -> LintM a) -> LintM a
lintAndScopeIds ids linterF
= go ids
where
go [] = linterF []
go (id:ids) = lintAndScopeId id $ \id ->
lintAndScopeIds ids $ \ids ->
linterF (id:ids)
lintAndScopeId :: InVar -> (OutVar -> LintM a) -> LintM a
lintAndScopeId id linterF
= do { flags <- getLintFlags
; checkL (not (lf_check_global_ids flags) || isLocalId id)
(ptext (sLit "Non-local Id binder") <+> ppr id)
-- See Note [Checking for global Ids]
; ty <- lintInTy (idType id)
; let id' = setIdType id ty
; addInScopeVar id' $ (linterF id') }
{-
************************************************************************
* *
Types and kinds
* *
************************************************************************
We have a single linter for types and kinds. That is convenient
because sometimes it's not clear whether the thing we are looking
at is a type or a kind.
-}
lintInTy :: InType -> LintM LintedType
-- Types only, not kinds
-- Check the type, and apply the substitution to it
-- See Note [Linting type lets]
lintInTy ty
= addLoc (InType ty) $
do { ty' <- applySubstTy ty
; _k <- lintType ty'
; return ty' }
-------------------
lintTyBndrKind :: OutTyVar -> LintM ()
-- Handles both type and kind foralls.
lintTyBndrKind tv = lintKind (tyVarKind tv)
-------------------
lintType :: OutType -> LintM LintedKind
-- The returned Kind has itself been linted
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintType (TyVarTy tv)
= do { checkTyCoVarInScope tv
; return (tyVarKind tv) }
-- We checked its kind when we added it to the envt
lintType ty@(AppTy t1 t2)
= do { k1 <- lintType t1
; k2 <- lintType t2
; lint_ty_app ty k1 [(t2,k2)] }
lintType ty@(FunTy t1 t2) -- (->) has two different rules, for types and kinds
= do { k1 <- lintType t1
; k2 <- lintType t2
; lintArrow (ptext (sLit "type or kind") <+> quotes (ppr ty)) k1 k2 }
lintType ty@(TyConApp tc tys)
| Just ty' <- coreView ty
= lintType ty' -- Expand type synonyms, so that we do not bogusly complain
-- about un-saturated type synonyms
| isUnLiftedTyCon tc || isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
-- See Note [The kind invariant] in TypeRep
-- Also type synonyms and type families
, length tys < tyConArity tc
= failWithL (hang (ptext (sLit "Un-saturated type application")) 2 (ppr ty))
| otherwise
= do { ks <- mapM lintType tys
; lint_ty_app ty (tyConKind tc) (tys `zip` ks) }
lintType (ForAllTy tv ty)
= do { lintTyBndrKind tv
; addInScopeVar tv (lintType ty) }
lintType ty@(LitTy l) = lintTyLit l >> return (typeKind ty)
lintKind :: OutKind -> LintM ()
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintKind k = do { sk <- lintType k
; unless (isSuperKind sk)
(addErrL (hang (ptext (sLit "Ill-kinded kind:") <+> ppr k)
2 (ptext (sLit "has kind:") <+> ppr sk))) }
lintArrow :: SDoc -> LintedKind -> LintedKind -> LintM LintedKind
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintArrow what k1 k2 -- Eg lintArrow "type or kind `blah'" k1 k2
-- or lintarrow "coercion `blah'" k1 k2
| isSuperKind k1
= return superKind
| otherwise
= do { unless (okArrowArgKind k1) (addErrL (msg (ptext (sLit "argument")) k1))
; unless (okArrowResultKind k2) (addErrL (msg (ptext (sLit "result")) k2))
; return liftedTypeKind }
where
msg ar k
= vcat [ hang (ptext (sLit "Ill-kinded") <+> ar)
2 (ptext (sLit "in") <+> what)
, what <+> ptext (sLit "kind:") <+> ppr k ]
lint_ty_app :: Type -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
lint_ty_app ty k tys
= lint_app (ptext (sLit "type") <+> quotes (ppr ty)) k tys
----------------
lint_co_app :: Coercion -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
lint_co_app ty k tys
= lint_app (ptext (sLit "coercion") <+> quotes (ppr ty)) k tys
----------------
lintTyLit :: TyLit -> LintM ()
lintTyLit (NumTyLit n)
| n >= 0 = return ()
| otherwise = failWithL msg
where msg = ptext (sLit "Negative type literal:") <+> integer n
lintTyLit (StrTyLit _) = return ()
lint_app :: SDoc -> LintedKind -> [(LintedType,LintedKind)] -> LintM Kind
-- (lint_app d fun_kind arg_tys)
-- We have an application (f arg_ty1 .. arg_tyn),
-- where f :: fun_kind
-- Takes care of linting the OutTypes
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lint_app doc kfn kas
= foldlM go_app kfn kas
where
fail_msg = vcat [ hang (ptext (sLit "Kind application error in")) 2 doc
, nest 2 (ptext (sLit "Function kind =") <+> ppr kfn)
, nest 2 (ptext (sLit "Arg kinds =") <+> ppr kas) ]
go_app kfn ka
| Just kfn' <- coreView kfn
= go_app kfn' ka
go_app (FunTy kfa kfb) (_,ka)
= do { unless (ka `isSubKind` kfa) (addErrL fail_msg)
; return kfb }
go_app (ForAllTy kv kfn) (ta,ka)
= do { unless (ka `isSubKind` tyVarKind kv) (addErrL fail_msg)
; return (substKiWith [kv] [ta] kfn) }
go_app _ _ = failWithL fail_msg
{-
************************************************************************
* *
Linting coercions
* *
************************************************************************
-}
lintInCo :: InCoercion -> LintM (LintedKind, LintedType, LintedType, Role)
-- Check the coercion, and apply the substitution to it
-- See Note [Linting type lets]
lintInCo co
= addLoc (InCo co) $
do { co' <- applySubstCo co
; lintCoercion co' }
lintCoercion :: OutCoercion -> LintM (LintedKind, LintedType, LintedType, Role)
-- Check the kind of a coercion term, returning the kind
-- Post-condition: the returned OutTypes are lint-free
-- and have the same kind as each other
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism]
lintCoercion (Refl r ty)
= do { k <- lintType ty
; return (k, ty, ty, r) }
lintCoercion co@(TyConAppCo r tc cos)
| tc `hasKey` funTyConKey
, [co1,co2] <- cos
= do { (k1,s1,t1,r1) <- lintCoercion co1
; (k2,s2,t2,r2) <- lintCoercion co2
; rk <- lintArrow (ptext (sLit "coercion") <+> quotes (ppr co)) k1 k2
; checkRole co1 r r1
; checkRole co2 r r2
; return (rk, mkFunTy s1 s2, mkFunTy t1 t2, r) }
| Just {} <- synTyConDefn_maybe tc
= failWithL (ptext (sLit "Synonym in TyConAppCo:") <+> ppr co)
| otherwise
= do { (ks,ss,ts,rs) <- mapAndUnzip4M lintCoercion cos
; rk <- lint_co_app co (tyConKind tc) (ss `zip` ks)
; _ <- zipWith3M checkRole cos (tyConRolesX r tc) rs
; return (rk, mkTyConApp tc ss, mkTyConApp tc ts, r) }
lintCoercion co@(AppCo co1 co2)
= do { (k1,s1,t1,r1) <- lintCoercion co1
; (k2,s2,t2,r2) <- lintCoercion co2
; rk <- lint_co_app co k1 [(s2,k2)]
; if r1 == Phantom
then checkL (r2 == Phantom || r2 == Nominal)
(ptext (sLit "Second argument in AppCo cannot be R:") $$
ppr co)
else checkRole co Nominal r2
; return (rk, mkAppTy s1 s2, mkAppTy t1 t2, r1) }
lintCoercion (ForAllCo tv co)
= do { lintTyBndrKind tv
; (k, s, t, r) <- addInScopeVar tv (lintCoercion co)
; return (k, mkForAllTy tv s, mkForAllTy tv t, r) }
lintCoercion (CoVarCo cv)
| not (isCoVar cv)
= failWithL (hang (ptext (sLit "Bad CoVarCo:") <+> ppr cv)
2 (ptext (sLit "With offending type:") <+> ppr (varType cv)))
| otherwise
= do { checkTyCoVarInScope cv
; cv' <- lookupIdInScope cv
; let (s,t) = coVarKind cv'
k = typeKind s
r = coVarRole cv'
; when (isSuperKind k) $
do { checkL (r == Nominal) (hang (ptext (sLit "Non-nominal kind equality"))
2 (ppr cv))
; checkL (s `eqKind` t) (hang (ptext (sLit "Non-refl kind equality"))
2 (ppr cv)) }
; return (k, s, t, r) }
lintCoercion (UnivCo _prov r ty1 ty2)
= do { k1 <- lintType ty1
; _k2 <- lintType ty2
-- ; unless (k1 `eqKind` k2) $
-- failWithL (hang (ptext (sLit "Unsafe coercion changes kind"))
-- 2 (ppr co))
; return (k1, ty1, ty2, r) }
lintCoercion (SymCo co)
= do { (k, ty1, ty2, r) <- lintCoercion co
; return (k, ty2, ty1, r) }
lintCoercion co@(TransCo co1 co2)
= do { (k1, ty1a, ty1b, r1) <- lintCoercion co1
; (_, ty2a, ty2b, r2) <- lintCoercion co2
; checkL (ty1b `eqType` ty2a)
(hang (ptext (sLit "Trans coercion mis-match:") <+> ppr co)
2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b]))
; checkRole co r1 r2
; return (k1, ty1a, ty2b, r1) }
lintCoercion the_co@(NthCo n co)
= do { (_,s,t,r) <- lintCoercion co
; case (splitTyConApp_maybe s, splitTyConApp_maybe t) of
(Just (tc_s, tys_s), Just (tc_t, tys_t))
| tc_s == tc_t
, isDistinctTyCon tc_s || r /= Representational
-- see Note [NthCo and newtypes] in Coercion
, tys_s `equalLength` tys_t
, n < length tys_s
-> return (ks, ts, tt, tr)
where
ts = getNth tys_s n
tt = getNth tys_t n
tr = nthRole r tc_s n
ks = typeKind ts
_ -> failWithL (hang (ptext (sLit "Bad getNth:"))
2 (ppr the_co $$ ppr s $$ ppr t)) }
lintCoercion the_co@(LRCo lr co)
= do { (_,s,t,r) <- lintCoercion co
; checkRole co Nominal r
; case (splitAppTy_maybe s, splitAppTy_maybe t) of
(Just s_pr, Just t_pr)
-> return (k, s_pick, t_pick, Nominal)
where
s_pick = pickLR lr s_pr
t_pick = pickLR lr t_pr
k = typeKind s_pick
_ -> failWithL (hang (ptext (sLit "Bad LRCo:"))
2 (ppr the_co $$ ppr s $$ ppr t)) }
lintCoercion (InstCo co arg_ty)
= do { (k,s,t,r) <- lintCoercion co
; arg_kind <- lintType arg_ty
; case (splitForAllTy_maybe s, splitForAllTy_maybe t) of
(Just (tv1,ty1), Just (tv2,ty2))
| arg_kind `isSubKind` tyVarKind tv1
-> return (k, substTyWith [tv1] [arg_ty] ty1,
substTyWith [tv2] [arg_ty] ty2, r)
| otherwise
-> failWithL (ptext (sLit "Kind mis-match in inst coercion"))
_ -> failWithL (ptext (sLit "Bad argument of inst")) }
lintCoercion co@(AxiomInstCo con ind cos)
= do { unless (0 <= ind && ind < brListLength (coAxiomBranches con))
(bad_ax (ptext (sLit "index out of range")))
-- See Note [Kind instantiation in coercions]
; let CoAxBranch { cab_tvs = ktvs
, cab_roles = roles
, cab_lhs = lhs
, cab_rhs = rhs } = coAxiomNthBranch con ind
; unless (equalLength ktvs cos) (bad_ax (ptext (sLit "lengths")))
; in_scope <- getInScope
; let empty_subst = mkTvSubst in_scope emptyTvSubstEnv
; (subst_l, subst_r) <- foldlM check_ki
(empty_subst, empty_subst)
(zip3 ktvs roles cos)
; let lhs' = Type.substTys subst_l lhs
rhs' = Type.substTy subst_r rhs
; case checkAxInstCo co of
Just bad_branch -> bad_ax $ ptext (sLit "inconsistent with") <+> (pprCoAxBranch (coAxiomTyCon con) bad_branch)
Nothing -> return ()
; return (typeKind rhs', mkTyConApp (coAxiomTyCon con) lhs', rhs', coAxiomRole con) }
where
bad_ax what = addErrL (hang (ptext (sLit "Bad axiom application") <+> parens what)
2 (ppr co))
check_ki (subst_l, subst_r) (ktv, role, co)
= do { (k, t1, t2, r) <- lintCoercion co
; checkRole co role r
; let ktv_kind = Type.substTy subst_l (tyVarKind ktv)
-- Using subst_l is ok, because subst_l and subst_r
-- must agree on kind equalities
; unless (k `isSubKind` ktv_kind)
(bad_ax (ptext (sLit "check_ki2") <+> vcat [ ppr co, ppr k, ppr ktv, ppr ktv_kind ] ))
; return (Type.extendTvSubst subst_l ktv t1,
Type.extendTvSubst subst_r ktv t2) }
lintCoercion co@(SubCo co')
= do { (k,s,t,r) <- lintCoercion co'
; checkRole co Nominal r
; return (k,s,t,Representational) }
lintCoercion this@(AxiomRuleCo co ts cs)
= do _ks <- mapM lintType ts
eqs <- mapM lintCoercion cs
let tyNum = length ts
case compare (coaxrTypeArity co) tyNum of
EQ -> return ()
LT -> err "Too many type arguments"
[ txt "expected" <+> int (coaxrTypeArity co)
, txt "provided" <+> int tyNum ]
GT -> err "Not enough type arguments"
[ txt "expected" <+> int (coaxrTypeArity co)
, txt "provided" <+> int tyNum ]
checkRoles 0 (coaxrAsmpRoles co) eqs
case coaxrProves co ts [ Pair l r | (_,l,r,_) <- eqs ] of
Nothing -> err "Malformed use of AxiomRuleCo" [ ppr this ]
Just (Pair l r) ->
do kL <- lintType l
kR <- lintType r
unless (eqKind kL kR)
$ err "Kind error in CoAxiomRule"
[ppr kL <+> txt "/=" <+> ppr kR]
return (kL, l, r, coaxrRole co)
where
txt = ptext . sLit
err m xs = failWithL $
hang (txt m) 2 $ vcat (txt "Rule:" <+> ppr (coaxrName co) : xs)
checkRoles n (e : es) ((_,_,_,r) : rs)
| e == r = checkRoles (n+1) es rs
| otherwise = err "Argument roles mismatch"
[ txt "In argument:" <+> int (n+1)
, txt "Expected:" <+> ppr e
, txt "Found:" <+> ppr r ]
checkRoles _ [] [] = return ()
checkRoles n [] rs = err "Too many coercion arguments"
[ txt "Expected:" <+> int n
, txt "Provided:" <+> int (n + length rs) ]
checkRoles n es [] = err "Not enough coercion arguments"
[ txt "Expected:" <+> int (n + length es)
, txt "Provided:" <+> int n ]
{-
************************************************************************
* *
\subsection[lint-monad]{The Lint monad}
* *
************************************************************************
-}
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism]
data LintEnv
= LE { le_flags :: LintFlags -- Linting the result of this pass
, le_loc :: [LintLocInfo] -- Locations
, le_subst :: TvSubst -- Current type substitution; we also use this
} -- to keep track of all the variables in scope,
-- both Ids and TyVars
data LintFlags
= LF { lf_check_global_ids :: Bool -- See Note [Checking for global Ids]
, lf_check_inline_loop_breakers :: Bool -- See Note [Checking for INLINE loop breakers]
}
defaultLintFlags :: LintFlags
defaultLintFlags = LF { lf_check_global_ids = False
, lf_check_inline_loop_breakers = True }
newtype LintM a =
LintM { unLintM ::
LintEnv ->
WarnsAndErrs -> -- Error and warning messages so far
(Maybe a, WarnsAndErrs) } -- Result and messages (if any)
type WarnsAndErrs = (Bag MsgDoc, Bag MsgDoc)
{- Note [Checking for global Ids]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Before CoreTidy, all locally-bound Ids must be LocalIds, even
top-level ones. See Note [Exported LocalIds] and Trac #9857.
Note [Type substitution]
~~~~~~~~~~~~~~~~~~~~~~~~
Why do we need a type substitution? Consider
/\(a:*). \(x:a). /\(a:*). id a x
This is ill typed, because (renaming variables) it is really
/\(a:*). \(x:a). /\(b:*). id b x
Hence, when checking an application, we can't naively compare x's type
(at its binding site) with its expected type (at a use site). So we
rename type binders as we go, maintaining a substitution.
The same substitution also supports let-type, current expressed as
(/\(a:*). body) ty
Here we substitute 'ty' for 'a' in 'body', on the fly.
-}
instance Functor LintM where
fmap = liftM
instance Applicative LintM where
pure = return
(<*>) = ap
instance Monad LintM where
return x = LintM (\ _ errs -> (Just x, errs))
fail err = failWithL (text err)
m >>= k = LintM (\ env errs ->
let (res, errs') = unLintM m env errs in
case res of
Just r -> unLintM (k r) env errs'
Nothing -> (Nothing, errs'))
data LintLocInfo
= RhsOf Id -- The variable bound
| LambdaBodyOf Id -- The lambda-binder
| BodyOfLetRec [Id] -- One of the binders
| CaseAlt CoreAlt -- Case alternative
| CasePat CoreAlt -- The *pattern* of the case alternative
| AnExpr CoreExpr -- Some expression
| ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
| TopLevelBindings
| InType Type -- Inside a type
| InCo Coercion -- Inside a coercion
initL :: LintFlags -> LintM a -> WarnsAndErrs -- Errors and warnings
initL flags m
= case unLintM m env (emptyBag, emptyBag) of
(_, errs) -> errs
where
env = LE { le_flags = flags, le_subst = emptyTvSubst, le_loc = [] }
getLintFlags :: LintM LintFlags
getLintFlags = LintM $ \ env errs -> (Just (le_flags env), errs)
checkL :: Bool -> MsgDoc -> LintM ()
checkL True _ = return ()
checkL False msg = failWithL msg
failWithL :: MsgDoc -> LintM a
failWithL msg = LintM $ \ env (warns,errs) ->
(Nothing, (warns, addMsg env errs msg))
addErrL :: MsgDoc -> LintM ()
addErrL msg = LintM $ \ env (warns,errs) ->
(Just (), (warns, addMsg env errs msg))
addWarnL :: MsgDoc -> LintM ()
addWarnL msg = LintM $ \ env (warns,errs) ->
(Just (), (addMsg env warns msg, errs))
addMsg :: LintEnv -> Bag MsgDoc -> MsgDoc -> Bag MsgDoc
addMsg env msgs msg
= ASSERT( notNull locs )
msgs `snocBag` mk_msg msg
where
locs = le_loc env
(loc, cxt1) = dumpLoc (head locs)
cxts = [snd (dumpLoc loc) | loc <- locs]
context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
ptext (sLit "Substitution:") <+> ppr (le_subst env)
| otherwise = cxt1
mk_msg msg = mkLocMessage SevWarning (mkSrcSpan loc loc) (context $$ msg)
addLoc :: LintLocInfo -> LintM a -> LintM a
addLoc extra_loc m
= LintM $ \ env errs ->
unLintM m (env { le_loc = extra_loc : le_loc env }) errs
inCasePat :: LintM Bool -- A slight hack; see the unique call site
inCasePat = LintM $ \ env errs -> (Just (is_case_pat env), errs)
where
is_case_pat (LE { le_loc = CasePat {} : _ }) = True
is_case_pat _other = False
addInScopeVars :: [Var] -> LintM a -> LintM a
addInScopeVars vars m
= LintM $ \ env errs ->
unLintM m (env { le_subst = extendTvInScopeList (le_subst env) vars })
errs
addInScopeVar :: Var -> LintM a -> LintM a
addInScopeVar var m
= LintM $ \ env errs ->
unLintM m (env { le_subst = extendTvInScope (le_subst env) var }) errs
extendSubstL :: TyVar -> Type -> LintM a -> LintM a
extendSubstL tv ty m
= LintM $ \ env errs ->
unLintM m (env { le_subst = Type.extendTvSubst (le_subst env) tv ty }) errs
updateTvSubst :: TvSubst -> LintM a -> LintM a
updateTvSubst subst' m
= LintM $ \ env errs -> unLintM m (env { le_subst = subst' }) errs
getTvSubst :: LintM TvSubst
getTvSubst = LintM (\ env errs -> (Just (le_subst env), errs))
getInScope :: LintM InScopeSet
getInScope = LintM (\ env errs -> (Just (getTvInScope (le_subst env)), errs))
applySubstTy :: InType -> LintM OutType
applySubstTy ty = do { subst <- getTvSubst; return (Type.substTy subst ty) }
applySubstCo :: InCoercion -> LintM OutCoercion
applySubstCo co = do { subst <- getTvSubst; return (substCo (tvCvSubst subst) co) }
lookupIdInScope :: Id -> LintM Id
lookupIdInScope id
| not (mustHaveLocalBinding id)
= return id -- An imported Id
| otherwise
= do { subst <- getTvSubst
; case lookupInScope (getTvInScope subst) id of
Just v -> return v
Nothing -> do { addErrL out_of_scope
; return id } }
where
out_of_scope = pprBndr LetBind id <+> ptext (sLit "is out of scope")
oneTupleDataConId :: Id -- Should not happen
oneTupleDataConId = dataConWorkId (tupleCon BoxedTuple 1)
checkBndrIdInScope :: Var -> Var -> LintM ()
checkBndrIdInScope binder id
= checkInScope msg id
where
msg = ptext (sLit "is out of scope inside info for") <+>
ppr binder
checkTyCoVarInScope :: Var -> LintM ()
checkTyCoVarInScope v = checkInScope (ptext (sLit "is out of scope")) v
checkInScope :: SDoc -> Var -> LintM ()
checkInScope loc_msg var =
do { subst <- getTvSubst
; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
(hsep [pprBndr LetBind var, loc_msg]) }
checkTys :: OutType -> OutType -> MsgDoc -> LintM ()
-- check ty2 is subtype of ty1 (ie, has same structure but usage
-- annotations need only be consistent, not equal)
-- Assumes ty1,ty2 are have alrady had the substitution applied
checkTys ty1 ty2 msg = checkL (ty1 `eqType` ty2) msg
checkRole :: Coercion
-> Role -- expected
-> Role -- actual
-> LintM ()
checkRole co r1 r2
= checkL (r1 == r2)
(ptext (sLit "Role incompatibility: expected") <+> ppr r1 <> comma <+>
ptext (sLit "got") <+> ppr r2 $$
ptext (sLit "in") <+> ppr co)
{-
************************************************************************
* *
\subsection{Error messages}
* *
************************************************************************
-}
dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
dumpLoc (RhsOf v)
= (getSrcLoc v, brackets (ptext (sLit "RHS of") <+> pp_binders [v]))
dumpLoc (LambdaBodyOf b)
= (getSrcLoc b, brackets (ptext (sLit "in body of lambda with binder") <+> pp_binder b))
dumpLoc (BodyOfLetRec [])
= (noSrcLoc, brackets (ptext (sLit "In body of a letrec with no binders")))
dumpLoc (BodyOfLetRec bs@(_:_))
= ( getSrcLoc (head bs), brackets (ptext (sLit "in body of letrec with binders") <+> pp_binders bs))
dumpLoc (AnExpr e)
= (noSrcLoc, text "In the expression:" <+> ppr e)
dumpLoc (CaseAlt (con, args, _))
= (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
dumpLoc (CasePat (con, args, _))
= (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
dumpLoc (ImportedUnfolding locn)
= (locn, brackets (ptext (sLit "in an imported unfolding")))
dumpLoc TopLevelBindings
= (noSrcLoc, Outputable.empty)
dumpLoc (InType ty)
= (noSrcLoc, text "In the type" <+> quotes (ppr ty))
dumpLoc (InCo co)
= (noSrcLoc, text "In the coercion" <+> quotes (ppr co))
pp_binders :: [Var] -> SDoc
pp_binders bs = sep (punctuate comma (map pp_binder bs))
pp_binder :: Var -> SDoc
pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
| otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
------------------------------------------------------
-- Messages for case expressions
mkDefaultArgsMsg :: [Var] -> MsgDoc
mkDefaultArgsMsg args
= hang (text "DEFAULT case with binders")
4 (ppr args)
mkCaseAltMsg :: CoreExpr -> Type -> Type -> MsgDoc
mkCaseAltMsg e ty1 ty2
= hang (text "Type of case alternatives not the same as the annotation on case:")
4 (vcat [ppr ty1, ppr ty2, ppr e])
mkScrutMsg :: Id -> Type -> Type -> TvSubst -> MsgDoc
mkScrutMsg var var_ty scrut_ty subst
= vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
text "Result binder type:" <+> ppr var_ty,--(idType var),
text "Scrutinee type:" <+> ppr scrut_ty,
hsep [ptext (sLit "Current TV subst"), ppr subst]]
mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> MsgDoc
mkNonDefltMsg e
= hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
mkNonIncreasingAltsMsg e
= hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
nonExhaustiveAltsMsg :: CoreExpr -> MsgDoc
nonExhaustiveAltsMsg e
= hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
mkBadConMsg :: TyCon -> DataCon -> MsgDoc
mkBadConMsg tycon datacon
= vcat [
text "In a case alternative, data constructor isn't in scrutinee type:",
text "Scrutinee type constructor:" <+> ppr tycon,
text "Data con:" <+> ppr datacon
]
mkBadPatMsg :: Type -> Type -> MsgDoc
mkBadPatMsg con_result_ty scrut_ty
= vcat [
text "In a case alternative, pattern result type doesn't match scrutinee type:",
text "Pattern result type:" <+> ppr con_result_ty,
text "Scrutinee type:" <+> ppr scrut_ty
]
integerScrutinisedMsg :: MsgDoc
integerScrutinisedMsg
= text "In a LitAlt, the literal is lifted (probably Integer)"
mkBadAltMsg :: Type -> CoreAlt -> MsgDoc
mkBadAltMsg scrut_ty alt
= vcat [ text "Data alternative when scrutinee is not a tycon application",
text "Scrutinee type:" <+> ppr scrut_ty,
text "Alternative:" <+> pprCoreAlt alt ]
mkNewTyDataConAltMsg :: Type -> CoreAlt -> MsgDoc
mkNewTyDataConAltMsg scrut_ty alt
= vcat [ text "Data alternative for newtype datacon",
text "Scrutinee type:" <+> ppr scrut_ty,
text "Alternative:" <+> pprCoreAlt alt ]
------------------------------------------------------
-- Other error messages
mkAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
mkAppMsg fun_ty arg_ty arg
= vcat [ptext (sLit "Argument value doesn't match argument type:"),
hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
hang (ptext (sLit "Arg:")) 4 (ppr arg)]
mkNonFunAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
mkNonFunAppMsg fun_ty arg_ty arg
= vcat [ptext (sLit "Non-function type in function position"),
hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
hang (ptext (sLit "Arg:")) 4 (ppr arg)]
mkLetErr :: TyVar -> CoreExpr -> MsgDoc
mkLetErr bndr rhs
= vcat [ptext (sLit "Bad `let' binding:"),
hang (ptext (sLit "Variable:"))
4 (ppr bndr <+> dcolon <+> ppr (varType bndr)),
hang (ptext (sLit "Rhs:"))
4 (ppr rhs)]
mkTyAppMsg :: Type -> Type -> MsgDoc
mkTyAppMsg ty arg_ty
= vcat [text "Illegal type application:",
hang (ptext (sLit "Exp type:"))
4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
hang (ptext (sLit "Arg type:"))
4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
mkRhsMsg :: Id -> SDoc -> Type -> MsgDoc
mkRhsMsg binder what ty
= vcat
[hsep [ptext (sLit "The type of this binder doesn't match the type of its") <+> what <> colon,
ppr binder],
hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
hsep [ptext (sLit "Rhs type:"), ppr ty]]
mkLetAppMsg :: CoreExpr -> MsgDoc
mkLetAppMsg e
= hang (ptext (sLit "This argument does not satisfy the let/app invariant:"))
2 (ppr e)
mkRhsPrimMsg :: Id -> CoreExpr -> MsgDoc
mkRhsPrimMsg binder _rhs
= vcat [hsep [ptext (sLit "The type of this binder is primitive:"),
ppr binder],
hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]
]
mkStrictMsg :: Id -> MsgDoc
mkStrictMsg binder
= vcat [hsep [ptext (sLit "Recursive or top-level binder has strict demand info:"),
ppr binder],
hsep [ptext (sLit "Binder's demand info:"), ppr (idDemandInfo binder)]
]
mkNonTopExportedMsg :: Id -> MsgDoc
mkNonTopExportedMsg binder
= hsep [ptext (sLit "Non-top-level binder is marked as exported:"), ppr binder]
mkNonTopExternalNameMsg :: Id -> MsgDoc
mkNonTopExternalNameMsg binder
= hsep [ptext (sLit "Non-top-level binder has an external name:"), ppr binder]
mkKindErrMsg :: TyVar -> Type -> MsgDoc
mkKindErrMsg tyvar arg_ty
= vcat [ptext (sLit "Kinds don't match in type application:"),
hang (ptext (sLit "Type variable:"))
4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
hang (ptext (sLit "Arg type:"))
4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
{- Not needed now
mkArityMsg :: Id -> MsgDoc
mkArityMsg binder
= vcat [hsep [ptext (sLit "Demand type has"),
ppr (dmdTypeDepth dmd_ty),
ptext (sLit "arguments, rhs has"),
ppr (idArity binder),
ptext (sLit "arguments,"),
ppr binder],
hsep [ptext (sLit "Binder's strictness signature:"), ppr dmd_ty]
]
where (StrictSig dmd_ty) = idStrictness binder
-}
mkCastErr :: CoreExpr -> Coercion -> Type -> Type -> MsgDoc
mkCastErr expr co from_ty expr_ty
= vcat [ptext (sLit "From-type of Cast differs from type of enclosed expression"),
ptext (sLit "From-type:") <+> ppr from_ty,
ptext (sLit "Type of enclosed expr:") <+> ppr expr_ty,
ptext (sLit "Actual enclosed expr:") <+> ppr expr,
ptext (sLit "Coercion used in cast:") <+> ppr co
]
dupVars :: [[Var]] -> MsgDoc
dupVars vars
= hang (ptext (sLit "Duplicate variables brought into scope"))
2 (ppr vars)
dupExtVars :: [[Name]] -> MsgDoc
dupExtVars vars
= hang (ptext (sLit "Duplicate top-level variables with the same qualified name"))
2 (ppr vars)
{-
************************************************************************
* *
\subsection{Annotation Linting}
* *
************************************************************************
-}
-- | This checks whether a pass correctly looks through debug
-- annotations (@SourceNote@). This works a bit different from other
-- consistency checks: We check this by running the given task twice,
-- noting all differences between the results.
lintAnnots :: SDoc -> (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
lintAnnots pname pass guts = do
-- Run the pass as we normally would
dflags <- getDynFlags
when (gopt Opt_DoAnnotationLinting dflags) $
liftIO $ Err.showPass dflags "Annotation linting - first run"
nguts <- pass guts
-- If appropriate re-run it without debug annotations to make sure
-- that they made no difference.
when (gopt Opt_DoAnnotationLinting dflags) $ do
liftIO $ Err.showPass dflags "Annotation linting - second run"
nguts' <- withoutAnnots pass guts
-- Finally compare the resulting bindings
liftIO $ Err.showPass dflags "Annotation linting - comparison"
let binds = flattenBinds $ mg_binds nguts
binds' = flattenBinds $ mg_binds nguts'
(diffs,_) = diffBinds True (mkRnEnv2 emptyInScopeSet) binds binds'
when (not (null diffs)) $ CoreMonad.putMsg $ vcat
[ lint_banner "warning" pname
, text "Core changes with annotations:"
, withPprStyle defaultDumpStyle $ nest 2 $ vcat diffs
]
-- Return actual new guts
return nguts
-- | Run the given pass without annotations. This means that we both
-- remove the @Opt_Debug@ flag from the environment as well as all
-- annotations from incoming modules.
withoutAnnots :: (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
withoutAnnots pass guts = do
-- Remove debug flag from environment.
dflags <- getDynFlags
let removeFlag env = env{hsc_dflags = gopt_unset dflags Opt_Debug}
withoutFlag corem =
liftIO =<< runCoreM <$> fmap removeFlag getHscEnv <*> getRuleBase <*>
getUniqueSupplyM <*> getModule <*>
getPrintUnqualified <*> pure corem
-- Nuke existing ticks in module.
-- TODO: Ticks in unfoldings. Maybe change unfolding so it removes
-- them in absence of @Opt_Debug@?
let nukeTicks = stripTicksE (not . tickishIsCode)
nukeAnnotsBind :: CoreBind -> CoreBind
nukeAnnotsBind bind = case bind of
Rec bs -> Rec $ map (\(b,e) -> (b, nukeTicks e)) bs
NonRec b e -> NonRec b $ nukeTicks e
nukeAnnotsMod mg@ModGuts{mg_binds=binds}
= mg{mg_binds = map nukeAnnotsBind binds}
-- Perform pass with all changes applied
fmap fst $ withoutFlag $ pass (nukeAnnotsMod guts)
|
alexander-at-github/eta
|
compiler/ETA/Core/CoreLint.hs
|
bsd-3-clause
| 70,068 | 349 | 25 | 20,001 | 15,881 | 8,202 | 7,679 | 1,078 | 12 |
module Data.Graph.Inductive.Graph
(Node, LNode, UNode, Edge, LEdge, UEdge, Adj, Context, MContext,
Decomp, GDecomp, UContext, UDecomp, Path, LPath(..), UPath,
Graph(..), DynGraph(..), ufold, gmap, nmap, emap, nodes, edges,
newNodes, gelem, insNode, insEdge, delNode, delEdge, delLEdge,
insNodes, insEdges, delNodes, delEdges, buildGr, mkUGraph, context,
lab, neighbors, suc, pre, lsuc, lpre, out, inn, outdeg, indeg, deg,
equal, node', lab', labNode', neighbors', suc', pre', lpre', lsuc',
out', inn', outdeg', indeg', deg')
where
{ import Data.List (sortBy);
type Node = Int;
type LNode a = (Node, a);
type UNode = LNode ();
type Edge = (Node, Node);
type LEdge b = (Node, Node, b);
type UEdge = LEdge ();
type Path = [Node];
newtype LPath a = LP [LNode a];
instance (Show a) => Show (LPath a) where
{ show (LP xs) = show xs};
type UPath = [UNode];
type Adj b = [(b, Node)];
type Context a b = (Adj b, Node, a, Adj b);
type MContext a b = Maybe (Context a b);
type Decomp g a b = (MContext a b, g a b);
type GDecomp g a b = (Context a b, g a b);
type UContext = ([Node], Node, [Node]);
type UDecomp g = (Maybe UContext, g);
class Graph gr where
{
empty :: gr a b;
isEmpty :: gr a b -> Bool;
match :: Node -> gr a b -> Decomp gr a b;
mkGraph :: [LNode a] -> [LEdge b] -> gr a b;
labNodes :: gr a b -> [LNode a];
matchAny :: gr a b -> GDecomp gr a b;
noNodes :: gr a b -> Int;
nodeRange :: gr a b -> (Node, Node);
labEdges :: gr a b -> [LEdge b];
matchAny g
= case labNodes g of
{ [] -> error "Match Exception, Empty Graph";
(v, _) : _ -> (c, g')
where { (Just c, g') = match v g}};
noNodes = length . labNodes;
nodeRange g = (minimum vs, maximum vs)
where { vs = map fst (labNodes g)};
labEdges
= ufold (\ (_, v, _, s) -> ((map (\ (l, w) -> (v, w, l)) s) ++))
[]};
class (Graph gr) => DynGraph gr where
{
(&) :: Context a b -> gr a b -> gr a b};
ufold :: (Graph gr) => (Context a b -> c -> c) -> c -> gr a b -> c;
ufold f u g
| isEmpty g = u
| otherwise = f c (ufold f u g')
where { (c, g') = matchAny g};
gmap ::
(DynGraph gr) => (Context a b -> Context c d) -> gr a b -> gr c d;
gmap f = ufold (\ c -> (f c &)) empty;
nmap :: (DynGraph gr) => (a -> c) -> gr a b -> gr c b;
nmap f = gmap (\ (p, v, l, s) -> (p, v, f l, s));
emap :: (DynGraph gr) => (b -> c) -> gr a b -> gr a c;
emap f = gmap (\ (p, v, l, s) -> (map1 f p, v, l, map1 f s))
where { map1 g = map (\ (l, v) -> (g l, v))};
nodes :: (Graph gr) => gr a b -> [Node];
nodes = map fst . labNodes;
edges :: (Graph gr) => gr a b -> [Edge];
edges = map (\ (v, w, _) -> (v, w)) . labEdges;
newNodes :: (Graph gr) => Int -> gr a b -> [Node];
newNodes i g = [n + 1 .. n + i]
where { (_, n) = nodeRange g};
gelem :: (Graph gr) => Node -> gr a b -> Bool;
gelem v g
= case match v g of
{ (Just _, _) -> True;
_ -> False};
insNode :: (DynGraph gr) => LNode a -> gr a b -> gr a b;
insNode (v, l) = (([], v, l, []) &);
insEdge :: (DynGraph gr) => LEdge b -> gr a b -> gr a b;
insEdge (v, w, l) g = (pr, v, la, (l, w) : su) & g'
where { (Just (pr, _, la, su), g') = match v g};
delNode :: (Graph gr) => Node -> gr a b -> gr a b;
delNode v = delNodes [v];
delEdge :: (DynGraph gr) => Edge -> gr a b -> gr a b;
delEdge (v, w) g
= case match v g of
{ (Nothing, _) -> g;
(Just (p, v', l, s), g')
-> (p, v', l, filter ((/= w) . snd) s) & g'};
delLEdge :: (DynGraph gr, Eq b) => LEdge b -> gr a b -> gr a b;
delLEdge (v, w, b) g
= case match v g of
{ (Nothing, _) -> g;
(Just (p, v', l, s), g')
-> (p, v', l, filter (\ (x, n) -> x /= b || n /= w) s) & g'};
insNodes :: (DynGraph gr) => [LNode a] -> gr a b -> gr a b;
insNodes vs g = foldr insNode g vs;
insEdges :: (DynGraph gr) => [LEdge b] -> gr a b -> gr a b;
insEdges es g = foldr insEdge g es;
delNodes :: (Graph gr) => [Node] -> gr a b -> gr a b;
delNodes [] g = g;
delNodes (v : vs) g = delNodes vs (snd (match v g));
delEdges :: (DynGraph gr) => [Edge] -> gr a b -> gr a b;
delEdges es g = foldr delEdge g es;
buildGr :: (DynGraph gr) => [Context a b] -> gr a b;
buildGr = foldr (&) empty;
mkUGraph :: (Graph gr) => [Node] -> [Edge] -> gr () ();
mkUGraph vs es = mkGraph (labUNodes vs) (labUEdges es)
where { labUEdges = map (\ (v, w) -> (v, w, ()));
labUNodes = map (\ v -> (v, ()))};
context :: (Graph gr) => gr a b -> Node -> Context a b;
context g v
= case match v g of
{ (Nothing, _) -> error ("Match Exception, Node: " ++ show v);
(Just c, _) -> c};
lab :: (Graph gr) => gr a b -> Node -> Maybe a;
lab g v = fst (match v g) >>= return . lab';
neighbors :: (Graph gr) => gr a b -> Node -> [Node];
neighbors = (\ (p, _, _, s) -> map snd (p ++ s)) .: context;
suc :: (Graph gr) => gr a b -> Node -> [Node];
suc = map snd .: context4l;
pre :: (Graph gr) => gr a b -> Node -> [Node];
pre = map snd .: context1l;
lsuc :: (Graph gr) => gr a b -> Node -> [(Node, b)];
lsuc = map flip2 .: context4l;
lpre :: (Graph gr) => gr a b -> Node -> [(Node, b)];
lpre = map flip2 .: context1l;
out :: (Graph gr) => gr a b -> Node -> [LEdge b];
out g v = map (\ (l, w) -> (v, w, l)) (context4l g v);
inn :: (Graph gr) => gr a b -> Node -> [LEdge b];
inn g v = map (\ (l, w) -> (w, v, l)) (context1l g v);
outdeg :: (Graph gr) => gr a b -> Node -> Int;
outdeg = length .: context4l;
indeg :: (Graph gr) => gr a b -> Node -> Int;
indeg = length .: context1l;
deg :: (Graph gr) => gr a b -> Node -> Int;
deg = (\ (p, _, _, s) -> length p + length s) .: context;
node' :: Context a b -> Node;
node' (_, v, _, _) = v;
lab' :: Context a b -> a;
lab' (_, _, l, _) = l;
labNode' :: Context a b -> LNode a;
labNode' (_, v, l, _) = (v, l);
neighbors' :: Context a b -> [Node];
neighbors' (p, _, _, s) = map snd p ++ map snd s;
suc' :: Context a b -> [Node];
suc' = map snd . context4l';
pre' :: Context a b -> [Node];
pre' = map snd . context1l';
lsuc' :: Context a b -> [(Node, b)];
lsuc' = map flip2 . context4l';
lpre' :: Context a b -> [(Node, b)];
lpre' = map flip2 . context1l';
out' :: Context a b -> [LEdge b];
out' c@(_, v, _, _) = map (\ (l, w) -> (v, w, l)) (context4l' c);
inn' :: Context a b -> [LEdge b];
inn' c@(_, v, _, _) = map (\ (l, w) -> (w, v, l)) (context1l' c);
outdeg' :: Context a b -> Int;
outdeg' = length . context4l';
indeg' :: Context a b -> Int;
indeg' = length . context1l';
deg' :: Context a b -> Int;
deg' (p, _, _, s) = length p + length s;
nodeComp :: (Eq b) => LNode b -> LNode b -> Ordering;
nodeComp n@(v, _) n'@(w, _)
| n == n' = EQ
| v < w = LT
| otherwise = GT;
slabNodes :: (Eq a, Graph gr) => gr a b -> [LNode a];
slabNodes = sortBy nodeComp . labNodes;
edgeComp :: (Eq b) => LEdge b -> LEdge b -> Ordering;
edgeComp e@(v, w, _) e'@(x, y, _)
| e == e' = EQ
| v < x || (v == x && w < y) = LT
| otherwise = GT;
slabEdges :: (Eq b, Graph gr) => gr a b -> [LEdge b];
slabEdges = sortBy edgeComp . labEdges;
equal :: (Eq a, Eq b, Graph gr) => gr a b -> gr a b -> Bool;
equal g g'
= slabNodes g == slabNodes g' && slabEdges g == slabEdges g';
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d;
(.:) = (.) . (.);
flip2 :: (a, b) -> (b, a);
flip2 (x, y) = (y, x);
context1l :: (Graph gr) => gr a b -> Node -> Adj b;
context1l = context1l' .: context;
context4l :: (Graph gr) => gr a b -> Node -> Adj b;
context4l = context4l' .: context;
context1l' :: Context a b -> Adj b;
context1l' (p, v, _, s) = p ++ filter ((== v) . snd) s;
context4l' :: Context a b -> Adj b;
context4l' (p, v, _, s) = s ++ filter ((== v) . snd) p}
|
ckaestne/CIDE
|
other/CaseStudies/fgl/CIDEfgl/Data/Graph/Inductive/Graph.hs
|
gpl-3.0
| 8,604 | 0 | 15 | 2,993 | 4,558 | 2,563 | 1,995 | 192 | 2 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pl-PL">
<title>Getting started Guide</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Zawartość</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Szukaj</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Ulubione</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
rnehra01/zap-extensions
|
src/org/zaproxy/zap/extension/gettingStarted/resources/help_pl_PL/helpset_pl_PL.hs
|
apache-2.0
| 970 | 94 | 29 | 158 | 402 | 213 | 189 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE DataKinds, KindSignatures, PolyKinds #-}
module Bug where
pattern PATTERN = ()
data Proxy (tag :: k) (a :: *)
wrongLift :: Proxy PATTERN ()
wrongLift = undefined
|
sdiehl/ghc
|
testsuite/tests/patsyn/should_fail/T9161-2.hs
|
bsd-3-clause
| 212 | 0 | 6 | 37 | 50 | 31 | 19 | -1 | -1 |
--------------------------------------------------------------------------------
-- | This module provides an wrapper API around the file system which does some
-- caching.
module Hakyll.Core.Provider
( -- * Constructing resource providers
Internal.Provider
, newProvider
-- * Querying resource properties
, Internal.resourceList
, Internal.resourceExists
, Internal.resourceFilePath
, Internal.resourceModified
, Internal.resourceModificationTime
-- * Access to raw resource content
, Internal.resourceString
, Internal.resourceLBS
-- * Access to metadata and body content
, Internal.resourceMetadata
, Internal.resourceBody
) where
--------------------------------------------------------------------------------
import qualified Hakyll.Core.Provider.Internal as Internal
import qualified Hakyll.Core.Provider.MetadataCache as Internal
import Hakyll.Core.Store (Store)
--------------------------------------------------------------------------------
-- | Create a resource provider
newProvider :: Store -- ^ Store to use
-> (FilePath -> IO Bool) -- ^ Should we ignore this file?
-> FilePath -- ^ Search directory
-> IO Internal.Provider -- ^ Resulting provider
newProvider store ignore directory = do
-- Delete metadata cache where necessary
p <- Internal.newProvider store ignore directory
mapM_ (Internal.resourceInvalidateMetadataCache p) $
filter (Internal.resourceModified p) $ Internal.resourceList p
return p
|
Javran/hakyll
|
src/Hakyll/Core/Provider.hs
|
bsd-3-clause
| 1,627 | 0 | 12 | 362 | 212 | 124 | 88 | 25 | 1 |
{-# LANGUAGE QuantifiedConstraints, StandaloneDeriving, GeneralizedNewtypeDeriving #-}
module T15290c where
import Prelude hiding ( Monad(..) )
import Data.Coerce ( Coercible )
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
join :: m (m a) -> m a
newtype StateT s m a = StateT { runStateT :: s -> m (s, a) }
instance Monad m => Monad (StateT s m) where
ma >>= fmb = StateT $ \s -> runStateT ma s >>= \(s1, a) -> runStateT (fmb a) s1
join ssa = StateT $ \s -> runStateT ssa s >>= \(s, sa) -> runStateT sa s
newtype IntStateT m a = IntStateT { runIntStateT :: StateT Int m a }
deriving instance (Monad m, forall p q. Coercible p q => Coercible (m p) (m q)) => Monad (IntStateT m)
|
sdiehl/ghc
|
testsuite/tests/deriving/should_compile/T15290c.hs
|
bsd-3-clause
| 701 | 0 | 12 | 155 | 314 | 171 | 143 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies,
ExistentialQuantification, RankNTypes,
FlexibleInstances #-}
-- Arguably, the type signature for f1 should be enough to make
-- this program compile, but in 5.04 it wasn't; the
-- extra sig in f2 was needed.
--
-- This is a pretty borderline case.
module ShouldCompile where
class C t a b | t a -> b
instance C Char a Bool
data P t a = forall b. (C t a b) => MkP b
data Q t = MkQ (forall a. P t a)
f1 :: Q Char
f1 = MkQ (MkP True)
f2 :: Q Char
f2 = MkQ (MkP True :: forall a. P Char a)
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/typecheck/should_compile/tc166.hs
|
bsd-3-clause
| 620 | 0 | 9 | 185 | 148 | 83 | 65 | -1 | -1 |
module Main where
{-
If a fixity declaration hasn't been supplied for
an operator, it is defaulted to being "infixl 9".
OLD: The derived Read instances for data types containing
left-assoc constructors produces code that causes
non-termination if you use 'read' to evaluate them
( (head (reads x)) is cool tho.)
==> The inferred assoc for :++ below left & the derived
Read instance should fail to terminate (with ghc-4.xx,
this is exemplified by having the stack overflow.)
NEW: the new H98 spec says that we ignore associativity when
parsing, so it terminates fine
-}
-- infixl 9 :++
data T = T1 | T :++ T deriving (Eq,Show, Read)
t :: T
t = read "T1"
main = do
print ((fst (head (reads "T1"))) :: T)
print t
|
wxwxwwxxx/ghc
|
testsuite/tests/deriving/should_run/drvrun005.hs
|
bsd-3-clause
| 754 | 0 | 14 | 173 | 89 | 48 | 41 | 7 | 1 |
module Main where
import Command
import Expense
import Parser
import StringUtils
import System.Environment
import System.IO
import Data.List
seeHelp :: String
seeHelp = ", see " ++ quote "pet help"
execArgs :: [String] -> ([Expense] -> Result)
execArgs [] = error $ "No command given" ++ seeHelp
execArgs (x:xs) = case res of
Nothing -> error $ "Unknown command " ++ quote x ++ seeHelp
Just c -> if length xs /= length (commandArgs c)
then error $ "Bad number of arguments" ++ seeHelp
else commandFunc c xs
where res = find (\(Command n _ _ _) -> n == x) commandList
execResult :: Result -> IO ()
execResult (Error { message = m }) = do hPutStrLn stderr m
hFlush stderr
main :: IO ()
main = do
allArgs <- getArgs
case allArgs of
[] -> error $ "No arguments given" ++ seeHelp
("help":_) -> execResult $ execArgs allArgs []
(file:args) -> case fmap getExpenses $ readFile file of
Left e -> do error $ show e
Right expenses -> do
let cmd = execArgs args
res = cmd expenses
putStrLn res
return ()
|
fredmorcos/attic
|
projects/pet/archive/pet_haskell_pet2/Main.hs
|
isc
| 1,129 | 0 | 18 | 320 | 416 | 208 | 208 | 34 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
import Control.Monad
import Control.Monad.State
import Control.Monad.Writer
newtype AppWithNewtype a = AppWithNewtype {
runAppWithNewtype' :: StateT Int (WriterT [Int] IO) a
} deriving (Monad, MonadIO, MonadState Int, MonadWriter [Int])
-- 이렇게 deriving에 MonadState, MonadWriter을 추가해서, 직접 이 타입에
-- get, put, tell등 MonadState, MonadWriter으로 역할. 이거 없으면,
-- 그냥 lift을 명시적으로 해서 접근해야함.
--
-- SEE: http://stackoverflow.com/questions/18519774/monad-transformer-explicit-lifting
-- SEE: http://stackoverflow.com/a/18520161
appWithNewtypeLiftWriter a = AppWithNewtype $ lift $ a
f :: AppWithNewtype ()
f = do
cur <- get
appWithNewtypeLiftWriter $ tell [4, 5]
appWithNewtypeLiftWriter $ doSomethingToWriter
liftIO $ putStrLn $ "CUR = " ++ (show cur)
return ()
-- Writer의 문맥으로만 제한하고 싶은 경우엔 타입을 이렇게 지정.
-- 위의 FlexibleContexts 확장이 필요함.
doSomethingToWriter :: (MonadWriter [Int] m) => m ()
doSomethingToWriter = do
tell [6, 7]
return ()
-- runApp :: App a -> Int -> IO ((a, Int), [Int])
runAppWithNewtype a init = runWriterT (runStateT (runAppWithNewtype' a) init)
main :: IO ()
main = do
r <- runAppWithNewtype f 123
putStrLn $ show r
return ()
-- EOF
|
ageldama/monad-transformer-basics
|
mtWithNewtype.hs
|
mit
| 1,402 | 0 | 10 | 221 | 299 | 157 | 142 | 26 | 1 |
module Hebrew where
import Data.Map (Map)
import qualified Data.Map as Map
import Prepare
import Prepare.Tanach.IndexParser (index)
import Prepare.Tanach.HeaderParser (header)
import Prepare.Tanach.TanachParser (tanach)
import qualified Prepare.Tanach.Paths as Paths
import System.FilePath ((</>))
loadIndex :: FilePath -> IO ()
loadIndex dataPath = do
result <- loadParse (Paths.indexFilePath dataPath) index emptyLog
case result of
Left e -> putStrLn $ "Error loading index:\n" ++ e
Right _ -> putStrLn "Success!"
loadHeader :: FilePath -> IO ()
loadHeader dataPath = do
result <- loadParse (Paths.headerFilePath dataPath) header emptyLog
case result of
Left e -> putStrLn $ "Error loading header:\n" ++ e
Right _ -> putStrLn "Success!"
showLoadSingle :: FilePath -> IO ()
showLoadSingle p = do
result <- loadParse p tanach emptyLog
case result of
Left e -> putStrLn $ "✗ " ++ p ++ "\n" ++ e
Right _ -> putStrLn $ "✓ " ++ p
loadSingle :: FilePath -> IO ()
loadSingle dataPath = showLoadSingle $ Paths.tanachBasePath dataPath </> "Amos.xml"
loadAll :: FilePath -> IO ()
loadAll dataPath = do
result <- loadParse (Paths.indexFilePath dataPath) index emptyLog
case result of
Left e -> putStrLn $ "Error loading index:\n" ++ e
Right idx ->
mapM_ showLoadSingle $ (Paths.getAllFilePaths dataPath) idx
commands :: FilePath -> Map String (IO ())
commands dataPath = Map.fromList
[ ("load-index", loadIndex dataPath)
, ("load-header", loadHeader dataPath)
, ("load-single", loadSingle dataPath)
, ("load-all", loadAll dataPath)
]
|
ancientlanguage/haskell-analysis
|
prepare/app/Hebrew.hs
|
mit
| 1,599 | 0 | 14 | 295 | 537 | 273 | 264 | 42 | 2 |
module Graphics.Application (
runDefaultApplication,
runAnotherApplication
) where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Control.Monad.State
import Data.IORef
import Data.Maybe
import qualified Data.Set as Set
import Data.Tree
import Data.Tree.Zipper
import qualified Graphics.Rendering.OpenGL as GL
import Graphics.Rendering.OpenGL (get, ($=),($~),($~!)) -- could also be used with IORef
import qualified Graphics.UI.GLFW as GLFW
import Numeric (showGFloat)
import System.Log.Logger
import Graphics.FunctionalGL
import Graphics.Layouts
import Graphics.Scene
import Graphics.View
import Graphics.World
----------------------------------------------------------------------------------------------------
type SceneUI = UI (Maybe Scene)
createSceneView :: Bool -> Layout (Maybe Scene) -> ViewHandleEvent (Maybe Scene) -> Maybe Scene -> View (Maybe Scene)
createSceneView hasFocus layout handleEvent content = (createView content)
{ viewHandleEvent = handleEvent
, viewLayout = layout
, viewHasFocus = hasFocus
}
{- | Handle an event through simple delegation to its inner content scene, if any. A scene being not
aware of the view holding it, any change will stay local (excepted for a Nothing interpreted as a
closure).
-}
sceneHandleEvent :: IORef ResourceMap -> ViewHandleEvent (Maybe Scene)
sceneHandleEvent currentResources event treeLoc =
let view = getLabel treeLoc
(_, size) = viewLocalBounds view
in case viewContent view of
Nothing -> return BubbleUp
Just scene -> do
resources <- GL.get currentResources
(content', resources') <- runStateT (sceneManipulate scene size event) resources
currentResources $= resources'
case content' of
Nothing -> return Terminate
Just scene' ->
let view' = view{ viewContent = Just scene' }
in return (Consume (modifyLabel (const view') treeLoc))
----------------------------------------------------------------------------------------------------
runDefaultApplication :: String -> IO ()
runDefaultApplication name = runApplication name createWorld createSceneUI
runAnotherApplication :: String -> IO ()
runAnotherApplication name = runApplication name createAnotherWorld createAnotherSceneUI
runApplication
:: String
-> (ResourceIO World)
-> (IORef World -> IORef Context -> IORef ResourceMap -> SceneUI)
-> IO ()
runApplication name worldBuilder sceneBuilder = do
let (w , h) = (800, 600)
size = GL.Size (fromIntegral w) (fromIntegral h)
(GLFW.Version x y z) <- GLFW.getVersion
infoM "Kage" ("Starting GLFW " ++ show x ++ "." ++ show y ++ "." ++ show z)
GLFW.setErrorCallback (Just (\e s -> errorM "Kage" (show e ++ ": " ++ show s)))
True <- GLFW.init
mapM_ GLFW.windowHint
[ GLFW.WindowHint'ContextVersionMajor 4 --
, GLFW.WindowHint'ContextVersionMinor 3 -- OpenGL >= 4.3 (required for compute shaders)
, GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core
, GLFW.WindowHint'Samples 4 -- 4x antialiasing (not very useful in deferred shading)
]
(Just window) <- GLFW.createWindow w h name Nothing Nothing
GLFW.makeContextCurrent (Just window)
GLFW.setWindowSize window w h -- must happen *after* 'createWindow'
mapM_ (\(k, v) -> GL.get v >>= infoM "Kage" . ((k ++ ": ") ++))
[ ("Renderer", GL.renderer)
, ("OpenGL version", GL.glVersion)
, ("Shading language version", GL.shadingLanguageVersion)
]
let resources0 = newResourceMap
((currentWorld, currentContext), resources1) <- flip runStateT resources0 $ do
currentWorld <- liftIO . newIORef =<< worldBuilder
currentContext <- liftIO . newIORef =<< createContext
return (currentWorld, currentContext)
currentResources <- newIORef resources1
uiRef <- newIORef (sceneBuilder currentWorld currentContext currentResources)
sizeRef <- newIORef size
quitRef <- newIORef False
GLFW.setWindowSizeCallback window $ Just $ \_ w h ->
sizeRef $= GL.Size (fromIntegral w) (fromIntegral h)
let doProcessEvent event = do
ui <- GL.get uiRef
ui' <- processEvent ui event
uiRef $= ui'
quitRef $= uiTerminated ui'
GLFW.setKeyCallback window $ Just $ \w k n ks mk ->
doProcessEvent (EventKey k n ks mk)
GLFW.setMouseButtonCallback window $ Just $ \w b bs mk ->
doProcessEvent (EventMouseButton b bs mk)
GLFW.setCursorPosCallback window $ Just $ \w x y ->
doProcessEvent (EventCursorPos x y)
GLFW.swapInterval 1 -- VSync on
GL.get currentResources >>= execStateT (do
-- run the main loop
mainLoop window currentWorld uiRef sizeRef quitRef (0, Nothing, Nothing)
-- cleaning
world <- GL.get currentWorld
disposeWorld world
context <- GL.get currentContext
disposeContext context
releaseUnreclaimedResources)
GLFW.destroyWindow window
GLFW.terminate
mainLoop
:: GLFW.Window
-> IORef World
-> IORef SceneUI
-> IORef GL.Size
-> IORef Bool
-> (Int, Maybe Double, Maybe Double)
-> ResourceIO ()
mainLoop window worldRef uiRef sizeRef quitRef (frameCount, mt0, mt1) = do
mt2 <- liftIO GLFW.getTime
let elapsedSeconds = fromMaybe 1 ((-) <$> mt2 <*> mt0)
(fps, timing) <- if elapsedSeconds > 0.25
then do
let fps = fromIntegral frameCount / elapsedSeconds
liftIO $ GLFW.setWindowTitle window ("Kage - OpenGL @ FPS: " ++ showGFloat (Just 2) fps "")
return (Just fps, (0, mt2, mt2))
else
return (Nothing, (frameCount + 1, mt0, mt2))
size@(GL.Size w h) <- GL.get sizeRef
uiRef $~ layout size
let frameDuration = fromMaybe 0 ((-) <$> mt2 <*> mt1)
GL.get worldRef >>= animateWorld frameDuration >>= ($=) worldRef
GL.get uiRef >>= animateUI frameDuration >>= ($=) uiRef
ui <- GL.get uiRef
when (w > 0) $ do -- avoid an upcoming divide by zero
liftIO $ GL.clear [GL.ColorBuffer]
renderViewTree size (uiRoot ui)
liftIO $ GLFW.swapBuffers window
liftIO GLFW.pollEvents
shouldQuit <- liftIO $ (||) <$> GL.get quitRef <*> GLFW.windowShouldClose window
if shouldQuit
then liftIO $ infoM "Kage" "Exiting"
else mainLoop window worldRef uiRef sizeRef quitRef timing
mf :: (b -> Bool) -> (a -> b) -> [a] -> [b]
mf = (. map) . (.) . filter
createSceneUI
:: IORef World
-> IORef Context
-> IORef ResourceMap
-> SceneUI
createSceneUI currentWorld currentContext currentResources = createUI ui where
masterScene = createScene DeferredRendering currentWorld currentContext
radarScene = createScene SimpleRendering currentWorld currentContext
[ssaoScene, positionScene, normalScene, albedoAndSpecularScene, shadowScene] =
map (`createColorBufferScene` currentContext) [0..4]
handleEvent = sceneHandleEvent currentResources
ui =
Node (createSceneView False adaptativeLayout handleEvent Nothing)
[ Node (createSceneView True (anchorLayout [AnchorConstraint (Just 50) (Just 50) Nothing Nothing]) handleEvent (Just masterScene))
[ Node (createSceneView False (fixedLayout (GL.Size 250 250)) handleEvent (Just radarScene)) []
]
, Node (createSceneView False defaultLayout handleEvent (Just ssaoScene)) []
, Node (createSceneView False defaultLayout handleEvent (Just positionScene)) []
, Node (createSceneView False defaultLayout handleEvent (Just normalScene)) []
, Node (createSceneView False defaultLayout handleEvent (Just albedoAndSpecularScene)) []
, Node (createSceneView False defaultLayout handleEvent (Just shadowScene)) []
]
createAnotherSceneUI
:: IORef World
-> IORef Context
-> IORef ResourceMap
-> SceneUI
createAnotherSceneUI currentWorld currentContext currentResources = createUI ui where
masterScene = createScene SimpleRendering currentWorld currentContext
handleEvent = sceneHandleEvent currentResources
ui = Node (createSceneView True defaultLayout handleEvent (Just masterScene)) []
animateUI :: Double -> SceneUI -> ResourceIO SceneUI
animateUI frameDuration ui = do
root' <- forM (uiRoot ui) $ \view -> do
let (_, size) = viewLocalBounds view
c <- case viewContent view of
Just scene -> Just <$> sceneAnimate scene size frameDuration
Nothing -> return Nothing
return view{ viewContent = c }
return $ ui{ uiRoot = root' }
renderViewTree :: GL.Size -> Tree (View (Maybe Scene)) -> ResourceIO ()
renderViewTree screenSize tree = do
let (GL.Size screenWidth screenHeigh) = screenSize
view = rootLabel tree
case viewContent view of
Just scene -> do
let (GL.Position x y, GL.Size w h) = viewLocalBounds view
liftIO $ GL.viewport $= (GL.Position x (screenHeigh - h - y), GL.Size w h)
liftIO $ GL.clear [GL.DepthBuffer]
sceneRender scene (GL.Size w h)
liftIO GL.flush
_ -> return ()
mapM_ (renderViewTree screenSize) (subForest tree)
|
Chatanga/kage
|
src/Graphics/Application.hs
|
mit
| 9,338 | 39 | 20 | 2,212 | 2,718 | 1,370 | 1,348 | 188 | 3 |
-- Problem 22
--
--Using names.txt (right click and 'Save Link/Target As...'), a 46K text
--file containing over five-thousand first names, begin by sorting it into
--alphabetical order. Then working out the alphabetical value for each
--name, multiply this value by its alphabetical position in the list to
--obtain a name score.
--
--For example, when the list is sorted into alphabetical order, COLIN,
--which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list.
--So, COLIN would obtain a score of 938 × 53 = 49714.
--
--What is the total of all the name scores in the file?
import qualified Data.Vector as V
import Data.List.Split
import Data.List
fileName = "p022_names.txt"
euler22 = do
file <- readFile fileName
print $ V.foldl (\n (i,xs) -> n + ((i + 1) * (sum xs))) 0 $ indexedVec file
where indexedVec = V.indexed . getValues
getValues :: String -> V.Vector [Int]
getValues s =V.fromList $ map (map (getValue)) $ (sort . getNames) s
where getNames = (splitOn ",") . (stripChars "\"")
getValue c = (fromEnum c) - 64
stripChars :: String -> String -> String
stripChars = filter . flip notElem
|
RossMeikleham/Project-Euler-Haskell
|
22.hs
|
mit
| 1,156 | 0 | 16 | 238 | 250 | 138 | 112 | 14 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.AbstractWorker
(error, AbstractWorker, castToAbstractWorker, gTypeAbstractWorker)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/AbstractWorker.onerror Mozilla AbstractWorker.onerror documentation>
error :: EventName AbstractWorker UIEvent
error = unsafeEventName (toJSString "error")
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/AbstractWorker.hs
|
mit
| 1,169 | 0 | 7 | 112 | 310 | 204 | 106 | 19 | 1 |
module Generator (
randomInt
, randomIntStreamFromGenerator
, randomIntListFromGenerator
, randomIntStream
, randomIntList
, randomStringFromGenerator
, randomStringStreamFromGenerator
, randomStringStream
, randomStreamOfStringStreams
, randomListOfStringStreams
, randomByteArray
, randomStreamOfByteArrays
, randomListOfByteArrays
) where
import System.Environment
import System.Random
import System.IO.Unsafe
import Data.Word
generateRandomIntStream :: (RandomGen g, Random a) => g -> [a]
--generateRandomIntStream gen = randoms gen
generateRandomIntStream gen = do
let (a, g) = random gen
in [a] ++ (generateRandomIntStream g)
randomByteArray :: (RandomGen g) => Int -> g -> [Word8]
randomByteArray n gen = take n (generateRandomIntStream gen :: [Word8])
randomStreamOfByteArrays :: (RandomGen g) => (Int, Int) -> g -> [[Word8]]
randomStreamOfByteArrays (min, max) gen =
let (n, nextGen) = randomInt (min, max) gen
in [randomByteArray n gen] ++ (randomStreamOfByteArrays (min, max) nextGen)
randomListOfByteArrays :: (RandomGen g) => (Int, Int) -> Int -> g -> [[Word8]]
randomListOfByteArrays (min, max) n gen
| n == 0 = []
| otherwise = do
let (n, nextGen) = randomInt (min, max) gen
in [randomByteArray n gen] ++ (randomListOfByteArrays (min, max) (n - 1) nextGen)
randomInt :: (RandomGen g) => (Int, Int) -> g -> (Int, g)
randomInt (min, max) gen = randomR (min, max) gen
randomIntStreamFromGenerator :: (RandomGen g) => (Int, Int) -> g -> [Int]
randomIntStreamFromGenerator (low, high) gen =
let (n, nextGen) = randomInt (low, high) gen
in [n] ++ (randomIntStreamFromGenerator (low, high) nextGen)
--_modSwap a b = mod b a
--(Prelude.map (+ low) (Prelude.map (_modSwap (high - low)) (randoms gen)))
randomIntListFromGenerator :: (RandomGen g) => (Int, Int) -> Int -> g -> [Int]
randomIntListFromGenerator (low, high) n gen
| n == 0 = []
| otherwise = do
let (toss, nextGen) = randomInt (low, high) gen
let nextString = take 1 (randomIntStreamFromGenerator (low, high) gen)
in nextString ++ (randomIntListFromGenerator (low, high) (n - 1) nextGen)
randomIntStream (low, high) = randomIntStreamFromGenerator (low, high)
randomIntList (low, high) n = randomIntListFromGenerator (low, high) n
randomCharStreamFromGenerator :: (RandomGen g) => g -> [Char]
randomCharStreamFromGenerator gen =
let (c, g) = randomR ('a', 'z') gen
in [c] ++ (randomCharStreamFromGenerator g)
randomStringFromGenerator :: (RandomGen g) => Int -> g -> String
randomStringFromGenerator len gen = take len (randomCharStreamFromGenerator gen)
_randomStringSwap :: (RandomGen g) => g -> Int -> String
_randomStringSwap gen val = randomStringFromGenerator val gen
randomStringStreamFromGenerator :: (RandomGen g) => (Int, Int) -> g -> [String]
randomStringStreamFromGenerator (low, high) gen = Prelude.map (_randomStringSwap gen) (randomIntStreamFromGenerator (low, high) gen)
randomStringListFromGenerator :: (RandomGen g) => (Int, Int) -> Int -> g -> [String]
randomStringListFromGenerator (low, high) n gen
| n == 0 = []
| otherwise = do
let (toss, nextGen) = randomInt (low, high) gen
let nextString = take 1 (randomStringStreamFromGenerator (low, high) gen)
in nextString ++ (randomStringListFromGenerator (low, high) (n - 1) nextGen)
randomStringStream (low, high) = randomStringStreamFromGenerator (low, high)
randomStringList (low, high) n = randomStringListFromGenerator (low, high) n
_randomListOfStringsMap :: (RandomGen g) => (Int, Int) -> g -> Int -> [String]
_randomListOfStringsMap (low, high) g n = randomStringList (low, high) n g
randomStreamOfStringStreams :: (RandomGen g) => (Int, Int) -> (Int, Int) -> g -> [[String]]
randomStreamOfStringStreams (low, high) (elow, ehigh) g = do
Prelude.map (_randomListOfStringsMap (elow, ehigh) g) (randomIntStream (low, high) g)
randomListOfStringStreams :: (RandomGen g) => (Int, Int) -> (Int, Int) -> Int -> g -> [[String]]
randomListOfStringStreams (low, high) (elow, ehigh) n g
| n == 0 = []
| otherwise = do
let (toss, nextGen) = randomInt (low, high) g
let nextStringList = take 1 (randomStreamOfStringStreams (low, high) (elow, ehigh) g)
in nextStringList ++ (randomListOfStringStreams (low, high) (elow, ehigh) (n - 1) nextGen)
|
chris-wood/ccnx-pktgen
|
src/Generator.hs
|
mit
| 4,429 | 0 | 15 | 839 | 1,617 | 882 | 735 | 80 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Server
( createServer
) where
import Control.Concurrent
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Network
import qualified Paradise.API as API
import qualified Paradise.Client as Paradise
import Paradise.Utils
import System.IO
import Text.Regex.PCRE
parse :: Handle -> Paradise.PlayerData -> B.ByteString
-> IO Paradise.PlayerData
parse client pdata result = do
B.hPutStr client clearScreenCode
B.hPutStr client homeRowCode
let action p r | r =~ API.vtRegexp = API.goto p r
| otherwise = do
B.hPutStr client =<< stripHTML result
B.hPutStr client "\r\n"
API.update p
(newdata, res) <- action pdata result
B.hPutStr client res
B.hPutStr client "\r\n\r\n"
return newdata
command :: Handle -> Paradise.PlayerData -> B.ByteString
-> IO Paradise.PlayerData
command client pdata "exit" = close client pdata
command client pdata "quit" = close client pdata
command client pdata line =
API.act line pdata
>>= parse client pdata
>>= return
close :: Handle -> Paradise.PlayerData -> IO Paradise.PlayerData
close client pdata = do
B.hPutStr client "\r\nGoodbye!\r\n"
hClose client
return pdata
handle :: Handle -> Paradise.PlayerData -> Bool -> IO ()
handle client pdata True = return ()
handle client pdata False = do
-- Read input and execute it
line <- B.hGetLine client
pdata <- command client pdata line
-- Continue if there is more data
handle client pdata =<< hIsEOF client
acceptAll :: Socket -> IO ()
acceptAll sock = do
(client, _, _) <- accept sock
hSetBuffering client NoBuffering
forkIO $ do
let pdata = (Paradise.PlayerData "3")
parse client pdata "::3"
handle client pdata False
acceptAll sock
createServer :: PortNumber -> IO ()
createServer port = withSocketsDo $ do
-- Create socket and accept everyone
sock <- listenOn $ PortNumber port
acceptAll sock
sClose sock
|
Hamcha/netslum
|
Server.hs
|
mit
| 2,274 | 0 | 15 | 707 | 633 | 302 | 331 | 59 | 1 |
{-
**************************************************************
* Filename : RRegTypes.hs *
* Author : Markus Forsberg *
* [email protected] *
* Last Modified : 5 July, 2001 *
* Lines : 113 *
**************************************************************
-}
module FST.RRegTypes ( module FST.RegTypes,
RReg(..), -- data type for regular relations.
-- (<|>), -- union combinator for regular relations.
-- (|>), -- product combinator for regular relations.
-- star, -- Kleene's star for regular relations.
-- plus, -- Kleene's plus for regular relations.
-- empty, -- The empty set of regular relations.
(<*>), -- Cross product opertor.
(<.>), -- Composition operator.
idR, -- Identity relation.
r, -- Relation.
-- symbols -- Collect the symbols in a regular relations.
) where
import FST.RegTypes
import FST.TransducerTypes (Symbol(..))
import Data.List(nub)
{- *************************************
* Datatype for a regular relations *
*************************************
-}
data RReg a
= Cross (Reg a) (Reg a) -- ^ Cross product
| Comp (RReg a) (RReg a) -- ^ Composition
| ProductR (RReg a) (RReg a) -- ^ Concatenation
| UnionR (RReg a) (RReg a) -- ^ Union
| StarR (RReg a) -- ^ Kleene star
| Identity (Reg a) -- ^ Identity relation
| Relation (Symbol a) (Symbol a) -- ^ (a:b)
| EmptyR -- ^ Empty language
deriving (Eq)
{- *************************************
* Instance of Combinators (RReg a) *
*************************************
-}
instance Eq a => Combinators (RReg a) where
EmptyR <|> r2 = r2 -- [ r1 | [] ] = r1
r1 <|> EmptyR = r1 -- [ [] | r2 ] = r2
r1 <|> r2
| r1 == r2 = r1 -- [ r1 | r1 ] = r1
| otherwise = UnionR r1 r2
EmptyR |> _ = EmptyR -- [ [] r2 ] = []
_ |> EmptyR = EmptyR -- [ r1 [] ] = []
r1 |> r2 = ProductR r1 r2
star (StarR r1) = star r1 -- [ r1* ]* = r1*
star r1 = StarR r1
plus r1 = r1 |> star r1
empty = EmptyR
infixl 2 <*>
infixl 1 <.>
-- Cross product operator.
(<*>) :: Eq a => Reg a -> Reg a -> RReg a
(<*>) = Cross
-- Composition operator
(<.>) :: Eq a => RReg a -> RReg a -> RReg a
(<.>) = Comp
-- Identity relation.
idR :: Eq a => Reg a -> RReg a
idR = Identity
r :: Eq a => a -> a -> RReg a
r a b = Relation (S a) (S b)
{- *************************************
* Instance of Symbols (RReg a) *
*************************************
-}
instance Symbols RReg where
symbols (Cross r1 r2) = nub $ symbols r1 ++ symbols r2
symbols (Comp r1 r2) = nub $ symbols r1 ++ symbols r2
symbols (ProductR r1 r2) = nub $ symbols r1 ++ symbols r2
symbols (UnionR r1 r2) = nub $ symbols r1 ++ symbols r2
symbols (StarR r1) = symbols r1
symbols (Identity r1) = symbols r1
symbols (Relation a b) = let sym (S c) = [c]
sym _ = []
in nub $ sym a ++ sym b
symbols _ = []
{- *************************************
* Instance of Show (RReg a) *
*************************************
-}
instance Show a => Show (RReg a) where
show (Cross r1 r2) = "[ " ++ show r1 ++ " .x. " ++ show r2 ++ " ]"
show (Comp r1 r2) = "[ " ++ show r1 ++ " .o. " ++ show r2 ++ " ]"
show (UnionR r1 r2) = "[ " ++ show r1 ++ " | " ++ show r2 ++ " ]"
show (ProductR r1 r2)= "[ " ++ show r1 ++ " " ++ show r2 ++ " ]"
show (Identity r) = show r
show (StarR r) = "[ " ++ show r ++ " ]*"
show (Relation a b) = "[ " ++ show a ++":"++show b ++" ]"
show (EmptyR) = "[]"
|
SAdams601/ParRegexSearch
|
test/fst-0.9.0.1/FST/RRegTypes.hs
|
mit
| 4,271 | 0 | 12 | 1,656 | 1,058 | 544 | 514 | 62 | 1 |
module WildcardSpec where
import Text.Wildcard
import Test.Hspec
import Test.QuickCheck hiding ((.&.))
spec :: Spec
spec = do
describe "test" $ do
it "matches to any string with *" $ property $ \x ->
(x :: String) `match` "*"
it "bachward match" $ property $ \x ->
("hoge" ++ x) `match` "hoge*"
it "forward match" $ property $ \x -> nonWild x ==>
(x ++ "hoge") `match` "*hoge"
it "intermediate match" $ property $ \x -> nonWild x ==>
("hoge" ++ x ++ "fuga") `match` "hoge*fuga"
it "matches forward and backward" $ property $ \x y -> nonWild x && nonWild y ==>
(x ++ "hoge" ++ y) `match` "*hoge*"
where
nonWild = not . elem '*'
|
ayachigin/wildcard
|
test/WildcardSpec.hs
|
mit
| 743 | 0 | 16 | 232 | 258 | 137 | 121 | 18 | 1 |
module Streamer.SessionManager.DigestsFile
( consumeDgstFile
, collectDigestFileEntries
) where
import Data.Maybe
import Streamer.Util ( maybeRead )
import Control.Concurrent ( threadDelay )
import System.IO ( IOMode(ReadMode)
, openFile
, hSeek
, SeekMode(AbsoluteSeek)
, hGetContents )
import System.Posix.Files ( getFileStatus, fileSize )
import Control.Monad.STM ( atomically )
import qualified Control.Concurrent.STM.TQueue as STQ
-- How much to wait if the digests file EOF found, in microseconds
consumeDigestsFileDelay :: Int
consumeDigestsFileDelay = 400000
-- | Consumes lines from a digest file and appends the lines to an TQueue. Takes
-- as arguments a FilePath, a TQueue, and a number representing the position in
-- file where it should start consuming, usually 0. The third parameter
-- indicates how many bytes to initially skip before starting to append to the
-- TQueue.
--
-- This function never returns (it will continue to call itself recursively),
-- therefore it should execute in its own thread.
--
-- Example:
-- > queue <- STQ.newTQueueIO :: IO (STQ.TQueue String)
-- > forkIO (consumeDgstFile "/tmp/a" 0 queue)
--
-- NB: Rewritten using example from: https://gist.github.com/ijt/1055731.
consumeDgstFile ::
FilePath -- ^ Path to the file which contains digests
-> Integer -- ^ Last known position in the file
-> STQ.TQueue (String) -- ^ Queue where we redirect the digests
-> IO ()
consumeDgstFile p s q = do
stat <- getFileStatus p
if (newS stat) <= s
then threadDelay consumeDigestsFileDelay >> consumeDgstFile p s q
else do
h <- openFile p ReadMode
hSeek h AbsoluteSeek s
lz <- hGetContents h
putStrLn $ "Consumed from " ++ (show s) ++ " until "
++ (show $ newS stat) ++ "; total: "
++ (show $ length (lines lz))
mapM_ (\l -> atomically $ STQ.writeTQueue q l) $ lines lz
consumeDgstFile p (newS stat) q
where
newS stt = fromIntegral $ fileSize stt :: Integer
-- | Collects entries from the digest file until either K are found or there is
-- no available entry. Optionally it takes as parameter a list of sequence
-- numbers to be skipped over.
--
-- Uses: 'getDigestFileEntry'
collectDigestFileEntries ::
STQ.TQueue (String) -- queue with digest lines
-> Int -- limit on the number of returned entries
-> [(Int,String)] -- accumulator
-> IO [(Int, String)]
collectDigestFileEntries _ 0 ac = return ac
collectDigestFileEntries q l ac = do
mEntry <- getDigestFileEntry q
case mEntry of
Just entry -> collectDigestFileEntries q (l-1) (ac++[entry])
Nothing -> return ac
--------------------------------------------------------------------------------
-- | Reads the next entry from the digest file. An entry has the form of a tuple
-- (sequence number, digest).
-- The digest file is represented as a fifo queue (STM.TQueue).
-- Non-blockin function: if there is no entry available, it returns Nothing.
getDigestFileEntry ::
STQ.TQueue (String) -- queue with digest lines
-> IO (Maybe (Int, String))
getDigestFileEntry queue = do
mLine <- atomically $ STQ.tryReadTQueue queue
case mLine of
Just digestLine -> do
let maybeFmTuple = digestLineToFrameMetadata digestLine
case maybeFmTuple of
Just (seqNr, digest) -> return $ Just (seqNr, digest)
Nothing -> putStrLn ("Couldn't parse line: " ++ show digestLine)
>> return Nothing
Nothing -> return Nothing
--------------------------------------------------------------------------------
-- | Takes a string (as read from the digests file) and parses it, yielding a
-- sequence number and the associated digest.
--
-- For example,
-- > digestLineToFrameMetadata
-- "2 076a27c79e5ace2a3d47f9dd2e83e4ff6ea8872b3c2218f66c92b89b55f36560"
-- will output the following tuple:
-- > ("2", "076a27c79e5ace2a3d47f9dd2e83e4ff6ea8872b3c2218f66c92b89b55f36560")
digestLineToFrameMetadata ::
String
-> Maybe (Int, String)
digestLineToFrameMetadata "" = Nothing
digestLineToFrameMetadata line
| (length items == 2) && (isJust seqNr) && (length digest == 64) =
Just (fromJust seqNr, digest)
| otherwise = Nothing
where
items = words line
seqNr = maybeRead $ items!!0 :: Maybe Int
digest = items!!1
|
adizere/nifty-tree
|
src/Streamer/SessionManager/DigestsFile.hs
|
mit
| 4,870 | 0 | 19 | 1,420 | 821 | 440 | 381 | 70 | 3 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for @xm list --long@ parser -}
{-
Copyright (C) 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.Hypervisor.Xen.XmParser
( testHypervisor_Xen_XmParser
) where
import Test.HUnit
import Test.QuickCheck as QuickCheck hiding (Result)
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Control.Monad (liftM)
import qualified Data.Attoparsec.Text as A
import Data.Text (pack)
import Data.Char
import qualified Data.Map as Map
import Text.Printf
import Ganeti.Hypervisor.Xen.Types
import Ganeti.Hypervisor.Xen.XmParser
{-# ANN module "HLint: ignore Use camelCase" #-}
-- * Arbitraries
-- | Generator for 'ListConfig'.
--
-- A completely arbitrary configuration would contain too many lists
-- and its size would be to big to be actually parsable in reasonable
-- time. This generator builds a random Config that is still of a
-- reasonable size, and it also Avoids generating strings that might
-- be interpreted as numbers.
genConfig :: Int -> Gen LispConfig
genConfig 0 =
-- only terminal values for size 0
frequency [ (5, liftM LCString (genName `suchThat` (not . canBeNumber)))
, (5, liftM LCDouble arbitrary)
]
genConfig n =
-- for size greater than 0, allow "some" lists
frequency [ (5, liftM LCString (resize n genName `suchThat`
(not . canBeNumber)))
, (5, liftM LCDouble arbitrary)
, (1, liftM LCList (choose (1, n) >>=
(\n' -> vectorOf n' (genConfig $ n `div` n'))))
]
-- | Arbitrary instance for 'LispConfig' using 'genConfig'.
instance Arbitrary LispConfig where
arbitrary = sized genConfig
-- | Determines conservatively whether a string could be a number.
canBeNumber :: String -> Bool
canBeNumber [] = False
canBeNumber (c:[]) = canBeNumberChar c
canBeNumber (c:xs) = canBeNumberChar c && canBeNumber xs
-- | Determines whether a char can be part of the string representation of a
-- number (even in scientific notation).
canBeNumberChar :: Char -> Bool
canBeNumberChar c = isDigit c || (c `elem` "eE-")
-- | Generates an arbitrary @xm uptime@ output line.
instance Arbitrary UptimeInfo where
arbitrary = do
name <- genFQDN
NonNegative idNum <- arbitrary :: Gen (NonNegative Int)
NonNegative days <- arbitrary :: Gen (NonNegative Int)
hours <- choose (0, 23) :: Gen Int
mins <- choose (0, 59) :: Gen Int
secs <- choose (0, 59) :: Gen Int
let uptime :: String
uptime =
if days /= 0
then printf "%d days, %d:%d:%d" days hours mins secs
else printf "%d:%d:%d" hours mins secs
return $ UptimeInfo name idNum uptime
-- * Helper functions for tests
-- | Function for testing whether a domain configuration is parsed correctly.
testDomain :: String -> Map.Map String Domain -> Assertion
testDomain fileName expectedContent = do
fileContent <- readTestData fileName
case A.parseOnly xmListParser $ pack fileContent of
Left msg -> assertFailure $ "Parsing failed: " ++ msg
Right obtained -> assertEqual fileName expectedContent obtained
-- | Function for testing whether a @xm uptime@ output (stored in a file)
-- is parsed correctly.
testUptimeInfo :: String -> Map.Map Int UptimeInfo -> Assertion
testUptimeInfo fileName expectedContent = do
fileContent <- readTestData fileName
case A.parseOnly xmUptimeParser $ pack fileContent of
Left msg -> assertFailure $ "Parsing failed: " ++ msg
Right obtained -> assertEqual fileName expectedContent obtained
-- | Computes the relative error of two 'Double' numbers.
--
-- This is the \"relative error\" algorithm in
-- http:\/\/randomascii.wordpress.com\/2012\/02\/25\/
-- comparing-floating-point-numbers-2012-edition (URL split due to too
-- long line).
relativeError :: Double -> Double -> Double
relativeError d1 d2 =
let delta = abs $ d1 - d2
a1 = abs d1
a2 = abs d2
greatest = max a1 a2
in if delta == 0
then 0
else delta / greatest
-- | Determines whether two LispConfig are equal, with the exception of Double
-- values, that just need to be \"almost equal\".
--
-- Meant mainly for testing purposes, given that Double values may be slightly
-- rounded during parsing.
isAlmostEqual :: LispConfig -> LispConfig -> Property
isAlmostEqual (LCList c1) (LCList c2) =
(length c1 ==? length c2) .&&.
conjoin (zipWith isAlmostEqual c1 c2)
isAlmostEqual (LCString s1) (LCString s2) = s1 ==? s2
isAlmostEqual (LCDouble d1) (LCDouble d2) = printTestCase msg $ rel <= 1e-12
where rel = relativeError d1 d2
msg = "Relative error " ++ show rel ++ " not smaller than 1e-12\n" ++
"expected: " ++ show d2 ++ "\n but got: " ++ show d1
isAlmostEqual a b =
failTest $ "Comparing different types: '" ++ show a ++ "' with '" ++
show b ++ "'"
-- | Function to serialize LispConfigs in such a way that they can be rebuilt
-- again by the lispConfigParser.
serializeConf :: LispConfig -> String
serializeConf (LCList c) = "(" ++ unwords (map serializeConf c) ++ ")"
serializeConf (LCString s) = s
serializeConf (LCDouble d) = show d
-- | Function to serialize UptimeInfos in such a way that they can be rebuilt
-- againg by the uptimeLineParser.
serializeUptime :: UptimeInfo -> String
serializeUptime (UptimeInfo name idNum uptime) =
printf "%s\t%d\t%s" name idNum uptime
-- | Test whether a randomly generated config can be parsed.
-- Implicitly, this also tests that the Show instance of Config is correct.
prop_config :: LispConfig -> Property
prop_config conf =
case A.parseOnly lispConfigParser . pack . serializeConf $ conf of
Left msg -> failTest $ "Parsing failed: " ++ msg
Right obtained -> printTestCase "Failing almost equal check" $
isAlmostEqual obtained conf
-- | Test whether a randomly generated UptimeInfo text line can be parsed.
prop_uptimeInfo :: UptimeInfo -> Property
prop_uptimeInfo uInfo =
case A.parseOnly uptimeLineParser . pack . serializeUptime $ uInfo of
Left msg -> failTest $ "Parsing failed: " ++ msg
Right obtained -> obtained ==? uInfo
-- | Test a Xen 4.0.1 @xm list --long@ output.
case_xen401list :: Assertion
case_xen401list = testDomain "xen-xm-list-long-4.0.1.txt" $
Map.fromList
[ ("Domain-0", Domain 0 "Domain-0" 184000.41332 ActualRunning Nothing)
, ("instance1.example.com", Domain 119 "instance1.example.com" 24.116146647
ActualBlocked Nothing)
]
-- | Test a Xen 4.0.1 @xm uptime@ output.
case_xen401uptime :: Assertion
case_xen401uptime = testUptimeInfo "xen-xm-uptime-4.0.1.txt" $
Map.fromList
[ (0, UptimeInfo "Domain-0" 0 "98 days, 2:27:44")
, (119, UptimeInfo "instance1.example.com" 119 "15 days, 20:57:07")
]
testSuite "Hypervisor/Xen/XmParser"
[ 'prop_config
, 'prop_uptimeInfo
, 'case_xen401list
, 'case_xen401uptime
]
|
narurien/ganeti-ceph
|
test/hs/Test/Ganeti/Hypervisor/Xen/XmParser.hs
|
gpl-2.0
| 7,668 | 9 | 17 | 1,611 | 1,492 | 788 | 704 | 116 | 2 |
{-# LANGUAGE DeriveDataTypeable, TypeSynonymInstances, MultiParamTypeClasses #-}
module Algebraic2.Central where
import Algebraic2.Instance
import Algebraic2.Class
import Expression.Op
import Challenger.Partial
import Inter.Types
import qualified Autolib.TES.Binu as B
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Reporter
import Autolib.Reporter.Set
import Autolib.Size
import Autolib.Set
import Autolib.FiniteMap
import Data.Typeable
newtype T t = T t deriving (Typeable)
instance OrderScore (T t) where
scoringOrder _ = Increasing
instance Show t => Show (T t) where
show (T t) = show t
instance Read t => Read (T t) where
readsPrec d s = [(T t, s') | (t, s') <- readsPrec d s]
instance Algebraic tag context a
=> Partial (T tag) ( Algebraic2.Instance.Type context a ) ( Exp a ) where
report (T p) i = do
introduce p $ context i
inform $ vcat
[ text "Gesucht ist ein Ausdruck (Term) mit dieser Bedeutung:"
, nest 4 $ case description i of
Nothing -> toDoc $ target i
Just cs -> text cs
, text "Der Ausdruck soll höchstens die Größe"
<+> toDoc (max_size i) <+> text "haben."
, text "Sie dürfen diese Symbole benutzen"
, nest 4 $ nice $ operators i
, text "und diese vordefinierten Konstanten:"
, nest 4 $ case fmToList $ predefined i of
[] -> parens $ text "keine"
bzs -> vcat $ do
( b, z ) <- bzs
return $ hsep [ toDoc b, text "=", toDoc z ]
]
present p $ target i
initial (T p) i = some_formula p i
partial (T p) i b = do
inform $ vcat
[ text "Die Baumstruktur Ihrer Einsendung ist:"
, nest 4 $ draw b
, text ""
]
silent $ Autolib.Reporter.Set.subeq
( parens $ text "benutzte Operatoren" , syms b )
( parens $ text "erlaubte Operatoren"
, mkSet $ flatten $ operators i
)
silent $ Autolib.Reporter.Set.subeq
( parens $ text "benutzte Konstanten" , vars b )
( parens $ text "erlaubte Konstanten"
, mkSet $ keysFM $ predefined i
)
let s = size b
inform $ text "Die Größe Ihres Ausdrucks ist" <+> toDoc s
when ( s > max_size i ) $ reject $ text "Das ist zuviel."
total (T p) i b = do
v <- evaluateC p ( context i ) ( predefined i ) b
eq <- equivalent p ( target i ) v
when ( not eq ) $ reject $ text "nicht äquivalent"
make :: Algebraic tag context m
=> tag -> Make
make tag = direct (T tag) $ default_instance tag
instance ( Reader c, ToDoc c ) => Nice ( B.Binu c ) where
nice b = vcat
[ text "zweistellige :" <+> toDoc ( B.binary b )
, text "einstellige :" <+> toDoc ( B.unary b )
, text "nullstellige :" <+> toDoc ( B.nullary b )
]
|
Erdwolf/autotool-bonn
|
src/Algebraic2/Central.hs
|
gpl-2.0
| 2,824 | 33 | 22 | 831 | 980 | 493 | 487 | 72 | 1 |
import System.IO
-- f = g 2
-- g a 1 = []
-- g a n = if n `mod` a == 0 then a : g a (n `div` a) else g (a+1) n
-- h x = [y | y<-[1..x], x `mod` y == 0]
-- i = j 0
-- j a (x:y:s) = if x == y then j (a+1) (y:s) else (a+1) : j 0 (y:s); j a [_] = [a+1]
-- j _ [] = []
-- k = product . map (1+) . i . f
-- main = putStrLn . concatMap (\ x -> if all even . i . f $ x then show x ++ "," else ".") . id $ (filter (\ x -> x `mod` 1000 == 576) $ scanl (+) 1 [2..])
-- let f ((x:s):xss) = x : zipWith (.) s (f xss); lamps = zipWith (flip id) (repeat False) . f $ map (\ n -> cycle (not : replicate (n-1) id)) [1..] in putStrLn $ concatMap (\ x -> if x then "X" else "_") lamps
-- sqrtBig :: Integer -> Integer
--sqrtBig n = head . dropWhile ((n<).(^2)) $ iterate f (n`div`2) where
sqrtBig n = head . dropWhile ((n<).(^2)) $ iterate f n where
f x = (x + n `div` x) `div` 2
isSquare :: Integer -> Bool
isSquare n = n == sn * sn where
sn = sqrtBig n
factors :: [Integer] -> Integer -> [Integer]
factors ps x = f (takeWhile (<= sqrtBig x) ps) x where
f _ 1 = []
f xs@(x:s) n = if m == 0 then x : f xs d else f s n where
(d,m) = divMod n x
f [] n = [n]
primes :: [Integer]
primes = 2 : [ x | x <- [3..], [_] <- [factors primes x]]
primes' = sieve [2..] where
sieve (x:s) = x : sieve (filter ((0/=) . flip mod x) s)
i :: [Integer] -> [Integer]
i = j 0 where
j a (x:y:s) = if x == y then j (a+1) (y:s) else (a+1) : j 0 (y:s)
j a [_] = [a+1]
j _ [] = []
dragonPositions :: [Integer]
-- dragonPositions = filter f $ scanl (+) 1 [2..] where
-- f x = x `mod` 1000 == 576 && x `mod` 16 == 0
dragonPositions = filter p . map f $ concatMap (\x -> [32 * x - 1, 32 * x]) [1,3..] where
f n = (n*(n+1)) `div` 2
p x = x `mod` 1000 == 576
progressFind :: (Integer -> Bool) -> [Integer] -> IO ()
progressFind p = putStrLn . concatMap (\ x -> if p x then show x ++ "," else ".")
main :: IO ()
main = do
-- hSetBuffering stdout NoBuffering
-- progressFind (all even . i . factors primes) dragonPositions
progressFind isSquare dragonPositions
{-
filter isSquare $ scanl (+) 1 [2..] ~>
[1,36,1225,41616,1413721,48024900,1631432881,55420693056,1882672131025,...
1^2 = 1 = 1 * 2 / 2
6^2 = 36 = 8 * 9 / 2
35^2 = 1225 = 49 * 50 / 2
204^2 = 41616 = 288 * 289 / 2
1189^2 = 1413721 = 1681 * 1682 / 2
-}
|
xkollar/handy-haskell
|
other/pt-2012-01/main.hs
|
gpl-3.0
| 2,392 | 3 | 13 | 673 | 728 | 392 | 336 | 30 | 4 |
{-# LANGUAGE GADTs #-}
module SKI where
data T t where
S :: T ((a -> b -> c) -> (a -> b) -> a -> c)
K :: T (a -> b -> a)
I :: T (a -> a)
(:$) :: T (a -> b) -> T a -> T b
instance Show (T t) where
show S = "s"
show K = "k"
show I = "i"
show (a :$ b) = show a ++ "(" ++ show b ++ ")"
type TChurch a = T ((a -> a) -> (a -> a))
encodeCharT :: Char -> TChurch a
encodeCharT '\n' = K :$ I
encodeCharT c = let
p = encodeCharT (pred c)
in
S
:$ ( S
:$ (K :$ S)
:$ (S :$ (K :$ K) :$ I)
)
:$ ( S
:$ (S :$ (K :$ S) :$ (S :$ (K :$ K) :$ (S :$ (K :$ p) :$ I)))
:$ (K :$ I)
)
|
KenetJervet/mapensee
|
haskell/theorem-proving/SKI/SKI.hs
|
gpl-3.0
| 631 | 28 | 19 | 233 | 380 | 206 | 174 | 24 | 1 |
{-# language DeriveFunctor, GeneralizedNewtypeDeriving #-}
module Control.Iterative.Internal (IterativeT(..), runIterativeT) where
import Control.Monad.Reader (MonadReader(..))
import Control.Monad.State.Strict (MonadState(..), get, put)
import Control.Monad.Trans.Class (MonadTrans(..), lift)
import Control.Monad.Trans.State.Strict (StateT(..), runStateT)
import Control.Monad.Trans.Reader (ReaderT(..), runReaderT)
import Control.Monad.Log (MonadLog(..), LoggingT(..), runLoggingT, Handler, logMessage)
import Control.Monad.Catch (MonadThrow(..), throwM)
-- | Iterative algorithms need configuration, state and logging; here we use a transformer stack of ReaderT + StateT + LoggingT (from `logging-effect`).
--
-- The idea is to compose the plumbing of iterative programs from 'MonadState', 'MonadReader' and 'MonadLog' instructions (the "specification" of the effects to be used), which is usually referred to as the "@mtl@ style".
--
-- Example usage:
--
-- @
-- mkIterativeT :: Monad m =>
-- (a -> s -> message)
-- -> (s -> r -> (a, s))
-- -> IterativeT r message s m a
-- mkIterativeT flog fs = 'IterativeT' $ do
-- s <- 'get'
-- c <- 'ask'
-- let (a, s') = fs s c
-- 'logMessage' $ flog a s'
-- 'put' s'
-- return a
-- @
--
newtype IterativeT c msg s m a =
IterativeT { unIterativeT :: ReaderT c (StateT s (LoggingT msg m)) a } deriving (Functor, Applicative, Monad, MonadReader c, MonadState s, MonadLog msg)
instance MonadTrans (IterativeT c msg s) where
lift = liftIterativeT
liftIterativeT :: Monad m => m a -> IterativeT c msg s m a
liftIterativeT m = IterativeT . lift . lift $ LoggingT mlog
where mlog = ReaderT (const m)
instance MonadThrow m => MonadThrow (IterativeT c msg s m) where
throwM e = lift $ throwM e
-- | Run an 'IterativeT' computation, return result and final state
runIterativeT :: Handler m message -- ^ Logging handler
-> r -- ^ Configuration
-> s -- ^ Initial state
-> IterativeT r message s m a
-> m (a, s) -- ^ (result, final state)
runIterativeT lh c x0 m =
runLoggingT (runStateT (runReaderT (unIterativeT m) c) x0) lh
execIterativeT :: Functor m =>
Handler m message
-> r
-> s
-> IterativeT r message s m a
-> m s
execIterativeT lh c x0 m = snd <$> runIterativeT lh c x0 m
|
ocramz/sparse-linear-algebra
|
src/Control/Iterative/Internal.hs
|
gpl-3.0
| 2,418 | 0 | 11 | 564 | 558 | 322 | 236 | 32 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module InnerEar.Exercises.FrequencyEnvelope (frequencyEnvelopeExercise) where
import Reflex
import Reflex.Dom
import Data.Map
import Text.JSON
import Text.JSON.Generic
import Sound.MusicW
import InnerEar.Exercises.MultipleChoice
import InnerEar.Types.ExerciseId
import InnerEar.Types.Exercise
import InnerEar.Types.Score
import InnerEar.Types.MultipleChoiceStore
import InnerEar.Widgets.Config
import InnerEar.Widgets.SpecEval
import InnerEar.Types.Data hiding (Time)
import InnerEar.Types.Frequency
import InnerEar.Types.Utility
import InnerEar.Widgets.AnswerButton
type Similarity = Int
type Duration = Int
type Octave = Double
type Config = (Similarity,Duration,Octave)
similarities :: [Similarity]
similarities = [1,2,3,4]
durations :: [Duration]
durations = [1000,500,250,125,100,80,60,40,20]
octaves :: [Octave]
octaves = [8.0,4.0,2.0,1.0,0.5,1/6,1/12]
data Answer = Quicker | Linear | Slower
deriving (Eq,Ord,Data,Typeable,Show)
instance Buttonable Answer where
makeButton = showAnswerButton
answers = [Quicker,Linear,Slower]
getEnvelope :: Similarity -> Answer -> (Double -> Double)
getEnvelope s Quicker = riseToRiseAndFall $ quickerEnvelope (similarityToExp s)
getEnvelope s Linear = riseToRiseAndFall $ linearEnvelope (similarityToExp s)
getEnvelope s Slower = riseToRiseAndFall $ slowerEnvelope (similarityToExp s)
similarityToExp :: Int -> Double
similarityToExp 1 = 3
similarityToExp 2 = 2
similarityToExp 3 = 1.5
similarityToExp 4 = 1.25
slowerEnvelope :: Double -> Double -> Double
slowerEnvelope e x = x**e
linearEnvelope :: Double -> Double -> Double
linearEnvelope _ x = x
quickerEnvelope :: Double -> Double -> Double
quickerEnvelope e x = 1 - (slowerEnvelope e (1-x))
lowPitch :: Octave -> Double -- double is Frequency
lowPitch o = midicps $ 69-(o*12/2)
highPitch :: Octave -> Double -- double is Frequency
highPitch o = midicps $ 69+(o*12/2)
actualEnvelope :: Config -> Answer -> Double -> Double
actualEnvelope (s,d,o) a = scaleRange (lowPitch o) (highPitch o) $ scaleDomain 0.0 (fromIntegral(d)/1000.0) $ getEnvelope s a
sampleEnvelope :: Int -> (Double -> Double) -> Duration -> [Double]
sampleEnvelope r f d = fmap (f . (\x -> x * fromIntegral(d)/1000.0/fromIntegral(r))) $ fmap fromIntegral [0, 1 .. (r-1)]
renderAnswer :: Map String AudioBuffer -> Config -> (SourceNodeSpec, Maybe Time)-> Maybe Answer -> Synth ()
renderAnswer _ c@(s, d, o) _ (Just ans) = buildSynth_ $ do
let dur = Millis $ fromIntegral d
let curve = sampleEnvelope 200 (actualEnvelope c ans) d
let env = unitRectEnv (Millis 1) dur --maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur
setDeletionTime $ dur + Millis 200
oscillator Triangle (Hz 0) >>= curveToParamValue "frequency" curve (Sec 0) dur
gain (Db $ fromIntegral $ -20)
env
destination
renderAnswer _ _ _ Nothing = buildSynth_ $ silent >> destination
displayEval :: MonadWidget t m => Dynamic t (Map Answer Score) -> Dynamic t (MultipleChoiceStore Config Answer) -> m ()
displayEval e _ = displayMultipleChoiceEvaluationGraph ("scoreBarWrapperThreeBars","svgBarContainerThreeBars","svgFaintedLineThreeBars","xLabelThreeBars") "Session Performance" "" answers e
generateQ :: Config -> [ExerciseDatum] -> IO ([Answer],Answer)
generateQ _ _ = randomMultipleChoiceQuestion answers
thisConfigWidget:: MonadWidget t m => Dynamic t (Map String AudioBuffer) -> Config -> m (Dynamic t Config, Dynamic t (Maybe (SourceNodeSpec, Maybe Time)), Event t (), Event t ())
thisConfigWidget _ c@(s,d,o) = do
text "Similarity: "
simDropDown <- dropdown (head similarities) (constDyn $ fromList [ (x,show x) | x <- similarities ]) (DropdownConfig never (constDyn empty))
text "Duration: "
durDropDown <- dropdown (head durations) (constDyn $ fromList [ (x,show x) | x <- durations]) (DropdownConfig never (constDyn empty))
text "Octaves: "
octDropDown <- dropdown (head octaves) (constDyn $ fromList [ (x,show x) | x <- octaves]) (DropdownConfig never (constDyn empty))
let sim = _dropdown_value simDropDown
let dur = _dropdown_value durDropDown
let oct = _dropdown_value octDropDown
simDur <- combineDyn (,) sim dur
simDurOct <- combineDyn (,) simDur oct
conf <- mapDyn (\((x,y),z) -> (x,y,z)) simDurOct
let source = constDyn $ Just (Silent, Nothing)
return (conf, source, never, never)
instructions :: MonadWidget t m => m ()
instructions = el "div" $ do
elClass "div" "instructionsText" $ text "Instructions placeholder"
frequencyEnvelopeExercise :: MonadWidget t m => Exercise t m Config [Answer] Answer (Map Answer Score) (MultipleChoiceStore Config Answer)
frequencyEnvelopeExercise = multipleChoiceExercise
2
answers
instructions
thisConfigWidget
renderAnswer
FrequencyEnvelope
(1,1000,8.0)
displayEval
generateQ
(const (0,2))
|
luisnavarrodelangel/InnerEar
|
src/InnerEar/Exercises/FrequencyEnvelope.hs
|
gpl-3.0
| 4,808 | 0 | 16 | 719 | 1,777 | 937 | 840 | 103 | 1 |
module Main(main) where
import Test.HUnit
import RLang.Parser
import RLang.L1DataTypes
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Text
import System.IO.Unsafe
import System.Exit
readTestCaseFile :: String -> BS.ByteString
readTestCaseFile filepath = BS.pack $ unsafePerformIO $ readFile filepath
----------------- Triv Tests ------------------
trivOpTest :: Triv -> String -> Test
trivOpTest expected filepath = TestCase $ assertEqual ""
(Just $ Prog $ TrivOp expected)
(parse $ readTestCaseFile filepath)
five = ConstantOp $ N 5
asConstant s = ConstantOp $ S $ pack s
notOpTest = trivOpTest (Not five) "tests/json/not-test.json"
resultOpTest = trivOpTest (ResultOf $ asConstant "some-tagger") "tests/json/resultOf-test.json"
valueOfOpTest = trivOpTest (ValueOf $ asConstant "some-variable") "tests/json/valueOf-test.json"
tableRefOpTest = trivOpTest (TableRef $ asConstant "some-table") "tests/json/tableRef-test.json"
eqOpTest = trivOpTest (Eq five five) "tests/json/eq-test.json"
orOpTest = trivOpTest (Or five five) "tests/json/or-test.json"
andOpTest = trivOpTest (And five five) "tests/json/and-test.json"
neqOpTest = trivOpTest (Neq five five) "tests/json/neq-test.json"
addOpTest = trivOpTest (Add five five) "tests/json/add-test.json"
mulOpTest = trivOpTest (Mul five five) "tests/json/mul-test.json"
divOpTest = trivOpTest (Div five five) "tests/json/div-test.json"
modOpTest = trivOpTest (Mod five five) "tests/json/mod-test.json"
grtOpTest = trivOpTest (Grt five five) "tests/json/grt-test.json"
lstOpTest = trivOpTest (Lst five five) "tests/json/lst-test.json"
geqOpTest = trivOpTest (Geq five five) "tests/json/geq-test.json"
leqOpTest = trivOpTest (Leq five five) "tests/json/leq-test.json"
smallTest = trivOpTest (Leq five five) "tests/json/small-test.json"
trivOpTests = TestList [notOpTest, resultOpTest, valueOfOpTest, tableRefOpTest, eqOpTest,
orOpTest, andOpTest, neqOpTest, addOpTest, mulOpTest, divOpTest, modOpTest, grtOpTest, lstOpTest, geqOpTest, leqOpTest, smallTest]
----------------- PrimOp Tests ------------------
primOpTest :: Prim -> String -> Test
primOpTest expected filepath = TestCase $ assertEqual ""
(Just $ Prog $ PrimOp expected)
(parse $ readTestCaseFile filepath)
epochSecondsOpTest = primOpTest NowEpochSeconds "tests/json/epochSeconds-test.json"
randomIntOpTest = primOpTest (RandomInt five) "tests/json/randomInt-test.json"
timestampDiffTest = primOpTest (EpochSecondsFromTimestamp five) "tests/json/epochSecondsFromTimestamp-test.json"
primOpTests = TestList [epochSecondsOpTest, randomIntOpTest, timestampDiffTest]
main :: IO ()
main = do
testResults <- runTestTT $ TestList [trivOpTests, primOpTests]
if 0 /= (failures testResults) || 0 /= (errors testResults) then exitFailure else return ()
|
czakian/Roxy
|
tests/TestParser.hs
|
gpl-3.0
| 2,934 | 0 | 12 | 473 | 734 | 386 | 348 | 47 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Instances.AddAccessConfig
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Adds an access config to an instance\'s network interface.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.addAccessConfig@.
module Network.Google.Resource.Compute.Instances.AddAccessConfig
(
-- * REST Resource
InstancesAddAccessConfigResource
-- * Creating a Request
, instancesAddAccessConfig
, InstancesAddAccessConfig
-- * Request Lenses
, iaacProject
, iaacNetworkInterface
, iaacZone
, iaacPayload
, iaacInstance
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instances.addAccessConfig@ method which the
-- 'InstancesAddAccessConfig' request conforms to.
type InstancesAddAccessConfigResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instances" :>
Capture "instance" Text :>
"addAccessConfig" :>
QueryParam "networkInterface" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AccessConfig :>
Post '[JSON] Operation
-- | Adds an access config to an instance\'s network interface.
--
-- /See:/ 'instancesAddAccessConfig' smart constructor.
data InstancesAddAccessConfig = InstancesAddAccessConfig'
{ _iaacProject :: !Text
, _iaacNetworkInterface :: !Text
, _iaacZone :: !Text
, _iaacPayload :: !AccessConfig
, _iaacInstance :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'InstancesAddAccessConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iaacProject'
--
-- * 'iaacNetworkInterface'
--
-- * 'iaacZone'
--
-- * 'iaacPayload'
--
-- * 'iaacInstance'
instancesAddAccessConfig
:: Text -- ^ 'iaacProject'
-> Text -- ^ 'iaacNetworkInterface'
-> Text -- ^ 'iaacZone'
-> AccessConfig -- ^ 'iaacPayload'
-> Text -- ^ 'iaacInstance'
-> InstancesAddAccessConfig
instancesAddAccessConfig pIaacProject_ pIaacNetworkInterface_ pIaacZone_ pIaacPayload_ pIaacInstance_ =
InstancesAddAccessConfig'
{ _iaacProject = pIaacProject_
, _iaacNetworkInterface = pIaacNetworkInterface_
, _iaacZone = pIaacZone_
, _iaacPayload = pIaacPayload_
, _iaacInstance = pIaacInstance_
}
-- | Project ID for this request.
iaacProject :: Lens' InstancesAddAccessConfig Text
iaacProject
= lens _iaacProject (\ s a -> s{_iaacProject = a})
-- | The name of the network interface to add to this instance.
iaacNetworkInterface :: Lens' InstancesAddAccessConfig Text
iaacNetworkInterface
= lens _iaacNetworkInterface
(\ s a -> s{_iaacNetworkInterface = a})
-- | The name of the zone for this request.
iaacZone :: Lens' InstancesAddAccessConfig Text
iaacZone = lens _iaacZone (\ s a -> s{_iaacZone = a})
-- | Multipart request metadata.
iaacPayload :: Lens' InstancesAddAccessConfig AccessConfig
iaacPayload
= lens _iaacPayload (\ s a -> s{_iaacPayload = a})
-- | The instance name for this request.
iaacInstance :: Lens' InstancesAddAccessConfig Text
iaacInstance
= lens _iaacInstance (\ s a -> s{_iaacInstance = a})
instance GoogleRequest InstancesAddAccessConfig where
type Rs InstancesAddAccessConfig = Operation
type Scopes InstancesAddAccessConfig =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient InstancesAddAccessConfig'{..}
= go _iaacProject _iaacZone _iaacInstance
(Just _iaacNetworkInterface)
(Just AltJSON)
_iaacPayload
computeService
where go
= buildClient
(Proxy :: Proxy InstancesAddAccessConfigResource)
mempty
|
rueshyna/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/Instances/AddAccessConfig.hs
|
mpl-2.0
| 4,878 | 0 | 19 | 1,191 | 628 | 370 | 258 | 99 | 1 |
module Obj where
import System.FilePath (takeFileName)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.List (intercalate, foldl')
import Data.Maybe (mapMaybe, fromMaybe, fromJust)
import Control.Monad.State
import Data.Char
import Types
import Util
import Debug.Trace
-- | Will the lookup look at other Carp code or at C code. This matters when calling functions, should they assume it's a lambda or a normal C function?
data GlobalMode = CarpLand
| ExternalCode
deriving (Eq, Show, Ord)
-- | Will the lookup look at a global variable
data DefinitionMode = AVariable
| AFunction
deriving (Eq, Show, Ord)
-- | For local lookups, does the variable live in the current function or is it captured from outside it's body?
data CaptureMode = NoCapture
| Capture
deriving (Eq, Show, Ord)
-- | A symbol knows a bit about what it refers to - is it a local scope or a global one? (the latter include modules).
-- | A symbol that is not used for looking up things will use the 'Symbol' case.
data SymbolMode = Symbol
| LookupLocal CaptureMode
| LookupRecursive
| LookupGlobal GlobalMode DefinitionMode
| LookupGlobalOverride String -- Used to emit another name than the one used in the Carp program.
deriving (Eq, Show, Ord)
isLookupGlobal :: SymbolMode -> Bool
isLookupGlobal (LookupGlobal _ _) = True
isLookupGlobal _ = False
isLookupLocal :: SymbolMode -> Bool
isLookupLocal (LookupLocal _) = True
isLookupLocal _ = False
-- | The canonical Lisp object.
data Obj = Sym SymPath SymbolMode
| MultiSym String [SymPath] -- refering to multiple functions with the same name
| InterfaceSym String -- refering to an interface. TODO: rename to InterfaceLookupSym?
| Num Ty Double
| Str String
| Pattern String
| Chr Char
| Bol Bool
| Lst [XObj]
| Arr [XObj]
| Dict (Map.Map XObj XObj)
| Defn
| Def
| Fn (Maybe SymPath) (Set.Set XObj) -- the name of the lifted function, and the set of variables this lambda captures
| Do
| Let
| While
| Break
| If
| Mod Env
| Typ Ty
| With
| External (Maybe String)
| ExternalType
| Deftemplate TemplateCreator
| Instantiate Template
| Defalias Ty
| Address
| SetBang
| Macro
| Dynamic
| Command CommandFunctionType
| The
| Ref
| Deref
| Interface Ty [SymPath]
deriving (Show, Eq)
-- | This instance is needed for the dynamic Dictionary
instance Ord Obj where
compare (Str a) (Str b) = compare a b
compare (Num _ a) (Num _ b) = compare a b
compare a b = compare (show a) (show b)
-- TODO: handle comparison of lists, arrays and dictionaries
newtype CommandFunctionType = CommandFunction { getCommand :: ([XObj] -> StateT Context IO (Either EvalError XObj)) }
instance Eq CommandFunctionType where
a == b = True
instance Show CommandFunctionType where
show t = "CommandFunction { ... }"
newtype TemplateCreator = TemplateCreator { getTemplateCreator :: TypeEnv -> Env -> Template }
instance Show TemplateCreator where
show _ = "TemplateCreator"
-- | Note: This is to make comparisons of Environments possible, otherwise
-- | they are always different when they contain TemplateCreators.
instance Eq TemplateCreator where
_ == _ = True
-- | Information about where the Obj originated from.
data Info = Info { infoLine :: Int
, infoColumn :: Int
, infoFile :: String
, infoDelete :: Set.Set Deleter
, infoIdentifier :: Int
} deriving (Show, Eq, Ord)
dummyInfo :: Info
dummyInfo = Info 0 0 "dummy-file" Set.empty (-1)
data Deleter = ProperDeleter { deleterPath :: SymPath
, deleterVariable :: String
}
| FakeDeleter { deleterVariable :: String -- used for external types with no delete function
}
deriving (Eq, Ord)
instance Show Deleter where
show (ProperDeleter path var) = "(ProperDel " ++ show path ++ " " ++ show var ++ ")"
show (FakeDeleter var) = "(FakeDel " ++ show var ++ ")"
prettyInfo :: Info -> String
prettyInfo i =
let line = infoLine i
column = infoColumn i
file = infoFile i
in (if line > -1 then "line " ++ show line else "unkown line") ++ ", " ++
(if column > -1 then "column " ++ show column else "unknown column") ++
" in '" ++ file ++ "'"
prettyInfoFromXObj :: XObj -> String
prettyInfoFromXObj xobj = case info xobj of
Just i -> prettyInfo i
Nothing -> "no info"
data FilePathPrintLength = FullPath
| ShortPath
instance Show FilePathPrintLength where
show FullPath = "full"
show ShortPath = "short"
machineReadableInfo :: FilePathPrintLength -> Info -> String
machineReadableInfo filePathPrintLength i =
let line = infoLine i
column = infoColumn i
file = infoFile i
file' = case filePathPrintLength of
FullPath -> file
ShortPath -> takeFileName file
in file' ++ ":" ++ show line ++ ":" ++ show column
machineReadableInfoFromXObj :: FilePathPrintLength -> XObj -> String
machineReadableInfoFromXObj fppl xobj =
case info xobj of
Just i -> machineReadableInfo fppl i
Nothing -> ""
-- TODO: change name of this function
freshVar :: Info -> String
freshVar i = "_" ++ show (infoIdentifier i)
-- | Obj with eXtra information.
data XObj = XObj { obj :: Obj
, info :: Maybe Info
, ty :: Maybe Ty
} deriving (Show, Eq, Ord)
getBinderDescription :: XObj -> String
getBinderDescription (XObj (Lst (XObj Defn _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "defn"
getBinderDescription (XObj (Lst (XObj Def _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "def"
getBinderDescription (XObj (Lst (XObj Macro _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "macro"
getBinderDescription (XObj (Lst (XObj Dynamic _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "dynamic"
getBinderDescription (XObj (Lst (XObj (Command _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "command"
getBinderDescription (XObj (Lst (XObj (Deftemplate _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "template"
getBinderDescription (XObj (Lst (XObj (Instantiate _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "instantiate"
getBinderDescription (XObj (Lst (XObj (Defalias _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "alias"
getBinderDescription (XObj (Lst (XObj (External _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "external"
getBinderDescription (XObj (Lst (XObj ExternalType _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "external-type"
getBinderDescription (XObj (Lst (XObj (Typ _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "deftype"
getBinderDescription (XObj (Lst (XObj (Interface _ _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "interface"
getBinderDescription (XObj (Mod _) _ _) = "module"
getBinderDescription b = error ("Unhandled binder: " ++ show b)
getName :: XObj -> String
getName xobj = show (getPath xobj)
getSimpleName :: XObj -> String
getSimpleName xobj = let SymPath _ name = (getPath xobj) in name
getSimpleNameWithArgs :: XObj -> Maybe String
getSimpleNameWithArgs xobj@(XObj (Lst (XObj Defn _ _ : _ : (XObj (Arr args) _ _) : _)) _ _) =
Just $
"(" ++ getSimpleName xobj ++ (if length args > 0 then " " else "") ++
unwords (map getSimpleName args) ++ ")"
getSimpleNameWithArgs xobj@(XObj (Lst (XObj Macro _ _ : _ : (XObj (Arr args) _ _) : _)) _ _) =
Just $
"(" ++ getSimpleName xobj ++ (if length args > 0 then " " else "") ++
unwords (map getSimpleName args) ++ ")"
getSimpleNameWithArgs xobj@(XObj (Lst (XObj Dynamic _ _ : _ : (XObj (Arr args) _ _) : _)) _ _) =
Just $
"(" ++ getSimpleName xobj ++ (if length args > 0 then " " else "") ++
unwords (map getSimpleName args) ++ ")"
getSimpleNameWithArgs xobj = Nothing
-- | Extracts the second form (where the name of definitions are stored) from a list of XObj:s.
getPath :: XObj -> SymPath
getPath (XObj (Lst (XObj Defn _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj Def _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj Macro _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj Dynamic _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Deftemplate _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Instantiate _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Defalias _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (External _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj ExternalType _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Typ _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Mod _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Interface _ _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Command _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Sym path _) _ _) = path
getPath x = SymPath [] (pretty x)
-- | Changes the second form (where the name of definitions are stored) in a list of XObj:s.
setPath :: XObj -> SymPath -> XObj
setPath (XObj (Lst (defn@(XObj Defn _ _) : XObj (Sym _ _) si st : rest)) i t) newPath =
XObj (Lst (defn : XObj (Sym newPath Symbol) si st : rest)) i t
setPath (XObj (Lst [extr@(XObj (External _) _ _), XObj (Sym _ _) si st]) i t) newPath =
XObj (Lst [extr, XObj (Sym newPath Symbol) si st]) i t
setPath x _ =
error ("Can't set path on " ++ show x)
-- | Convert an XObj to a pretty string representation.
pretty :: XObj -> String
pretty = visit 0
where visit :: Int -> XObj -> String
visit indent xobj =
case obj xobj of
Lst lst -> "(" ++ joinWithSpace (map (visit indent) lst) ++ ")"
Arr arr -> "[" ++ joinWithSpace (map (visit indent) arr) ++ "]"
Dict dict -> "{" ++ joinWithSpace (map (visit indent) (concatMap (\(a, b) -> [a, b]) (Map.toList dict))) ++ "}"
Num IntTy num -> show (round num :: Int)
Num LongTy num -> show num ++ "l"
Num FloatTy num -> show num ++ "f"
Num DoubleTy num -> show num
Num _ _ -> error "Invalid number type."
Str str -> show str
Pattern str -> '#' : show str
Chr c -> '\\' : c : ""
Sym path mode -> show path -- ++ " <" ++ show mode ++ ">"
MultiSym originalName paths -> originalName ++ "{" ++ joinWithComma (map show paths) ++ "}"
InterfaceSym name -> name
Bol b -> if b then "true" else "false"
Defn -> "defn"
Def -> "def"
Fn _ captures -> "fn" ++ " <" ++ joinWithComma (map getName (Set.toList captures)) ++ ">"
If -> "if"
While -> "while"
Do -> "do"
Let -> "let"
Mod env -> fromMaybe "module" (envModuleName env)
Typ _ -> "deftype"
Deftemplate _ -> "deftemplate"
Instantiate _ -> "instantiate"
External Nothing -> "external"
External (Just override) -> "external (override: " ++ show override ++ ")"
ExternalType -> "external-type"
Defalias _ -> "defalias"
Address -> "address"
SetBang -> "set!"
Macro -> "macro"
Dynamic -> "dynamic"
Command _ -> "command"
The -> "the"
Ref -> "ref"
Deref -> "deref"
Break -> "break"
Interface _ _ -> "interface"
With -> "with"
newtype EvalError = EvalError String deriving (Eq)
instance Show EvalError where
show (EvalError msg) = msg
-- | Get the type of an XObj as a string.
typeStr :: XObj -> String
typeStr xobj = case ty xobj of
Nothing -> " : _"
Just t -> " : " ++ show t
-- | Get the identifier of an XObj as a string.
identifierStr :: XObj -> String
identifierStr xobj = case info xobj of
Just i -> "#" ++ show (infoIdentifier i)
Nothing -> "#?"
-- | Get the deleters of an XObj as a string.
deletersStr :: XObj -> String
deletersStr xobj = case info xobj of
Just i -> joinWithComma (map show (Set.toList (infoDelete i)))
Nothing -> ""
-- | Convert XObj to pretty string representation with type annotations.
prettyTyped :: XObj -> String
prettyTyped = visit 0
where visit :: Int -> XObj -> String
visit indent xobj =
let suffix = typeStr xobj ++ " " ++
identifierStr xobj ++ " " ++
deletersStr xobj ++ " " ++
"\n"
in case obj xobj of
Lst lst -> "(" ++ joinWithSpace (map (visit indent) lst) ++ ")" ++ suffix
Arr arr -> "[" ++ joinWithSpace (map (visit indent) arr) ++ "]" ++ suffix
_ -> pretty xobj ++ suffix
-- | Datatype for holding meta data about a binder, like type annotation or docstring.
newtype MetaData = MetaData { getMeta :: Map.Map String XObj } deriving (Eq, Show)
emptyMeta :: MetaData
emptyMeta = (MetaData Map.empty)
metaIsTrue :: MetaData -> String -> Bool
metaIsTrue metaData key =
case Map.lookup key (getMeta metaData) of
Just (XObj (Bol True) _ _) -> True
_ -> False
-- | Wraps and holds an XObj in an environment.
data Binder = Binder { binderMeta :: MetaData, binderXObj :: XObj } deriving Eq
instance Show Binder where
show binder = showBinderIndented 0 (getName (binderXObj binder), binder)
showBinderIndented :: Int -> (String, Binder) -> String
showBinderIndented indent (name, Binder _ (XObj (Mod env) _ _)) =
replicate indent ' ' ++ name ++ " : Module = {\n" ++
prettyEnvironmentIndented (indent + 4) env ++
"\n" ++ replicate indent ' ' ++ "}"
showBinderIndented indent (name, Binder _ (XObj (Lst [XObj (Interface t paths) _ _, _]) _ _)) =
replicate indent ' ' ++ name ++ " : " ++ show t ++ " = {\n " ++
joinWith "\n " (map show paths) ++
"\n" ++ replicate indent ' ' ++ "}"
showBinderIndented indent (name, Binder meta xobj) =
if metaIsTrue meta "hidden"
then ""
else replicate indent ' ' ++ name ++
-- " (" ++ show (getPath xobj) ++ ")" ++
" : " ++ showMaybeTy (ty xobj)
-- ++ " <" ++ getBinderDescription xobj ++ ">"
-- | Get a list of pairs from a deftype declaration.
memberXObjsToPairs :: [XObj] -> [(String, Ty)]
memberXObjsToPairs xobjs = map (\(n, t) -> (mangle (getName n), fromJust (xobjToTy t))) (pairwise xobjs)
replaceGenericTypeSymbolsOnMembers :: Map.Map String Ty -> [XObj] -> [XObj]
replaceGenericTypeSymbolsOnMembers mappings memberXObjs =
concatMap (\(v, t) -> [v, replaceGenericTypeSymbols mappings t]) (pairwise memberXObjs)
replaceGenericTypeSymbols :: Map.Map String Ty -> XObj -> XObj
replaceGenericTypeSymbols mappings xobj@(XObj (Sym (SymPath pathStrings name) _) i t) =
let Just perhapsTyVar = xobjToTy xobj
in if isFullyGenericType perhapsTyVar
then case Map.lookup name mappings of
Just found -> tyToXObj found
Nothing -> xobj -- error ("Failed to concretize member '" ++ name ++ "' at " ++ prettyInfoFromXObj xobj ++ ", mappings: " ++ show mappings)
else xobj
replaceGenericTypeSymbols mappings (XObj (Lst lst) i t) =
(XObj (Lst (map (replaceGenericTypeSymbols mappings) lst)) i t)
replaceGenericTypeSymbols mappings (XObj (Arr arr) i t) =
(XObj (Arr (map (replaceGenericTypeSymbols mappings) arr)) i t)
replaceGenericTypeSymbols _ xobj = xobj
-- | Convert a Ty to the s-expression that represents that type.
-- | TODO: Add more cases and write tests for this.
tyToXObj :: Ty -> XObj
tyToXObj (StructTy n []) = XObj (Sym (SymPath [] n) Symbol) Nothing Nothing
tyToXObj (StructTy n vs) = XObj (Lst ((XObj (Sym (SymPath [] n) Symbol) Nothing Nothing) : (map tyToXObj vs))) Nothing Nothing
tyToXObj (RefTy t) = XObj (Lst [(XObj (Sym (SymPath [] "Ref") Symbol) Nothing Nothing), tyToXObj t]) Nothing Nothing
tyToXObj (PointerTy t) = XObj (Lst [(XObj (Sym (SymPath [] "Ptr") Symbol) Nothing Nothing), tyToXObj t]) Nothing Nothing
tyToXObj (FuncTy argTys returnTy) = XObj (Lst [(XObj (Sym (SymPath [] "Fn") Symbol) Nothing Nothing), XObj (Arr (map tyToXObj argTys)) Nothing Nothing, tyToXObj returnTy]) Nothing Nothing
tyToXObj x = XObj (Sym (SymPath [] (show x)) Symbol) Nothing Nothing
-- | Helper function to create binding pairs for registering external functions.
register :: String -> Ty -> (String, Binder)
register name t = (name, Binder emptyMeta
(XObj (Lst [XObj (External Nothing) Nothing Nothing,
XObj (Sym (SymPath [] name) Symbol) Nothing Nothing])
(Just dummyInfo) (Just t)))
data EnvMode = ExternalEnv | InternalEnv | RecursionEnv deriving (Show, Eq)
-- | Environment
data Env = Env { envBindings :: Map.Map String Binder
, envParent :: Maybe Env
, envModuleName :: Maybe String
, envUseModules :: [SymPath]
, envMode :: EnvMode
, envFunctionNestingLevel :: Int -- Normal defn:s have 0, lambdas get +1 for each level of nesting
} deriving (Show, Eq)
newtype TypeEnv = TypeEnv { getTypeEnv :: Env }
instance Show TypeEnv where
show (TypeEnv env) = "(TypeEnv " ++ show env ++ ")"
safeEnvModuleName :: Env -> String
safeEnvModuleName env =
case envModuleName env of
Just name -> name ++ ", with parent " ++ parent
Nothing -> "???, with parent " ++ parent
where parent =
case envParent env of
Just p -> safeEnvModuleName p
Nothing -> "Global"
-- | Used by the compiler command "(env)"
prettyEnvironment :: Env -> String
prettyEnvironment = prettyEnvironmentIndented 0
prettyEnvironmentIndented :: Int -> Env -> String
prettyEnvironmentIndented indent env =
joinWith "\n" $ filter (/= "") (map (showBinderIndented indent) (Map.toList (envBindings env))) ++
let modules = envUseModules env
in if null modules
then []
else ("\n" ++ replicate indent ' ' ++ "Used modules:") : map (showImportIndented indent) modules
-- | For debugging nested environments
prettyEnvironmentChain :: Env -> String
prettyEnvironmentChain env =
let bs = envBindings env
name = case envModuleName env of
Just n -> n
Nothing -> "<env has no name>"
otherInfo = "(" ++ show (envMode env) ++ ", lvl " ++ show (envFunctionNestingLevel env) ++ ")"
in (if length bs < 20
then "'" ++ name ++ "' " ++ otherInfo ++ ":\n" ++ (joinWith "\n" $ filter (/= "")
(map (showBinderIndented 4) (Map.toList (envBindings env))))
else "'" ++ name ++ "' " ++ otherInfo ++ ":\n Too big to show bindings.")
++
(case envParent env of
Just parent -> "\nWITH PARENT ENV " ++ prettyEnvironmentChain parent
Nothing -> "")
pathToEnv :: Env -> [String]
pathToEnv rootEnv = visit rootEnv
where
visit env =
case envModuleName env of
Just name -> name : parent
Nothing -> parent
where parent =
case envParent env of
Just p -> visit p
Nothing -> []
showImportIndented :: Int -> SymPath -> String
showImportIndented indent path = replicate indent ' ' ++ " * " ++ show path
-- | Project (represents a lot of useful information for working at the REPL and building executables)
data Project = Project { projectTitle :: String
, projectIncludes :: [Includer]
, projectCFlags :: [FilePath]
, projectLibFlags :: [FilePath]
, projectFiles :: [FilePath]
, projectAlreadyLoaded :: [FilePath]
, projectEchoC :: Bool
, projectLibDir :: FilePath
, projectCarpDir :: FilePath
, projectOutDir :: FilePath
, projectDocsDir :: FilePath
, projectDocsLogo :: FilePath
, projectDocsPrelude :: String
, projectDocsURL :: String
, projectDocsStyling :: String
, projectPrompt :: String
, projectCarpSearchPaths :: [FilePath]
, projectPrintTypedAST :: Bool
, projectCompiler :: String
, projectCore :: Bool
, projectEchoCompilationCommand :: Bool
, projectCanExecute :: Bool
, projectFilePathPrintLength :: FilePathPrintLength
}
projectFlags :: Project -> String
projectFlags proj = joinWithSpace (projectCFlags proj ++ projectLibFlags proj)
instance Show Project where
show (Project
title
incl
cFlags
libFlags
srcFiles
alreadyLoaded
echoC
libDir
carpDir
outDir
docsDir
docsLogo
docsPrelude
docsURL
docsStyling
prompt
searchPaths
printTypedAST
compiler
core
echoCompilationCommand
canExecute
filePathPrintLength
) =
unlines [ "Title: " ++ title
, "Compiler: " ++ compiler
, "Includes:\n " ++ joinWith "\n " (map show incl)
, "Cflags:\n " ++ joinWith "\n " cFlags
, "Library flags:\n " ++ joinWith "\n " libFlags
, "Carp source files:\n " ++ joinWith "\n " srcFiles
, "Already loaded:\n " ++ joinWith "\n " alreadyLoaded
, "Echo C: " ++ if echoC then "true" else "false"
, "Echo compilation command: " ++ if echoCompilationCommand then "true" else "false"
, "Can execute: " ++ if canExecute then "true" else "false"
, "Output directory: " ++ outDir
, "Docs directory: " ++ docsDir
, "Docs logo: " ++ docsLogo
, "Docs prelude: " ++ docsPrelude
, "Docs Project URL: " ++ docsURL
, "Docs CSS URL: " ++ docsStyling
, "Library directory: " ++ libDir
, "CARP_DIR: " ++ carpDir
, "Prompt: " ++ prompt
, "Using Core: " ++ show core
, "Search paths for 'load' command:\n " ++ joinWith "\n " searchPaths
, "Print AST (with 'info' command): " ++ if printTypedAST then "true" else "false"
, "File path print length (when using --check): " ++ show filePathPrintLength
]
-- | Represent the inclusion of a C header file, either like <string.h> or "string.h"
data Includer = SystemInclude String
| LocalInclude String
deriving Eq
instance Show Includer where
show (SystemInclude file) = "<" ++ file ++ ">"
show (LocalInclude file) = "\"" ++ file ++ "\""
-- | Converts an S-expression to one of the Carp types.
xobjToTy :: XObj -> Maybe Ty
xobjToTy (XObj (Sym (SymPath _ "Int") _) _ _) = Just IntTy
xobjToTy (XObj (Sym (SymPath _ "Float") _) _ _) = Just FloatTy
xobjToTy (XObj (Sym (SymPath _ "Double") _) _ _) = Just DoubleTy
xobjToTy (XObj (Sym (SymPath _ "Long") _) _ _) = Just LongTy
xobjToTy (XObj (Sym (SymPath _ "String") _) _ _) = Just StringTy
xobjToTy (XObj (Sym (SymPath _ "Pattern") _) _ _) = Just PatternTy
xobjToTy (XObj (Sym (SymPath _ "Char") _) _ _) = Just CharTy
xobjToTy (XObj (Sym (SymPath _ "Bool") _) _ _) = Just BoolTy
xobjToTy (XObj (Sym (SymPath _ s@(firstLetter:_)) _) _ _) | isLower firstLetter = Just (VarTy s)
| otherwise = Just (StructTy s [])
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Ptr") _) _ _, innerTy]) _ _) =
do okInnerTy <- xobjToTy innerTy
return (PointerTy okInnerTy)
xobjToTy (XObj (Lst (XObj (Sym (SymPath _ "Ptr") _) _ _ : _)) _ _) =
Nothing
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Ref") _) _ _, innerTy]) _ _) =
do okInnerTy <- xobjToTy innerTy
return (RefTy okInnerTy)
xobjToTy (XObj (Lst [XObj Ref i t, innerTy]) _ _) = -- This enables parsing of '&'
do okInnerTy <- xobjToTy innerTy
return (RefTy okInnerTy)
xobjToTy (XObj (Lst (XObj (Sym (SymPath _ "Ref") _) _ _ : _)) _ _) =
Nothing
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "╬╗") _) fi ft, XObj (Arr argTys) ai at, retTy]) i t) =
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "Fn") Symbol) fi ft, XObj (Arr argTys) ai at, retTy]) i t)
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "λ") _) fi ft, XObj (Arr argTys) ai at, retTy]) i t) =
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "Fn") Symbol) fi ft, XObj (Arr argTys) ai at, retTy]) i t)
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Fn") _) _ _, XObj (Arr argTys) _ _, retTy]) _ _) =
do okArgTys <- mapM xobjToTy argTys
okRetTy <- xobjToTy retTy
return (FuncTy okArgTys okRetTy)
xobjToTy (XObj (Lst []) _ _) = Just UnitTy
xobjToTy (XObj (Lst (x:xs)) _ _) =
do okX <- xobjToTy x
okXS <- mapM xobjToTy xs
case okX of
(StructTy n []) -> return (StructTy n okXS)
(VarTy n) -> return (StructTy n okXS) -- Struct type with type variable as a name, i.e. "(a b)"
_ -> Nothing
xobjToTy _ = Nothing
-- | Generates the suffix added to polymorphic functions when they are instantiated.
-- For example (defn id [x] x) : t -> t
-- might be invoked like this (id 5)
-- which will generate int id__Int(int x) { return x; }
-- The "__Int" is the suffix!
polymorphicSuffix :: Ty -> Ty -> String
polymorphicSuffix signature actualType =
case evalState (visit signature actualType) [] of
[] -> ""
parts -> "__" ++ intercalate "_" parts
where visit :: Ty -> Ty -> State VisitedTypes [String]
visit sig actual =
case (sig, actual) of
(VarTy _, VarTy _) -> -- error $ "Unsolved variable in actual type: " ++ show sig ++ " => " ++ show actual ++
-- " when calculating polymorphic suffix for " ++
-- show signature ++ " => " ++ show actualType
return ["?"]
(a@(VarTy _), b) -> do visitedTypeVariables <- get
if a `elem` visitedTypeVariables
then return []
else do put (a : visitedTypeVariables) -- now it's visited
return [tyToC b]
(FuncTy argTysA retTyA, FuncTy argTysB retTyB) -> do visitedArgs <- fmap concat (zipWithM visit argTysA argTysB)
visitedRets <- visit retTyA retTyB
return (visitedArgs ++ visitedRets)
(StructTy _ a, StructTy _ b) -> fmap concat (zipWithM visit a b)
(PointerTy a, PointerTy b) -> visit a b
(RefTy a, RefTy b) -> visit a b
(_, _) -> return []
type VisitedTypes = [Ty]
-- | Templates are like macros, but defined inside the compiler and with access to the types they are instantiated with
data Template = Template { templateSignature :: Ty
, templateDeclaration :: Ty -> [Token] -- Will this parameterization ever be useful?
, templateDefinition :: Ty -> [Token]
, templateDependencies :: Ty -> [XObj]
}
instance Show Template where
show _ = "Template"
-- | Note: This is to make comparisons of Environments possible, otherwise
-- | they are always different when they contain Templates.
instance Eq Template where
a == b = templateSignature a == templateSignature b
data TokTyMode = Normal | Raw deriving (Eq, Ord)
-- | Tokens are used for emitting C code from templates.
data Token = TokTy Ty TokTyMode -- | Some kind of type, will be looked up if it's a type variable.
| TokC String -- | Plain C code.
| TokDecl -- | Will emit the declaration (i.e. "foo(int x)"), this is useful
-- for avoiding repetition in the definition part of the template.
| TokName -- | Will emit the name of the instantiated function/variable.
deriving (Eq, Ord)
instance Show Token where
show (TokC s) = s
show (TokTy t Normal) = tyToCLambdaFix t -- Any function type will be emitted as 'Lambda'
show (TokTy t Raw) = tyToC t -- Function types will be emitted in typedef:able form
show TokName = "<name>"
show TokDecl = "<declaration>"
instantiateTemplate :: SymPath -> Ty -> Template -> (XObj, [XObj])
instantiateTemplate path actualType template =
let defLst = [XObj (Instantiate template) Nothing Nothing, XObj (Sym path Symbol) Nothing Nothing]
deps = templateDependencies template actualType
in (XObj (Lst defLst) (Just (Info (-1) (-1) (show path ++ " template") Set.empty (-1))) (Just actualType), deps)
-- | Type aliases are used to create C-typedefs when those are needed.
defineTypeAlias :: String -> Ty -> XObj
defineTypeAlias name t = XObj (Lst [XObj (Defalias t) Nothing Nothing
,XObj (Sym (SymPath [] name) Symbol) Nothing Nothing
]) (Just dummyInfo) (Just TypeTy)
defineFunctionTypeAlias :: Ty -> XObj
defineFunctionTypeAlias aliasTy = defineTypeAlias (tyToC aliasTy) aliasTy
defineArrayTypeAlias :: Ty -> XObj
defineArrayTypeAlias t = defineTypeAlias (tyToC t) (StructTy "Array" [])
-- |
defineInterface :: String -> Ty -> [SymPath] -> Maybe Info -> XObj
defineInterface name t paths info =
XObj (Lst [XObj (Interface t paths) Nothing Nothing
,XObj (Sym (SymPath [] name) Symbol) Nothing Nothing
])
info (Just InterfaceTy)
-- | Unsafe way of getting the type from an XObj
forceTy :: XObj -> Ty
forceTy xobj = fromMaybe (error ("No type in " ++ show xobj)) (ty xobj)
-- | How should the compiler be run? Interactively or just build / build & run and then quit?
data ExecutionMode = Repl | Build | BuildAndRun | Install String | Check deriving (Show, Eq)
-- | Information needed by the REPL
data Context = Context { contextGlobalEnv :: Env
, contextTypeEnv :: TypeEnv
, contextPath :: [String]
, contextProj :: Project
, contextLastInput :: String
, contextExecMode :: ExecutionMode
} deriving Show
popModulePath :: Context -> Context
popModulePath ctx = ctx { contextPath = init (contextPath ctx) }
-- | Unwrapping of XObj:s
-- | String
unwrapStringXObj :: XObj -> Either String String
unwrapStringXObj (XObj (Str s) _ _) = Right s
unwrapStringXObj x = Left ("The value '" ++ pretty x ++ "' at " ++ prettyInfoFromXObj x ++ " is not a String.")
-- | Bool
unwrapBoolXObj :: XObj -> Either String Bool
unwrapBoolXObj (XObj (Bol b) _ _) = Right b
unwrapBoolXObj x = Left ("The value '" ++ pretty x ++ "' at " ++ prettyInfoFromXObj x ++ " is not a Bool.")
-- | Symbol
unwrapSymPathXObj :: XObj -> Either String SymPath
unwrapSymPathXObj (XObj (Sym p _) _ _) = Right p
unwrapSymPathXObj x = Left ("The value '" ++ pretty x ++ "' at " ++ prettyInfoFromXObj x ++ " is not a Symbol.")
-- | Given a form, what definition mode will it generate?
definitionMode :: XObj -> DefinitionMode
definitionMode (XObj (Lst (XObj Def _ _ : _)) _ _) = AVariable
definitionMode _ = AFunction
isGlobalVariableLookup :: SymbolMode -> Bool
isGlobalVariableLookup (LookupGlobal _ AVariable) = True
isGlobalVariableLookup _ = False
|
eriksvedang/Carp
|
src/Obj.hs
|
mpl-2.0
| 32,278 | 0 | 19 | 9,634 | 10,130 | 5,186 | 4,944 | 584 | 42 |
import Data.List
data Tree a = Empty | Nd a (Tree a) (Tree a) deriving (Show)
fromList :: Ord a => [a] -> Tree a
fromList [] = Empty
fromList (x:xs) = Nd x lhs rhs
where
lhs = fromList $ filter (< x) xs
rhs = fromList $ filter (> x) xs
f :: IO String
f = do
print "daewon"
return "daewon"
with :: String -> IO String
with s = do
print s
return s
ask :: String -> IO String
-- ask is = is >>= return ""
ask is = return ""
main :: IO ()
main = f >>= ask >>= print
|
daewon/til
|
haskell/haskell_the_hard/aa/test.hs
|
mpl-2.0
| 486 | 0 | 9 | 132 | 238 | 120 | 118 | 19 | 1 |
module CostasLikeArrays.A320575Spec (main, spec) where
import Test.Hspec
import CostasLikeArrays.A320575 (a320575)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A320575" $
it "correctly computes the first 6 elements" $
map a320575 [1..6] `shouldBe` expectedValue where
expectedValue = [1,2,6,2,2,28]
|
peterokagey/haskellOEIS
|
test/CostasLikeArrays/A320575Spec.hs
|
apache-2.0
| 330 | 0 | 8 | 57 | 112 | 64 | 48 | 10 | 1 |
import QDSL01
import Language.Haskell.TH.Lib
import Language.Haskell.TH
main = do
let pow1 = $$(power 4)
print $ pow1 3
print $ (3*3*3*3 :: Float)
expr <- runQ $ power 4
putStrLn.pprint.unType $ expr
return ()
|
egaburov/funstuff
|
Haskell/thsk/qdsl01.hs
|
apache-2.0
| 227 | 0 | 12 | 51 | 106 | 52 | 54 | -1 | -1 |
module JDBC.Types.Blob
( freeBlob,
getBinaryStreamBlob,
getBinaryStreamBlob2,
getBytesBlob,
lengthBlob,
positionBlob,
positionBlob2,
setBinaryStreamBlob,
setBytesBlob,
setBytesBlob2,
truncateBlob)
where
import Java
import Interop.Java.IO
import JDBC.Types
foreign import java unsafe "@interface free" freeBlob :: Java Blob () --Todo
foreign import java unsafe "@interface getBinaryStream" getBinaryStreamBlob :: Java Blob InputStream
foreign import java unsafe "@interface getBinaryStream" getBinaryStreamBlob2 :: Int64 -> Int64
-> Java Blob InputStream
foreign import java unsafe "@interface getBytes" getBytesBlob_ :: Int64 -> Int -> Java Blob JByteArray
--Wrapper
getBytesBlob :: Int64 -> Int -> Java Blob [Byte]
getBytesBlob t1 t2 = fmap fromJava (getBytesBlob_ t1 t2)
--End Wrapper
foreign import java unsafe "@interface length" lengthBlob :: Java Blob Int64
foreign import java unsafe "@interface position" positionBlob :: Blob -> Int64 -> Java Blob Int64
foreign import java unsafe "@interface position" positionBlob2_ :: JByteArray -> Int64 -> Java Blob Int64
--Wrapper
positionBlob2 :: [Byte] -> Int64 -> Java Blob Int64
positionBlob2 t1 t2 = positionBlob2_ (toJava t1) t2
--End Wrapper
foreign import java unsafe "@interface setBinaryStream" setBinaryStreamBlob :: Int64 -> Java Blob OutputStream
foreign import java unsafe "@interface setBytes" setBytesBlob_ :: Int64 -> JByteArray -> Java Blob Int
--Wrapper
setBytesBlob :: Int64 -> [Byte] -> Java Blob Int
setBytesBlob t1 t2 = setBytesBlob_ t1 (toJava t2)
--End Wrapper
foreign import java unsafe "@interface setBytes" setBytesBlob2_ ::
Int64 -> JByteArray -> Int -> Int -> Java Blob Int
--Wrapper
setBytesBlob2 :: Int64 -> [Byte] -> Int -> Int -> Java Blob Int
setBytesBlob2 t1 t2 = setBytesBlob2_ t1 (toJava t2)
--End Wrapper
foreign import java unsafe "@interface tuncate" truncateBlob :: Int64 -> Java Blob ()
|
Jyothsnasrinivas/eta-jdbc
|
src/JDBC/Types/Blob.hs
|
apache-2.0
| 2,011 | 47 | 8 | 394 | 527 | 279 | 248 | -1 | -1 |
-- |Set labels for control flow analysis.
module CFA.Labels (Label (..)
, buildLabels, buildLabels', isBuiltinLabel,
labelSource, labelPos, labelName,primeLabel, labelSources
, unsafeLabelIx,deconstructLabel,propLabel) where
import Data.Generics
import Text.ParserCombinators.Parsec.Pos (SourcePos,sourceLine,sourceColumn,
initialPos,sourceName)
import Control.Monad.Trans
import Data.Maybe (fromJust,isJust)
import Data.List (intersperse,groupBy,concatMap)
import Framework
-- | Labels identify sources and are built compositionally.
data Label
= PrimedLabel Label Int -- ^a label indexed by a unique number
| SourceLabel (Maybe SourcePos) (Maybe String) Int -- ^a label representing a source location
| IdLabel Label String -- ^usually used for properties
| IxLabel Int
deriving (Typeable,Data,Eq,Ord)
labelPos :: Label -> Maybe SourcePos
labelPos (SourceLabel (Just p) _ _) = Just p
labelPos _ = Nothing
labelSource :: Label -> Maybe String
labelSource lbl = case labelPos lbl of
Just p -> Just (sourceName p)
Nothing -> Nothing
unsafeLabelIx (IxLabel ix) = Just ix
unsafeLabelIx (PrimedLabel _ ix) = Just ix
unsafeLabelIx (SourceLabel _ _ ix) = Just ix
unsafeLabelIx _ = Nothing
labelName :: Label -> Maybe String
labelName (SourceLabel _ (Just id) _) = Just id
labelName _ = Nothing
labelSources :: Label -> [SourcePos]
labelSources lbl = everything (++) (mkQ [] (\pos -> [pos])) lbl
deconstructLabel :: Label -> [Label]
deconstructLabel lbl = everything (++) (mkQ [] id) lbl
-- ---------------------------------------------------------------------------------------------------------------------
-- Printing
showSrc :: SourcePos -> Bool -> String
showSrc pos showLoc = name ++ show (sourceLine pos) ++ ":" ++ show (sourceColumn pos) where
name = if showLoc then sourceName pos ++ ":" else ""
instance Show Label where
show (SourceLabel (Just pos) (Just id) _) = id ++ ":" ++ (showSrc pos False)
show (SourceLabel (Just pos) Nothing _) = showSrc pos True
show (SourceLabel Nothing (Just id) _) = id
show (IdLabel lbl id) = show lbl ++ ":" ++ id
show (SourceLabel _ _ _) = error "Label.show : illegal SourceLabel"
show (IxLabel ix) = "{" ++ show ix ++ "}"
show (PrimedLabel lbl n) = show lbl ++ "." ++ show n
-- ---------------------------------------------------------------------------------------------------------------------
-- Constructing labels
primeLabel :: Label -> Int -> Label
primeLabel lbl ix = PrimedLabel lbl ix
propLabel :: Label -> String -> Label
propLabel lbl id = IdLabel lbl id
-- ---------------------------------------------------------------------------------------------------------------------
-- Miscellaneous
isBuiltinLabel (SourceLabel Nothing (Just _) _) = True
isBuiltinLabel _ = False
buildLabels :: Monad m => CounterT m a -> m a
buildLabels = evalCounter
-- |Builds labels that are distinct from all labels ' <= init'
buildLabels' :: Monad m => Counter -> CounterT m a -> m (a,Counter)
buildLabels' init m = runCounter init m
|
brownplt/ovid
|
src/CFA/Labels.hs
|
bsd-2-clause
| 3,038 | 0 | 10 | 491 | 940 | 493 | 447 | 56 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Hoodle.Render.BBox
-- Copyright : (c) 2011, 2012 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
module Graphics.Hoodle.Render.BBox where
import Graphics.Rendering.Cairo
import Graphics.Hoodle.Render.Simple
import Graphics.Hoodle.Render.HitTest
import Graphics.Hoodle.Render.Type
import Data.Hoodle.Generic
import Data.Hoodle.Map
import Data.Hoodle.Simple
import Data.Hoodle.BBox
import Data.Hoodle.Predefined
import Data.Foldable
import Data.Monoid
import qualified Data.Map as M
import Data.ByteString hiding (map, minimum, maximum, concat, concatMap, filter )
import Prelude hiding (fst,snd,curry,uncurry,mapM_,concatMap)
-- |
clipBBox :: Maybe BBox -> Render ()
clipBBox (Just (BBox (x1,y1) (x2,y2))) = do {resetClip; rectangle x1 y1 (x2-x1) (y2-y1); clip}
clipBBox Nothing = resetClip
-- |
clearBBox :: Maybe BBox -> Render ()
clearBBox Nothing = return ()
clearBBox (Just (BBox (x1,y1) (x2,y2))) = do
save
setSourceRGBA 0 0 0 0
setOperator OperatorSource
rectangle x1 y1 (x2-x1) (y2-y1)
fill
restore
cairoOneStrokeSelected :: StrokeBBox -> Render ()
cairoOneStrokeSelected sbbox = do
let s = gToStroke sbbox
case s of
Img _ _ _ -> cairoOneStrokeBBoxOnly sbbox
_ -> do
case M.lookup (stroke_color s) predefined_pencolor of
Just (r,g,b,a) -> setSourceRGBA r g b a
Nothing -> setSourceRGBA 0 0 0 1
case s of
Stroke _ _ w d -> do
setLineWidth (w * 4.0)
setLineCap LineCapRound
setLineJoin LineJoinRound
drawOneStrokeCurve d
stroke
setSourceRGBA 1 1 1 1
setLineWidth w
drawOneStrokeCurve . stroke_data $ s
stroke
VWStroke _ _ d -> do
setFillRule FillRuleWinding
drawOneVWStrokeCurve $ map (\(x,y,z)->(x,y,4*z)) d
fill
setSourceRGBA 1 1 1 1
drawOneVWStrokeCurve d
fill
_ -> error "in cairoOneStrokeSelected"
cairoOneStrokeBBoxOnly :: StrokeBBox -> Render ()
cairoOneStrokeBBoxOnly sbbox = do
let s = gToStroke sbbox
-- case M.lookup (stroke_color s) predefined_pencolor of
-- Just (r,g,b,a) -> setSourceRGBA r g b a
-- Nothing -> setSourceRGBA 0 0 0 1
setSourceRGBA 0 0 0 1
-- setLineWidth (stroke_width s)
setLineWidth 10
let BBox (x1,y1) (x2,y2) = strokebbox_bbox sbbox
rectangle x1 y1 (x2-x1) (y2-y1)
stroke
cairoDrawPageBBoxOnly :: TPageBBoxMap -> Render ()
cairoDrawPageBBoxOnly page = do
let layers = glayers page
cairoDrawBackground (toPage id page)
mapM_ cairoDrawLayerBBoxOnly layers
cairoDrawLayerBBoxOnly :: TLayerBBox -> Render ()
cairoDrawLayerBBoxOnly = mapM_ cairoOneStrokeBBoxOnly . gstrokes
----
cairoDrawPageBBox :: Maybe BBox -> TPageBBoxMap -> Render ()
cairoDrawPageBBox mbbox page = do
cairoDrawBackgroundBBox mbbox (gdimension page) (gbackground page)
mapM_ (cairoDrawLayerBBox mbbox) (glayers page)
cairoDrawLayerBBox :: Maybe BBox -> TLayerBBox -> Render ()
cairoDrawLayerBBox mbbox layer = do
clipBBox mbbox
let hittestbbox = case mbbox of
Nothing -> NotHitted []
:- Hitted (gstrokes layer)
:- Empty
Just bbox -> mkHitTestBBoxBBox bbox (gstrokes layer)
mapM_ drawOneStroke . map gToStroke . concatMap unHitted . getB $ hittestbbox
resetClip
cairoDrawBackgroundBBox :: Maybe BBox -> Dimension -> Background -> Render ()
cairoDrawBackgroundBBox mbbox dim@(Dim w h) (Background typ col sty) = do
let mbbox2 = toMaybe $ fromMaybe mbbox `mappend` (Intersect (Middle (dimToBBox dim)))
case mbbox2 of
Nothing -> cairoDrawBkg (Dim w h) (Background typ col sty)
Just bbox@(BBox (x1,y1) (x2,y2)) -> do
let c = M.lookup col predefined_bkgcolor
case c of
Just (r,g,b,_a) -> setSourceRGB r g b
Nothing -> setSourceRGB 1 1 1
rectangle x1 y1 (x2-x1) (y2-y1)
fill
cairoDrawRulingBBox bbox w h sty
cairoDrawBackgroundBBox _ _ (BackgroundPdf _ _ _ _) =
error "BackgroundPdf in cairoDrawBackgroundBBox"
cairoDrawRulingBBox :: BBox -> Double -> Double -> ByteString -> Render ()
cairoDrawRulingBBox (BBox (x1,y1) (x2,y2)) w h style = do
let drawonerule y = do
moveTo x1 y
lineTo x2 y
stroke
let drawonegraphvert x = do
moveTo x y1
lineTo x y2
stroke
let drawonegraphhoriz y = do
moveTo x1 y
lineTo x2 y
stroke
fullRuleYs = [ predefined_RULING_TOPMARGIN
, predefined_RULING_TOPMARGIN+predefined_RULING_SPACING
..
h-1 ]
ruleYs = filter (\y-> (y <= y2) && (y >= y1)) fullRuleYs
fullGraphXs = [0,predefined_RULING_GRAPHSPACING..w-1]
fullGraphYs = [0,predefined_RULING_GRAPHSPACING..h-1]
graphXs = filter (\x->(x<=x2)&&(x>=x1)) fullGraphXs
graphYs = filter (\y->(y<=y2)&&(y>=y1)) fullGraphYs
let drawHorizRules = do
let (r,g,b,a) = predefined_RULING_COLOR
setSourceRGBA r g b a
setLineWidth predefined_RULING_THICKNESS
mapM_ drawonerule ruleYs
case style of
"plain" -> return ()
"lined" -> do
drawHorizRules
let (r2,g2,b2,a2) = predefined_RULING_MARGIN_COLOR
setSourceRGBA r2 g2 b2 a2
setLineWidth predefined_RULING_THICKNESS
moveTo predefined_RULING_LEFTMARGIN 0
lineTo predefined_RULING_LEFTMARGIN h
stroke
"ruled" -> drawHorizRules
"graph" -> do
let (r3,g3,b3,a3) = predefined_RULING_COLOR
setSourceRGBA r3 g3 b3 a3
setLineWidth predefined_RULING_THICKNESS
mapM_ drawonegraphvert graphXs
mapM_ drawonegraphhoriz graphYs
_ -> return ()
|
wavewave/hoodle-render
|
src/trash/Old/BBoxOld.hs
|
bsd-2-clause
| 6,129 | 30 | 22 | 1,662 | 1,830 | 946 | 884 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Trustworthy #-}
-- | This module was written based on
-- <http://hackage.haskell.org/package/reinterpret-cast-0.1.0/docs/src/Data-ReinterpretCast-Internal-ImplArray.html>.
--
-- Implements casting via a 1-elemnt STUArray, as described in
-- <http://stackoverflow.com/a/7002812/263061>.
module Util.FloatCast
( floatToWord
, wordToFloat
, doubleToWord
, wordToDouble
) where
import Data.Word ( Word32, Word64 )
import Data.Array.ST ( MArray, STUArray, newArray, readArray )
import Data.Array.Unsafe ( castSTUArray )
import GHC.ST ( ST, runST )
-- | Reinterpret-casts a `Float` to a `Word32`.
floatToWord :: Float -> Word32
floatToWord x = runST (cast x)
{-# INLINE floatToWord #-}
-- | Reinterpret-casts a `Word32` to a `Float`.
wordToFloat :: Word32 -> Float
wordToFloat x = runST (cast x)
{-# INLINE wordToFloat #-}
-- | Reinterpret-casts a `Double` to a `Word64`.
doubleToWord :: Double -> Word64
doubleToWord x = runST (cast x)
{-# INLINE doubleToWord #-}
-- | Reinterpret-casts a `Word64` to a `Double`.
wordToDouble :: Word64 -> Double
wordToDouble x = runST (cast x)
{-# INLINE wordToDouble #-}
cast :: (MArray (STUArray s) a (ST s), MArray (STUArray s) b (ST s)) => a -> ST s b
cast x = newArray (0 :: Int, 0) x >>= castSTUArray >>= flip readArray 0
{-# INLINE cast #-}
|
LTI2000/hinterface
|
src/Util/FloatCast.hs
|
bsd-3-clause
| 1,430 | 0 | 8 | 305 | 293 | 166 | 127 | 26 | 1 |
import qualified Wigner.Transformations as T
import qualified Wigner.Symbols as S
import qualified Wigner.DefineExpression as D
import qualified Wigner.OperatorAlgebra as O
import Wigner.Texable
import Wigner.Expression
import qualified Data.Map as M
import qualified Data.List as L
index :: Integer -> Index
index i = S.index (fromInteger i :: Int)
s_psi = S.symbol "\\Psi"
corr = M.fromList [(s_psi, s_psi)]
psi i = D.operatorFuncIx s_psi [i] [Func (Element S.x [] [])]
psi' i = D.operatorFuncIx s_psi [i] [Func (Element S.x' [] [])]
s_rho = S.symbol "\\rho"
rho = D.operator s_rho
gamma1 i = D.constantIx (S.symbol "\\gamma") [index i]
gamma2 i j = D.constantIx (S.symbol "\\gamma") (L.sort [index i, index j])
gamma3 i j k = D.constantIx (S.symbol "\\gamma") (L.sort [index i, index j, index k])
commutator x y = x * y - y * x
lossTerm x = 2 * x * rho * dagger x - dagger x * x * rho - rho * dagger x * x
--loss_terms =
--gamma1 1 * lossTerm (psi 1) +
--gamma3 1 1 1 * lossTerm (psi 1 * psi 1 * psi 1)
--gamma2 2 2 * lossTerm (a 2 * a 2) +
--gamma3 1 1 1 * lossTerm (a 1 * a 1 * a 1) +
master_eqn = commutator (dagger (psi S.ix_j) * dagger (psi' S.ix_k)
* psi' S.ix_k * psi S.ix_j) rho
fpe = T.wignerTransformation corr s_rho master_eqn
main = do
putStrLn $ T.showTexByDifferentials fpe
|
fjarri/wigner
|
examples/me_psi.hs
|
bsd-3-clause
| 1,325 | 8 | 13 | 270 | 549 | 272 | 277 | 26 | 1 |
module Tools where
import qualified Tct.Core.Data as TcT
import qualified Tct.Core.Main as TcT
import qualified Tools.HoCA as HoCA
import qualified Tools.TRS as TRS
data Tool a = Tool { tctConfig :: TcT.TctConfig a
, toolName :: String
, defaultInput :: FilePath }
data SomeTool where
SomeTool :: TcT.Declared a a => Tool a -> SomeTool
tools :: [SomeTool]
tools = [ SomeTool $ Tool { tctConfig = HoCA.config, toolName = "HoCA", defaultInput = "rev-dl.fp" }
, SomeTool $ Tool { tctConfig = TRS.config, toolName = "TRS", defaultInput = "square.trs" } ]
|
mzini/tct-homepage
|
src/Tools.hs
|
bsd-3-clause
| 610 | 0 | 10 | 150 | 169 | 107 | 62 | -1 | -1 |
module FileData.Data2 where
dataVersion :: Int
dataVersion = 2
type Version = Int
type Levels = [Level]
data Data = Data Version Levels deriving (Show, Read)
type Id = Int
type Ids = [Id]
type Entities = [Entity]
type Layers = [Layer]
type Gravity = Double
data Level = Level Entities Layers deriving (Show, Read)
data Layer = Layer Entities Gravity deriving (Show, Read)
type Vector = (Double, Double, Double)
type Box = (Vector, Vector)
type Velocity = Double
type Path = [Vector]
type Bidirectional = Bool
data Animation = Animation Velocity Path Bidirectional deriving (Show, Read)
type Position = Vector
type InitialPosition = Position
type PositionOrAnimation = Either Position Animation
type Bound = Box
data Entity = Player Id InitialPosition
| Enemy Id PositionOrAnimation
| Platform Id PositionOrAnimation Bound
| Star Id Position deriving (Show, Read)
|
dan-t/layers
|
src/FileData/Data2.hs
|
bsd-3-clause
| 994 | 0 | 6 | 268 | 282 | 170 | 112 | 27 | 1 |
import Book
main :: IO ()
main = interact $ fromBooklist . read
|
YoshikuniJujo/funpaala
|
samples/25_nml/encodeBooks.hs
|
bsd-3-clause
| 65 | 0 | 6 | 14 | 27 | 14 | 13 | 3 | 1 |
module CommonMUnitTests (commonMUnitTests) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import qualified Data.EnumMap.Strict as EM
import Test.Tasty
import Test.Tasty.HUnit
import Game.LambdaHack.Client.CommonM
import Game.LambdaHack.Common.Area
import Game.LambdaHack.Common.Kind
import Game.LambdaHack.Common.Level
import Game.LambdaHack.Common.Perception
import Game.LambdaHack.Common.Point
import Game.LambdaHack.Common.State
import Game.LambdaHack.Common.Time
import Game.LambdaHack.Content.TileKind
import qualified Game.LambdaHack.Core.Dice as Dice
import UnitTestHelpers
testLevel :: Level
testLevel = Level
{ lkind = toEnum 0
, ldepth = Dice.AbsDepth 1
, lfloor = EM.empty
, lembed = EM.empty
, lbig = EM.empty
, lproj = EM.empty
, ltile = unknownTileMap (fromJust (toArea (0,0,0,0))) unknownId 10 10
, lentry = EM.empty
, larea = trivialArea (Point 0 0)
, lsmell = EM.empty
, lstair = ([],[])
, lescape = []
, lseen = 0
, lexpl = 0
, ltime = timeZero
, lnight = False
}
commonMUnitTests :: TestTree
commonMUnitTests = testGroup "commonMUnitTests"
[ testCase "getPerFid stubCliState returns emptyPerception" $ do
result <- executorCli (getPerFid testLevelId) stubCliState
fst result @?= emptyPer
, testCase "makeLine, when actor stands at the target position, fails" $
Nothing @?= makeLine False testActor (Point 0 0) 1 emptyCOps testLevel
, testCase "makeLine unknownTiles succeeds" $
Just 1 @?= makeLine False testActor (Point 2 0) 1 emptyCOps testLevel
]
|
LambdaHack/LambdaHack
|
test/CommonMUnitTests.hs
|
bsd-3-clause
| 1,665 | 0 | 13 | 375 | 428 | 254 | 174 | 44 | 1 |
{-# LANGUAGE Rank2Types, FlexibleContexts #-}
module Numeric.AD.Lagrangian.Internal where
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Storable as S
import qualified Data.Packed.Vector as V
import qualified Data.Packed.Matrix as M
import GHC.IO (unsafePerformIO)
import Numeric.AD
import Numeric.Optimization.Algorithms.HagerZhang05
import Numeric.LinearAlgebra.Algorithms
-- | An equality constraint of the form @g(x, y, ...) = c@. Use '<=>' to
-- construct a 'Constraint'.
newtype Constraint = Constraint
{unConstraint :: forall a. (Floating a) => ([a] -> a, a)}
infixr 1 <=>
-- | Build a 'Constraint' from a function and a constant
(<=>) :: (forall a. (Floating a) => [a] -> a)
-> (forall b. (Floating b) => b)
-> Constraint
f <=> c = Constraint (f, c)
-- | Numerically minimize the Langrangian. The objective function and each of
-- the constraints must take the same number of arguments.
minimize :: (forall a. (Floating a) => [a] -> a)
-- ^ The objective function to minimize
-> [Constraint]
-- ^ A list of constraints @g \<=\> c@ corresponding to equations of
-- the form @g(x, y, ...) = c@
-> Double
-- ^ Stop iterating when the largest component of the gradient is
-- smaller than this value
-> Int
-- ^ The arity of the objective function, which must equal the arity of
-- the constraints
-> Either (Result, Statistics) (V.Vector Double, V.Vector Double)
-- ^ Either a 'Right' containing the argmin and the Lagrange
-- multipliers, or a 'Left' containing an explanation of why the
-- gradient descent failed
minimize f constraints tolerance argCount = result where
-- At a constrained minimum of `f`, the gradient of the Lagrangian must be
-- zero. So we square the Lagrangian's gradient (making it non-negative) and
-- minimize it.
(sqGradLgn, gradSqGradLgn) = (fst . g, snd . g) where
g = grad' $ squaredGrad $ lagrangian f constraints argCount
-- Perhaps this should be exposed. ...
guess = U.replicate (argCount + length constraints) 1
result = case unsafePerformIO $
optimize
(defaultParameters {printFinal = False})
tolerance
guess
(VFunction (sqGradLgn . U.toList))
(VGradient (U.fromList . gradSqGradLgn . U.toList))
Nothing of
(vs, ToleranceStatisfied, _) -> Right (S.take argCount vs,
S.drop argCount vs)
(_, x, y) -> Left (x, y)
-- | Numerically maximize the Langrangian. The objective function and each of
-- the constraints must take the same number of arguments.
maximize :: (forall a. (Floating a) => [a] -> a)
-- ^ The objective function to minimize
-> [Constraint]
-- ^ A list of constraints @g \<=\> c@ corresponding to equations of
-- the form @g(x, y, ...) = c@
-> Double
-- ^ Stop iterating when the largest component of the gradient is
-- smaller than this value
-> Int
-- ^ The arity of the objective function, which must equal the arity of
-- the constraints
-> Either (Result, Statistics) (V.Vector Double, V.Vector Double)
-- ^ Either a 'Right' containing the argmax and the Lagrange
-- multipliers, or a 'Left' containing an explanation of why the
-- gradient ascent failed
maximize f = minimize $ negate . f
lagrangian :: (Floating a)
=> (forall b. (Floating b) => [b] -> b)
-> [Constraint]
-> Int
-> [a]
-> a
lagrangian f constraints argCount argsAndLams = result where
args = take argCount argsAndLams
lams = drop argCount argsAndLams
-- g(x, y, ...) = c <=> g(x, y, ...) - c = 0
appliedConstraints = fmap (\(Constraint (g, c)) -> g args - c) constraints
-- L(x, y, ..., lam0, ...) = f(x, y, ...) + lam0 * (g0 - c0) ...
result = (f args) + (sum . zipWith (*) lams $ appliedConstraints)
squaredGrad :: (Floating a)
=> (forall b. (Floating b) => [b] -> b)
-> [a]
-> a
squaredGrad f = sum . fmap square . grad f where
square x = x * x
-- | WARNING: Experimental.
-- This is not a true feasibility test for the function. I am not sure
-- exactly how to implement that. This just checks the feasiblility at a
-- point. If this ever returns false, 'solve' can fail.
feasible :: (Floating a, Field a, M.Element a)
=> (forall b. (Floating b) => [b] -> b)
->[Constraint]
-> [a]
-> Bool
feasible f constraints points = result where
sqGradLgn :: (Floating a) => [a] -> a
sqGradLgn = squaredGrad $ lagrangian f constraints $ length points
hessianMatrix = M.fromLists . hessian sqGradLgn $ points
-- make sure all of the eigenvalues are positive
result = all (>0) . V.toList . eigenvaluesSH $ hessianMatrix
|
jfischoff/lagrangian
|
src/Numeric/AD/Lagrangian/Internal.hs
|
bsd-3-clause
| 5,088 | 0 | 15 | 1,474 | 1,040 | 596 | 444 | 70 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module DataFlow.JSONGraphFormat.RendererSpec where
import Control.Monad (when)
import Data.Aeson ((.=), object, toJSON, ToJSON, encode)
import qualified Data.Aeson as A
import Data.Vector (fromList)
import qualified Data.Map as M
import Test.Hspec (Spec, describe, it, expectationFailure, Expectation)
import Data.ByteString.Lazy.Char8 (unpack)
import Text.Printf (printf)
import DataFlow.Core
import DataFlow.JSONGraphFormat.Renderer (convertDiagram)
shouldEncodeAsJSON :: (ToJSON a) => a -> A.Value -> Expectation
v `shouldEncodeAsJSON` e = do
let j = toJSON v
when (j /= e) $
expectationFailure $
printf "expected:\n%s\nbut got:\n%s\n" (unpack $ encode e) (unpack $ encode j)
spec :: Spec
spec =
describe "renderJSONGraph" $ do
it "converts an empty diagram" $
convertDiagram (Diagram M.empty [] []) `shouldEncodeAsJSON` object [
"graph" .= object [
"metadata" .= object [],
"nodes" .= A.Array (fromList []),
"edges" .= A.Array (fromList [])
]
]
it "uses diagram title attribute as graph label" $
convertDiagram (Diagram (M.singleton "title" (String "Foo")) [] []) `shouldEncodeAsJSON` object [
"graph" .= object [
"label" .= A.String "Foo",
"metadata" .= object [],
"nodes" .= A.Array (fromList []),
"edges" .= A.Array (fromList [])
]
]
it "converts nodes" $
convertDiagram (Diagram M.empty [
Node $ InputOutput "foo" $ M.fromList [
("title", String "Foo"),
("a", String "b")
],
Node $ Function "bar" $ M.fromList [
("title", String "Bar"),
("c", String "d")
]
] []) `shouldEncodeAsJSON` object [
"graph" .= object [
"nodes" .= A.Array (fromList [
object [
"id" .= A.String "foo",
"label" .= A.String "Foo",
"metadata" .= object [
"type" .= A.String "io",
"a" .= A.String "b"
]
],
object [
"id" .= A.String "bar",
"label" .= A.String "Bar",
"metadata" .= object [
"type" .= A.String "function",
"c" .= A.String "d"
]
]
]),
"edges" .= A.Array (fromList []),
"metadata" .= object []
]
]
it "converts edges" $
convertDiagram (Diagram M.empty [] [
Flow "a" "b" $ M.fromList [
("title", String "Foo"),
("a", String "b")
],
Flow "b" "c" $ M.fromList [
("title", String "Bar"),
("b", String "c")
]
]) `shouldEncodeAsJSON` object [
"graph" .= object [
"nodes" .= A.Array (fromList []),
"edges" .= A.Array (fromList [
object [
"source" .= A.String "a",
"target" .= A.String "b",
"label" .= A.String "Foo",
"metadata" .= object [
"a" .= A.String "b"
]
],
object [
"source" .= A.String "b",
"target" .= A.String "c",
"label" .= A.String "Bar",
"metadata" .= object [
"b" .= A.String "c"
]
]
]),
"metadata" .= object []
]
]
it "adds boundary id as node metadata if available" $
convertDiagram (Diagram M.empty [
TrustBoundary "foo" M.empty [
InputOutput "bar" M.empty
]
] []) `shouldEncodeAsJSON` object [
"graph" .= object [
"nodes" .= A.Array (fromList [
object [
"id" .= A.String "bar",
"metadata" .= object [
"type" .= A.String "io",
"trust-boundary" .= A.String "foo"
]
]
]),
"edges" .= A.Array (fromList []),
"metadata" .= object []
]
]
|
sonyxperiadev/dataflow
|
test/DataFlow/JSONGraphFormat/RendererSpec.hs
|
bsd-3-clause
| 4,457 | 0 | 26 | 1,946 | 1,254 | 648 | 606 | 98 | 1 |
--------------------------------------------------------------------------------
-- Copyright © 2011 National Institute of Aerospace / Galois, Inc.
--------------------------------------------------------------------------------
-- | An tagless interpreter for Copilot specifications.
{-# LANGUAGE Trustworthy #-} -- Because of Data.Map (Containers)
module Copilot.Core.Interpret.Render
( renderAsTable
, renderAsCSV
) where
import Data.List (intersperse, transpose, foldl')
import Data.Maybe (catMaybes)
import Copilot.Core.Interpret.Eval (Output, ExecTrace (..))
import qualified Data.Map as M
import Text.PrettyPrint.NCol (asColumns)
import Text.PrettyPrint (Doc, ($$), (<>), text, render, empty)
--------------------------------------------------------------------------------
renderAsTable :: ExecTrace -> String
renderAsTable
ExecTrace
{ interpTriggers = trigs
, interpObservers = obsvs } =
( render
. asColumns
. transpose
. (:) (ppTriggerNames ++ ppObserverNames)
. transpose
) (ppTriggerOutputs ++ ppObserverOutputs)
where
ppTriggerNames :: [Doc]
ppTriggerNames = map (text . (++ ":")) (M.keys trigs)
ppObserverNames :: [Doc]
ppObserverNames = map (text . (++ ":")) (M.keys obsvs)
ppTriggerOutputs :: [[Doc]]
ppTriggerOutputs = map (map ppTriggerOutput) (M.elems trigs)
ppTriggerOutput :: Maybe [Output] -> Doc
ppTriggerOutput (Just vs) = text $ "(" ++ concat (intersperse "," vs) ++ ")"
ppTriggerOutput Nothing = text "--"
ppObserverOutputs :: [[Doc]]
ppObserverOutputs = map (map text) (M.elems obsvs)
--------------------------------------------------------------------------------
renderAsCSV :: ExecTrace -> String
renderAsCSV = render . unfold
unfold :: ExecTrace -> Doc
unfold r =
case step r of
(cs, Nothing) -> cs
(cs, Just r') -> cs $$ unfold r'
step :: ExecTrace -> (Doc, Maybe ExecTrace)
step ExecTrace
{ interpTriggers = trigs
} =
if M.null trigs then (empty, Nothing)
else (foldl' ($$) empty (text "#" : ppTriggerOutputs), tails)
where
ppTriggerOutputs :: [Doc]
ppTriggerOutputs =
catMaybes
. fmap ppTriggerOutput
. M.assocs
. fmap head
$ trigs
ppTriggerOutput :: (String, Maybe [Output]) -> Maybe Doc
ppTriggerOutput (_, Nothing) = Nothing
ppTriggerOutput (cs, Just xs) = Just $
text cs <> text "," <>
(foldr (<>) empty . map text . intersperse ",") xs
tails :: Maybe ExecTrace
tails =
if any null (M.elems (fmap tail trigs))
then Nothing
else Just
ExecTrace
{ interpTriggers = fmap tail trigs
, interpObservers = M.empty
}
--------------------------------------------------------------------------------
|
leepike/copilot-core
|
src/Copilot/Core/Interpret/Render.hs
|
bsd-3-clause
| 2,747 | 0 | 12 | 537 | 760 | 424 | 336 | 65 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.