code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- |
-- Module : Crypto.Random.Entropy.Source
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : Good
--
module Crypto.Random.Entropy.Source where
import Foreign.Ptr
import Data.Word (Word8)
-- | A handle to an entropy maker, either a system capability
-- or a hardware generator.
class EntropySource a where
-- | try to open an handle for this source
entropyOpen :: IO (Maybe a)
-- | try to gather a number of entropy bytes into a buffer.
-- return the number of actual bytes gathered
entropyGather :: a -> Ptr Word8 -> Int -> IO Int
-- | Close an open handle
entropyClose :: a -> IO ()
| vincenthz/hs-crypto-random | Crypto/Random/Entropy/Source.hs | bsd-3-clause | 702 | 0 | 10 | 158 | 96 | 57 | 39 | 7 | 0 |
{- |
Module : $Header$
Description : analyse xml update input
Copyright : (c) Christian Maeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
collect xupdate information
<http://xmldb-org.sourceforge.net/xupdate/xupdate-wd.html>
<http://www.xmldatabases.org/projects/XUpdate-UseCases/>
-}
module Common.XUpdate where
import Common.XPath
import Common.ToXml
import Common.Utils
import Text.XML.Light as XML
import Data.Char
import Data.List
import Control.Monad
-- | possible insertions
data AddChange
= AddElem Element
| AddAttr Attr
| AddText String
| AddComment String
| AddPI String String
| ValueOf
instance Show AddChange where
show c = case c of
AddElem e -> showElement e
AddAttr a -> showAttr a
AddText s -> show s
AddComment s -> "<!--" ++ s ++ "-->"
AddPI n s -> "<?" ++ n ++ " " ++ s ++ "?>"
ValueOf -> valueOfS
valueOfS :: String
valueOfS = "value-of"
data Insert = Before | After | Append deriving (Eq, Show)
showInsert :: Insert -> String
showInsert i = let s = map toLower $ show i in case i of
Append -> s
_ -> "insert-" ++ s
data ChangeSel
= Add Insert [AddChange]
| Remove
| Update String
| Rename String
| Variable String
instance Show ChangeSel where
show c = case c of
Add i cs -> showInsert i ++ concatMap (('\n' :) . show) cs
Remove -> ""
Update s -> '=' : s
Rename s -> s
Variable s -> '$' : s
data Change = Change ChangeSel Expr
instance Show Change where
show (Change c p) =
show p ++ ":" ++ show c
anaXUpdates :: Monad m => String -> m [Change]
anaXUpdates input = case parseXMLDoc input of
Nothing -> fail "cannot parse xupdate file"
Just e -> anaMods e
anaMods :: Monad m => Element -> m [Change]
anaMods = mapM anaXUpdate . elChildren
{- the input element is expected to be one of
xupdate:insert-before
xupdate:insert-after
xupdate:append
xupdate:remove
xupdate:update
-}
xupdateS :: String
xupdateS = "xupdate"
updateS :: String
updateS = "update"
elementS :: String
elementS = "element"
attributeS :: String
attributeS = "attribute"
textS :: String
textS = "text"
appendS :: String
appendS = "append"
removeS :: String
removeS = "remove"
selectS :: String
selectS = "select"
isXUpdateQN :: QName -> Bool
isXUpdateQN = (Just xupdateS ==) . qPrefix
hasLocalQN :: String -> QName -> Bool
hasLocalQN s = (== s) . qName
isElementQN :: QName -> Bool
isElementQN = hasLocalQN elementS
isAttributeQN :: QName -> Bool
isAttributeQN = hasLocalQN attributeS
isTextQN :: QName -> Bool
isTextQN = hasLocalQN textS
isAddQN :: QName -> Bool
isAddQN q = any (flip isPrefixOf $ qName q) ["insert", appendS]
isRemoveQN :: QName -> Bool
isRemoveQN = hasLocalQN removeS
-- | extract the non-empty attribute value
getAttrVal :: Monad m => String -> Element -> m String
getAttrVal n e = case findAttr (unqual n) e of
Nothing -> failX ("missing " ++ n ++ " attribute") $ elName e
Just s -> return s
-- | apply a read operation to the extracted value
readAttrVal :: (Read a, Monad m) => String -> String -> Element -> m a
readAttrVal err attr = (>>= maybeF err . readMaybe) . getAttrVal attr
maybeF :: Monad m => String -> Maybe a -> m a
maybeF err = maybe (fail err) return
getSelectAttr :: Monad m => Element -> m String
getSelectAttr = getAttrVal selectS
getNameAttr :: Monad m => Element -> m String
getNameAttr = getAttrVal "name"
-- | convert a string to a qualified name by splitting at the colon
str2QName :: String -> QName
str2QName str = let (ft, rt) = break (== ':') str in
case rt of
_ : l@(_ : _) -> (unqual l) { qPrefix = Just ft }
_ -> unqual str
-- | extract text and check for no other children
getText :: Monad m => Element -> m String
getText e = let s = trim $ strContent e in
case elChildren e of
[] -> return s
c : _ -> failX "unexpected child" $ elName c
getXUpdateText :: Monad m => Element -> m String
getXUpdateText e = let
msg = fail "expected single <xupdate:text> element"
in case elChildren e of
[] -> getText e
[s] -> let
q = elName s
u = qName q
in if isXUpdateQN q && u == "text" then getText s else msg
_ -> msg
anaXUpdate :: Monad m => Element -> m Change
anaXUpdate e = let
q = elName e
u = qName q in
if isXUpdateQN q then do
sel <- getSelectAttr e
case parseExpr sel of
Left _ -> fail $ "unparsable xpath: " ++ sel
Right p -> case () of
_ | isRemoveQN q -> noContent e $ Change Remove p
| hasLocalQN "variable" q -> do
vn <- getNameAttr e
noContent e $ Change (Variable vn) p
_ -> case lookup u [(updateS, Update), ("rename", Rename)] of
Just c -> do
s <- getXUpdateText e
return $ Change (c s) p
Nothing -> case lookup u $ map (\ i -> (showInsert i, i))
[Before, After, Append] of
Just i -> do
cs <- mapM addXElem $ elChildren e
return $ Change (Add i cs) p
Nothing -> failX "no xupdate modification" q
else failX "no xupdate qualified element" q
-- | partitions additions and ignores comments, pi, and value-of
partitionAddChanges :: [AddChange] -> ([Attr], [Content])
partitionAddChanges = foldr (\ c (as, cs) -> case c of
AddAttr a -> (a : as, cs)
AddElem e -> (as, Elem e : cs)
AddText s -> (as, mkText s : cs)
_ -> (as, cs)) ([], [])
failX :: Monad m => String -> QName -> m a
failX str q = fail $ str ++ ": " ++ showQName q
-- | check if the element contains no other content
noContent :: Monad m => Element -> a -> m a
noContent e a = case elContent e of
[] -> return a
c : _ -> fail $ "unexpected content: " ++ showContent c
addXElem :: Monad m => Element -> m AddChange
addXElem e = let q = elName e in
if isXUpdateQN q then case () of
_ | isTextQN q -> liftM AddText $ getText e
| hasLocalQN "comment" q -> liftM AddComment $ getText e
| hasLocalQN valueOfS q -> noContent e ValueOf
_ -> do
n <- getNameAttr e
let qn = str2QName n
case () of
_ | isAttributeQN q ->
liftM (AddAttr . Attr qn) $ getText e
| isElementQN q -> do
es <- mapM addXElem $ elChildren e
let (as, cs) = partitionAddChanges es
return $ AddElem $ add_attrs as $ node qn cs
| hasLocalQN pIS q -> liftM (AddPI n) $ getText e
_ -> failX "unknown change" q
else return $ AddElem e
{-
xupdate:element
xupdate:attribute
xupdate:text
xupdate:element may contain xupdate:attribute elements and further
xupdate:element or xupdate:text elements.
-}
emptyCData :: CData -> Bool
emptyCData = all isSpace . cdData
validContent :: Content -> Bool
validContent c = case c of
XML.Text t | emptyCData t -> False
_ -> True
cleanUpElem :: Element -> Element
cleanUpElem e = e
{ elContent = map (\ c -> case c of
Elem m -> Elem $ cleanUpElem m
_ -> c) $ filter validContent $ elContent e }
| mariefarrell/Hets | Common/XUpdate.hs | gpl-2.0 | 7,119 | 6 | 28 | 1,845 | 2,410 | 1,195 | 1,215 | 181 | 6 |
{-# LANGUAGE NoMonomorphismRestriction, ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Module : Data.Array.Accelerate.Test.QuickCheck.Arbitrary
-- Copyright : [2010..2011] Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Manuel M T Chakravarty <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.Test.QuickCheck.Arbitrary (
-- * Instances of Arbitrary
arbitraryIntegralExp, arbitraryIntegralVector,
arbitraryFloatingExp, arbitraryFloatingVector
) where
import Data.Array.Accelerate
import Data.Array.Accelerate.Smart
import Control.Applicative hiding (Const)
import Control.Monad
import Data.List
import Foreign.Storable
import Test.QuickCheck
-- Primitive Types
-- ---------------
instance Arbitrary Int8 where arbitrary = arbitrarySizedIntegral
instance Arbitrary Int16 where arbitrary = arbitrarySizedIntegral
instance Arbitrary Int32 where arbitrary = arbitrarySizedIntegral
instance Arbitrary Int64 where arbitrary = arbitrarySizedIntegral
instance Arbitrary Word where arbitrary = arbitrarySizedIntegral
instance Arbitrary Word8 where arbitrary = arbitrarySizedIntegral
instance Arbitrary Word16 where arbitrary = arbitrarySizedIntegral
instance Arbitrary Word32 where arbitrary = arbitrarySizedIntegral
instance Arbitrary Word64 where arbitrary = arbitrarySizedIntegral
-- Arrays
-- ------
instance (Elem e, Arbitrary e) => Arbitrary (Array DIM0 e) where
arbitrary = fromList () <$> vector 1
instance (Elem e, Arbitrary e) => Arbitrary (Array DIM1 e) where
arbitrary = do
n <- suchThat arbitrary (>= 0)
fromList n <$> vector n
instance (Elem e, Arbitrary e) => Arbitrary (Array DIM2 e) where
arbitrary = do
(n, [a,b]) <- clamp <$> vectorOf 2 (suchThat arbitrary (> 0))
fromList (a,b) <$> vector n
instance (Elem e, Arbitrary e) => Arbitrary (Array DIM3 e) where
arbitrary = do
(n, [a,b,c]) <- clamp <$> vectorOf 3 (suchThat arbitrary (> 0))
fromList (a,b,c) <$> vector n
instance (Elem e, Arbitrary e) => Arbitrary (Array DIM4 e) where
arbitrary = do
(n, [a,b,c,d]) <- clamp <$> vectorOf 4 (suchThat arbitrary (> 0))
fromList (a,b,c,d) <$> vector n
instance (Elem e, Arbitrary e) => Arbitrary (Array DIM5 e) where
arbitrary = do
(n, [a,b,c,d,e]) <- clamp <$> vectorOf 5 (suchThat arbitrary (> 0))
fromList (a,b,c,d,e) <$> vector n
-- make sure not to create an index too large that we get integer overflow when
-- converting it to linear form
--
clamp :: [Int] -> (Int, [Int])
clamp = mapAccumL k 1
where k a x = let n = Prelude.max 1 (x `mod` (maxBound `div` a))
in (n*a, n)
-- Expressions
-- -----------
instance Arbitrary (Acc (Vector Int)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Int8)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Int16)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Int32)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Int64)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Word)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Word8)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Word16)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Word32)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Word64)) where arbitrary = sized arbitraryIntegralVector
instance Arbitrary (Acc (Vector Float)) where arbitrary = sized arbitraryFloatingVector
instance Arbitrary (Acc (Vector Double)) where arbitrary = sized arbitraryFloatingVector
-- ugly ugly duplication...
--
arbitraryIntegralExp :: (IsIntegral e, Elem e, Arbitrary e) => Int -> Gen (Exp e)
arbitraryIntegralExp 0 = liftM Const arbitrary
arbitraryIntegralExp n =
let m = n `div` 4
in oneof [ do vec <- arbitraryIntegralVector m
idx <- abs <$> arbitrary
let idx' = shape vec ==* 0 ? (0, constant idx `mod` shape vec)
return (IndexScalar vec idx')
, liftM (!constant ()) (Fold <$> associative <*> arbitraryIntegralExp m <*> arbitraryIntegralVector m)
]
arbitraryIntegralVector :: (IsNum e, IsIntegral e, Elem e, Arbitrary e) => Int -> Gen (Acc (Vector e))
arbitraryIntegralVector 0 = Use <$> arbitrary
arbitraryIntegralVector n =
let m = n `div` 4
in oneof [ Map <$> unaryIntegral <*> arbitraryIntegralVector m
, ZipWith <$> binaryIntegral <*> arbitraryIntegralVector m <*> arbitraryIntegralVector m
, liftM FstArray (Scanl <$> associative <*> arbitraryIntegralExp m <*> arbitraryIntegralVector m)
, liftM FstArray (Scanr <$> associative <*> arbitraryIntegralExp m <*> arbitraryIntegralVector m)
]
arbitraryFloatingExp :: (IsFloating e, Elem e, Arbitrary e) => Int -> Gen (Exp e)
arbitraryFloatingExp 0 = liftM Const arbitrary
arbitraryFloatingExp n =
let m = n `div` 4
in oneof [ do vec <- arbitraryFloatingVector m
idx <- abs <$> arbitrary
let idx' = shape vec ==* 0 ? (0, constant idx `mod` shape vec)
return (IndexScalar vec idx')
, liftM (!constant ()) (Fold <$> associative <*> arbitraryFloatingExp m <*> arbitraryFloatingVector m)
]
arbitraryFloatingVector :: (IsNum e, IsFloating e, Elem e, Arbitrary e) => Int -> Gen (Acc (Vector e))
arbitraryFloatingVector 0 = Use <$> arbitrary
arbitraryFloatingVector n =
let m = n `div` 4
in oneof [ Map <$> unaryFloating <*> arbitraryFloatingVector m
, ZipWith <$> binaryFloating <*> arbitraryFloatingVector m <*> arbitraryFloatingVector m
, liftM FstArray (Scanl <$> associative <*> arbitraryFloatingExp m <*> arbitraryFloatingVector m)
, liftM FstArray (Scanr <$> associative <*> arbitraryFloatingExp m <*> arbitraryFloatingVector m)
]
-- Functions
-- ---------
wordSize :: Int
wordSize = 8 * sizeOf (undefined :: Int)
unaryNum :: (Elem t, IsNum t, Arbitrary t) => Gen (Exp t -> Exp t)
unaryNum = oneof
[ return mkNeg
, return mkAbs
, return mkSig
]
binaryNum :: (Elem t, IsNum t) => Gen (Exp t -> Exp t -> Exp t)
binaryNum = oneof
[ return mkAdd
, return mkSub
, return mkMul
]
unaryIntegral :: (Elem t, IsIntegral t, Arbitrary t) => Gen (Exp t -> Exp t)
unaryIntegral = sized $ \n -> oneof
[ return mkBNot
, flip shift . constant <$> choose (-wordSize,wordSize)
, flip rotate . constant <$> choose (-wordSize,wordSize)
, flip mkBShiftL . constant <$> choose (0,wordSize)
, flip mkBShiftR . constant <$> choose (0,wordSize)
, flip mkBRotateL . constant <$> choose (0,wordSize)
, flip mkBRotateR . constant <$> choose (0,wordSize)
, flip setBit . constant <$> choose (0,wordSize)
, flip clearBit . constant <$> choose (0,wordSize)
, flip complementBit . constant <$> choose (0,wordSize)
, unaryNum
, binaryNum <*> arbitraryIntegralExp (n `div` 2)
, binaryIntegral <*> arbitraryIntegralExp (n `div` 2)
]
binaryIntegral :: (Elem t, IsIntegral t) => Gen (Exp t -> Exp t -> Exp t)
binaryIntegral = oneof
[ return mkQuot
, return mkRem
, return mkIDiv
, return mkMod
, return mkBAnd
, return mkBOr
, return mkBXor
, return mkMax
, return mkMin
, binaryNum
]
unaryFloating :: (Elem t, IsFloating t, Arbitrary t) => Gen (Exp t -> Exp t)
unaryFloating = sized $ \n -> oneof
[ return mkSin
, return mkCos
, return mkTan
-- , return mkAsin -- can't be sure inputs will be in the valid range
-- , return mkAcos
, return mkAtan
, return mkAsinh
-- , return mkAcosh
-- , return mkAtanh
-- , return mkExpFloating
-- , return mkSqrt
-- , return mkLog
, unaryNum
, binaryFloating `ap` arbitraryFloatingExp (n `div` 2)
]
binaryFloating :: (Elem t, IsFloating t) => Gen (Exp t -> Exp t -> Exp t)
binaryFloating = oneof
[ return mkFPow
, return mkLogBase
, return mkMax
, return mkMin
, binaryNum
]
associative :: (Elem t, IsNum t) => Gen (Exp t -> Exp t -> Exp t)
associative = oneof
[ return mkMax
, return mkMin
, return mkAdd
, return mkMul
]
| wilbowma/accelerate | Data/Array/Accelerate/Test/QuickCheck/Arbitrary.hs | bsd-3-clause | 8,457 | 0 | 17 | 1,793 | 2,779 | 1,449 | 1,330 | 155 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>Retire.js Add-on</title>
<maps>
<homeID>retire</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/retire/src/main/javahelp/org/zaproxy/addon/retire/resources/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 964 | 77 | 67 | 156 | 413 | 209 | 204 | -1 | -1 |
module IrrefutableIn1 where
-- test for irrefutable patterns
f :: [Int] -> Int
f ~x = hd x
hd x = head x
tl x = tail x | kmate/HaRe | old/testing/introPattern/IrrefutableIn1.hs | bsd-3-clause | 121 | 0 | 6 | 30 | 51 | 26 | 25 | 5 | 1 |
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.STRef
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (uses Control.Monad.ST)
--
-- Mutable references in the (strict) ST monad.
--
-----------------------------------------------------------------------------
module Data.STRef (
-- * STRefs
STRef, -- abstract
newSTRef,
readSTRef,
writeSTRef,
modifySTRef,
modifySTRef'
) where
import GHC.ST
import GHC.STRef
-- | Mutate the contents of an 'STRef'.
--
-- >>> :{
-- runST (do
-- ref <- newSTRef ""
-- modifySTRef ref (const "world")
-- modifySTRef ref (++ "!")
-- modifySTRef ref ("Hello, " ++)
-- readSTRef ref )
-- :}
-- "Hello, world!"
--
-- Be warned that 'modifySTRef' does not apply the function strictly. This
-- means if the program calls 'modifySTRef' many times, but seldomly uses the
-- value, thunks will pile up in memory resulting in a space leak. This is a
-- common mistake made when using an STRef as a counter. For example, the
-- following will leak memory and may produce a stack overflow:
--
-- >>> import Control.Monad (replicateM_)
-- >>> :{
-- print (runST (do
-- ref <- newSTRef 0
-- replicateM_ 1000 $ modifySTRef ref (+1)
-- readSTRef ref ))
-- :}
-- 1000
--
-- To avoid this problem, use 'modifySTRef'' instead.
modifySTRef :: STRef s a -> (a -> a) -> ST s ()
modifySTRef ref f = writeSTRef ref . f =<< readSTRef ref
-- | Strict version of 'modifySTRef'
--
-- @since 4.6.0.0
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' ref f = do
x <- readSTRef ref
let x' = f x
x' `seq` writeSTRef ref x'
| ezyang/ghc | libraries/base/Data/STRef.hs | bsd-3-clause | 1,913 | 0 | 10 | 432 | 217 | 134 | 83 | 17 | 1 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1993-1998
\section[TcAnnotations]{Typechecking annotations}
-}
{-# LANGUAGE CPP #-}
module TcAnnotations ( tcAnnotations, annCtxt ) where
#ifdef GHCI
import {-# SOURCE #-} TcSplice ( runAnnotation )
import Module
import DynFlags
import Control.Monad ( when )
#endif
import HsSyn
import Annotations
import Name
import TcRnMonad
import SrcLoc
import Outputable
import FastString
#ifndef GHCI
tcAnnotations :: [LAnnDecl Name] -> TcM [Annotation]
-- No GHCI; emit a warning (not an error) and ignore. cf Trac #4268
tcAnnotations [] = return []
tcAnnotations anns@(L loc _ : _)
= do { setSrcSpan loc $ addWarnTc $
(ptext (sLit "Ignoring ANN annotation") <> plural anns <> comma
<+> ptext (sLit "because this is a stage-1 compiler or doesn't support GHCi"))
; return [] }
#else
tcAnnotations :: [LAnnDecl Name] -> TcM [Annotation]
-- GHCI exists, typecheck the annotations
tcAnnotations anns = mapM tcAnnotation anns
tcAnnotation :: LAnnDecl Name -> TcM Annotation
tcAnnotation (L loc ann@(HsAnnotation _ provenance expr)) = do
-- Work out what the full target of this annotation was
mod <- getModule
let target = annProvenanceToTarget mod provenance
-- Run that annotation and construct the full Annotation data structure
setSrcSpan loc $ addErrCtxt (annCtxt ann) $ do
-- See #10826 -- Annotations allow one to bypass Safe Haskell.
dflags <- getDynFlags
when (safeLanguageOn dflags) $ failWithTc safeHsErr
runAnnotation target expr
where
safeHsErr = vcat [ ptext (sLit "Annotations are not compatible with Safe Haskell.")
, ptext (sLit "See https://ghc.haskell.org/trac/ghc/ticket/10826") ]
annProvenanceToTarget :: Module -> AnnProvenance Name -> AnnTarget Name
annProvenanceToTarget _ (ValueAnnProvenance (L _ name)) = NamedTarget name
annProvenanceToTarget _ (TypeAnnProvenance (L _ name)) = NamedTarget name
annProvenanceToTarget mod ModuleAnnProvenance = ModuleTarget mod
#endif
annCtxt :: OutputableBndr id => AnnDecl id -> SDoc
annCtxt ann
= hang (ptext (sLit "In the annotation:")) 2 (ppr ann)
| wxwxwwxxx/ghc | compiler/typecheck/TcAnnotations.hs | bsd-3-clause | 2,217 | 0 | 14 | 444 | 238 | 130 | 108 | 19 | 1 |
{-# LANGUAGE GADTs #-}
module T4087 where
data Equal a b where
Equal :: Equal a a
| urbanslug/ghc | testsuite/tests/ghci/scripts/T4087.hs | bsd-3-clause | 89 | 0 | 6 | 24 | 21 | 14 | 7 | 4 | 0 |
{-# LANGUAGE StandaloneDeriving #-}
module Main where
import T9830a
deriving instance (Show a, Show b) => Show (ADT a b)
main :: IO ()
main = do
putStrLn $ "Prec 6: " ++ showsPrec 6 ("test" :?: "show") ""
putStrLn $ "Prec 7: " ++ showsPrec 7 ("test" :?: "show") ""
putStrLn $ "Prec 9: " ++ showsPrec 9 ("test" :?: "show") ""
putStrLn $ "Prec 10: " ++ showsPrec 10 ("test" :?: "show") ""
| ghc-android/ghc | testsuite/tests/deriving/should_run/T9830.hs | bsd-3-clause | 412 | 0 | 10 | 100 | 154 | 78 | 76 | 10 | 1 |
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
-- This fails, because the type in the pattern doesn't exactly match
-- the context type. We don't do subsumption in patterns any more.
-- GHC 7.0: now we do again
module Foo where
foo :: (forall c. c -> c) -> [Char]
foo (f :: forall a. [a] -> [a]) = f undefined
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/typecheck/should_fail/tcfail145.hs | bsd-3-clause | 318 | 0 | 10 | 65 | 65 | 39 | 26 | 4 | 1 |
-- | Carefully optimised implementations of GPU transpositions.
-- Written in ImpCode so we can compile it to both CUDA and OpenCL.
module Futhark.CodeGen.ImpGen.GPU.Transpose
( TransposeType (..),
TransposeArgs,
mapTransposeKernel,
)
where
import Futhark.CodeGen.ImpCode.GPU
import Futhark.IR.Prop.Types
import Futhark.Util.IntegralExp (divUp, quot, rem)
import Prelude hiding (quot, rem)
-- | Which form of transposition to generate code for.
data TransposeType
= TransposeNormal
| TransposeLowWidth
| TransposeLowHeight
| -- | For small arrays that do not
-- benefit from coalescing.
TransposeSmall
deriving (Eq, Ord, Show)
-- | The types of the arguments accepted by a transposition function.
type TransposeArgs =
( VName,
TExp Int32,
VName,
TExp Int32,
TExp Int32,
TExp Int32,
TExp Int32,
TExp Int32,
TExp Int32,
VName
)
elemsPerThread :: TExp Int32
elemsPerThread = 4
mapTranspose :: TExp Int32 -> TransposeArgs -> PrimType -> TransposeType -> KernelCode
mapTranspose block_dim args t kind =
case kind of
TransposeSmall ->
mconcat
[ get_ids,
dec our_array_offset $ le32 get_global_id_0 `quot` (height * width) * (height * width),
dec x_index $ (le32 get_global_id_0 `rem` (height * width)) `quot` height,
dec y_index $ le32 get_global_id_0 `rem` height,
DeclareScalar val Nonvolatile t,
dec odata_offset $
(basic_odata_offset `quot` primByteSize t) + le32 our_array_offset,
dec idata_offset $
(basic_idata_offset `quot` primByteSize t) + le32 our_array_offset,
dec index_in $ le32 y_index * width + le32 x_index,
dec index_out $ le32 x_index * height + le32 y_index,
when
(le32 get_global_id_0 .<. width * height * num_arrays)
( mconcat
[ Read val idata (elements $ sExt64 $ le32 idata_offset + le32 index_in) t (Space "global") Nonvolatile,
Write odata (elements $ sExt64 $ le32 odata_offset + le32 index_out) t (Space "global") Nonvolatile (var val t)
]
)
]
TransposeLowWidth ->
mkTranspose $
lowDimBody
(le32 get_group_id_0 * block_dim + (le32 get_local_id_0 `quot` muly))
( le32 get_group_id_1 * block_dim * muly + le32 get_local_id_1
+ (le32 get_local_id_0 `rem` muly) * block_dim
)
( le32 get_group_id_1 * block_dim * muly + le32 get_local_id_0
+ (le32 get_local_id_1 `rem` muly) * block_dim
)
(le32 get_group_id_0 * block_dim + (le32 get_local_id_1 `quot` muly))
TransposeLowHeight ->
mkTranspose $
lowDimBody
( le32 get_group_id_0 * block_dim * mulx + le32 get_local_id_0
+ (le32 get_local_id_1 `rem` mulx) * block_dim
)
(le32 get_group_id_1 * block_dim + (le32 get_local_id_1 `quot` mulx))
(le32 get_group_id_1 * block_dim + (le32 get_local_id_0 `quot` mulx))
( le32 get_group_id_0 * block_dim * mulx + le32 get_local_id_1
+ (le32 get_local_id_0 `rem` mulx) * block_dim
)
TransposeNormal ->
mkTranspose $
mconcat
[ dec x_index $ le32 get_global_id_0,
dec y_index $ le32 get_group_id_1 * tile_dim + le32 get_local_id_1,
DeclareScalar val Nonvolatile t,
when (le32 x_index .<. width) $
For j (untyped elemsPerThread) $
let i = le32 j * (tile_dim `quot` elemsPerThread)
in mconcat
[ dec index_in $ (le32 y_index + i) * width + le32 x_index,
when (le32 y_index + i .<. height) $
mconcat
[ Read
val
idata
(elements $ sExt64 $ le32 idata_offset + le32 index_in)
t
(Space "global")
Nonvolatile,
Write
block
( elements $
sExt64 $
(le32 get_local_id_1 + i) * (tile_dim + 1)
+ le32 get_local_id_0
)
t
(Space "local")
Nonvolatile
(var val t)
]
],
Op $ Barrier FenceLocal,
SetScalar x_index $ untyped $ le32 get_group_id_1 * tile_dim + le32 get_local_id_0,
SetScalar y_index $ untyped $ le32 get_group_id_0 * tile_dim + le32 get_local_id_1,
when (le32 x_index .<. height) $
For j (untyped elemsPerThread) $
let i = le32 j * (tile_dim `quot` elemsPerThread)
in mconcat
[ dec index_out $ (le32 y_index + i) * height + le32 x_index,
when (le32 y_index + i .<. width) $
mconcat
[ Read
val
block
( elements . sExt64 $
le32 get_local_id_0 * (tile_dim + 1) + le32 get_local_id_1 + i
)
t
(Space "local")
Nonvolatile,
Write
odata
(elements $ sExt64 $ le32 odata_offset + le32 index_out)
t
(Space "global")
Nonvolatile
(var val t)
]
]
]
where
dec v (TPrimExp e) =
DeclareScalar v Nonvolatile (primExpType e) <> SetScalar v e
tile_dim = 2 * block_dim
when a b = If a b mempty
( odata,
basic_odata_offset,
idata,
basic_idata_offset,
width,
height,
mulx,
muly,
num_arrays,
block
) = args
-- Be extremely careful when editing this list to ensure that
-- the names match up. Also, be careful that the tags on
-- these names do not conflict with the tags of the
-- surrounding code. We accomplish the latter by using very
-- low tags (normal variables start at least in the low
-- hundreds).
[ our_array_offset,
x_index,
y_index,
odata_offset,
idata_offset,
index_in,
index_out,
get_global_id_0,
get_local_id_0,
get_local_id_1,
get_group_id_0,
get_group_id_1,
get_group_id_2,
j,
val
] =
zipWith (flip VName) [30 ..] $
map
nameFromString
[ "our_array_offset",
"x_index",
"y_index",
"odata_offset",
"idata_offset",
"index_in",
"index_out",
"get_global_id_0",
"get_local_id_0",
"get_local_id_1",
"get_group_id_0",
"get_group_id_1",
"get_group_id_2",
"j",
"val"
]
get_ids =
mconcat
[ DeclareScalar get_global_id_0 Nonvolatile int32,
Op $ GetGlobalId get_global_id_0 0,
DeclareScalar get_local_id_0 Nonvolatile int32,
Op $ GetLocalId get_local_id_0 0,
DeclareScalar get_local_id_1 Nonvolatile int32,
Op $ GetLocalId get_local_id_1 1,
DeclareScalar get_group_id_0 Nonvolatile int32,
Op $ GetGroupId get_group_id_0 0,
DeclareScalar get_group_id_1 Nonvolatile int32,
Op $ GetGroupId get_group_id_1 1,
DeclareScalar get_group_id_2 Nonvolatile int32,
Op $ GetGroupId get_group_id_2 2
]
mkTranspose body =
mconcat
[ get_ids,
dec our_array_offset $ le32 get_group_id_2 * width * height,
dec odata_offset $
(basic_odata_offset `quot` primByteSize t) + le32 our_array_offset,
dec idata_offset $
(basic_idata_offset `quot` primByteSize t) + le32 our_array_offset,
body
]
lowDimBody x_in_index y_in_index x_out_index y_out_index =
mconcat
[ dec x_index x_in_index,
dec y_index y_in_index,
DeclareScalar val Nonvolatile t,
dec index_in $ le32 y_index * width + le32 x_index,
when (le32 x_index .<. width .&&. le32 y_index .<. height) $
mconcat
[ Read
val
idata
(elements $ sExt64 $ le32 idata_offset + le32 index_in)
t
(Space "global")
Nonvolatile,
Write
block
(elements $ sExt64 $ le32 get_local_id_1 * (block_dim + 1) + le32 get_local_id_0)
t
(Space "local")
Nonvolatile
(var val t)
],
Op $ Barrier FenceLocal,
SetScalar x_index $ untyped x_out_index,
SetScalar y_index $ untyped y_out_index,
dec index_out $ le32 y_index * height + le32 x_index,
when (le32 x_index .<. height .&&. le32 y_index .<. width) $
mconcat
[ Read
val
block
(elements $ sExt64 $ le32 get_local_id_0 * (block_dim + 1) + le32 get_local_id_1)
t
(Space "local")
Nonvolatile,
Write
odata
(elements $ sExt64 (le32 odata_offset + le32 index_out))
t
(Space "global")
Nonvolatile
(var val t)
]
]
-- | Generate a transpose kernel. There is special support to handle
-- input arrays with low width, low height, or both.
--
-- Normally when transposing a @[2][n]@ array we would use a @FUT_BLOCK_DIM x
-- FUT_BLOCK_DIM@ group to process a @[2][FUT_BLOCK_DIM]@ slice of the input
-- array. This would mean that many of the threads in a group would be inactive.
-- We try to remedy this by using a special kernel that will process a larger
-- part of the input, by using more complex indexing. In our example, we could
-- use all threads in a group if we are processing @(2/FUT_BLOCK_DIM)@ as large
-- a slice of each rows per group. The variable @mulx@ contains this factor for
-- the kernel to handle input arrays with low height.
--
-- See issue #308 on GitHub for more details.
--
-- These kernels are optimized to ensure all global reads and writes
-- are coalesced, and to avoid bank conflicts in shared memory. Each
-- thread group transposes a 2D tile of block_dim*2 by block_dim*2
-- elements. The size of a thread group is block_dim/2 by
-- block_dim*2, meaning that each thread will process 4 elements in a
-- 2D tile. The shared memory array containing the 2D tile consists
-- of block_dim*2 by block_dim*2+1 elements. Padding each row with
-- an additional element prevents bank conflicts from occuring when
-- the tile is accessed column-wise.
mapTransposeKernel ::
String ->
Integer ->
TransposeArgs ->
PrimType ->
TransposeType ->
Kernel
mapTransposeKernel desc block_dim_int args t kind =
Kernel
{ kernelBody =
DeclareMem block (Space "local")
<> Op (LocalAlloc block block_size)
<> mapTranspose block_dim args t kind,
kernelUses = uses,
kernelNumGroups = map untyped num_groups,
kernelGroupSize = map untyped group_size,
kernelName = nameFromString name,
kernelFailureTolerant = True,
kernelCheckLocalMemory = False
}
where
pad2DBytes k = k * (k + 1) * primByteSize t
block_size =
bytes $
case kind of
TransposeSmall -> 1 :: TExp Int64
-- Not used, but AMD's OpenCL
-- does not like zero-size
-- local memory.
TransposeNormal -> fromInteger $ pad2DBytes $ 2 * block_dim_int
TransposeLowWidth -> fromInteger $ pad2DBytes block_dim_int
TransposeLowHeight -> fromInteger $ pad2DBytes block_dim_int
block_dim = fromInteger block_dim_int :: TExp Int32
( odata,
basic_odata_offset,
idata,
basic_idata_offset,
width,
height,
mulx,
muly,
num_arrays,
block
) = args
(num_groups, group_size) =
case kind of
TransposeSmall ->
( [(num_arrays * width * height) `divUp` (block_dim * block_dim)],
[block_dim * block_dim]
)
TransposeLowWidth ->
lowDimKernelAndGroupSize block_dim num_arrays width $ height `divUp` muly
TransposeLowHeight ->
lowDimKernelAndGroupSize block_dim num_arrays (width `divUp` mulx) height
TransposeNormal ->
let actual_dim = block_dim * 2
in ( [ width `divUp` actual_dim,
height `divUp` actual_dim,
num_arrays
],
[actual_dim, actual_dim `quot` elemsPerThread, 1]
)
uses =
map
(`ScalarUse` int32)
( namesToList $
mconcat $
map
freeIn
[ basic_odata_offset,
basic_idata_offset,
num_arrays,
width,
height,
mulx,
muly
]
)
++ map MemoryUse [odata, idata]
name =
case kind of
TransposeSmall -> desc ++ "_small"
TransposeLowHeight -> desc ++ "_low_height"
TransposeLowWidth -> desc ++ "_low_width"
TransposeNormal -> desc
lowDimKernelAndGroupSize ::
TExp Int32 ->
TExp Int32 ->
TExp Int32 ->
TExp Int32 ->
([TExp Int32], [TExp Int32])
lowDimKernelAndGroupSize block_dim num_arrays x_elems y_elems =
( [ x_elems `divUp` block_dim,
y_elems `divUp` block_dim,
num_arrays
],
[block_dim, block_dim, 1]
)
| diku-dk/futhark | src/Futhark/CodeGen/ImpGen/GPU/Transpose.hs | isc | 14,525 | 0 | 26 | 5,727 | 3,028 | 1,599 | 1,429 | 321 | 10 |
{-# LANGUAGE TupleSections, ViewPatterns #-}
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, PatternGuards, QuasiQuotes #-}
module Control.OperationalTransformation.JSON.Compose where
import Control.OperationalTransformation.JSON.Types
import Control.OperationalTransformation.JSON.Util
import Control.OperationalTransformation.Text0
import Data.Monoid
import qualified Data.Text as T
compose :: JSONOperation -> JSONOperation -> Either String JSONOperation
-- Null operations compose to no-ops
compose (JSONOperation []) _ = Right $ JSONOperation []
compose _ (JSONOperation []) = Right $ JSONOperation []
compose (JSONOperation [op1]) (JSONOperation [op2]) = case compose' op1 op2 of
Left err -> Right $ JSONOperation [op1, op2]
Right ops -> Right $ JSONOperation ops
compose (JSONOperation ops1) (JSONOperation ops2) = Right $ JSONOperation $ ops1 ++ ops2
compose' :: JSONOp -> JSONOp -> Either String [JSONOp]
compose' (Add path1 n1) (Add path2 n2) | path1 == path2 = Right [Add path1 (n1 + n2)]
-- List insert and delete cancel out
compose' (ListInsert path1 index1 obj1) (ListDelete path2 index2 obj2)
| path1 == path2, index1 == index2, obj1 == obj2
= Right [Identity]
compose' (ListDelete path1 index1 obj1) (ListInsert path2 index2 obj2)
| path1 == path2, index1 == index2, obj1 == obj2
= Right [Identity]
-- List replace and delete get mashed togeter if possible
compose' (ListReplace path1 index1 obj11 obj12) (ListDelete path2 index2 obj2)
| path1 == path2, index1 == index2, obj12 == obj2
= Right [ListDelete path1 index1 obj11]
-- String inserts get mashed together if possible
compose' (StringInsert path1 pos1 text1) (StringInsert path2 pos2 text2)
| path1 == path2, pos2 == pos1 + (T.length text1)
= Right [StringInsert path1 pos1 (text1 <> text2)]
compose' (ApplySubtypeOperation path1 "text0" (T0 [TextInsert pos1 text1]))
(ApplySubtypeOperation path2 "text0" (T0 [TextInsert pos2 text2]))
| path1 == path2, pos2 == pos1 + (T.length text1)
= Right [ApplySubtypeOperation path1 "text0" (T0 [TextInsert pos1 (text1 <> text2)])]
-- Object replacements compose
compose' op1@(ObjectReplace path key from1 to1) op2@(ObjectReplace _ _ from2 to2)
| (getFullPath op1) == (getFullPath op2) = Right [ObjectReplace path key from1 to2]
-- Object delete + insert becomes replace
compose' op1@(ObjectDelete path key val1) op2@(ObjectInsert _ _ val2)
| (getFullPath op1) == (getFullPath op2) = Right [ObjectReplace path key val1 val2]
compose' op1 op2 = Left "Don't know how to compose these"
| thomasjm/ot.hs | src/Control/OperationalTransformation/JSON/Compose.hs | mit | 2,553 | 0 | 14 | 405 | 865 | 436 | 429 | 38 | 2 |
module Tools.Formatting (
prefix_spaces,
postfix_spaces
) where
postfix_spaces :: String -> Int -> String
postfix_spaces string len =
postfix_string string (len - (length string)) " "
prefix_spaces :: String -> Int -> String
prefix_spaces string len =
prefix_string string (len - (length string)) " "
prefix_string :: String -> Int -> String -> String
prefix_string string len prefix =
if len < 0 then
string
else
prefix_string (prefix ++ string) (len - 1) prefix
postfix_string :: String -> Int -> String -> String
postfix_string string len postfix =
if len < 0 then
string
else
postfix_string (string ++ postfix) (len - 1) postfix
| quintenpalmer/fresh | haskell/src/Tools/Formatting.hs | mit | 701 | 0 | 9 | 171 | 224 | 119 | 105 | 19 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Text.CommonParsers where
import Prelude hiding (takeWhile)
import Control.Monad
import Control.Applicative
import Data.Attoparsec.Text
import Data.Attoparsec.Combinator
import Data.Text (Text, pack)
oneOf = choice . fmap char
ignored = comment <|> spaces
where
spaces = void (takeWhile $ \e -> e `elem` " \t\n\f\r")
comment = do
spaces
many $ do
string ";;"
manyTill anyChar endOfLine
spaces
spaces
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
identifier = do
head <- letter <|> symbol
tail <- many (letter <|> digit <|> symbol)
return . pack $ head : tail
inParens :: Parser a -> Parser a
inParens parser = (char '(' >> ignored) *> parser <* (ignored >> char ')')
| AKST/scheme.llvm | src/Text/CommonParsers.hs | mit | 776 | 0 | 12 | 185 | 246 | 128 | 118 | 25 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Language.Haskell.TypeCheck.Types where
import Control.Monad.ST
import Control.Monad.ST.Unsafe
import Data.Data
import Data.STRef
import GHC.Generics
import Language.Haskell.Exts.SrcLoc
import qualified Language.Haskell.TypeCheck.Pretty as P
import System.IO.Unsafe
import qualified Text.PrettyPrint.ANSI.Leijen as Doc
import Language.Haskell.Scope (Entity (..), Location,
QualifiedName (..))
import qualified Language.Haskell.Scope as Scope
-- Type variables are uniquely identified by their name and binding point.
data TcVar
= TcVar String Location
| TcSkolemVar String
| TcUniqueVar Int
deriving ( Show, Eq, Ord, Data, Generic )
-- data TcVar_ = TcVar String Location | SkolemVar String | UniqueVar Int
data TyVar = TyVar String
deriving ( Show, Eq, Ord, Data, Generic )
data TcMetaVar s = TcMetaRef Int (STRef s (Maybe (TcType s)))
instance Show (TcMetaVar s) where
show (TcMetaRef name _) = show name
instance Eq (TcMetaVar s) where
TcMetaRef _ r1 == TcMetaRef _ r2 = r1==r2
instance Ord (TcMetaVar s) where
compare (TcMetaRef i1 _) (TcMetaRef i2 _) = compare i1 i2
data Expected s a = Infer (STRef s a) | Check a
data TcType s
= TcForall [TcVar] (TcQual s (TcType s))
| TcFun (TcType s) (TcType s)
| TcApp (TcType s) (TcType s)
-- Uninstantiated tyvar
| TcRef TcVar
| TcCon QualifiedName
-- Instantiated tyvar
| TcMetaVar (TcMetaVar s)
| TcUnboxedTuple [TcType s]
| TcTuple [TcType s]
| TcList (TcType s)
| TcStar
-- | TcUndefined
deriving ( Show, Eq, Ord )
-- Foralls can appear anywhere.
type Sigma s = TcType s
-- No foralls at the top-level
type Rho s = TcType s
-- No foralls anywhere.
type Tau s = TcType s
type ExpectedRho s = Expected s (Rho s)
-- data TyVar = TyVar String Location
-- deriving ( Show, Eq, Ord )
data Type
= TyForall [TyVar] (Qualified Type)
| TyFun Type Type
| TyApp Type Type
| TyRef TyVar
| TyCon QualifiedName
| TyUnboxedTuple [Type]
| TyTuple [Type]
| TyList Type
| TyStar
-- | TyUndefined
deriving ( Show, Eq, Ord, Data, Generic )
toTcType :: Type -> TcType s
toTcType ty =
case ty of
TyForall tyvars (predicates :=> t) ->
TcForall [ TcVar name [] | TyVar name <- tyvars ] (TcQual (map toTcPred predicates) (toTcType t))
TyFun t1 t2 -> TcFun (toTcType t1) (toTcType t2)
TyApp t1 t2 -> TcApp (toTcType t1) (toTcType t2)
TyRef (TyVar name) -> TcRef (TcVar name [])
TyCon qualifiedName -> TcCon qualifiedName
TyUnboxedTuple tys -> TcUnboxedTuple (map toTcType tys)
TyTuple tys -> TcTuple (map toTcType tys)
TyList t1 -> TcList (toTcType t1)
-- TyUndefined -> TcUndefined
TyStar -> TcStar
toTcPred :: Predicate -> TcPred s
toTcPred (IsIn className ty) = TcIsIn className (toTcType ty)
type TcCoercion s = TcProof s -> TcProof s
data TcProof s
= TcProofAbs [TcVar] (TcProof s)
| TcProofAp (TcProof s) [TcType s]
| TcProofLam Int (TcType s) (TcProof s)
| TcProofSrc (TcType s)
| TcProofPAp (TcProof s) (TcProof s)
| TcProofVar Int
deriving (Show)
data Proof
= ProofAbs [TyVar] Proof
| ProofAp Proof [Type]
| ProofLam Int Type Proof
| ProofSrc Type
| ProofPAp Proof Proof
| ProofVar Int
deriving (Eq, Ord, Show, Data, Generic)
-- for arguments to the left of ->
arrowPrecedence :: Int
arrowPrecedence = 1
-- for arguments of type or data constructors, or of a class.
appPrecedence :: Int
appPrecedence = 2
instance P.Pretty (TcType s) where
prettyPrec p thisTy =
case thisTy of
TcForall [] (TcQual [] t) ->
P.prettyPrec p t
TcForall vars qual -> P.parensIf (p > 0) $
Doc.text "∀" Doc.<+> Doc.hsep (map P.pretty vars) Doc.<>
Doc.dot Doc.<+> P.pretty qual
TcFun a b -> P.parensIf (p > 0) $
P.prettyPrec arrowPrecedence a Doc.<+>
Doc.text "→ " Doc.<+> P.pretty b
TcApp a b -> P.parensIf (p > arrowPrecedence) $
P.pretty a Doc.<+> P.prettyPrec appPrecedence b
TcCon (QualifiedName "" ident) ->
Doc.text ident
TcCon (QualifiedName m ident) ->
Doc.text (m ++ "." ++ ident)
TcRef var -> P.pretty var
TcMetaVar meta ->
P.prettyPrec p meta
TcUnboxedTuple tys ->
Doc.text "(#" Doc.<+>
Doc.hsep (Doc.punctuate Doc.comma $ map P.pretty tys) Doc.<+>
Doc.text "#)"
TcTuple tys -> Doc.tupled (map P.pretty tys)
TcList ty ->
Doc.brackets (P.pretty ty)
-- TcUndefined ->
-- Doc.red (Doc.text "undefined")
TcStar ->
Doc.text "*"
instance P.Pretty TcVar where
pretty (TcVar ident _src) = Doc.text ident
pretty (TcSkolemVar ident) = Doc.text "skolem" <> Doc.parens (Doc.text ident)
pretty (TcUniqueVar ident) = Doc.int ident
instance P.Pretty TyVar where
pretty (TyVar ident) = Doc.text ident
unsafePerformST :: ST s a -> a
unsafePerformST = unsafePerformIO . unsafeSTToIO
instance P.Pretty (TcMetaVar s) where
prettyPrec p (TcMetaRef ident ref) =
-- Doc.parens (Doc.text ident) Doc.<>
unsafePerformST (do
mbTy <- readSTRef ref
case mbTy of
Just ty -> return $ Doc.blue (Doc.int ident) Doc.<> Doc.angles (P.prettyPrec p ty)
Nothing -> return $ Doc.red (Doc.int ident))
-- pretty (TcMetaRef ident _) = Doc.red (Doc.text ident)
instance P.Pretty t => P.Pretty (TcQual s t) where
prettyPrec p (TcQual [] t) = P.prettyPrec p t
prettyPrec p (TcQual quals t) =
P.parensIf (length quals > 1) (Doc.hsep $ Doc.punctuate Doc.comma $ map P.pretty quals) Doc.<+>
Doc.text "⇒" Doc.<+> P.prettyPrec p t
instance P.Pretty t => P.Pretty (Qualified t) where
prettyPrec p ([] :=> t) = P.prettyPrec p t
prettyPrec p (quals :=> t) =
P.parensIf (length quals > 1) (Doc.hsep $ Doc.punctuate Doc.comma $ map P.pretty quals) Doc.<+>
Doc.text "⇒" Doc.<+> P.prettyPrec p t
instance P.Pretty Entity where
pretty = P.pretty . entityName
instance P.Pretty QualifiedName where
pretty (QualifiedName m ident) =
Doc.text (m ++ "." ++ ident)
instance P.Pretty (TcPred s) where
pretty (TcIsIn gname t) =
P.pretty gname Doc.<+> P.pretty t
instance P.Pretty Predicate where
pretty (IsIn gname t) =
P.pretty gname Doc.<+> P.pretty t
instance P.Pretty Type where
prettyPrec p thisTy =
case thisTy of
-- TyForall [] ([] :=> t) ->
-- P.prettyPrec p t
TyForall vars qual -> P.parensIf (p > 0) $
Doc.text "∀" Doc.<+> Doc.hsep (map P.pretty vars) Doc.<>
Doc.dot Doc.<+> P.pretty qual
TyFun a b -> P.parensIf (p > 0) $
P.prettyPrec arrowPrecedence a Doc.<+>
Doc.text "→ " Doc.<+> P.pretty b
TyApp a b -> P.parensIf (p > arrowPrecedence) $
P.pretty a Doc.<+> P.prettyPrec appPrecedence b
TyCon (QualifiedName "" ident) ->
Doc.text ident
TyCon (QualifiedName m ident) ->
Doc.text (m ++ "." ++ ident)
TyRef var -> P.pretty var
TyUnboxedTuple tys ->
Doc.text "(#" Doc.<+>
Doc.hsep (Doc.punctuate Doc.comma $ map P.pretty tys) Doc.<+>
Doc.text "#)"
TyTuple tys -> Doc.tupled (map P.pretty tys)
TyList ty ->
Doc.brackets (P.pretty ty)
TyStar -> Doc.text "*"
-- TyUndefined ->
-- Doc.red (Doc.text "undefined")
instance P.Pretty Proof where
prettyPrec prec p =
case p of
ProofAbs tvs p' -> P.parensIf (prec > 0) $
Doc.text "Λ" Doc.<> Doc.hsep (map P.pretty tvs) Doc.<> Doc.dot Doc.<+> P.pretty p'
ProofAp p' tys -> P.parensIf (prec > 0) $
P.prettyPrec arrowPrecedence p' Doc.<+> Doc.text "@" Doc.<+> Doc.hsep (map (P.prettyPrec appPrecedence) tys)
ProofLam n ty p' -> -- P.parensIf (True) $
Doc.text "λ" Doc.<>
Doc.int n Doc.<> Doc.text "::" Doc.<> P.prettyPrec appPrecedence ty Doc.<>
Doc.dot Doc.<+> P.pretty p'
ProofSrc ty -> P.prettyPrec prec ty
ProofPAp p1 p2 -> P.parensIf (prec > arrowPrecedence) $
P.prettyPrec arrowPrecedence p1 Doc.<+> P.prettyPrec appPrecedence p2
ProofVar n -> Doc.int n
instance P.Pretty (TcProof s) where
prettyPrec prec p =
case p of
TcProofAbs tvs p' -> P.parensIf (prec > 0) $
Doc.text "Λ" Doc.<> Doc.hsep (map P.pretty tvs) Doc.<> Doc.dot Doc.<+> P.pretty p'
TcProofAp p' tys -> P.parensIf (prec > 0) $
P.prettyPrec arrowPrecedence p' Doc.<+> Doc.text "@" Doc.<+> Doc.hsep (map (P.prettyPrec appPrecedence) tys)
TcProofLam n ty p' -> -- P.parensIf (True) $
Doc.text "λ" Doc.<>
Doc.int n Doc.<> Doc.text "::" Doc.<> P.prettyPrec appPrecedence ty Doc.<>
Doc.dot Doc.<+> P.pretty p'
TcProofSrc ty -> P.prettyPrec prec ty
TcProofPAp p1 p2 -> P.parensIf (prec > arrowPrecedence) $
P.prettyPrec arrowPrecedence p1 Doc.<+> P.prettyPrec appPrecedence p2
TcProofVar n -> Doc.int n
data TcQual s t = TcQual [TcPred s] t
deriving ( Show, Eq, Ord )
data Qualified t = [Predicate] :=> t
deriving ( Show, Eq, Ord, Data, Generic )
data TcPred s = TcIsIn Entity (TcType s)
deriving ( Show, Eq, Ord )
data Predicate = IsIn Entity Type
deriving ( Show, Eq, Ord, Data, Generic )
-- type TcInstance s = TcQual s (TcPred s)
-- type Instance = Qualified Predicate
--data Typed = Typed TcType Origin
data Typed
= Coerced Scope.NameInfo SrcSpanInfo Proof
| Scoped Scope.NameInfo SrcSpanInfo
deriving (Show)
data Pin s = Pin Scope.Origin (STRef s (Maybe (TcProof s)))
instance Show (Pin s) where
show (Pin origin _ref) = show origin
| Lemmih/haskell-tc | src/Language/Haskell/TypeCheck/Types.hs | mit | 9,901 | 0 | 18 | 2,576 | 3,545 | 1,780 | 1,765 | 228 | 9 |
module Tak.Display where
import qualified UI.HSCurses.CursesHelper as CH
import qualified UI.HSCurses.Curses as C
import Prelude
import Control.Monad
import Control.Monad.Writer
import Data.Char (chr, ord)
import Data.Bits ( (.|.) )
import System.Locale.SetLocale
import qualified Data.ByteString as B
import qualified Data.Text as DT
import qualified Data.Text.Encoding as DTE
import Foreign.C.Types (CInt)
import Tak.Types
import Tak.Util (clamp)
import Debug.Trace (trace)
invertPair = 1
withCurses :: IO () -> IO ()
withCurses f = do
setLocale LC_ALL Nothing
CH.start
C.echo False
C.keypad C.stdScr True
C.nl True
C.timeout 200
C.initPair (C.Pair invertPair) CH.black CH.white
(y, x) <- getScreenSize
C.move (y-1) (x-1)
C.move 0 0
C.wAddStr C.stdScr "Loading..."
refresh
f
C.endWin
CH.end
clearScreen = C.wclear C.stdScr
getScreenSize :: IO (Int, Int)
getScreenSize = C.scrSize
refresh = C.refresh
keyCharEvt c
| (ord c) >= 32 = KeyChar c
| otherwise = KeyCtrlChar (chr ((ord c) .|. (2 ^ 6)))
cursesKeyToEvt :: C.Key -> Event
cursesKeyToEvt (C.KeyChar '\n') = KeyEvent KeyEnter
cursesKeyToEvt (C.KeyChar '\DEL') = KeyEvent KeyDel
cursesKeyToEvt (C.KeyChar c) = KeyEvent $ keyCharEvt c
cursesKeyToEvt C.KeyUp = KeyEvent KeyUp
cursesKeyToEvt C.KeyDown = KeyEvent KeyDown
cursesKeyToEvt C.KeyLeft = KeyEvent KeyLeft
cursesKeyToEvt C.KeyRight = KeyEvent KeyRight
cursesKeyToEvt C.KeyEnter = KeyEvent KeyEnter
cursesKeyToEvt C.KeyNPage = KeyEvent KeyPageDown
cursesKeyToEvt C.KeyPPage = KeyEvent KeyPageUp
cursesKeyToEvt C.KeyHome = KeyEvent KeyHome
cursesKeyToEvt C.KeyEnd = KeyEvent KeyEnd
cursesKeyToEvt (C.KeyUnknown 562) = KeyEvent KeyCtrlUp
cursesKeyToEvt (C.KeyUnknown 541) = KeyEvent KeyCtrlLeft
cursesKeyToEvt (C.KeyUnknown 556) = KeyEvent KeyCtrlRight
cursesKeyToEvt (C.KeyUnknown 521) = KeyEvent KeyCtrlDown
cursesKeyToEvt (C.KeyUnknown 531) = KeyEvent KeyCtrlHome
cursesKeyToEvt (C.KeyUnknown 526) = KeyEvent KeyCtrlEnd
cursesKeyToEvt (C.KeyUnknown (-1))= TimeoutEvent
cursesKeyToEvt _ = NoEvent
escape = ord '\ESC'
getNextKey = C.getch
ungetKey = C.ungetCh
decodeEscSeq :: IO Event
decodeEscSeq = do
key1 <- getNextKey
case C.decodeKey key1 of
C.KeyChar c -> return $ KeyEvent $ KeyEscaped $ keyCharEvt c
C.KeyUp -> return $ KeyEvent $ KeyEscaped $ KeyUp
C.KeyDown -> return $ KeyEvent $ KeyEscaped $ KeyDown
C.KeyLeft -> return $ KeyEvent $ KeyEscaped $ KeyLeft
C.KeyRight -> return $ KeyEvent $ KeyEscaped $ KeyRight
otherwise -> do ungetKey key1
return $ KeyEvent $ KeyEscape
waitEvent :: IO Event
waitEvent = let
isValidFirstKey key =
key <= 255
isValidNextKey key =
key >= 128 && key <= 191
nMoreBytes firstKey
| firstKey <= 127 = 0
| firstKey >= 194 && firstKey <= 223 = 1
| firstKey >= 224 && firstKey <= 239 = 2
| firstKey >= 240 && firstKey <= 244 = 3
| otherwise = 0
cIntToBs :: [CInt] -> B.ByteString
cIntToBs l = B.pack $ map (fromIntegral . toInteger) l
decodeKey :: CInt -> IO (C.Key)
decodeKey firstKey =
if isValidFirstKey firstKey
then decodeAfterNMore (nMoreBytes firstKey) [firstKey]
else return $ C.decodeKey firstKey
decodeAfterNMore :: Int -> [CInt] -> IO (C.Key)
decodeAfterNMore nBytes ints =
if nBytes > 0
then do
key <- getNextKey
if isValidNextKey key
then decodeAfterNMore (nBytes - 1) (ints ++ [key])
else decodeKey key
else decodeInts ints
decodeInts :: [CInt] -> IO (C.Key)
decodeInts ints =
let doYourBest = return $ C.decodeKey (ints !! 0)
in case (DTE.decodeUtf8' . cIntToBs) ints of
Right bs -> case DT.unpack bs of
c:_ -> return $ C.KeyChar c
otherwise -> doYourBest
otherwise -> doYourBest
in do
firstKeyCInt <- getNextKey
case (fromIntegral . toInteger) firstKeyCInt == ord '\ESC' of
True -> decodeEscSeq
otherwise ->
do utf8DecodedKey <- decodeKey firstKeyCInt
return $ cursesKeyToEvt utf8DecodedKey
printStr :: Pos -> String -> RenderW ()
printStr p s = RenderW ((), [PrintStr p s])
setCursor :: Pos -> RenderW ()
setCursor p = RenderW ((), [SetCursor p])
regularText :: RenderW ()
regularText = RenderW ((), [SetColorPair 0])
invertText :: RenderW ()
invertText = RenderW ((), [SetColorPair invertPair])
drawToScreen :: Box -> RenderAction -> IO ()
drawToScreen (Box top left height width) command =
let clampLine = clamp top (top + height - 1)
clampRow = clamp left (left + width - 1)
in
case command of
SetColorPair pairId -> C.attrSet C.attr0 (C.Pair pairId)
SetCursor (Pos line row) -> C.move (clampLine (top + line))
(clampRow (left + row))
PrintStr (Pos line row) str -> do
let realLine = line + top
realRow = row + left
realWidth = width - realRow - 1
realStr = take realWidth (str ++ (repeat ' '))
C.move (clampLine realLine) (clampRow realRow)
C.wAddStr C.stdScr realStr
return ()
renderEditor :: Editor a => Box -> a -> IO ()
renderEditor b@(Box _ _ height width) editor =
let (_, commands) = execRender (render editor height width)
in do mapM (drawToScreen b) ([SetColorPair 0] ++ commands)
return ()
| sixohsix/tak | src/Tak/Display.hs | mit | 5,499 | 0 | 19 | 1,375 | 2,001 | 996 | 1,005 | 148 | 7 |
{-# OPTIONS_HADDOCK hide, prune #-}
module Handler.Mooc.ViewProposal
( getViewProposalR
) where
import Import
getViewProposalR :: ScenarioId -> Handler Html
getViewProposalR scId = do
setSafeSession userSessionQuaViewMode "view"
setSafeSession userSessionScenarioId scId
redirect HomeR
| mb21/qua-kit | apps/hs/qua-server/src/Handler/Mooc/ViewProposal.hs | mit | 299 | 0 | 7 | 44 | 58 | 29 | 29 | 9 | 1 |
module Display (display,reshape) where
import Graphics.Rendering.OpenGL
import Util.Util
import MyndState
import MyndNet
calcWidth (MyndNode _ _ w []) = w + 50
calcWidth (MyndNode _ _ w c@(cx:cxs)) = max (sum $ map calcWidth c) w
display :: MyndState -> IO ()
display state1 = do
clearColor $= Color4 1 1 1 1
clear [ColorBuffer, DepthBuffer]
texture Texture2D $= Enabled
blend $= Enabled
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
display' state1 (-250) (250)
texture Texture2D $= Disabled
blend $= Disabled
where
display' state@(MyndState {net=node@(MyndNode _ _ w [])}) x y =
display'' state (x + (fromIntegral $ calcWidth node - w - 50) / 2) y
display' state@(MyndState {delta=angle, net=node@(MyndNode _ _ w c@(cx:cxs))}) x y = do
display'' state (x + (fromIntegral $ calcWidth node - w - 50) / 2) y
display' (state{net=cx}) x (y-100)
mapM_ (\(a, b) -> display' (state{net=b}) (x + (fromIntegral a)) (y-100))
$ zip ((calcWidth cx):(zipWith (+) (map calcWidth c) (map calcWidth cxs))) cxs
display'' state@(MyndState {delta=angle, net=(MyndNode _ tex _ _)}) x y =
preservingMatrix $ do
translate $ Vector3 x y (angle::GLfloat)
textureBinding Texture2D $= tex
color $ Color3 (1::GLfloat) 1 1
plane (256::GLfloat)
reshape :: (Int, Int) -> IO ()
reshape (w, 0) = reshape (w, 1) -- prevent divide by zero
reshape (w, h) = do
viewport $= (Position 0 0, Size width height)
matrixMode $= Projection
loadIdentity
matrixPerspectivePixelPerfect width height 2000 10 (-10)
matrixMode $= Modelview 0
loadIdentity
flush
where width = (2::GLsizei) * fromIntegral (w `div` 2)
height = (2::GLsizei) * fromIntegral (h `div` 2)
-- |width and height defines the 2D space available at z=0, must be the same
-- as the size of the viewport.
-- z_near defines the z position of the near plane, must be greater than 0.
-- z_far defines the z position of the far plane, must be lesser than 0.
-- z_eye defines the position of the viewer, must be greater that z_near.
matrixPerspectivePixelPerfect :: GLsizei -> GLsizei -> GLfloat -> GLfloat -> GLfloat -> IO ()
matrixPerspectivePixelPerfect w h z_eye z_near z_far = do
m <- newMatrix RowMajor [(2 * z_eye) / width, 0, 0, 0
, 0, (2 * z_eye) / height, 0, 0
, 0, 0, ktz - ksz * z_eye, -1
, 0 :: GLfloat, 0, ksz, z_eye]
(matrix (Just Projection) :: StateVar(GLmatrix GLfloat)) $= m
where kdn = z_eye - z_near
kdf = z_eye - z_far
ksz = - (kdf + kdn) / (kdf - kdn)
ktz = - (2 * kdn * kdf) / (kdf - kdn)
width = fromIntegral w
height = fromIntegral h
| andrey013/mynd | src/Display.hs | mit | 2,899 | 0 | 18 | 857 | 1,092 | 579 | 513 | 55 | 2 |
module Game where
import Data.Array.IArray
import Data.Array.IO
import Data.Array.MArray
import Data.Array.Unboxed
import Data.IORef
import Data.List
import Graphics.UI.Gtk hiding (on,get)
import qualified Graphics.UI.Gtk as G
import Numeric.LinearAlgebra ((<>),(><),(|>),(@>),(@@>),Vector,Matrix)
import qualified Numeric.LinearAlgebra as V
import System.Random
import RotButtons
import Types
import Utils
generateField :: IORef GameState -> Index -> IO (Field,Near)
generateField gameStateRef i = do
gameState <- readIORef gameStateRef
let is = getDimensions gameState
g = getGen gameState
nMines = getMinesStart gameState
(g',g'') = split g
cells = range is
mineIs = take nMines $ randPermutation g' $ cells\\(rawAdjacents i)
field <- newArray is 6
mapM_ (flip (writeArray field) 7) mineIs
minesNear <- fmap (array is) $ mapM (\ i -> fmap ((,) i) $ fmap sum $ mapM ((fmap (+(-6))) . readArray field) $ filter (inRange is) $ rawAdjacents i) cells
writeIORef gameStateRef $ gameState { getGen = g'', getField = Just (field, minesNear) }
return (field, minesNear)
randPermutation :: (RandomGen g) => g -> [a] -> [a]
randPermutation g [] = []
randPermutation g xs = z:(randPermutation g' $ ys ++ zs)
where n = length xs
(i,g') = randomR (0,n-1) g
(ys, z:zs) = splitAt i xs
win :: IORef GameState -> IO ()
win r = do
modifyIORef r (\gS -> gS { getOutcome = Just True })
gameState <- readIORef r
widgetQueueDraw (getDrawingArea gameState)
imageSetIcon (getFace gameState) "face-smile-big"
let dialog = getWinDialog gameState
response <- dialogRun dialog
widgetHide dialog
case response of
ResponseYes -> modifyIORef r newGameSame
_ -> mainQuit
lose :: IORef GameState -> IO ()
lose r = do
modifyIORef r (\gS -> gS { getOutcome = Just False})
gameState <- readIORef r
widgetQueueDraw (getDrawingArea gameState)
imageSetIcon (getFace gameState) "face-sad"
let dialog = getLoseDialog gameState
response <- dialogRun dialog
widgetHide dialog
case response of
ResponseYes -> modifyIORef r newGameSame
_ -> mainQuit
newGame :: IORef GameState -> IO ()
newGame r = do
gameState <- readIORef r
let new = getNewGameWindow gameState
[dS,mS,sS] = getSpins gameState
spinButtonSetValue dS (fromIntegral $ getN gameState)
spinButtonSetValue mS (fromIntegral $ getMinesStart gameState)
spinButtonSetValue sS (fromIntegral $ (+1) $ head $ snd $ getDimensions gameState)
widgetShowAll new
playNewGame :: IORef GameState -> IO ()
playNewGame r = do
gameState <- readIORef r
[n,m,k] <- mapM spinButtonGetValueAsInt $ getSpins gameState
let is = (replicate n 0, replicate n (k-1))
widgetHideAll (getNewGameWindow gameState)
writeIORef r $ gameState { getN = n
, getDimensions = is
, getField = Nothing
, getMinesLeft = m
, getMinesStart = m
, getOutcome = Nothing
, getViewPoint = if n==(getN gameState) && is==(getDimensions gameState)
then getViewPoint gameState
else V.optimiseMult $ map (\i -> rotPlane n (i`mod`2) i (pi/12*(fromIntegral $ i`div`2))) [2..(n-1)]
}
refreshButtons r
widgetQueueDraw (getDrawingArea gameState)
newGameSame :: GameState -> GameState
newGameSame gameState = gameState { getField = Nothing, getMinesLeft = getMinesStart gameState, getOutcome = Nothing }
| benjaminjkraft/nmines | Game.hs | mit | 3,613 | 0 | 22 | 913 | 1,304 | 668 | 636 | 87 | 2 |
module Main
where
import Data.Monoid (mempty)
import Test.Framework.Options (TestOptions, TestOptions'(..))
import Test.Framework.Runners.Options (RunnerOptions, RunnerOptions'(..))
import Test.Framework (Test, defaultMainWithOpts)
import qualified UntypedLambdaTests
main :: IO ()
main = do
let emptyTestOpts = mempty :: TestOptions
let testOpts = emptyTestOpts { topt_maximum_generated_tests = Just 100 }
let emptyRunnerOpts = mempty :: RunnerOptions
let runnerOpts = emptyRunnerOpts { ropt_test_options = Just testOpts }
defaultMainWithOpts tests runnerOpts
tests :: [Test]
tests = UntypedLambdaTests.allTests
| mmakowski/ambc | test/Test.hs | mit | 629 | 1 | 12 | 85 | 168 | 97 | 71 | 15 | 1 |
{-# LANGUAGE DeriveFunctor, GeneralizedNewtypeDeriving #-}
module Lisp.Runtime (eval, evalSeq, reduce) where
import Prelude hiding (lookup)
import Control.Monad.State
import Control.Applicative
import Lisp.Spefication
import Data.SyntaxIR
import Data.Maybe
import qualified Data.Map as M
type Eval a = State Environment a
-- evaluates the abstract syntax tree &
-- applies any top level changes to the
-- runtime environment.
eval :: AST -> Eval AST
eval ast = do
env <- get
if isStateful ast
then case ast of
Def ref def -> define ref (reduce env def)
_ -> return ()
else return ()
return $ reduce env ast
-- Evaluates an series of expressions
evalSeq :: [AST] -> Eval AST
evalSeq [] = return $ invokeEmptyExpr
evalSeq (expr:[]) = eval expr
evalSeq (expr:rest) = eval expr >> evalSeq rest
-- consider it a stateless version of eval
reduce :: Environment -> AST -> AST
reduce env ast = case ast of
Compound [] -> invokeEmptyExpr
Compound (f:args) -> case (reduce env f) of
Func fn -> invoke env fn evalArgs
other -> notInvokable other
where
evalArgs = map (reduce env) args
Ref ref -> case (lookup ref env) of
Just ast -> ast
Nothing -> outOfScope ref
IfExpr pred cons altv -> case (reduce env pred) of
Boolean True -> reduce env cons
Boolean False -> reduce env altv
_ -> boolError
-- makes closure
Func (LangFn ps body) -> Func (ClojFn env ps body)
_ -> ast
-- derefences a reference
lookup _ [] = Nothing
lookup ref (inner : outer) =
case M.lookup ref inner of
Nothing -> lookup ref outer
result -> result
define :: String -> AST -> Eval ()
define ref ast = do
memeber <- hasInCurrent ref
if not memeber
then insert ref ast
else fail $ ref ++ " already defined."
hasInCurrent :: String -> Eval Bool
hasInCurrent ref = do
env <- get
let val = M.lookup ref (head env)
return $ isJust val
insert :: String -> AST -> Eval ()
insert ref ast = do
env <- get
case env of
[] -> fail $ "You defined "++ref++" in empty scope"
head:tail -> do
put $ (M.insert ref ast head):tail
isStateful (Def _ _) = True
isStateful _ = False
-- # Function behavior
-- handles all the evaluation before apply the arguments
invoke :: Environment -> Function -> [AST] -> AST
invoke env f args = result
where
evals = fmap (apply env f) . lookForErr . fmap (reduce env)
result = case evals args of
Left err -> err
Right ans -> ans
-- looks for error in function arguments
lookForErr :: [AST] -> Either AST [AST]
lookForErr args = impl args
where impl (Err str:_) = Left (Err str)
impl [] = Right args
impl (_:xs) = impl xs
apply :: Environment -> Function -> [AST] -> AST
apply _ (NatvFn func _) args = func args
apply env fn args
| sameLength = evalSeq body `evalState` newEnviron
| otherwise = diffNumOfArgParamErr
where params = case fn of { (LangFn p _) -> p; (ClojFn _ p _) -> p }
body = case fn of { (LangFn _ b) -> b; (ClojFn _ _ b) -> b }
sameLength = (length args) == (length params)
localScope = (M.fromList $ zip params args)
newEnviron = case fn of
(ClojFn cenv _ _) -> (localScope: cenv ++ env)
_ -> (localScope: env)
| AKST/lisp.hs | src/Lisp/Runtime.hs | mit | 3,502 | 0 | 16 | 1,061 | 1,239 | 624 | 615 | 87 | 10 |
{-# LANGUAGE OverloadedStrings #-}
module Esthree.Parser where
import Data.Attoparsec.Text
import Control.Applicative
import Esthree.Types
import Aws.S3
s3Command :: Parser S3Command
s3Command = listBucketsCmd <|>
listBucketCmd <|>
putBucketCmd <|>
helpCmd <|>
quitCmd <|>
unknownCmd
putBucketCmd :: Parser S3Command
putBucketCmd = do
_ <- string "putBucket" <|> string "pb"
skipSpace
name <- takeWhile1 (/= ' ')
skipSpace
loc <- location
return $ S3PutBucket name loc
location :: Parser LocationConstraint
location = west <|>
west2 <|>
eu <|>
southeast <|>
southeast2 <|>
northeast <|>
classic
where classic = return ""
west = "us-west-1"
west2 = "us-west-2"
eu = "EU"
southeast = "ap-southeast-1"
southeast2 = "ap-southeast-2"
northeast = "ap-northeast-1"
listBucketsCmd :: Parser S3Command
listBucketsCmd = S3ListBuckets <$ (string "listBuckets" <|> string "lbs")
listBucketCmd :: Parser S3Command
listBucketCmd = do
_ <- string "listBucket" <|> string "lb"
b <- takeText
return $ S3ListBucket b
helpCmd :: Parser S3Command
helpCmd = S3Help <$ (string "help" <|> string "?")
unknownCmd :: Parser S3Command
unknownCmd = S3Unknown <$> takeText
quitCmd :: Parser S3Command
quitCmd = S3Quit <$ (string "quit" <|> string "q")
| schell/esthree | Esthree/Parser.hs | mit | 1,499 | 0 | 10 | 448 | 361 | 183 | 178 | 49 | 1 |
-- Warm-up and review
-- 1
stops = "pbtdkg"
vowels = "aeiou"
-- a)
tuples = [ (a, b, c) | a <- stops, b <- vowels, c <- stops ]
-- b)
tuplesP = [ (a, b, c) | a <- stops, b <- vowels, c <- stops, a == 'p' ]
-- c)
nouns = ["balance", "farm", "coal", "fall", "chin", "fire"]
verbs = ["yell", "pull", "admire", "learn", "visit", "plant"]
sentence = [ (a, b, c) | a <- nouns, b <- verbs, c <- nouns ]
-- 2
-- Calculate average word length in string
seekritFunc :: String -> Int
seekritFunc x =
div (sum (map length (words x)))
(length (words x))
seekritFunc' :: Fractional a => String -> a
seekritFunc' x =
fromIntegral (sum (map length (words x)))
/ fromIntegral (length (words x))
-- Rewriting functions using folds
-- 1
myOr :: [Bool] -> Bool
myOr = foldr (||) False
-- 2
myAny :: (a -> Bool) -> [a] -> Bool
myAny f = foldr (\a b -> if f a then True else b) False
-- 3
myElem :: Eq a => a -> [a] -> Bool
myElem x = foldr (\a b -> if a == x then True else b) False
myElem' :: Eq a => a -> [a] -> Bool
myElem' x = any (== x)
-- 4
myReverse :: [a] -> [a]
myReverse = foldl (flip (:)) []
-- 5
myMap :: (a -> b) -> [a] -> [b]
myMap f = foldr (\a b -> f a : b) []
-- 6
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f = foldr (\a b -> if f a then a : b else b) []
-- 7
squish :: [[a]] -> [a]
squish = foldr (++) []
-- 8
squishMap :: (a -> [b]) -> [a] -> [b]
squishMap f = foldr (\a b -> f a ++ b) []
-- 9
squishAgain :: [[a]] -> [a]
squishAgain = squishMap id
-- 10
myMaximumBy :: (a -> a -> Ordering)
-> [a]
-> a
myMaximumBy f xs = foldr (\a b -> if f a b == GT then a else b) (last xs) xs
-- 11
myMinimumBy :: (a -> a -> Ordering)
-> [a]
-> a
myMinimumBy f xs = foldr (\a b -> if f a b == LT then a else b) (last xs) xs
| ashnikel/haskellbook | ch10/ch10.10_ex.hs | mit | 1,785 | 0 | 12 | 472 | 936 | 519 | 417 | 43 | 2 |
{-# LANGUAGE ConstraintKinds #-}
module GHCJS.DOM.EventM
(
EventM(..)
, SaferEventListener(..)
, EventName
, newListener
, newListenerSync
, newListenerAsync
, addListener
, removeListener
, releaseListener
, on
, event
, eventTarget
, target
, eventCurrentTarget
, eventPhase
, bubbles
, cancelable
, timeStamp
, stopPropagation
, preventDefault
, defaultPrevented
, stopImmediatePropagation
, srcElement
, getCancelBubble
, cancelBubble
, getReturnValue
, returnValue
, uiView
, uiDetail
, uiKeyCode
, uiCharCode
, uiLayerX
, uiLayerY
, uiLayerXY
, uiPageX
, uiPageY
, uiPageXY
, uiWhich
, mouseScreenX
, mouseScreenY
, mouseScreenXY
, mouseClientX
, mouseClientY
, mouseClientXY
, mouseMovementX
, mouseMovementY
, mouseMovementXY
, mouseCtrlKey
, mouseShiftKey
, mouseAltKey
, mouseMetaKey
, mouseButton
, mouseRelatedTarget
, mouseOffsetX
, mouseOffsetY
, mouseOffsetXY
, mouseX
, mouseY
, mouseXY
, mouseFromElement
, mouseToElement
)
where
import Control.Applicative ((<$>))
import Control.Monad.Trans.Reader (ReaderT, ask, runReaderT)
import Control.Monad.IO.Class (MonadIO(..))
import GHCJS.DOM.Types
import qualified GHCJS.DOM.JSFFI.Generated.Event as Event
import qualified GHCJS.DOM.JSFFI.Generated.UIEvent as UIEvent
import qualified GHCJS.DOM.JSFFI.Generated.MouseEvent as MouseEvent
import GHCJS.DOM.JSFFI.Generated.EventTarget
import GHCJS.DOM.EventTargetClosures
import Data.Word (Word)
import Data.Foldable (forM_)
type EventM t e = ReaderT e IO
newListener :: (IsEvent e) => EventM t e () -> IO (SaferEventListener t e)
newListener f = SaferEventListener <$> eventListenerNew (runReaderT f)
newListenerSync :: (IsEvent e) => EventM t e () -> IO (SaferEventListener t e)
newListenerSync f = SaferEventListener <$> eventListenerNewSync (runReaderT f)
newListenerAsync :: (IsEvent e) => EventM t e () -> IO (SaferEventListener t e)
newListenerAsync f = SaferEventListener <$> eventListenerNewAsync (runReaderT f)
addListener :: (IsEventTarget t, IsEvent e) => t -> EventName t e -> SaferEventListener t e -> Bool -> IO ()
addListener target (EventName eventName) (SaferEventListener l) useCapture =
addEventListener target eventName (Just l) useCapture
removeListener :: (IsEventTarget t, IsEvent e) => t -> EventName t e -> SaferEventListener t e -> Bool -> IO ()
removeListener target (EventName eventName) (SaferEventListener l) useCapture =
removeEventListener target eventName (Just l) useCapture
releaseListener :: (IsEventTarget t, IsEvent e) => SaferEventListener t e -> IO ()
releaseListener (SaferEventListener l) = eventListenerRelease l
on :: (IsEventTarget t, IsEvent e) => t -> EventName t e -> EventM t e () -> IO (IO ())
on target eventName callback = do
l <- newListener callback
addListener target eventName l False
return (removeListener target eventName l False >> releaseListener l)
onThese :: (IsEventTarget t, IsEvent e) => [(t, EventName t e)] -> EventM t e () -> IO (IO ())
onThese targetsAndEventNames callback = do
l <- newListener callback
forM_ targetsAndEventNames $ \(target, eventName) ->
addListener target eventName l False
return (do
forM_ targetsAndEventNames (\(target, eventName) ->
removeListener target eventName l False)
releaseListener l)
event :: EventM t e e
event = ask
eventTarget :: IsEvent e => EventM t e (Maybe EventTarget)
eventTarget = event >>= Event.getTarget
target :: (IsEvent e, IsGObject t) => EventM t e (Maybe t)
target = (fmap (unsafeCastGObject . toGObject)) <$> eventTarget
eventCurrentTarget :: IsEvent e => EventM t e (Maybe EventTarget)
eventCurrentTarget = event >>= Event.getCurrentTarget
eventPhase :: IsEvent e => EventM t e Word
eventPhase = event >>= Event.getEventPhase
bubbles :: IsEvent e => EventM t e Bool
bubbles = event >>= Event.getBubbles
cancelable :: IsEvent e => EventM t e Bool
cancelable = event >>= Event.getCancelable
timeStamp :: IsEvent e => EventM t e Word
timeStamp = event >>= Event.getTimeStamp
stopPropagation :: IsEvent e => EventM t e ()
stopPropagation = event >>= Event.stopPropagation
preventDefault :: IsEvent e => EventM t e ()
preventDefault = event >>= Event.preventDefault
defaultPrevented :: IsEvent e => EventM t e Bool
defaultPrevented = event >>= Event.getDefaultPrevented
stopImmediatePropagation :: IsEvent e => EventM t e ()
stopImmediatePropagation = event >>= Event.stopImmediatePropagation
srcElement :: IsEvent e => EventM t e (Maybe EventTarget)
srcElement = event >>= Event.getSrcElement
getCancelBubble :: IsEvent e => EventM t e Bool
getCancelBubble = event >>= Event.getCancelBubble
cancelBubble :: IsEvent e => Bool -> EventM t e ()
cancelBubble f = event >>= flip Event.setCancelBubble f
getReturnValue :: IsEvent e => EventM t e Bool
getReturnValue = event >>= Event.getReturnValue
returnValue :: IsEvent e => Bool -> EventM t e ()
returnValue f = event >>= flip Event.setReturnValue f
uiView :: IsUIEvent e => EventM t e (Maybe Window)
uiView = event >>= UIEvent.getView
uiDetail :: IsUIEvent e => EventM t e Int
uiDetail = event >>= UIEvent.getDetail
uiKeyCode :: IsUIEvent e => EventM t e Int
uiKeyCode = event >>= UIEvent.getKeyCode
uiCharCode :: IsUIEvent e => EventM t e Int
uiCharCode = event >>= UIEvent.getCharCode
uiLayerX :: IsUIEvent e => EventM t e Int
uiLayerX = event >>= UIEvent.getLayerX
uiLayerY :: IsUIEvent e => EventM t e Int
uiLayerY = event >>= UIEvent.getLayerY
uiLayerXY :: IsUIEvent e => EventM t e (Int, Int)
uiLayerXY = do
e <- event
x <- UIEvent.getLayerX e
y <- UIEvent.getLayerY e
return (x, y)
uiPageX :: IsUIEvent e => EventM t e Int
uiPageX = event >>= UIEvent.getPageX
uiPageY :: IsUIEvent e => EventM t e Int
uiPageY = event >>= UIEvent.getPageY
uiPageXY :: IsUIEvent e => EventM t e (Int, Int)
uiPageXY = do
e <- event
x <- UIEvent.getPageX e
y <- UIEvent.getPageY e
return (x, y)
uiWhich :: IsUIEvent e => EventM t e Int
uiWhich = event >>= UIEvent.getWhich
mouseScreenX :: IsMouseEvent e => EventM t e Int
mouseScreenX = event >>= MouseEvent.getScreenX
mouseScreenY :: IsMouseEvent e => EventM t e Int
mouseScreenY = event >>= MouseEvent.getScreenY
mouseScreenXY :: IsMouseEvent e => EventM t e (Int, Int)
mouseScreenXY = do
e <- event
x <- MouseEvent.getScreenX e
y <- MouseEvent.getScreenY e
return (x, y)
mouseClientX :: IsMouseEvent e => EventM t e Int
mouseClientX = event >>= MouseEvent.getClientX
mouseClientY :: IsMouseEvent e => EventM t e Int
mouseClientY = event >>= MouseEvent.getClientY
mouseClientXY :: IsMouseEvent e => EventM t e (Int, Int)
mouseClientXY = do
e <- event
x <- MouseEvent.getClientX e
y <- MouseEvent.getClientY e
return (x, y)
mouseMovementX :: IsMouseEvent e => EventM t e Int
mouseMovementX = event >>= MouseEvent.getMovementX
mouseMovementY :: IsMouseEvent e => EventM t e Int
mouseMovementY = event >>= MouseEvent.getMovementY
mouseMovementXY :: IsMouseEvent e => EventM t e (Int, Int)
mouseMovementXY = do
e <- event
x <- MouseEvent.getMovementX e
y <- MouseEvent.getMovementY e
return (x, y)
mouseCtrlKey :: IsMouseEvent e => EventM t e Bool
mouseCtrlKey = event >>= MouseEvent.getCtrlKey
mouseShiftKey :: IsMouseEvent e => EventM t e Bool
mouseShiftKey = event >>= MouseEvent.getShiftKey
mouseAltKey :: IsMouseEvent e => EventM t e Bool
mouseAltKey = event >>= MouseEvent.getAltKey
mouseMetaKey :: IsMouseEvent e => EventM t e Bool
mouseMetaKey = event >>= MouseEvent.getMetaKey
mouseButton :: IsMouseEvent e => EventM t e Word
mouseButton = event >>= MouseEvent.getButton
mouseRelatedTarget :: IsMouseEvent e => EventM t e (Maybe EventTarget)
mouseRelatedTarget = event >>= MouseEvent.getRelatedTarget
mouseOffsetX :: IsMouseEvent e => EventM t e Int
mouseOffsetX = event >>= MouseEvent.getOffsetX
mouseOffsetY :: IsMouseEvent e => EventM t e Int
mouseOffsetY = event >>= MouseEvent.getOffsetY
mouseOffsetXY :: IsMouseEvent e => EventM t e (Int, Int)
mouseOffsetXY = do
e <- event
x <- MouseEvent.getOffsetX e
y <- MouseEvent.getOffsetY e
return (x, y)
mouseX :: IsMouseEvent e => EventM t e Int
mouseX = event >>= MouseEvent.getX
mouseY :: IsMouseEvent e => EventM t e Int
mouseY = event >>= MouseEvent.getY
mouseXY :: IsMouseEvent e => EventM t e (Int, Int)
mouseXY = do
e <- event
x <- MouseEvent.getX e
y <- MouseEvent.getY e
return (x, y)
mouseFromElement :: IsMouseEvent e => EventM t e (Maybe Node)
mouseFromElement = event >>= MouseEvent.getFromElement
mouseToElement :: IsMouseEvent e => EventM t e (Maybe Node)
mouseToElement = event >>= MouseEvent.getToElement
| manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/EventM.hs | mit | 8,714 | 0 | 14 | 1,576 | 2,938 | 1,510 | 1,428 | 234 | 1 |
{- Chapter 14 :: Monads and more -}
import Data.Monoid -- importing this will cause an "Ambiguous
-- occurrence" error with our user defined ‘Sum’ type
import Data.Foldable
{-
class Monoid a where
mempty :: a
mppend :: a -> a -> a
mconcat :: [a] -> a
mconcat = foldr mappend mempty
-------------------------------------------------------
Monoids are required to satisfy the following identity and associativity laws:
mempty 'mappend' x = x
x 'mappend' mempty = x
x 'mappend' (y 'mappend' z) = (x 'mappend' y) 'mappend' z
-------------------------------------------------------
instance Monoid [a] where
-- mempty :: [a]
mempty = []
-- mappend :: [a] -> [a] -> [a]
mappend = (++)
instance Monoid a => Monoid (Maybe a) where
-- mempty :: Maybe a
mempty = Nothing
-- mappend :: Maybe a -> Maybe a -> Maybe a
Nothing `mappend` my = my
mx `mappend` Nothing = mx
Just x `mappend` Just y = Just (x `mappend` y)
-------------------------------------------------------
User defined:
instance Monoid Int where
-- mempty :: Int
mempty = 0
-- mappend :: Int -> Int -> Int
mappend = (+)
newtype Sum a = Sum a
deriving (Eq, Ord, Show, Read)
instance Monoid Int where
-- mempty :: Int
mempty = 1
-- mempty :: Int -> Int -> Int
mappend = (*)
-------------------------------------------------------
getSum :: Sum a -> a
getSum (Sum x) = x
instance Num a => Monoid (Sum a) where
-- mempty :: Sum a
mempty = Sum 0
-- mappend :: Sum a -> Sum a -> Sum a
Sum x `mappend` Sum y = Sum (x+y)
> mconcat [Sum 2, Sum 3, Sum 4]
Sum 9
> Sum 0
Sum 0
> Sum 0.0
Sum 0.0
> Sum (-1.5)
Sum (-1.5)
-------------------------------------------------------
newtype Product a = Product a
deriving (Eq, Ord, Show, Read)
getProduct :: Product a -> a
getProduct (Product x) = x
instance Num a => Monoid (Product a) where
-- mempty :: Product a
mempty = Product 1
-- mappend :: Product a -> Product a -> Product a
Product x `mappend` Product y = Product (x*y)
> mconcat [Product 2, Product 3, Product 4]
> mconcat [All True, All True, All True]
All {getAll = True}
> mconcat [Any False, Any False, Any False]
Any {getAny = False}
> mconcat [Any False, Any False, Any True]
Any {getAny = True}
> mconcat [All True, All True, All False]
All {getAll = False}
-}
-- fold :: Monoid a => [a] -> a
-- fold [] = mempty
-- fold (x:xs) = x `mappend` fold xs
{-
> fold [Sum 2, Sum 3, Sum 4]
Sum {getSum = 9}
> fold [Product 2, Product 3, Product 4]
Product {getProduct = 24}
> fold [All True, All True, All True]
All {getAll = True}
-}
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving Show
fold' :: Monoid a => Tree a -> a
fold' (Leaf x) = x
fold' (Node l r) = fold' l `mappend` fold' r
{-
> fold' $ Node (Leaf (Sum 3)) (Leaf (Sum 5))
Sum {getSum = 8}
-------------------------------------------------------
class Foldable t where
fold :: Monoid a => t a -> a
foldMap :: Monoid b => (a -> b) -> t a -> b
foldr :: (a -> b -> b) => b -> t a -> b
foldl :: (a -> b -> a) -> a -> t b -> a
instance Foldable [] where
-- fold :: Monoid a -> [a] -> a
fold [] = mempty
fold (x:xs) = x `mappend` fold xs
-- foldMap :: Monoid b => (a -> b) -> [a] -> b
foldMap _ [] = mempty
foldMap f (x:xs) = f x `mappend` foldMap f xs
-- foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ v [] = v
foldr f v (x:xs) = f x (foldr f v xs)
-- foldr :: (a -> b -> a) -> a -> [b] -> a
foldl _ v [] = v
foldl f v (x:xs) = foldl f (f v x) xs
> getSum (foldMap Sum [1..10])
55
> getProduct (foldMap Product [1..10])
3628800
-}
instance Foldable Tree where
-- fold :: Monoid a => Tree a -> a
fold (Leaf x) = x
fold (Node l r) = fold l `mappend` fold r
-- foldMap :: Monoid b => (a -> b) -> Tree a -> b
foldMap f (Leaf x) = f x
foldMap f (Node l r) = foldMap f l `mappend` foldMap f r
-- foldr :: (a -> b -> b) -> b -> Tree a -> b
foldr f v (Leaf x) = f x v
foldr f v (Node l r) = foldr f (foldr f v r) l
-- foldl :: (a -> b -> a) -> a -> Tree b -> a
foldl f v (Leaf x) = f v x
foldl f v (Node l r) = foldl f (foldl f v l) r
tree :: Tree Int
tree = Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)
{-
> foldr (+) 0 tree
6
> foldl (+) 0 tree
6
-------------------------------------------------------
The Foldable class includes:
null :: t a -> Bool
length :: t a -> Int
elem :: Eq a => a -> t a -> Bool
maximum :: Ord a => t a -> a
minimum :: Ord a => t a -> a
sum :: Num a => t a -> a
product :: Num a => t a -> a
> null []
True
> null (Leaf 1)
False
> length [1..10]
10
> length (Node (Leaf 'a') (Leaf 'b'))
2
Also versions of foldr and foldl for structures that
contain at least one element, and hence do not require
a starting value:
foldr1 :: (a -> a -> a) -> t a -> a
foldl1 :: (a -> a -> a) -> t a -> a
> foldr1 (+) [1..10]
55
> foldl1 (+) [1..10]
55
> foldl1 (+) (Node (Leaf 1) (Leaf 2))
3
The final primitive in the class flattens a data structure
to a list:
toList :: t a -> [a]
> toList (Node (Leaf 1) (Leaf 2))
[1,2]
-------------------------------------------------------
In fact, the function toList plays a special role in the
declaration of the Foldable class, as it can be used to
provide default definitions for most of the other
primitives in the class in terms of the corresponding
primitives for lists. In particular, we have the following
collection of default definitions:
foldr f v = foldr f v . toList
foldl f v = foldl f v . toList
foldr1 f = foldr1 f . toList
foldl1 f = foldl1 f . toList
null = null . toList
length = length . toList
elem x = elem x . toList
maximum = maximum . toList
minimum = minimum . toList
sum = sum . toList
product = product . toList
For example, the definition null = null . toList states
that we can decide if a data structure is empty by first
flattening the structure to a list, and then checking if
this list is empty using the instance of null for lists.
The final three default definitions in the foldable class
establish importand relationships between the primitives
fold, foldMap and toList:
fold = foldMap id
foldMap f = foldr (mappend . f) mempty
toList = foldMap (\x -> [x])
------------------ Generic Functions ------------------
-}
average :: [Int] -> Int
average ns = sum ns `div` length ns
average' :: Foldable t => t Int -> Int
average' ns = sum ns `div` length ns
{-
average' can be applied to both lists and trees
> average' [1..10]
5
> average' (Node (Leaf 1) (Leaf 3))
2
-------------------------------------------------------
and :: Foldable t => t Bool -> Bool
and = getAll . foldMap All
or :: Foldable t => t Bool -> Bool
or = getAny . foldMap Any
all :: Foldable t => (a -> Bool) -> t a -> Bool
all p = getAll . foldMap (All . p)
any :: Foldable t => (a -> Bool) -> t a -> Bool
any p = getAny . foldMap (Any . p)
> and (Node (Leaf True) (Leaf False))
False
> and [True,False,True]
False
> or (Node (Leaf True) (Leaf False))
True
> all even [1,2,3]
False
> any even (Node (Leaf 1) (Leaf 2))
True
-------------------------------------------------------
As a final example, the function concat :: [[a]] -> [a]
that concatenates a list of lists can now be generalised
to any foldable type whose elements are lists by simply
folding the elements using the list Monoid:
concat :: Foldable t => t [a] -> [a]
concat = fold
> concat ["ab", "cd", "ef"]
"abcdef"
> concat (Node (Leaf [1,2]) (Leaf [3]))
[1,2,3]
------------------ Traversables -----------------------
class Functor f where
fmap :: (a -> b) -> f a -> f b
map :: (a -> b) -> [a] -> [b]
map g [] = []
map g (x:xs) = g x : map g xs
traverse :: (a -> Maybe b) -> [a] -> Maybe [b]
traverse g [] = pure []
traverse g (x:xs) = pure (:) <*> g x <*> traverse g xs
-}
-- traverse' :: (a -> Maybe b) -> [a] -> Maybe [b]
-- traverse' g [] = pure []
-- traverse' g (x:xs) = pure (:) <*> g x <*> traverse' g xs
dec :: Int -> Maybe Int
dec n = if n > 0 then Just (n-1) else Nothing
{-
> dec 10
Just 9
> traverse' dec [1,2,3]
Just [0,1,2]
> traverse' dec [2,1,0]
Nothing
-------------------------------------------------------
class (Functor t, Foldable t) => Traversable t where
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
instance Traversable [] where
-- traverse :: Applicative f => (a -> f b) -> [a] -> f [b]
traverse g [] = pure []
traverse g (x:xs) = pure (:) <*> g x <*> traverse g xs
instance Traversable Tree where
-- traverse :: Applicative f => (a -> f b) -> Tree a -> f (Tree b)
traverse g (Leaf x) = pure Leaf <*> g x
traverse g (Node l r) = pure Node <*> traverse g l <*> traverse g r
-}
instance Functor Tree where
-- fmap :: (a -> b) -> Tree a -> Tree b
fmap g (Leaf x) = Leaf (g x)
fmap g (Node l r) = Node (fmap g l) (fmap g r)
instance Traversable Tree where
-- traverse :: Applicative f => (a -> f b) -> Tree a -> f (Tree b)
traverse g (Leaf x) = pure Leaf <*> g x
traverse g (Node l r) = pure Node <*> traverse g l <*> traverse g r
{-
> traverse dec [1,2,3]
Just [0,1,2]
> traverse dec [2,1,0]
Nothing
> traverse dec (Node (Leaf 1) (Leaf 2))
Just (Node (Leaf 0) (Leaf 1))
> traverse dec (Node (Leaf 0) (Leaf 1))
Nothing
-------------------------------------------------------
sequenceA :: Applicative f => t (f a) -> f (t a)
sequenceA = traverse id
The type expresses that sequenceA transform a data structure whose
elements are applicative actions into a single such action that returns
a data structure... For example, sequenceA can be used to transform
a data structure whose elements may fail into a data structure that
may fail.
> sequenceA [Just 1, Just 2, Just 3]
Just [1,2,3]
> sequenceA [Just 1, Nothing, Just 3]
Nothing
> sequenceA (Node (Leaf (Just 1)) (Leaf (Just 2)))
Just (Node (Leaf 1) (Leaf 2))
> sequenceA (Node (Leaf (Just 1)) (Leaf Nothing))
Nothing
-- traverse :: Applicaative f => (a -> f b) -> t a -> f (t b)
traverse g = sequenceA . fmap g
-}
| rad1al/hutton_exercises | notes_ch14.hs | gpl-2.0 | 10,213 | 0 | 9 | 2,568 | 651 | 334 | 317 | 30 | 2 |
{-# LANGUAGE OverloadedStrings, CPP #-}
module Bot.Config
( loadConfig
) where
import Bot.Types
import Data.Configurator
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>), (<*>))
#endif
loadConfig :: IO Config
loadConfig = do
f <- load [ Required "/etc/h4h-bot.cfg" ]
Config <$> require f "bot.token"
<*> require f "access.group"
<*> require f "access.door"
<*> require f "access.gate"
<*> require f "message.timeout"
| house4hack/h4h-bot | src/Bot/Config.hs | gpl-3.0 | 476 | 0 | 12 | 103 | 118 | 63 | 55 | 14 | 1 |
module Language.SMTLib2.Composite.Domains where
import Language.SMTLib2 hiding (select,store)
import Language.SMTLib2.Composite.Class
import Language.SMTLib2.Internals.Type.Nat
import Language.SMTLib2.Internals.Type (bvPred,bvSucc,bvAdd,bvSub,bvMul,bvNegate,bvDiv,bvMod,bvMinValue,bvMaxValue,bwSize,BitWidth(..),withBW)
import Language.SMTLib2.Internals.Embed
import Data.List (sortBy,sort)
import Data.Ord (comparing)
import Data.Functor.Identity
import Data.GADT.Compare
import Data.GADT.Show
import Data.Foldable
import Data.Maybe (catMaybes)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Either (partitionEithers)
import Text.Show
import qualified GHC.TypeLits as TL
class Composite c => IsSingleton c where
type SingletonType c :: Type
getSingleton :: (Embed m e,Monad m) => c e -> m (e (SingletonType c))
compositeFromValue :: (Embed m e,Monad m) => Value (SingletonType c) -> m (c e)
class IsSingleton c => ToSingleton c where
toSingleton :: Embed m e => e (SingletonType c) -> m (c e)
class IsSingleton c => IsConstant c where
getConstant :: c e -> Maybe (Value (SingletonType c))
getConstant _ = Nothing
class IsSingleton c => IsRanged c where
getRange :: (Embed m e,Monad m,GetType e) => c e -> m (Range (SingletonType c))
getRange x = do
x' <- getSingleton x
tp <- embedTypeOf
return $ fullRange (tp x')
class (Composite c) => IsNumeric c where
compositeFromInteger :: Integer -> c Repr -> Maybe (c Value)
compositeToInteger :: c Value -> Integer
compositePlus :: (Embed m e,Monad m)
=> c e -> c e -> m (Maybe (c e))
compositeMinus :: (Embed m e,Monad m)
=> c e -> c e -> m (Maybe (c e))
compositeSum :: (Embed m e,Monad m)
=> [c e] -> m (Maybe (c e))
compositeSum (x:xs) = sum' x xs
where
sum' cur [] = return $ Just cur
sum' cur (x:xs) = do
ncur <- compositePlus cur x
case ncur of
Nothing -> return Nothing
Just ncur' -> sum' ncur' xs
compositeNegate :: (Embed m e,Monad m)
=> c e -> m (Maybe (c e))
--compositeNegate x = do
-- zero <- compositeFromValue (fromInteger 0)
-- compositeMinus zero x
compositeMult :: (Embed m e,Monad m)
=> c e -> c e -> m (Maybe (c e))
compositeGEQ :: (Embed m e,Monad m)
=> c e -> c e -> m (Maybe (e BoolType))
compositeDiv :: (Embed m e,Monad m)
=> c e -> c e -> m (Maybe (c e))
compositeMod :: (Embed m e,Monad m)
=> c e -> c e -> m (Maybe (c e))
class (IsSingleton c,IsNumeric c,Integral (Value (SingletonType c))) => IsNumSingleton c
class (Composite c,Composite (ElementType c)) => Wrapper c where
type ElementType c :: (Type -> *) -> *
elementType :: c Repr -> ElementType c Repr
class (Wrapper arr,Composite idx) => IsArray arr idx where
newArray :: (Embed m e,Monad m,GetType e)
=> idx Repr -> ElementType arr e -> m (arr e)
select :: (Embed m e,Monad m,GetType e,GCompare e)
=> arr e -> idx e -> m (Maybe (ElementType arr e))
store :: (Embed m e,Monad m,GetType e,GCompare e)
=> arr e -> idx e -> ElementType arr e -> m (Maybe (arr e))
-- | Store an element only if a condition is true
storeCond :: (Embed m e,Monad m,GetType e,GCompare e) => arr e -> e BoolType -> idx e -> ElementType arr e -> m (Maybe (arr e))
storeCond arr cond idx el = do
narr <- store arr idx el
case narr of
Nothing -> return Nothing
Just narr' -> compITE cond narr' arr
indexType :: GetType e => arr e -> idx Repr
data ErrorCondition e
= NoError
| SometimesError (e BoolType)
| AlwaysError
class Wrapper arr => IsStaticBounded arr where
checkStaticIndex :: (Embed m e,Monad m,GetType e)
=> arr e -> Integer -> m (ErrorCondition e)
class (IsArray arr idx) => IsBounded arr idx where
checkIndex :: (Embed m e,Monad m,GetType e)
=> arr e -> idx e -> m (ErrorCondition e)
arraySize :: (Embed m e,Monad m) => arr e -> m (idx e)
class (Composite c,IsNumeric idx) => ByteWidth c idx where
byteWidth :: (Embed m e,Monad m,GetType e) => c e -> idx Repr -> m (idx e)
class StaticByteWidth (c :: (Type -> *) -> *) where
staticByteWidth :: c e -> Integer
data ByteRead a e
= ByteRead { overreads :: Map Integer (a e,e BoolType) -- ^ Maps remaining bytes to incomplete reads
, readOutside :: Maybe (e BoolType)
, fullRead :: Maybe (a e)
, readImprecision :: Maybe (e BoolType) }
data ByteWrite a b e
= ByteWrite { overwrite :: [(b e,e BoolType)]
, writeOutside :: Maybe (e BoolType)
, fullWrite :: Maybe (a e)
, writeImprecision :: Maybe (e BoolType) }
class (ByteWidth c idx,ByteWidth el idx) => ByteAccess c idx el where
byteRead :: (Embed m e,Monad m,GetType e,GCompare e)
=> c e
-> idx e
-> Integer
-> m (ByteRead el e)
byteWrite :: (Embed m e,Monad m,GetType e,GCompare e)
=> c e
-> idx e
-> el e
-> m (ByteWrite c el e)
class (Composite c,Composite el) => StaticByteAccess c el where
staticByteRead :: (Embed m e,Monad m,GetType e,GCompare e)
=> c e
-> Integer
-> Integer
-> m (Maybe (el e,Integer))
staticByteWrite :: (Embed m e,Monad m,GetType e,GCompare e)
=> c e
-> Integer
-> el e
-> m (Maybe (c e,Maybe (el e)))
class Composite c => CanConcat c where
withConcat :: (Embed m e,Monad m)
=> (c e -> m (a,c e)) -> [c e] -> m (Maybe (a,[c e]))
withConcat f [c] = do
(res,nc) <- f c
return $ Just (res,[nc])
withConcat _ _ = return Nothing
compConcat :: (Embed m e,Monad m)
=> [c e] -> m (Maybe (c e))
compConcat xs = do
res <- withConcat (\c -> return (c,c)) xs
return $ fmap fst res
class Composite c => CanSplit c where
withSplit :: (Embed m e,Monad m) => ((c e,c e) -> m (a,c e,c e)) -> Integer -> c e -> m (Maybe (a,c e))
withSplit _ _ _ = return Nothing
outsideRead :: e BoolType -> ByteRead a e
outsideRead c = ByteRead Map.empty (Just c) Nothing Nothing
impreciseRead :: e BoolType -> ByteRead a e
impreciseRead c = ByteRead Map.empty Nothing Nothing (Just c)
outsideWrite :: e BoolType -> ByteWrite a b e
outsideWrite c = ByteWrite [] (Just c) Nothing Nothing
fullReadCond :: (Embed m e,Monad m) => ByteRead el e -> m [e BoolType]
fullReadCond r = do
c1 <- mapM (\(_,c) -> not' c) (Map.elems $ overreads r)
c2 <- case readOutside r of
Nothing -> return []
Just c -> do
c' <- not' c
return [c']
c3 <- case readImprecision r of
Nothing -> return []
Just c -> do
c' <- not' c
return [c']
return $ c1++c2++c3
fullWriteCond :: (Embed m e,Monad m) => ByteWrite c el e -> m [e BoolType]
fullWriteCond w = do
c1 <- mapM (\(_,c) -> not' c) $ overwrite w
c2 <- case writeOutside w of
Nothing -> return []
Just c -> do
c' <- not' c
return [c']
c3 <- case writeImprecision w of
Nothing -> return []
Just c -> do
c' <- not' c
return [c']
return $ c1++c2++c3
concatRead :: (Embed m e,Monad m,GetType e,CanConcat el) => el e -> ByteRead el e -> m (ByteRead el e)
concatRead part read = do
fcond <- true
let fail = impreciseRead fcond
novers <- mapM (\(el,cond) -> do
nel <- compConcat [part,el]
case nel of
Nothing -> return Nothing
Just nel' -> return $ Just (nel',cond)) (overreads read)
case sequence novers of
Nothing -> return fail
Just novers' -> do
nfull <- case fullRead read of
Nothing -> return $ Just Nothing
Just full -> do
full' <- compConcat [part,full]
case full' of
Nothing -> return Nothing
Just f -> return $ Just $ Just f
case nfull of
Nothing -> return fail
Just nfull' -> return read { overreads = novers'
, fullRead = nfull' }
compSplit :: (CanSplit c,Embed m e,Monad m) => Integer -> c e -> m (Maybe (c e,c e))
compSplit off c = do
res <- withSplit (\(pre,post) -> return ((pre,post),pre,post)) off c
return $ fmap fst res
maybeITE :: (Embed m e,Monad m) => e BoolType -> Maybe (e BoolType) -> Maybe (e BoolType) -> m (Maybe (e BoolType))
maybeITE c Nothing Nothing = return Nothing
maybeITE c (Just r1) Nothing = do
nr <- c .&. r1
return $ Just nr
maybeITE c Nothing (Just r2) = do
nr <- (not' c) .&. r2
return $ Just nr
maybeITE c (Just r1) (Just r2) = do
nr <- (c .&. r1) .|. ((not' c) .&. r2)
return $ Just nr
byteReadITE :: (Embed m e,Monad m,Composite el,GetType e,GCompare e)
=> [(ByteRead el e,e BoolType)] -> m (ByteRead el e)
byteReadITE [] = return $ ByteRead Map.empty Nothing Nothing Nothing
byteReadITE [(r,_)] = return r
byteReadITE ((r,c):rs) = do
rest <- byteReadITE rs
notc <- not' c
over <- merge c notc (overreads r) (overreads rest)
outside <- maybeITE c (readOutside r) (readOutside rest)
full <- case fullRead r of
Nothing -> return $ fullRead rest
Just full1 -> case fullRead rest of
Nothing -> return $ Just full1
Just full2 -> do
Just nfull <- compITE c full1 full2
return $ Just nfull
imprec <- maybeITE c (readImprecision r) (readImprecision rest)
return $ ByteRead over outside full imprec
where
merge :: (Embed m e,Monad m,Composite a,GetType e,GCompare e)
=> e BoolType -> e BoolType
-> Map Integer (a e,e BoolType)
-> Map Integer (a e,e BoolType)
-> m (Map Integer (a e,e BoolType))
merge c notc x y
= sequence $ Map.mergeWithKey (\_ (el1,c1) (el2,c2) -> Just $ do
Just nel <- compITE c el1 el2
cond <- c .&. (c1 .|. c2)
return (nel,cond))
(fmap (\(el,c') -> do
nc <- c' .&. c
return (el,nc)))
(fmap (\(el,c') -> do
nc <- c' .&. notc
return (el,nc))) x y
byteWriteITE :: (Embed m e,Monad m,Composite c,Composite el,GetType e,GCompare e)
=> [(ByteWrite c el e,e BoolType)] -> m (ByteWrite c el e)
byteWriteITE [] = return $ ByteWrite [] Nothing Nothing Nothing
byteWriteITE [(w,_)] = return w
byteWriteITE ((w,c):ws) = do
rest <- byteWriteITE ws
notc <- not' c
over <- merge c notc (overwrite w) (overwrite rest)
outside <- maybeITE c (writeOutside w) (writeOutside rest)
full <- case fullWrite w of
Nothing -> return $ fullWrite rest
Just full1 -> case fullWrite rest of
Nothing -> return $ Just full1
Just full2 -> do
Just nfull <- compITE c full1 full2
return $ Just nfull
imprec <- maybeITE c (writeImprecision w) (writeImprecision rest)
return $ ByteWrite over outside full imprec
where
merge c notc [] ys = mapM (\(rest,cond) -> do
ncond <- notc .&. cond
return (rest,ncond)) ys
merge c notc xs [] = mapM (\(rest,cond) -> do
ncond <- c .&. cond
return (rest,ncond)) xs
merge c notc ((xrest,xcond):xs) ((yrest,ycond):ys)
= case compCompare xrest yrest of
EQ -> do
Just nrest <- compITE c xrest yrest
ncond <- (c .&. xcond) .|. (notc .&. ycond)
ns <- merge c notc xs ys
return $ (nrest,ncond):ns
LT -> do
ncond <- c .&. xcond
ns <- merge c notc xs ((yrest,ycond):ys)
return $ (xrest,ncond):ns
GT -> do
ncond <- notc .&. ycond
ns <- merge c notc ((xrest,ncond):xs) ys
return $ (yrest,ncond):ns
toByteRead :: (Embed m e,Monad m) => Maybe (el e,Integer) -> m (ByteRead el e)
toByteRead Nothing = do
cond <- true
return $ ByteRead Map.empty Nothing Nothing (Just cond)
toByteRead (Just (el,0)) = return $ ByteRead Map.empty Nothing (Just el) Nothing
toByteRead (Just (el,ov)) = do
cond <- true
return $ ByteRead (Map.singleton ov (el,cond)) Nothing Nothing Nothing
toByteWrite :: (Embed m e,Monad m) => Maybe (c e,Maybe (el e)) -> m (ByteWrite c el e)
toByteWrite Nothing = do
cond <- true
return $ ByteWrite [] Nothing Nothing (Just cond)
toByteWrite (Just (el,Nothing))
= return $ ByteWrite [] Nothing (Just el) Nothing
toByteWrite (Just (el,Just rest)) = do
cond <- true
return $ ByteWrite [(rest,cond)] Nothing (Just el) Nothing
fromStaticByteRead :: (ByteWidth c idx,StaticByteAccess c el,IsRanged idx,Integral (Value (SingletonType idx)),
Embed m e,Monad m,GetType e,GCompare e)
=> c e
-> idx e
-> Integer
-> m (ByteRead el e)
fromStaticByteRead c (idx :: idx e) sz = do
rangeStart <- getRange idx
(objSize :: idx e) <- byteWidth c (compType idx)
objSizeRange <- getRange objSize
let objRange = betweenRange (rangedConst 0) objSizeRange
rangeStart' = intersectionRange objRange rangeStart
rangeOutside = setMinusRange rangeStart objRange
case asFiniteRange rangeStart' of
Just starts -> do
reads <- sequence
[ do
cond <- getSingleton idx .==. constant start
res <- staticByteRead c (toInteger start) sz
case res of
Nothing -> return $ Left cond
Just (el,rsz) -> return $ Right (cond,el,rsz)
| start <- starts ]
let (imprecs,reads') = partitionEithers reads
imprec <- case imprecs of
[] -> return Nothing
_ -> fmap Just $ and' imprecs
full <- compITEs [ (cond,el) | (cond,el,0) <- reads' ]
(parts,imprec2) <- foldlM (\(part,cimprec) (cond,el,rsz)
-> if rsz==0
then return (part,cimprec)
else case Map.lookup rsz part of
Just (cur,cond') -> do
ncur <- compITE cond el cur
case ncur of
Nothing -> case cimprec of
Nothing -> return (part,Just cond)
Just cond' -> do
ncond <- cond .|. cond'
return (part,Just ncond)
Just ncur' -> do
ncond <- cond .|. cond'
return (Map.insert rsz (ncur',ncond) part,cimprec)
Nothing -> return (Map.insert rsz (el,cond) part,cimprec)
) (Map.empty,imprec) reads'
outside <- if nullRange rangeOutside
then return Nothing
else compositeGEQ idx objSize
return $ ByteRead parts outside full imprec2
Nothing -> do
cond <- true
return $ ByteRead Map.empty Nothing Nothing (Just cond)
fromStaticByteWrite :: (ByteWidth c idx,StaticByteAccess c el,IsRanged idx,
Integral (Value (SingletonType idx)),Embed m e,Monad m,
GetType e,GCompare e)
=> c e
-> idx e
-> el e
-> m (ByteWrite c el e)
fromStaticByteWrite c (idx :: idx e) el = do
rangeStart <- getRange idx
(objSize :: idx e) <- byteWidth c (compType idx)
objSizeRange <- getRange objSize
let objRange = betweenRange (rangedConst 0) objSizeRange
rangeStart' = intersectionRange objRange rangeStart
rangeOutside = setMinusRange rangeStart objRange
case asFiniteRange rangeStart' of
Just starts -> do
nelems <- sequence [ do
cond <- getSingleton idx .==. constant start
res <- staticByteWrite c (toInteger start) el
return (cond,res)
| start <- starts ]
imprec <- case [ cond | (cond,Nothing) <- nelems ] of
[] -> return Nothing
[c] -> return $ Just c
cs -> fmap Just $ and' cs
full <- compITEs [ (cond,nc) | (cond,Just (nc,_)) <- nelems ]
let overs = [ (rest,cond) | (cond,Just (_,Just rest)) <- nelems ]
outside <- if nullRange rangeOutside
then return Nothing
else compositeGEQ idx objSize
return $ ByteWrite overs outside full imprec
Nothing -> do
cond <- true
return $ ByteWrite [] Nothing Nothing (Just cond)
-- | The boolean states if the range starts included (True) or not (False).
-- Invariant: The range elements are sorted ascending.
type IntRange = (Bool,[Integer])
-- | Describes the allowed values that an expression may have.
-- BoolRange x y describes if value False is allowed (x) and if value True is allowed (y).
data Range tp where
BoolRange :: Bool -> Bool -> Range BoolType
IntRange :: IntRange -> Range IntType
BitVecRange :: BitWidth bw -> [(Integer,Integer)] -> Range (BitVecType bw)
deriving instance Eq (Range tp)
--deriving instance Show (Range tp)
showIntRange :: IntRange -> ShowS
showIntRange (open,rng)
= showChar '[' .
(if open
then showString "-inf" .
(case rng of
[] -> showString "..inf"
x:xs -> showsPrec 5 x . renderRange xs)
else renderRange rng) .
showChar ']'
where
renderRange [] = id
renderRange [x] = showsPrec 5 x .
showString "..inf"
renderRange [x,y]
| x==y = showsPrec 5 x
| otherwise = showsPrec 5 x .
showString ".." .
showsPrec 5 y
renderRange (x:y:rest)
| x==y = showsPrec 5 x .
showChar ',' .
renderRange rest
| otherwise = showsPrec 5 x .
showString ".." .
showsPrec 5 y .
showChar ',' .
renderRange rest
instance Show (Range tp) where
showsPrec _ (BoolRange f t)
= shows ((if f then [False] else [])++
(if t then [True] else []))
showsPrec _ (IntRange rng) = showIntRange rng
showsPrec _ (BitVecRange _ rng)
= showListWith (\(x,y) -> if x==y
then showsPrec 5 x
else showsPrec 5 x .
showString ".." .
showsPrec 5 y) rng
instance Ord (Range tp) where
compare (BoolRange f1 t1) (BoolRange f2 t2) = compare (f1,t1) (f2,t2)
compare (IntRange x) (IntRange y) = compare x y
compare (BitVecRange _ rx) (BitVecRange _ ry) = compare rx ry
instance GetType Range where
getType (BoolRange _ _) = bool
getType (IntRange _) = int
getType (BitVecRange bw _) = bitvec bw
unionRange :: Range tp -> Range tp -> Range tp
unionRange (BoolRange f1 t1) (BoolRange f2 t2) = BoolRange (f1 || f2) (t1 || t2)
unionRange (IntRange x) (IntRange y) = IntRange (unionIntRange x y)
where
unionIntRange :: IntRange -> IntRange -> IntRange
unionIntRange (False,[]) ys = ys
unionIntRange (True,[]) _ = (True,[])
unionIntRange xs (False,[]) = xs
unionIntRange _ (True,[]) = (True,[])
unionIntRange (False,xs) (False,ys)
= (False,unionIntRange' xs ys)
unionIntRange (xi,x:xs) (yi,y:ys)
= (True,filterRange zs)
where
(z,zs)
| xi && yi = (max x y,unionIntRange' xs ys)
| xi = (x,unionIntRange' xs (y:ys))
| yi = (y,unionIntRange' (x:xs) ys)
filterRange [] = [z]
filterRange (l:u:rest) = if l <= z-1
then if u>z
then u:rest
else filterRange rest
else z:l:u:rest
unionIntRange' :: [Integer] -> [Integer] -> [Integer]
unionIntRange' [] ys = ys
unionIntRange' xs [] = xs
unionIntRange' (xl:xu:xs) (yl:yu:ys)
| xu < yl-1 = xl:xu:unionIntRange' xs (yl:yu:ys)
| yu < xl-1 = yl:yu:unionIntRange' (xl:xu:xs) ys
| otherwise = unionIntRange' (min xl yl:max xu yu:xs) ys
unionIntRange' [x] [y] = [min x y]
unionIntRange' [x] (yl:yu:ys)
| yu < x-1 = yl:yu:unionIntRange' [x] ys
| otherwise = [min x yl]
unionIntRange' (xl:xu:xs) [y]
| xu < y-1 = xl:xu:unionIntRange' xs [y]
| otherwise = [min xl y]
unionRange (BitVecRange bw xr) (BitVecRange _ yr)
= BitVecRange bw (unionRange' xr yr)
where
unionRange' [] yr = yr
unionRange' xr [] = xr
unionRange' (x@(xlower,xupper):xs) (y@(ylower,yupper):ys)
| xupper < ylower-1 = x:unionRange' xs (y:ys)
| yupper < xlower-1 = y:unionRange' (x:xs) ys
| otherwise = unionRange' ((min xlower ylower,max xupper yupper):xs) ys
intersectionRange :: Range tp -> Range tp -> Range tp
intersectionRange (BoolRange f1 t1) (BoolRange f2 t2)
= BoolRange (f1 && f2) (t1 && t2)
intersectionRange (IntRange x) (IntRange y) = IntRange (intersectionIntRange x y)
where
intersectionIntRange :: IntRange -> IntRange -> IntRange
intersectionIntRange (True,[]) ys = ys
intersectionIntRange xs (True,[]) = xs
intersectionIntRange (True,u1:r1) (True,u2:r2)
= if u1 > u2
then (True,u2:intersectionIntRange' (u2:u1:r1) r2)
else (True,u1:intersectionIntRange' r1 (u1:u2:r2))
intersectionIntRange (True,u1:r1) (False,l2:r2)
= if u1 < l2
then (False,intersectionIntRange' r1 (l2:r2))
else (False,intersectionIntRange' (l2:u1:r1) (l2:r2))
intersectionIntRange (False,l1:r1) (True,u2:r2)
= if u2 < l1
then (False,intersectionIntRange' (l1:r1) r2)
else (False,intersectionIntRange' (l1:r1) (l1:u2:r2))
intersectionIntRange (False,[]) _ = (False,[])
intersectionIntRange _ (False,[]) = (False,[])
intersectionIntRange (False,r1) (False,r2)
= (False,intersectionIntRange' r1 r2)
intersectionIntRange' [] _ = []
intersectionIntRange' _ [] = []
intersectionIntRange' [l1] [l2] = [max l1 l2]
intersectionIntRange' [l1] (l2:u2:r2)
= if l1 > u2
then intersectionIntRange' [l1] r2
else max l1 l2:u2:r2
intersectionIntRange' (l1:u1:r1) [l2]
= if l2 > u1
then intersectionIntRange' r1 [l2]
else max l1 l2:u1:r1
intersectionIntRange' (l1:u1:r1) (l2:u2:r2)
| u1 < l2 = intersectionIntRange' r1 (l2:u2:r2)
| u2 < l1 = intersectionIntRange' (l1:u1:r1) r2
| otherwise = max l1 l2:min u1 u2:case compare u1 u2 of
LT -> intersectionIntRange' r1 (u1:u2:r2)
EQ -> intersectionIntRange' r1 r2
GT -> intersectionIntRange' (u2:u1:r1) r2
intersectionRange (BitVecRange bw x) (BitVecRange _ y)
= BitVecRange bw (intersectionBV x y)
where
intersectionBV [] _ = []
intersectionBV _ [] = []
intersectionBV ((l1,u1):r1) ((l2,u2):r2)
| u1 < l2 = intersectionBV r1 ((l2,u2):r2)
| u2 < l1 = intersectionBV ((l1,u1):r1) r2
| otherwise = (max l1 l2,min u1 u2):case compare u1 u2 of
LT -> intersectionBV r1 ((u1,u2):r2)
EQ -> intersectionBV r1 r2
GT -> intersectionBV ((u2,u1):r1) r2
setMinusRange :: Range tp -> Range tp -> Range tp
setMinusRange (BoolRange f1 t1) (BoolRange f2 t2)
= BoolRange (if f2 then False else f1) (if t2 then False else t1)
setMinusRange (IntRange x) (IntRange y) = IntRange $ minus x y
where
minus :: IntRange -> IntRange -> IntRange
minus (False,[]) _ = (False,[])
minus _ (True,[]) = (False,[])
minus xs (False,[]) = xs
minus (False,xs) (False,ys) = (False,minus' xs ys)
minus (True,[]) (True,y:ys) = minus (False,[y+1]) (False,ys)
minus (True,x:xs) (True,y:ys)
= if x <= y
then minus (False,xs) (True,y:ys)
else minus (False,y+1:x:xs) (False,ys)
minus (False,lx:xs) (True,uy:ys)
= if uy < lx
then minus (False,lx:xs) (False,ys)
else case xs of
[] -> minus (False,[uy+1]) (False,ys)
ux:xs' -> if ux <= uy
then minus (False,xs') (True,uy:ys)
else minus (False,uy+1:ux:xs') (False,ys)
minus (True,[]) (False,[ly])
= (True,[ly-1])
minus (True,[]) (False,ly:uy:ys)
= minus (True,[ly-1,uy+1]) (False,ys)
minus (True,ux:xs) (False,[ly])
= if ly > ux
then (True,ux:minus' xs [ly])
else (True,[ly-1])
minus (True,ux:xs) (False,ly:uy:ys)
| ly > ux = (True,ux:minus' xs (ly:uy:ys))
| uy == ux = minus (True,ly-1:xs) (False,ys)
| uy < ux = minus (True,ly-1:uy+1:ux:xs) (False,ys)
| otherwise = minus (True,ly-1:xs) (False,ux+1:uy:ys)
minus' [] _ = []
minus' xs [] = xs
minus' [lx] [ly] = if ly <= lx
then []
else [lx,ly-1]
minus' [lx] (ly:uy:ys)
| uy < lx = minus' [lx] ys
| ly <= lx = minus' [uy+1] ys
| otherwise = lx:ly-1:minus' [uy+1] ys
minus' (lx:ux:xs) [ly]
| ly <= lx = []
| ux < ly = lx:ux:minus' xs [ly]
| otherwise = [lx,ly-1]
minus' (lx:ux:xs) (ly:uy:ys)
| ux < ly = lx:ux:minus' xs (ly:uy:ys)
| uy < lx = minus' (lx:ux:xs) ys
| otherwise = let before = if lx < ly
then [lx,ly-1]
else []
after = if ux > uy
then [uy+1,ux]
else []
rest = if uy > ux
then [ux+1,uy]
else []
in before++minus' (after++xs) (rest++ys)
setMinusRange (BitVecRange bw r1) (BitVecRange _ r2) = BitVecRange bw (minus r1 r2)
where
minus :: [(Integer,Integer)] -> [(Integer,Integer)] -> [(Integer,Integer)]
minus [] _ = []
minus xs [] = xs
minus ((lx,ux):xs) ((ly,uy):ys)
| ux < ly = (lx,ux):minus xs ((ly,uy):ys)
| uy < lx = minus ((lx,ux):xs) ys
| otherwise = let before = if lx < ly
then [(lx,ly-1)]
else []
after = if ux > uy
then [(uy+1,ux)]
else []
rest = if uy > ux
then [(ux+1,uy)]
else []
in before++minus (after++xs) (rest++ys)
rangedConst :: Value tp -> Range tp
rangedConst (BoolValue b) = BoolRange (not b) b
rangedConst (IntValue i) = IntRange (False,[i,i])
rangedConst (BitVecValue i bw) = BitVecRange bw [(i,i)]
rangeFromList :: Repr tp -> [Value tp] -> Range tp
rangeFromList BoolRepr xs = foldl (\(BoolRange f t) (BoolValue x)
-> if x then BoolRange f True
else BoolRange True t
) (BoolRange False False) xs
rangeFromList IntRepr xs = IntRange (False,mkBnds $ sort xs)
where
mkBnds :: [Value IntType] -> [Integer]
mkBnds [] = []
mkBnds (IntValue x:rest) = buildRange x x rest
buildRange :: Integer -> Integer -> [Value IntType] -> [Integer]
buildRange l u [] = [l,u]
buildRange l u (IntValue y:ys)
= if y==u || y==u+1
then buildRange l y ys
else l:u:buildRange y y ys
rangeFromList (BitVecRepr bw) xs
= BitVecRange bw (mkBnds $ sort xs)
where
mkBnds :: [Value (BitVecType bw)] -> [(Integer,Integer)]
mkBnds [] = []
mkBnds (BitVecValue x _:rest) = buildRange x x rest
buildRange :: Integer -> Integer -> [Value (BitVecType bw)] -> [(Integer,Integer)]
buildRange l u [] = [(l,u)]
buildRange l u (BitVecValue y _:ys)
= if y==u || y==u+1
then buildRange l y ys
else (l,u):buildRange y y ys
nullRange :: Range tp -> Bool
nullRange (BoolRange False False) = True
nullRange (IntRange (False,[])) = True
nullRange (BitVecRange _ []) = True
nullRange _ = False
isConst :: Range tp -> Maybe (Value tp)
isConst (BoolRange True False) = Just (BoolValue False)
isConst (BoolRange False True) = Just (BoolValue True)
isConst (IntRange (False,[i,j]))
| i==j = Just (IntValue i)
isConst (BitVecRange bw [(i,j)])
| i==j = Just (BitVecValue i bw)
isConst _ = Nothing
rangeInvariant :: Embed m e => Range tp -> e tp -> m (e BoolType)
rangeInvariant (BoolRange True True) _ = true
rangeInvariant (BoolRange False False) _ = false
rangeInvariant (BoolRange True False) e = not' e
rangeInvariant (BoolRange False True) e = pure e
rangeInvariant (IntRange r) e = rangeInvariant' (\isLE c -> if isLE then e .<=. cint c else e .>=. cint c) r
rangeInvariant (BitVecRange bw r) e
= or' $ fmap (\(lower,upper)
-> and' $ (if lower==0
then []
else [e `bvuge` cbv lower bw])++
(if upper==2^bw'-1
then []
else [e `bvule` cbv upper bw])
) r
where
bw' = bwSize bw
rangeInvariant' :: Embed m e => (Bool -> Integer -> m (e BoolType)) -- ^ First parameter decides if the operator is <=x (True) or >=x (False).
-> IntRange
-> m (e BoolType)
rangeInvariant' f (c,xs) = if c then case xs of
[] -> true
x:xs' -> case mk xs' of
[] -> f True x
conj -> or' (f True x:conj)
else case mk xs of
[] -> false
[x] -> x
conj -> or' conj
where
mk (l:u:xs) = ((f False l) .&. (f True u)) : mk xs
mk [l] = [f False l]
mk [] = []
lowerIntBound :: IntRange -> Maybe (Integer,Bool)
lowerIntBound (incl,x:xs) = Just (x,incl)
lowerIntBound (_,[]) = Nothing
upperIntBound :: IntRange -> Maybe (Integer,Bool)
upperIntBound (_,[]) = Nothing
upperIntBound (incl,xs) = Just $ upper incl xs
where
upper incl [i] = (i,not incl)
upper incl (_:is) = upper (not incl) is
extendLowerIntBound :: IntRange -> IntRange
extendLowerIntBound (False,[]) = (True,[])
extendLowerIntBound (False,_:xs) = (True,xs)
extendLowerIntBound (True,[]) = (True,[])
extendLowerIntBound (True,[_]) = (True,[])
extendLowerIntBound (True,u:l:xs) = (True,xs)
extendUpperIntBound :: IntRange -> IntRange
extendUpperIntBound (False,[]) = (True,[])
extendUpperIntBound (False,[_]) = (True,[])
extendUpperIntBound (incl,xs) = (incl,extend incl xs)
where
extend True [u] = []
extend True [u,l] = []
extend incl (x:xs) = x:extend (not incl) xs
rangeFixpoint :: Range tp -> Range tp -> Range tp
rangeFixpoint _ (BoolRange f t) = BoolRange f t
rangeFixpoint (IntRange r1) (IntRange r2) = IntRange r3
where
r3' = if lowerIntBound r1 == lowerIntBound r2
then r2
else extendLowerIntBound r2
r3 = if upperIntBound r1 == upperIntBound r2
then r3'
else extendUpperIntBound r3'
rangeFixpoint (BitVecRange bw []) (BitVecRange _ r2) = BitVecRange bw r2
rangeFixpoint (BitVecRange bw r1) (BitVecRange _ []) = BitVecRange bw r1
rangeFixpoint (BitVecRange bw r1) (BitVecRange _ r2)
= BitVecRange bw $ fixEnd r1 (fixStart r1 r2)
where
fixStart ((l1,u1):r1) ((l2,u2):r2)
| l1==l2 = (l2,u2):r2
| otherwise = (0,u2):r2
fixEnd [(l1,u1)] [(l2,u2)]
| u1==u2 = [(l2,u2)]
| otherwise = [(l2,2^(bwSize bw)-1)]
fixEnd (x:xs) [y] = fixEnd xs [y]
fixEnd [x] (y:ys) = y:fixEnd [x] ys
fixEnd (_:xs) (y:ys) = y:fixEnd xs ys
lowerBound :: Range tp -> Maybe (Inf (Value tp))
lowerBound (BoolRange f t)
| f = Just (Regular (BoolValue False))
| t = Just (Regular (BoolValue True))
| otherwise = Nothing
lowerBound (IntRange (True,_)) = Just NegInfinity
lowerBound (IntRange (False,[])) = Nothing
lowerBound (IntRange (False,l:_)) = Just (Regular (IntValue l))
lowerBound (BitVecRange _ []) = Nothing
lowerBound (BitVecRange bw ((l,_):_)) = Just (Regular (BitVecValue l bw))
upperBound :: Range tp -> Maybe (Inf (Value tp))
upperBound (BoolRange f t)
| t = Just (Regular (BoolValue True))
| f = Just (Regular (BoolValue False))
| otherwise = Nothing
upperBound (IntRange (False,[])) = Nothing
upperBound (IntRange (True,[])) = Just PosInfinity
upperBound (IntRange (incl,rng)) = upper incl rng
where
upper False [l] = Just PosInfinity
upper True [u] = Just (Regular (IntValue u))
upper incl (_:xs) = upper (not incl) xs
upperBound (BitVecRange _ []) = Nothing
upperBound (BitVecRange bw xs) = Just (Regular (BitVecValue (snd $ last xs) bw))
intRangeIncludes :: Integer -> IntRange -> Bool
intRangeIncludes _ (incl,[]) = incl
intRangeIncludes n (False,l:xs)
| n < l = False
| otherwise = intRangeIncludes n (True,xs)
intRangeIncludes n (True,u:xs)
| n <= u = True
| otherwise = intRangeIncludes n (False,xs)
includes :: Value tp -> Range tp -> Bool
includes (BoolValue v) (BoolRange f t) = if v then t else f
includes (IntValue v) (IntRange r) = intRangeIncludes v r
includes (BitVecValue v _) (BitVecRange _ r)
= includes' r
where
includes' [] = False
includes' ((l,u):rest) = (v >= l && v <= u) || includes' rest
fullRange :: Repr tp -> Range tp
fullRange BoolRepr = BoolRange True True
fullRange IntRepr = IntRange (True,[])
fullRange (BitVecRepr bw) = BitVecRange bw [(0,2^(bwSize bw)-1)]
emptyRange :: Repr tp -> Range tp
emptyRange BoolRepr = BoolRange False False
emptyRange IntRepr = IntRange (False,[])
emptyRange (BitVecRepr bw) = BitVecRange bw []
isEmptyRange :: Range tp -> Bool
isEmptyRange (BoolRange False False) = True
isEmptyRange (IntRange (False,[])) = True
isEmptyRange (BitVecRange _ []) = True
isEmptyRange _ = False
singletonRange :: Value tp -> Range tp
singletonRange (BoolValue b) = BoolRange (not b) b
singletonRange (IntValue v) = IntRange (False,[v,v])
singletonRange (BitVecValue v bw) = BitVecRange bw [(v,v)]
leqRange :: Integer -> Range IntType
leqRange x = IntRange (True,[x])
ltRange :: Integer -> Range IntType
ltRange x = IntRange (True,[x-1])
geqRange :: Integer -> Range IntType
geqRange x = IntRange (False,[x])
gtRange :: Integer -> Range IntType
gtRange x = IntRange (False,[x+1])
intersectionIntRange :: IntRange -> IntRange -> IntRange
intersectionIntRange (False,[]) _ = (False,[])
intersectionIntRange _ (False,[]) = (False,[])
intersectionIntRange (True,[]) ys = ys
intersectionIntRange xs (True,[]) = xs
intersectionIntRange (False,xs) (False,ys)
= (False,intersectionIntRange' xs ys)
--intersectionIntRange (True,x:xs) (True,y:ys) = case compare x y of
-- EQ -> (True,x:intersectionIntRange'
intersectionIntRange' :: [Integer] -> [Integer] -> [Integer]
intersectionIntRange' [] _ = []
intersectionIntRange' _ [] = []
intersectionIntRange' (xl:xu:xs) (yl:yu:ys)
| xu < yl-1 = intersectionIntRange' xs (yl:yu:ys)
| yu < xl-1 = intersectionIntRange' (xl:xu:xs) ys
| otherwise = max xl yl:min xu yu:
case compare xu yu of
EQ -> intersectionIntRange' xs ys
LT -> intersectionIntRange' xs (xu:yu:ys)
GT -> intersectionIntRange' (yu:xu:xs) ys
rangeType :: Range tp -> Repr tp
rangeType (BoolRange _ _) = bool
rangeType (IntRange _) = int
rangeType (BitVecRange bw _) = bitvec bw
asFiniteRange :: Range tp -> Maybe [Value tp]
asFiniteRange (BoolRange f t)
= Just $ (if f then [BoolValue False] else [])++
(if t then [BoolValue True] else [])
asFiniteRange (IntRange (True,_)) = Nothing
asFiniteRange (IntRange (False,xs))
= asFinite xs
where
asFinite [] = Just []
asFinite [_] = Nothing
asFinite (l:u:xs) = do
xs' <- asFinite xs
return $ [IntValue x | x <- [l..u]]++xs'
asFiniteRange (BitVecRange bw rng)
= Just $ [ BitVecValue x bw
| (l,u) <- rng
, x <- [l..u] ]
-- To support easier manipulation of ranges, we introduce the Bounds type:
--type Bounds = Maybe (Maybe Integer,[(Integer,Integer)],Maybe Integer)
data Inf x = NegInfinity | Regular x | PosInfinity deriving (Eq,Ord,Show,Functor)
type Bounds x = [(Inf x,Inf x)]
addInf :: (a -> a -> a) -> Inf a -> Inf a -> Maybe (Inf a)
addInf add (Regular x) (Regular y) = Just $ Regular $ x `add` y
addInf _ NegInfinity PosInfinity = Nothing
addInf _ PosInfinity NegInfinity = Nothing
addInf _ PosInfinity _ = Just PosInfinity
addInf _ NegInfinity _ = Just NegInfinity
addInf _ _ PosInfinity = Just PosInfinity
addInf _ _ NegInfinity = Just NegInfinity
addInf' :: (a -> a -> a) -> Inf a -> Inf a -> Inf a
addInf' add x y = case addInf add x y of
Just r -> r
Nothing -> error "Adding positive and negative infinity undefined."
subInf :: (a -> a -> a) -> Inf a -> Inf a -> Maybe (Inf a)
subInf sub (Regular x) (Regular y) = Just $ Regular $ x `sub` y
subInf _ NegInfinity NegInfinity = Nothing
subInf _ PosInfinity PosInfinity = Nothing
subInf _ PosInfinity _ = Just PosInfinity
subInf _ NegInfinity _ = Just NegInfinity
subInf _ _ PosInfinity = Just NegInfinity
subInf _ _ NegInfinity = Just PosInfinity
subInf' :: (a -> a -> a) -> Inf a -> Inf a -> Inf a
subInf' add x y = case subInf add x y of
Just r -> r
Nothing -> error "Subtracting infinity undefined."
mulInf :: Ord a => a -- ^ Zero
-> (a -> a -> a) -- ^ Multiplication
-> Inf a -> Inf a -> Inf a
mulInf _ mul (Regular x) (Regular y) = Regular $ x `mul` y
mulInf zero _ (Regular x) PosInfinity = case compare x zero of
LT -> NegInfinity
EQ -> Regular zero
GT -> PosInfinity
mulInf zero _ (Regular x) NegInfinity = case compare x zero of
LT -> PosInfinity
EQ -> Regular zero
GT -> NegInfinity
mulInf _ _ PosInfinity PosInfinity = PosInfinity
mulInf _ _ PosInfinity NegInfinity = NegInfinity
mulInf zero _ PosInfinity (Regular y) = case compare y zero of
LT -> NegInfinity
EQ -> Regular zero
GT -> PosInfinity
mulInf _ _ NegInfinity PosInfinity = NegInfinity
mulInf _ _ NegInfinity NegInfinity = PosInfinity
mulInf zero _ NegInfinity (Regular y) = case compare y zero of
LT -> PosInfinity
EQ -> Regular zero
GT -> NegInfinity
instance (Ord x,Num x) => Num (Inf x) where
fromInteger = Regular . fromInteger
(+) = addInf' (+)
(-) = subInf' (-)
(*) = mulInf 0 (*)
negate (Regular x) = Regular $ negate x
negate NegInfinity = PosInfinity
negate PosInfinity = NegInfinity
abs (Regular x) = Regular $ abs x
abs _ = PosInfinity
signum (Regular x) = Regular $ signum x
signum PosInfinity = 1
signum NegInfinity = -1
instance Real x => Real (Inf x) where
toRational NegInfinity = error "toRational.{Inf x}: called on negative infinity"
toRational (Regular x) = toRational x
toRational PosInfinity = error "toRational.{Inf x}: called on positive infinity"
instance Enum x => Enum (Inf x) where
succ NegInfinity = NegInfinity
succ (Regular x) = Regular (succ x)
succ PosInfinity = PosInfinity
pred NegInfinity = NegInfinity
pred (Regular x) = Regular (pred x)
pred PosInfinity = PosInfinity
toEnum x = Regular (toEnum x)
fromEnum NegInfinity = error "fromEnum.{Inf x}: called on negative infinity"
fromEnum (Regular x) = fromEnum x
fromEnum PosInfinity = error "fromEnum.{Inf x}: called on positive infinity"
{-instance Integral x => Integral (Inf x) where
quot NegInfinity (Regular y) = case compare y 0 of
LT -> PosInfinity
EQ -> error "quot{Inf}: divide by zero"
GT -> NegInfinity
quot PosInfinity (Regular y) = case compare y 0 of
LT -> NegInfinity
EQ -> error "quot{Inf}: divide by zero"
GT -> PosInfinity
quot (Regular x) (Regular y) = Regular (x `quot` y)
quot (Regular _) PosInfinity = Regular 0
quot (Regular _) NegInfinity = Regular 0
quot _ _ = error "quot{Inf}: two infinite arguments"
rem (Regular x) (Regular y) = Regular (x `rem` y)
rem PosInfinity _ = error "rem{Inf}: first argument cannot be infinite."
rem NegInfinity _ = error "rem{Inf}: first argument cannot be infinite."
rem (Regular x) PosInfinity = Regular x
rem (Regular x) NegInfinity = Regular x
div (Regular x) (Regular y) = Regular (x `div` y)
div PosInfinity (Regular x) = case compare x 0 of
LT -> NegInfinity
EQ -> error "div{Inf}: divide by zero"
GT -> PosInfinity
div NegInfinity (Regular x) = case compare x 0 of
LT -> PosInfinity
EQ -> error "div{Inf}: divide by zero"
GT -> NegInfinity
div (Regular x) PosInfinity = if x>=0
then Regular 0
else Regular (-1)
div (Regular x) NegInfinity = if x>0
then Regular (-1)
else Regular 0
div _ _ = error "div{Inf}: two infinite arguments"
mod (Regular x) (Regular y) = Regular (x `mod` y)
mod (Regular x) PosInfinity = if x>=0
then Regular x
else error "mod{Inf}: undefined for negative first parameter and positive infinity second parameter"
mod (Regular x) NegInfinity = if x<=0
then Regular x
else error "mod{Inf}: undefined for positive first parameter and negative infinity second parameter"
mod _ _ = error "mod{Inf}: undefined"-}
toBounds :: Range tp -> Bounds (Value tp)
toBounds (BoolRange True True) = [(Regular $ BoolValue False,Regular $ BoolValue True)]
toBounds (BoolRange f t) = (if f then [(Regular $ BoolValue False,Regular $ BoolValue False)] else [])++
(if t then [(Regular $ BoolValue True,Regular $ BoolValue True)] else [])
toBounds (IntRange r) = case r of
(True,[]) -> [(NegInfinity,PosInfinity)]
(True,x:xs) -> (NegInfinity,Regular $ IntValue x):toBounds' xs
(False,xs) -> toBounds' xs
where
toBounds' :: [Integer] -> Bounds (Value IntType)
toBounds' [] = []
toBounds' [lower] = [(Regular $ IntValue lower,PosInfinity)]
toBounds' (lower:upper:xs) = (Regular $ IntValue lower,Regular $ IntValue upper):toBounds' xs
toBounds (BitVecRange bw rng) = [(Regular $ BitVecValue lower bw,
Regular $ BitVecValue upper bw)
| (lower,upper) <- rng]
fromBounds :: Repr tp -> Bounds (Value tp) -> Range tp
fromBounds tp bnd = case tp of
BoolRepr -> boolRange False bnd''
IntRepr -> intRange bnd''
BitVecRepr bw -> bvRange bw bnd''
where
bnd' = sortBy (comparing fst) bnd
bnd'' = mergeBounds prev bnd
prev = case tp of
BoolRepr -> pred
IntRepr -> pred
RealRepr -> id
BitVecRepr _ -> bvPred
mergeBounds :: Ord a => (a -> a) -> Bounds a -> Bounds a
mergeBounds _ [] = []
mergeBounds _ [x] = [x]
mergeBounds f ((NegInfinity,NegInfinity):xs) = mergeBounds f xs
mergeBounds f ((PosInfinity,PosInfinity):xs) = mergeBounds f xs
mergeBounds f ((l1,u1):(l2,u2):xs)
| l1 > u1 = mergeBounds f ((l2,u2):xs)
| l2 > u2 = mergeBounds f ((l1,u1):xs)
| u1>=fmap f l2 = mergeBounds f ((l1,max u1 u2):xs)
| otherwise = (l1,u1):mergeBounds f ((l2,u2):xs)
boolRange :: Bool -> Bounds (Value BoolType) -> Range BoolType
boolRange hasF [] = BoolRange hasF False
boolRange _ ((NegInfinity,PosInfinity):_) = BoolRange True True
boolRange _ ((NegInfinity,Regular (BoolValue x)):xs)
= if x
then BoolRange True True
else boolRange True xs
boolRange hasF ((Regular (BoolValue x),PosInfinity):xs)
= BoolRange (hasF && not x) True
boolRange hasF ((Regular (BoolValue l),Regular (BoolValue u)):xs)
= if u
then BoolRange (hasF || not l) True
else boolRange True xs
intRange :: Bounds (Value IntType) -> Range IntType
intRange [] = IntRange (False,[])
intRange [(NegInfinity,PosInfinity)] = IntRange (True,[])
intRange ((NegInfinity,Regular (IntValue x)):xs) = IntRange (True,x:intRange' xs)
intRange xs = IntRange (False,intRange' xs)
intRange' :: Bounds (Value IntType) -> [Integer]
intRange' [] = []
intRange' [(Regular (IntValue x),PosInfinity)] = [x]
intRange' ((Regular (IntValue l),Regular (IntValue u)):xs) = l:u:intRange' xs
bvRange :: BitWidth bw -> Bounds (Value (BitVecType bw)) -> Range (BitVecType bw)
bvRange bw xs = BitVecRange bw (bvRange' (bwSize bw) xs)
bvRange' :: Integer -> Bounds (Value (BitVecType bw)) -> [(Integer,Integer)]
bvRange' _ [] = []
bvRange' bw ((NegInfinity,PosInfinity):_) = [(0,2^bw-1)]
bvRange' bw ((NegInfinity,Regular (BitVecValue u _)):xs)
| u >= 0 = (0,u):bvRange' bw xs
| otherwise = bvRange' bw xs
bvRange' bw ((Regular (BitVecValue l _),PosInfinity):_)
| l < 2^bw = [(l,2^bw-1)]
| otherwise = []
bvRange' bw ((Regular (BitVecValue l _),Regular (BitVecValue u _)):xs)
| u < 0 || l >= 2^bw = bvRange' bw xs
| otherwise = (max l 0,min u (2^bw-1)):bvRange' bw xs
addOverflow :: Ord a => a -- ^ Zero
-> (a -> a -> a) -- ^ Addition
-> a -> a -> (a,Bool)
addOverflow zero add x y = (sum,overf)
where
sum = x `add` y
overf = if x >= zero
then sum < y
else sum > y
multOverflow :: Eq a => (a -> a -> a) -> (a -> a -> a) -> a -> a -> (a,Bool)
multOverflow mul div x y = (prod,prod `div` y /= x)
where
prod = x `mul` y
addBounds :: Ord a => a -> (a -> a -> a) -> Maybe a -> Bounds a -> Bounds a -> Bounds a
addBounds zero add lim b1 b2 = [ r
| r1 <- b1
, r2 <- b2
, r <- addRange zero (addInf' add) lim r1 r2 ]
subBounds :: Ord a => a -> (a -> a -> a) -> Maybe a -> Bounds a -> Bounds a -> Bounds a
subBounds zero add lim b1 b2 = [ r
| r1 <- b1
, r2 <- b2
, r <- addRange zero (subInf' add) lim r1 r2 ]
addRange :: Ord a => a -- ^ Zero
-> (Inf a -> Inf a -> Inf a) -- ^ Addition
-> Maybe a -- ^ Upper bound
-> (Inf a,Inf a)
-> (Inf a,Inf a)
-> [(Inf a,Inf a)]
addRange zero add (Just lim) (l1,u1) (l2,u2)
| overfL = [(nl,nu)]
| overfU = if nl <= nu
then [(Regular zero,Regular lim)]
else [(Regular zero,nu),(nl,Regular lim)]
| otherwise = [(nl,nu)]
where
(nl,overfL) = addOverflow (Regular zero) add l1 l2
(nu,overfU) = addOverflow (Regular zero) add u1 u2
addRange _ add Nothing (l1,u1) (l2,u2)
= [(add l1 l2,add u1 u2)]
multBounds :: Ord a => a -> (a -> a -> a) -> (a -> a -> a) -> Maybe a -> Bounds a -> Bounds a -> Bounds a
multBounds zero mul div lim b1 b2 = [ r | r1 <- b1
, r2 <- b2
, r <- multRange zero mul div lim r1 r2 ]
where
multRange :: Ord a => a -> (a -> a -> a) -> (a -> a -> a) -> Maybe a -> (Inf a,Inf a) -> (Inf a,Inf a) -> [(Inf a,Inf a)]
multRange zero mul div (Just lim) (Regular l1,Regular u1) (Regular l2,Regular u2)
| overfL || overfU = [(Regular zero,Regular lim)]
| otherwise = [(Regular nl,Regular nu)]
where
(nl,overfL) = multOverflow mul div l1 l2
(nu,overfU) = multOverflow mul div u1 u2
multRange zero mul _ Nothing (l1,u1) (l2,u2) = [(mulInf zero mul l1 l2,mulInf zero mul u1 u2)]
divBounds :: Ord a => a -> a -> (a -> a -> a) -> Bounds a -> Bounds a -> Bounds a
divBounds zero negOne div b1 b2 = [ divRange zero negOne div r1 r2
| r1 <- b1
, r2 <- b2 ]
where
divRange :: Ord a => a -> a -> (a -> a -> a) -> (Inf a,Inf a) -> (Inf a,Inf a) -> (Inf a,Inf a)
divRange zero negOne div (lx,ux) (ly,uy)
| ly <= Regular zero && uy >= Regular zero = (NegInfinity,PosInfinity)
| ly >= Regular zero = (case lx of
NegInfinity -> NegInfinity
PosInfinity -> PosInfinity
Regular x -> case uy of
PosInfinity -> Regular zero
Regular y -> Regular $ x `div` y,
case ux of
NegInfinity -> NegInfinity
PosInfinity -> PosInfinity
Regular x -> case ly of
PosInfinity -> if x < zero
then Regular negOne
else Regular zero
Regular y -> Regular $ x `div` y)
| otherwise = (case ux of
NegInfinity -> PosInfinity
PosInfinity -> NegInfinity
Regular x -> case ly of
NegInfinity -> if x>=zero
then Regular zero
else Regular negOne
Regular y -> Regular $ x `div` y,
case lx of
NegInfinity -> PosInfinity
PosInfinity -> NegInfinity
Regular x -> case uy of
NegInfinity -> if x>=zero
then Regular zero
else Regular negOne
Regular y -> Regular $ x `div` y)
modBounds :: Ord a => a -> (a -> a -> a) -> Bounds a -> Bounds a -> Bounds a
modBounds zero mod b1 b2 = [ modRange zero mod r1 r2
| r1 <- b1
, r2 <- b2 ]
where
modRange :: Ord a => a -> (a -> a -> a) -> (Inf a,Inf a) -> (Inf a,Inf a) -> (Inf a,Inf a)
modRange zero mod (lx,ux) (ly,uy)
| ly <= Regular zero && uy >= Regular zero = (NegInfinity,PosInfinity)
| uy < Regular zero = if lx > ly && ux <= Regular zero
then (lx,ux)
else (ly,Regular zero)
| otherwise = if ux < ly && lx >= Regular zero
then (lx,ly)
else (Regular zero,uy)
negBounds :: Ord a => (a -> a) -> Bounds a -> Bounds a
negBounds negate = reverse . fmap neg
where
neg (l,u) = (negate' u,negate' l)
negate' PosInfinity = NegInfinity
negate' NegInfinity = PosInfinity
negate' (Regular x) = Regular $ negate x
absBounds :: (Num a,Ord a) => Bounds a -> Bounds a
absBounds = fmap abs'
where
abs' (l,u)
| l >= 0 = (l,u)
| u >= 0 = (0,u)
| otherwise = (abs u,abs l)
signumBounds :: (Num a,Ord a) => Bounds a -> Bounds a
signumBounds = sign False False False
where
sign True True True _ = [(-1,1)]
sign True True False [] = [(-1,0)]
sign True False True [] = [(-1,-1),(1,1)]
sign True False False [] = [(-1,-1)]
sign False True True [] = [(0,1)]
sign False True False [] = [(0,0)]
sign False False True [] = [(1,1)]
sign False False False [] = []
sign hasN hasZ hasP ((l,u):xs)
= case compare l 0 of
LT -> case compare u 0 of
LT -> sign True hasZ hasP xs
EQ -> sign True True hasP xs
GT -> sign True True True xs
EQ -> case compare u 0 of
EQ -> sign hasN True hasP xs
GT -> sign hasN True True xs
GT -> sign hasN hasZ True xs
instance Num (Range IntType) where
(+) r1 r2 = fromBounds int $ addBounds 0 (+) Nothing (toBounds r1) (toBounds r2)
(-) r1 r2 = fromBounds int $ subBounds 0 (-) Nothing (toBounds r1) (toBounds r2)
(*) r1 r2 = fromBounds int $ multBounds 0 (*) div Nothing (toBounds r1) (toBounds r2)
negate r = fromBounds int $ negBounds negate (toBounds r)
abs r = fromBounds int $ absBounds (toBounds r)
signum r = fromBounds int $ signumBounds (toBounds r)
fromInteger x = IntRange (False,[x,x])
instance TL.KnownNat bw => Num (Range (BitVecType bw)) where
(+) r1@(BitVecRange bw _) r2 = fromBounds (bitvec bw) $ addBounds (BitVecValue 0 bw) bvAdd (Just maxBound) (toBounds r1) (toBounds r2)
(-) r1@(BitVecRange bw _) r2 = fromBounds (bitvec bw) $ subBounds (BitVecValue 0 bw) bvSub (Just maxBound) (toBounds r1) (toBounds r2)
(*) r1@(BitVecRange bw _) r2 = fromBounds (bitvec bw) $ multBounds (BitVecValue 0 bw) bvMul bvDiv (Just maxBound) (toBounds r1) (toBounds r2)
negate r@(BitVecRange bw _) = fromBounds (bitvec bw) $ negBounds negate (toBounds r)
abs r@(BitVecRange bw _) = fromBounds (bitvec bw) $ absBounds (toBounds r)
signum r@(BitVecRange bw _) = fromBounds (bitvec bw) $ signumBounds (toBounds r)
fromInteger x = withBW $ \w -> BitVecRange (bw w) [(x,x)]
betweenBounds :: Ord a => Bounds a -> Bounds a -> Bounds a
betweenBounds b1 b2 = [ (min l1 l2,max u1 u2)
| (l1,u1) <- b1, (l2,u2) <- b2 ]
betweenRange :: Range tp -> Range tp -> Range tp
betweenRange r1 r2 = fromBounds (rangeType r1) $ betweenBounds (toBounds r1) (toBounds r2)
rangeFromTo :: Value tp -> Value tp -> Range tp
rangeFromTo from to = fromBounds (getType from) [(Regular from,Regular to)]
rangeFrom :: Value tp -> Range tp
rangeFrom from = fromBounds (getType from) [(Regular from,PosInfinity)]
rangeTo :: Value tp -> Range tp
rangeTo to = fromBounds (getType to) [(NegInfinity,Regular to)]
rangeAdd :: Range tp -> Range tp -> Range tp
rangeAdd r1@(IntRange {}) r2 = fromBounds int $ addBounds 0 (+) Nothing (toBounds r1) (toBounds r2)
rangeAdd r1@(BitVecRange bw _) r2 = fromBounds (bitvec bw) $ addBounds (BitVecValue 0 bw) bvAdd (Just $ bvMaxValue False (BitVecRepr bw)) (toBounds r1) (toBounds r2)
rangeMult :: Range tp -> Range tp -> Range tp
rangeMult r1@(IntRange {}) r2 = fromBounds int $ multBounds 0 (*) div Nothing (toBounds r1) (toBounds r2)
rangeMult r1@(BitVecRange bw _) r2 = fromBounds (bitvec bw) $ multBounds (BitVecValue 0 bw) bvMul bvDiv (Just $ bvMaxValue False (BitVecRepr bw)) (toBounds r1) (toBounds r2)
rangeNeg :: Range tp -> Range tp
rangeNeg r@(IntRange {}) = fromBounds int $ negBounds negate $ toBounds r
rangeNeg r@(BitVecRange bw _) = fromBounds (bitvec bw) $ negBounds bvNegate $ toBounds r
rangeDiv :: Range tp -> Range tp -> Range tp
rangeDiv r1@(IntRange {}) r2 = fromBounds int $ divBounds 0 (-1) div (toBounds r1) (toBounds r2)
rangeDiv r1@(BitVecRange bw _) r2 = fromBounds (bitvec bw) $
divBounds (BitVecValue 0 bw) (BitVecValue (2^(bwSize bw-1)) bw) bvDiv
(toBounds r1) (toBounds r2)
rangeMod :: Range tp -> Range tp -> Range tp
rangeMod r1@(IntRange {}) r2 = fromBounds int $ modBounds 0 mod (toBounds r1) (toBounds r2)
rangeMod r1@(BitVecRange bw _) r2 = fromBounds (bitvec bw) $
modBounds (BitVecValue 0 bw) bvMod
(toBounds r1) (toBounds r2)
instance (Composite a,GShow e) => Show (ByteRead a e) where
showsPrec p rd = showParen (p>10) $
showString "ByteRead { overreads = " .
showListWith (\(off,(obj,c))
-> showsPrec 11 off . showString " -> " .
compShow 0 obj . showChar '{' .
gshowsPrec 0 c . showChar '}') (Map.toList $ overreads rd) .
showString ", readOutside = " .
(case readOutside rd of
Nothing -> showString "Nothing"
Just c -> showString "Just " . gshowsPrec 11 c) .
showString ", fullRead = " .
(case fullRead rd of
Nothing -> showString "Nothing"
Just c -> showString "Just " . compShow 11 c) .
showString ", readImprecision = " .
(case readImprecision rd of
Nothing -> showString "Nothing"
Just c -> showString "Just " . gshowsPrec 11 c) .
showString " }"
instance (Composite a,Composite b,GShow e) => Show (ByteWrite a b e) where
showsPrec p wr = showParen (p>10) $
showString "ByteWrite { overwrite = " .
showListWith (\(obj,c)
-> compShow 0 obj . showChar '{' .
gshowsPrec 0 c . showChar '}') (overwrite wr) .
showString ", writeOutside = " .
(case writeOutside wr of
Nothing -> showString "Nothing"
Just c -> showString "Just " . gshowsPrec 11 c) .
showString ", fullWrite = " .
(case fullWrite wr of
Nothing -> showString "Nothing"
Just c -> showString "Just " . compShow 11 c) .
showString ", writeImprecision = " .
(case writeImprecision wr of
Nothing -> showString "Nothing"
Just c -> showString "Just " . gshowsPrec 11 c) .
showString " }"
instance GEq Range where
geq (BoolRange f1 t1) (BoolRange f2 t2)
= if f1==f2 && t1==t2
then Just Refl
else Nothing
geq (IntRange r1) (IntRange r2)
= if r1==r2
then Just Refl
else Nothing
geq (BitVecRange bw1 r1) (BitVecRange bw2 r2) = do
Refl <- geq bw1 bw2
if r1==r2
then return Refl
else Nothing
geq _ _ = Nothing
instance GCompare Range where
gcompare (BoolRange f1 t1) (BoolRange f2 t2)
= case compare (f1,t1) (f2,t2) of
EQ -> GEQ
LT -> GLT
GT -> GGT
gcompare (BoolRange _ _) _ = GLT
gcompare _ (BoolRange _ _) = GGT
gcompare (IntRange r1) (IntRange r2) = case compare r1 r2 of
EQ -> GEQ
LT -> GLT
GT -> GGT
gcompare (IntRange _) _ = GLT
gcompare _ (IntRange _) = GGT
gcompare (BitVecRange bw1 r1) (BitVecRange bw2 r2) = case gcompare bw1 bw2 of
GEQ -> case compare r1 r2 of
EQ -> GEQ
LT -> GLT
GT -> GGT
GLT -> GLT
GGT -> GGT
| hguenther/smtlib2 | extras/composite/Language/SMTLib2/Composite/Domains.hs | gpl-3.0 | 57,849 | 1,201 | 27 | 17,806 | 23,887 | 12,388 | 11,499 | -1 | -1 |
-- | CodeUI textxs
{-# OPTIONS -O0 #-}
{-# LANGUAGE TemplateHaskell, DerivingVia #-}
module Lamdu.I18N.CodeUI where
import qualified Control.Lens as Lens
import qualified Data.Aeson.TH.Extended as JsonTH
import GUI.Momentu.Animation.Id (ElemIds)
import Lamdu.Prelude
data CodeUI a = CodeUI
{ _hidden :: a
, _shown :: a
, _hide :: a
, _show :: a
, _createNew :: a
, _new :: a
, _newAndJumpToNextEntry :: a
, _newName :: a
, _apply :: a
, _lambda :: a
, _completion :: a
, _rename :: a
, _renameTag :: a
, _doneRenaming :: a
, _changeImportedName :: a
, _doneChangingImportedName :: a
, _pane :: a
, _nominal :: a
, _deleteToNominal :: a
, _tag :: a
, _record :: a
, _injectValue :: a
, _caseLabel :: a
, _addField :: a
, _deleteField :: a
, _addAlt :: a
, _deleteAlt :: a
, _open :: a
, _close :: a
, _shrinkLambdaParams :: a
, _expandLambdaParams :: a
, _moveDown :: a
, _moveUp :: a
, _presentationMode :: a
, _pModeVerbose :: a
, _pModeOperator :: a
, _jsException :: a
, _jsReachedAHole :: a
, _jsStaleDep :: a
, _jsUnhandledCase :: a
, _inline :: a
, _transform :: a
, _replace :: a
, _replaceParent :: a
, _applyOperator :: a
, _swapOperatorArgs :: a
, _add :: a
, _letClause :: a
, _detach :: a
, _literal :: a
, _literalText :: a
, _literalNumber :: a
, _literalBytes :: a
, _startEditing :: a
, _stopEditing :: a
, _nameFirstParameter :: a
, _parameter :: a
, _addParameter :: a
, _addNextParameter :: a
, _deleteParameter :: a
, _deleteParameterBackwards :: a
, _moveBefore :: a
, _moveAfter :: a
, _fragment :: a
, _heal :: a
, _setToHole :: a
, _negate :: a
, _value :: a
, _evaluation :: a
, _scope :: a
, _name :: a
, _abbreviation :: a
, _disambiguationText :: a
, _symbolType :: a
, _noSymbol :: a
, _symbol :: a
, _directionalSymbol :: a
, _leftToRightSymbol :: a
, _rightToLeftSymbol :: a
, _typeOperatorHere :: a
, _injectSection :: a
, _order :: a
, _opaque :: a
}
deriving stock (Generic, Generic1, Eq, Functor, Foldable, Traversable)
deriving anyclass ElemIds
deriving Applicative via (Generically1 CodeUI)
Lens.makeLenses ''CodeUI
JsonTH.derivePrefixed "_" ''CodeUI
| Peaker/lamdu | src/Lamdu/I18N/CodeUI.hs | gpl-3.0 | 2,460 | 0 | 8 | 762 | 622 | 405 | 217 | -1 | -1 |
import Data.List
import System.Environment
import Control.Monad (when)
solveRPN :: [String] -> Float
solveRPN = head . foldl foldingFunc []
where foldingFunc (x:y:ys) "*" = x * y:ys
foldingFunc (x:y:ys) "/" = x / y:ys
foldingFunc (x:y:ys) "-" = x - y:ys
foldingFunc (x:y:ys) "+" = x + y:ys
foldingFunc xs "sum" = [sum xs]
foldingFunc (x:xs) "ln" = log x:xs
foldingFunc (x:y:ys) "^" = (y ** x):ys
foldingFunc xs numStr = read numStr:xs
main = do
args <- getArgs
if null args then
do
putStrLn "Reverse Polish Notation Calculator"
putStrLn "Operators suported: * / - + sum ln ^"
putStrLn "Options:"
putStrLn "\t--help: for help message"
else
do
when (head args == "--help") $ do
putStrLn "Operators suported: * / - + sum ln ^"
putStrLn "Don't forget to escape \\* when using command line"
print $ solveRPN args
| jonfk/rpn-calc | src/Main.hs | gpl-3.0 | 971 | 0 | 14 | 302 | 348 | 171 | 177 | 26 | 8 |
Store (set (set a s)) (get (set a s)) = Store (set a) s | hmemcpy/milewski-ctfp-pdf | src/content/3.9/code/haskell/snippet13.hs | gpl-3.0 | 55 | 1 | 9 | 13 | 51 | 24 | 27 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Database.Design.Ampersand.Output.ToPandoc.ChapterDiagnosis where
import Database.Design.Ampersand.Output.ToPandoc.SharedAmongChapters
import Data.List(nub,partition)
import Data.Maybe(isJust)
chpDiagnosis :: FSpec -> (Blocks,[Picture])
chpDiagnosis fSpec
= ( chptHeader (fsLang fSpec) Diagnosis
<> para ( (str.l) (NL "Dit hoofdstuk geeft een analyse van het Ampersand-script van "
,EN "This chapter provides an analysis of the Ampersand script of ")
<> (emph.singleQuoted.str.name) fSpec
<> str ". "
<> (str.l) (NL $ "Deze analyse is bedoeld voor de auteur(s) van dit script. "
++ "Op basis hiervan kunnen zij het script completeren en mogelijke tekortkomingen verbeteren."
,EN $ "This analysis is intended for the author(s) of this script. "
++ "It can be used to complete the script or to improve possible flaws.")
)
<> roleomissions -- tells which role-rule, role-interface, and role-relation assignments are missing
<> roleRuleTable -- gives an overview of rule-rule assignments
<> missingConceptDefs -- tells which concept definitions have been declared without a purpose
<> missingRels -- tells which relations have been declared without a purpose and/or without a meaning
<> unusedConceptDefs -- tells which concept definitions are not used in any relation
<> relsNotUsed -- tells which relations are not used in any rule
<> missingRules -- tells which rule definitions are missing
<> ruleRelationRefTable -- table that shows percentages of relations and rules that have references
<> processrulesInPatterns --
<> wipReport -- sums up the work items (i.e. the violations of process rules)
<> violationReport -- sums up the violations caused by the population of this script.
, pics )
where
-- shorthand for easy localizing
l :: LocalizedStr -> String
l lstr = localize (fsLang fSpec) lstr
roleRuleTable :: Blocks
roleRuleTable
| null ruls = mempty
| null (fRoles fSpec) =
para ( (emph.str.upCap.name) fSpec
<> (str.l) (NL " specificeert geen rollen. "
,EN " does not define any roles. ")
)
| otherwise =
case (filter isSignal) ruls of
[] -> para ( (emph.str.upCap.name) fSpec
<> (str.l) (NL " kent geen procesregels. "
,EN " does not define any process rules. ")
)
sigs -> (para ( (emph.str.upCap.name) fSpec
<> (str.l) (NL " kent regels aan rollen toe. "
,EN " assigns rules to roles. ")
<> (str.l) (NL "De volgende tabel toont welke regels door een bepaalde rol kunnen worden gehandhaafd."
,EN "The following table shows the rules that are being maintained by a given role.")
)
) <>
( table -- No caption:
mempty
-- Alignment:
( (AlignLeft,0.4)
: replicate (length.fRoles $ fSpec) (AlignLeft, 0.6/(fromIntegral.length.fRoles $ fSpec))
)
-- Header row:
( (plain.str.l) (NL "Regel", EN "Rule")
: map (plain.str.name) (fRoles fSpec)
)
-- Content rows:
[ (plain.str.name) rul
:[f rol rul | rol<-fRoles fSpec]
| rul<-sigs
]
)
where
ruls = filter inScopeRule . filter isSignal . vrules $ fSpec
f :: Role -> Rule -> Blocks
f rol rul | (rol,rul) `elem` maintained = (plain.emph.str.l) (NL "ja",EN "yes")
| (rol,rul) `elem` dead = (plain.emph.str.l) (NL "nee",EN "no")
| (rol,rul) `elem` fRoleRuls fSpec = (plain.emph.str.l) (NL "part",EN "part")
| otherwise = mempty
maintained -- (r,rul) `elem` maintained means that r can maintain rul without restrictions.
= [ (role,rul)
| (role,rul)<-fRoleRuls fSpec
, and (map (mayedit role) (relsUsedIn rul))
]
mayedit :: Role -> Declaration -> Bool
mayedit role decl = decl `elem` ((snd.unzip) (filter (\x -> role == fst x) (fRoleRels fSpec)))
dead -- (r,rul) `elem` dead means that r cannot maintain rul without restrictions.
= [ (role,rul)
| (role,rul)<-fRoleRuls fSpec
, (not.or) (map (mayedit role) (relsUsedIn rul))
]
roleomissions :: Blocks
roleomissions
= if (null . filter inScopePat . vpatterns) fSpec
then mempty
else (if (null.fRoleRuls) fSpec && (not.null.vrules) fSpec
then plain ( (emph.str.upCap.name) fSpec
<> (str.l) (NL " kent geen regels aan rollen toe. "
,EN " does not assign rules to roles. ")
<> (str.l) (NL "Een generieke rol, User, zal worden gedefinieerd om al het werk te doen wat in het bedrijfsproces moet worden uitgevoerd."
,EN "A generic role, User, will be defined to do all the work that is necessary in the business process.")
)
else mempty
)<>
(if null (fRoleRels fSpec) && (not.null.fRoleRuls) fSpec ||(not.null.fRoleRels) fSpec
then plain ( (emph.str.upCap.name) fSpec
<> (str.l) (NL " specificeert niet welke rollen de inhoud van welke relaties mogen wijzigen. "
,EN " does not specify which roles may change the contents of which relations. ")
)
else mempty
)
missingConceptDefs :: Blocks
missingConceptDefs =
case missing of
[] -> if (null.concs) fSpec
then mempty
else (para.str.l) (NL "Alle concepten in dit document zijn voorzien van een bestaansreden."
,EN "All concepts in this document have been provided with a purpose.")
[c] -> para ( (str.l) (NL "De bestaansreden van concept "
,EN "The concept ")
<> (singleQuoted.str.name) c
<> (str.l) (NL " is niet gedocumenteerd."
,EN " remains without a purpose.")
)
xs -> para ( (str.l) (NL "De bestaansreden van de concepten: "
,EN "Concepts ")
<> commaPandocAnd (fsLang fSpec) (map (str.name) xs)
<> (str.l) (NL " is niet gedocumenteerd."
,EN " remain without a purpose.")
)
where missing = [c | c <-ccs
, cd <- concDefs fSpec c
, null (purposesDefinedIn fSpec (fsLang fSpec) cd)
]++
[c | c <-ccs, null (concDefs fSpec c)]
ccs = concs [ d | d<-vrels fSpec, null (themes fSpec)||decpat d `elem` themes fSpec] -- restrict if the documentation is partial.
unusedConceptDefs :: Blocks
unusedConceptDefs
= case [cd | cd <-cDefsInScope fSpec, name cd `notElem` map name (concs fSpec)] of
[] -> if (null.cDefsInScope) fSpec
then mempty
else para.str.l $
(NL "Alle concepten, die in dit document zijn voorzien van een definitie, worden gebruikt in relaties."
,EN "All concepts defined in this document are used in relations.")
[c] -> para ( (str.l) (NL "Het concept ",EN "The concept ")
<> singleQuoted (str (name c))
<> (str.l) (NL " is gedefinieerd, maar wordt niet gebruikt."
,EN " is defined, but isn't used.")
)
xs -> para ( (str.l) (NL "De concepten: ", EN "Concepts ")
<> commaPandocAnd (fsLang fSpec) (map (str . name) xs)
<> (str.l) (NL " zijn gedefinieerd, maar worden niet gebruikt."
,EN " are defined, but not used.")
)
missingRels :: Blocks
missingRels
= case bothMissing ++ purposeOnlyMissing ++ meaningOnlyMissing of
[] -> (para.str.l) (NL "Alle relaties in dit document zijn voorzien van zowel een reden van bestaan (purpose) als een betekenis (meaning)."
,EN "All relations in this document have been provided with a purpose as well as a meaning.")
_ ->(case bothMissing of
[] -> mempty
[d] -> para ( (str.l) (NL "Van de relatie ",EN "The relation ")
<> showDcl d
<> (str.l) (NL " ontbreekt zowel de betekenis (meaning) als de reden van bestaan (purpose)."
,EN " lacks both a purpose as well as a meaning.")
)
ds -> para ( (str.l) (NL "Van de relaties ",EN "The relations ")
<> commaPandocAnd (fsLang fSpec) (map showDcl ds)
<>(str.l) (NL " ontbreken zowel de betekenis (meaning) als de reden van bestaan (purpose)."
,EN " all lack both a purpose and a meaning.")
)
)<>
(case purposeOnlyMissing of
[] -> mempty
[d] -> para ( (str.l) (NL "De reden waarom relatie ",EN "The purpose of relation ")
<> showDcl d
<> (str.l) (NL " bestaat wordt niet uitgelegd."
,EN " remains unexplained.")
)
ds -> para ( (str.l) (NL "Relaties ",EN "The purpose of relations ")
<> commaPandocAnd (fsLang fSpec) (map showDcl ds)
<>(str.l) (NL " zijn niet voorzien van een reden van bestaan (purpose)."
,EN " is not documented.")
)
)<>
(case meaningOnlyMissing of
[] -> mempty
[d] -> para ( (str.l) (NL "De betekenis van relatie ",EN "The meaning of relation ")
<> showDcl d
<> (str.l) (NL " is niet gedocumenteerd."
,EN " is not documented.")
)
ds -> para ( (str.l) (NL "De betekenis van relaties ",EN "The meaning of relations ")
<> commaPandocAnd (fsLang fSpec) (map showDcl ds)
<>(str.l) (NL " zijn niet gedocumenteerd."
,EN " is not documented.")
)
)
where bothMissing, purposeOnlyMissing, meaningOnlyMissing :: [Declaration]
bothMissing = filter (not . hasPurpose) . filter (not . hasMeaning) $ decls
purposeOnlyMissing = filter (not . hasPurpose) . filter ( hasMeaning) $ decls
meaningOnlyMissing = filter ( hasPurpose) . filter (not . hasMeaning) $ decls
decls = allDecls fSpec -- A restriction on only themes that the user wants the document for is not supported,
-- because it is possible that declarations from other themes are required in the
-- generated document.
showDcl = math . showMath . EDcD
hasPurpose :: Motivated a => a -> Bool
hasPurpose = not . null . purposesDefinedIn fSpec (fsLang fSpec)
hasMeaning :: Meaning a => a -> Bool
hasMeaning = isJust . meaning (fsLang fSpec)
relsNotUsed :: Blocks
pics :: [Picture]
(relsNotUsed,pics)
= (
(case notUsed of
[] -> ( if (null.relsMentionedIn.vrules) fSpec
then mempty
else (para .str.l)
(NL "Alle relaties in dit document worden in één of meer regels gebruikt."
,EN "All relations in this document are being used in one or more rules.")
)
[r] -> para ( (str.l) (NL "De relatie ",EN "Relation ")
<> r
<> (str.l) (NL " wordt in geen enkele regel gebruikt. "
,EN " is not being used in any rule. ")
)
rs -> para ( (str.l) (NL "Relaties ", EN "Relations ")
<> commaPandocAnd (fsLang fSpec) rs
<> (str.l) (NL " worden niet gebruikt in regels. "
,EN " are not used in any rule. ")
)
) <>
( case pictsWithUnusedRels of
[pict] -> para ( (str.l) (NL "Figuur ", EN "Figure ")
<> xRefReference (getOpts fSpec) pict
<> (str.l) (NL " geeft een conceptueel diagram met alle relaties."
,EN " shows a conceptual diagram with all relations.")
) <>
plain((showImage (getOpts fSpec)) pict)
picts -> mconcat
[ para ( (str.l) (NL "Figuur ", EN "Figure ")
<> xRefReference (getOpts fSpec) pict
<> (str.l) (NL " geeft een conceptueel diagram met alle relaties die gedeclareerd zijn in "
,EN " shows a conceptual diagram with all relations declared in ")
<> (singleQuoted.str.name) pat <> "."
)
<>(plain . showImage (getOpts fSpec)) pict
| (pict,pat)<-zip picts pats
]
)
, pictsWithUnusedRels -- draw the conceptual diagram
)
where notUsed :: [Inlines]
notUsed = [(math . showMath) (EDcD d)
| d@Sgn{} <- nub (relsInThemes fSpec) -- only signal relations that are used or defined in the selected themes
, decusr d
, d `notElem` (relsMentionedIn . vrules) fSpec
]
pats = [ pat | pat<-vpatterns fSpec
, null (themes fSpec) || name pat `elem` themes fSpec -- restrict if the documentation is partial.
, (not.null) (relsDefdIn pat>-relsUsedIn pat) ]
pictsWithUnusedRels = [makePicture fSpec (PTDeclaredInPat pat) | pat<-pats ]
missingRules :: Blocks
missingRules
= case if null (themes fSpec)
then vrules fSpec
else concat [udefrules pat | pat<-vpatterns fSpec, name pat `elem` themes fSpec] of
[] -> mempty
ruls ->
( if all hasMeaning ruls && all hasPurpose ruls
then (para.str.l) (NL "Alle regels in dit document zijn voorzien van een uitleg."
,EN "All rules in this document have been provided with a meaning and a purpose.")
else ( case filter (not.hasPurpose) ruls of
[] -> mempty
rls -> (para.str.l) (NL "Van de volgende regels is de bestaansreden niet uitgelegd:"
,EN "Rules are defined without documenting their purpose:")
<> bulletList [ (para.emph.str.name) r
<> (plain.str.show.origin) r
| r <- rls]
) <>
( case filter (not.hasMeaning) ruls of
[] -> mempty
rls -> (para.str.l) (NL "Van de volgende regels is de betekenis uitgelegd in taal die door de computer is gegenereerd:"
,EN "Rules are defined, the meaning of which is documented by means of computer generated language:")
<> bulletList [ (para.emph.str.name) r
<> (plain.str.show.origin) r
| r <- rls]
)
)
ruleRelationRefTable :: Blocks
ruleRelationRefTable =
(para.str.l) (NL $ "Onderstaande tabel bevat per thema (dwz. proces of patroon) tellingen van het aantal relaties en regels, " ++
"gevolgd door het aantal en het percentage daarvan dat een referentie bevat. Relaties die in meerdere thema's " ++
"gedeclareerd worden, worden ook meerdere keren geteld."
,EN $ "The table below shows for each theme (i.e. process or pattern) the number of relations and rules, followed " ++
" by the number and percentage that have a reference. Relations declared in multiple themes are counted multiple " ++
" times."
)
<>(table -- No caption:
mempty
-- Alignment:
((AlignLeft,0.4) : replicate 6 (AlignCenter,0.1))
-- Headers
(map (plain.str.l) [ (NL "Thema" , EN "Theme")
, (NL "Relaties" , EN "Relations")
, (NL "Met referentie", EN "With reference")
, (NL "%" , EN "%")
, (NL "Regels" , EN "Rules")
, (NL "Gehele context", EN "Entire context")
, (NL "%" , EN "%")
]
)
-- Content rows
( map mkTableRowPat (vpatterns fSpec)
++ [mempty] -- empty row
++ [mkTableRow (l (NL "Gehele context", EN "Entire context")) (filter decusr $ vrels fSpec) (vrules fSpec)]
)
)
where mkTableRow :: String -- The name of the pattern / fSpec
-> [Declaration] --The user-defined relations of the pattern / fSpec
-> [Rule] -- The user-defined rules of the pattern / fSpec
-> [Blocks]
mkTableRowPat p = mkTableRow (name p) (relsDefdIn p) (udefrules p)
mkTableRow nm rels ruls =
map (plain.str) [ nm
, (show.length) rels
, (show.length) (filter hasRef rels)
, showPercentage (length rels) (length.filter hasRef $ rels)
, (show.length) ruls
, (show.length) (filter hasRef ruls)
, showPercentage (length ruls) (length.filter hasRef $ ruls)
]
hasRef :: Motivated a => a -> Bool
hasRef x = maybe False (any ((/=[]).explRefIds)) (purposeOf fSpec (fsLang fSpec) x)
showPercentage x y = if x == 0 then "-" else show (y*100 `div` x)++"%"
processrulesInPatterns :: Blocks
processrulesInPatterns =
para ("TODO: Inleiding bij de rol-regel tabel")
<> if null (fRoleRuls fSpec)
then mempty
else table -- No caption:
mempty
-- Alignment:
( if multProcs
then replicate 4 (AlignLeft,1/4)
else replicate 3 (AlignLeft,1/3)
)
-- Headers:
( [ (plain.str.l) (NL "rol" , EN "role")]
++[ (plain.str.l) (NL "in proces", EN "in process") | multProcs]
++[ (plain.str.l) (NL "regel" , EN "rule")
, (plain.str.l) (NL "uit" , EN "from")
]
)
-- Rows:
[ [ (plain.str.name) rol]
++[ (plain.str.r_env) rul | multProcs]
++[ (plain.str.name) rul
, (plain.str.r_env) rul
]
| (rol,rul)<-fRoleRuls fSpec]
where multProcs = length procsInScope>1
procsInScope = filter inScopePat (vpatterns fSpec)
wipReport :: Blocks
wipReport
= case popwork of
[] -> (para.str.l) (NL "De populatie in dit script beschrijft geen onderhanden werk. "
,EN "The population in this script does not specify any work in progress. ")
[(r,ps)] -> para ( (str.l) (NL"Regel ",EN "Rule")
<> quoterule r
<>(str.l) (NL $ " laat " ++count Dutch (length ps) "taak"++" zien."
,EN $ " shows "++count English (length ps) "task"++".")
)
_ -> (para.str.l) (NL "Dit script bevat onderhanden werk. De volgende tabellen geven details met regelnummers in de oorspronkelijk script-bestanden."
,EN "This script contains work in progress. The following tables provide details with line numbers from the original script files.")
<> if null popwork
then mempty
else table -- No caption:
mempty
-- Alignment:
((AlignLeft,1/3): replicate 2 (AlignRight,1/3))
--Header:
(map (plain.str.l)
[ (NL "regel" ,EN "rule" )
, (NL "locatie",EN "location" )
, (NL "#taken" ,EN "#tasks" )
])
-- Rows:
[ map (plain.str)
[ name r
, (show.origin) r
, (show.length) ps
]
| (r,ps)<-popwork
]
<>
-- the tables containing the actual work in progress population
mconcat
[ para ( (str.l) (NL "Regel", EN "Rule")
<> quoterule r
<> xRefTo (XRefNaturalLanguageRule r)
<> (str.l) (NL " luidt: ", EN "says: ")
)
<> fromList (meaning2Blocks (fsLang fSpec) r)
<> para ( (str.l) (NL "Deze regel bevat nog werk (voor "
,EN "This rule contains work (for ")
<>commaPandocOr (fsLang fSpec) (map (str.name) (nub [rol | (rol, rul)<-fRoleRuls fSpec, r==rul]))
<>")"
<> if length ps == 1
then (str.l) (NL ", te weten ", EN " by ")
<> oneviol r (head ps)
<> "."
else (str.l) (NL $ ". De volgende tabel laat de "++(if length ps>10 then "eerste tien " else "")++"items zien die aandacht vragen."
,EN $ "The following table shows the "++(if length ps>10 then "first ten " else "")++"items that require attention.")
)
<> if length ps <= 1
then mempty -- iff there is a single violation, it is already shown in the previous paragraph
else violtable r ps
| (r,ps)<- popwork ]
where
-- text r
-- = if null expls
-- then explains2Blocks (autoMeaning (fsLang fSpec) r)
-- else expls
-- where expls = [Plain (block++[Space]) | Means l econt<-rrxpl r, l==Just (fsLang fSpec) || l==Nothing, Para block<-econt]
quoterule r
= if null (name r)
then (str.l) (NL $ "op "++show (origin r)
,EN $ "at "++show (origin r))
else (singleQuoted.str.name) r
oneviol :: Rule -> AAtomPair -> Inlines
oneviol r p
= if source r==target r && apLeft p==apRight p
then singleQuoted ( (str.name.source) r
<>(str.showValADL.apLeft) p
)
else "(" <> (str.name.source) r <> (str.showValADL.apLeft) p
<> ", " <> (str.name.target) r <> (str.showValADL.apRight) p
<> ")"
popwork :: [(Rule,[AAtomPair])]
popwork = [(r,ps) | (r,ps) <- allViolations fSpec, isSignal r, inScopeRule r]
violationReport :: Blocks
violationReport =
(para (case (invariantViolations, processViolations) of
([] , [] ) -> (str.l) (NL "De populatie in dit script overtreedt geen regels. "
,EN "The population in this script violates no rule. ")
(iVs, pVs) -> (str.l) (NL "De populatie in dit script overtreedt "
,EN "The population in this script violates ")
<>(str.show.length) iVs
<>(str.l) (NL $ " invariant"++(if length iVs == 1 then "" else "en")++" en "
,EN $ " invariant"++(if length iVs == 1 then "" else "s")++" and ")
<>(str.show.length) pVs
<>(str.l) (NL $ " procesregel" ++if length pVs == 1 then "" else "s"++"."
,EN $ " process rule"++if length pVs == 1 then "" else "s"++"."
)
)
)
<> bulletList (map showViolatedRule invariantViolations)
<> bulletList (map showViolatedRule processViolations)
where
(processViolations,invariantViolations) = partition (isSignal.fst) (allViolations fSpec)
showViolatedRule :: (Rule,[AAtomPair]) -> Blocks
showViolatedRule (r,ps)
= (para.emph)
( (str.l) (NL "Regel ", EN "Rule ")
<>(str.name) r
)
<> para( (if isSignal r
then (str.l) (NL "Totaal aantal taken: " ,EN "Total number of work items: ")
else (str.l) (NL "Totaal aantal overtredingen: ",EN "Total number of violations: ")
)
<>(str.show.length) ps
)
<> table -- Caption
(if isSignal r
then ( (str.l) (NL "Openstaande taken voor " ,EN "Tasks yet to be performed by ")
<>(commaPandocOr (fsLang fSpec) (map (str.name) (nub [rol | (rol, rul)<-fRoleRuls fSpec, r==rul])))
)
else ( (str.l) (NL "Overtredingen van invariant ",EN "Violations of invariant ")
<>(str.name) r
)
)
-- Alignment:
(replicate 2 (AlignLeft,1/2))
-- Headers:
[(para.strong.text.name.source.rrexp) r
,(para.strong.text.name.target.rrexp) r
]
-- Rows:
[ [(para.text.showValADL.apLeft) p
,(para.text.showValADL.apRight) p
]
| p<- ps]
violtable :: Rule -> [AAtomPair] -> Blocks
violtable r ps
= if hasantecedent r && isIdent (antecedent r) -- note: treat 'isIdent (consequent r) as binary table.
then table -- No caption:
mempty
-- Alignment:
[(AlignLeft,1.0)]
-- Header:
[(plain.str.name.source) r]
-- Data rows:
[ [(plain.str.showValADL.apLeft) p]
| p <-take 10 ps --max 10 rows
]
else table -- No caption:
mempty
-- Alignment:
(replicate 2 (AlignLeft,1/2))
-- Header:
[(plain.str.name.source) r , (plain.str.name.target) r ]
-- Data rows:
[ [(plain.str.showValADL.apLeft) p,(plain.str.showValADL.apRight) p]
| p <-take 10 ps --max 10 rows
]
inScopePat :: Pattern -> Bool
inScopePat x = null (themes fSpec) || name x `elem` themes fSpec -- restrict if this is partial documentation.
inScopeRule :: Rule -> Bool
inScopeRule r =
or [ null (themes fSpec)
, r `elem` concat [udefrules pat | pat<-vpatterns fSpec, name pat `elem` themes fSpec]
]
| 4ZP6Capstone2015/ampersand | src/Database/Design/Ampersand/Output/ToPandoc/ChapterDiagnosis.hs | gpl-3.0 | 28,814 | 1 | 27 | 12,233 | 6,647 | 3,468 | 3,179 | 423 | 47 |
{-# 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.DFAReporting.AdvertiserLandingPages.List
-- 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)
--
-- Retrieves a list of landing pages.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.advertiserLandingPages.list@.
module Network.Google.Resource.DFAReporting.AdvertiserLandingPages.List
(
-- * REST Resource
AdvertiserLandingPagesListResource
-- * Creating a Request
, advertiserLandingPagesList
, AdvertiserLandingPagesList
-- * Request Lenses
, alplXgafv
, alplUploadProtocol
, alplAccessToken
, alplCampaignIds
, alplSearchString
, alplUploadType
, alplIds
, alplProFileId
, alplSortOrder
, alplPageToken
, alplSortField
, alplSubAccountId
, alplAdvertiserIds
, alplArchived
, alplMaxResults
, alplCallback
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.advertiserLandingPages.list@ method which the
-- 'AdvertiserLandingPagesList' request conforms to.
type AdvertiserLandingPagesListResource =
"dfareporting" :>
"v3.5" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"advertiserLandingPages" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParams "campaignIds" (Textual Int64) :>
QueryParam "searchString" Text :>
QueryParam "uploadType" Text :>
QueryParams "ids" (Textual Int64) :>
QueryParam "sortOrder"
AdvertiserLandingPagesListSortOrder
:>
QueryParam "pageToken" Text :>
QueryParam "sortField"
AdvertiserLandingPagesListSortField
:>
QueryParam "subaccountId" (Textual Int64) :>
QueryParams "advertiserIds" (Textual Int64)
:>
QueryParam "archived" Bool :>
QueryParam "maxResults" (Textual Int32)
:>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
AdvertiserLandingPagesListResponse
-- | Retrieves a list of landing pages.
--
-- /See:/ 'advertiserLandingPagesList' smart constructor.
data AdvertiserLandingPagesList =
AdvertiserLandingPagesList'
{ _alplXgafv :: !(Maybe Xgafv)
, _alplUploadProtocol :: !(Maybe Text)
, _alplAccessToken :: !(Maybe Text)
, _alplCampaignIds :: !(Maybe [Textual Int64])
, _alplSearchString :: !(Maybe Text)
, _alplUploadType :: !(Maybe Text)
, _alplIds :: !(Maybe [Textual Int64])
, _alplProFileId :: !(Textual Int64)
, _alplSortOrder :: !AdvertiserLandingPagesListSortOrder
, _alplPageToken :: !(Maybe Text)
, _alplSortField :: !AdvertiserLandingPagesListSortField
, _alplSubAccountId :: !(Maybe (Textual Int64))
, _alplAdvertiserIds :: !(Maybe [Textual Int64])
, _alplArchived :: !(Maybe Bool)
, _alplMaxResults :: !(Textual Int32)
, _alplCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AdvertiserLandingPagesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'alplXgafv'
--
-- * 'alplUploadProtocol'
--
-- * 'alplAccessToken'
--
-- * 'alplCampaignIds'
--
-- * 'alplSearchString'
--
-- * 'alplUploadType'
--
-- * 'alplIds'
--
-- * 'alplProFileId'
--
-- * 'alplSortOrder'
--
-- * 'alplPageToken'
--
-- * 'alplSortField'
--
-- * 'alplSubAccountId'
--
-- * 'alplAdvertiserIds'
--
-- * 'alplArchived'
--
-- * 'alplMaxResults'
--
-- * 'alplCallback'
advertiserLandingPagesList
:: Int64 -- ^ 'alplProFileId'
-> AdvertiserLandingPagesList
advertiserLandingPagesList pAlplProFileId_ =
AdvertiserLandingPagesList'
{ _alplXgafv = Nothing
, _alplUploadProtocol = Nothing
, _alplAccessToken = Nothing
, _alplCampaignIds = Nothing
, _alplSearchString = Nothing
, _alplUploadType = Nothing
, _alplIds = Nothing
, _alplProFileId = _Coerce # pAlplProFileId_
, _alplSortOrder = ALPLSOAscending
, _alplPageToken = Nothing
, _alplSortField = ALPLSFID
, _alplSubAccountId = Nothing
, _alplAdvertiserIds = Nothing
, _alplArchived = Nothing
, _alplMaxResults = 1000
, _alplCallback = Nothing
}
-- | V1 error format.
alplXgafv :: Lens' AdvertiserLandingPagesList (Maybe Xgafv)
alplXgafv
= lens _alplXgafv (\ s a -> s{_alplXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
alplUploadProtocol :: Lens' AdvertiserLandingPagesList (Maybe Text)
alplUploadProtocol
= lens _alplUploadProtocol
(\ s a -> s{_alplUploadProtocol = a})
-- | OAuth access token.
alplAccessToken :: Lens' AdvertiserLandingPagesList (Maybe Text)
alplAccessToken
= lens _alplAccessToken
(\ s a -> s{_alplAccessToken = a})
-- | Select only landing pages that are associated with these campaigns.
alplCampaignIds :: Lens' AdvertiserLandingPagesList [Int64]
alplCampaignIds
= lens _alplCampaignIds
(\ s a -> s{_alplCampaignIds = a})
. _Default
. _Coerce
-- | Allows searching for landing pages by name or ID. Wildcards (*) are
-- allowed. For example, \"landingpage*2017\" will return landing pages
-- with names like \"landingpage July 2017\", \"landingpage March 2017\",
-- or simply \"landingpage 2017\". Most of the searches also add wildcards
-- implicitly at the start and the end of the search string. For example, a
-- search string of \"landingpage\" will match campaigns with name \"my
-- landingpage\", \"landingpage 2015\", or simply \"landingpage\".
alplSearchString :: Lens' AdvertiserLandingPagesList (Maybe Text)
alplSearchString
= lens _alplSearchString
(\ s a -> s{_alplSearchString = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
alplUploadType :: Lens' AdvertiserLandingPagesList (Maybe Text)
alplUploadType
= lens _alplUploadType
(\ s a -> s{_alplUploadType = a})
-- | Select only landing pages with these IDs.
alplIds :: Lens' AdvertiserLandingPagesList [Int64]
alplIds
= lens _alplIds (\ s a -> s{_alplIds = a}) . _Default
. _Coerce
-- | User profile ID associated with this request.
alplProFileId :: Lens' AdvertiserLandingPagesList Int64
alplProFileId
= lens _alplProFileId
(\ s a -> s{_alplProFileId = a})
. _Coerce
-- | Order of sorted results.
alplSortOrder :: Lens' AdvertiserLandingPagesList AdvertiserLandingPagesListSortOrder
alplSortOrder
= lens _alplSortOrder
(\ s a -> s{_alplSortOrder = a})
-- | Value of the nextPageToken from the previous result page.
alplPageToken :: Lens' AdvertiserLandingPagesList (Maybe Text)
alplPageToken
= lens _alplPageToken
(\ s a -> s{_alplPageToken = a})
-- | Field by which to sort the list.
alplSortField :: Lens' AdvertiserLandingPagesList AdvertiserLandingPagesListSortField
alplSortField
= lens _alplSortField
(\ s a -> s{_alplSortField = a})
-- | Select only landing pages that belong to this subaccount.
alplSubAccountId :: Lens' AdvertiserLandingPagesList (Maybe Int64)
alplSubAccountId
= lens _alplSubAccountId
(\ s a -> s{_alplSubAccountId = a})
. mapping _Coerce
-- | Select only landing pages that belong to these advertisers.
alplAdvertiserIds :: Lens' AdvertiserLandingPagesList [Int64]
alplAdvertiserIds
= lens _alplAdvertiserIds
(\ s a -> s{_alplAdvertiserIds = a})
. _Default
. _Coerce
-- | Select only archived landing pages. Don\'t set this field to select both
-- archived and non-archived landing pages.
alplArchived :: Lens' AdvertiserLandingPagesList (Maybe Bool)
alplArchived
= lens _alplArchived (\ s a -> s{_alplArchived = a})
-- | Maximum number of results to return.
alplMaxResults :: Lens' AdvertiserLandingPagesList Int32
alplMaxResults
= lens _alplMaxResults
(\ s a -> s{_alplMaxResults = a})
. _Coerce
-- | JSONP
alplCallback :: Lens' AdvertiserLandingPagesList (Maybe Text)
alplCallback
= lens _alplCallback (\ s a -> s{_alplCallback = a})
instance GoogleRequest AdvertiserLandingPagesList
where
type Rs AdvertiserLandingPagesList =
AdvertiserLandingPagesListResponse
type Scopes AdvertiserLandingPagesList =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient AdvertiserLandingPagesList'{..}
= go _alplProFileId _alplXgafv _alplUploadProtocol
_alplAccessToken
(_alplCampaignIds ^. _Default)
_alplSearchString
_alplUploadType
(_alplIds ^. _Default)
(Just _alplSortOrder)
_alplPageToken
(Just _alplSortField)
_alplSubAccountId
(_alplAdvertiserIds ^. _Default)
_alplArchived
(Just _alplMaxResults)
_alplCallback
(Just AltJSON)
dFAReportingService
where go
= buildClient
(Proxy :: Proxy AdvertiserLandingPagesListResource)
mempty
| brendanhay/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/AdvertiserLandingPages/List.hs | mpl-2.0 | 10,451 | 0 | 28 | 2,767 | 1,622 | 925 | 697 | 231 | 1 |
-- Copyright © 2014 Bart Massey
-- Based on material Copyright © 2013 School of Haskell
-- https://www.fpcomplete.com/school/advanced-haskell/
-- building-a-file-hosting-service-in-yesod
-- This work is made available under the "GNU AGPL v3", as
-- specified the terms in the file COPYING in this
-- distribution.
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Foundation where
import Control.Concurrent.STM
import Data.ByteString.Lazy (ByteString)
import Data.Char
import Data.Default
import Data.Map (Map)
import qualified Data.Map as M
import Text.Hamlet
import Yesod
import Yesod.Default.Util
data Filetype = FiletypeText | FiletypeImage | FiletypeOther
deriving Eq
data FileAssoc = FileAssoc { fileAssocId :: !Int,
fileAssocName :: !String,
fileAssocContents :: !ByteString,
fileAssocMime :: !String,
fileAssocType :: !Filetype }
data App = App { appNextId :: !(TVar Int),
appGalleries :: !(TVar (Map Int FileAssoc)) }
instance Yesod App where
defaultLayout widget = do
let wf = $(widgetFileNoReload def "default-layout")
pageContent <- widgetToPageContent wf
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
mkYesodData "App" $(parseRoutesFile "config/routes")
getFAList :: Handler [FileAssoc]
getFAList = do
state <- getYesod
galleryMap <- liftIO $ readTVarIO $ appGalleries state
return $ M.elems galleryMap
addFile :: App -> FileAssoc -> Handler ()
addFile state op = do
faid <- getNextId state
let op' = op { fileAssocId = faid }
liftIO $ atomically $
modifyTVar (appGalleries state) (M.insert faid op')
getById :: Int -> Handler FileAssoc
getById faid = do
state <- getYesod
fileAssocs <- liftIO $ readTVarIO $ appGalleries state
case M.lookup faid fileAssocs of
Just fa -> return fa
_ -> notFound
getNextId :: App -> Handler Int
getNextId state = do
nid <- liftIO $ atomically $ rmwNextId $ appNextId state
return nid
where
rmwNextId tvar = do
nextId <- readTVar tvar
writeTVar tvar (nextId + 1)
return nextId
parseFiletype :: String -> Filetype
parseFiletype mime =
case break (== '/') mime of
(_, "") -> FiletypeOther
(field, _) ->
case map toLower field of
"text" -> FiletypeText
"image" -> FiletypeImage
_ -> FiletypeOther
| BartMassey/hgallery | Foundation.hs | agpl-3.0 | 2,723 | 0 | 13 | 660 | 658 | 338 | 320 | 82 | 4 |
module HaskellSetup where
{- This is the low-level stuff that hooks into the ncurses library, together
with the Haskell versions of the Agda types. You should not need to bother
reading or modifying this file. -}
import Debug.Trace
import Foreign
import Foreign.C (CInt(..))
import ANSIEscapes
import System.IO
import System.Environment
import Control.Applicative
import Control.Concurrent
foreign import ccall
initscr :: IO ()
foreign import ccall "endwin"
endwin :: IO CInt
foreign import ccall "refresh"
refresh :: IO CInt
foreign import ccall "&LINES"
linesPtr :: Ptr CInt
foreign import ccall "&COLS"
colsPtr :: Ptr CInt
scrSize :: IO (Int, Int)
scrSize = do
lnes <- peek linesPtr
cols <- peek colsPtr
return (fromIntegral cols, fromIntegral lnes)
data Direction = DU | DD | DL | DR deriving Show
data Modifier = Normal | Shift | Control deriving Show
data Key = Char Char | Arrow Modifier Direction | Enter | Backspace | Delete | Escape deriving Show
data Nat = Zero | Suc Nat
toNat :: Int -> Nat
toNat 0 = Zero
toNat n = Suc (toNat (n - 1))
fromNat :: Nat -> Int
fromNat Zero = 0
fromNat (Suc n) = 1 + fromNat n
data EQ a b c = Refl
data Change = AllQuiet | CursorMove | LineEdit | BigChange
data Action = GoRowCol Nat Nat | SendText [Char]
act :: Action -> IO ()
act (GoRowCol y x) = do
resetCursor
forward (fromNat x)
down (fromNat y)
act (SendText s) = putStr s
getEscapeKey :: [(String, Key)] -> IO (Maybe Key)
getEscapeKey [] = return Nothing
getEscapeKey sks = case lookup "" sks of
Just k -> return (Just k)
_ -> do
c <- getChar
getEscapeKey [(cs, k) | (d : cs, k) <- sks, d == c]
directions :: [(Char, Direction)]
directions = [('A', DU), ('B', DD),
('C', DR), ('D', DL)]
escapeKeys :: [(String, Key)]
escapeKeys =
[([c], Arrow Normal d) | (c, d) <- directions] ++
[("1;2" ++ [c], Arrow Shift d) | (c, d) <- directions] ++
[("1;5" ++ [c], Arrow Control d) | (c, d) <- directions] ++
[("3~", Delete)]
keyReady :: IO (Maybe Key)
keyReady = do
b <- hReady stdin
if not b then return Nothing else do
c <- getChar
case c of
'\n' -> return $ Just Enter
'\r' -> return $ Just Enter
'\b' -> return $ Just Backspace
'\DEL' -> return $ Just Backspace
_ | c >= ' ' -> return $ Just (Char c)
'\ESC' -> do
b <- hReady stdin
if not b then return $ Just Escape else do
c <- getChar
case c of
'[' -> getEscapeKey escapeKeys
_ -> return $ Just Escape
_ -> return $ Nothing
pni :: (Int, Int) -> (Nat, Nat)
pni (y, x) = (toNat y, toNat x)
mainLoop ::
([[Char]] -> b) ->
(Key -> b -> (Change, b)) ->
((Nat, Nat) -> (Nat, Nat) -> (Change, b) -> ([Action], (Nat, Nat))) ->
IO ()
mainLoop initBuf keystroke render = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
xs <- getArgs
buf <- case xs of
[] -> return (initBuf [])
(x : _) -> (initBuf . lines) <$> readFile x
initscr
innerLoop (0, 0) (Zero, Zero) (BigChange, buf)
endwin
return ()
where
innerLoop oldSize topLeft (c, b) = do
refresh
size <- scrSize
(acts, topLeft) <- return $
if size /= oldSize
then render (pni size) topLeft (BigChange, b)
else render (pni size) topLeft (c, b)
mapM_ act acts
mc <- keyReady
case mc of
Nothing -> threadDelay 100 >> innerLoop size topLeft (AllQuiet, b)
Just k -> innerLoop size topLeft (keystroke k b)
| pigworker/CS410-14 | Ex5/HaskellSetup.hs | unlicense | 3,521 | 0 | 22 | 915 | 1,457 | 769 | 688 | 108 | 10 |
module Haskoin.Crypto.Point
( Point( InfPoint )
, makePoint
, makeInfPoint
, getAffine, getX, getY
, validatePoint
, isInfPoint
, addPoint
, doublePoint
, mulPoint
, shamirsTrick
, curveB
) where
import Data.Maybe (isJust, fromJust)
import Data.Bits (testBit, shiftR, bitSize)
import Control.Applicative ((<$>), (<*>))
import Control.Monad (unless, when)
import Haskoin.Crypto.Ring (FieldP, FieldN, quadraticResidue)
curveB :: FieldP
curveB = fromInteger 0x07
{-
Elliptic curves of the form y^2 = x^3 + 7 (mod p)
Point on the elliptic curve in transformed Jacobian coordinates
(X,Y,Z) such that (x,y) = (X/Z^2, Y/Z^3)
InfPoint is the point at infinity
-}
data Point = Point !FieldP !FieldP !FieldP | InfPoint
deriving Show
instance Eq Point where
InfPoint == InfPoint = True
(Point x1 y1 z1) == (Point x2 y2 z2) = a == b && c == d
where a = x1*z2 ^ (2 :: Int)
b = x2*z1 ^ (2 :: Int)
c = y1*z2 ^ (3 :: Int)
d = y2*z1 ^ (3 :: Int)
_ == _ = False
-- Create a new point from (x,y) coordinates.
-- Returns Nothing if the point doesn't lie on the curve
makePoint :: FieldP -> FieldP -> Maybe Point
makePoint x y
| validatePoint point = Just point
| otherwise = Nothing
where point = Point x y 1
makeInfPoint :: Point
makeInfPoint = InfPoint
-- Get the original (x,y) coordinates from the Jacobian triple (X,Y,Z)
getAffine :: Point -> Maybe (FieldP, FieldP)
getAffine point = case point of
InfPoint -> Nothing
(Point _ _ 0) -> Nothing
(Point x y z) -> Just (x/z ^ (2 :: Int), y/z ^ (3 :: Int))
getX :: Point -> Maybe FieldP
getX point = fst <$> (getAffine point)
getY :: Point -> Maybe FieldP
getY point = snd <$> (getAffine point)
-- Section 3.2.2.1 http://www.secg.org/download/aid-780/sec1-v2.pdf
-- point 3.2.2.1.4 is not necessary as h=1
validatePoint :: Point -> Bool
validatePoint point = case getAffine point of
-- 3.2.2.1.1 (check that point not equal to InfPoint)
Nothing -> False
-- 3.2.2.1.2 (check that the point lies on the curve)
Just (x,y) -> y ^ (2 :: Int) == x ^ (3 :: Int) + curveB
isInfPoint :: Point -> Bool
isInfPoint InfPoint = True
isInfPoint (Point _ _ 0) = True
isInfPoint _ = False
-- Elliptic curve point addition
addPoint :: Point -> Point -> Point
addPoint InfPoint point = point
addPoint point InfPoint = point
addPoint p1@(Point x1 y1 z1) (Point x2 y2 z2)
| u1 == u2 = if s1 == s2 then doublePoint p1 else InfPoint
| otherwise = Point x3 y3 z3
where u1 = x1*z2 ^ (2 :: Int)
u2 = x2*z1 ^ (2 :: Int)
s1 = y1*z2 ^ (3 :: Int)
s2 = y2*z1 ^ (3 :: Int)
h = u2 - u1
r = s2 - s1
x3 = r ^ (2 :: Int) - h ^ (3 :: Int) - 2*u1*h ^ (2 :: Int)
y3 = r*(u1 * h ^ (2 :: Int) - x3) - s1 * h ^ (3 :: Int)
z3 = h * z1 * z2
-- Elliptic curve point doubling
doublePoint :: Point -> Point
doublePoint InfPoint = InfPoint
doublePoint (Point x y z)
| y == 0 = InfPoint
| otherwise = Point x' y' z'
where s = 4*x*y ^ (2 :: Int)
m = 3*x ^ (2 :: Int)
x' = m ^ (2 :: Int) - 2*s
y' = m*(s - x') - 8*y ^ (4 :: Int)
z' = 2*y*z
-- Elliptic curve point multiplication
mulPoint :: FieldN -> Point -> Point
mulPoint 0 _ = InfPoint
mulPoint 1 p = p
mulPoint _ InfPoint = InfPoint
mulPoint n p
| n == 0 = InfPoint
| odd n = addPoint p (mulPoint (n-1) p)
| otherwise = mulPoint (n `shiftR` 1) (doublePoint p)
-- Efficiently compute r1*p1 + r2*p2
shamirsTrick :: FieldN -> Point -> FieldN -> Point -> Point
shamirsTrick r1 p1 r2 p2 = go r1 r2
where q = addPoint p1 p2
go 0 0 = InfPoint
go a b | ea && eb = b2
| ea = addPoint b2 p2
| eb = addPoint b2 p1
| otherwise = addPoint b2 q
where b2 = doublePoint $ go (a `shiftR` 1) (b `shiftR` 1)
ea = even a
eb = even b
| lynchronan/haskoin-crypto | src/Haskoin/Crypto/Point.hs | unlicense | 4,094 | 0 | 14 | 1,267 | 1,466 | 786 | 680 | 105 | 3 |
module S1E9 where
allEqual :: (Eq a) => [a] -> Bool
allEqual xs = and ( map (== head xs) (tail xs) )
lengthEqual :: [[Int]] -> Bool
lengthEqual xss = allEqual (map length xss)
totalRows :: [[Int]] -> [Int]
totalRows = map sum
transpose :: [[Int]] -> [[Int]]
transpose ([]:_) = []
transpose xss = map head xss : transpose (map tail xss)
totalColumns :: [[Int]] -> [Int]
totalColumns ([]:_) = []
totalColumns xs = sum (map head xs) : totalColumns (map tail xs)
| wouwouwou/module_8 | src/main/haskell/series1/exercise9.hs | apache-2.0 | 464 | 0 | 9 | 90 | 256 | 137 | 119 | 13 | 1 |
module Main where
import qualified Data.List as List
import qualified Data.Set as Set
import Data.Version (showVersion)
import Paths_sarsi (version)
import qualified Rosetta as Rosetta
import Sarsi (getBroker, getSockAddr, getTopic, title)
import Sarsi.Processor (languageProcess, processAll, processAny)
import Sarsi.Tools.Pipe (pipe)
import Sarsi.Tools.Trace (traceCleanCurses, traceHS, traceRS)
import System.Environment (getArgs)
import System.IO (stdin)
main :: IO ()
main = getArgs >>= run
where
run ["--trace", "clean-curses"] = traceCleanCurses stdin
run ["--trace", "hs"] = traceHS stdin
run ["--trace", "rs"] = traceRS stdin
run ["--topic"] = do
b <- getBroker
t <- getTopic b "."
print $ getSockAddr t
run ["--version"] = putStrLn $ concat [title, "-", showVersion version]
run [] = pipe "any" processAny
run exts = case Set.fromList <$> traverse parseExt exts of
Right languageTags -> do
ps <- traverse fetchProcess $ Set.toList languageTags
pipe (concat $ List.intersperse "+" (Rosetta.languageLabel <$> (Set.toList languageTags))) (processAll $ ps >>= id)
Left err -> putStrLn $ concat [title, ": ", err]
fetchProcess lt = case languageProcess lt of
Just process -> return [process]
Nothing -> do
putStrLn $ concat [title, ": ", "unsupported language '", Rosetta.languageLabel lt, "'"]
return []
parseExt ext =
case Rosetta.fromExtension ext of
Just lt -> Right lt
Nothing -> Left (concat ["invalid extension '", ext, "'."])
| aloiscochard/sarsi | sarsi/Main.hs | apache-2.0 | 1,575 | 0 | 20 | 340 | 535 | 284 | 251 | 37 | 10 |
{- |
Module : Text.Tabl.Util
Description : Various utilities
Copyright : (c) 2016-2020 Daniel Lovasko
License : BSD2
Maintainer : Daniel Lovasko <[email protected]>
Stability : stable
Portability : portable
Set of general utilities that are used across the whole project.
-}
module Text.Tabl.Util
( bool
, extend
, intersperseOn
, zipcat
) where
-- | Extend a list to a defined length with one repeated element. This
-- function assumes that the list is shorter than the provided length.
extend
:: Int -- ^ expected length
-> a -- ^ element to pad with
-> [a] -- ^ original list
-> [a] -- ^ extended list
extend n x xs = xs ++ replicate (n - length xs) x
-- | Insert an element in front of the i-th position, if the i-th element
-- is True.
intersperseOn :: (Monoid a)
=> [a] -- ^ list
-> [Bool] -- ^ insert rules
-> a -- ^ element to insert
-> [a] -- ^ new list
intersperseOn xs bs x = init $ concat $ zipWith glue bs (xs ++ [mempty])
where
glue True i = [x, i]
glue False i = [i]
-- | Functional implementation of the if/then/else concept.
bool
:: a -- ^ True option
-> a -- ^ False option
-> Bool -- ^ condition
-> a -- ^ result
bool x _ True = x
bool _ y False = y
-- | Create an object by zipping two lists together. The second list is
-- expected to be one element shorter.
zipcat :: (Monoid a)
=> [a] -- ^ first list
-> [a] -- ^ second list
-> a -- ^ result
zipcat xs ys = mconcat $ zipWith mappend xs (mappend ys [mempty])
| lovasko/tabl | src/Text/Tabl/Util.hs | bsd-2-clause | 1,525 | 0 | 9 | 376 | 302 | 174 | 128 | 31 | 2 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, NoImplicitPrelude, PackageImports #-}
module Control.Monad.Pause (PauseT, pause, stepPause, runPauseT, runPause) where
import "base" Prelude
import Control.Applicative
import Control.Monad
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans
import Control.Monad.Writer
newtype PauseT m a = PauseT {stepPause :: m (Either (PauseT m a) a)}
type Pause = PauseT Identity
instance (Monad m) => Functor (PauseT m) where
fmap = liftM
instance (Monad m) => Monad (PauseT m) where
return x = lift (return x)
(PauseT s) >>= f = PauseT $ s >>= either (return . Left . (>>= f)) (stepPause . f)
instance (Functor m, Monad m) => Applicative (PauseT m) where
pure = return
(<*>) = ap
instance MonadTrans PauseT where
lift k = PauseT (liftM Right k)
instance (MonadError e m) => MonadError e (PauseT m) where
throwError = lift . throwError
catchError m f = PauseT $ catchError (stepPause m) (stepPause . f)
instance MonadState s m => MonadState s (PauseT m) where
get = lift get
put = lift . put
state = lift . state
instance (MonadReader r m) => MonadReader r (PauseT m) where
ask = lift ask
local f m = PauseT $ local f $ stepPause m
runPauseT :: Monad m => PauseT m a -> m a
runPauseT m = stepPause m >>= either runPauseT return
runPause :: Pause a -> a
runPause = runIdentity . runPauseT
class Monad m => MonadPause m where
pause :: m ()
instance Monad m => MonadPause (PauseT m) where
pause = PauseT (return (Left (return ())))
instance (MonadPause m) => MonadPause (ReaderT s m) where
pause = lift pause
instance (MonadPause m) => MonadPause (StateT s m) where
pause = lift pause
instance (MonadPause m, Monoid w) => MonadPause (WriterT w m) where
pause = lift pause
instance (MonadPause m) => MonadPause (ExceptT e m) where
pause = lift pause
| 3of8/mockio | Pause.hs | bsd-2-clause | 1,985 | 0 | 13 | 377 | 762 | 401 | 361 | 49 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-|
Module: HaskHOL.Core.Lib
Copyright: (c) Evan Austin 2015
LICENSE: BSD3
Maintainer: [email protected]
Stability: unstable
Portability: unknown
This module defines or re-exports common utility functions, type classes,
and auxilliary data types used in HaskHOL. The following conventions hold
true:
* Where possible, we favor re-exporting common functions rather than
redefining them.
* We favor re-exporting individual functions rather entire modules to reduce
the number of items in our utility library.
* We default to the names of functions commonly used by Haskell libraries,
however, if there's a different name for a function in HOL systems we
include an alias for it. For example, 'iComb' and 'id'.
Note that none of the functions in this module depend on data types
introduced by HaskHOL. Utility functions that do have such a dependence are
found in the "HaskHOL.Core.Basics" module.
-}
module HaskHOL.Core.Lib
( -- * Function Combinators
wComb
, ffComb
, ffCombM
, on
-- * Basic Operations on Pairs
, swap
, pairMap
, pairMapM
, first
, firstM
, second
, secondM
-- * Basic Operations on Lists
, tryHead
, tryTail
, tryInit
, tryLast
, tryIndex
-- * Basic Operations on Association Lists
, assoc
, revAssoc
, assocd
, revAssocd
-- * Methods for Error Handling
, (<|>)
, (<?>)
, note
, fail'
, failWhen
, maybeToFail
, eitherToFail
, try'
, tryd
, test'
, can
, can'
, canNot
, check
-- * Methods for Function Repetition
, funpow
, funpowM
, repeatM
, map2
, map2M
, allpairs
-- * Methods for List Iteration
, foldrM
, itlistM
, foldlM
, revItlistM
, tryFoldr1
, foldr1M
, foldr2
, foldr2M
, foldl2
, foldl2M
-- * Methods for Sorting and Merging Lists
, sort
, sortBy
, merge
, mergesort
-- * Methods for Splitting and Stripping Binary Terms
, splitList
, splitListM
, revSplitList
, revSplitListM
, nsplit
, stripList
, stripListM
-- * Methods for Searching and Manipulating Lists
, all2
, partition
, mapFilter
, mapFilterM
, find
, findM
, tryFind
, dropWhileEnd
, remove
, trySplitAt
, index
, stripPrefix
, uniq
, shareOut
-- * Set Operations on Lists
, insert
, insertMap
, union
, unions
, intersect
, delete
, (\\)
, subset
, setEq
, setify
, nub
-- * Set Operations Parameterized by Predicate
, mem'
, insert'
, union'
, unions'
, subtract'
, group'
, uniq'
, setify'
-- * Operations on \"Num\" Types
, (%)
, numdom
, numerator
, denominator
, numOfString
-- * Polymorphic, Finite, Partial Functions Via Patricia Trees
, Func
, funcEmpty
, isEmpty
, funcMap
, funcFoldl
, funcFoldr
, graph
, dom
, ran
, applyd
, apply
, tryApplyd
, defined
, undefine
, (|->)
, combine
, (|=>)
, choose
-- * Re-exported 'Map' primitives
, Map
, mapEmpty
, mapInsert
, mapUnion
, mapDelete
, mapAssoc
, mapElems
, mapFromList
, mapToList
, mapMap
, mapFoldrWithKey
, mapRemove
, mapToAscList
-- * Re-exported 'Text' primitives
, Text
, append
, cons
, snoc
, pack
, unpack
, textHead
, textTail
, textNull
, textEmpty
, textStrip
, textShow
, textWords
, textUnwords
-- * Re-exported 'AcidState' primitives
, Update
, Query
, get
, put
, ask
, makeAcidic
-- * Classes for Common \"Language\" Operations
-- $LangClasses
, Lang(..)
, LangSeq(..)
-- * Miscellaneous Re-exported Libraries
, module HaskHOL.Core.Lib.Families {-|
Re-exports a few type families used for basic, type-level boolean
computation.
-}
, module Control.DeepSeq {-|
Re-exports the entirety of the library, but currently only 'NFData' is
used. Necessary for using the "Criterion" benchmarking library.
-}
, module Control.Monad {-|
Re-exports the entirety of the library for use with the 'HOL' monad.
-}
, module Data.Data {-|
Re-exports the 'Data' and 'Typeable' class names for use in deriving
clauses.
-}
, module Data.SafeCopy {-|
Re-exports the entirety of the library for use with the 'HOL' monad's
acid state primitives.
-}
, module Control.Monad.Catch {-|
Re-exports the entirety of the library, serving as the basis for our
extensible exception handling.
-}
, module Control.Monad.Catch.Pure {-|
Re-exports the entirety of the library, serving as a pure alternative
to the methods in @Control.Monad.Catch@
-}
) where
import HaskHOL.Core.Kernel.Prims (HOLPrimError(..))
import HaskHOL.Core.Lib.Families
-- Libraries re-exported in their entirety, except for applicative
import Control.DeepSeq
import Control.Monad hiding (mzero)
import Data.Data (Data, Typeable)
import Data.SafeCopy
import Control.Monad.Catch
import Control.Monad.Catch.Pure
-- Libraries containing Re-exports
import qualified Control.Arrow as A
import qualified Data.Foldable as F
import qualified Data.Function as DF (on)
import qualified Data.List as L
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Ratio as R
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as Text
import qualified TextShow as Text
import qualified Data.Tuple as T
-- Acid State imports
import qualified Control.Monad.State as State (MonadState, get, put)
import qualified Control.Monad.Reader as Reader (MonadReader, ask)
import Data.Acid (Update, Query)
import qualified Data.Acid as Acid
import Language.Haskell.TH
-- Libraries containing utility functions used, but not exported directly
import Numeric (readInt, readHex, readDec)
import Data.Char (digitToInt)
import Data.Bits
import Data.Hashable
-- combinators
{-|
The W combinator. Takes a function of arity 2 and applies a single argument
to it twice.
-}
wComb :: (a -> a -> b) -> a -> b
wComb f x = f x x
-- | The FF combinator. An alias for the arrow combinator 'A.***'.
ffComb :: (a -> c) -> (b -> d) -> (a, b) -> (c, d)
ffComb = (A.***)
{-|
The monadic version of the FF combinator. An alias for the arrow combinator
'A.***' lifted for 'A.Kleisli' arrows.
-}
ffCombM :: Monad m => (a -> m c) -> (b -> m d) -> (a, b) -> m (c, d)
ffCombM f g = A.runKleisli $ A.Kleisli f A.*** A.Kleisli g
{-|
Re-export of the 'DF.on' combination from @Data.Function@.
-}
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
on = DF.on
-- pair basics
-- | Swaps the order of a pair. A re-export of 'T.swap'.
swap :: (a, b) -> (b, a)
swap = T.swap
-- | Applies a function to both elements of a pair using the 'A.***' operator.
pairMap :: (a -> b) -> (a, a) -> (b, b)
pairMap f = f A.*** f
-- | The monadic version of 'pairMap'.
pairMapM :: Monad m => (a -> m b) -> (a, a) -> m (b, b)
pairMapM f = f `ffCombM` f
{-|
Applies a function only to the first element of a pair. A re-export of
'A.first'.
-}
first :: (a -> c) -> (a, b) -> (c, b)
first = A.first
-- | A monadic version of 'first' lifted for 'A.Kleisli' arrows.
firstM :: Monad m => (a -> m c) -> (a, b) -> m (c, b)
firstM = A.runKleisli . A.first . A.Kleisli
{-|
Applies a function only to the second element of a pair. A re-export of
'A.second'.
-}
second :: (b -> c) -> (a, b) -> (a, c)
second = A.second
-- | A monadic version of 'second' lifted for 'A.Kleisli' arrows.
secondM :: Monad m => (b -> m c) -> (a, b) -> m (a, c)
secondM = A.runKleisli . A.second . A.Kleisli
-- list basics
-- | A guarded version of 'head'.
tryHead :: MonadThrow m => [a] -> m a
tryHead (x:_) = return x
tryHead _ = fail' "tryHead"
-- | A guarded version of 'tail'.
tryTail :: MonadThrow m => [a] -> m [a]
tryTail (_:t) = return t
tryTail _ = fail' "tryTail"
-- | A guarded version of 'init'.
tryInit :: MonadThrow m => [a] -> m [a]
tryInit [_] = return []
tryInit (x:xs) = (:) x `fmap` tryInit xs
tryInit _ = fail' "tryInit"
-- | A guarded version of 'last'.
tryLast :: MonadThrow m => [a] -> m a
tryLast [x] = return x
tryLast (_:xs) = tryLast xs
tryLast _ = fail' "tryLast"
-- | A guarded version of 'index'.
tryIndex :: MonadThrow m => [a] -> Int -> m a
tryIndex xs n
| n >= 0 = tryHead $ drop n xs
| otherwise = fail' "tryIndex"
-- association lists
-- | A guarded alias to 'lookup'.
assoc :: (MonadThrow m, Eq a) => a -> [(a, b)] -> m b
assoc x = maybeToFail "assoc" . lookup x
{-|
A guarded version of 'lookup' where the search is performed against the
second element of the pair instead of the first.
-}
revAssoc :: (MonadThrow m, Eq a) => a -> [(b, a)] -> m b
revAssoc _ [] = fail' "revAssoc"
revAssoc x ((f, s):as)
| x == s = return f
| otherwise = revAssoc x as
-- | A version of 'assoc' that defaults to a provided value rather than fail.
assocd :: Eq a => a -> [(a, b)] -> b -> b
assocd x xs b = tryd b $ assoc x xs
{-|
A version of 'revAssoc' that defaults to a provided value rather than fail.
-}
revAssocd :: Eq a => a -> [(b, a)] -> b -> b
revAssocd x xs b = tryd b $ revAssoc x xs
-- error handling and checking
infixl 3 <|>
-- | A version of the alternative operator based on 'MonadCatch'.
(<|>) :: forall m a. MonadCatch m => m a -> m a -> m a
job <|> err = job `catch` ferr
where ferr :: SomeException -> m a
ferr _ = err
infix 0 <?>
{-|
Replaces the exception thrown by a computation with a provided 'String'
message, i.e.
> m (<?>) str = m <|> fail' str
-}
(<?>) :: MonadCatch m => m a -> String -> m a
m <?> str = m <|> fail' str
{-|
Converts the exception thrown by a computaiton to a 'String' and prepends it
with a provided message.
-}
note :: MonadCatch m => String -> m a -> m a
note str m =
m `catch` (\ e -> case fromException e of
Just (HOLErrorMsg str2) ->
throwM $! HOLErrorMsg (str ++ ": " ++ str2)
_ ->
throwM $! HOLErrorMsg (str ++ ": " ++ show e))
-- | A version of 'fail' based on 'MonadThrow' using 'HOLPrimError'.
fail' :: MonadThrow m => String -> m a
fail' = throwM . HOLErrorMsg
-- | The 'fail'' method guarded by 'when'.
failWhen :: MonadCatch m => m Bool -> String -> m ()
failWhen m str =
do cond <- m
when cond $ fail' str
-- | Converts a 'Maybe' value to a 'MonadThrow' value using 'fail''.
maybeToFail :: MonadThrow m => String -> Maybe a -> m a
maybeToFail str = maybe (fail' str) return
-- | Converts an 'Either' value to a 'MonadThrow' value using 'fail''.
eitherToFail :: (Show err, MonadThrow m) => Either err a -> m a
eitherToFail = either (fail' . show) return
{-|
Forces the evaluation of a 'Catch' computation, relying on 'error' if it
fails.
-}
try' :: Catch a -> a
try' = either (\ _ -> error "try'") id . runCatch
{-|
Forces the evaluation of a 'Catch' computation, returning a default value if
it fails.
-}
tryd :: a -> Catch a -> a
tryd d = either (const d) id . runCatch
-- | Tests if the evaluation of a 'Catch' computation succeeds or not.
test' :: Catch a -> Bool
test' = either (const False) (const True) . runCatch
{-|
Returns a boolean value indicating whether a monadic computation succeeds or
fails. The '<|>' operator is used for branching.
-}
can :: MonadCatch m => (a -> m b) -> a -> m Bool
can f x = (f x >> return True) <|> return False
{-|
A version of 'can' that instead marks success or failure with a 'Maybe' value.
Turns a potentially failing monadic computation into a guarded, always
successful monadic computation.
-}
can' :: MonadCatch m => (a -> m b) -> a -> m (Maybe b)
can' f x = (f x >>= \ x' -> return (Just x')) <|> return Nothing
{-|
The opposite of 'can'. Functionally equivalent to
> \ f -> liftM not . can f
-}
canNot :: MonadCatch m => (a -> m b) -> a -> m Bool
canNot f x = (f x >> return False) <|> return True
{-|
Checks if a predicate succeeds for a provided value, returning that value
guarded if so.
-}
check :: MonadThrow m => (a -> Bool) -> a -> m a
check p x
| p x = return x
| otherwise = fail' "check"
-- repetition of a functions
{-|
Repeatedly applies a function to an argument @n@ times. Rather than fail,
the original argument is returned when @n<=0@.
-}
funpow :: Int -> (a -> a) -> a -> a
funpow n f x
| n <= 0 = x
| otherwise = funpow (n - 1) f (f x)
-- | The monadic version of 'funpow'.
funpowM :: Monad m => Int -> (a -> m a) -> a -> m a
funpowM n f x
| n <= 0 = return x
| otherwise = funpowM (n - 1) f =<< f x
{-|
Repeatedly applies a monadic computation to an argument until there is a
failure. The '<|>' operator is used for branching.
-}
repeatM :: MonadCatch m => (a -> m a) -> a -> m a
repeatM f x = (repeatM f =<< f x) <|> return x
-- | A guarded version of a list map for functions of arity 2.
map2 :: MonadThrow m => (a -> b -> c) -> [a] -> [b] -> m [c]
map2 _ [] [] = return []
map2 f (x:xs) (y:ys) = (:) (f x y) `fmap` map2 f xs ys
map2 _ _ _ = fail' "map2"
-- | A version of 'map2' that accepts monadic functions.
map2M :: MonadThrow m => (a -> b -> m c) -> [a] -> [b] -> m [c]
map2M _ [] [] = return []
map2M f (x:xs) (y:ys) =
do h <- f x y
t <- map2M f xs ys
return (h : t)
map2M _ _ _ = fail' "map2M"
-- all pairs arrising from applying a function over two lists
{-|
Produces a list containing the results of applying a function to all possible
combinations of arguments from two lists. Rather than failing if the lists
are of different lengths, iteration is shortcutted to end when the left most
list is null.
-}
allpairs :: (a -> b -> c) -> [a] -> [b] -> [c]
allpairs _ [] _ = []
allpairs f (h:t) l2 = foldr (\ x a -> f h x : a) (allpairs f t l2) l2
-- list iteration
-- | The monadic version of 'foldr'. A re-export of 'F.foldrM'.
foldrM :: (F.Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
foldrM = F.foldrM
-- | A version of 'foldrM' with its arguments flipped.
itlistM :: (F.Foldable t, Monad m) => (a -> b -> m b) -> t a -> b -> m b
itlistM f = flip (F.foldrM f)
-- | The monadic version of 'foldl'. A re-export of 'F.foldlM'.
foldlM :: (F.Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a
foldlM = F.foldlM
-- | A version of 'foldlM' with its arguments flipped.
revItlistM :: (F.Foldable t, Monad m) => (b -> a -> m a) -> t b -> a -> m a
revItlistM f = flip (F.foldlM (flip f))
-- | A guarded version of 'foldr1'.
tryFoldr1 :: MonadThrow m => (a -> a -> a) -> [a] -> m a
tryFoldr1 _ [] = fail' "tryFoldr1"
tryFoldr1 _ [x] = return x
tryFoldr1 f (x:xs) = f x `fmap` tryFoldr1 f xs
-- | A version of 'foldr1' that accepts monadic functions.
foldr1M :: MonadThrow m => (a -> a -> m a) -> [a] -> m a
foldr1M _ [] = fail' "foldr1M"
foldr1M _ [x] = return x
foldr1M f (h:t) = f h =<< foldr1M f t
-- | A guarded version of a right, list fold for functions of arity 2.
foldr2 :: MonadThrow m => (a -> b -> c -> c) -> c -> [a] -> [b] -> m c
foldr2 _ b [] [] = return b
foldr2 f b (x:xs) (y:ys) = f x y `fmap` foldr2 f b xs ys
foldr2 _ _ _ _ = fail' "foldr2"
-- | A version of 'foldr2' that accepts monadic functions.
foldr2M :: MonadThrow m => (a -> b -> c -> m c) -> c -> [a] -> [b] -> m c
foldr2M _ b [] [] = return b
foldr2M f b (h1:t1) (h2:t2) = f h1 h2 =<< foldr2M f b t1 t2
foldr2M _ _ _ _ = fail' "foldr2M"
-- | A guarded version of a left, list fold for functions of arity 2.
foldl2 :: MonadThrow m => (c -> a -> b -> c) -> c -> [a] -> [b] -> m c
foldl2 _ b [] [] = return b
foldl2 f b (x:xs) (y:ys) =
foldl2 f (f b x y) xs ys
foldl2 _ _ _ _ = fail' "foldl2"
-- | A version of `foldl2` that accepts monadic functions.
foldl2M :: MonadThrow m => (c -> a -> b -> m c) -> c -> [a] -> [b] -> m c
foldl2M _ b [] [] = return b
foldl2M f b (h1:t1) (h2:t2) =
do b' <- f b h1 h2
foldl2M f b' t1 t2
foldl2M _ _ _ _ = fail' "foldl2M"
-- sorting and merging of lists
{-|
Sorts a list using a partitioning predicate to build an implied ordering.
If @p@ is the predicate and @x \`p\` y@ and @not (y \`p\` x)@ are true then
@x@ will be in front of @y@ in the sorted list.
-}
sort :: Eq a => (a -> a -> Bool) -> [a] -> [a]
sort _ [] = []
sort f (piv:rest) =
let (r, l) = partition (f piv) rest in
sort f l ++ (piv : sort f r)
{-|
A more traditional sort using an 'Ordering' relationship between elements. A
re-export of 'L.sortBy'.
-}
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
sortBy = L.sortBy
{-|
Merges two lists using a partitioning predicate to build an implied ordering.
See 'sort' for more information on how the predicate affects the order of the
resultant list.
-}
merge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
merge _ [] l2 = l2
merge _ l1 [] = l1
merge ord l1@(x:xs) l2@(y:ys)
| ord x y = x : merge ord xs l2
| otherwise = y : merge ord l1 ys
{-|
Sorts a list using a partitioning predicate to build an implied ordering;
uses 'merge' internally. See 'sort' for more information on how the predicate
affects the order of the resultant list.
-}
mergesort :: forall a. (a -> a -> Bool) -> [a] -> [a]
mergesort _ [] = []
mergesort ord l = mergepairs [] $ map (: []) l
where mergepairs :: [[a]] -> [[a]] -> [a]
mergepairs [x] [] = x
mergepairs xs [] = mergepairs [] xs
mergepairs xs [y] = mergepairs (y:xs) []
mergepairs xs (y1:y2:ys) = mergepairs (merge ord y1 y2 : xs) ys
-- iterative term splitting and stripping via destructor
{-|
Repeatedly applies a binary destructor function to a term until failure.
Application is forward, or left-associative, such that for a term of the form
@x1 \`f\` x2 \`f\` b@ calling this function with a destructor for @f@ will
produce the result @([x1, x2], b)@.
-}
splitList :: (b -> Catch (a, b)) -> b -> ([a], b)
splitList f = try' . splitListM f
-- | The monadic version of 'splitList'.
splitListM :: MonadCatch m => (b -> m (a, b)) -> b -> m ([a], b)
splitListM f x =
(do (l, r) <- f x
(ls, res) <- splitListM f r
return (l:ls, res))
<|> return ([], x)
{-|
Repeatedly applies a binary destructor function to a term until failure.
Application is reverse, or right-associative, such that for a term of the form
@x1 \`f\` x2 \`f\` b@ calling this function with a destructor for @f@ will
produce the result @(f, [x1, x2 \`f\` b])@.
-}
revSplitList :: (a -> Catch (a, b)) -> a -> (a, [b])
revSplitList f = try' . revSplitListM f
-- | The monadic version of 'revSplitList'.
revSplitListM :: forall m a b. MonadCatch m => (a -> m (a, b))
-> a -> m (a, [b])
revSplitListM f = rsplist []
where rsplist :: [b] -> a -> m (a, [b])
rsplist ls y =
(do (l, r) <- f y
rsplist (r:ls) l)
<|> return (y, ls)
{-|
Repeatedly applies a binary destructor function to a term for every element
in a provided list.
Application is reverse, or right-associative, such that for a term of the form
@f x1 (f x2 ...(f xn b))@ calling this function with a destructor for @f@ and
a list @l@ will produce the result @([x1 .. xk], f x(k+1) ...(f xn b))@ where
@k@ is the length of list @l@.
-}
nsplit :: Monad m => (a -> m (a, a)) -> [b] -> a -> m ([a], a)
nsplit _ [] x = return ([], x)
nsplit dest (_:cs) x =
do (l, r) <- dest x
(ll, y) <- nsplit dest cs r
return (l:ll, y)
{-|
Repeatedly applies a binary destructor function to a term until failure.
Application is forward, or left-associative, such that for a term of the form
@x1 \`f\` x2 \`f\` x3@ calling this function with a destructor for @f@ will
produce the result @[x1, x2, x3]@.
-}
stripList :: (a -> Catch (a, a)) -> a -> [a]
stripList dest = try' . stripListM dest
-- | The monadic version of 'stripList'.
stripListM :: forall m a. MonadCatch m => (a -> m (a, a)) -> a -> m [a]
stripListM dest x = strip x []
where strip :: a -> [a] -> m [a]
strip x' acc =
(do (l, r) <- dest x'
strip l =<< strip r acc)
<|> return (x' : acc)
-- miscellaneous list methods
{-|
A version of 'all' for predicates of arity 2. Iterates down two lists
simultaneously with 'map2', using 'and' to combine the results.
-}
all2 :: MonadThrow m => (a -> b -> Bool) -> [a] -> [b] -> m Bool
all2 f xs ys = and `fmap` map2 f xs ys
{-|
Separates a list of elements using a predicate. Re-export of `L.partition`.
-}
partition :: (a -> Bool) -> [a] -> ([a], [a])
partition = L.partition
-- | Filter's a list of items using a `Catch` predicate.
mapFilter :: (a -> Catch b) -> [a] -> [b]
mapFilter f = try' . mapFilterM f
-- | The monadic version of 'mapFilter'.
mapFilterM :: MonadCatch m => (a -> m b) -> [a] -> m [b]
mapFilterM _ [] = return []
mapFilterM f (x:xs) =
do xs' <- mapFilterM f xs
(do x' <- f x
return (x':xs'))
<|> return xs'
-- | A guarded re-export of 'L.find'.
find :: MonadThrow m => (a -> Bool) -> [a] -> m a
find f = maybeToFail "find" . L.find f
{-|
The monadic version of 'find'. Fails if the monadic predicate does.
-}
findM :: forall m a. MonadCatch m => (a -> m Bool) -> [a] -> m a
findM _ [] = fail' "findM"
findM f (x:xs) = test <|> findM f xs
where test :: m a
test =
do b <- f x
if b
then return x
else fail' "findM: test"
{-|
An alternative monadic version of 'find' where the predicate is a monadic
computation not necessarily of a boolean return type. Returns the result of
the first successful application of the predicate to an element of the list.
Fails when called on an empty list.
-}
tryFind :: MonadCatch m => (a -> m b) -> [a] -> m b
tryFind _ [] = fail' "tryFind"
tryFind f (x:xs) = f x <|> tryFind f xs
{-|
Drops elements from the end of a list while a predicate is true. A re-export
of 'L.dropWhileEnd'.
-}
dropWhileEnd :: (a -> Bool) -> [a] -> [a]
dropWhileEnd = L.dropWhileEnd
{-|
Separates the first element of a list that satisfies a predicate. Fails with
'Nothing' if no such element is found.
-}
remove :: MonadThrow m => (a -> Bool) -> [a] -> m (a, [a])
remove _ [] = fail' "remove"
remove p (h:t)
| p h = return (h, t)
| otherwise =
do (y, n) <- remove p t
return (y, h:n)
{-|
A guarded version of 'splitAt'.
Fails if a split is attempted at an index that doesn't exist.
-}
trySplitAt :: MonadThrow m => Int -> [a] -> m ([a], [a])
trySplitAt n l
| n < 0 = fail' "trySplitAt"
| n == 0 = return ([], l)
| otherwise =
case l of
[] -> fail' "trySplitAt"
(x:xs) -> do (m, l') <- trySplitAt (n - 1) xs
return (x:m, l')
-- | Returns the first index where an element appears in list.
index :: (MonadThrow m, Eq a) => a -> [a] -> m Int
index x = maybeToFail "index" . L.elemIndex x
-- | A guarded versino of 'L.stripPrefix'.
stripPrefix :: (MonadThrow m, Eq a) => [a] -> [a] -> m [a]
stripPrefix xs = maybeToFail "stripPrefix" . L.stripPrefix xs
-- | Removes adjacent, equal elements from a list.
uniq :: Eq a => [a] -> [a]
uniq (x:y:t) =
let t' = uniq t in
if x == y then t' else x : t'
uniq l = l
{-|
Partitions a list into a list of lists matching the structure of the first
argument. For example:
@shareOut [[1, 2], [3], [4, 5]] \"abcde\" === [\"ab\", \"c\", \"de\"]@
-}
shareOut :: MonadThrow m => [[a]] -> [b] -> m [[b]]
shareOut [] _ = return []
shareOut (p:ps) bs =
do (l, r) <- trySplitAt (length p) bs
ls <- shareOut ps r
return (l : ls)
-- set operations on lists
{-|
Inserts an item into a list if it would be a unique element.
Important note: This insert is unordered, unlike the 'L.insert' in the
"Data.List" module.
-}
insert :: Eq a => a -> [a] -> [a]
insert x l
| x `elem` l = l
| otherwise = x : l
{-|
Inserts, or updates, a key value pair in an association list.
Note that this insert is unordered, but uniqueness preserving.
-}
insertMap :: Eq a => a -> b -> [(a, b)] -> [(a, b)]
insertMap key v [] = [(key, v)]
insertMap key v (x@(key', _):xs)
| key == key' = (key, v) : xs
| otherwise = x : insertMap key v xs
{-|
Unions two list maintaining uniqueness of elements.
Important note: This union is unordered, unlike the 'L.union' in the
"Data.List" module.
-}
union :: Eq a => [a] -> [a] -> [a]
union l1 l2 = foldr insert l2 l1
-- | Unions a list of lists using 'union'.
unions :: Eq a => [[a]] -> [a]
unions = foldr union []
-- | Finds the intersection of two lists. A re-export of 'L.intersect'.
intersect :: Eq a => [a] -> [a] -> [a]
intersect = L.intersect
-- | Removes an item from a list. A re-export of 'L.delete'.
delete :: Eq a => a -> [a] -> [a]
delete = L.delete
-- | Subtracts one list from the other. A re-export of 'L.\\'.
(\\) :: Eq a => [a] -> [a] -> [a]
(\\) = (L.\\)
-- | Tests if the first list is a subset of the second.
subset :: Eq a => [a] -> [a] -> Bool
subset xs ys = all (`elem` ys) xs
-- | A test for set equality using 'subset'.
setEq :: Eq a => [a] -> [a] -> Bool
setEq l1 l2 = subset l1 l2 && subset l2 l1
-- | Converts a list to a set by removing duplicates. A re-export of 'L.nub'.
nub :: Eq a => [a] -> [a]
nub = L.nub
-- | A version of 'nub' where the resultant list is sorted.
setify :: Ord a => [a] -> [a]
setify = L.sort . nub
-- set operations parameterized by equality
{-|
A version of 'mem' where the membership test is an explicit predicate, rather
than a strict equality test.
-}
mem' :: (a -> a -> Bool) -> a -> [a] -> Bool
mem' _ _ [] = False
mem' eq a (x:xs) = eq a x || mem' eq a xs
{-|
A version of 'insert' where the uniqueness test is an explicit predicate,
rather than a strict equality test.
-}
insert' :: (a -> a -> Bool) -> a -> [a] -> [a]
insert' eq x xs
| mem' eq x xs = xs
| otherwise = x : xs
{-|
A version of 'union' where the uniqueness test is an explicit predicate,
rather than a strict equality test.
-}
union' :: (a -> a -> Bool) -> [a] -> [a] -> [a]
union' eq xs ys = foldr (insert' eq) ys xs
{-|
A version of 'unions' where the uniqueness test is an explicit predicate,
rather than a strict equality test.
-}
unions' :: (a -> a -> Bool) -> [[a]] -> [a]
unions' eq = foldr (union' eq) []
{-|
A version of 'subtract' where the uniqueness test is an explicit predicate,
rather than a strict equality test.
-}
subtract' :: (a -> a -> Bool) -> [a] -> [a] -> [a]
subtract' eq xs ys = filter (\ x -> not $ mem' eq x ys) xs
{-|
Groups neighbors in a list together based on a predicate. A re-export of
'L.groupBy'.
-}
group' :: (a -> a -> Bool) -> [a] -> [[a]]
group' = L.groupBy
-- | A version of 'uniq' that eliminates elements based on a provided predicate.
uniq' :: Eq a => (a -> a -> Bool) -> [a] -> [a]
uniq' eq l@(x:t@(y:_)) =
let t' = uniq' eq t in
if x `eq` y then t'
else if t' == t then l else x:t'
uniq' _ l = l
{-|
A version of 'setify' that eliminates elements based on a provided predicate.
-}
setify' :: Eq a => (a -> a -> Bool) -> (a -> a -> Bool) -> [a] -> [a]
setify' le eq xs = uniq' eq $ sort le xs
-- | Constructs a 'Rational' from two 'Integer's. A re-export of (R.%).
(%) :: Integer -> Integer -> Rational
(%) = (R.%)
{-|
Converts a real number to a rational representation.
An alias to 'toRational' for HOL users more familiar with this name.
-}
numdom :: Rational -> (Integer, Integer)
numdom r =
(R.numerator r, R.denominator r)
-- | Returns the numerator of a rational number. A re-export of 'R.numerator'.
numerator :: Rational -> Integer
numerator = R.numerator
{-|
Returns the denominator of a rational number. A re-export of 'R.denominator'.
-}
denominator :: Rational -> Integer
denominator = R.denominator
{-|
Converts a 'String' representation of a number to an appropriate instance of
the 'Num' class. Fails with 'Nothing' if the conversion cannot be performed.
Note: The following prefixes are valid:
* @0x@ - number read as a hexidecimal value
* @0b@ - number read as a binary value
* Any other prefix causes the number to be read as a decimal value
-}
numOfString :: forall m a. (MonadThrow m, Eq a, Num a) => String -> m a
numOfString s =
case res of
[(x, "")] -> return x
_ -> fail' "numOfString"
where res :: [(a, String)]
res = case s of
('0':'x':s') -> readHex s'
('0':'b':s') -> readInt 2 (`elem` ("01"::String)) digitToInt s'
_ -> readDec s
-- Polymorphic, finite, partial functions via Patricia trees
{-| 'Func' is a Patricia Tree representation of polymorphic, finite, partial
functions.
-}
data Func a b
= Empty
| Leaf !Int ![(a, b)]
| Branch !Int !Int !(Func a b) !(Func a b) deriving Eq
-- | An empty 'Func' tree.
funcEmpty :: Func a b
funcEmpty = Empty
-- | The predicate for empty 'Func' trees.
isEmpty :: Func a b -> Bool
isEmpty Empty = True
isEmpty _ = False
-- | A version of 'map' for 'Func' trees.
funcMap :: (b -> c) -> Func a b -> Func a c
funcMap _ Empty = Empty
funcMap f (Leaf h l) = Leaf h $ map (A.second f) l
funcMap f (Branch p b l r) = Branch p b (funcMap f l) $ funcMap f r
-- | A version of 'foldl' for 'Func' trees.
funcFoldl :: (c -> a -> b -> c) -> c -> Func a b -> c
funcFoldl _ a Empty = a
funcFoldl f a (Leaf _ l) =
let (xs, ys) = unzip l
Just res = foldl2 f a xs ys in res
funcFoldl f a (Branch _ _ l r) = funcFoldl f (funcFoldl f a l) r
-- | A version of 'foldr' for 'Func' trees.
funcFoldr :: (a -> b -> c -> c) -> c -> Func a b -> c
funcFoldr _ a Empty = a
funcFoldr f a (Leaf _ l) =
let (xs, ys) = unzip l
Just res = foldr2 f a xs ys in res
funcFoldr f a (Branch _ _ l r) = funcFoldr f (funcFoldr f a r) l
-- | Converts a 'Func' tree to a sorted association list.
graph :: (Ord a, Ord b) => Func a b -> [(a, b)]
graph f = setify $ funcFoldl (\ a x y -> ((x, y):a)) [] f
-- | Converts a 'Func' tree to a sorted list of domain elements.
dom :: Ord a => Func a b -> [a]
dom f = setify $ funcFoldl (\ a x _ -> x:a) [] f
-- | Converts a 'Func' tree to a sorted list of range elements.
ran :: Ord b => Func a b -> [b]
ran f = setify $ funcFoldl (\ a _ y -> y:a) [] f
-- | Application for 'Func' trees.
applyd :: forall m a b. (Monad m, Hashable a, Ord a)
=> Func a b -> (a -> m b) -> a -> m b
applyd Empty d x = d x
applyd (Branch p b l r) d x
| (k `xor` p) .&. (b - 1) == 0 =
applyd (if k .&. b == 0 then l else r) d x
| otherwise = d x
where k = hash x
applyd (Leaf h l) d x
| h == hash x = applydRec l
| otherwise = d x
where applydRec :: [(a, b)] -> m b
applydRec [] = d x
applydRec ((a, b):t)
| x == a = return b
| x > a = applydRec t
| otherwise = d x
-- | Guarded application for 'Func' trees.
apply :: (MonadThrow m, Hashable a, Ord a) => Func a b -> a -> m b
apply f = applyd f (\_ -> fail' "apply")
-- | Application for 'Func' trees with a default value.
tryApplyd :: (Hashable a, Ord a) => Func a b -> a -> b -> b
tryApplyd f a d =
case runCatch $ applyd f (\ _ -> return d) a of
Right res -> res
_ -> d
-- | Predicate for testing if a value is defined in a 'Func' tree.
defined ::(Hashable a, Ord a) => Func a b -> a -> Bool
defined f x =
case runCatch $ apply f x of
Right{} -> True
_ -> False
-- | Undefine a value in a 'Func' tree.
undefine :: forall a b. (Hashable a, Ord a, Eq b) => a -> Func a b -> Func a b
undefine _ Empty = Empty
undefine x t@(Branch p b l r)
| hash x .&. b == 0 =
let l' = undefine x l in
if l' == l then t
else case l' of
Empty -> r
_ -> Branch p b l' r
| otherwise =
let r' = undefine x r in
if r' == r then t
else case r' of
Empty -> l
_ -> Branch p b l r'
undefine x t@(Leaf h l)
| h == hash x =
let l' = undefineRec l in
if l' == l then t
else if null l' then Empty
else Leaf h l'
| otherwise = t
where undefineRec :: [(a, b)] -> [(a, b)]
undefineRec [] = []
undefineRec l'@(ab@(a, _):xs)
| x == a = xs
| x < a = l'
| otherwise =
let xs' = undefineRec xs in
if xs' == xs then l' else ab:xs'
newBranch :: Int -> Func a b -> Int -> Func a b -> Func a b
newBranch p1 t1 p2 t2 =
let zp = p1 `xor` p2
b = zp .&. (-zp)
p = p1 .&. (b - 1) in
if p1 .&. b == 0 then Branch p b t1 t2
else Branch p b t2 t1
-- | Insert or update an element in a 'Func' tree.
(|->) :: forall a b. (Hashable a, Ord a) => a -> b -> Func a b -> Func a b
(x |-> y) Empty = Leaf (hash x) [(x, y)]
(x |-> y) t@(Branch p b l r)
| k .&. (b - 1) /= p =
newBranch p t k $ Leaf k [(x, y)]
| k .&. b == 0 = Branch p b ((x |-> y) l) r
| otherwise = Branch p b l $ (x |-> y) r
where k = hash x
(x |-> y) t@(Leaf h l)
| h == k = Leaf h $ defineRec l
| otherwise =
newBranch h t k $ Leaf k [(x, y)]
where k = hash x
defineRec :: [(a, b)] -> [(a, b)]
defineRec [] = [(x, y)]
defineRec l'@(ab@(a, _):xs)
| x == a = (x, y):xs
| x < a = (x, y):l'
| otherwise = ab:defineRec xs
-- | Combines two 'Func' trees.
combine :: forall a b. Ord a => (b -> b -> b) -> (b -> Bool)
-> Func a b -> Func a b -> Func a b
combine _ _ Empty t2 = t2
combine _ _ t1 Empty = t1
combine op z lf@(Leaf k _) br@(Branch p b l r)
| k .&. (b - 1) == p =
if k .&. b == 0
then case combine op z lf l of
Empty -> r
l' -> Branch p b l' r
else case combine op z lf r of
Empty -> l
r' -> Branch p b l r'
| otherwise = newBranch k lf p br
combine op z br@(Branch p b l r) lf@(Leaf k _)
| k .&. (b - 1) == p =
if k .&. b == 0
then case combine op z l lf of
Empty -> r
l' -> Branch p b l' r
else case combine op z r lf of
Empty -> l
r' -> Branch p b l r'
| otherwise = newBranch p br k lf
combine op z t1@(Branch p1 b1 l1 r1) t2@(Branch p2 b2 l2 r2)
| b1 < b2 =
if p2 .&. (b1 - 1) /= p1 then newBranch p1 t1 p2 t2
else if p2 .&. b1 == 0
then case combine op z l1 t2 of
Empty -> r1
l -> Branch p1 b1 l r1
else case combine op z r1 t2 of
Empty -> l1
r -> Branch p1 b1 l1 r
| b2 < b1 =
if p1 .&. (b2 - 1) /= p2 then newBranch p1 t1 p2 t2
else if p1 .&. b2 == 0
then case combine op z t1 l2 of
Empty -> r2
l -> Branch p2 b2 l r2
else case combine op z t1 r2 of
Empty -> l2
r -> Branch p2 b2 l2 r
| p1 == p2 =
case (combine op z l1 l2, combine op z r1 r2) of
(Empty, r) -> r
(l, Empty) -> l
(l, r) -> Branch p1 b1 l r
| otherwise = newBranch p1 t1 p2 t2
combine op z t1@(Leaf h1 l1) t2@(Leaf h2 l2)
| h1 == h2 =
let l = combineRec l1 l2 in
if null l then Empty else Leaf h1 l
| otherwise = newBranch h1 t1 h2 t2
where combineRec :: [(a, b)] -> [(a, b)] -> [(a, b)]
combineRec [] ys = ys
combineRec xs [] = xs
combineRec xs@(xy1@(x1, y1):xs') ys@(xy2@(x2, y2):ys')
| x1 < x2 = xy1:combineRec xs' ys
| x1 > x2 = xy2:combineRec xs ys'
| otherwise =
let y = op y1 y2
l = combineRec xs' ys' in
if z y then l else (x1, y):l
-- | Special case of '(|->)' applied to 'funcEmpty'.
(|=>) :: (Hashable a, Ord a) => a -> b -> Func a b
x |=> y = (x |-> y) funcEmpty
-- | Selects an arbitrary element from a 'Func' tree.
choose :: MonadThrow m => Func a b -> m (a, b)
choose Empty = fail' "choose"
choose (Leaf _ l) = tryHead l
choose (Branch _ _ t1 _) = choose t1
-- Maps
-- | A re-export of 'Map.empty'.
mapEmpty :: Map a b
mapEmpty = Map.empty
-- | A re-export of 'Map.insert'.
mapInsert :: Ord a => a -> b -> Map a b -> Map a b
mapInsert = Map.insert
-- | A re-export of 'Map.union'.
mapUnion :: Ord k => Map k a -> Map k a -> Map k a
mapUnion = Map.union
-- | A re-export of 'Map.delete'.
mapDelete :: Ord k => k -> Map k a -> Map k a
mapDelete = Map.delete
-- | A guarded re-export of 'Map.lookup'.
mapAssoc :: (MonadThrow m, Ord a) => a -> Map a b -> m b
mapAssoc x = maybeToFail "mapAssoc" . Map.lookup x
-- | A re-export of 'Map.elems'.
mapElems :: Map k a -> [a]
mapElems = Map.elems
-- | A re-export of 'Map.fromList'.
mapFromList :: Ord a => [(a, b)] -> Map a b
mapFromList = Map.fromList
-- | A re-export of 'Map.toList'.
mapToList :: Map a b -> [(a, b)]
mapToList = Map.toList
-- | A re-export of 'Map.map'.
mapMap :: (a -> b) -> Map k a -> Map k b
mapMap = Map.map
-- | A re-export of 'Map.foldrWithKey'.
mapFoldrWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
mapFoldrWithKey = Map.foldrWithKey
-- | A version of 'remove' for 'Map's based on 'Map.updateLookupWithKey'.
mapRemove :: (MonadThrow m, Ord k) => k -> Map k a -> m (a, Map k a)
mapRemove x m =
let (child, map') = Map.updateLookupWithKey (\ _ _ -> Nothing) x m in
case child of
Nothing -> fail' "mapRemove"
Just x' -> return (x', map')
-- | A re-export of 'Map.toAscList'.
mapToAscList :: Map k a -> [(k, a)]
mapToAscList = Map.toAscList
-- | A re-export of 'Text.append'.
append :: Text -> Text -> Text
append = Text.append
-- | A re-export of 'Text.cons'.
cons :: Char -> Text -> Text
cons = Text.cons
-- | A re-export of 'Text.snoc'.
snoc :: Text -> Char -> Text
snoc = Text.snoc
-- | A re-export of 'Text.pack'.
pack :: String -> Text
pack = Text.pack
-- | A re-export of 'Text.unpack'.
unpack :: Text -> String
unpack = Text.unpack
-- | A re-export of 'Text.head'.
textHead :: Text -> Char
textHead = Text.head
-- | A re-export of 'Text.tail'.
textTail :: Text -> Text
textTail = Text.tail
-- | A re-export of 'Text.null'.
textNull :: Text -> Bool
textNull = Text.null
-- | A re-export of 'Text.empty'.
textEmpty :: Text
textEmpty = Text.empty
-- | A re-export of 'Text.strip'.
textStrip :: Text -> Text
textStrip = Text.strip
-- | A re-export of 'Text.showt'.
textShow :: Text.TextShow a => a -> Text
textShow = Text.fromStrict . Text.showt
-- | A re-export of 'Text.words'.
textWords :: Text -> [Text]
textWords = Text.words
-- | A re-export of 'Text.unwords'.
textUnwords :: [Text] -> Text
textUnwords = Text.unwords
-- Acid State re-exports
-- | A re-export of 'State.get' from @Control.Monad.State@.
get :: State.MonadState s m => m s
get = State.get
-- | A re-export of 'State.put' from @Control.Monad.State@.
put :: State.MonadState s m => s -> m ()
put = State.put
-- | A re-export of 'Reader.ask' from @Control.Monad.Reader@.
ask :: Reader.MonadReader r m => m r
ask = Reader.ask
-- | A re-export of 'Acid.makeAcidic' from @Data.Acid@.
makeAcidic :: Name -> [Name] -> Q [Dec]
makeAcidic = Acid.makeAcidic
-- language type classes
{-$LangClasses
The following two classes are used as an ad hoc mechanism for sharing
\"language\" operations between different types. For example, both tactics
and conversions share a number of the same operations. Rather than having
multiple functions, such as @thenTac@ and @thenConv@, we've found it easier to
have a single, polymorphic function to use, '_THEN'.
The sequencing operations are seperated in their own class, 'LangSeq', because
their tactic instances have a reliance on the boolean logic theory. Rather
than unecessarily propogate this prerequisite for all members of the 'Lang'
class, we elected to separate them.
-}
{-|
The 'Lang' class defines common language operations and combinators not based
on sequencing.
-}
class Lang a where
{-|
A primitive language operation that always fails. Typically this is
written using 'throw'.
-}
_FAIL :: String -> a
-- | An instance of '_FAIL' with a fixed failure string.
_NO :: a
_NO = _FAIL "_NO"
-- | A primitive language operation that always succeeds.
_ALL :: a
{-|
A language combinator for branching based on failure. The language
equivalent of the '<|>' operator.
-}
_ORELSE :: a -> a -> a
-- | A language combinator that performs the first operation in a list.
_FIRST :: [a] -> a
_FIRST [] = _FAIL "_FIRST: empty list"
_FIRST xs = foldr1 _ORELSE xs
{-|
A language combinator that fails if the wrapped operation doesn't invoke
some change, i.e. a tactic fails to change the goal state.
-}
_CHANGED :: a -> a
{-|
A language combinator that prevents the wrapped operation from having an
effect if it fails. The language equivalent of the backtracking 'try'
operator.
-}
_TRY :: a -> a
_TRY x = x `_ORELSE` _ALL
{-|
A language combinator that annotates the wrapped operation with a provided
'String'. The language equivalent of 'note''.
-}
_NOTE :: String -> a -> a
{-|
The 'LangSeq' class defines common language operations and combinators based
on sequencing. See the note at the top of this section for more details as
to why these are separated on their own.
-}
class Lang a => LangSeq a where
-- | A language combinator that sequences operations.
_THEN :: a -> a -> a
{-|
A language combinator that repeatedly applies a language operation until
failure.
-}
_REPEAT :: a -> a
_REPEAT x = (x `_THEN` _REPEAT x) `_ORELSE` _ALL
{-|
A language combinator that performs every operation in a list
sequentially.
-}
_EVERY :: [a] -> a
_EVERY = foldr _THEN _ALL
| ecaustin/haskhol-core | src/HaskHOL/Core/Lib.hs | bsd-2-clause | 42,441 | 6 | 16 | 11,797 | 13,075 | 6,948 | 6,127 | 803 | 21 |
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, FlexibleInstances #-}
-- | Helpers for instantiating transitive and reflexive instances of Iterable.
module Data.Iterable.Instantiate(self_iterable ,
trans_iterable) where
import Language.Haskell.TH.Syntax
import Data.Iterable
import Data.Proxy(Proxy)
-- | Generates convenience function for iterating over a single object.
--self_iterable typA = gen_iterable typA typA [e| id |] [e| L.singleton |]
self_iterable typA =
[d| instance Iterable $(typA) $(typA) where
itmapM f a = f a
itfoldM f e a = f e a
itfoldr f e a = f a e
itfoldl f e a = f e a
itfoldl' f e a = f e a
itlength d a = 1
|]
-- | Generates a transitive instance of `Iterable` between $typA and $typC,
-- assuming existence of `Iterable` $typA $typB, and `Iterable` $typB $typC.
trans_iterable typA typB typC =
[d| instance Iterable $(typA) $(typC) where
itmapM f a = (itmapM :: (Monad m) => ( $(typB) -> m $(typB) ) -> $(typA) -> m $(typA) ) (itmapM f) a
itmap f a = (itmap :: ( $(typB) -> $(typB) ) -> $(typA) -> $(typA) ) (itmap f) a
itfoldM f e a = (itfoldM :: (Monad m) => (c -> $(typB) -> m c) -> c -> $(typA) -> m c ) (itfoldM f) e a
itfoldr f e a = (itfoldr :: ($(typB) -> c -> c) -> c -> $(typA) -> c ) (\bb cc -> itfoldr f cc bb) e a
itfoldl f e a = (itfoldl :: (c -> $(typB) -> c) -> c -> $(typA) -> c ) (itfoldl f) e a
itfoldl' f e a = (itfoldl' :: (c -> $(typB) -> c) -> c -> $(typA) -> c ) (itfoldl' f) e a
itlength _ a = (itfoldl' :: (c -> $(typB) -> c) -> c -> $(typA) -> c ) (\a b-> a + itlength (undefined :: Proxy $(typC)) b) 0 a
|]
| BioHaskell/iterable | Data/Iterable/Instantiate.hs | bsd-3-clause | 1,945 | 0 | 5 | 690 | 71 | 48 | 23 | 23 | 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.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Email.Rules
( rules ) where
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Email.Types (EmailData (..))
import qualified Duckling.Email.Types as TEmail
import Duckling.Regex.Types
import Duckling.Types
ruleEmail :: Rule
ruleEmail = Rule
{ name = "email"
, pattern =
[ regex "([\\w\\._+-]+@[\\w_-]+(\\.[\\w_-]+)+)"
]
, prod = \xs -> case xs of
(Token RegexMatch (GroupMatch (x:_)):_) ->
Just $ Token Email EmailData {TEmail.value = x}
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleEmail
]
| facebookincubator/duckling | Duckling/Email/Rules.hs | bsd-3-clause | 851 | 0 | 17 | 167 | 185 | 114 | 71 | 23 | 2 |
module Text.Nagato.Query.IO where
import Text.Nagato.Query.Trigram
import Text.Nagato.Models
import Data.Either.Unwrap
import Data.Serialize
import Data.ByteString as BS
writeModel :: FilePath -> [([Int], Probs (Trigram String))] -> IO()
writeModel filePath model = do
let bytes = encode model
BS.writeFile filePath bytes
readModel :: FilePath -> IO [([Int], Probs (Trigram String))]
readModel filePath = do
bytes <- BS.readFile filePath
let decoded = decode bytes :: Either String [([Int], Probs (Trigram String))]
return $ fromRight decoded
| haru2036/nl-query | Text/Nagato/Query/IO.hs | bsd-3-clause | 560 | 0 | 15 | 88 | 214 | 114 | 100 | 15 | 1 |
{-# LANGUAGE BangPatterns, OverloadedStrings #-}
-- |
-- Module: Data.Aeson.Encode.Builder
-- Copyright: (c) 2011 MailRank, Inc.
-- (c) 2013 Simon Meier <[email protected]>
-- License: Apache
-- Maintainer: Bryan O'Sullivan <[email protected]>
-- Stability: experimental
-- Portability: portable
--
-- Efficiently serialize a JSON value using the UTF-8 encoding.
module Data.Aeson.Encode.Builder
(
encodeToBuilder
, null_
, bool
, array
, emptyArray_
, emptyObject_
, object
, text
, string
, unquoted
, number
, ascii2
, ascii4
, ascii5
) where
import Data.Aeson.Types.Internal (Encoding(..), Value(..))
import Data.ByteString.Builder as B
import Data.ByteString.Builder.Prim as BP
import Data.ByteString.Builder.Scientific (scientificBuilder)
import Data.Char (ord)
import Data.Foldable (foldMap)
import Data.Monoid ((<>))
import Data.Scientific (Scientific, base10Exponent, coefficient)
import Data.Word (Word8)
import qualified Data.HashMap.Strict as HMS
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Vector as V
-- | Encode a JSON value to a "Data.ByteString" 'B.Builder'.
--
-- Use this function if you are encoding over the wire, or need to
-- prepend or append further bytes to the encoded JSON value.
encodeToBuilder :: Value -> Builder
encodeToBuilder Null = null_
encodeToBuilder (Bool b) = bool b
encodeToBuilder (Number n) = number n
encodeToBuilder (String s) = text s
encodeToBuilder (Array v) = array v
encodeToBuilder (Object m) = object m
-- | Encode a JSON null.
null_ :: Builder
null_ = BP.primBounded (ascii4 ('n',('u',('l','l')))) ()
-- | Encode a JSON boolean.
bool :: Bool -> Builder
bool = BP.primBounded (BP.condB id (ascii4 ('t',('r',('u','e'))))
(ascii5 ('f',('a',('l',('s','e'))))))
-- | Encode a JSON array.
array :: V.Vector Value -> Builder
array v
| V.null v = emptyArray__
| otherwise = B.char8 '[' <>
encodeToBuilder (V.unsafeHead v) <>
V.foldr withComma (B.char8 ']') (V.unsafeTail v)
where
withComma a z = B.char8 ',' <> encodeToBuilder a <> z
-- Encode a JSON object.
object :: HMS.HashMap T.Text Value -> Builder
object m = case HMS.toList m of
(x:xs) -> B.char8 '{' <> one x <> foldr withComma (B.char8 '}') xs
_ -> emptyObject__
where
withComma a z = B.char8 ',' <> one a <> z
one (k,v) = text k <> B.char8 ':' <> encodeToBuilder v
-- | Encode a JSON string.
text :: T.Text -> Builder
text t = B.char8 '"' <> unquoted t <> B.char8 '"'
-- | Encode a JSON string, without enclosing quotes.
unquoted :: T.Text -> Builder
unquoted t = TE.encodeUtf8BuilderEscaped escapeAscii t
-- | Encode a JSON string.
string :: String -> Builder
string t = B.char8 '"' <> BP.primMapListBounded go t <> B.char8 '"'
where go = BP.condB (> '\x7f') BP.charUtf8 (c2w >$< escapeAscii)
escapeAscii :: BP.BoundedPrim Word8
escapeAscii =
BP.condB (== c2w '\\' ) (ascii2 ('\\','\\')) $
BP.condB (== c2w '\"' ) (ascii2 ('\\','"' )) $
BP.condB (>= c2w '\x20') (BP.liftFixedToBounded BP.word8) $
BP.condB (== c2w '\n' ) (ascii2 ('\\','n' )) $
BP.condB (== c2w '\r' ) (ascii2 ('\\','r' )) $
BP.condB (== c2w '\t' ) (ascii2 ('\\','t' )) $
(BP.liftFixedToBounded hexEscape) -- fallback for chars < 0x20
where
hexEscape :: BP.FixedPrim Word8
hexEscape = (\c -> ('\\', ('u', fromIntegral c))) BP.>$<
BP.char8 >*< BP.char8 >*< BP.word16HexFixed
{-# INLINE escapeAscii #-}
c2w :: Char -> Word8
c2w c = fromIntegral (ord c)
-- | Encode a JSON number.
number :: Scientific -> Builder
number s
| e < 0 = scientificBuilder s
| otherwise = B.integerDec (coefficient s * 10 ^ e)
where
e = base10Exponent s
emptyArray_ :: Encoding
emptyArray_ = Encoding emptyArray__
emptyArray__ :: Builder
emptyArray__ = BP.primBounded (ascii2 ('[',']')) ()
emptyObject_ :: Encoding
emptyObject_ = Encoding emptyObject__
emptyObject__ :: Builder
emptyObject__ = BP.primBounded (ascii2 ('{','}')) ()
ascii2 :: (Char, Char) -> BP.BoundedPrim a
ascii2 cs = BP.liftFixedToBounded $ (const cs) BP.>$< BP.char7 >*< BP.char7
{-# INLINE ascii2 #-}
ascii4 :: (Char, (Char, (Char, Char))) -> BP.BoundedPrim a
ascii4 cs = BP.liftFixedToBounded $ (const cs) >$<
BP.char7 >*< BP.char7 >*< BP.char7 >*< BP.char7
{-# INLINE ascii4 #-}
ascii5 :: (Char, (Char, (Char, (Char, Char)))) -> BP.BoundedPrim a
ascii5 cs = BP.liftFixedToBounded $ (const cs) >$<
BP.char7 >*< BP.char7 >*< BP.char7 >*< BP.char7 >*< BP.char7
{-# INLINE ascii5 #-}
| nurpax/aeson | Data/Aeson/Encode/Builder.hs | bsd-3-clause | 4,661 | 0 | 14 | 975 | 1,502 | 818 | 684 | 101 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Prelude (IO)
import qualified Sound.Driver.Jack as Driver
import Sound.Amplifier
import Sound.Oscillators
import Language.Frontend
main :: IO ()
main = do
Driver.runAudioFun $(compile (square 440 48000 >>> amp 0.5))
| svenkeidel/hsynth | examples/ExampleJack.hs | bsd-3-clause | 318 | 0 | 13 | 80 | 82 | 46 | 36 | 10 | 1 |
import AI.MDP
import AI.MDP.GridWorld
gv = initVals $ absorb (2,2) 100 $ gridWorld (10, 10) 0.5 0 scatterActions (map (\x -> (x, 6)) [0..6])
main = do
putStrLn "Rewards:"
showRewards gv
putStrLn "\n\nInit Values:"
print gv
putStrLn "\n\nValues after 100 Iterations:"
print $ iterVals 100 gv
| chetant/mdp | test/Test.hs | bsd-3-clause | 305 | 1 | 11 | 60 | 130 | 63 | 67 | 10 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Language.Haskell.Pretty.PrettyUtils
-- Copyright :
-- License : AllRightsReserved
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- Utilities functions for pretty printting
--
-----------------------------------------------------------------------------
module Haskell.Pretty.PrettyUtils where
import Haskell.Syntax.Syntax(SrcLoc(..))
import qualified Text.PrettyPrint as P
infixl 5 $$$
-- | Varieties of layout we can use.
data PPLayout = PPOffsideRule -- ^ classical layout
| PPSemiColon -- ^ classical layout made explicit
| PPInLine -- ^ inline decls, with newlines between them
| PPNoLayout -- ^ everything on a single line
deriving Eq
type Indent = Int
-- | Pretty-printing parameters.
--
-- /Note:/ the 'onsideIndent' must be positive and less than all other indents.
data PPHsMode = PPHsMode {
-- | indentation of a class or instance
classIndent :: Indent,
-- | indentation of a @do@-expression
doIndent :: Indent,
-- | indentation of the body of a
-- @case@ expression
caseIndent :: Indent,
-- | indentation of the declarations in a
-- @let@ expression
letIndent :: Indent,
-- | indentation of the declarations in a
-- @where@ clause
whereIndent :: Indent,
-- | indentation added for continuation
-- lines that would otherwise be offside
onsideIndent :: Indent,
-- | blank lines between statements?
spacing :: Bool,
-- | Pretty-printing style to use
layout :: PPLayout,
-- | add GHC-style @LINE@ pragmas to output?
linePragmas :: Bool,
-- | not implemented yet
comments :: Bool
}
-- | The default mode: pretty-print using the offside rule and sensible
-- defaults.
defaultMode :: PPHsMode
defaultMode = PPHsMode{
classIndent = 8,
doIndent = 3,
caseIndent = 4,
letIndent = 4,
whereIndent = 6,
onsideIndent = 2,
spacing = True,
layout = PPOffsideRule,
linePragmas = False,
comments = True
}
-- | Pretty printing monad
newtype DocM s a = DocM (s -> a)
instance Functor (DocM s) where
fmap f xs = do x <- xs; return (f x)
instance Monad (DocM s) where
(>>=) = thenDocM
(>>) = then_DocM
return = retDocM
{-# INLINE thenDocM #-}
{-# INLINE then_DocM #-}
{-# INLINE retDocM #-}
{-# INLINE unDocM #-}
{-# INLINE getPPEnv #-}
thenDocM :: DocM s a -> (a -> DocM s b) -> DocM s b
thenDocM m k = DocM $ (\s -> case unDocM m $ s of a -> unDocM (k a) $ s)
then_DocM :: DocM s a -> DocM s b -> DocM s b
then_DocM m k = DocM $ (\s -> case unDocM m $ s of _ -> unDocM k $ s)
retDocM :: a -> DocM s a
retDocM a = DocM (\_s -> a)
unDocM :: DocM s a -> (s -> a)
unDocM (DocM f) = f
-- all this extra stuff, just for this one function.
getPPEnv :: DocM s s
getPPEnv = DocM id
-- So that pp code still looks the same
-- this means we lose some generality though
-- | The document type produced by these pretty printers uses a 'PPHsMode'
-- environment.
type Doc = DocM PPHsMode P.Doc
-- | Things that can be pretty-printed, including all the syntactic objects
-- in "Language.Haskell.Syntax".
class Pretty a where
-- | Pretty-print something in isolation.
pretty :: a -> Doc
-- | Pretty-print something in a precedence context.
prettyPrec :: Int -> a -> Doc
pretty = prettyPrec 0
prettyPrec _ = pretty
-- The pretty printing combinators
empty :: Doc
empty = return P.empty
nest :: Int -> Doc -> Doc
nest i m = m >>= return . P.nest i
-- Literals
text, ptext :: String -> Doc
text = return . P.text
ptext = return . P.text
char :: Char -> Doc
char = return . P.char
int :: Int -> Doc
int = return . P.int
integer :: Integer -> Doc
integer = return . P.integer
float :: Float -> Doc
float = return . P.float
double :: Double -> Doc
double = return . P.double
rational :: Rational -> Doc
rational = return . P.rational
-- Simple Combining Forms
parens, brackets, braces,quotes,doubleQuotes :: Doc -> Doc
parens d = d >>= return . P.parens
brackets d = d >>= return . P.brackets
braces d = d >>= return . P.braces
quotes d = d >>= return . P.quotes
doubleQuotes d = d >>= return . P.doubleQuotes
parensIf :: Bool -> Doc -> Doc
parensIf True = parens
parensIf False = id
-- Constants
semi,comma,colon,space,equals :: Doc
semi = return P.semi
comma = return P.comma
colon = return P.colon
space = return P.space
equals = return P.equals
lparen,rparen,lbrack,rbrack,lbrace,rbrace :: Doc
lparen = return P.lparen
rparen = return P.rparen
lbrack = return P.lbrack
rbrack = return P.rbrack
lbrace = return P.lbrace
rbrace = return P.rbrace
-- Combinators
(<>),(<+>),($$),($+$) :: Doc -> Doc -> Doc
aM <> bM = do{a<- aM;b<- bM;return (a P.<> b)}
aM <+> bM = do{a<- aM;b<- bM;return (a P.<+> b)}
aM $$ bM = do{a<- aM;b<- bM;return (a P.$$ b)}
aM $+$ bM = do{a<- aM;b<- bM;return (a P.$+$ b)}
hcat,hsep,vcat,sep,cat,fsep,fcat :: [Doc] -> Doc
hcat dl = sequence dl >>= return . P.hcat
hsep dl = sequence dl >>= return . P.hsep
vcat dl = sequence dl >>= return . P.vcat
sep dl = sequence dl >>= return . P.sep
cat dl = sequence dl >>= return . P.cat
fsep dl = sequence dl >>= return . P.fsep
fcat dl = sequence dl >>= return . P.fcat
-- Some More
hang :: Doc -> Int -> Doc -> Doc
hang dM i rM = do{d<- dM;r<- rM;return $ P.hang d i r}
-- Yuk, had to cut-n-paste this one from Pretty.hs
punctuate :: Doc -> [Doc] -> [Doc]
punctuate _ [] = []
punctuate p (d1:ds) = go d1 ds
where
go d [] = [d]
go d (e:es) = (d <> p) : go e es
-- | render the document with a given style and mode.
renderStyleMode :: P.Style -> PPHsMode -> Doc -> String
renderStyleMode ppStyle ppMode d = P.renderStyle ppStyle . unDocM d $ ppMode
-- | render the document with a given mode.
renderWithMode :: PPHsMode -> Doc -> String
renderWithMode = renderStyleMode P.style
-- | render the document with 'defaultMode'.
render :: Doc -> String
render = renderWithMode defaultMode
-- | pretty-print with a given style and mode.
prettyPrintStyleMode :: Pretty a => P.Style -> PPHsMode -> a -> String
prettyPrintStyleMode ppStyle ppMode = renderStyleMode ppStyle ppMode . pretty
-- | pretty-print with the default style and a given mode.
prettyPrintWithMode :: Pretty a => PPHsMode -> a -> String
prettyPrintWithMode = prettyPrintStyleMode P.style
-- | pretty-print with the default style and 'defaultMode'.
prettyPrint :: Pretty a => a -> String
prettyPrint = prettyPrintWithMode defaultMode
fullRenderWithMode :: PPHsMode -> P.Mode -> Int -> Float ->
(P.TextDetails -> a -> a) -> a -> Doc -> a
fullRenderWithMode ppMode m i f fn e mD =
P.fullRender m i f fn e $ (unDocM mD) ppMode
fullRender :: P.Mode -> Int -> Float -> (P.TextDetails -> a -> a)
-> a -> Doc -> a
fullRender = fullRenderWithMode defaultMode
-- Some utilities functions
maybePP :: (a -> Doc) -> Maybe a -> Doc
maybePP _ Nothing = empty
maybePP pp (Just a) = pp a
parenList :: [Doc] -> Doc
parenList = parens . myFsepSimple . punctuate comma
braceList :: [Doc] -> Doc
braceList = braces . myFsepSimple . punctuate comma
bracketList :: [Doc] -> Doc
bracketList = brackets . myFsepSimple
-- Wrap in braces and semicolons, with an extra space at the start in
-- case the first doc begins with "-", which would be scanned as {-
flatBlock :: [Doc] -> Doc
flatBlock = braces . (space <>) . hsep . punctuate semi
-- Same, but put each thing on a separate line
prettyBlock :: [Doc] -> Doc
prettyBlock = braces . (space <>) . vcat . punctuate semi
-- Monadic PP Combinators -- these examine the env
blankline :: Doc -> Doc
blankline dl = do{e<- getPPEnv;if spacing e && layout e /= PPNoLayout
then space $$ dl else dl}
topLevel :: Doc -> [Doc] -> Doc
topLevel header dl = do
e <- fmap layout getPPEnv
case e of
PPOffsideRule -> header $$ vcat dl
PPSemiColon -> header $$ prettyBlock dl
PPInLine -> header $$ prettyBlock dl
PPNoLayout -> header <+> flatBlock dl
ppBody :: (PPHsMode -> Int) -> [Doc] -> Doc
ppBody f dl = do
e <- fmap layout getPPEnv
i <- fmap f getPPEnv
case e of
PPOffsideRule -> nest i . vcat $ dl
PPSemiColon -> nest i . prettyBlock $ dl
_ -> flatBlock dl
ppBindings :: [Doc] -> Doc
ppBindings dl = do
e <- fmap layout getPPEnv
case e of
PPOffsideRule -> vcat dl
PPSemiColon -> vcat . punctuate semi $ dl
_ -> hsep . punctuate semi $ dl
($$$) :: Doc -> Doc -> Doc
a $$$ b = layoutChoice (a $$) (a <+>) b
mySep :: [Doc] -> Doc
mySep = layoutChoice mySep' hsep
where
-- ensure paragraph fills with indentation.
mySep' [x] = x
mySep' (x:xs) = x <+> fsep xs
mySep' [] = error "Internal error: mySep"
myVcat :: [Doc] -> Doc
myVcat = layoutChoice vcat hsep
myFsepSimple :: [Doc] -> Doc
myFsepSimple = layoutChoice fsep hsep
-- same, except that continuation lines are indented,
-- which is necessary to avoid triggering the offside rule.
myFsep :: [Doc] -> Doc
myFsep = layoutChoice fsep' hsep
where fsep' [] = empty
fsep' (d:ds) = do
e <- getPPEnv
let n = onsideIndent e
nest n (fsep (nest (-n) d:ds))
layoutChoice :: (a -> Doc) -> (a -> Doc) -> a -> Doc
layoutChoice a b dl = do e <- getPPEnv
if layout e == PPOffsideRule ||
layout e == PPSemiColon
then a dl else b dl
-- Prefix something with a LINE pragma, if requested.
-- GHC's LINE pragma actually sets the current line number to n-1, so
-- that the following line is line n. But if there's no newline before
-- the line we're talking about, we need to compensate by adding 1.
markLine :: SrcLoc -> Doc -> Doc
markLine loc doc = do
e <- getPPEnv
let y = srcLine loc
let line l =
text ("{-# LINE " ++ show l ++ " \"" ++ srcFilename loc ++ "\" #-}")
if linePragmas e then layoutChoice (line y $$) (line (y+1) <+>) doc
else doc
| emcardoso/CTi | src/Haskell/Pretty/PrettyUtils.hs | bsd-3-clause | 10,279 | 59 | 16 | 2,622 | 3,096 | 1,666 | 1,430 | 211 | 4 |
{-# LANGUAGE
TemplateHaskell,
TypeFamilies,
TupleSections,
MultiParamTypeClasses,
FunctionalDependencies,
FlexibleInstances,
OverloadedStrings,
GeneralizedNewtypeDeriving,
FlexibleContexts,
RankNTypes,
NoImplicitPrelude
#-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module DB
(
-- * Types
Session,
User(..),
nick,
name,
email,
pass,
admin,
WordReq(..),
submitted,
perUser,
Game(..),
title,
createdBy,
registerUntil,
begun,
ended,
wordReq,
groups,
nextPhasePlayers,
pastPhases,
currentPhase,
Phase(..),
timePerRound,
winnersPerRoom,
Round(..),
mbInfo,
RoundInfo(..),
score,
namerPenalty,
guesserPenalty,
discards,
ScheduleStatus(..),
Timer(..),
CurrentRound(..),
timer,
roundInfo,
Room(..),
winners,
currentRound,
absentees,
remainingPlayers,
filteredPastGames,
table,
pastGames,
schedule,
GlobalState(..),
games,
rooms,
users,
sessions,
dirty,
DB,
-- * Common lenses
uid,
created,
players,
-- * Stuff
emptyState,
userById,
mkSchedule,
execCommand,
reschedule,
-- * Methods
GetGlobalState(..),
GetSessions(..), SetSessions(..),
AddUser(..),
AddPlayer(..), RemovePlayer(..),
GetUser(..),
GetUserByNick(..), GetUserByNick'(..),
SetAdmin(..),
AddGame(..),
GetGame(..),
BeginGame(..),
SetGameGroups(..),
SetGameCurrentPhase(..),
FinishCurrentPhase(..),
StartRound(..),
SetRoundResults(..),
CancelCurrentRound(..),
FinishCurrentRound(..),
UpdateCurrentRound(..),
SetAbsent(..),
SetWinner(..),
SetWords(..),
PauseTimer(..),
AdvanceSchedule(..),
SetDirty(..), UnsetDirty(..),
)
where
-- General
import BasePrelude
-- Lenses
import Lens.Micro.Platform hiding ((&))
-- Containers
import Data.Map (Map)
import qualified Data.Set as S
import Data.Set (Set)
import qualified Data.Vector.Unboxed as U
-- Text
import qualified Data.Text.All as T
import Data.Text.All (Text)
-- Randomness
import Control.Monad.Random
import System.Random.Shuffle
-- Time
import Data.Time
-- Web
import Web.Spock (SessionId)
-- acid-state
import Data.Acid as Acid
import Data.SafeCopy
-- Passwords
import Crypto.Scrypt
-- Command-line parsing
import Options.Applicative.Simple
-- Exception handling
import Control.Exception.Enclosed
-- Local
import Utils
import Schedule
data User = User {
_userUid :: Uid User,
_userNick :: Text,
_userName :: Text,
_userEmail :: Maybe Text,
_userCreated :: UTCTime,
_userPass :: Maybe EncryptedPass,
_userAdmin :: Bool }
deriving (Show)
type Session = Maybe (Uid User)
data WordReq = WordReq {
-- | Already submitted words
_wordReqSubmitted :: Map (Uid User) (Set Text),
-- | How many words each user should submit
_wordReqPerUser :: Int }
deriving (Show)
data RoundInfo = RoundInfo {
_score :: Int,
_namerPenalty :: Int,
_guesserPenalty :: Int,
_discards :: Int }
deriving (Show)
data Round
= RoundNotYetPlayed
| RoundPlayed {_roundMbInfo :: RoundInfo}
| RoundImpossible -- e.g. the user can't play against themself
deriving (Show)
data ScheduleStatus
= ScheduleCalculating PartialSchedule
| ScheduleDone [(Uid User, Uid User)]
deriving (Show)
data Phase = Phase {
-- | In seconds
_phaseTimePerRound :: Int,
_phaseWinnersPerRoom :: Map Int Int,
_phaseRooms :: [Room] }
deriving (Show)
data CurrentRound = CurrentRound {
_currentRoundPlayers :: (Uid User, Uid User),
_currentRoundRoundInfo :: RoundInfo,
_currentRoundTimer :: Timer }
deriving (Show)
data Timer
= TimerGoing UTCTime -- when the timer will end
| TimerPaused Int -- how many seconds are left
deriving (Show)
data Room = Room {
_roomCurrentRound :: Maybe CurrentRound,
_roomPlayers :: [Uid User],
_roomAbsentees :: Set (Uid User),
_roomWinners :: Set (Uid User),
-- namer, guesser
_roomTable :: Map (Uid User, Uid User) Round,
-- | History of past games. Might be inaccunrate because of manual editing,
-- but is guaranteed to include all played games in the 'table' and not
-- include any of the not-played games.
_roomPastGames :: [(Uid User, Uid User)],
_roomSchedule :: ScheduleStatus }
deriving (Show)
data Game = Game {
_gameUid :: Uid Game,
_gameTitle :: Text,
_gameCreatedBy :: Uid User,
_gameWordReq :: Maybe WordReq,
_gameRegisterUntil :: UTCTime,
_gameBegun :: Bool,
_gameEnded :: Bool,
_gamePlayers :: Set (Uid User),
_gameNextPhasePlayers :: Set (Uid User),
-- | A generated division of players into groups
_gameGroups :: Maybe [[Uid User]],
_gamePastPhases :: [Phase],
_gameCurrentPhase :: Maybe Phase }
deriving (Show)
deriveSafeCopySimple 0 'base ''User
deriveSafeCopySimple 0 'base ''WordReq
deriveSafeCopySimple 0 'base ''ScheduleStatus
deriveSafeCopySimple 0 'base ''Phase
deriveSafeCopySimple 0 'base ''Timer
deriveSafeCopySimple 0 'base ''CurrentRound
deriveSafeCopySimple 0 'base ''RoundInfo
deriveSafeCopySimple 0 'base ''Round
deriveSafeCopySimple 0 'base ''Room
deriveSafeCopySimple 0 'base ''Game
makeFields ''User
makeFields ''WordReq
makeFields ''ScheduleStatus
makeFields ''Phase
makeFields ''CurrentRound
makeFields ''Room
makeFields ''Round
makeFields ''Game
makeLenses ''RoundInfo
remainingPlayers :: SimpleGetter Room [Uid User]
remainingPlayers = to $ \room -> room^.players \\ S.toList (room^.absentees)
filteredPastGames :: SimpleGetter Room [(Uid User, Uid User)]
filteredPastGames = to $ \room ->
filter (\(a,b) -> all (`S.notMember` (room^.absentees)) [a,b])
(room^.pastGames)
intPastGames :: Room -> U.Vector (Int, Int)
intPastGames room =
let rp = room^.remainingPlayers
playerIndex p = fromJust (elemIndex p rp)
in U.fromList (room^.filteredPastGames & each.each %~ playerIndex)
data GlobalState = GlobalState {
_globalStateUsers :: [User],
_globalStateGames :: [Game],
_globalStateSessions :: [(SessionId, UTCTime, Session)],
_globalStateDirty :: Bool }
deriving (Show)
deriveSafeCopySimple 0 'base ''GlobalState
makeFields ''GlobalState
type DB = AcidState GlobalState
roomByNum :: Uid Game -> Int -> Lens' GlobalState Room
roomByNum gameId num = singular $
gameById gameId.currentPhase._Just.rooms.ix (num-1)
hasUid :: HasUid a (Uid u) => Uid u -> a -> Bool
hasUid u x = x^.uid == u
userById :: Uid User -> Lens' GlobalState User
userById uid' = singular $
users.each . filtered (hasUid uid') `failing`
error ("userById: couldn't find user with uid " ++
T.unpack (uidToText uid'))
userByNick :: Text -> Lens' GlobalState User
userByNick nick' = singular $
userByNick' nick' `failing`
error ("userById: couldn't find user with nick " ++
T.unpack nick')
userByNick' :: Text -> Traversal' GlobalState User
userByNick' nick' = users.each . filtered ((== nick') . view nick)
gameById :: Uid Game -> Lens' GlobalState Game
gameById uid' = singular $
games.each . filtered (hasUid uid') `failing`
error ("gameById: couldn't find game with uid " ++
T.unpack (uidToText uid'))
emptyState :: GlobalState
emptyState = GlobalState {
_globalStateUsers = [],
_globalStateGames = [],
_globalStateSessions = [],
_globalStateDirty = True }
getGlobalState :: Acid.Query GlobalState GlobalState
getGlobalState = view id
getSessions :: Acid.Query GlobalState [(SessionId, UTCTime, Session)]
getSessions = view sessions
setSessions :: [(SessionId, UTCTime, Session)] -> Acid.Update GlobalState ()
setSessions x = sessions .= x
addUser
:: Uid User -- ^ New user's uid
-> Text -- ^ Nick
-> Text -- ^ Name
-> Maybe EncryptedPass -- ^ Pass
-> Maybe Text -- ^ Email
-> UTCTime -- ^ Creation time
-> Acid.Update GlobalState User
addUser uid' nick' name' pass' email' now = do
let user = User {
_userUid = uid',
_userNick = nick',
_userName = name',
_userEmail = email',
_userCreated = now,
_userPass = pass',
_userAdmin = False }
users %= (user:)
return user
addPlayer :: Uid Game -> Uid User -> Acid.Update GlobalState ()
addPlayer gameId userId = do
gameById gameId . players %= S.insert userId
gameById gameId . groups .= Nothing
removePlayer :: Uid Game -> Uid User -> Acid.Update GlobalState ()
removePlayer gameId userId = do
gameById gameId . players %= S.delete userId
gameById gameId . wordReq . _Just . submitted . at userId .= Nothing
gameById gameId . groups .= Nothing
getUser :: Uid User -> Acid.Query GlobalState User
getUser uid' = view (userById uid')
getUserByNick :: Text -> Acid.Query GlobalState User
getUserByNick nick' = view (userByNick nick')
getUserByNick' :: Text -> Acid.Query GlobalState (Maybe User)
getUserByNick' nick' = preview (userByNick' nick')
setAdmin :: Uid User -> Bool -> Acid.Update GlobalState ()
setAdmin userId adm = userById userId . admin .= adm
addGame
:: Uid Game -- ^ Uid
-> Text -- ^ Title
-> Uid User -- ^ Created by
-> Maybe WordReq -- ^ Word requirements
-> UTCTime -- ^ “Register until”
-> Set (Uid User) -- ^ Initial set of players
-> Acid.Update GlobalState Game
addGame uid' title' createdBy' wordReq' registerUntil' players' = do
let game' = Game {
_gameUid = uid',
_gameTitle = title',
_gameCreatedBy = createdBy',
_gameWordReq = wordReq',
_gameRegisterUntil = registerUntil',
_gameBegun = False,
_gameEnded = False,
_gamePlayers = players',
_gameNextPhasePlayers = mempty,
_gameGroups = Nothing,
_gamePastPhases = [],
_gameCurrentPhase = Nothing }
games %= (game':)
return game'
getGame :: Uid Game -> Acid.Query GlobalState Game
getGame uid' = view (gameById uid')
beginGame :: Uid Game -> Acid.Update GlobalState ()
beginGame gameId = do
game' <- use (gameById gameId)
gameById gameId . begun .= True
gameById gameId . nextPhasePlayers .= game'^.players
setGameGroups :: Uid Game -> Maybe [[Uid User]] -> Acid.Update GlobalState ()
setGameGroups gameId val = gameById gameId . groups .= val
setGameCurrentPhase :: Uid Game -> Phase -> Acid.Update GlobalState ()
setGameCurrentPhase gameId val = gameById gameId . currentPhase .= Just val
finishCurrentPhase :: Uid Game -> Acid.Update GlobalState ()
finishCurrentPhase gameId = do
game' <- use (gameById gameId)
case game'^.currentPhase of
Nothing -> return ()
Just p -> do
gameById gameId . currentPhase .= Nothing
gameById gameId . pastPhases %= (++ [p])
gameById gameId . nextPhasePlayers .= S.unions (p^..rooms.each.winners)
gameById gameId . groups .= Nothing
startRound
:: Uid Game
-> Int -- ^ Room
-> UTCTime -- ^ Current time
-> Acid.Update GlobalState ()
startRound gameId roomNum now = do
let roomLens :: Lens' GlobalState Room
roomLens = roomByNum gameId roomNum
phase' <- use (singular (gameById gameId.currentPhase._Just))
room' <- use roomLens
let timerEnd = fromIntegral (phase'^.timePerRound) `addUTCTime` now
roomLens.currentRound .= Just CurrentRound {
_currentRoundPlayers = case room'^.schedule of
ScheduleCalculating{} -> error "startRound: no schedule"
ScheduleDone [] -> error "startRound: no rounds"
ScheduleDone (x:_) -> x,
_currentRoundRoundInfo = RoundInfo {
_score = 0,
_namerPenalty = 0,
_guesserPenalty = 0,
_discards = 0 },
_currentRoundTimer = TimerGoing timerEnd }
setRoundResults
:: Uid Game
-> Int -- ^ Room
-> (Uid User, Uid User) -- ^ Namer, guesser
-> Round -- ^ Round
-> Acid.Update GlobalState ()
setRoundResults gameId roomNum pls roundRes = do
let roomLens :: Lens' GlobalState Room
roomLens = roomByNum gameId roomNum
old <- roomLens.table.at pls <<.= Just roundRes
-- Now we have to update 'pastGames' and the schedule
room <- use roomLens
case (fromMaybe RoundNotYetPlayed old, roundRes) of
(RoundNotYetPlayed, RoundPlayed{}) -> do
roomLens.pastGames %= (<> [pls])
case room^.schedule of
ScheduleCalculating _ -> return ()
ScheduleDone sch ->
roomLens.schedule .= ScheduleDone (delete pls sch)
(RoundImpossible, RoundPlayed{}) -> do
roomLens.pastGames %= (<> [pls])
case room^.schedule of
ScheduleCalculating _ -> return ()
ScheduleDone sch ->
roomLens.schedule .= ScheduleDone (delete pls sch)
(RoundPlayed{}, RoundNotYetPlayed) -> do
roomLens.pastGames %= delete pls
case room^.schedule of
ScheduleCalculating _ -> return ()
ScheduleDone sch ->
roomLens.schedule .= ScheduleDone (sch ++ [pls])
(RoundPlayed{}, RoundImpossible) ->
roomLens.pastGames %= delete pls
_other -> return ()
cancelCurrentRound
:: Uid Game
-> Int
-> Acid.Update GlobalState ()
cancelCurrentRound gameId roomNum = do
roomByNum gameId roomNum.currentRound .= Nothing
finishCurrentRound
:: Uid Game
-> Int
-> Acid.Update GlobalState ()
finishCurrentRound gameId roomNum = do
mbCr <- use (roomByNum gameId roomNum.currentRound)
case mbCr of
Nothing -> return ()
Just cr -> do
setRoundResults gameId roomNum (cr^.players)
(RoundPlayed (cr^.roundInfo))
roomByNum gameId roomNum.currentRound .= Nothing
updateCurrentRound
:: Uid Game
-> Int
-> Int
-> Int
-> Int
-> Int
-> Acid.Update GlobalState ()
updateCurrentRound gameId roomNum scoreD namerPenD guesserPenD discardsD = do
roomByNum gameId roomNum.currentRound._Just.roundInfo %=
over score (\x -> max 0 (x+scoreD)) .
over namerPenalty (\x -> max 0 (x+namerPenD)) .
over guesserPenalty (\x -> max 0 (x+guesserPenD)) .
over discards (\x -> max 0 (x+discardsD))
setAbsent
:: Uid Game
-> Int -- ^ Room
-> Uid User -- ^ Player
-> Bool -- ^ Absent = 'True'
-> UTCTime -- ^ Current time
-> Acid.Update GlobalState ()
setAbsent gameId roomNum playerId absent now = do
let roomLens :: Lens' GlobalState Room
roomLens = roomByNum gameId roomNum
room <- use roomLens
if absent
then do
roomLens.absentees %= S.insert playerId
when (any (== playerId) (room^..currentRound._Just.players.each)) $
pauseTimer gameId roomNum True now
else do
roomLens.absentees %= S.delete playerId
setWinner
:: Uid Game
-> Int -- ^ Room
-> Uid User -- ^ Player
-> Bool -- ^ Winner = 'True'
-> Acid.Update GlobalState ()
setWinner gameId roomNum playerId winner = do
let roomLens :: Lens' GlobalState Room
roomLens = roomByNum gameId roomNum
if winner then roomLens.winners %= S.insert playerId
else roomLens.winners %= S.delete playerId
setWords :: Uid Game -> Uid User -> [Text] -> Acid.Update GlobalState ()
setWords gameId userId ws =
gameById gameId.wordReq._Just.submitted.at userId .= Just (S.fromList ws)
pauseTimer
:: Uid Game
-> Int
-> Bool
-> UTCTime -- ^ Current time
-> Acid.Update GlobalState ()
pauseTimer gameId roomNum pause now = do
roomByNum gameId roomNum.currentRound._Just.timer %= \tmr ->
case (tmr, pause) of
(TimerGoing t, True) -> TimerPaused (max 0 (round (diffUTCTime t now)))
(TimerPaused t, False) -> TimerGoing (fromIntegral t `addUTCTime` now)
_ -> tmr
mkSchedule :: [Uid User] -> Schedule -> [(Uid User, Uid User)]
mkSchedule players' sch = U.toList sch & each.each %~ (players'!!)
advanceSchedule
:: Uid Game
-> Int
-> PartialSchedule
-> Either PartialSchedule Schedule
-> Acid.Update GlobalState ()
advanceSchedule gameId roomNum ps ps' = do
let roomLens :: Lens' GlobalState Room
roomLens = roomByNum gameId roomNum
room <- use roomLens
roomLens.schedule .= case room^.schedule of
ScheduleCalculating s
| s /= ps -> room^.schedule
| otherwise -> case ps' of
Left x -> ScheduleCalculating x
Right x -> ScheduleDone (mkSchedule (room^.remainingPlayers) x)
ScheduleDone _ -> room^.schedule
setPartialSchedule
:: Uid Game
-> Int
-> [Uid User] -- ^ Non-absent players
-> [(Uid User, Uid User)] -- ^ Past games of non-absent players
-> Schedule
-> Acid.Update GlobalState ()
setPartialSchedule gameId roomNum players' pastGames' sch = do
let roomLens :: Lens' GlobalState Room
roomLens = roomByNum gameId roomNum
room <- use roomLens
let playerCount = length players'
roundsLeft = playerCount*(playerCount-1) - length pastGames'
iters | roundsLeft <= 3 = 50000
| roundsLeft <= 6 = 100000
| otherwise = 400000
when (room^.remainingPlayers == players' &&
room^.filteredPastGames == pastGames') $
roomLens.schedule .= ScheduleCalculating (PartialSchedule {
_schPlayerCount = playerCount,
_schPastGames = intPastGames room,
_schCurrent = sch,
_schBest = sch,
_schIterationsTotal = iters,
_schIterationsLeft = iters })
setDirty :: Acid.Update GlobalState ()
setDirty = dirty .= True
unsetDirty :: Acid.Update GlobalState Bool
unsetDirty = dirty <<.= False
makeAcidic ''GlobalState [
'getGlobalState,
'getSessions, 'setSessions,
'addUser,
'addPlayer, 'removePlayer,
'getUser,
'getUserByNick, 'getUserByNick',
'setAdmin,
'addGame,
'getGame,
'beginGame,
'setGameGroups,
'setGameCurrentPhase,
'finishCurrentPhase,
'startRound,
'setRoundResults,
'setAbsent,
'setWinner,
'setWords,
'pauseTimer,
'cancelCurrentRound,
'finishCurrentRound,
'updateCurrentRound,
'advanceSchedule,
'setPartialSchedule,
'setDirty, 'unsetDirty
]
reschedule :: DB -> Uid Game -> Int -> IO ()
reschedule db gameId roomNum = do
game' <- Acid.query db (GetGame gameId)
let room = game'^?!currentPhase._Just.rooms.ix (roomNum-1)
sch <- randomSchedule (length (room^.remainingPlayers))
(intPastGames room)
Acid.update db $
SetPartialSchedule gameId roomNum
(room^.remainingPlayers) (room^.filteredPastGames) sch
execCommand :: DB -> String -> IO ()
execCommand db s = do
let res = execParserPure (prefs showHelpOnError) parserInfo (breakArgs s)
case res of
Success ((), io) -> catchAny io $ \e ->
if isJust (fromException e :: Maybe ExitCode)
then throwIO e
else print e
Failure f -> do
let (msg, _) = renderFailure f ""
putStrLn msg
CompletionInvoked _ -> error "completion invoked"
where
breakArgs "" = []
breakArgs (x:xs)
| x == '"' = let (l, r) = break (== '"') xs
in read (x:l++"\"") : breakArgs (drop 1 r)
| isSpace x = breakArgs xs
| otherwise = let (l, r) = break (\c -> isSpace c || c == '"') xs
in (x:l) : breakArgs r
userArg = argument
(do input <- T.pack <$> str
return $ case T.stripPrefix "id:" input of
Nothing -> Right input
Just x -> Left (Uid x))
(metavar "(NICK|id:ID)")
gameArg = Uid . T.pack <$> strArgument (metavar "GAME")
findUser = either (Acid.query db . GetUser)
(Acid.query db . GetUserByNick)
addCommand' cmd descr act = addCommand cmd descr (const act) (pure ())
parserInfo = info parser mempty
parser = simpleParser (pure ()) $ do
addCommand' "exit"
"Stop the server"
(exitSuccess)
addCommand' "sessions"
"Print open sessions"
(do ss <- Acid.query db GetSessions
for_ ss $ \(_, time, content) -> do
printf " * %s: %s\n" (show time) (show content)
)
addCommand "user"
"Show information about a user"
(\u -> do
user <- findUser u
printf "%s (%s)\n" (user^.name) (user^.nick)
printf "\n"
printf " * uid %s\n" (uidToText (user^.uid))
printf " * email %s\n" (fromMaybe "none" (user^.email))
printf " * created %s\n" (show (user^.created))
printf " * admin %s\n" (show (user^.admin))
)
userArg
addCommand' "users"
"List users"
(do us <- view users <$> Acid.query db GetGlobalState
for_ us $ \u ->
printf " * %s (%s)\n" (u^.name) (u^.nick)
)
addCommand "users.add"
"Create a new user"
(\(nick', name', pass', email') -> do
uid' <- randomShortUid
now <- getCurrentTime
encPass <- encryptPassIO' (Pass (T.encodeUtf8 pass'))
Acid.update db $
AddUser uid' nick' name' (Just encPass) (Just email') now
printf "uid: %s\n" (uidToText uid')
)
(fmap (each %~ T.pack) $
(,,,) <$> strArgument (metavar "NICK")
<*> strArgument (metavar "NAME")
<*> strArgument (metavar "PASS")
<*> strArgument (metavar "EMAIL"))
addCommand "users.admin"
"Make someone an admin"
(\u -> do
user <- findUser u
Acid.update db $
SetAdmin (user^.uid) True
)
userArg
addCommand "users.unadmin"
"Make someone an ordinary user"
(\u -> do
user <- findUser u
Acid.update db $
SetAdmin (user^.uid) False
)
userArg
addCommand' "games"
"List games"
(do gs <- view games <$> Acid.query db GetGlobalState
for_ gs $ \g ->
printf " * %s (%s)\n" (g^.title) (uidToText (g^.uid))
)
addCommand "game.reg"
"Register a user for the game"
(\(g, u) -> do
user <- findUser u
Acid.update db (AddPlayer g (user^.uid))
)
((,) <$> gameArg <*> userArg)
addCommand' "populate"
"Generate random users and games"
(do -- generating users
putStrLn "Generating users u{0..199}"
putStrLn "(passwords = nicks; users 0..19 are admins)"
generatedUsers <- for [0..199::Int] $ \i -> do
let nick' = T.format "u{}" [i]
name' = T.format "User #{}" [i]
email' = T.format "u{}@hat.hat" [i]
uid' <- randomShortUid
now <- getCurrentTime
encPass <- encryptPassIO' (Pass (T.encodeUtf8 nick'))
u <- Acid.update db $
AddUser uid' nick' name' (Just encPass) (Just email') now
when (i < 20) $ Acid.update db $
SetAdmin uid' True
when (i `mod` 10 == 0) $
putStr "."
return u
putStrLn ""
-- generating games
putStrLn "Generating games g{0..9} with n×10 players in each"
for_ [0..9::Int] $ \i -> do
let title' = T.format "Game-{}" [i]
wordReq' = Just (WordReq mempty 10)
players' <- S.fromList . map (view uid) . take (i*10) <$>
shuffleM generatedUsers
delay <- (60 *) <$> getRandomR (0, 120::Int)
registerUntil' <- addUTCTime (fromIntegral delay) <$>
getCurrentTime
uid' <- randomShortUid
createdBy' <- view uid <$> uniform generatedUsers
Acid.update db $
AddGame uid' title' createdBy' wordReq' registerUntil' players'
putStr "."
putStrLn ""
)
addCommand "room.reschedule"
"Generate a new schedule for a room"
(\(gameId, roomNum) -> reschedule db gameId roomNum)
((,) <$> gameArg
<*> argument auto (metavar "ROOM"))
| neongreen/hat | src/DB.hs | bsd-3-clause | 24,026 | 0 | 25 | 6,388 | 7,407 | 3,846 | 3,561 | -1 | -1 |
module Servant.Servant.Utils where
infixl 4 <$$>
(<$$>) :: (Functor f, Functor f') => (a -> b) -> f (f' a) -> f (f' b)
(<$$>) = fmap . fmap
| jkarni/servant-servant | src/Servant/Servant/Utils.hs | bsd-3-clause | 141 | 0 | 10 | 30 | 78 | 44 | 34 | 4 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.APPLE.RGB422
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.APPLE.RGB422 (
-- * Extension Support
glGetAPPLERGB422,
gl_APPLE_rgb_422,
-- * Enums
pattern GL_RGB_422_APPLE,
pattern GL_RGB_RAW_422_APPLE,
pattern GL_UNSIGNED_SHORT_8_8_APPLE,
pattern GL_UNSIGNED_SHORT_8_8_REV_APPLE
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
| haskell-opengl/OpenGLRaw | src/Graphics/GL/APPLE/RGB422.hs | bsd-3-clause | 741 | 0 | 5 | 103 | 62 | 45 | 17 | 10 | 0 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NamedFieldPuns #-}
module Test.Complexity.Chart ( statsToChart
, quickStatsToChart
, showStatsChart
) where
import Graphics.Rendering.Chart
import Graphics.Rendering.Chart.Gtk
import Data.Accessor
import Data.List (intercalate)
import Data.Colour
import Data.Colour.Names
import Test.Complexity.Base ( MeasurementStats(..)
, Stats(..)
)
statsToChart :: [(MeasurementStats, Colour Double)] -> Layout1 Double Double
statsToChart [] = defaultLayout1
statsToChart xs = layout1_title ^= intercalate ", " [msDesc | (MeasurementStats {msDesc}, _) <- xs]
$ layout1_plots ^= concat [map Left $ statsToPlots colour stats | (stats, colour) <- xs]
$ layout1_left_axis .> laxis_title ^= "time (ms)"
$ layout1_bottom_axis .> laxis_title ^= "input size (n)"
$ defaultLayout1
quickStatsToChart :: [MeasurementStats] -> Layout1 Double Double
quickStatsToChart xs = statsToChart $ zip xs $ cycle colours
where colours = [ blue
, red
, green
, darkgoldenrod
, orchid
, sienna
, darkcyan
, olivedrab
, silver
]
statsToPlots :: Colour Double -> MeasurementStats -> [Plot Double Double]
statsToPlots c stats = [ plot_legend ^= [] $ toPlot cpuMinMax
, plot_legend ^= [] $ toPlot cpuMin
, plot_legend ^= [] $ toPlot cpuMax
, toPlot cpuMean
, plot_legend ^= [] $ toPlot cpuErr
, plot_legend ^= [] $ toPlot cpuMeanPts
]
where meanLineColour = opaque c
meanPointColour = opaque $ blend 0.5 c black
stdDevColour = withOpacity c 0.7
minMaxEdgeColour = withOpacity c 0.2
minMaxAreaColour = withOpacity c 0.05
cpuMean = plot_lines_values ^= [zip xs ys_cpuMean2]
$ plot_lines_style .> line_color ^= meanLineColour
$ plot_lines_title ^= msDesc stats
$ defaultPlotLines
cpuMin = plot_lines_values ^= [zip xs ys_cpuMin]
$ plot_lines_style .> line_color ^= minMaxEdgeColour
$ defaultPlotLines
cpuMax = plot_lines_values ^= [zip xs ys_cpuMax]
$ plot_lines_style .> line_color ^= minMaxEdgeColour
$ defaultPlotLines
cpuMeanPts = plot_points_values ^= zip xs ys_cpuMean2
$ plot_points_style ^= filledCircles 2 meanPointColour
$ defaultPlotPoints
cpuMinMax = plot_fillbetween_values ^= zip xs (zip ys_cpuMin ys_cpuMax)
$ plot_fillbetween_style ^= solidFillStyle minMaxAreaColour
$ defaultPlotFillBetween
cpuErr = plot_errbars_values ^= [symErrPoint x y 0 e | (x, y, e) <- zip3 xs ys_cpuMean vs_cpuStdDev]
$ plot_errbars_line_style .> line_color ^= stdDevColour
$ defaultPlotErrBars
ps = msSamples stats
xs = map (fromIntegral . fst) ps
ys_cpuMean = map (statsMean . snd) ps
ys_cpuMean2 = map (statsMean2 . snd) ps
ys_cpuMin = map (statsMin . snd) ps
ys_cpuMax = map (statsMax . snd) ps
vs_cpuStdDev = map (statsStdDev . snd) ps
showStatsChart :: [MeasurementStats] -> IO ()
showStatsChart xs = renderableToWindow (toRenderable $ quickStatsToChart xs) 640 480
| adarqui/Complexity | Test/Complexity/Chart.hs | bsd-3-clause | 3,773 | 0 | 21 | 1,395 | 865 | 457 | 408 | 71 | 1 |
{-# LANGUAGE TemplateHaskell,TypeOperators#-}
module Product where
import Data.Monoid hiding(Product)
import Data.Functor.Product
import Data.Traversable
import Data.Functor.Compose
import Data.Distributive
import CartesianProduct
import Control.Applicative
import Control.Lens.TH
import SemiProduct
import Linear.Matrix
import Linear.Vector
class FProduct t where
_ffst :: Functor f => (g a -> f ( g a)) -> t g h a -> f (t g h a)
_fsnd :: Functor f => (h a -> f ( h a)) -> t g h a -> f (t g h a)
instance FProduct (:|:) where
_ffst f ( a :|: b ) = ( :|: b) <$> f a
_fsnd f ( a :|: b ) = ( a :|: ) <$> f b
instance FProduct Product where
_ffst f ( a `Pair` b ) = ( `Pair` b) <$> f a
_fsnd f ( a `Pair` b ) = ( a `Pair` ) <$> f b
instance FProduct (:>:) where
_ffst f ( a :>: b ) = ( :>: b) <$> f a
_fsnd f ( a :>: b ) = ( a :>: ) <$> f b
| massudaw/mtk | Product.hs | bsd-3-clause | 867 | 0 | 13 | 207 | 396 | 216 | 180 | 25 | 0 |
module TypeSystem.Parser.ExpressionParser (MEParseTree, typeAs, parseExpression, parseExpression', dynamicTranslate) where
{-
This module defines a parser for expressions.
In this approach, we tokenize first to a tree, and then try to match a rule with it by typing the rule.
-}
import TypeSystem.Parser.ParsingUtils
import TypeSystem.Parser.BNFParser
import TypeSystem.Parser.TargetLanguageParser
import TypeSystem.TypeSystemData
import Utils.Utils
import Utils.ToString
import Graphs.Lattice
import Text.Parsec
import Data.Maybe
import Data.Char
import Text.Read (readMaybe)
import qualified Data.Map as M
import Data.Map (Map)
import Data.List (intercalate, isPrefixOf, nub)
import Data.Either
import Control.Monad
import Control.Arrow ((&&&))
-- Simple parsetree, only knowing of tokens. Mirrors 'expressions' from typesystem, but with less metainfo
data MEParseTree = MePtToken String
| MePtSeq [MEParseTree]
| MePtVar Name
| MePtInt Int
| MePtCall Name Bool (Maybe TypeName) [MEParseTree] -- builtin if the bool is True, might provide a type in that case
| MePtAscription Name MEParseTree
| MePtEvalContext Name MEParseTree -- The type of the EvaluationContext is derived... from, well the context :p
deriving (Show, Ord, Eq)
fromMePtToken (MePtToken s) = Just s
fromMePtToken _ = Nothing
instance ToString MEParseTree where
toParsable = showMEPT
showMEPT (MePtToken s) = show s
showMEPT (MePtSeq pts) = pts |> showMEPT & unwords & inParens
showMEPT (MePtVar v) = v
showMEPT (MePtInt i) = show i
showMEPT (MePtCall n bi biTp args)
= (if bi then "!" else "") ++ n ++ maybe "" (":"++) biTp ++ inParens (args |> showMEPT & intercalate ", ")
showMEPT (MePtAscription n pt) = inParens (showMEPT pt++" : "++n)
showMEPT (MePtEvalContext n expr) = n++"["++ showMEPT expr ++"]"
{- Given a context (knwon function typings + bnf syntax), given a bnf rule (as type),
the parsetree is interpreted/typed following the bnf syntax.
-}
typeAs :: Map Name Type -> Syntax -> TypeName -> MEParseTree -> Either String Expression
typeAs functions rules ruleName pt
= inMsg ("While typing "++toParsable pt++" against "++ruleName) $
do when (isDissapearing $ BNFRuleCall ruleName) $ _dissapearingMsg ruleName
matchTyping functions rules (BNFRuleCall ruleName) (ruleName, error "Should not be used") pt
_dissapearingMsg ruleName
= Left $ "Trying to match against "++show ruleName++", which is a dissapearing builtin, thus it's no use matching it"
-- we compare the expected parse type (known via the BNF) and the expression we got
matchTyping :: Map Name Type -> Syntax -> BNF -> (TypeName, Int) -> MEParseTree -> Either String Expression
matchTyping f r (BNFRuleCall ruleCall) tp (MePtAscription as expr)
| not (alwaysIsA r as ruleCall)
= Left $ "Invalid cast: "++ruleCall++" is not a "++as
| otherwise = typeAs f r as expr |> MAscription as
matchTyping f r bnf tp c@(MePtAscription as expr)
= Left $ "Invalid cast: '"++toParsable c++"' could not be matched with '"++toParsable bnf++"'"
matchTyping _ _ (BNFRuleCall ruleCall) tp (MePtVar nm)
| nm == "_" = return $ MVar topSymbol "_"
| otherwise = return $ MVar ruleCall nm
matchTyping _ _ exp tp (MePtVar nm)
| nm == "_" = return $ MVar topSymbol "_"
| otherwise
= Left $ "Non-rulecall (expected: "++toParsable exp++") with a var "++ nm
matchTyping f r bnf (tp, _) ctx@(MePtEvalContext nm hole@(MePtVar someName))
= inMsg ("While typing the evalution context (with only an identifier as hole)"++ toParsable ctx) $
do let types = bnfNames r
let options = types & filter (`isPrefixOf` someName)
let actualType = head options
when (null options) $ Left ("The type of the lifted-out expression is not found: "++someName
++"\nAn identifier should start with its type(or BNF-rulename)."
++"\nAvailable types are: "++showComma types)
hole' <- typeAs f r actualType hole
let holeAsc = MAscription actualType hole'
return $ MEvalContext tp nm hole'
matchTyping f r bnf (tp, _) ctx@(MePtEvalContext nm expr)
= inMsg ("While typing the evaluation context (which has an expression as hole)"++toParsable ctx) $
do let possibleTypes = bnf & calledRules >>= reachableVia r :: [TypeName]
let possibleTypings = possibleTypes |> flip (typeAs f r) expr :: [Either String Expression]
let successfullTypings = zip possibleTypes possibleTypings |> sndEffect & rights :: [(TypeName, Expression)]
let successfull = successfullTypings |> fst & nub :: [TypeName]
let successfull' = successfull & smallestCommonType' r :: Maybe TypeName
let ambiguousTypingErr = Left $
"Trying a possible typing for the expression "++toParsable expr++" is ambiguous, as it can be typed as "++showComma successfull
++"\nAdd a type annotation to resolve this: "++nm++"[ ("++toParsable expr ++" : someType) ]"
inMsg "No typing for the hole can be found" $ when (null successfull) $ Left (possibleTypings & lefts & unlines & indent)
when (isNothing successfull') ambiguousTypingErr
let expr' = successfullTypings & filter ((== fromJust successfull') . fst) & head & snd
return $ MEvalContext tp nm expr'
-- Builtin function
matchTyping f s (BNFRuleCall ruleName) _ (MePtCall fNm True returnTypAct args)
= do when (isDissapearing $ BNFRuleCall ruleName) $ _dissapearingMsg ruleName
let fNm' = show ('!':fNm)
let notFoundMsg = "Builtin function "++fNm'++" is not defined. Consult the reference manual for a documentation about builtin functions."
++"\nKnown builtins are:\n"++(builtinFunctions' & M.keys & unlines & indent)
funcDef <- checkExists fNm builtinFunctions' notFoundMsg
let inTps = get bifInArgs funcDef
let outTpKnown = get bifResultType funcDef
let outTpAct = maybe outTpKnown (infimum (get lattice s) outTpKnown) returnTypAct
unless (alwaysIsA s outTpAct ruleName) $ Left $
"The builtin function returns a "++outTpAct++", but a "++ruleName++" is expected. Add (or change) an explicit typing:\n"
++ indent (toParsable $ MePtCall fNm True (Just ruleName) args)
args' <- case inTps of
(Right knownTypes) ->
do let nonMatchingMsg = "Expected "++show (length knownTypes)++" arguments to "++fNm'++", but got "++show (length args)
unless (length args == length knownTypes) $ Left nonMatchingMsg
inMsg ("While typing arguments to the builtin function "++fNm') $
zip args knownTypes |> (\(arg, tp) -> typeAs f s tp arg) & allRight'
(Left (shouldBe, atLeast)) ->
do unless (length args >= atLeast) $ Left $
"Expected at least "++show atLeast++" arguments of type "++shouldBe++" to the bulitin function "++fNm'
inMsg ("While typing arguments to the builtin function "++fNm') $
args |> typeAs f s shouldBe & allRight'
return $ MCall outTpAct fNm True args'
-- Normal function
matchTyping functions syntax (BNFRuleCall ruleName) _ (MePtCall fNm False _ args)
| fNm `M.notMember` functions = Left $ "Unknown function: "++fNm
| ruleName `M.notMember` get bnf syntax && not (isBuiltinName ruleName)
= Left $ "Unknown type/syntactic form: "++ruleName
| otherwise = do let fType = functions M.! fNm
let argTypes = init fType
let returnTyp = last fType
assert Left (equivalent syntax returnTyp ruleName) $
"Actual type "++show returnTyp ++" does not match expected type "++show ruleName
let lengthMsg = "Expected "++show (length argTypes)++" arguments to "++show fNm++", but got "++show (length args)++" arguments"
unless (length args == length argTypes) $ Left lengthMsg
args' <- zip args argTypes
|> (\(arg, tp) -> typeAs functions syntax tp arg)
& allRight'
return $ MCall returnTyp fNm False args'
matchTyping _ _ bnf _ pt@MePtCall{}
= Left $ "Could not match " ++ toParsable bnf ++ " ~ " ++ toParsable pt
matchTyping f s (BNFSeq bnfs) tp (MePtSeq pts)
| length bnfs == length pts
= do let joined = zip bnfs pts |> (\(bnf, pt) -> matchTyping f s bnf tp pt)
joined & allRight'
|> MSeq tp
| otherwise = Left $ "Seq could not match " ++ toParsable' " " bnfs ++ " ~ " ++ toParsable' " " pts
matchTyping _ _ (BNFRuleCall "Number") tp (MePtToken s) -- TODO Dehardcode this
= readMaybe s & maybe (Left $ "Not a valid int: "++s) return |> MInt () tp |> MParseTree
matchTyping _ _ (BNFRuleCall "Number") tp (MePtInt i) -- TODO dehardcode this
= return $ MParseTree $ MInt () tp i
matchTyping f syntax (BNFRuleCall nm) _ pt
| isDissapearing (BNFRuleCall nm)
= _dissapearingMsg nm
| isBuiltinName nm
= do contents <- maybe (Left "Builtin with no token matched") return $
fromMePtToken pt
unless (isValidBuiltin (BNFRuleCall nm) contents) $ Left $ contents ++" is not a "++nm
MLiteral () (nm, 0) contents & MParseTree & return
| nm == topSymbol
= dynamicTranslate f syntax nm pt
| nm `M.member` get bnf syntax
= do let bnfASTs = get bnf syntax M.! nm
let grouped = get groupModes syntax M.! nm
if not grouped then do
let oneOption i bnf = inMsg ("Trying to match "++nm++"." ++ show i++" ("++toParsable bnf++")") $
matchTyping f syntax bnf (nm, i) pt
let options' = zip [0..] bnfASTs |> uncurry oneOption
let options = options' & rights & nub
when (null options) $ Left $ "No clauses matched:\n"++(options' & lefts & unlines & indent)
when (length options > 1) $ Left $ "Multiple matches: \n"++indent (toCoParsable' "\n| " options)
return $ head options
else do
let noTokenMsg = Left $ "Trying to decipher a grouped rule "++show nm++", but '"++toParsable pt++"' is not a token"
str <- fromMePtToken pt |> return & fromMaybe noTokenMsg
let groupedMsg = "While parsing grouped token "++show str++" against "++show nm
pt' <- inMsg groupedMsg $ parseTargetLang syntax nm "Literal of a grouped value" str
return $ MParseTree pt'
| otherwise = Left $ "No bnf rule with name " ++ nm
-- Simpler cases
matchTyping _ _ (Literal s) tp (MePtToken s')
| s == s' = MLiteral () tp s & MParseTree & return
| otherwise = Left $ "Not the right literal: "++show s++" ~ "++show s'
matchTyping _ _ bnf _ pt
= Left $ "Could not match "++toParsable bnf++" ~ "++toParsable pt
-- only used for builtin functions, as it's arguments do not have a typing.
dynamicTranslate :: Map Name Type -> Syntax -> TypeName -> MEParseTree -> Either String Expression
dynamicTranslate _ _ tp (MePtToken s) = MLiteral () (tp, -1) s & MParseTree & return
dynamicTranslate f s tp (MePtSeq pts) = pts |+> dynamicTranslate f s tp |> MSeq (tp, -1)
dynamicTranslate _ _ tp (MePtVar nm) = MVar tp nm & return
dynamicTranslate _ _ tp (MePtInt i) = MInt () (tp, -1) i & MParseTree & return
dynamicTranslate f s _ ascr@(MePtAscription tp e)
= typeAs f s tp e
dynamicTranslate f s tp call@(MePtCall nm _ bi _)
= do tp' <- maybe (Left $ "Could not find function "++nm) return $ firstJusts [bi, M.lookup nm f |> last]
typeAs f s tp' call
dynamicTranslate f s tp (MePtEvalContext name hole)
= Left "Evaluation contexts can not be typed blind/in a dynamic context. Add a type ascription around it"
---------------------- PARSING ---------------------------
parseExpression :: Parser u MEParseTree
parseExpression = parseExpression' (identifier <|> iDentifier)
-- we allow expression with some injected 'identifier' parser
parseExpression' :: Parser u String -> Parser u MEParseTree
parseExpression' = mePt
mePt ident
= many1 (ws' *> mePtPart ident <* ws') |> mePtSeq
where mePtSeq [a] = a
mePtSeq as = MePtSeq as
mePtPart ident = try mePtToken
<|> meContext ident
<|> try (mePtCall ident)
<|> try (meAscription ident)
<|> try (meNested ident)
<|> try mePtInt
<|> mePtVar ident
meNested ident = char '(' *> ws *> mePt ident <* ws <* char ')'
mePtToken = dqString |> MePtToken
mePtVar :: Parser u Name-> Parser u MEParseTree
mePtVar ident = do nm <- try ident
<|> (char '_' |> (:[]))
return $ MePtVar nm
mePtInt = negNumber |> MePtInt
mePtCall ident = do builtin <- try (char '!' >> return True) <|> return False
nm <- identifier -- here we use the normal identifier, not the injected one
biType <- if builtin then (char ':' >> identifier |> Just) <|> return Nothing else return Nothing
char '('
args <- (ws *> mePt ident <* ws) `sepBy` char ','
char ')'
return $ MePtCall nm builtin biType args
meAscription ident
= do char '('
ws
expr <- mePt ident
ws
char ':'
ws
nm <- identifier -- this is a bnf-syntax rule; the normal identifier too
ws
char ')'
return $ MePtAscription nm expr
meContext ident = do name <- try (ident <* char '[')
-- char '[' ---------------------------- ^
ws
hole <- parseExpression' ident
ws
char ']'
return $ MePtEvalContext name hole
| pietervdvn/ALGT | src/TypeSystem/Parser/ExpressionParser.hs | bsd-3-clause | 12,788 | 468 | 34 | 2,596 | 4,356 | 2,253 | 2,103 | 226 | 3 |
{-|
Module : Idris.Docs
Description : Data structures and utilities to work with Idris Documentation.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE DeriveFunctor, PatternGuards, MultiWayIf #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Docs (
pprintDocs
, getDocs, pprintConstDocs, pprintTypeDoc
, FunDoc, FunDoc'(..), Docs, Docs'(..)
) where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import Idris.Delaborate
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Docstrings (Docstring, emptyDocstring, noDocs, nullDocstring, renderDocstring, DocTerm, renderDocTerm, overview)
import Util.Pretty
import Prelude hiding ((<$>))
import Control.Arrow (first)
import Data.Maybe
import Data.List
import qualified Data.Text as T
-- TODO: Only include names with public/export accessibility
--
-- Issue #1573 on the Issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1573
data FunDoc' d = FD Name d
[(Name, PTerm, Plicity, Maybe d)] -- args: name, ty, implicit, docs
PTerm -- function type
(Maybe Fixity)
deriving Functor
type FunDoc = FunDoc' (Docstring DocTerm)
data Docs' d = FunDoc (FunDoc' d)
| DataDoc (FunDoc' d) -- type constructor docs
[FunDoc' d] -- data constructor docs
| ClassDoc Name d -- class docs
[FunDoc' d] -- method docs
[(Name, Maybe d)] -- parameters and their docstrings
[(Maybe Name, PTerm, (d, [(Name, d)]))] -- instances: name for named instances, the constraint term, the docs
[PTerm] -- subclasses
[PTerm] -- superclasses
(Maybe (FunDoc' d)) -- explicit constructor
| RecordDoc Name d -- record docs
(FunDoc' d) -- data constructor docs
[FunDoc' d] -- projection docs
[(Name, PTerm, Maybe d)] -- parameters with type and doc
| NamedInstanceDoc Name (FunDoc' d) -- name is class
| ModDoc [String] -- Module name
d
deriving Functor
type Docs = Docs' (Docstring DocTerm)
showDoc ist d
| nullDocstring d = empty
| otherwise = text " -- " <>
renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) d
pprintFD :: IState -> Bool -> Bool -> FunDoc -> Doc OutputAnnotation
pprintFD ist totalityFlag nsFlag (FD n doc args ty f) =
nest 4 (prettyName True nsFlag [] n
<+> colon
<+> pprintPTerm ppo [] [ n | (n@(UN n'),_,_,_) <- args
, not (T.isPrefixOf (T.pack "__") n') ] infixes ty
-- show doc
<$> renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) doc
-- show fixity
<$> maybe empty (\f -> text (show f) <> line) f
-- show arguments doc
<> let argshow = showArgs args [] in
(if not (null argshow)
then nest 4 $ text "Arguments:" <$> vsep argshow
else empty)
-- show totality status
<> let totality = getTotality in
(if totalityFlag && not (null totality)
then line <> (vsep . map (\t -> text "The function is" <+> t) $ totality)
else empty))
where
ppo = ppOptionIst ist
infixes = idris_infixes ist
-- Recurse over and show the Function's Documented arguments
showArgs ((n, ty, Exp {}, Just d):args) bnd = -- Explicitly bound.
bindingOf n False
<+> colon
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, False):bnd)
showArgs ((n, ty, Constraint {}, Just d):args) bnd = -- Class constraints.
text "Class constraint"
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, True):bnd)
showArgs ((n, ty, Imp {}, Just d):args) bnd = -- Implicit arguments.
text "(implicit)"
<+> bindingOf n True
<+> colon
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, True):bnd)
showArgs ((n, ty, TacImp{}, Just d):args) bnd = -- Tacit implicits
text "(auto implicit)"
<+> bindingOf n True
<+> colon
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, True):bnd)
showArgs ((n, _, _, _):args) bnd = -- Anything else
showArgs args ((n, True):bnd)
showArgs [] _ = [] -- end of arguments
getTotality = map (text . show) $ lookupTotal n (tt_ctxt ist)
pprintFDWithTotality :: IState -> Bool -> FunDoc -> Doc OutputAnnotation
pprintFDWithTotality ist = pprintFD ist True
pprintFDWithoutTotality :: IState -> Bool -> FunDoc -> Doc OutputAnnotation
pprintFDWithoutTotality ist = pprintFD ist False
pprintDocs :: IState -> Docs -> Doc OutputAnnotation
pprintDocs ist (FunDoc d) = pprintFDWithTotality ist True d
pprintDocs ist (DataDoc t args)
= text "Data type" <+> pprintFDWithoutTotality ist True t <$>
if null args then text "No constructors."
else nest 4 (text "Constructors:" <> line <>
vsep (map (pprintFDWithoutTotality ist False) args))
pprintDocs ist (ClassDoc n doc meths params instances subclasses superclasses ctor)
= nest 4 (text "Interface" <+> prettyName True (ppopt_impl ppo) [] n <>
if nullDocstring doc
then empty
else line <> renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) doc)
<> line <$>
nest 4 (text "Parameters:" <$> prettyParameters)
<> line <$>
nest 4 (text "Methods:" <$>
vsep (map (pprintFDWithTotality ist False) meths))
<$>
maybe empty
((<> line) . nest 4 .
(text "Implementation constructor:" <$>) .
pprintFDWithoutTotality ist False)
ctor
<>
nest 4 (text "Implementations:" <$>
vsep (if null instances then [text "<no implementations>"]
else map pprintInstance normalInstances))
<>
(if null namedInstances then empty
else line <$> nest 4 (text "Named implementations:" <$>
vsep (map pprintInstance namedInstances)))
<>
(if null subclasses then empty
else line <$> nest 4 (text "Child interfaces:" <$>
vsep (map (dumpInstance . prettifySubclasses) subclasses)))
<>
(if null superclasses then empty
else line <$> nest 4 (text "Default parent implementations:" <$>
vsep (map dumpInstance superclasses)))
where
params' = zip pNames (repeat False)
(normalInstances, namedInstances) = partition (\(n, _, _) -> not $ isJust n)
instances
pNames = map fst params
ppo = ppOptionIst ist
infixes = idris_infixes ist
pprintInstance (mname, term, (doc, argDocs)) =
nest 4 (iname mname <> dumpInstance term <>
(if nullDocstring doc
then empty
else line <>
renderDocstring
(renderDocTerm
(pprintDelab ist)
(normaliseAll (tt_ctxt ist) []))
doc) <>
if null argDocs
then empty
else line <> vsep (map (prettyInstanceParam (map fst argDocs)) argDocs))
iname Nothing = empty
iname (Just n) = annName n <+> colon <> space
prettyInstanceParam params (name, doc) =
if nullDocstring doc
then empty
else prettyName True False (zip params (repeat False)) name <+>
showDoc ist doc
-- if any (isJust . snd) params
-- then vsep (map (\(nm,md) -> prettyName True False params' nm <+> maybe empty (showDoc ist) md) params)
-- else hsep (punctuate comma (map (prettyName True False params' . fst) params))
dumpInstance :: PTerm -> Doc OutputAnnotation
dumpInstance = pprintPTerm ppo params' [] infixes
prettifySubclasses (PPi (Constraint _ _) _ _ tm _) = prettifySubclasses tm
prettifySubclasses (PPi plcity nm fc t1 t2) = PPi plcity (safeHead nm pNames) NoFC (prettifySubclasses t1) (prettifySubclasses t2)
prettifySubclasses (PApp fc ref args) = PApp fc ref $ updateArgs pNames args
prettifySubclasses tm = tm
safeHead _ (y:_) = y
safeHead x [] = x
updateArgs (p:ps) ((PExp prty opts _ ref):as) = (PExp prty opts p (updateRef p ref)) : updateArgs ps as
updateArgs ps (a:as) = a : updateArgs ps as
updateArgs _ _ = []
updateRef nm (PRef fc _ _) = PRef fc [] nm
updateRef _ pt = pt
isSubclass (PPi (Constraint _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args')) = nm == n && map getTm args == map getTm args'
isSubclass (PPi _ _ _ _ pt) = isSubclass pt
isSubclass _ = False
prettyParameters =
if any (isJust . snd) params
then vsep (map (\(nm,md) -> prettyName True False params' nm <+> maybe empty (showDoc ist) md) params)
else hsep (punctuate comma (map (prettyName True False params' . fst) params))
pprintDocs ist (RecordDoc n doc ctor projs params)
= nest 4 (text "Record" <+> prettyName True (ppopt_impl ppo) [] n <>
if nullDocstring doc
then empty
else line <>
renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) doc)
-- Parameters
<$> (if null params
then empty
else line <> nest 4 (text "Parameters:" <$> prettyParameters) <> line)
-- Constructor
<$> nest 4 (text "Constructor:" <$> pprintFDWithoutTotality ist False ctor)
-- Projections
<$> nest 4 (text "Projections:" <$> vsep (map (pprintFDWithoutTotality ist False) projs))
where
ppo = ppOptionIst ist
infixes = idris_infixes ist
pNames = [n | (n,_,_) <- params]
params' = zip pNames (repeat False)
prettyParameters =
if any isJust [d | (_,_,d) <- params]
then vsep (map (\(n,pt,d) -> prettyParam (n,pt) <+> maybe empty (showDoc ist) d) params)
else hsep (punctuate comma (map prettyParam [(n,pt) | (n,pt,_) <- params]))
prettyParam (n,pt) = prettyName True False params' n <+> text ":" <+> pprintPTerm ppo params' [] infixes pt
pprintDocs ist (NamedInstanceDoc _cls doc)
= nest 4 (text "Named instance:" <$> pprintFDWithoutTotality ist True doc)
pprintDocs ist (ModDoc mod docs)
= nest 4 $ text "Module" <+> text (concat (intersperse "." mod)) <> colon <$>
renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) docs
-- | Determine a truncation function depending how much docs the user
-- wants to see
howMuch FullDocs = id
howMuch OverviewDocs = overview
-- | Given a fully-qualified, disambiguated name, construct the
-- documentation object for it
getDocs :: Name -> HowMuchDocs -> Idris Docs
getDocs n@(NS n' ns) w | n' == modDocName
= do i <- getIState
case lookupCtxtExact n (idris_moduledocs i) of
Just doc -> return . ModDoc (reverse (map T.unpack ns)) $ howMuch w doc
Nothing -> fail $ "Module docs for " ++ show (reverse (map T.unpack ns)) ++
" do not exist! This shouldn't have happened and is a bug."
getDocs n w
= do i <- getIState
docs <- if | Just ci <- lookupCtxtExact n (idris_classes i)
-> docClass n ci
| Just ri <- lookupCtxtExact n (idris_records i)
-> docRecord n ri
| Just ti <- lookupCtxtExact n (idris_datatypes i)
-> docData n ti
| Just class_ <- classNameForInst i n
-> do fd <- docFun n
return $ NamedInstanceDoc class_ fd
| otherwise
-> do fd <- docFun n
return (FunDoc fd)
return $ fmap (howMuch w) docs
where classNameForInst :: IState -> Name -> Maybe Name
classNameForInst ist n =
listToMaybe [ cn
| (cn, ci) <- toAlist (idris_classes ist)
, n `elem` map fst (class_instances ci)
]
docData :: Name -> TypeInfo -> Idris Docs
docData n ti
= do tdoc <- docFun n
cdocs <- mapM docFun (con_names ti)
return (DataDoc tdoc cdocs)
docClass :: Name -> ClassInfo -> Idris Docs
docClass n ci
= do i <- getIState
let docStrings = listToMaybe $ lookupCtxt n $ idris_docstrings i
docstr = maybe emptyDocstring fst docStrings
params = map (\pn -> (pn, docStrings >>= (lookup pn . snd)))
(class_params ci)
docsForInstance inst = fromMaybe (emptyDocstring, []) .
flip lookupCtxtExact (idris_docstrings i) $
inst
instances = map (\inst -> (namedInst inst,
delabTy i inst,
docsForInstance inst))
(nub (map fst (class_instances ci)))
(subclasses, instances') = partition (isSubclass . (\(_,tm,_) -> tm)) instances
superclasses = catMaybes $ map getDInst (class_default_superclasses ci)
mdocs <- mapM (docFun . fst) (class_methods ci)
let ctorN = instanceCtorName ci
ctorDocs <- case basename ctorN of
SN _ -> return Nothing
_ -> fmap Just $ docFun ctorN
return $ ClassDoc
n docstr mdocs params
instances' (map (\(_,tm,_) -> tm) subclasses) superclasses
ctorDocs
where
namedInst (NS n ns) = fmap (flip NS ns) (namedInst n)
namedInst n@(UN _) = Just n
namedInst _ = Nothing
getDInst (PInstance _ _ _ _ _ _ _ _ _ _ _ _ t _ _) = Just t
getDInst _ = Nothing
isSubclass (PPi (Constraint _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args'))
= nm == n && map getTm args == map getTm args'
isSubclass (PPi _ _ _ _ pt)
= isSubclass pt
isSubclass _
= False
docRecord :: Name -> RecordInfo -> Idris Docs
docRecord n ri
= do i <- getIState
let docStrings = listToMaybe $ lookupCtxt n $ idris_docstrings i
docstr = maybe emptyDocstring fst docStrings
params = map (\(pn,pt) -> (pn, pt, docStrings >>= (lookup (nsroot pn) . snd)))
(record_parameters ri)
pdocs <- mapM docFun (record_projections ri)
ctorDocs <- docFun $ record_constructor ri
return $ RecordDoc n docstr ctorDocs pdocs params
docFun :: Name -> Idris FunDoc
docFun n
= do i <- getIState
let (docstr, argDocs) = case lookupCtxt n (idris_docstrings i) of
[d] -> d
_ -> noDocs
let ty = delabTy i n
let args = getPArgNames ty argDocs
let infixes = idris_infixes i
let fixdecls = filter (\(Fix _ x) -> x == funName n) infixes
let f = case fixdecls of
[] -> Nothing
(Fix x _:_) -> Just x
return (FD n docstr args ty f)
where funName :: Name -> String
funName (UN n) = str n
funName (NS n _) = funName n
funName n = show n
getPArgNames :: PTerm -> [(Name, Docstring DocTerm)] -> [(Name, PTerm, Plicity, Maybe (Docstring DocTerm))]
getPArgNames (PPi plicity name _ ty body) ds =
(name, ty, plicity, lookup name ds) : getPArgNames body ds
getPArgNames _ _ = []
pprintConstDocs :: IState -> Const -> String -> Doc OutputAnnotation
pprintConstDocs ist c str = text "Primitive" <+> text (if constIsType c then "type" else "value") <+>
pprintPTerm (ppOptionIst ist) [] [] [] (PConstant NoFC c) <+> colon <+>
pprintPTerm (ppOptionIst ist) [] [] [] (t c) <>
nest 4 (line <> text str)
where t (Fl _) = PConstant NoFC $ AType ATFloat
t (BI _) = PConstant NoFC $ AType (ATInt ITBig)
t (Str _) = PConstant NoFC StrType
t (Ch c) = PConstant NoFC $ AType (ATInt ITChar)
t _ = PType NoFC
pprintTypeDoc :: IState -> Doc OutputAnnotation
pprintTypeDoc ist = prettyIst ist (PType emptyFC) <+> colon <+> type1Doc <+>
nest 4 (line <> text typeDescription)
| ozgurakgun/Idris-dev | src/Idris/Docs.hs | bsd-3-clause | 17,381 | 0 | 25 | 6,116 | 5,482 | 2,778 | 2,704 | 323 | 24 |
module Generics.GPAH.Interp.PPrint where
import Generics.GPAH.Interp.Base
import Text.CSV
import System.IO
import qualified Data.Map as M
import Data.List
import Data.Function (on)
pprint :: Analysis -> FilePath -> IO ()
pprint (Analysis a1) fp = do
let p = [["NrTypes", show $ length $ concat $ M.elems a1],
["AssocTypes", show $ map (\ t -> (t, length $ filter (t `isInfixOf`) $ concat $ M.elems a1)) intTypes]
]
pCSV = printCSV p
writeFile fp pCSV
putStrLn "Interpretation Results:\n###############"
putStrLn pCSV
| bezirg/gpah | src/Generics/GPAH/Interp/PPrint.hs | bsd-3-clause | 559 | 0 | 21 | 119 | 203 | 111 | 92 | 15 | 1 |
module System.Nemesis.Jinjing.Cabal where
import System.Nemesis.Env
import System.Nemesis (Unit)
import Air.Env
import Prelude ()
cabal_dist :: Unit
cabal_dist = do
desc "prepare cabal dist"
task "dist" - do
sh "cabal clean"
sh "cabal configure"
sh "cabal sdist" | nfjinjing/nemesis-jinjing | src/System/Nemesis/Jinjing/Cabal.hs | bsd-3-clause | 282 | 0 | 10 | 55 | 79 | 41 | 38 | 12 | 1 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Functions to modify prepend common Changelog entries.
module Ops.Changelog where
import Ops.Common
import Data.Text (Text)
import qualified Data.Text as T
import qualified Filesystem.Path.CurrentOS as FP
import Shelly
import Prelude hiding (FilePath)
-- | Test whether a given filename looks like a changelog.
changelogNames :: FilePath -> Bool
changelogNames fp = e (FP.extension fp) && b (toTextIgnore . FP.basename $ fp)
where
e ext = ext `elem` [Nothing, Just "md", Just "markdown"]
b name = name `elem` ["CHANGES", "CHANGELOG"]
-- | Looks in the current directory for a changelog file. Returns the
-- filename if available, or an error.
findChangelog :: Sh (Either FileMatchError FilePath)
findChangelog = do
dir <- pwd
fns <- ls dir
case filter changelogNames fns of
[] -> return $ Left NoMatches
[one] -> return $ Right one
multiple -> return . Left . MultipleMatches $ multiple
-- | remove the top header
trimChangelog :: Text -> Text
trimChangelog oldCL = case T.lines oldCL of
("# Change Log":rest) -> T.unlines $ dropWhile (\l -> T.strip l == "") rest
_ -> oldCL
| diagrams/package-ops | src/Ops/Changelog.hs | bsd-3-clause | 1,337 | 0 | 14 | 340 | 329 | 179 | 150 | 26 | 3 |
{-# LANGUAGE TypeSynonymInstances #-}
module Types.Hitbox where
import Types.Drawable
import Graphics.Gloss.Data.Picture
import Graphics.Gloss.Data.Point
import Graphics.Gloss.Geometry
import Graphics.Gloss.Geometry.Line
import Graphics.Gloss.Geometry.Angle
class (Drawable a)=> Hitbox a where
hitTest :: a -> a -> Bool -- ^ Collision detection
| Smurf/dodgem | src/Types/Hitbox.hs | bsd-3-clause | 359 | 0 | 8 | 50 | 78 | 49 | 29 | 10 | 0 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
[lq| isEven, isOdd :: Nat -> Bool |]
isEven :: Int -> Bool
isEven 0 = True
isEven n = isOdd $ n - 1
isOdd 0 = False
isOdd m = isEven $ m - 1
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/Even.hs | bsd-3-clause | 200 | 0 | 6 | 52 | 74 | 38 | 36 | 8 | 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.
module Duckling.Numeral.ES.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Numeral.ES.Corpus
import Duckling.Testing.Asserts
import Duckling.Testing.Types hiding (examples)
import qualified Duckling.Numeral.ES.AR.Corpus as AR
import qualified Duckling.Numeral.ES.CL.Corpus as CL
import qualified Duckling.Numeral.ES.CO.Corpus as CO
import qualified Duckling.Numeral.ES.ES.Corpus as ES
import qualified Duckling.Numeral.ES.MX.Corpus as MX
import qualified Duckling.Numeral.ES.PE.Corpus as PE
import qualified Duckling.Numeral.ES.VE.Corpus as VE
import qualified Duckling.Region as R
( Region
( AR
, ES
)
)
tests :: TestTree
tests = testGroup "ES Tests"
[ makeCorpusTest [Seal Numeral] corpus
, localeTests
]
localeTests :: TestTree
localeTests = testGroup "Locale Tests"
[ testGroup "ES_AR Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeAR AR.allExamples
]
, testGroup "ES_CL Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeCL CL.allExamples
]
, testGroup "ES_CO Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeCO CO.allExamples
]
, testGroup "ES_ES Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeES ES.allExamples
]
, testGroup "ES_MX Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeMX MX.allExamples
]
, testGroup "ES_PE Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localePE PE.allExamples
]
, testGroup "ES_VE Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeVE VE.allExamples
]
]
where
localeAR = makeLocale ES $ Just R.AR
localeCL = makeLocale ES $ Just CL
localeCO = makeLocale ES $ Just CO
localeES = makeLocale ES $ Just R.ES
localeMX = makeLocale ES $ Just MX
localePE = makeLocale ES $ Just PE
localeVE = makeLocale ES $ Just VE
| facebookincubator/duckling | tests/Duckling/Numeral/ES/Tests.hs | bsd-3-clause | 2,196 | 0 | 12 | 418 | 552 | 312 | 240 | 48 | 1 |
-- | Generic class with properties and methods that are available for all
-- different implementations ('IntPSQ', 'OrdPSQ' and 'HashPSQ').
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.PSQ.Class
( PSQ (..)
) where
import Data.Hashable (Hashable)
import qualified Data.IntPSQ as IntPSQ
import qualified Data.HashPSQ as HashPSQ
import qualified Data.OrdPSQ as OrdPSQ
class PSQ (psq :: * -> * -> *) where
type Key psq :: *
-- Query
null
:: Ord p => psq p v -> Bool
size
:: Ord p => psq p v -> Int
member
:: Ord p => Key psq -> psq p v -> Bool
lookup
:: Ord p => Key psq -> psq p v -> Maybe (p, v)
findMin
:: Ord p => psq p v -> Maybe (Key psq, p, v)
-- Construction
empty
:: Ord p => psq p v
singleton
:: Ord p => Key psq -> p -> v -> psq p v
-- Insertion
insert
:: Ord p => Key psq -> p -> v -> psq p v -> psq p v
-- Delete/update
delete
:: Ord p => Key psq -> psq p v -> psq p v
alter
:: Ord p
=> (Maybe (p, v) -> (b, Maybe (p, v)))
-> Key psq -> psq p v -> (b, psq p v)
alterMin
:: Ord p
=> (Maybe (Key psq, p, v) -> (b, Maybe (Key psq, p, v)))
-> psq p v -> (b, psq p v)
-- Lists
fromList
:: Ord p => [(Key psq, p, v)] -> psq p v
toList
:: Ord p => psq p v -> [(Key psq, p, v)]
keys
:: Ord p => psq p v -> [Key psq]
-- Views
insertView
:: Ord p => Key psq -> p -> v -> psq p v -> (Maybe (p, v), psq p v)
deleteView
:: Ord p => Key psq -> psq p v -> Maybe (p, v, psq p v)
minView
:: Ord p => psq p v -> Maybe (Key psq, p, v, psq p v)
-- Traversals
map :: Ord p => (Key psq -> p -> v -> w) -> psq p v -> psq p w
fold'
:: Ord p => (Key psq -> p -> v -> a -> a) -> a -> psq p v -> a
instance PSQ IntPSQ.IntPSQ where
type Key IntPSQ.IntPSQ = Int
null = IntPSQ.null
size = IntPSQ.size
member = IntPSQ.member
lookup = IntPSQ.lookup
findMin = IntPSQ.findMin
empty = IntPSQ.empty
singleton = IntPSQ.singleton
insert = IntPSQ.insert
delete = IntPSQ.delete
alter = IntPSQ.alter
alterMin = IntPSQ.alterMin
fromList = IntPSQ.fromList
toList = IntPSQ.toList
keys = IntPSQ.keys
insertView = IntPSQ.insertView
deleteView = IntPSQ.deleteView
minView = IntPSQ.minView
map = IntPSQ.map
fold' = IntPSQ.fold'
instance forall k. Ord k => PSQ (OrdPSQ.OrdPSQ k) where
type Key (OrdPSQ.OrdPSQ k) = k
null = OrdPSQ.null
size = OrdPSQ.size
member = OrdPSQ.member
lookup = OrdPSQ.lookup
findMin = OrdPSQ.findMin
empty = OrdPSQ.empty
singleton = OrdPSQ.singleton
insert = OrdPSQ.insert
delete = OrdPSQ.delete
alter = OrdPSQ.alter
alterMin = OrdPSQ.alterMin
fromList = OrdPSQ.fromList
toList = OrdPSQ.toList
keys = OrdPSQ.keys
insertView = OrdPSQ.insertView
deleteView = OrdPSQ.deleteView
minView = OrdPSQ.minView
map = OrdPSQ.map
fold' = OrdPSQ.fold'
instance forall k. (Hashable k, Ord k) => PSQ (HashPSQ.HashPSQ k) where
type Key (HashPSQ.HashPSQ k) = k
null = HashPSQ.null
size = HashPSQ.size
member = HashPSQ.member
lookup = HashPSQ.lookup
findMin = HashPSQ.findMin
empty = HashPSQ.empty
singleton = HashPSQ.singleton
insert = HashPSQ.insert
delete = HashPSQ.delete
alter = HashPSQ.alter
alterMin = HashPSQ.alterMin
fromList = HashPSQ.fromList
toList = HashPSQ.toList
keys = HashPSQ.keys
insertView = HashPSQ.insertView
deleteView = HashPSQ.deleteView
minView = HashPSQ.minView
map = HashPSQ.map
fold' = HashPSQ.fold'
| meiersi/psqueues-old | tests/Data/PSQ/Class.hs | bsd-3-clause | 4,085 | 83 | 49 | 1,407 | 1,439 | 731 | 708 | 116 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Client.KeyFuncT where
import Control.Lens (makeLenses)
import Types
makeLenses ''KeyFuncT
| ksaveljev/hake-2 | src/Client/KeyFuncT.hs | bsd-3-clause | 153 | 0 | 6 | 37 | 28 | 16 | 12 | 5 | 0 |
{-# LANGUAGE PackageImports, NamedFieldPuns #-}
module Data.Tree23.Entry where
import Data.Maybe
import Data.Ord
import qualified "dlist" Data.DList as D
-- import Data.Monoid (Monoid, mempty, mappend, (<>), mconcat)
data Valid = Valid | Invalid deriving (Eq, Show)
data Entry k v = Entry {key :: k, value :: v, valid :: Valid} deriving Show
instance Eq k => Eq (Entry k v) where
(Entry x _ _) == (Entry y _ _) = x == y
entryPair :: Entry k v -> (k, v)
entryPair e @ Entry {key, value} = (key, value)
instance Ord k => Ord (Entry k v) where
compare = comparing key
valToDList :: Entry k v -> D.DList (k, v)
valToDList (Entry k v Valid) = D.singleton (k, v)
valToDList (Entry _ _ Invalid) = D.empty
toMaybe :: Entry k v -> Maybe (k, v)
toMaybe (Entry k v Valid) = Just (k, v)
toMaybe (Entry _ _ Invalid) = Nothing
isValid :: Entry k v -> Bool
isValid (Entry _ _ Valid) = True
isValid (Entry _ _ Invalid) = False
invalidate :: Entry k v -> Entry k v
invalidate e = e { valid = Invalid}
-- combine entry values of entries with same key
combineEntry :: Eq k => (v -> v -> v) -> Entry k v -> Entry k v -> Entry k v
combineEntry f (Entry k1 v1 Valid) (Entry k2 v2 w)
| k1 == k2 = Entry k1 (f v1 v2) w
combineEntry f (Entry k1 v1 Invalid) e2 @ (Entry k2 v2 w)
| k1 == k2 = e2
mapEntryValue :: (a -> b) -> Entry k a -> Entry k b
mapEntryValue f (Entry k v w) = Entry k (f v) w
mapEntryKey :: (k1 -> k2) -> Entry k1 v -> Entry k2 v
mapEntryKey f (Entry k v w) = Entry (f k) v w
filterEntry :: (k -> Bool) -> Entry k v -> Entry k v
filterEntry prop e @ (Entry _ _ Invalid) = e
filterEntry prop e @ (Entry k v Valid) = if prop k then e else Entry k v Invalid
-- used to get intersection from difference
flipEntryValid :: Entry k v -> Entry k v
flipEntryValid (Entry k v Valid) = Entry k v Invalid
flipEntryValid (Entry k v Invalid) = Entry k v Valid
{-
foldEntryKey :: (Monoid m) => (k -> m) -> Entry k v -> m
foldEntryKey f e = if isValid e then (f . key $ e) else mempty
foldEntryVal :: (Monoid m) => (a -> m) -> Entry a -> m
foldEntryVal f e = if isValid e then (f . value $ e) else mempty
-} | griba2001/tree23-map-set | src/Data/Tree23/Entry.hs | bsd-3-clause | 2,131 | 4 | 10 | 495 | 897 | 457 | 440 | 39 | 2 |
{- |
Module : $Header$
Copyright : Felix Gabriel Mance
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Static analysis for OWL 2
-}
module OWL2.StaticAnalysis where
import OWL2.Sign
import OWL2.Morphism
import OWL2.AS
import OWL2.MS
import OWL2.Print ()
import OWL2.Theorem
import OWL2.Function
import OWL2.Symbols
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.List
import Common.AS_Annotation hiding (Annotation)
import Common.DocUtils
import Common.Result
import Common.GlobalAnnotations hiding (PrefixMap)
import Common.ExtSign
import Common.Lib.State
import qualified Common.Id as Id
import Common.IRI (iriToStringUnsecure, setAngles)
import Control.Monad
import Logic.Logic
-- | Error messages for static analysis
failMsg :: Entity -> ClassExpression -> Result a
failMsg (Entity _ ty e) desc =
fatal_error
("undeclared `" ++ showEntityType ty
++ " " ++ showQN e ++ "` in the following ClassExpression:\n"
++ showDoc desc "") $ iriPos e
-- | checks if an entity is in the signature
checkEntity :: Sign -> Entity -> Result ()
checkEntity s t@(Entity _ ty e) =
let errMsg = mkError ("unknown " ++ showEntityType ty) e
in case ty of
Datatype -> unless (Set.member e (datatypes s) || isDatatypeKey e) errMsg
Class -> unless (Set.member e (concepts s) || isThing e) errMsg
ObjectProperty -> unless (isDeclObjProp s $ ObjectProp e) errMsg
DataProperty -> unless (isDeclDataProp s e) errMsg
AnnotationProperty -> unless (Set.member e (annotationRoles s)
|| isPredefAnnoProp e) $ justWarn () $ showDoc t " unknown"
_ -> return ()
-- | takes an iri and finds out what entities it belongs to
correctEntity :: Sign -> IRI -> [Entity]
correctEntity s iri =
[mkEntity AnnotationProperty iri | Set.member iri (annotationRoles s)] ++
[mkEntity Class iri | Set.member iri (concepts s)] ++
[mkEntity ObjectProperty iri | Set.member iri (objectProperties s)] ++
[mkEntity DataProperty iri | Set.member iri (dataProperties s)] ++
[mkEntity Datatype iri | Set.member iri (datatypes s)] ++
[mkEntity NamedIndividual iri | Set.member iri (individuals s)]
checkLiteral :: Sign -> Literal -> Result ()
checkLiteral s l = case l of
Literal _ (Typed dt) -> checkEntity s $ mkEntity Datatype dt
_ -> return ()
isDeclObjProp :: Sign -> ObjectPropertyExpression -> Bool
isDeclObjProp s ope = let op = objPropToIRI ope in
Set.member op (objectProperties s) || isPredefObjProp op
isDeclDataProp :: Sign -> DataPropertyExpression -> Bool
isDeclDataProp s dp = Set.member dp (dataProperties s) || isPredefDataProp dp
{- | takes a list of object properties and discards the ones
which are not in the signature -}
filterObjProp :: Sign -> [ObjectPropertyExpression]
-> [ObjectPropertyExpression]
filterObjProp = filter . isDeclObjProp
checkObjPropList :: Sign -> [ObjectPropertyExpression] -> Result ()
checkObjPropList s ol = do
let ls = map (isDeclObjProp s) ol
unless (and ls) $ fail $ "Static analysis found that not all properties" ++
" in the following list are ObjectProperties\n\n" ++ show ol
checkDataPropList :: Sign -> [DataPropertyExpression] -> Result ()
checkDataPropList s dl = do
let ls = map (isDeclDataProp s) dl
unless (and ls) $ fail $ "Static analysis found that not all properties" ++
" in the following list are DataProperties\n\n" ++ show dl
-- | checks if a DataRange is valid
checkDataRange :: Sign -> DataRange -> Result ()
checkDataRange s dr = case dr of
DataType dt rl -> do
checkEntity s $ mkEntity Datatype dt
mapM_ (checkLiteral s . snd) rl
DataJunction _ drl -> mapM_ (checkDataRange s) drl
DataComplementOf r -> checkDataRange s r
DataOneOf ll -> mapM_ (checkLiteral s) ll
{- | converts ClassExpression to DataRanges because some
DataProperties may be parsed as ObjectProperties -}
classExpressionToDataRange :: Sign -> ClassExpression -> Result DataRange
classExpressionToDataRange s ce = case ce of
Expression u -> checkEntity s (mkEntity Datatype u)
>> return (DataType u [])
ObjectJunction jt cel -> fmap (DataJunction jt)
$ mapM (classExpressionToDataRange s) cel
ObjectComplementOf c -> fmap DataComplementOf
$ classExpressionToDataRange s c
_ -> fail $ "cannot convert ClassExpression to DataRange\n"
++ showDoc ce ""
{- | checks a ClassExpression and recursively converts the
(maybe inappropriately) parsed syntax to a one satisfying the signature -}
checkClassExpression :: Sign -> ClassExpression -> Result ClassExpression
checkClassExpression s desc =
let errMsg i = failMsg i desc
objErr i = errMsg $ mkEntity ObjectProperty i
datErr i = errMsg $ mkEntity DataProperty i
in case desc of
Expression u -> if isThing u
then return $ Expression $ setReservedPrefix u
else checkEntity s (mkEntity Class u) >> return desc
ObjectJunction ty ds -> fmap (ObjectJunction ty)
$ mapM (checkClassExpression s) ds
ObjectComplementOf d -> fmap ObjectComplementOf $ checkClassExpression s d
ObjectOneOf _ -> return desc
ObjectValuesFrom q opExpr d -> if isDeclObjProp s opExpr
then fmap (ObjectValuesFrom q opExpr) $ checkClassExpression s d
else let iri = objPropToIRI opExpr
in if isDeclDataProp s iri then
fmap (DataValuesFrom q iri)
$ classExpressionToDataRange s d
else objErr iri
ObjectHasSelf opExpr -> if isDeclObjProp s opExpr then return desc
else objErr $ objPropToIRI opExpr
ObjectHasValue opExpr _ -> if isDeclObjProp s opExpr then return desc
else objErr $ objPropToIRI opExpr
ObjectCardinality (Cardinality a b opExpr md) -> do
let iri = objPropToIRI opExpr
mbrOP = Set.member iri $ objectProperties s
case md of
Nothing
| mbrOP -> return desc
| isDeclDataProp s iri ->
return $ DataCardinality $ Cardinality a b iri Nothing
| otherwise -> objErr iri
Just d ->
if mbrOP then fmap (ObjectCardinality . Cardinality a b opExpr
. Just) $ checkClassExpression s d
else do
dr <- classExpressionToDataRange s d
if isDeclDataProp s iri then
return $ DataCardinality
$ Cardinality a b iri $ Just dr
else datErr iri
DataValuesFrom _ dExp r -> checkDataRange s r
>> if isDeclDataProp s dExp then return desc else datErr dExp
DataHasValue dExp l -> do
checkLiteral s l
if isDeclDataProp s dExp then return desc
else datErr dExp
DataCardinality (Cardinality _ _ dExp mr) -> if isDeclDataProp s dExp
then case mr of
Nothing -> return desc
Just d -> checkDataRange s d >> return desc
else datErr dExp
checkFact :: Sign -> Fact -> Result ()
checkFact s f = case f of
ObjectPropertyFact _ op _ -> unless (isDeclObjProp s op) $
fail $ "Static analysis. ObjectPropertyFact failed " ++ show f
DataPropertyFact _ dp l -> do
checkLiteral s l
unless (isDeclDataProp s dp)
$ fail $ "Static analysis. DataProperty fact failed " ++ show f
checkFactList :: Sign -> [Fact] -> Result ()
checkFactList = mapM_ . checkFact
-- | sorts the data and object properties
checkHasKey :: Sign -> [ObjectPropertyExpression] -> [DataPropertyExpression]
-> Result AnnFrameBit
checkHasKey s ol dl = do
let nol = filterObjProp s ol
ndl = map objPropToIRI (ol \\ nol) ++ dl
key = ClassHasKey nol ndl
decl = map (isDeclDataProp s) ndl
if and decl then return key
else fail $ "Keys failed " ++ showDoc ol "" ++ showDoc dl "\n"
checkAnnotation :: Sign -> Annotation -> Result ()
checkAnnotation s (Annotation ans apr av) = do
checkAnnos s [ans]
checkEntity s (mkEntity AnnotationProperty apr)
case av of
AnnValLit lit -> checkLiteral s lit
_ -> return ()
checkAnnos :: Sign -> [Annotations] -> Result ()
checkAnnos = mapM_ . mapM . checkAnnotation
checkAnnoList :: Sign -> ([t] -> Result ()) -> [(Annotations, t)] -> Result ()
checkAnnoList s f anl = do
checkAnnos s $ map fst anl
f $ map snd anl
checkListBit :: Sign -> Maybe Relation -> ListFrameBit -> Result ListFrameBit
checkListBit s r fb = case fb of
AnnotationBit anl -> case r of
Just (DRRelation _) -> checkAnnos s (map fst anl) >> return fb
_ -> checkAnnoList s (mapM_ $ checkEntity s .
mkEntity AnnotationProperty) anl >> return fb
ExpressionBit anl -> do
let annos = map fst anl
checkAnnos s annos
n <- mapM (checkClassExpression s . snd) anl
return $ ExpressionBit $ zip annos n
ObjectBit anl -> do
let annos = map fst anl
ol = map snd anl
sorted = filterObjProp s ol
if null sorted then do
let dpl = map objPropToIRI ol
checkAnnos s annos
checkDataPropList s dpl >> return (DataBit $ zip annos dpl)
else if length sorted == length ol then return fb
else fail $ "Static analysis found that there are" ++
" multiple types of properties in\n\n" ++
show sorted ++ show (map objPropToIRI $ ol \\ sorted)
ObjectCharacteristics anl -> checkAnnos s (map fst anl) >> return fb
DataBit anl -> checkAnnoList s (checkDataPropList s) anl >> return fb
DataPropRange anl -> checkAnnoList s (mapM_ $ checkDataRange s) anl
>> return fb
IndividualFacts anl -> checkAnnoList s (checkFactList s) anl >> return fb
IndividualSameOrDifferent anl -> checkAnnos s (map fst anl) >> return fb
checkAnnBit :: Sign -> AnnFrameBit -> Result AnnFrameBit
checkAnnBit s fb = case fb of
DatatypeBit dr -> checkDataRange s dr >> return fb
ClassDisjointUnion cel -> fmap ClassDisjointUnion
$ mapM (checkClassExpression s) cel
ClassHasKey ol dl -> checkHasKey s ol dl
ObjectSubPropertyChain ol -> checkObjPropList s ol >> return fb
_ -> return fb
checkAssertion :: Sign -> IRI -> Annotations -> Result [Axiom]
checkAssertion s iri ans = do
let entList = correctEntity s iri
ab = AnnFrameBit ans $ AnnotationFrameBit Assertion
if null entList
then let misc = Misc [Annotation [] iri $ AnnValue iri]
in return [PlainAxiom misc ab] -- only for anonymous individuals
else return $ map (\ x -> PlainAxiom (SimpleEntity x) ab) entList
checkExtended :: Sign -> Extended -> Result Extended
checkExtended s e = case e of
ClassEntity ce -> fmap ClassEntity $ checkClassExpression s ce
ObjectEntity oe -> case oe of
ObjectInverseOf op -> let i = objPropToIRI op in
if Set.member i (objectProperties s)
then return e else mkError "unknown object property" i
_ -> return e
Misc ans -> checkAnnos s [ans] >> return e
_ -> return e
-- | corrects the axiom according to the signature
checkAxiom :: Sign -> Axiom -> Result [Axiom]
checkAxiom s ax@(PlainAxiom ext fb) = case fb of
ListFrameBit mr lfb -> do
next <- checkExtended s ext
nfb <- fmap (ListFrameBit mr) $ checkListBit s mr lfb
return [PlainAxiom next nfb]
ab@(AnnFrameBit ans afb) -> do
checkAnnos s [ans]
case afb of
AnnotationFrameBit ty -> case ty of
Assertion -> case ext of
-- this can only come from XML
Misc [Annotation _ iri _] -> checkAssertion s iri ans
-- these can only come from Manchester Syntax
SimpleEntity (Entity _ _ iri) -> checkAssertion s iri ans
ClassEntity (Expression iri) -> checkAssertion s iri ans
ObjectEntity (ObjectProp iri) -> checkAssertion s iri ans
_ -> do
next <- checkExtended s ext
-- could rarely happen, and only in our extended syntax
return [PlainAxiom next ab]
Declaration -> return [ax]
_ -> return []
_ -> do
next <- checkExtended s ext
nfb <- fmap (AnnFrameBit ans) $ checkAnnBit s afb
return [PlainAxiom next nfb]
-- | checks a frame and applies desired changes
checkFrame :: Sign -> Frame -> Result [Frame]
checkFrame s (Frame eith fbl) = if null fbl then do
ext <- checkExtended s eith
return [Frame ext []]
else fmap (map axToFrame . concat) $ mapM (checkAxiom s . PlainAxiom eith) fbl
correctFrames :: Sign -> [Frame] -> Result [Frame]
correctFrames s = fmap concat . mapM (checkFrame s)
collectEntities :: Frame -> State Sign ()
collectEntities f = case f of
Frame (SimpleEntity e) _ -> addEntity e
Frame (ClassEntity (Expression e)) _ -> addEntity $ mkEntity Class e
Frame (ObjectEntity (ObjectProp e)) _ ->
addEntity $ mkEntity ObjectProperty e
_ -> return ()
-- | collects all entites from the frames
createSign :: [Frame] -> State Sign ()
createSign f = do
pm <- gets prefixMap
mapM_ (collectEntities . function Expand (StringMap pm)) f
noDecl :: Axiom -> Bool
noDecl ax = case ax of
PlainAxiom _ (AnnFrameBit _ (AnnotationFrameBit Declaration)) -> False
_ -> True
-- | corrects the axioms according to the signature
createAxioms :: Sign -> [Frame] -> Result ([Named Axiom], [Frame])
createAxioms s fl = do
cf <- correctFrames s $ map (function Expand $ StringMap $ prefixMap s) fl
return (map anaAxiom . filter noDecl $ concatMap getAxioms cf, cf)
check1Prefix :: Maybe String -> String -> Bool
check1Prefix ms s = case ms of
Nothing -> True
Just iri -> iri == s
checkPrefixMap :: PrefixMap -> Bool
checkPrefixMap pm =
let pl = map (`Map.lookup` pm) ["owl", "rdf", "rdfs", "xsd"]
in and $ zipWith check1Prefix pl
(map snd $ tail $ Map.toList predefPrefixes)
newODoc :: OntologyDocument -> [Frame] -> Result OntologyDocument
newODoc OntologyDocument {ontology = mo, prefixDeclaration = pd} fl =
if checkPrefixMap pd
then return OntologyDocument
{ ontology = mo {ontFrames = fl}, prefixDeclaration = pd}
else fail $ "Incorrect predefined prefixes " ++ showDoc pd "\n"
-- | static analysis of ontology with incoming sign.
basicOWL2Analysis :: (OntologyDocument, Sign, GlobalAnnos)
-> Result (OntologyDocument, ExtSign Sign Entity, [Named Axiom])
basicOWL2Analysis (inOnt, inSign, ga) = do
let pm = Map.union (prefixDeclaration inOnt)
. Map.map (iriToStringUnsecure . setAngles False)
. Map.delete "" $ prefix_map ga
odoc = inOnt { prefixDeclaration = pm }
fs = ontFrames $ ontology odoc
accSign = execState (createSign fs) inSign { prefixMap = pm }
syms = Set.difference (symOf accSign) $ symOf inSign
(axl, nfl) <- createAxioms accSign fs
newdoc <- newODoc odoc nfl
return (newdoc
, ExtSign accSign {labelMap = generateLabelMap accSign nfl} syms, axl)
-- | extrace labels from Frame-List (after processing with correctFrames)
generateLabelMap :: Sign -> [Frame] -> Map.Map IRI String
generateLabelMap sig = foldr (\ (Frame ext fbl) -> case ext of
SimpleEntity (Entity _ _ ir) -> case fbl of
[AnnFrameBit [Annotation _ apr (AnnValLit (Literal s' _))] _]
| namePrefix apr == "rdfs" && localPart apr == "label"
-> Map.insert ir s'
_ -> id
_ -> id ) (labelMap sig)
-- | adding annotations for theorems
anaAxiom :: Axiom -> Named Axiom
anaAxiom ax = findImplied ax $ makeNamed "" ax
findImplied :: Axiom -> Named Axiom -> Named Axiom
findImplied ax sent =
if prove ax then sent
{ isAxiom = False
, isDef = False
, wasTheorem = False }
else sent { isAxiom = True }
addEquiv :: Sign -> Sign -> [SymbItems] -> [SymbItems] ->
Result (Sign, Sign, Sign,
EndoMap Entity, EndoMap Entity)
addEquiv ssig tsig l1 l2 = do
let l1' = statSymbItems ssig l1
l2' = statSymbItems tsig l2
case (l1', l2') of
([rs1], [rs2]) -> do
let match1 = filter (`matchesSym` rs1) $ Set.toList $ symOf ssig
match2 = filter (`matchesSym` rs2) $ Set.toList $ symOf tsig
case
(match1, match2) of
([e1], [e2]) ->
if entityKind e1 == entityKind e2 then do
s <- pairSymbols e1 e2
sig <- addSymbToSign emptySign s
sig1 <- addSymbToSign emptySign e1
sig2 <- addSymbToSign emptySign e2
return (sig, sig1, sig2,
Map.insert e1 s Map.empty,
Map.insert e2 s Map.empty)
else
fail "only symbols of same kind can be equivalent in an alignment"
_ -> fail $ "non-unique symbol match:" ++ show l1 ++ " " ++ show l2
_ -> fail "terms not yet supported in alignments"
corr2theo :: Sign -> Sign -> [SymbItems] -> [SymbItems] ->
EndoMap Entity -> EndoMap Entity -> REL_REF ->
Result (Sign, [Named Axiom], Sign, Sign,
EndoMap Entity, EndoMap Entity)
corr2theo ssig tsig l1 l2 eMap1 eMap2 rref = do
let l1' = statSymbItems ssig l1
l2' = statSymbItems tsig l2
case (l1', l2') of
([rs1], [rs2]) -> do
let match1 = filter (`matchesSym` rs1) $ Set.toList $ symOf ssig
match2 = filter (`matchesSym` rs2) $ Set.toList $ symOf tsig
case
(match1, match2) of
([e1], [e2]) -> do
let e1' = Map.findWithDefault e1 e1 eMap1
e2' = Map.findWithDefault e2 e2 eMap2
sig = emptySign
eMap1' = Map.union eMap1 $ Map.fromAscList [(e1, e1)]
eMap2' = Map.union eMap2 $ Map.fromAscList [(e2, e2)]
sig1 <- addSymbToSign sig e1
sig2 <- addSymbToSign sig e2
sigI <- addSymbToSign sig e1'
sigB <- addSymbToSign sigI e2'
case rref of
Subs -> do
let extPart = mkExtendedEntity e2'
axiom = PlainAxiom extPart $
ListFrameBit (Just $
case (entityKind e1, entityKind e2) of
(Class, Class) -> SubClass
(ObjectProperty, ObjectProperty) ->
SubPropertyOf
_ -> error $ "use subsumption only between"
++ "classes or roles:" ++
show l1 ++ " " ++ show l2) $
ExpressionBit [([], Expression $ cutIRI e1')]
return (sigB, [makeNamed "" axiom], sig1, sig2, eMap1', eMap2')
Incomp -> do
let extPart = mkExtendedEntity e1'
axiom = PlainAxiom extPart $
ListFrameBit (Just $ EDRelation Disjoint) $
ExpressionBit [([], Expression $ cutIRI e2')]
return (sigB, [makeNamed "" axiom], sig1, sig2, eMap1', eMap2')
IsSubs -> do
let extPart = mkExtendedEntity e1'
axiom = PlainAxiom extPart $
ListFrameBit (Just SubClass) $
ExpressionBit [([], Expression $ cutIRI e2')]
return (sigB, [makeNamed "" axiom], sig1, sig2, eMap1', eMap2')
InstOf -> do
let extPart = mkExtendedEntity e1'
axiom = PlainAxiom extPart $
ListFrameBit (Just Types) $
ExpressionBit [([], Expression $ cutIRI e2')]
return
(sigB, [makeNamed "" axiom], sig1, sig2, eMap1', eMap2')
HasInst -> do
let extPart = mkExtendedEntity e2'
axiom = PlainAxiom extPart $
ListFrameBit (Just Types) $
ExpressionBit [([], Expression $ cutIRI e1')]
return
(sigB, [makeNamed "" axiom], sig1, sig2, eMap1', eMap2')
RelName r -> do
let extPart = mkExtendedEntity e1'
rQName = QN "" (iriToStringUnsecure r)
Abbreviated (iriToStringUnsecure r) Id.nullRange
sym = mkEntity ObjectProperty rQName
rSyms = filter (== sym) $
Set.toList $ symOf tsig
case rSyms of
[] -> fail $ "relation " ++ show rQName ++
" not in " ++ show tsig
[rsym] -> do
let sym'@(Entity _ ObjectProperty rQName') =
Map.findWithDefault rsym rsym eMap2'
axiom = PlainAxiom extPart $
ListFrameBit (Just SubClass) $
ExpressionBit [([],
ObjectValuesFrom
SomeValuesFrom
(ObjectProp rQName')
(Expression $ cutIRI e2'))]
sigB' <- addSymbToSign sigB sym'
sig2' <- addSymbToSign sig2 rsym
return
(sigB', [makeNamed "" axiom], sig1, sig2', eMap1',
Map.union eMap2' $ Map.fromAscList [(rsym, sym')])
_ -> fail $ "too many matches for " ++ show rQName
_ -> fail $ "nyi:" ++ show rref
_ -> fail $ "non-unique symbol match:" ++ show l1 ++ " " ++ show l2
_ -> fail "terms not yet supported in alignments"
| keithodulaigh/Hets | OWL2/StaticAnalysis.hs | gpl-2.0 | 21,989 | 257 | 21 | 6,883 | 6,472 | 3,268 | 3,204 | 439 | 23 |
module Rasa.Internal.ActionSpec where
import Test.Hspec
spec :: Spec
spec = return ()
| samcal/rasa | rasa/test/Rasa/Internal/ActionSpec.hs | gpl-3.0 | 88 | 0 | 6 | 14 | 27 | 16 | 11 | 4 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Dense.Mutable
-- Copyright : (c) Christopher Chalmers
-- License : BSD3
--
-- Maintainer : Christopher Chalmers
-- Stability : provisional
-- Portability : non-portable
--
-- This module provides generic functions over mutable multidimensional
-- arrays.
-----------------------------------------------------------------------------
module Data.Dense.Mutable
(
-- * Mutable array
MArray (..)
, UMArray
, SMArray
, BMArray
, PMArray
-- * Lenses
, mlayout
, mvector
-- * Creation
, new
, replicate
, replicateM
, clone
-- * Standard operations
-- ** Indexing
, read
, linearRead
, unsafeRead
, unsafeLinearRead
-- ** Writing
, write
, linearWrite
, unsafeWrite
, unsafeLinearWrite
-- ** Modifying
, modify
, linearModify
, unsafeModify
, unsafeLinearModify
-- ** Swap
, swap
, linearSwap
, unsafeSwap
, unsafeLinearSwap
-- ** Exchange
, exchange
, linearExchange
, unsafeExchange
, unsafeLinearExchange
-- * Misc
, set
, clear
, copy
) where
import Control.Monad (liftM)
import Control.Monad.Primitive
import Control.Lens (IndexedLens, indexed, Lens, (<&>))
import Data.Foldable as F
import Data.Typeable
import qualified Data.Vector as B
import Data.Vector.Generic.Mutable (MVector)
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Primitive.Mutable as P
import qualified Data.Vector.Storable.Mutable as S
import qualified Data.Vector.Unboxed.Mutable as U
import Linear.V1
import Data.Dense.Index
import Prelude hiding (read, replicate)
-- | A mutable array with a shape.
data MArray v l s a = MArray !(Layout l) !(v s a)
deriving Typeable
-- | Boxed mutable array.
type BMArray = MArray B.MVector
-- | Unboxed mutable array.
type UMArray = MArray U.MVector
-- | Storable mutable array.
type SMArray = MArray S.MVector
-- | Primitive mutable array.
type PMArray = MArray P.MVector
-- | Lens onto the shape of the vector. The total size of the layout
-- _must_ remain the same or an error is thrown.
mlayout :: (Shape f, Shape f') => Lens (MArray v f s a) (MArray v f' s a) (Layout f) (Layout f')
mlayout f (MArray l v) = f l <&> \l' ->
sizeMissmatch (F.product l) (F.product l')
("mlayout: trying to replace shape " ++ showShape l ++ ", with " ++ showShape l')
$ MArray l' v
{-# INLINE mlayout #-}
instance Shape f => HasLayout f (MArray v f s a) where
layout = mlayout
{-# INLINE layout #-}
-- | Indexed lens over the underlying vector of an array. The index is
-- the 'extent' of the array. You must __not__ change the length of
-- the vector, otherwise an error will be thrown.
mvector :: (MVector v a, MVector w b) => IndexedLens (Layout f) (MArray v f s a) (MArray w f t b) (v s a) (w t b)
mvector f (MArray l v) =
indexed f l v <&> \w ->
sizeMissmatch (GM.length v) (GM.length w)
("mvector: trying to replace vector of length " ++ show (GM.length v) ++ ", with one of length " ++ show (GM.length w))
$ MArray l w
{-# INLINE mvector #-}
-- | New mutable array with shape @l@.
new :: (PrimMonad m, Shape f, MVector v a) => Layout f -> m (MArray v f (PrimState m) a)
new l = MArray l `liftM` GM.new (F.product l)
{-# INLINE new #-}
-- | New mutable array with shape @l@ filled with element @a@.
replicate :: (PrimMonad m, Shape f, MVector v a) => Layout f -> a -> m (MArray v f (PrimState m) a)
replicate l a = MArray l `liftM` GM.replicate (F.product l) a
{-# INLINE replicate #-}
-- | New mutable array with shape @l@ filled with result of monadic
-- action @a@.
replicateM :: (PrimMonad m, Shape f, MVector v a) => Layout f -> m a -> m (MArray v f (PrimState m) a)
replicateM l a = MArray l `liftM` GM.replicateM (F.product l) a
{-# INLINE replicateM #-}
-- | Clone a mutable array, making a new, separate mutable array.
clone :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> m (MArray v f (PrimState m) a)
clone (MArray l v) = MArray l `liftM` GM.clone v
{-# INLINE clone #-}
-- Individual elements -------------------------------------------------
-- | Clear the elements of a mutable array. This is usually a no-op for
-- unboxed arrays.
clear :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> m ()
clear (MArray _ v) = GM.clear v
{-# INLINE clear #-}
-- | Read a mutable array at element @l@.
read :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> m a
read (MArray l v) s = boundsCheck l s $ GM.unsafeRead v (shapeToIndex l s)
{-# INLINE read #-}
-- | Write a mutable array at element @l@.
write :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> a -> m ()
write (MArray l v) s a = boundsCheck l s $ GM.unsafeWrite v (shapeToIndex l s) a
{-# INLINE write #-}
-- | Modify a mutable array at element @l@ by applying a function.
modify :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> (a -> a) -> m ()
modify (MArray l v) s f = boundsCheck l s $ GM.unsafeRead v i >>= GM.unsafeWrite v i . f
where i = shapeToIndex l s
{-# INLINE modify #-}
-- | Swap two elements in a mutable array.
swap :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> f Int -> m ()
swap (MArray l v) i j = boundsCheck l i boundsCheck l j $ GM.unsafeSwap v (shapeToIndex l i) (shapeToIndex l j)
{-# INLINE swap #-}
-- | Replace the element at the give position and return the old
-- element.
exchange :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> a -> m a
exchange (MArray l v) i a = boundsCheck l i $ GM.unsafeExchange v (shapeToIndex l i) a
{-# INLINE exchange #-}
-- | Read a mutable array at element @i@ by indexing the internal
-- vector.
linearRead :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> m a
linearRead (MArray _ v) = GM.read v
{-# INLINE linearRead #-}
-- | Write a mutable array at element @i@ by indexing the internal
-- vector.
linearWrite :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> a -> m ()
linearWrite (MArray _ v) = GM.write v
{-# INLINE linearWrite #-}
-- | Swap two elements in a mutable array by indexing the internal
-- vector.
linearSwap :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> Int -> m ()
linearSwap (MArray _ v) = GM.swap v
{-# INLINE linearSwap #-}
-- | Modify a mutable array at element @i@ by applying a function.
linearModify :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> (a -> a) -> m ()
linearModify (MArray _ v) i f = GM.read v i >>= GM.unsafeWrite v i . f
{-# INLINE linearModify #-}
-- | Replace the element at the give position and return the old
-- element.
linearExchange :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> a -> m a
linearExchange (MArray _ v) i a = GM.exchange v i a
{-# INLINE linearExchange #-}
-- Unsafe varients
-- | 'read' without bounds checking.
unsafeRead :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> m a
unsafeRead (MArray l v) s = GM.unsafeRead v (shapeToIndex l s)
{-# INLINE unsafeRead #-}
-- | 'write' without bounds checking.
unsafeWrite :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> a -> m ()
unsafeWrite (MArray l v) s = GM.unsafeWrite v (shapeToIndex l s)
{-# INLINE unsafeWrite #-}
-- | 'swap' without bounds checking.
unsafeSwap :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> f Int -> m ()
unsafeSwap (MArray l v) s j = GM.unsafeSwap v (shapeToIndex l s) (shapeToIndex j s)
{-# INLINE unsafeSwap #-}
-- | 'modify' without bounds checking.
unsafeModify :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> (a -> a) -> m ()
unsafeModify (MArray l v) s f = GM.unsafeRead v i >>= GM.unsafeWrite v i . f
where i = shapeToIndex l s
{-# INLINE unsafeModify #-}
-- | Replace the element at the give position and return the old
-- element.
unsafeExchange :: (PrimMonad m, Shape f, MVector v a) => MArray v f (PrimState m) a -> f Int -> a -> m a
unsafeExchange (MArray l v) i a = GM.unsafeExchange v (shapeToIndex l i) a
{-# INLINE unsafeExchange #-}
-- | 'linearRead' without bounds checking.
unsafeLinearRead :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> m a
unsafeLinearRead (MArray _ v) = GM.unsafeRead v
{-# INLINE unsafeLinearRead #-}
-- | 'linearWrite' without bounds checking.
unsafeLinearWrite :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> a -> m ()
unsafeLinearWrite (MArray _ v) = GM.unsafeWrite v
{-# INLINE unsafeLinearWrite #-}
-- | 'linearSwap' without bounds checking.
unsafeLinearSwap :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> Int -> m ()
unsafeLinearSwap (MArray _ v) = GM.unsafeSwap v
{-# INLINE unsafeLinearSwap #-}
-- | 'linearModify' without bounds checking.
unsafeLinearModify :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> (a -> a) -> m ()
unsafeLinearModify (MArray _ v) i f = GM.unsafeRead v i >>= GM.unsafeWrite v i . f
{-# INLINE unsafeLinearModify #-}
-- | Replace the element at the give position and return the old
-- element.
unsafeLinearExchange :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> Int -> a -> m a
unsafeLinearExchange (MArray _ v) i a = GM.unsafeExchange v i a
{-# INLINE unsafeLinearExchange #-}
-- Filling and copying -------------------------------------------------
-- | Set all elements in a mutable array to a constant value.
set :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> a -> m ()
set (MArray _ v) = GM.set v
{-# INLINE set #-}
-- | Copy all elements from one array into another.
copy :: (PrimMonad m, MVector v a) => MArray v f (PrimState m) a -> MArray v f (PrimState m) a -> m ()
copy (MArray _ v) (MArray _ u) = GM.copy v u
{-# INLINE copy #-}
-- V1 instances --------------------------------------------------------
-- Array v V1 a is essentially v a with a wrapper. Instance is provided
-- for convience.
instance (MVector v a, f ~ V1) => MVector (MArray v f) a where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicInitialize #-}
basicLength (MArray (V1 n) _) = n
basicUnsafeSlice i n (MArray _ v) = MArray (V1 n) $ GM.basicUnsafeSlice i n v
basicOverlaps (MArray _ v) (MArray _ w) = GM.basicOverlaps v w
basicUnsafeNew n = MArray (V1 n) `liftM` GM.basicUnsafeNew n
basicUnsafeRead (MArray _ v) = GM.basicUnsafeRead v
basicUnsafeWrite (MArray _ v) = GM.basicUnsafeWrite v
basicInitialize (MArray _ v) = GM.basicInitialize v
| cchalmers/dense | src/Data/Dense/Mutable.hs | bsd-3-clause | 11,197 | 0 | 16 | 2,447 | 3,536 | 1,851 | 1,685 | 178 | 1 |
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class
import Data.Aeson (object, (.=))
import Data.Default
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.HashMap.Strict as HashMap
import qualified Data.HashSet as HashSet
import qualified Data.Graph.Inductive.Dot as Graph
import qualified Data.Graph.Inductive.Graph as Graph
import qualified Data.Set as Set
import Data.Text (Text)
import Lucid
import Web.Scotty
import Network.Wai.Middleware.RequestLogger
import Text.Printf
import NanoML
import NanoML.Explore
import NanoML.Learn
import NanoML.Misc
import NanoML.Pretty
import Debug.Trace
data Tool = Nanomaly | Nate
toolTitle Nanomaly = "NanoMaLy"
toolTitle Nate = "NanoMaLy + Nate"
toolJS Nanomaly = "/nanoml.js"
toolJS Nate = "/nanoml-nate.js"
main = do
log <- mkRequestLogger def { outputFormat = Detailed False }
(net, features) <- stdNet
scotty 8091 $ do
middleware log
get "/" $ home Nanomaly
get "/nate" $ home Nate
get "/zepto.min.js" $ file "bin/dist/zepto.min.js"
get "/vis.css" $ file "bin/dist/vis.css"
get "/vis.js" $ file "bin/dist/vis.js"
get "/codemirror-min.js" $ file "bin/dist/codemirror-min.js"
get "/panel.js" $ file "bin/dist/panel.js"
get "/codemirror.css" $ file "bin/dist/codemirror.css"
get "/dialog.css" $ file "bin/dist/dialog.css"
get "/lint.css" $ file "bin/dist/lint.css"
get "/nanoml.css" $ file "bin/nanoml.css"
get "/nanoml.js" $ file "bin/nanoml.js"
get "/nanoml-nate.js" $ file "bin/nanoml-nate.js"
post "/check" $ do
prog <- param "prog"
var <- param "var" <|> return ""
-- liftIO $ print (var, prog)
let p = fromRight (parseTopForm prog)
case parseTopForm prog of
Right p -> json =<< run p var net features
Left e -> json $ object [ "result" .= ("parse-error" :: String)
, "error" .= e
]
home tool = do
prog <- lookup "prog" <$> params
html . renderText . doctypehtml_ $ do
head_ $ do
title_ (toolTitle tool)
link_ [ href_ "//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css", rel_ "stylesheet", type_ "text/css" ]
link_ [ href_ "//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css", rel_ "stylesheet", type_ "text/css" ]
script_ [ src_ "//code.jquery.com/jquery-2.1.4.min.js", type_ "text/javascript" ] ("" :: Text)
script_ [ src_ "//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js", type_ "text/javascript" ] ("" :: Text)
script_ [ src_ "/zepto.min.js", type_ "text/javascript" ] ("" :: Text)
link_ [ href_ "/vis.css", rel_ "stylesheet", type_ "text/css" ]
script_ [ src_ "/vis.js", type_ "text/javascript" ] ("" :: Text)
script_ [ src_ "/codemirror-min.js", type_ "text/javascript" ] ("" :: Text)
script_ [ src_ "/panel.js", type_ "text/javascript" ] ("" :: Text)
link_ [ href_ "/codemirror.css", rel_ "stylesheet", type_ "text/css" ]
link_ [ href_ "/dialog.css", rel_ "stylesheet", type_ "text/css" ]
link_ [ href_ "/lint.css", rel_ "stylesheet", type_ "text/css" ]
link_ [ href_ "/nanoml.css", rel_ "stylesheet", type_ "text/css" ]
script_ [ src_ (toolJS tool), type_ "text/javascript" ] ("" :: Text)
body_ [class_ "container-fluid", onload_ "setup()"] $ do
nav_ [class_ "navbar navbar-default"] $ do
div_ [class_ "container-fluid"] $ do
div_ [class_ "navbar-header"] $ do
a_ [class_ "navbar-brand", href_ "#"] (toolTitle tool)
ul_ [class_ "nav navbar-nav"] $ do
li_ [class_ "dropdown"] $ do
button_ [ class_ "btn btn-default navbar-btn dropdown-toggle"
, type_ "button"
, id_ "loadMenu", data_ "toggle" "dropdown" ] $ do
"Demo "
span_ [class_ "caret"] ""
ul_ [class_ "dropdown-menu"] $ do
li_ $ a_ [onclick_ "loadDemo('factorial')"] "factorial"
li_ $ a_ [onclick_ "loadDemo('sumList')"] "sumList"
li_ $ a_ [onclick_ "loadDemo('sepConcat')"] "sepConcat"
-- li_ $ a_ [onclick_ "loadDemo('padZero')"] "padZero"
li_ $ a_ [onclick_ "loadDemo('mulByDigit')"] "mulByDigit"
-- li_ $ a_ [onclick_ "loadDemo('digitsOfInt')"] "digitsOfInt"
li_ $ a_ [onclick_ "loadDemo('wwhile')"] "wwhile"
-- li_ $ a_ [onclick_ "loadDemo('palindrome')"] "palindrome"
form_ [class_ "navbar-form navbar-left"] $ do
div_ [class_ "form-group"] $ do
input_ [ id_ "var-input", name_ "var"
, placeholder_ "check this function"
, type_ "text", class_ "form-control"
, style_ "font-family: monospace;"
]
button_ [id_ "check-btn", class_ "btn btn-default", type_ "submit"]
"Check!"
form_ [class_ "navbar-form navbar-right"] $ do
div_ [ class_ "form-group" ] $ do
button_ [ type_ "button", class_ "btn btn-default", disabled_ "disabled"
, id_ "undo", onclick_ "stepUndo()" ]
"Undo"
button_ [ type_ "button", class_ "btn btn-default", disabled_ "disabled"
, id_ "step-forward", onclick_ "stepForward()" ]
"Step forward"
button_ [ type_ "button", class_ "btn btn-default", disabled_ "disabled"
, id_ "step-backward", onclick_ "stepBackward()" ]
"Step backward"
button_ [ type_ "button", class_ "btn btn-default", disabled_ "disabled"
, id_ "jump-forward", onclick_ "jumpForward()" ]
"Jump forward"
button_ [ type_ "button", class_ "btn btn-default", disabled_ "disabled"
, id_ "jump-backward", onclick_ "jumpBackward()" ]
"Jump backward"
button_ [ type_ "button", class_ "btn btn-default", disabled_ "disabled"
, id_ "step-into", onclick_ "stepInto()" ]
"Step into"
button_ [ type_ "button", class_ "btn btn-default", disabled_ "disabled"
, id_ "step-over", onclick_ "stepOver()" ]
"Step over"
div_ [class_ "mybody row"] $ do
div_ [class_ "mybody col-md-6"] $ do
-- form_ [id_ "form", action_ "/", method_ "POST"] $ do
-- div_ [class_ "row"] $
-- div_ [class_ "input-group"] $ do
-- span_ [class_ "input-group-btn"] $
-- button_ [class_ "btn btn-default", type_ "submit"] "Check!"
-- div_ [class_ "row"] $
textarea_ [ id_ "prog", name_ "prog"
-- , rows_ "10", cols_ "50"
-- , style_ "font-family: monospace;"
] (toHtml $ fromMaybe "" prog)
div_ [class_ "mybody col-md-6"] $ do
div_ [ id_ "safe-banner", class_ "alert alert-info"
, style_ "display: none;" ] $ do
"Couldn't find a type error.."
div_ [ id_ "unsafe-banner", class_ "alert alert-warning"
, style_ "display: none;" ] $ do
"Your program contains a type error!"
div_ [ id_ "vis", class_ "mybody", style_ "border: 1px solid lightgray;"
] ""
run p var net features = do
-- liftIO $ print (prettyProg p)
let myOpts = stdOpts { size = 5, maxTests = 100 }
res <- liftIO $ if null var
then fromJust <$> checkWith myOpts Nothing p
else checkDeclWith myOpts var p
let mkSpan s =
object [ "startLine" .= srcSpanStartLine s
, "startCol" .= srcSpanStartCol s
, "endLine" .= srcSpanEndLine s
, "endCol" .= srcSpanEndCol s
]
let mkNode (n, ((l,as),s,e)) =
object [ "id" .= n
, "label" .= l
, "span" .= fmap mkSpan s
, "annots" .= as
, "env" .= e
]
let mkEdge (x, y, l) =
object [ "arrows" .= ("to" :: String)
, "from" .= x, "to" .= y
, "label" .= show l
]
let mkBlame (c, MkConstraint s t1 t2 msg) =
object [ "confidence" .= c, "srcSpan" .= mkSpan (fromJust s)
, "expected" .= render (pretty t1), "actual" .= render (pretty t2)
, "message" .= (printf msg (render (pretty t2)) (render (pretty t1)) :: String)
]
-- liftIO $ print res
let blame = take 3 $ rankExprs net features p
case res of
Success n finalState v -> do
-- liftIO $ print v
let gr = buildGraph (HashSet.toList $ stEdges finalState)
let st = findRoot gr (v, stVarEnv finalState)
let root = findRoot gr (stRoot finalState)
let gr' = gr
-- gr <- liftIO $ buildGraph (stEdges finalState)
-- st <- liftIO $ findRoot gr v -- (stCurrentExpr finalState)
-- root <- liftIO $ findRoot gr (stRoot finalState)
-- gr' <- liftIO $ addEnvs finalState gr
let gr'' = Graph.gmap (\(inc, i, (n,e), outc) ->
let ?ctx = fromMaybe Elsewhere
(HashMap.lookup n (stContexts finalState))
?pctx = fromMaybe Elsewhere (do
(m,_) <- backStep gr i
HashMap.lookup m (stContexts finalState))
in
(inc, i,
( renderSpans $ prettyRedex e $
fillHoles finalState n
, getSrcSpanExprMaybe . fromMaybe n $
(applyContext_maybe (stContexts finalState) n)
, addFreeVars finalState n e
), outc)
)
gr'
let gr''' = collapseBadEdges gr''
let nodes = Graph.labNodes gr'''
let edges = Graph.labEdges gr'''
-- let root = backback gr'' st
let value = st
-- liftIO $ writeFile "tmp.dot" $ Graph.showDot (Graph.fglToDotGeneric gr''' (fst.fst) show id)
return $ object [ -- ("dot" :: String, dot)
"nodes" .= map mkNode nodes
, "edges" .= map mkEdge edges
, "root" .= root
, "value" .= value
, "result" .= ("value" :: String)
, "blame" .= map mkBlame blame
]
-- html . renderText . doctypehtml_ $ do
-- title_ "NanoML"
-- body_ $ do
-- "Could not find a counter-example after "
-- toHtml (show n)
-- "tests.."
Failure {..} -> do
-- FIXME: handle programs that time out!!!
liftIO $ print $ pretty errorMsg
liftIO $ print counterExample
case errorMsg of
TimeoutError i -> return $ object [ "result" .= ("timeout" :: String)
, "root" .= show counterExample
]
_ -> do
-- liftIO $ mapM_ print (stEdges finalState)
let gr = buildGraph (HashSet.toList $ stEdges finalState)
let bad = findRoot gr (stCurrentExpr finalState)
let root = findRoot gr (stRoot finalState)
let gr' = gr
-- gr <- liftIO $ buildGraph (stEdges finalState)
-- bad <- liftIO $ findRoot gr (stCurrentExpr finalState)
-- root <- liftIO $ findRoot gr (stRoot finalState)
let st = ancestor gr bad
-- gr' <- liftIO $ addEnvs finalState gr
-- liftIO $ putStrLn "CONTEXTS"
-- liftIO $ mapM_ print $ [(pretty e, c) | (e, c) <- HashMap.toList (stContexts finalState)]
-- liftIO $ putStrLn ""
let gr'' = Graph.gmap (\(inc, i, (n,e), outc) ->
let ?ctx = fromMaybe Elsewhere
(HashMap.lookup n (stContexts finalState))
?pctx = fromMaybe Elsewhere (do
(m,_) <- backStep gr i
HashMap.lookup m (stContexts finalState))
in -- traceShow (pretty n, ?ctx, ?pctx, renderSpans $ prettyRedex e $ fillHoles finalState n)
(inc, i,
( -- first ((show (envId e) ++ " : " ++ show (getSrcSpanExprMaybe n) ++ "\n") ++) $
renderSpans $ prettyRedex e $
fillHoles finalState n
, getSrcSpanExprMaybe . fromMaybe n $
(applyContext_maybe (stContexts finalState) n)
, addFreeVars finalState n e
), outc)
)
gr'
-- let gr'' = Graph.nmap (\(n,e) -> (renderSpans $ pretty $ fillHoles finalState n, getSrcSpanExprMaybe n, e)) gr'
let gr''' = collapseBadEdges gr''
let nodes = Graph.labNodes gr'''
let edges = Graph.labEdges gr'''
-- let root = backback gr'' st
let stuck = st
let dot = Graph.showDot (Graph.fglToDotGeneric gr'' (fst.fst3) show id)
liftIO $ writeFile "tmp.dot" dot
-- liftIO $ mapM_ print blame
let o = object [ -- ("dot" :: String, dot)
"nodes" .= map mkNode nodes
, "edges" .= map mkEdge edges
, "root" .= root
, "stuck" .= stuck
, "bad" .= bad
, "result" .= ("stuck" :: String)
, "reason" .= show (pretty errorMsg)
, "blame" .= map mkBlame blame
]
-- traceShowM o
-- liftIO $ putStrLn "helo"
return o
-- html . renderText . doctypehtml_ $ do
-- head_ $ do
-- title_ "NanoML"
-- link_ [ href_ "/vis.css", rel_ "stylesheet", type_ "text/css" ]
-- script_ [ src_ "/vis.js", type_ "text/javascript" ] ("" :: Text)
-- script_ [ src_ "/codemirror-min.js", type_ "text/javascript" ] ("" :: Text)
-- link_ [ href_ "/dialog.css", rel_ "stylesheet", type_ "text/css" ]
-- script_ [ id_ "reduction-graph", type_ "text/dot" ] dot
-- script_ [ id_ "root-node" ] (show (backback gr st))
-- script_ [ id_ "stuck-node" ] (show st)
-- script_ [ src_ "/nanoml.js", type_ "text/javascript" ] ("" :: Text)
-- body_ [ onload_ "draw()" ] $ do
-- h2_ "Program"
-- div_ [ style_ "font-family: monospace;" ] $
-- code_ $ pre_ $ toHtml prog
-- h2_ "Trace"
-- div_ $ do
-- div_ [ id_ "menu" ] $ ul_ $ do
-- li_ $
-- button_ [ disabled_ "true", id_ "step-forward", onclick_ "stepForward()" ]
-- "Step forward"
-- li_ $
-- button_ [ disabled_ "true", id_ "step-backward", onclick_ "stepBackward()" ]
-- "Step backward"
-- li_ $
-- button_ [ disabled_ "true", id_ "jump-forward", onclick_ "jumpForward()" ]
-- "Jump forward"
-- li_ $
-- button_ [ disabled_ "true", id_ "jump-backward", onclick_ "jumpBackward()" ]
-- "Jump backward"
-- div_ [ id_ "vis", style_ "width: 50%; border: 1px solid lightgray;" ] ""
-- h2_ "Counter-example"
-- div_ [ style_ "font-family: monospace;" ] (toHtml (show counterExample))
-- h2_ "Interesting paths"
-- div_ [ style_ "font-family: monospace;" ] $ forM pathSlices $ \p -> do
-- div_ [ style_ "float:left; margin:0; width:33%;" ] $
-- code_ $ pre_ $ toHtml (show p)
-- html . renderText . doctypehtml_ $ do
-- title_ "NanoML"
-- body_ $ do
-- form_ $ do
-- textarea_ [placeholder_ "Bad code here", rows_ "10", cols_ "50"] ""
-- button_ [type_ "submit"] "Submit"
| ucsd-progsys/nanomaly | bin/Main.hs | bsd-3-clause | 17,258 | 0 | 33 | 6,646 | 3,308 | 1,650 | 1,658 | 240 | 4 |
------------------------------------------------------------------------
-- |
-- Module : ALife.Creatur.Wain.Iomha.ActionQC
-- Copyright : (c) Amy de Buitléir 2013-2016
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- QuickCheck tests.
--
------------------------------------------------------------------------
module ALife.Creatur.Wain.Iomha.ActionQC
(
test
) where
import ALife.Creatur.Wain.Iomha.Action (Action)
import ALife.Creatur.Wain.TestUtils (prop_serialize_round_trippable,
prop_genetic_round_trippable, prop_diploid_identity)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
instance Arbitrary Action where
arbitrary = elements [minBound .. maxBound]
test :: Test
test = testGroup "ALife.Creatur.Wain.Iomha.ActionQC"
[
testProperty "prop_serialize_round_trippable - Action"
(prop_serialize_round_trippable :: Action -> Property),
testProperty "prop_genetic_round_trippable - Action"
(prop_genetic_round_trippable (==) :: Action -> Property),
testProperty "prop_diploid_identity - Action"
(prop_diploid_identity (==) :: Action -> Property)
]
| mhwombat/creatur-wains-iomha | test/ALife/Creatur/Wain/Iomha/ActionQC.hs | bsd-3-clause | 1,265 | 0 | 9 | 177 | 188 | 118 | 70 | 20 | 1 |
-- | Common config and debugging functions. Imported by most modules.
module Data.Array.Parallel.Base
( -- * Debugging infrastructure
module Data.Array.Parallel.Base.Config
, module Data.Array.Parallel.Base.Debug
-- * Data constructor rags
, module Data.Array.Parallel.Base.Tag
-- * ST monad re-exported from GHC
, ST(..)
, runST)
where
import Data.Array.Parallel.Base.Debug
import Data.Array.Parallel.Base.Config
import Data.Array.Parallel.Base.Tag
import GHC.ST (ST(..), runST)
| mainland/dph | dph-base/Data/Array/Parallel/Base.hs | bsd-3-clause | 554 | 0 | 6 | 127 | 92 | 68 | 24 | 11 | 0 |
{-# LANGUAGE PatternGuards, DeriveDataTypeable #-}
-- | Interned strings
module General.IString(
IString, fromIString, toIString
) where
import Data.Data
import Data.IORef
import Control.DeepSeq
import Data.String
import qualified Data.Map as Map
import System.IO.Unsafe
data IString = IString {-# UNPACK #-} !Int !String
deriving (Data,Typeable)
instance Eq IString where
IString x _ == IString y _ = x == y
instance Ord IString where
compare (IString x1 x2) (IString y1 y2)
| x1 == y1 = EQ
| otherwise = compare x2 y2
instance Show IString where show = fromIString
instance Read IString where readsPrec _ x = [(toIString x,"")]
instance IsString IString where fromString = toIString
instance NFData IString where rnf (IString _ _) = () -- we force the string at construction time
{-# NOINLINE istrings #-}
istrings :: IORef (Map.Map String IString)
istrings = unsafePerformIO $ newIORef Map.empty
fromIString :: IString -> String
fromIString (IString _ x) = x
toIString :: String -> IString
toIString x | () <- rnf x = unsafePerformIO $ atomicModifyIORef istrings $ \mp -> case Map.lookup x mp of
Just v -> (mp, v)
Nothing -> let res = IString (Map.size mp) x in (Map.insert x res mp, res)
| BartAdv/hoogle | src/General/IString.hs | bsd-3-clause | 1,246 | 0 | 18 | 248 | 429 | 222 | 207 | 32 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudFront.GetCloudFrontOriginAccessIdentity
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- 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)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Get the information about an origin access identity.
--
-- <http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/GetCloudFrontOriginAccessIdentity.html>
module Network.AWS.CloudFront.GetCloudFrontOriginAccessIdentity
(
-- * Request
GetCloudFrontOriginAccessIdentity
-- ** Request constructor
, getCloudFrontOriginAccessIdentity
-- ** Request lenses
, gcfoaiId
-- * Response
, GetCloudFrontOriginAccessIdentityResponse
-- ** Response constructor
, getCloudFrontOriginAccessIdentityResponse
-- ** Response lenses
, gcfoairCloudFrontOriginAccessIdentity
, gcfoairETag
) where
import Network.AWS.Prelude
import Network.AWS.Request.RestXML
import Network.AWS.CloudFront.Types
import qualified GHC.Exts
newtype GetCloudFrontOriginAccessIdentity = GetCloudFrontOriginAccessIdentity
{ _gcfoaiId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'GetCloudFrontOriginAccessIdentity' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gcfoaiId' @::@ 'Text'
--
getCloudFrontOriginAccessIdentity :: Text -- ^ 'gcfoaiId'
-> GetCloudFrontOriginAccessIdentity
getCloudFrontOriginAccessIdentity p1 = GetCloudFrontOriginAccessIdentity
{ _gcfoaiId = p1
}
-- | The identity's id.
gcfoaiId :: Lens' GetCloudFrontOriginAccessIdentity Text
gcfoaiId = lens _gcfoaiId (\s a -> s { _gcfoaiId = a })
data GetCloudFrontOriginAccessIdentityResponse = GetCloudFrontOriginAccessIdentityResponse
{ _gcfoairCloudFrontOriginAccessIdentity :: Maybe CloudFrontOriginAccessIdentity
, _gcfoairETag :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'GetCloudFrontOriginAccessIdentityResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gcfoairCloudFrontOriginAccessIdentity' @::@ 'Maybe' 'CloudFrontOriginAccessIdentity'
--
-- * 'gcfoairETag' @::@ 'Maybe' 'Text'
--
getCloudFrontOriginAccessIdentityResponse :: GetCloudFrontOriginAccessIdentityResponse
getCloudFrontOriginAccessIdentityResponse = GetCloudFrontOriginAccessIdentityResponse
{ _gcfoairCloudFrontOriginAccessIdentity = Nothing
, _gcfoairETag = Nothing
}
-- | The origin access identity's information.
gcfoairCloudFrontOriginAccessIdentity :: Lens' GetCloudFrontOriginAccessIdentityResponse (Maybe CloudFrontOriginAccessIdentity)
gcfoairCloudFrontOriginAccessIdentity =
lens _gcfoairCloudFrontOriginAccessIdentity
(\s a -> s { _gcfoairCloudFrontOriginAccessIdentity = a })
-- | The current version of the origin access identity's information. For example:
-- E2QWRUHAPOMQZL.
gcfoairETag :: Lens' GetCloudFrontOriginAccessIdentityResponse (Maybe Text)
gcfoairETag = lens _gcfoairETag (\s a -> s { _gcfoairETag = a })
instance ToPath GetCloudFrontOriginAccessIdentity where
toPath GetCloudFrontOriginAccessIdentity{..} = mconcat
[ "/2014-11-06/origin-access-identity/cloudfront/"
, toText _gcfoaiId
]
instance ToQuery GetCloudFrontOriginAccessIdentity where
toQuery = const mempty
instance ToHeaders GetCloudFrontOriginAccessIdentity
instance ToXMLRoot GetCloudFrontOriginAccessIdentity where
toXMLRoot = const (namespaced ns "GetCloudFrontOriginAccessIdentity" [])
instance ToXML GetCloudFrontOriginAccessIdentity
instance AWSRequest GetCloudFrontOriginAccessIdentity where
type Sv GetCloudFrontOriginAccessIdentity = CloudFront
type Rs GetCloudFrontOriginAccessIdentity = GetCloudFrontOriginAccessIdentityResponse
request = get
response = xmlHeaderResponse $ \h x -> GetCloudFrontOriginAccessIdentityResponse
<$> x .@? "CloudFrontOriginAccessIdentity"
<*> h ~:? "ETag"
| kim/amazonka | amazonka-cloudfront/gen/Network/AWS/CloudFront/GetCloudFrontOriginAccessIdentity.hs | mpl-2.0 | 4,835 | 0 | 11 | 903 | 518 | 311 | 207 | 63 | 1 |
module TestImport
( module TestImport
, module X
) where
import Application (makeFoundation, makeLogWare)
import ClassyPrelude as X
import Database.Persist as X hiding (get)
import Database.Persist.Sql (SqlPersistM, SqlBackend, runSqlPersistMPool, rawExecute, rawSql, unSingle, connEscapeName)
import Foundation as X
import Model as X
import Test.Hspec as X
import Text.Shakespeare.Text (st)
import Yesod.Default.Config2 (ignoreEnv, loadAppSettings)
import Yesod.Test as X
runDB :: SqlPersistM a -> YesodExample App a
runDB query = do
app <- getTestYesod
liftIO $ runDBWithApp app query
runDBWithApp :: App -> SqlPersistM a -> IO a
runDBWithApp app query = runSqlPersistMPool query (appConnPool app)
withApp :: SpecWith (TestApp App) -> Spec
withApp = before $ do
settings <- loadAppSettings
["config/test-settings.yml", "config/settings.yml"]
[]
ignoreEnv
foundation <- makeFoundation settings
wipeDB foundation
logWare <- liftIO $ makeLogWare foundation
return (foundation, logWare)
-- This function will truncate all of the tables in your database.
-- 'withApp' calls it before each test, creating a clean environment for each
-- spec to run in.
wipeDB :: App -> IO ()
wipeDB app = runDBWithApp app $ do
tables <- getTables
sqlBackend <- ask
let escapedTables = map (connEscapeName sqlBackend . DBName) tables
query = "TRUNCATE TABLE " ++ intercalate ", " escapedTables
rawExecute query []
getTables :: MonadIO m => ReaderT SqlBackend m [Text]
getTables = do
tables <- rawSql [st|
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public';
|] []
return $ map unSingle tables
| Drezil/FFF | test/TestImport.hs | apache-2.0 | 1,805 | 0 | 14 | 435 | 447 | 239 | 208 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
-- | Tag a Store instance with structural version info to ensure we're
-- reading a compatible format.
module Data.Store.VersionTagged
( versionedEncodeFile
, versionedDecodeOrLoad
, versionedDecodeFile
, storeVersionConfig
) where
import Control.Applicative
import Control.Exception.Lifted (catch, IOException, assert)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Control.Monad.Trans.Control (MonadBaseControl)
import qualified Data.ByteString as BS
import Data.Data (Data)
import qualified Data.Map as M
import Data.Monoid ((<>))
import qualified Data.Set as S
import Data.Store
import Data.Store.Version
import qualified Data.Text as T
import Language.Haskell.TH
import Path
import Path.IO (ensureDir)
import Prelude
versionedEncodeFile :: Data a => VersionConfig a -> Q Exp
versionedEncodeFile vc = [e| \fp x -> storeEncodeFile fp ($(wrapVersion vc) x) |]
versionedDecodeOrLoad :: Data a => VersionConfig a -> Q Exp
versionedDecodeOrLoad vc = [| versionedDecodeOrLoadImpl $(wrapVersion vc) $(checkVersion vc) |]
versionedDecodeFile :: Data a => VersionConfig a -> Q Exp
versionedDecodeFile vc = [e| versionedDecodeFileImpl $(checkVersion vc) |]
-- | Write to the given file.
storeEncodeFile :: (Store a, MonadIO m, MonadLogger m, Eq a)
=> Path Abs File
-> a
-> m ()
storeEncodeFile fp x = do
let fpt = T.pack (toFilePath fp)
$logDebug $ "Encoding " <> fpt
ensureDir (parent fp)
let encoded = encode x
assert (decodeEx encoded == x) $ liftIO $ BS.writeFile (toFilePath fp) encoded
$logDebug $ "Finished writing " <> fpt
-- | Read from the given file. If the read fails, run the given action and
-- write that back to the file. Always starts the file off with the
-- version tag.
versionedDecodeOrLoadImpl :: (Store a, Eq a, MonadIO m, MonadLogger m, MonadBaseControl IO m)
=> (a -> WithVersion a)
-> (WithVersion a -> Either VersionCheckException a)
-> Path Abs File
-> m a
-> m a
versionedDecodeOrLoadImpl wrap check fp mx = do
let fpt = T.pack (toFilePath fp)
$logDebug $ "Trying to decode " <> fpt
mres <- versionedDecodeFileImpl check fp
case mres of
Just x -> do
$logDebug $ "Success decoding " <> fpt
return x
_ -> do
$logDebug $ "Failure decoding " <> fpt
x <- mx
storeEncodeFile fp (wrap x)
return x
versionedDecodeFileImpl :: (Store a, MonadIO m, MonadLogger m, MonadBaseControl IO m)
=> (WithVersion a -> Either VersionCheckException a)
-> Path loc File
-> m (Maybe a)
versionedDecodeFileImpl check fp = do
mbs <- liftIO (Just <$> BS.readFile (toFilePath fp)) `catch` \(err :: IOException) -> do
$logDebug ("Exception ignored when attempting to load " <> T.pack (toFilePath fp) <> ": " <> T.pack (show err))
return Nothing
case mbs of
Nothing -> return Nothing
Just bs ->
liftIO (do decoded <- decodeIO bs
return $ case check decoded of
Right res -> Just res
_ -> Nothing) `catch` \(err :: PeekException) -> do
let fpt = T.pack (toFilePath fp)
$logDebug ("Error while decoding " <> fpt <> ": " <> T.pack (show err) <> " (this might not be an error, when switching between stack versions)")
return Nothing
storeVersionConfig :: String -> String -> VersionConfig a
storeVersionConfig name hash = (namedVersionConfig name hash)
{ vcIgnore = S.fromList
[ "Data.Vector.Unboxed.Base.Vector GHC.Types.Word"
, "Data.ByteString.Internal.ByteString"
]
, vcRenames = M.fromList
[ ( "Data.Maybe.Maybe", "GHC.Base.Maybe") ]
}
| AndreasPK/stack | src/Data/Store/VersionTagged.hs | bsd-3-clause | 4,232 | 0 | 20 | 1,175 | 1,075 | 552 | 523 | 90 | 3 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# OPTIONS_GHC -fwarn-unused-imports #-}
-- #1386
-- We do not want a warning about unused imports
module Foo () where
import Control.Monad (liftM)
foo :: IO ()
foo = id `liftM` return ()
foreign export ccall "hs_foo" foo :: IO ()
| sdiehl/ghc | testsuite/tests/rename/should_compile/rn058.hs | bsd-3-clause | 279 | 0 | 7 | 50 | 64 | 38 | 26 | 7 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableSuperClasses #-}
module T10592 where
import Data.Kind (Type)
import Prelude (Bool(True,False),Integer,Ordering)
import qualified Prelude
--------------------
-- class hierarchy
class Boolean (Logic a) => Eq a where
type Logic a :: Type
(==) :: a -> a -> Logic a
(/=) :: a -> a -> Logic a
a/=b = not (a==b)
class Eq a => POrd a where
inf :: a -> a -> a
class POrd a => MinBound a where
minBound :: a
class POrd a => Lattice a where
sup :: a -> a -> a
class (Lattice a, MinBound a) => Bounded a where
maxBound :: a
class Bounded a => Complemented a where
not :: a -> a
class Bounded a => Heyting a where
infixr 3 ==>
(==>) :: a -> a -> a
class (Complemented a, Heyting a) => Boolean a
(||) :: Boolean a => a -> a -> a
(||) = sup
(&&) :: Boolean a => a -> a -> a
(&&) = inf
--------------------
-- Bool instances
-- (these work fine)
instance Eq Bool where
type Logic Bool = Bool
(==) = (Prelude.==)
instance POrd Bool where
inf True True = True
inf _ _ = False
instance MinBound Bool where
minBound = False
instance Lattice Bool where
sup False False = False
sup _ _ = True
instance Bounded Bool where
maxBound = True
instance Complemented Bool where
not True = False
not False = True
instance Heyting Bool where
False ==> _ = True
True ==> a = a
instance Boolean Bool
--------------------
-- Integer instances
-- (these work fine)
instance Eq Integer where
type Logic Integer = Bool
(==) = (Prelude.==)
instance POrd Integer where
inf = Prelude.min
instance Lattice Integer where
sup = Prelude.max
--------------------
-- function instances
-- (these cause GHC to loop)
instance Eq b => Eq (a -> b) where
type Logic (a -> b) = a -> Logic b
f==g = \a -> f a == g a
instance POrd b => POrd (a -> b) where
inf f g = \a -> inf (f a) (g a)
instance MinBound b => MinBound (a -> b) where
minBound = \_ -> minBound
instance Lattice b => Lattice (a -> b) where
sup f g = \a -> sup (f a) (g a)
instance Bounded b => Bounded (a -> b) where
maxBound = \_ -> maxBound
instance Complemented b => Complemented (a -> b) where
not f = \a -> not (f a)
instance Heyting b => Heyting (a -> b) where
f ==> g = \a -> f a ==> g a
instance Boolean b => Boolean (a -> b)
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T10592.hs | bsd-3-clause | 2,430 | 0 | 9 | 646 | 972 | 513 | 459 | -1 | -1 |
module LibSpec where
import Test.Hspec
import Test.Hspec.QuickCheck
import Lib (ourAdd)
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "Lib" $ do
it "works" $ do
True `shouldBe` True
prop "ourAdd is commutative" $ \x y ->
ourAdd x y `shouldBe` ourAdd y x
| jamesdabbs/leeloo | test/LibSpec.hs | bsd-3-clause | 295 | 0 | 11 | 75 | 110 | 58 | 52 | 13 | 1 |
import XMonad
import XMonad.Config.Gnome
import XMonad.Hooks.DynamicLog
import Control.OldException
import DBus
import DBus.Connection
import DBus.Message
main :: IO ()
main = withConnection Session $ \dbus -> do
getWellKnownName dbus
xmonad $ gnomeConfig
{ logHook = dynamicLogWithPP (prettyPrinter dbus)
}
prettyPrinter :: Connection -> PP
prettyPrinter dbus = defaultPP
{ ppOutput = dbusOutput dbus
, ppTitle = pangoSanitize
, ppCurrent = pangoColor "green" . wrap "[" "]" . pangoSanitize
, ppVisible = pangoColor "yellow" . wrap "(" ")" . pangoSanitize
, ppHidden = const ""
, ppUrgent = pangoColor "red"
, ppLayout = const ""
, ppSep = " "
}
getWellKnownName :: Connection -> IO ()
getWellKnownName dbus = tryGetName `catchDyn` (\(DBus.Error _ _) -> getWellKnownName dbus)
where
tryGetName = do
namereq <- newMethodCall serviceDBus pathDBus interfaceDBus "RequestName"
addArgs namereq [String "org.xmonad.Log", Word32 5]
sendWithReplyAndBlock dbus namereq 0
return ()
dbusOutput :: Connection -> String -> IO ()
dbusOutput dbus str = do
msg <- newSignal "/org/xmonad/Log" "org.xmonad.Log" "Update"
addArgs msg [String ("<b>" ++ str ++ "</b>")]
-- If the send fails, ignore it.
send dbus msg 0 `catchDyn` (\(DBus.Error _ _) -> return 0)
return ()
pangoColor :: String -> String -> String
pangoColor fg = wrap left right
where
left = "<span foreground=\"" ++ fg ++ "\">"
right = "</span>"
pangoSanitize :: String -> String
pangoSanitize = foldr sanitize ""
where
sanitize '>' xs = ">" ++ xs
sanitize '<' xs = "<" ++ xs
sanitize '\"' xs = """ ++ xs
sanitize '&' xs = "&" ++ xs
sanitize x xs = x:xs
| theeternalsw0rd/ports-2012 | x11-misc/xmonad-log-applet/files/xmonad.hs | gpl-2.0 | 1,801 | 0 | 14 | 441 | 562 | 287 | 275 | 46 | 5 |
module Recursive2 where
-- source functions
f1 :: Int -> [a] -> [a]
f1 _ [] = []
f1 0 xs = []
f1 n (x:xs) = x : (f1 (n-1) xs)
f2 :: Int -> [a] -> [a]
f2 _ [] = []
f2 0 xs = xs
f2 n (x:xs) = f2 (n-1) xs
f3 :: Int -> Int
f3 42 = 56 | mpickering/HaRe | old/testing/merging/Recursive2_TokOut.hs | bsd-3-clause | 232 | 0 | 9 | 67 | 175 | 94 | 81 | 11 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.ForeignPtr.Safe
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- The 'ForeignPtr' type and operations. This module is part of the
-- Foreign Function Interface (FFI) and will usually be imported via
-- the "Foreign" module.
--
-- Safe API Only.
--
-----------------------------------------------------------------------------
module Foreign.ForeignPtr.Safe (
-- * Finalised data pointers
ForeignPtr
, FinalizerPtr
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, FinalizerEnvPtr
#endif
-- ** Basic operations
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
#endif
, withForeignPtr
#ifdef __GLASGOW_HASKELL__
, finalizeForeignPtr
#endif
-- ** Low-level operations
, touchForeignPtr
, castForeignPtr
-- ** Allocating managed memory
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
) where
import Foreign.ForeignPtr.Imp
| jtojnar/haste-compiler | libraries/ghc-7.8/base/Foreign/ForeignPtr/Safe.hs | bsd-3-clause | 1,501 | 0 | 4 | 345 | 92 | 71 | 21 | 16 | 0 |
{-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-overlapping-patterns #-}
module PMC006 where
len :: [a] -> Int
len xs = case xs of
[] -> 0
(_:ys) -> case () of
() | (_:_) <- xs -> 1 + len ys
-- -- we would like these to work too but they don't yet
--
-- len :: [a] -> Int
-- len [] = 0
-- len xs = case xs of
-- (_:ys) -> 1 + len ys
--
-- len :: [a] -> Int
-- len xs = case xs of
-- [] -> 0
-- ys -> case ys of
-- (_:zs) -> 1 + len zs
| olsner/ghc | testsuite/tests/pmcheck/should_compile/pmc006.hs | bsd-3-clause | 541 | 0 | 16 | 211 | 100 | 58 | 42 | 7 | 2 |
module T3303 where
import T3303A
bar :: Int
bar = foo
bar2 :: Int
bar2 = foo2
| sdiehl/ghc | testsuite/tests/parser/should_compile/T3303.hs | bsd-3-clause | 82 | 0 | 4 | 21 | 27 | 17 | 10 | 6 | 1 |
{-# LANGUAGE GADTs #-}
module Handler.People
( people
) where
import Model
import Handler.Helpers
import View.People
people :: App Response
people = routeResource $ defaultActions {
resActionList = peopleList
, resActionNew = peopleNew
, resActionEdit = peopleEdit
, resActionShow = peopleShow
, resActionCreate = peopleCreate
, resActionUpdate = peopleUpdate
}
peopleRes :: Resource Person
peopleRes = defaultResource {
resNewView = peopleNewView
, resEditView = peopleEditView
, resIndexUri = "/people"
}
peopleList :: App Response
peopleList = do
people <- runDB $ selectList [] [] :: App [Entity Person]
personViews <- runDB $
loadAssociations people $
PersonView
<$> own id
ok $ toResponse $ peopleListView personViews
peopleNew :: App Response
peopleNew = do
view <- getForm "person" (personForm Nothing)
ok $ toResponse $ peopleNewView view
peopleEdit :: Entity Person -> App Response
peopleEdit ent@(Entity key person) = do
view <- getForm "person" (personForm (Just person))
ok $ toResponse $ peopleEditView ent view
peopleShow :: Entity Person -> App Response
peopleShow ent@(Entity key person) = do
applications <- runDB $ selectList [ApplicationPersonId ==. key] []
membership <- runDB $ getBy (MemberId key)
ok $ toResponse $ peopleShowView ent applications membership
peopleCreate :: App Response
peopleCreate = do
post <- runForm "person" (personForm Nothing)
handleCreate peopleRes post
peopleUpdate :: Entity Person -> App Response
peopleUpdate ent@(Entity key person) = do
post <- runForm "person" (personForm (Just person))
handleUpdate peopleRes ent post
personForm :: Monad m => Formlet Text m Person
personForm p = Person
<$> "firstName" .: validate notEmpty (string (personFirstName <$> p))
<*> "lastName" .: validate notEmpty (string (personLastName <$> p))
| flipstone/glados | src/Handler/People.hs | mit | 1,872 | 0 | 12 | 349 | 599 | 300 | 299 | 52 | 1 |
module Language.Jass.Runtime.Natives(
callNativeBinder
) where
import Language.Jass.JIT.Calling
import Language.Jass.JIT.Module
import LLVM.General.AST as LLVMAST
import Control.Monad.Trans.Except
import Foreign.Ptr
type NativeBinder = FunPtr () -> IO ()
foreign import ccall "dynamic"
mkNativeBinder :: FunPtr NativeBinder -> NativeBinder
callNativeBinder :: JITModule -> LLVMAST.Name -> FunPtr () -> ExceptT String IO ()
callNativeBinder ex (LLVMAST.Name nativeName) = callFunc1 ex nativeName mkNativeBinder
callNativeBinder ex (LLVMAST.UnName i) = callFunc1 ex (show i) mkNativeBinder | NCrashed/hjass | src/library/Language/Jass/Runtime/Natives.hs | mit | 598 | 0 | 9 | 77 | 175 | 96 | 79 | 13 | 1 |
module GridLand
( Config(..)
, Color(..)
, Stretch(..)
, ColorFilter(..)
, Angle(..)
, Backdrop(..)
, Input(..)
, Key(..)
, KeyState(..)
, Location(..)
, ToSprite(..)
, BackdropImage
, Sprite
, Sfx
, Music
, GridLand
, titleBar
, loadSprite
, loadSpriteStretch
, loadBackdropImage
, loadBackdropImageStretch
, drawSpriteFront
, drawSpriteMiddle
, drawSpriteBack
, loadMusic
, playMusic
, stopMusic
, stopAllMusic
, loadSfx
, playSfx
, print'
, putStrLn'
, runGridLand
, backdrop
, getData
, putData
, modifyData
, getPlayingMusic
, io
, getInputs
, getMousePosition
) where
import qualified Graphics.UI.SDL as SDL
import qualified Graphics.UI.SDL.Video as SDL
import qualified Graphics.UI.SDL.Image as Image
-- import qualified Graphics.UI.SDL.TTF as TTF
import qualified Graphics.UI.SDL.Mixer as Mixer
import qualified Graphics.UI.SDL.Framerate as Gfx
import qualified Graphics.UI.SDL.Primitives as Gfx
import qualified Graphics.UI.SDL.Rotozoomer as Gfx
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Math.Geometry.Grid as Grid
import qualified Data.Vector as V
import qualified Control.Monad.State as State
import qualified Control.Monad.RWS as RWS
import qualified Data.Array as Array
import qualified Safe as Safe
import Debug.Trace
import Data.IORef
import Data.Char
import Data.Maybe
import Control.Arrow
import System.Environment
import GridLand.Import
import GridLand.Data
import GridLand.SDL
import GridLand.Color
newTodo :: Todo
newTodo = Todo Map.empty Map.empty Map.empty (BkdColor White)
getData :: GridLand a a
getData = RWS.gets snd
putData :: a -> GridLand a ()
putData a = RWS.modify . second $ const a
modifyData :: (a -> a) -> GridLand a ()
modifyData f = RWS.modify . second $ f
spriteDegrees :: [Int]
spriteDegrees = [ rot * 360 `div` rotations | rot <- [0 .. (rotations - 1)]]
spriteOpts :: [(ColorFilter, Int)]
spriteOpts = noFilters ++ filters
where
noFilters = [(NoFilter, theta) | theta <- spriteDegrees]
filters = [(cf c, theta) | cf <- [Tint, Replace], c <- [minBound..maxBound], theta <- spriteDegrees]
loadSpriteStretch :: FilePath -> Stretch -> GridLand a Sprite
loadSpriteStretch rawPath stretch = do
path <- correctPath rawPath
base <- liftIO $ Image.load path >>= SDL.displayFormat >>= setColorKey (0xff,0x00,0xff)
let (w,h) = (SDL.surfaceGetWidth base, SDL.surfaceGetHeight base)
let side = max w h
ts <- RWS.asks tileSize
let zoom = (fromIntegral ts) / (fromIntegral side)
fmt <- io (surfacePixelFormat base)
let blitter = blit stretch base zoom
frames <- liftIO $ mapM (\(cf, theta) -> blitter (mapFilterColor fmt cf) theta) spriteOpts
liftIO $ SDL.freeSurface base
let spriteFrames = V.fromListN totalFrames frames
key <- RWS.gets (Map.size . sprites . fst)
let spr = Sprite key
RWS.modify . first $ \s -> s { sprites = Map.insert spr spriteFrames (sprites s) }
return spr
blit
:: Stretch
-> SDL.Surface
-> Double
-> (Word32 -> SDL.Pixel)
-> Int
-> IO SDL.Surface
blit stretch base zoom toPixel theta = do
rotozoom <- Gfx.rotozoom base (fromIntegral theta) zoom (stretch == Smooth)
ping <- SDL.displayFormat rotozoom >>= setColorKey (0xff, 0x00, 0xff)
pong <- setColorKey (0xff, 0x00, 0xff) rotozoom
let (w,h) = (SDL.surfaceGetWidth rotozoom, SDL.surfaceGetHeight rotozoom)
let fmt = SDL.surfaceGetPixelFormat rotozoom
forM_ ([(x,y) | x <- [0 .. w - 1], y <- [0 .. h - 1]]) $ \(x,y) -> do
(SDL.Pixel v) <- getPixel32 x y ping
putPixel32 x y (toPixel v) pong
SDL.freeSurface ping
return pong
mapFilterColor :: PixelFormat -> ColorFilter -> Word32 -> SDL.Pixel
mapFilterColor RGBA = filterColorRGBA
mapFilterColor BGRA = filterColorBGRA
mapFilterColor ARGB = filterColorARGB
mapFilterColor ABGR = filterColorABGR
filterColorABGR :: ColorFilter -> Word32 -> SDL.Pixel
filterColorABGR = mkFilterColor toColorABGR fromColorABGR 0xff000000
filterColorARGB :: ColorFilter -> Word32 -> SDL.Pixel
filterColorARGB = mkFilterColor toColorARGB fromColorARGB 0xff000000
filterColorRGBA :: ColorFilter -> Word32 -> SDL.Pixel
filterColorRGBA = mkFilterColor toColorRGBA fromColorRGBA 0x000000ff
filterColorBGRA :: ColorFilter -> Word32 -> SDL.Pixel
filterColorBGRA = mkFilterColor toColorBGRA fromColorBGRA 0x000000ff
mkFilterColor
:: (Word8 -> Word8 -> Word8 -> Word32)
-> (Word32 -> (Word8, Word8, Word8))
-> Word32
-> ColorFilter
-> Word32
-> SDL.Pixel
mkFilterColor toColor fromColor transMask = let
magenta = toColor 0xff 0x00 0xff
white = toColor 0xff 0xff 0xff
trans = xor magenta transMask
in filterColor toColor fromColor white magenta trans
filterColor
:: (Word8 -> Word8 -> Word8 -> Word32)
-> (Word32 -> (Word8, Word8, Word8))
-> Word32
-> Word32
-> Word32
-> ColorFilter
-> Word32
-> SDL.Pixel
filterColor _ _ _ _ _ NoFilter v = SDL.Pixel v
filterColor toColor fromColor white magenta trans (Tint color) v = let
(cr, cg, cb) = fromColor v
(tr, tg, tb) = colorValue color
(r, g, b) = (shiftR tr 1 + shiftR cr 1, shiftR tg 1 + shiftR cg 1, shiftR tb 1 + shiftR cb 1)
tinted = toColor r g b
in SDL.Pixel $ if magenta == toColor cr cg cb .&. white
then trans
else tinted
filterColor toColor fromColor white magenta trans (Replace color) v = let
(cr, cg, cb) = fromColor v
(r, g, b) = colorValue color
p = toColor r g b
in SDL.Pixel $ if magenta == (toColor cr cg cb) .&. white
then trans
else p
-- This is a necessary hack because the SDL bindings are insufficient
correctPath :: FilePath -> GridLand a FilePath
correctPath "" = RWS.gets (pathPrefix . fst)
correctPath path =
if head path == '/'
then return path
else do
prefix <- RWS.gets (pathPrefix . fst)
return $ prefix ++ path
loadSprite :: FilePath -> GridLand a Sprite
loadSprite path = loadSpriteStretch path Pixelated
loadBackdropImageStretch :: FilePath -> Stretch -> GridLand a Backdrop
loadBackdropImageStretch rawPath stretch = do
path <- correctPath rawPath
base <- liftIO $ Image.load path
scr <- RWS.asks screen
let (scrW,scrH) = (SDL.surfaceGetWidth scr, SDL.surfaceGetHeight scr)
let (w,h) = (SDL.surfaceGetWidth base, SDL.surfaceGetHeight base)
let (zoomW, zoomH) = (fromIntegral scrW / fromIntegral w, fromIntegral scrH / fromIntegral h)
zoomed <- liftIO $ Gfx.zoom base zoomW zoomH (stretch == Smooth)
key <- RWS.gets (Map.size . bkdImages . fst)
let bi = BackdropImage key
RWS.modify . first $ \s -> s { bkdImages = Map.insert bi zoomed (bkdImages s) }
liftIO $ SDL.freeSurface base
return (BkdImage bi)
loadBackdropImage :: FilePath -> GridLand a Backdrop
loadBackdropImage path = loadBackdropImageStretch path Smooth
pollEvents :: IO [SDL.Event]
pollEvents = do
event <- SDL.pollEvent
if event == SDL.NoEvent
then return []
else (:) <$> return event <*> pollEvents
toMousePosition :: Foundation -> (Word16, Word16) -> Location
toMousePosition Foundation{..} (x,y) = Location {
locX = fromIntegral x `div` tileSize,
locY = fromIntegral y `div` tileSize
}
pollInputs :: Foundation -> IO ([Input], Maybe Location)
pollInputs foundation = do
events <- pollEvents
return (foldr cvt [] events, mousePos events)
where
mousePos = Safe.headMay . catMaybes . map mpos
mpos (SDL.MouseMotion x y _ _) = let
pos = toMousePosition foundation (x,y)
in if inRange foundation pos
then Just pos
else Nothing
mpos _ = Nothing
-- Quit
cvt SDL.Quit inputs = Quit : inputs
cvt (SDL.KeyDown (SDL.Keysym keysym _ ch)) inputs = case keysym of
SDL.SDLK_ESCAPE -> Quit : inputs
-- Key (pressed)
SDL.SDLK_UP -> pressed UpArrow : inputs
SDL.SDLK_DOWN -> pressed DownArrow : inputs
SDL.SDLK_LEFT -> pressed LeftArrow : inputs
SDL.SDLK_RIGHT -> pressed RightArrow : inputs
SDL.SDLK_RETURN -> pressed Enter : inputs
SDL.SDLK_LSHIFT -> pressed Shift : inputs
SDL.SDLK_RSHIFT -> pressed Shift : inputs
SDL.SDLK_LCTRL -> pressed Ctrl : inputs
SDL.SDLK_RCTRL -> pressed Ctrl : inputs
SDL.SDLK_LALT -> pressed AltKey : inputs
SDL.SDLK_RALT -> pressed AltKey : inputs
SDL.SDLK_TAB-> pressed Tab : inputs
SDL.SDLK_BACKSPACE -> pressed Backspace : inputs
SDL.SDLK_LSUPER -> pressed Meta : inputs
SDL.SDLK_RSUPER -> pressed Meta : inputs
key ->
if (key >= SDL.SDLK_SPACE && key <= SDL.SDLK_z)
then pressed (Char $ toLower ch) : inputs
else inputs -- ignore
-- Key (released)
cvt (SDL.KeyUp (SDL.Keysym keysym _ ch)) inputs = case keysym of
SDL.SDLK_UP -> released UpArrow : inputs
SDL.SDLK_DOWN -> released DownArrow : inputs
SDL.SDLK_LEFT -> released LeftArrow : inputs
SDL.SDLK_RIGHT -> released RightArrow : inputs
SDL.SDLK_RETURN -> released Enter : inputs
SDL.SDLK_LSHIFT -> released Shift : inputs
SDL.SDLK_RSHIFT -> released Shift : inputs
SDL.SDLK_LCTRL -> released Ctrl : inputs
SDL.SDLK_RCTRL -> released Ctrl : inputs
SDL.SDLK_LALT -> released AltKey : inputs
SDL.SDLK_RALT -> released AltKey : inputs
SDL.SDLK_TAB-> released Tab : inputs
SDL.SDLK_BACKSPACE -> released Backspace : inputs
SDL.SDLK_LSUPER -> released Meta : inputs
SDL.SDLK_RSUPER -> released Meta : inputs
key ->
if (key >= SDL.SDLK_SPACE && key <= SDL.SDLK_z)
then released (Char $ toLower ch) : inputs
else inputs -- ignore
-- Click
cvt (SDL.MouseButtonDown x y SDL.ButtonLeft) inputs = Click Location{ locX = fromIntegral x, locY = fromIntegral y } : inputs
-- Ignore the rest
cvt _ inputs = inputs
mergeInputs :: [Input] -> [Input] -> [Input]
mergeInputs old new = new
stepInputs :: [Input] -> [Input]
stepInputs = foldr step []
where
held key = Key key Held
step inp inps = case inp of
Key key Pressed -> held key : inps
Key key Released -> inps
_ -> inp : inps
getInputs :: GridLand a [Input]
getInputs = State.gets (inputs . fst)
getMousePosition :: GridLand a Location
getMousePosition = State.gets (mousePosition . fst)
pressed :: Key -> Input
pressed = flip Key Pressed
released :: Key -> Input
released = flip Key Released
rotations, colors, withoutColors, withColors, totalFrames, colorAngleInterval:: Int
rotations = 36
colors = 1 + fromEnum (maxBound :: Color)
withColors = 2
withoutColors = 1
totalFrames = (withoutColors + withColors * colors) * rotations
colorAngleInterval = colors * rotations
colorAngleOffset :: Color -> Angle -> Int
colorAngleOffset c t = colorOffset c + angleOffset t
angleOffset :: Angle -> Int
angleOffset (Radians r) = angleOffset $ Degrees (round $ 180 * r / pi)
angleOffset (Degrees d) = ((d `mod` 360) * rotations `div` 360)
colorOffset :: Color -> Int
colorOffset c = fromEnum c * rotations
frameOffset :: ColorFilter -> Angle -> Int
frameOffset NoFilter theta = angleOffset theta
frameOffset (Tint c) theta = rotations + colorAngleOffset c theta
frameOffset (Replace c) theta = rotations + colorAngleInterval + colorAngleOffset c theta
spriteGfx :: Sprite -> ColorFilter -> Location -> Angle -> GridLand a Gfx
spriteGfx spr cf loc theta = do
let offset = frameOffset cf theta
sprMap <- RWS.gets (sprites . fst)
let sur = (sprMap Map.! spr) V.! offset
return $ Gfx sur loc
gfxRect :: Int -> Location -> SDL.Surface -> SDL.Rect
gfxRect ts Location{..} sur = let
(w, h) = (SDL.surfaceGetWidth sur, SDL.surfaceGetHeight sur)
in SDL.Rect (ts * locX) (ts * locY) ts ts
drawSpriteMapFront :: ToSprite s => Map Location s -> GridLand a ()
drawSpriteMapFront sprMap = do
return ()
drawSpriteFront :: ToSprite s => s -> ColorFilter -> Location -> Angle -> GridLand a ()
drawSpriteFront a cf loc theta = do
gfx <- spriteGfx (toSprite a) cf loc theta
RWS.tell $ mempty { todoFrontSprites = Map.singleton loc gfx }
drawSpriteMiddle :: ToSprite s => s -> ColorFilter -> Location -> Angle -> GridLand a ()
drawSpriteMiddle a cf loc theta = do
gfx <- spriteGfx (toSprite a) cf loc theta
RWS.tell $ mempty { todoMiddleSprites = Map.singleton loc gfx }
drawSpriteBack :: ToSprite s => s -> ColorFilter -> Location -> Angle -> GridLand a ()
drawSpriteBack a cf loc theta = do
gfx <- spriteGfx (toSprite a) cf loc theta
RWS.tell $ mempty { todoBackSprites = Map.singleton loc gfx }
drawSprite :: ToSprite s => s -> ColorFilter -> Location -> Angle -> GridLand a ()
drawSprite a cf loc theta = do
(s, ts) <- RWS.asks (screen &&& tileSize)
Gfx{..} <- spriteGfx (toSprite a) cf loc theta
let (w, h) = (SDL.surfaceGetWidth gfxSurface, SDL.surfaceGetHeight gfxSurface)
let tileRect = Just $ SDL.Rect ((w - ts) `div` 2) ((h - ts) `div` 2) ts ts
void . liftIO $ SDL.blitSurface gfxSurface tileRect s (Just $ gfxRect ts gfxLocation gfxSurface)
drawGfx :: SDL.Surface -> Int -> Gfx -> IO ()
drawGfx scr ts Gfx{..} = do
let (w, h) = (SDL.surfaceGetWidth gfxSurface, SDL.surfaceGetHeight gfxSurface)
let tileRect = Just $ SDL.Rect ((w - ts) `div` 2) ((h - ts) `div` 2) ts ts
void $ SDL.blitSurface gfxSurface tileRect scr (Just $ gfxRect ts gfxLocation gfxSurface)
loadMusic :: FilePath -> GridLand a Music
loadMusic rawPath = do
path <- correctPath rawPath
mus <- liftIO $ Mixer.loadMUS path
key <- RWS.gets (Map.size . musics . fst)
let music = Music key
RWS.modify . first $ \s -> s { musics = Map.insert music mus (musics s) }
return music
playMusic :: Music -> Maybe Int -> GridLand a ()
playMusic music mloops = do
mus <- RWS.gets ((Map.! music) . musics . fst)
let loops = maybe (-1) (\n -> if n < -1 then 0 else n) mloops
liftIO $ Mixer.playMusic mus loops
RWS.modify . first $ (\s -> s { playingMusic = Just music } )
stopMusic :: Music -> GridLand a ()
stopMusic music = do
mplaying <- RWS.gets (playingMusic . fst)
case mplaying of
Nothing -> return ()
Just currMusic -> do
when (music == currMusic) $ do
liftIO Mixer.haltMusic
RWS.modify . first $ (\s -> s { playingMusic = Nothing } )
stopAllMusic :: GridLand a ()
stopAllMusic = do
liftIO Mixer.haltMusic
RWS.modify . first $ (\s -> s { playingMusic = Nothing } )
getPlayingMusic :: GridLand a (Maybe Music)
getPlayingMusic = RWS.gets (playingMusic . fst)
establishPlayingMusic :: GridLand a ()
establishPlayingMusic = do
isPlaying <- liftIO Mixer.playingMusic
unless isPlaying $ RWS.modify . first $ (\s -> s { playingMusic = Nothing } )
loadSfx :: FilePath -> GridLand a Sfx
loadSfx rawPath = do
path <- correctPath rawPath
sfxRef <- liftIO $ Mixer.loadWAV path
key <- RWS.gets (Map.size . sfxs . fst)
let sfx = Sfx key
RWS.modify . first $ \s -> s { sfxs = Map.insert sfx sfxRef (sfxs s) }
return sfx
playSfx :: Sfx -> GridLand a ()
playSfx sfx = do
chunk <- RWS.gets ((Map.! sfx) . sfxs . fst)
chan <- RWS.gets (currSfxChan . fst)
void . liftIO $ Mixer.playChannel chan chunk 0
RWS.modify . first $ \s -> s { currSfxChan = mod (chan + 1) sfxChannels }
sfxChannels :: Int
sfxChannels = 16
-- | Config -> Start -> Update -> End -> IO ()
runGridLand :: Config -> GridLand () a -> GridLand a () -> GridLand a () -> IO ()
runGridLand cfg onStart onUpdate onEnd = do
execPath <- getExecutablePath
progName <- getProgName
let pathPrefix = take (length execPath - length progName) execPath
foundation@Foundation{..} <- start cfg
let common = newCommon { pathPrefix = pathPrefix }
(initUserData, (initCommon,_), _) <- RWS.runRWST (unGridLand onStart) foundation (common, ())
let initState = (initCommon, initUserData)
let update = establishPlayingMusic >> onUpdate >> drawBackdrop
let dgfx = drawGfx screen tileSize
endState <- ($ initState) $ fix $ \loop state -> do
startTick <- SDL.getTicks
let inps = (inputs . fst) state
let pos = (mousePosition . fst) state
(inps', mpos) <- first (mergeInputs (stepInputs inps)) <$> pollInputs foundation
let state' = first (\s -> s {
inputs = inps',
mousePosition = fromMaybe (mousePosition s) mpos
}) state
(continue, state'', todo) <- RWS.runRWST (unGridLand update) foundation state'
let ranger loc _ = inRange foundation loc
mapM_ dgfx (Map.elems . Map.filterWithKey ranger $ todoBackSprites todo)
mapM_ dgfx (Map.elems . Map.filterWithKey ranger $ todoMiddleSprites todo)
mapM_ dgfx (Map.elems . Map.filterWithKey ranger $ todoFrontSprites todo)
liftIO $ SDL.flip screen
endTick <- SDL.getTicks
let diff = endTick - startTick
when (diff < 16) (SDL.delay $ 16 - diff)
if elem Quit inps'
then return state''
else loop state''
void $ RWS.execRWST (unGridLand onEnd) foundation endState
end foundation common
inRange :: Foundation -> Location -> Bool
inRange Foundation{..} Location{..} = locX >= 0 && locY >= 0 && locX < cols && locY < rows
start :: Config -> IO Foundation
start Config{..} = do
SDL.init [SDL.InitEverything]
screen <- SDL.setVideoMode (cfgCols * cfgTileSize) (cfgRows * cfgTileSize) 32 [SDL.SWSurface]
SDL.setCaption "Grid Land" ""
SDL.enableUnicode True
colorMap <- getColorMap screen
-- ttfOk <- TTF.init
Mixer.openAudio 22050 Mixer.AudioS16Sys 2 4096
Mixer.allocateChannels sfxChannels
return $ Foundation screen colorMap cfgRows cfgCols cfgTileSize
getColorMap :: SDL.Surface -> IO (Color -> SDL.Pixel)
getColorMap s = do
let fmt = SDL.surfaceGetPixelFormat s
pixels <- forM [minBound..maxBound] (\c -> liftIO $ colorValueCurry c (SDL.mapRGB fmt))
let table = V.fromList pixels
return $ \c -> table V.! (fromEnum c)
newCommon :: Common
newCommon = Common Map.empty Map.empty Map.empty Map.empty (BkdColor White) Nothing [] (Location 0 0) 0 ""
end :: Foundation -> Common -> IO ()
end Foundation{..} Common{..} = do
mapM_ SDL.freeSurface (Map.elems bkdImages)
mapM_ (mapM_ SDL.freeSurface . V.toList) (Map.elems sprites)
mapM_ Mixer.freeMusic (Map.elems musics)
mapM_ (const $ return ()) (Map.elems sfxs) -- Mixer.freeChunks is missing its binding
SDL.freeSurface screen
Mixer.closeAudio
-- TTF.quit
SDL.quit
putStrLn' :: String -> GridLand a ()
putStrLn' = liftIO . putStrLn
print' :: Show b => b -> GridLand a ()
print' = liftIO . print
titleBar :: String -> GridLand a ()
titleBar title = liftIO $ SDL.setCaption title ""
backdrop :: Backdrop -> GridLand a ()
backdrop b = RWS.modify . first $ \s -> s { currBkd = b }
drawBackdrop :: GridLand a ()
drawBackdrop = do
(s, cmap) <- RWS.asks (screen &&& colorMap)
b <- RWS.gets (currBkd . fst)
case b of
BkdColor c -> void . liftIO $ SDL.fillRect s Nothing (cmap c)
BkdImage bi -> do
img <- RWS.gets ((Map.! bi) . bkdImages . fst)
void . liftIO $ SDL.blitSurface img Nothing s Nothing
io :: IO b -> GridLand a b
io = liftIO
| jxv/gridland | src/GridLand.hs | mit | 19,524 | 0 | 22 | 4,577 | 7,164 | 3,641 | 3,523 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGAngle
(js_newValueSpecifiedUnits, newValueSpecifiedUnits,
js_convertToSpecifiedUnits, convertToSpecifiedUnits,
pattern SVG_ANGLETYPE_UNKNOWN, pattern SVG_ANGLETYPE_UNSPECIFIED,
pattern SVG_ANGLETYPE_DEG, pattern SVG_ANGLETYPE_RAD,
pattern SVG_ANGLETYPE_GRAD, js_getUnitType, getUnitType,
js_setValue, setValue, js_getValue, getValue,
js_setValueInSpecifiedUnits, setValueInSpecifiedUnits,
js_getValueInSpecifiedUnits, getValueInSpecifiedUnits,
js_setValueAsString, setValueAsString, js_getValueAsString,
getValueAsString, SVGAngle, castToSVGAngle, gTypeSVGAngle)
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
foreign import javascript unsafe
"$1[\"newValueSpecifiedUnits\"]($2,\n$3)" js_newValueSpecifiedUnits
:: SVGAngle -> Word -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.newValueSpecifiedUnits Mozilla SVGAngle.newValueSpecifiedUnits documentation>
newValueSpecifiedUnits ::
(MonadIO m) => SVGAngle -> Word -> Float -> m ()
newValueSpecifiedUnits self unitType valueInSpecifiedUnits
= liftIO
(js_newValueSpecifiedUnits (self) unitType valueInSpecifiedUnits)
foreign import javascript unsafe
"$1[\"convertToSpecifiedUnits\"]($2)" js_convertToSpecifiedUnits ::
SVGAngle -> Word -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.convertToSpecifiedUnits Mozilla SVGAngle.convertToSpecifiedUnits documentation>
convertToSpecifiedUnits :: (MonadIO m) => SVGAngle -> Word -> m ()
convertToSpecifiedUnits self unitType
= liftIO (js_convertToSpecifiedUnits (self) unitType)
pattern SVG_ANGLETYPE_UNKNOWN = 0
pattern SVG_ANGLETYPE_UNSPECIFIED = 1
pattern SVG_ANGLETYPE_DEG = 2
pattern SVG_ANGLETYPE_RAD = 3
pattern SVG_ANGLETYPE_GRAD = 4
foreign import javascript unsafe "$1[\"unitType\"]" js_getUnitType
:: SVGAngle -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.unitType Mozilla SVGAngle.unitType documentation>
getUnitType :: (MonadIO m) => SVGAngle -> m Word
getUnitType self = liftIO (js_getUnitType (self))
foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue
:: SVGAngle -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.value Mozilla SVGAngle.value documentation>
setValue :: (MonadIO m) => SVGAngle -> Float -> m ()
setValue self val = liftIO (js_setValue (self) val)
foreign import javascript unsafe "$1[\"value\"]" js_getValue ::
SVGAngle -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.value Mozilla SVGAngle.value documentation>
getValue :: (MonadIO m) => SVGAngle -> m Float
getValue self = liftIO (js_getValue (self))
foreign import javascript unsafe
"$1[\"valueInSpecifiedUnits\"] = $2;" js_setValueInSpecifiedUnits
:: SVGAngle -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.valueInSpecifiedUnits Mozilla SVGAngle.valueInSpecifiedUnits documentation>
setValueInSpecifiedUnits ::
(MonadIO m) => SVGAngle -> Float -> m ()
setValueInSpecifiedUnits self val
= liftIO (js_setValueInSpecifiedUnits (self) val)
foreign import javascript unsafe "$1[\"valueInSpecifiedUnits\"]"
js_getValueInSpecifiedUnits :: SVGAngle -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.valueInSpecifiedUnits Mozilla SVGAngle.valueInSpecifiedUnits documentation>
getValueInSpecifiedUnits :: (MonadIO m) => SVGAngle -> m Float
getValueInSpecifiedUnits self
= liftIO (js_getValueInSpecifiedUnits (self))
foreign import javascript unsafe "$1[\"valueAsString\"] = $2;"
js_setValueAsString :: SVGAngle -> Nullable JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.valueAsString Mozilla SVGAngle.valueAsString documentation>
setValueAsString ::
(MonadIO m, ToJSString val) => SVGAngle -> Maybe val -> m ()
setValueAsString self val
= liftIO (js_setValueAsString (self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"valueAsString\"]"
js_getValueAsString :: SVGAngle -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAngle.valueAsString Mozilla SVGAngle.valueAsString documentation>
getValueAsString ::
(MonadIO m, FromJSString result) => SVGAngle -> m (Maybe result)
getValueAsString self
= liftIO (fromMaybeJSString <$> (js_getValueAsString (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGAngle.hs | mit | 5,366 | 66 | 10 | 786 | 1,110 | 624 | 486 | 81 | 1 |
module GHCJS.DOM.DelayNode (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/DelayNode.hs | mit | 39 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
myLength :: [a] -> Int
myLength = foldr (\ _ x -> 1 + x) 0
| tamasgal/haskell_exercises | 99questions/Problem04.hs | mit | 59 | 0 | 8 | 16 | 37 | 20 | 17 | 2 | 1 |
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Time.Units (Second)
import Data.Yaml (decodeEither')
import Database.Persist.Postgresql (PostgresConf(..))
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.AWS.S3 (BucketName(..))
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
import Web.Heroku.Postgres (parseDatabaseUrl)
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: PostgresConf
-- ^ Configuration settings for accessing the database.
, appDatabasePoolSize :: Int
-- ^ Database pool size
, appRoot :: Text
-- ^ Base for all generated URLs.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appCommandTimeout :: Second
-- ^ How long to consider a command no longer running in seconds
, appS3Bucket :: BucketName
-- ^ S3 bucket to archive commands to
, appDebug :: Bool
-- ^ Should logging occur at the DEBUG level (otherwise INFO)
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
}
deriving Show
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabasePoolSize <- o .: "database-pool-size"
appDatabaseConf <- fromDatabaseUrl appDatabasePoolSize <$> o .: "database-url"
appRoot <- o .: "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appCommandTimeout <- toSecond <$> o .: "command-timeout"
appS3Bucket <- BucketName <$> o .: "s3-bucket"
appDebug <- o .: "debug"
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
return AppSettings {..}
where
fromDatabaseUrl :: Int -> String -> PostgresConf
fromDatabaseUrl poolSize url = PostgresConf
{ pgConnStr = formatParams $ parseDatabaseUrl url
, pgPoolSize = poolSize
}
formatParams :: [(Text, Text)] -> ByteString
formatParams = encodeUtf8 . unwords . map toKeyValue
toKeyValue :: (Text, Text) -> Text
toKeyValue (k, v) = k <> "=" <> v
toSecond :: Integer -> Second
toSecond = fromIntegral
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
| mrb/tee-io | src/Settings.hs | mit | 6,049 | 0 | 13 | 1,673 | 879 | 505 | 374 | -1 | -1 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
module DSL where
import Numeric.AD
data Exp a
= Const a
| Neg (Exp a)
| (Exp a) :+: (Exp a)
| (Exp a) :*: (Exp a)
deriving (Functor, Foldable, Traversable)
instance Num a => Num (Exp a) where
(+) = (:+:)
(*) = (:*:)
fromInteger = Const . fromInteger
negate = Neg
eval :: Num a => Exp a -> a
eval (Const a) = a
eval (Neg e) = negate (eval e)
eval (e1 :+: e2) = eval e1 + eval e2
eval (e1 :*: e2) = eval e1 * eval e2
| vladfi1/hs-misc | DSL.hs | mit | 506 | 0 | 8 | 125 | 243 | 130 | 113 | 19 | 1 |
module MoveTests where
import Chess.Internal.Piece
import Chess.Internal.Board
import Chess.Internal.Move
import TestUtils
import Test.Hspec
moveSpec :: IO ()
moveSpec = hspec $
describe "Move" $ do
isCorrectStartPieceSpec
isRightPlayerMoveSpec
areCoordinatesValidSpec
generateAllRookMovesSpec
generateAllBishopMovesSpec
generateAllQueenMovesSpec
generateAllKnightMovesSpec
generateAllKingMovesSpec
generateAllPawnMovesSpec
generateAllPotentialMovesSpec
boardAfterMoveSpec
generateAllMovesSpec
isCorrectStartPieceSpec :: Spec
isCorrectStartPieceSpec =
describe "isCorrectStartPiece" $
it "should detect whether the piece in the coordinates matches the given piece information" $ do
isCorrectStartPiece initialBoard (Piece White Pawn) (coord "e2") `shouldBe` True
isCorrectStartPiece initialBoard (Piece White Knight) (coord "b1") `shouldBe` True
isCorrectStartPiece initialBoard (Piece Black Pawn) (coord "e2") `shouldBe` False
isCorrectStartPiece initialBoard (Piece White Bishop) (coord "e2") `shouldBe` False
isCorrectStartPiece initialBoard (Piece White Pawn) (coord "e3") `shouldBe` False
isRightPlayerMoveSpec :: Spec
isRightPlayerMoveSpec =
describe "isRightPlayerMove" $
it "should detect whether the movement is by given player" $ do
isRightPlayerMove White (Movement (Piece White Pawn) (coord "e2") (coord "e3")) `shouldBe` True
isRightPlayerMove White (Movement (Piece Black Pawn) (coord "e7") (coord "e6")) `shouldBe` False
isRightPlayerMove Black (Capture (Piece Black Queen) (coord "a1") (coord "a2")) `shouldBe` True
isRightPlayerMove Black (Capture (Piece White Queen) (coord "a1") (coord "a2")) `shouldBe` False
isRightPlayerMove White (Castling White Short) `shouldBe` True
isRightPlayerMove Black (Castling White Long) `shouldBe` False
isRightPlayerMove White (EnPassant (Piece White Pawn) (coord "e2") (coord "d3")) `shouldBe` True
isRightPlayerMove Black (EnPassant (Piece White Pawn) (coord "e2") (coord "d3")) `shouldBe` False
isRightPlayerMove Black (Promotion (Piece Black Pawn) (coord "e2") (coord "e1") Queen) `shouldBe` True
isRightPlayerMove White (Promotion (Piece Black Pawn) (coord "e2") (coord "e1") Queen) `shouldBe` False
isRightPlayerMove White (PawnDoubleMove (Piece White Pawn) (coord "e2") (coord "e4")) `shouldBe` True
isRightPlayerMove Black (PawnDoubleMove (Piece White Pawn) (coord "e2") (coord "e4")) `shouldBe` False
areCoordinatesValidSpec :: Spec
areCoordinatesValidSpec =
describe "areCoordinatesValid" $ do
it "should return Nothing if both coordinates are inside bounds" $ do
areCoordinatesValid (0, 0) (1, 2) `shouldBe` Nothing
areCoordinatesValid (4, 4) (0, 7) `shouldBe` Nothing
it "should return InvalidCoordinates error if at least one coordinate is out of bounds" $ do
areCoordinatesValid (3, 3) (3, 3) `shouldBe` Just InvalidCoordinates
areCoordinatesValid (-1, 0) (3, 3) `shouldBe` Just InvalidCoordinates
areCoordinatesValid (7, 0) (7, 8) `shouldBe` Just InvalidCoordinates
generateAllRookMovesSpec :: Spec
generateAllRookMovesSpec =
describe "generateAllRookMoves" $ do
it "should return all movement and capture moves for a rook in a square" $
generateAllRookMoves (game "k4b1r/p7/7p/4P3/1n2P2R/8/P2B1P2/3K2N1 w - - 6 9") (coord "h4") `shouldMatchList`
[ Movement (Piece White Rook) (coord "h4") (coord "h5")
, Movement (Piece White Rook) (coord "h4") (coord "g4")
, Movement (Piece White Rook) (coord "h4") (coord "f4")
, Movement (Piece White Rook) (coord "h4") (coord "h3")
, Movement (Piece White Rook) (coord "h4") (coord "h2")
, Movement (Piece White Rook) (coord "h4") (coord "h1")
, Capture (Piece White Rook) (coord "h4") (coord "h6")]
it "should return empty list of moves if no move is possible" $
generateAllRookMoves (game "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") (coord "a1") `shouldMatchList` []
generateAllBishopMovesSpec :: Spec
generateAllBishopMovesSpec =
describe "generateAllBishopMoves" $ do
it "should return all movement and capture moves for a bishop in a square" $
generateAllBishopMoves (game "rnb1kbnr/pppp1ppp/8/5p2/8/3B4/PPPP3P/Rq1QKN2 w Qkq - 4 12") (coord "d3") `shouldMatchList`
[ Movement (Piece White Bishop) (coord "d3") (coord "c4")
, Movement (Piece White Bishop) (coord "d3") (coord "b5")
, Movement (Piece White Bishop) (coord "d3") (coord "a6")
, Movement (Piece White Bishop) (coord "d3") (coord "e4")
, Movement (Piece White Bishop) (coord "d3") (coord "e2")
, Capture (Piece White Bishop) (coord "d3") (coord "f5")]
it "should return empty list of moves if no move is possible" $
generateAllBishopMoves (game "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") (coord "c1") `shouldMatchList` []
generateAllQueenMovesSpec :: Spec
generateAllQueenMovesSpec =
describe "generateAllQueenMoves" $ do
it "should return all movement and capture moves for a queen in a square" $ do
generateAllQueenMoves (game "rnb1kbnr/pppp1ppp/8/5p2/8/3B4/PPPP3P/Rq1QKN2 b Qkq - 4 12") (coord "b1") `shouldMatchList`
[ Movement (Piece Black Queen) (coord "b1") (coord "c1")
, Capture (Piece Black Queen) (coord "b1") (coord "a1")
, Capture (Piece Black Queen) (coord "b1") (coord "a2")
, Capture (Piece Black Queen) (coord "b1") (coord "b2")
, Capture (Piece Black Queen) (coord "b1") (coord "c2")
, Capture (Piece Black Queen) (coord "b1") (coord "d1")]
generateAllQueenMoves (game "r2qkb1r/ppnp2pp/4pp1n/4b3/2Q2P2/1P2P3/1P2BPPP/RPB1K1NR w KQkq - 2 13") (coord "c4") `shouldMatchList`
[ Movement (Piece White Queen) (coord "c4") (coord "b5")
, Movement (Piece White Queen) (coord "c4") (coord "a6")
, Movement (Piece White Queen) (coord "c4") (coord "d5")
, Movement (Piece White Queen) (coord "c4") (coord "d3")
, Movement (Piece White Queen) (coord "c4") (coord "b4")
, Movement (Piece White Queen) (coord "c4") (coord "a4")
, Movement (Piece White Queen) (coord "c4") (coord "c5")
, Movement (Piece White Queen) (coord "c4") (coord "c6")
, Movement (Piece White Queen) (coord "c4") (coord "d4")
, Movement (Piece White Queen) (coord "c4") (coord "e4")
, Movement (Piece White Queen) (coord "c4") (coord "c3")
, Movement (Piece White Queen) (coord "c4") (coord "c2")
, Capture (Piece White Queen) (coord "c4") (coord "c7")
, Capture (Piece White Queen) (coord "c4") (coord "e6")]
it "should return empty list of moves if no move is possible" $
generateAllQueenMoves (game "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") (coord "d1") `shouldMatchList` []
generateAllKnightMovesSpec :: Spec
generateAllKnightMovesSpec =
describe "generateAllKnightMoves" $
it "should return all movement and capture moves for a knight in a square" $ do
generateAllKnightMoves (game "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") (coord "b1") `shouldMatchList`
[ Movement (Piece White Knight) (coord "b1") (coord "a3")
, Movement (Piece White Knight) (coord "b1") (coord "c3")]
generateAllKnightMoves (game "r2qkbnr/2p1pppp/ppp5/bn6/3P4/2P5/PP2PPPP/RNBQKBNR b - - 3 7") (coord "b5") `shouldMatchList`
[ Movement (Piece Black Knight) (coord "b5") (coord "d6")
, Movement (Piece Black Knight) (coord "b5") (coord "a7")
, Movement (Piece Black Knight) (coord "b5") (coord "a3")
, Capture (Piece Black Knight) (coord "b5") (coord "c3")
, Capture (Piece Black Knight) (coord "b5") (coord "d4")]
generateAllKingMovesSpec :: Spec
generateAllKingMovesSpec =
describe "generateAllKingMoves" $ do
it "should return empty list of moves if no move is possible" $
generateAllKingMoves (game "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") (coord "e1") `shouldMatchList` []
it "should return all movement and capture moves for a king in a square" $
generateAllKingMoves (game "2b5/pkp1prpp/8/rpn5/1K6/2P5/PP2N1PR/N1Q5 w - - 2 15") (coord "b4") `shouldMatchList`
[ Movement (Piece White King) (coord "b4") (coord "a4")
, Movement (Piece White King) (coord "b4") (coord "a3")
, Movement (Piece White King) (coord "b4") (coord "b3")
, Movement (Piece White King) (coord "b4") (coord "c4")
, Capture (Piece White King) (coord "b4") (coord "a5")
, Capture (Piece White King) (coord "b4") (coord "b5")
, Capture (Piece White King) (coord "b4") (coord "c5")]
it "should return castling moves when castling is possible" $
generateAllKingMoves (game "1rq1kbr1/pppbnn1p/8/8/8/3N4/PPPP2PP/R3K2R w KQ - 0 10") (coord "e1") `shouldMatchList`
[ Movement (Piece White King) (coord "e1") (coord "d1")
, Movement (Piece White King) (coord "e1") (coord "e2")
, Movement (Piece White King) (coord "e1") (coord "f2")
, Movement (Piece White King) (coord "e1") (coord "f1")
, Castling White Long
, Castling White Short]
it "should not return castling move if the castling has been invalidated" $ do
generateAllKingMoves (game "r3k2r/ppppp1pp/2n2p2/3b4/8/2B2PPB/PPPPP2P/R3K2R w Qk - 5 14") (coord "e1") `shouldMatchList`
[ Movement (Piece White King) (coord "e1") (coord "d1")
, Movement (Piece White King) (coord "e1") (coord "f2")
, Movement (Piece White King) (coord "e1") (coord "f1")
, Castling White Long]
generateAllKingMoves (game "r3k2r/ppppp1pp/2n2p2/3b4/8/2B2PPB/PPPPP2P/R3K2R w Qk - 5 14") (coord "e8") `shouldMatchList`
[ Movement (Piece Black King) (coord "e8") (coord "d8")
, Movement (Piece Black King) (coord "e8") (coord "f7")
, Movement (Piece Black King) (coord "e8") (coord "f8")
, Castling Black Short]
it "should not return castling move if there is piece between castling line" $
generateAllKingMoves (game "4k3/n7/8/8/8/5N2/P1N2PPP/R1n1K1R1 w Q - 0 16") (coord "e1") `shouldMatchList`
[ Movement (Piece White King) (coord "e1") (coord "d1")
, Movement (Piece White King) (coord "e1") (coord "d2")
, Movement (Piece White King) (coord "e1") (coord "e2")
, Movement (Piece White King) (coord "e1") (coord "f1")]
it "should not return castling move if there is an opponent piece threatening castling end square" $
generateAllKingMoves (game "3rk1r1/5p2/8/8/3b2N1/5P2/1PP1P1PP/4K2R w K - 2 20") (coord "e1") `shouldMatchList`
[ Movement (Piece White King) (coord "e1") (coord "d1")
, Movement (Piece White King) (coord "e1") (coord "d2")
, Movement (Piece White King) (coord "e1") (coord "f1")
, Movement (Piece White King) (coord "e1") (coord "f2")]
it "should not return castling move if there is an opponent piece threatening a castling line square" $
generateAllKingMoves (game "3rk3/5p2/5r2/8/3P2N1/8/1PP1P1PP/4K2R w K - 0 12") (coord "e1") `shouldMatchList`
[ Movement (Piece White King) (coord "e1") (coord "d1")
, Movement (Piece White King) (coord "e1") (coord "d2")
, Movement (Piece White King) (coord "e1") (coord "f1")
, Movement (Piece White King) (coord "e1") (coord "f2")]
it "castling out of check should not be legal" $
generateAllKingMoves (game "3rk3/5p2/4r3/8/3P2N1/8/1PP2PPP/4K2R w K - 0 12") (coord "e1") `shouldMatchList`
[ Movement (Piece White King) (coord "e1") (coord "d1")
, Movement (Piece White King) (coord "e1") (coord "d2")
, Movement (Piece White King) (coord "e1") (coord "e2")
, Movement (Piece White King) (coord "e1") (coord "f1")]
it "castling when rook is threatened should be possible" $
generateAllKingMoves (game "3rk3/5p2/7r/8/3P2N1/8/1PP2PP1/4K2R w K - 0 12") (coord "e1") `shouldMatchList`
[ Movement (Piece White King) (coord "e1") (coord "d1")
, Movement (Piece White King) (coord "e1") (coord "d2")
, Movement (Piece White King) (coord "e1") (coord "e2")
, Movement (Piece White King) (coord "e1") (coord "f1")
, Castling White Short]
generateAllPawnMovesSpec :: Spec
generateAllPawnMovesSpec =
describe "generateAllPawnMoves" $ do
it "should return both normal movement and double move when possible" $ do
generateAllPawnMoves (game "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") (coord "e2") `shouldMatchList`
[ Movement (Piece White Pawn) (coord "e2") (coord "e3")
, PawnDoubleMove (Piece White Pawn) (coord "e2") (coord "e4")]
generateAllPawnMoves (game "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1") (coord "a7") `shouldMatchList`
[ Movement (Piece Black Pawn) (coord "a7") (coord "a6")
, PawnDoubleMove (Piece Black Pawn) (coord "a7") (coord "a5")]
it "should return empty list when no moves are possible" $ do
generateAllPawnMoves (game "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPP2PPP/RNBQKBNR w KQkq - 0 1") (coord "e4") `shouldMatchList` []
generateAllPawnMoves (game "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPP2PPP/RNBQKBNR b KQkq - 0 1") (coord "e5") `shouldMatchList` []
it "should return both movement and capture moves when possible" $
generateAllPawnMoves (game "rnbqkbnr/pppp1ppp/8/4p3/4PP2/8/PPP5/RNBQKBNR w KQkq - 0 1") (coord "f4") `shouldMatchList`
[ Movement (Piece White Pawn) (coord "f4") (coord "f5")
, Capture (Piece White Pawn) (coord "f4") (coord "e5")]
it "should return only capture when normal movement is not possible" $
generateAllPawnMoves (game "rnbqkbnr/pppp1ppp/8/4p3/4PP2/8/PPP5/RNBQKBNR w KQkq - 0 1") (coord "e5") `shouldMatchList`
[ Capture (Piece Black Pawn) (coord "e5") (coord "f4")]
it "should return normal movement when capture is not possible" $
generateAllPawnMoves (game "rnbqkbnr/pppp1p1p/8/4pPp1/4P3/8/PPPP2PP/RNBQKBNR w KQkq - 0 4") (coord "f5") `shouldMatchList`
[ Movement (Piece White Pawn) (coord "f5") (coord "f6")]
it "should return en passant when it is possible" $ do
generateAllPawnMoves (game "rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3") (coord "e5") `shouldMatchList`
[ Movement (Piece White Pawn) (coord "e5") (coord "e6")
, EnPassant (Piece White Pawn) (coord "e5") (coord "f6")]
generateAllPawnMoves (game "rnbqkbnr/ppp1pppp/8/8/2PpPP2/8/PP1P2PP/RNBQKBNR b KQkq c3 0 3") (coord "d4") `shouldMatchList`
[ Movement (Piece Black Pawn) (coord "d4") (coord "d3")
, EnPassant (Piece Black Pawn) (coord "d4") (coord "c3")]
it "should not return en passant when en passant square is not one of the capture squares" $
generateAllPawnMoves (game "rnbqkbnr/1pppp3/p5pp/3PPp2/8/8/PPP2PPP/RNBQKBNR w KQkq f6 0 5") (coord "d5") `shouldMatchList`
[ Movement (Piece White Pawn) (coord "d5") (coord "d6")]
it "should return all promotion moves when promotion with normal movement or by capture is possible" $ do
generateAllPawnMoves (game "1r5k/2P5/8/8/8/8/8/4K2N w - - 0 1") (coord "c7") `shouldMatchList`
[ Promotion (Piece White Pawn) (coord "c7") (coord "c8") Rook
, Promotion (Piece White Pawn) (coord "c7") (coord "c8") Knight
, Promotion (Piece White Pawn) (coord "c7") (coord "c8") Bishop
, Promotion (Piece White Pawn) (coord "c7") (coord "c8") Queen
, Promotion (Piece White Pawn) (coord "c7") (coord "b8") Rook
, Promotion (Piece White Pawn) (coord "c7") (coord "b8") Knight
, Promotion (Piece White Pawn) (coord "c7") (coord "b8") Bishop
, Promotion (Piece White Pawn) (coord "c7") (coord "b8") Queen]
generateAllPawnMoves (game "k7/8/8/8/8/8/p7/1N2K3 w - - 0 1") (coord "a2") `shouldMatchList`
[ Promotion (Piece Black Pawn) (coord "a2") (coord "a1") Rook
, Promotion (Piece Black Pawn) (coord "a2") (coord "a1") Knight
, Promotion (Piece Black Pawn) (coord "a2") (coord "a1") Bishop
, Promotion (Piece Black Pawn) (coord "a2") (coord "a1") Queen
, Promotion (Piece Black Pawn) (coord "a2") (coord "b1") Rook
, Promotion (Piece Black Pawn) (coord "a2") (coord "b1") Knight
, Promotion (Piece Black Pawn) (coord "a2") (coord "b1") Bishop
, Promotion (Piece Black Pawn) (coord "a2") (coord "b1") Queen]
it "should not return any moves if no move is possible" $ do
generateAllPawnMoves (game "k7/8/8/8/8/8/p7/N3K3 w - - 0 1") (coord "a2") `shouldMatchList` []
generateAllPawnMoves (game "k7/8/8/8/8/4b3/4P3/K7 w - - 0 1") (coord "e2") `shouldMatchList` []
it "should generate normal movement correctly" $
generateAllPawnMoves (game "6k1/8/8/8/8/3P4/8/4K3 w - - 0 1") (coord "d3") `shouldMatchList`
[ Movement (Piece White Pawn) (coord "d3") (coord "d4")]
generateAllPotentialMovesSpec :: Spec
generateAllPotentialMovesSpec =
describe "generateAllPotentialMoves" $
it "should return all potential moves for all pieces of the current player" $ do
generateAllPotentialMoves (game "8/k7/8/8/6p1/7P/6PK/8 w - - 0 1") `shouldMatchList`
[ Movement (Piece White Pawn) (coord "g2") (coord "g3")
, Movement (Piece White Pawn) (coord "h3") (coord "h4")
, Capture (Piece White Pawn) (coord "h3") (coord "g4")
, Movement (Piece White King) (coord "h2") (coord "g3")
, Movement (Piece White King) (coord "h2") (coord "h1")
, Movement (Piece White King) (coord "h2") (coord "g1")]
generateAllPotentialMoves (game "8/k7/8/8/6p1/7P/6PK/8 b - - 0 1") `shouldMatchList`
[ Capture (Piece Black Pawn) (coord "g4") (coord "h3")
, Movement (Piece Black Pawn) (coord "g4") (coord "g3")
, Movement (Piece Black King) (coord "a7") (coord "a8")
, Movement (Piece Black King) (coord "a7") (coord "a6")
, Movement (Piece Black King) (coord "a7") (coord "b8")
, Movement (Piece Black King) (coord "a7") (coord "b7")
, Movement (Piece Black King) (coord "a7") (coord "b6")]
boardAfterMoveSpec :: Spec
boardAfterMoveSpec =
describe "boardAfterMove" $ do
it "should make pawn double move correctly" $ do
boardAfterMove (fenBoard "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") (PawnDoubleMove (Piece White Pawn) (coord "e2") (coord "e4")) `shouldBe` Just (fenBoard "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 1")
boardAfterMove (fenBoard "rnbqkbnr/p1pp1ppp/p7/4p3/4P3/5N2/PPPP1PPP/RNBQ1RK1 b kq - 1 1") (PawnDoubleMove (Piece Black Pawn) (coord "c7") (coord "c5")) `shouldBe` Just (fenBoard "rnbqkbnr/p2p1ppp/p7/2p1p3/4P3/5N2/PPPP1PPP/RNBQ1RK1 w kq c6 0 2")
boardAfterMove (fenBoard "rnbqkbnr/p2p1ppp/p7/4N3/2p1P3/8/PPPP1PPP/RNBQ1RK1 w kq - 0 3") (PawnDoubleMove (Piece White Pawn) (coord "d2") (coord "d4")) `shouldBe` Just (fenBoard "rnbqkbnr/p2p1ppp/p7/4N3/2pPP3/8/PPP2PPP/RNBQ1RK1 b kq d3 0 3")
it "should make pawn normal move correctly" $ do
boardAfterMove (fenBoard "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 1") (Movement (Piece White Knight) (coord "g1") (coord "f3")) `shouldBe` Just (fenBoard "rnbqkbnr/pppp1ppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 0 1")
boardAfterMove (fenBoard "rnbqkbnr/p2p1ppp/p7/2p1N3/4P3/8/PPPP1PPP/RNBQ1RK1 b kq - 0 2") (Movement (Piece Black Pawn) (coord "c5") (coord "c4")) `shouldBe` Just (fenBoard "rnbqkbnr/p2p1ppp/p7/4N3/2p1P3/8/PPPP1PPP/RNBQ1RK1 w kq - 0 3")
it "should make pawn capture move correctly" $
boardAfterMove (fenBoard "rnbqkbnr/pppp1ppp/B7/4p3/4P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 0 1") (Capture (Piece Black Pawn) (coord "b7") (coord "a6")) `shouldBe` Just (fenBoard "rnbqkbnr/p1pp1ppp/p7/4p3/4P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 0 1")
it "should move king and rook correctly in castling move" $
boardAfterMove (fenBoard "rnbqkbnr/p1pp1ppp/p7/4p3/4P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 0 1") (Castling White Short) `shouldBe` Just (fenBoard "rnbqkbnr/p1pp1ppp/p7/4p3/4P3/5N2/PPPP1PPP/RNBQ1RK1 b kq - 1 1")
it "should make knight's capture move correctly" $
boardAfterMove (fenBoard "rnbqkbnr/p2p1ppp/p7/2p1p3/4P3/5N2/PPPP1PPP/RNBQ1RK1 w kq c6 0 2") (Capture (Piece White Knight) (coord "f3") (coord "e5")) `shouldBe` Just (fenBoard "rnbqkbnr/p2p1ppp/p7/2p1N3/4P3/8/PPPP1PPP/RNBQ1RK1 b kq - 0 2")
it "should make en passant move correctly" $
boardAfterMove (fenBoard "rnbqkbnr/p2p1ppp/p7/4N3/2pPP3/8/PPP2PPP/RNBQ1RK1 b kq d3 0 3") (EnPassant (Piece Black Pawn) (coord "c4") (coord "d3")) `shouldBe` Just (fenBoard "rnbqkbnr/p2p1ppp/p7/4N3/4P3/3p4/PPP2PPP/RNBQ1RK1 w kq - 0 4")
generateAllMovesSpec :: Spec
generateAllMovesSpec =
describe "generateAllMoves" $ do
it "should generate all legal moves for the current player in a given game state" $
generateAllMoves (game "rnbqkb1r/pp1p1Bpp/5n2/2p1p3/4P3/2P5/PP1P1PPP/RNBQK1NR b KQkq - 0 4") `shouldMatchList`
[Movement (Piece Black King) (0,4) (1,4), Capture (Piece Black King) (0,4) (1,5)]
it "should not give any legal moves in checkmate" $ do
generateAllMoves (game "8/5r2/4K1q1/4p3/3k4/8/8/8 w - - 0 7") `shouldBe` []
generateAllMoves (game "4r2r/p6p/1pnN2p1/kQp5/3pPq2/3P4/PPP3PP/R5K1 b - - 0 2") `shouldBe` []
generateAllMoves (game "r3k2r/ppp2p1p/2n1p1p1/8/2B2P1q/2NPb1n1/PP4PP/R2Q3K w kq - 0 8") `shouldBe` []
generateAllMoves (game "8/6R1/pp1r3p/6p1/P3R1Pk/1P4P1/7K/8 b - - 0 4") `shouldBe` []
it "should not give any legal moves in stalemate" $ do
generateAllMoves (game "1R6/8/8/8/8/8/7R/k6K b - - 0 1") `shouldBe` []
generateAllMoves (game "8/8/5k2/p4p1p/P4K1P/1r6/8/8 w - - 0 2") `shouldBe` []
| nablaa/hchesslib | test/Chess/MoveTests.hs | gpl-2.0 | 23,504 | 0 | 16 | 6,027 | 6,709 | 3,341 | 3,368 | 297 | 1 |
module LineParse ( lineParse ) where
import IrcBot
import Types
import Cmds
import Data.List
import System.Time
import Control.Concurrent.MVar
import Data.List.Split
import Control.Monad.Reader
lineParse :: String -> Net ()
lineParse s
| ("PING :" `isPrefixOf` s) = write "PONG" (':' : drop 6 s)
| (rnum == "332") = liftIO (takeMVar topic) >> liftIO (putMVar topic (splitOn " | " ((drop 1 . dropWhile (/= ':') . drop 1) s)))
| otherwise = do
let msg = (getIRCMessage s)
liftIO $ putStrLn (show msg)
eval msg
where
rnum = getResponseNum s
getResponseNum :: String -> String
getResponseNum s = (takeWhile (/= ' ') . drop 1 . dropWhile (/= ' ')) s
getIRCMessage :: String -> IRCMessage
getIRCMessage raw = IRCMessage { fullText = raw, command = (readCommand raw), rightText = (readRight raw), channel = (readChannel raw), user = (readUser raw) , semiText = reverse (takeWhile (/= ':') (reverse raw)) }
where
readUser r = if ((take 1 r) == ":")
then (takeWhile (/= '!') . drop 1) r
else ""
readChannel r = if ((cm r) == nick)
then readUser r
else cm r
where cm r = (takeWhile (/= ' ') . drop 1 . dropWhile (/= ' ') . removeLeft) r
readCommand r = (takeWhile (/= ' ') . removeLeft) r
readRight r = (drop 1 . dropWhile (/= ' ') . removeLeft) r
removeLeft r = if ((take 1 r) == ":")
then (drop 1 . dropWhile (/= ' ')) r
else r
eval :: IRCMessage -> Net ()
eval m = eval' m cmdList
eval' :: IRCMessage -> [IRCCommand] -> Net ()
eval' _ [] = return ()
eval' m@(IRCMessage { semiText=x }) ((IRCCommand { name = nam, function = func}):cmds) =
if ((nam) `isPrefixOf` (drop 1 x)) then (func) m else eval' m cmds
| DSMan195276/QB64Bot | LineParse.hs | gpl-2.0 | 2,029 | 0 | 18 | 729 | 777 | 410 | 367 | 40 | 4 |
-- Copyright (C) 2013-2015 Moritz Schulte <[email protected]>
-- This code needs a major cleanup, less imperative programing style,
-- safer programing (eliminate fromJust, etc.), less code duplication,
-- a nicer state handling, etc.
--
-- Feel free to submit patches. -MS
module Main (main) where
import Graphics.UI.Gtk -- The GUI Toolkit.
import System.Glib.UTFString
import System.Environment -- Commandline Arguments.
import System.Random -- For picking players randomly.
import System.Process
import System.IO -- Support for file handles.
import System.IO.Temp -- We need temporary files.
import System.Exit -- ExitCode handling.
import Data.List -- List functions like 'nub'.
import Data.IORef -- We manage state with IORefs.
import Data.Maybe -- The Maybe type.
import Data.Foldable
import qualified Data.Map as M -- The Map type.
import qualified Data.ByteString as B -- We also need ByteStrings.
import qualified Codec.Archive.Tar as Tar -- Support for Tar archives.
import Control.Concurrent -- For 'forkIO'.
import Control.Exception -- For 'assert', 'try'.
import System.IO.Error
import Control.Monad -- For 'when'.
import Control.Monad.Trans(liftIO) -- We need liftIO for Gtk.
import Jeopardy.Data -- Jeopardy data structures.
import Jeopardy.GUI
import Jeopardy.Utils -- General utility functions.
import Paths_silverratio_jeopardy -- Access to data files.
----------------------
-- Type Definitions --
----------------------
-- 'Player' data structure.
type PlayerID = Integer
type PlayerName = String
type PlayerBuzzer = String
data Player = Player { playerName :: PlayerName
, playerBuzzer :: Maybe PlayerBuzzer
} deriving (Read, Show)
-- Mapping: {PlayerID} -> {Player}
type PlayerMap = M.Map PlayerID Player
-- This is the state which contains all the necessary data to restore
-- the current game state.
data State_ = State_ { stateJDataFile_ :: Maybe FilePath
, statePlayers_ :: PlayerMap
, stateActionLog_ :: [JAction]
, stateCurrentDecider_ :: Maybe PlayerID
} deriving (Read, Show)
-- Main program state.
data State = State {
-- Logger MVar
stateLogger :: MVar (),
-- State for the Audio Subsystem.
stateAudio :: AudioState,
-- Players in the game.
statePlayers :: PlayerMap,
-- The list of 'jeopardy actions' (e.g., Player P has answered
-- Question Q of price P correctly).
stateActionLog :: [JAction],
-- This is the {Player} -> {Points} mapping. It can be entirely
-- (re)computed via a list of JActions.
statePoints :: PointTable,
-- We need a random number generator.
stateRandom :: StdGen,
-- BEGIN: GUI Toolkit specific members
stateBuilder :: Builder,
-- END: GUI Toolkit specific members
-- To keep track of players who have buzzed.
stateBuzzed :: [PlayerID],
-- This is the compiled 'Jeopardy Data' (i.e. the table of
-- answers/questions).
stateJData :: JDataCompiled,
-- Filename from which we have read the Jeopardy Data.
stateJDataFile :: Maybe FilePath,
-- The current phase of the Jeopardy state machine.
statePhase :: GamePhase,
-- Statefile. If set, we use this for saving snapshots of the game
-- state. This state can be used to restore the game.
stateStateFile :: Maybe FilePath,
-- When we need the notion of 'current player'. e.g. during player
-- initialization or when a player has buzzed during a query.
stateCurrentPlayer :: Maybe PlayerID,
-- If Just, this contains the player ID of the player who has picked
-- the last JItem.
stateCurrentDecider :: Maybe PlayerID,
-- During a query, this is the 'current jeopardy item'.
stateCurrentJItem :: Maybe (Category, Price),
-- The timeout handler during the query phase.
stateTimeoutHandler :: Maybe HandlerId,
-- The name of the 'screen' which is currently displayed on the
-- 'game board'.
stateGameScreen :: String,
-- When the timeout is reached while waiting for a player's answer,
-- this flag is set.
stateTimeoutReached :: Bool,
-- Controls wether we need to pick a random player or not during
-- PrepareQuery.
--stateNeedRandomPlayer :: Bool,
-- If we are currently in 'Double Jeopardy' mode.
stateDoubleJeopardy :: Bool,
-- If debugging (i.e. verbosity) is enabled or not.
stateDebug :: Bool }
-- Type used for points.
type Points = Integer
-- This is the map {playerID} -> {Points}.
type PointTable = M.Map PlayerID Points
-- A "JAction" describes what player has answered which question
-- correctly/wrong.
data JAction = JAction {
-- ID of the player. ID == -1 means 'timeout reached'
jactionPlayerID :: PlayerID,
-- The question:
jactionCategory :: Category,
jactionPrice :: Price,
-- If it was answered correct or not.
jactionCorrect :: Bool } deriving (Read, Show)
-- The GamePhase describes the 'current state' of the game.
data GamePhase =
PhaseNothing | -- Not a valid phase.
PhasePreGame | -- No game started yet.
PhasePrepareGame | -- Currently waiting for game init
-- data.
PhaseGamePrepared | -- Game init data has been provided.
PhasePlayerInit | -- Currently initializing player list.
PhasePreQuery | -- No JItem as been chosen so yet.
PhaseInQuery | -- JItem chosen, waiting for buzzers.
PhaseQueryTimeout |
PhasePostGame | -- Game is over.
PhaseQueryBuzzed | -- We have received buzzer events
-- during query.
PhaseShowAnswer | -- Currently showing the answer.
PhaseShowAnswerAfterTimeout | -- Currently showing answer, after timeout.
PhaseGameRestored | -- Game state has been restored.
PhasePreDoubleJeopardy | -- Prepare Double Jeopardy.
PhaseInDoubleJeopardy | -- Ask Double Jeopardy.
PhasePostQuery -- Query phase is over.
deriving (Eq, Show, Read)
-- These are the 'game actions'. The set of actions which are allowed
-- to be triggered depends on the current GamePhase.
data JeopardyAction =
AdminGameNew |
AdminGameStop |
AdminGameQuit |
AdminHelpAbout |
AdminNewGameStart |
AdminNewGameCancel |
AdminNewGameSelectDataFile |
AdminNewGameSelectStateFile |
AdminGameEnter |
PrepareQuery |
AdminRestoreGame |
AdminShowAnswer |
AdminContinue |
AdminPickRandomPlayer |
AdminAnswerCorrect |
AdminCancelPlayerInit |
AdminPlayerInit |
GameQueryTimeout |
GameBuzzed PlayerID |
DigitPressed PlayerID |
GameEnterQuery Category Price |
QueryAnswered Bool |
GameOver
deriving (Read, Show)
-- Suitable for initializing JDataCompiled values.
emptyJData :: JDataCompiled
emptyJData = JDataCompiled { jdataName_ = ""
, jdataCategories_ = []
, jdataTable_ = M.empty
}
----------------------------
-- Game Related Constants --
----------------------------
-- These are GUI-specific names of some important widgets.
cardContainerPrefix :: String
cardContainerPrefix = "eventbox_"
cardPrefix :: String
cardPrefix = "label_"
-- Audio Player Command
audioPlayer :: String
audioPlayer = "play"
-- The audio files to play on events.
audioFileBuzzer :: String
audioFileBuzzer = "Button.ogg"
audioFileTimeout :: String
audioFileTimeout = "Timeout.ogg"
audioFileClosing :: String
audioFileClosing = "Closing.ogg"
audioFileTheme :: String
audioFileTheme = "Theme.ogg"
audioFileCorrect :: String
audioFileCorrect = "Ding.ogg"
audioFileWrong :: String
audioFileWrong = "Wrong.ogg"
audioFileStart :: String
audioFileStart = "Woosh.ogg"
audioFileDouble :: String
audioFileDouble = "DoubleJeopardy.ogg"
audioFileRandom :: String
audioFileRandom = "DingLing.ogg"
bootScreenImage :: String
bootScreenImage = "Images/Boot.jpg"
buzzerImageName :: String
buzzerImageName = "Images/Buzzed.png"
-- Maximum number of players allowed.
maxPlayers :: Integer
maxPlayers = 4
-- In miliseconds.
timeoutDisplayBuzzing :: Int
timeoutDisplayBuzzing = 2000
timeoutQuery :: Int
timeoutQuery = 20000
timeoutRandomCB1 :: Int
timeoutRandomCB1 = 1000
timeoutRandomCB2 :: Int
timeoutRandomCB2 = 2000
-- Std Files
devNull :: String
devNull = "/dev/null"
-------------------------------
-- GUI Toolkit Encapsulation --
-------------------------------
-- Color theme.
colorGameBg :: Color
colorGameBg = Color 0 0 0
colorCardBg :: Color
colorCardBg = Color 0 0 40535
colorCardBg' :: Color
colorCardBg' = Color 0 0 9000
colorCardFg :: Color
colorCardFg = Color 65535 65535 65535
colorGameFg :: Color
colorGameFg = Color 65535 65535 65535
-- Define the colors of players.
colorPlayers :: [Color]
colorPlayers = [ Color 65535 0 0 -- 1st player: Red
, Color 0 65535 0 -- 2nd player: Green
, Color 65535 65535 0 -- 3rd player: Yellow
, Color 65535 0 65535 -- 4th player: Purple
]
-- Same as above, only darker.
colorPlayers' :: [Color]
colorPlayers' = [ Color 35535 0 0
, Color 0 35535 0
, Color 35535 35535 0
, Color 35535 0 35535
]
------------
-- Logger --
------------
logInfo :: State -> String -> IO ()
logInfo state msg =
withMVar (stateLogger state) (\ _ -> putStrLn msg)
logErr :: State -> String -> IO ()
logErr state msg =
withMVar (stateLogger state) (\ _ -> hPutStrLn stderr msg)
------------------------------------------------
-- GUI Sensitivity Control of certain widget --
------------------------------------------------
-- The 'Jeopardy State' includes some kind of 'Context' for the
-- underlying GUI Toolkit. In case of Gtk this is simply the
-- "Builder", which we use from time to time to retrieve widgets.
type GUICtx = Builder
-- GUI Controls
data GUIControl =
ButtonPickRandomPlayer |
ButtonAnsweredCorrectly |
ButtonAnsweredWrong |
ButtonShowAnswer |
ButtonContinue |
ButtonJItem Category Price |
AdminJItemTable
deriving (Eq, Show, Read)
-- Convert GUIControl values into their according widget names.
_GUIControlName :: GUIControl -> String
_GUIControlName guictrl =
case guictrl of
ButtonPickRandomPlayer -> "button_random_player"
ButtonAnsweredCorrectly -> "admin_button_answer_correct"
ButtonAnsweredWrong -> "admin_button_answer_wrong"
ButtonShowAnswer -> "button_show_answer"
ButtonContinue -> "button_continue"
ButtonJItem category price -> "admin_jitem_" ++ category ++ show price
AdminJItemTable -> "admin_jitem_table"
-- Manage Sensitivity of GUI widgets.
_GUISetSensitivity :: IORef State -> GUIControl -> Bool -> IO ()
_GUISetSensitivity state' guictrl bool = do
state <- readIORef state'
let builder = stateBuilder state
wName = _GUIControlName guictrl
widget <- _GUIWidget builder wName
widgetSetSensitive widget bool
_GUISensitivityOn :: IORef State -> GUIControl -> IO ()
_GUISensitivityOn state' guictrl =
_GUISetSensitivity state' guictrl True
_GUISensitivityOff :: IORef State -> GUIControl -> IO ()
_GUISensitivityOff state' guictrl =
_GUISetSensitivity state' guictrl False
------------------------------------------------------------
-----------------
-- GUI Helpers --
-----------------
-- Display a popup window containing an error message.
_GUIError :: Window -> String -> String -> IO ()
_GUIError parent _ msg = do
dialog <- dialogNew
windowSetTransientFor dialog parent
_ <- on dialog deleteEvent (liftIO $ return True) -- FIXME: True or False?
set dialog [ windowTitle := "" ]
contentArea <- dialogGetUpper dialog
label <- labelNew $ Just msg
boxPackStart contentArea label PackGrow 10
widgetShowAll contentArea
_ <- dialogAddButton dialog stockOk ResponseOk
_ <- dialogRun dialog
widgetDestroy dialog
-- Display message, ask user Ok/Cancel question.
_GUIAskOkCancel :: Window -> String -> String -> IO Bool
_GUIAskOkCancel parent title msg = do
dialog <- dialogNew
windowSetTransientFor dialog parent
_ <- on dialog deleteEvent (liftIO $ return True) -- FIXME: True or False?
set dialog [ windowTitle := title ]
contentArea <- dialogGetUpper dialog
label <- labelNew $ Just msg
boxPackStart contentArea label PackGrow 10
widgetShowAll contentArea
_ <- dialogAddButton dialog stockOk ResponseOk
_ <- dialogAddButton dialog stockCancel ResponseCancel
res <- dialogRun dialog
widgetDestroy dialog
return (res == ResponseOk)
-- Display a File Chooser Dialog. PARENT is the parent window.
_GUIfileDialog :: Window -> String -> Bool -> IO (Maybe FilePath)
_GUIfileDialog parent title openMode = do
let mode = if openMode
then FileChooserActionOpen
else FileChooserActionSave
title' = Just title
parent' = Just parent
buttons = [ (glibToString stockCancel, ResponseCancel)
, (glibToString stockOk, ResponseOk) ]
fileChooser <- fileChooserDialogNew title' parent' mode buttons
res <- dialogRun fileChooser
if res == ResponseOk
then do fileName <- fileChooserGetFilename fileChooser
widgetDestroy fileChooser
return fileName
else do widgetDestroy fileChooser
return Nothing
-- Display a File Chooser Dialog for opening a file.
_GUIfileDialogOpen :: Window -> IO (Maybe FilePath)
_GUIfileDialogOpen parent = _GUIfileDialog parent "Open" True
-- Display a File Chooser Dialog for saving a file.
_GUIfileDialogSaveAs :: Window -> IO (Maybe FilePath)
_GUIfileDialogSaveAs parent = _GUIfileDialog parent "Save File" False
-- newWidgetName is expected to denote a widget of type
-- 'Alignment'. The currently displayed (Alignment) widget in the
-- game_board is replaced with the one specified here.
_GUIFrobGameBoard :: IORef State -> String -> IO ()
_GUIFrobGameBoard state' newWidgetName = do
state <- readIORef state'
let builder = stateBuilder state
gameBoard <- _GUIWindow builder "game_board"
currentWidget <- _GUIAlignment builder (stateGameScreen state)
newWidget <- _GUIAlignment builder newWidgetName
containerRemove gameBoard currentWidget
containerAdd gameBoard newWidget
writeIORef state' $ state { stateGameScreen = newWidgetName }
-- Install a callback handler for events. Install CALLBACK for widget
-- NAME on SIGNAL. CAST has to be the correct Gtk casting function
-- which is to be used for builderGetObject.
_GUIInstallCB :: (GObjectClass cls) =>
IORef State -> String -> (GObject -> cls) ->
Signal cls callback -> callback ->
IO (ConnectId cls)
_GUIInstallCB state' name cast signal callback = do
state <- readIORef state'
let builder = stateBuilder state
obj <- builderGetObject builder cast name
on obj signal callback
------------------------------
-- GUI Initialization/Setup --
------------------------------
-- Enter the GUI Main loop.
_GUIStart :: IO ()
_GUIStart = mainGUI
-- Initialize the GUI Toolkit. Return the created GUI Context.
_GUIInit :: IO GUICtx
_GUIInit = do
_ <- initGUI
builder <- builderNew
gladeFilename <- getDataFileName jeopardyGtkBuilder
builderAddFromFile builder gladeFilename
return builder
-- Shutdown GUI and quit application.
_GUIQuit :: IORef State -> IO ()
_GUIQuit _ = mainQuit
_GUIDetachChilds :: Builder -> [(String, String)] -> IO ()
_GUIDetachChilds builder list = do
let detachChild (windowName, childName) = do
window <- _GUIWindow builder windowName
widget <- _GUIWidget builder childName
containerRemove window widget
mapM_ detachChild list
_GUIFrobColors :: Builder ->
[(String, StateType, Maybe Color, Maybe Color)] -> IO ()
_GUIFrobColors builder list = do
let detachChild (wName, stateType, colorFg, colorBg) = do
widget <- _GUIWidget builder wName
forM_ colorFg $ widgetModifyFg widget stateType
forM_ colorBg $ widgetModifyBg widget stateType
mapM_ detachChild list
-- Setup Menu actions.
_GUISetupMenuActions :: IORef State -> IO ()
_GUISetupMenuActions state' = do
-- This function installs the handlers to be called on activation of
-- the menu items.
let installCB (name, action) =
_GUIInstallCB state' name castToMenuItem
menuItemActivate (_STM action state')
-- Install the handlers for the given menu items.
mapM_ installCB
[ ("admin_game_new", AdminGameNew),
("admin_game_stop", AdminGameStop),
("admin_game_quit", AdminGameQuit),
("menu_item_about", AdminHelpAbout) ]
-- Setup Button actions.
_GUISetupButtonActions :: IORef State -> IO ()
_GUISetupButtonActions state' = do
-- This function installs the handlers to be called on activation of
-- the buttons.
let installCB (name, action) =
_GUIInstallCB state' name castToButton
buttonActivated (_STM action state')
-- Install the handlers
mapM_ installCB
[ ("button_random_player", AdminPickRandomPlayer),
("admin_button_answer_correct", QueryAnswered True),
("admin_button_answer_wrong", QueryAnswered False),
("button_select_data_file", AdminNewGameSelectDataFile),
("button_select_statefile", AdminNewGameSelectStateFile),
("button_start_game", AdminNewGameStart),
("button_cancel_new_game", AdminNewGameCancel),
("player_init_cancel", AdminCancelPlayerInit),
("button_show_answer", AdminShowAnswer),
("button_continue", AdminContinue)]
-- Now for the JItem Buttons in the Admin CP.
let installCB' (category, price) = do
let suffix = category ++ show price
name = "admin_jitem_" ++ suffix
cb = _STM (GameEnterQuery category price) state'
_GUIInstallCB state'
name castToButton buttonActivated cb
mapM_ installCB' cardIndex'
-- Setup actions, handlers; change colors of widgets, etc.
_GUISetup :: IORef State -> IO ()
_GUISetup state' = do
state <- readIORef state'
let builder = stateBuilder state
-- Setup Menu actions.
_GUISetupMenuActions state'
-- Setup Button actions.
_GUISetupButtonActions state'
-- Install handlers which manage sensitivity of buttons in 'New
-- Game'-dialogue (the 'Start' button shall only be clickable when a
-- non-zero number of player names has been entered and when a JDC
-- file has been specified).
let installHandler idx =
let wName = "new_game_player_" ++ show idx
cb = newGameDataChanged state'
in _GUIInstallCB state' wName castToEntry editableChanged cb
mapM_ installHandler [1..maxPlayers]
-- Detach childs of the windows (we don't need so many toplevel
-- windows, in many cases we only need the content of the toplevel
-- windows).
_GUIDetachChilds builder [ ("answerwin", "answerscreen"),
("window3", "buzzerscreen"),
("win_query", "queryscreen"),
("window_boot", "box_boot"),
("game_board", "gamescreen"),
("win_ranking", "box_ranking"),
("win_doublejeopardy", "screen_doublejeopardy"),
("window_random", "randomscreen") ]
-- Modify Window Colors.
_GUIFrobColors builder
[ ("game_board",
StateNormal, Just colorGameFg, Just colorGameBg),
("randomscreen",
StateNormal, Just colorGameFg, Just colorGameBg),
("box_question_preview",
StateNormal, Just colorGameFg, Just colorGameBg),
("box_boot",
StateNormal, Just colorGameFg, Just colorGameBg),
("screen_doublejeopardy",
StateNormal, Just colorGameFg, Just colorGameBg),
("box_ranking",
StateNormal, Just colorGameFg, Just colorGameBg) ]
--
-- Prepare game_board.
--
window1 <- _GUIWindow builder "game_board"
bootBox <- _GUIAlignment builder "box_boot"
windowSetDeletable window1 False
windowSetTitle window1 "Jeopardy Game Board"
containerAdd window1 bootBox
-- Set 'Boot Image'.
bootImage <- _GUIImage builder "boot_image"
getDataFileName bootScreenImage >>= imageSetFromFile bootImage
-- Set 'Buzzer Image'
buzzerImage <- _GUIImage builder "image_buzzer"
getDataFileName buzzerImageName >>= imageSetFromFile buzzerImage
-- imageSetFromFile buzzerImage imgName
-- Modify colors of player & points labels in gameboard.
setPlayerColors builder colorPlayers
clearCurrentPlayer builder
--
-- Prepare Admin Control Panel.
--
adminWindow <- _GUIWindow builder "window2"
windowSetTitle adminWindow "Jeopardy Admin Control Panel"
_ <- _GUIInstallCB state' "window2" castToWindow deleteEvent $
liftIO $ _STM AdminGameQuit state' >> return False
_ <- _GUIInstallCB state' "game_board" castToWindow deleteEvent $
liftIO $ return True
_ <- _GUIInstallCB state' "dialog_new_game" castToWindow deleteEvent $
liftIO $ _STM AdminNewGameCancel state' >> return True
_ <- _GUIInstallCB state' "window2" castToWindow keyPressEvent $
tryEvent $ eventBuzzerPressed' state'
_ <- _GUIInstallCB state' "window_player_init" castToWindow
keyPressEvent $ tryEvent $ playerInitialBuzzer state'
_ <- _GUIInstallCB state' "window_player_init" castToWindow
keyPressEvent $ tryEvent $ eventBuzzerPressed' state'
mapM_ (_GUISensitivityOff state')
[ ButtonPickRandomPlayer,
ButtonAnsweredCorrectly,
ButtonAnsweredWrong,
ButtonShowAnswer,
ButtonContinue ]
_GUISensitivityOff state' AdminJItemTable
-- Reset the ame board, i.e.
_GUIResetGameBoard :: IORef State -> IO ()
_GUIResetGameBoard state' = do
state <- readIORef state'
let builder = stateBuilder state
-- Change colors of the card widgets on the game board.
mapM_ (\ suf -> do
eventbox <- _GUIEventBox builder (cardContainerPrefix ++ suf)
label <- builderGetObject builder
castToLabel (cardPrefix ++ suf)
widgetModifyBg eventbox StateNormal colorCardBg
widgetModifyFg label StateNormal colorCardFg)
cardIndex
-- Reset Player/Points info.
mapM_ (\ idx -> do
setPlayerName builder idx Nothing
setPlayerPoints builder idx Nothing)
[1..maxPlayers]
doubleJeopardyCB :: IORef State -> IO Bool
doubleJeopardyCB state' = do
_GUISensitivityOn state' ButtonContinue
return False
_GUIAdminContinue :: IORef State -> IO ()
_GUIAdminContinue state' = do
state <- readIORef state'
let builder = stateBuilder state
mapM_ (_GUISensitivityOff state') [ButtonContinue]
-- Clear image in Admin CP.
img <- _GUIImage builder "admin_question_preview"
imageClear img
_GUIFrobGameBoard state' "gamescreen"
-- Ask for data file, ask for players, show game window.
_GUIGameNew :: IORef State -> IO ()
_GUIGameNew state' = do
state <- readIORef state'
let builder = stateBuilder state
_GUILabel builder "data_file_to_load" >>= flip labelSetText ""
_GUILabel builder "statefile_to_use" >>= flip labelSetText ""
parent <- _GUIWindow builder "window2"
dialog <- _GUIWindow builder "dialog_new_game"
windowSetTransientFor dialog parent
windowSetModal dialog True
widgetShow dialog
newGameDataChanged state'
setCurrentPlayer :: IORef State -> PlayerID -> Player -> IO ()
setCurrentPlayer state' pID player = do
state <- readIORef state'
let builder = stateBuilder state
pName = playerNameEscaped player
pColor = colorPlayers !! (fromIntegral pID - 1)
text = pName
label <- _GUILabel builder "label_current_player"
logInfo state $ "setCurrentPlayer Color " ++ show pColor
widgetModifyFg label StateNormal pColor
labelSetMarkup label $
"<span weight='bold' font='30'>" ++ text ++ "</span>"
setCurrentPlayerTimeout :: IORef State -> IO ()
setCurrentPlayerTimeout state' = do
state <- readIORef state'
let builder = stateBuilder state
label <- _GUILabel builder "label_current_player"
widgetModifyFg label StateNormal colorGameFg
labelSetMarkup label "<span weight='bold' font='30'>T I M E O U T</span>"
clearCurrentPlayer :: Builder -> IO ()
clearCurrentPlayer builder = do
label <- _GUILabel builder "label_current_player"
widgetModifyFg label StateNormal (Color 0 0 0)
labelSetMarkup label "<span weight='bold' size='large'></span>"
_GUIGameBuzzed :: IORef State -> PlayerID -> Player -> IO ()
_GUIGameBuzzed state' pID player = do
audioSilenceBackground state'
audioPlayOnce state' audioFileBuzzer
state <- readIORef state'
let builder = stateBuilder state
pColor = colorPlayers !! (fromIntegral pID - 1)
_ <- _GUIWindow builder "game_board"
label <- _GUILabel builder "buzzer_screen_player"
widgetModifyFg label StateNormal pColor
labelSetMarkup label $
"<span weight='bold' font='30'>" ++
playerNameEscaped player ++ "</span>"
_GUIFrobGameBoard state' "buzzerscreen"
setCurrentPlayer state' pID player
_GUICancelGame :: IORef State -> IO ()
_GUICancelGame _ = return ()
_GUIShowAbout :: IORef State -> IO ()
_GUIShowAbout state' = do
state <- readIORef state'
let builder = stateBuilder state
about <- builderGetObject builder castToAboutDialog "window_about"
widgetShowAll about
_ <- dialogRun about
widgetHide about
_GUIInitPlayer :: IORef State -> IO ()
_GUIInitPlayer state' = do
state <- readIORef state'
assert (isJust (stateCurrentPlayer state)) $ return ()
let builder = stateBuilder state
playerID' = stateCurrentPlayer state
playerID = assert (isJust playerID') $ fromJust playerID'
playerTable = statePlayers state
-- We assume it is a valid PlayerID!
player' = M.lookup playerID playerTable
player = assert (isJust player') $ fromJust player'
win <- _GUIWindow builder "window_player_init"
labelName <- _GUILabel builder "player_init_name"
labelSetText labelName $ playerName player
parent <- _GUIWindow builder "window2"
windowSetTransientFor win parent
windowSetModal win True
widgetShow win
_GUICancelPlayerInit :: IORef State -> IO ()
_GUICancelPlayerInit state' = do
state <- readIORef state'
let builder = stateBuilder state
win <- _GUIWindow builder "window_player_init"
widgetHide win
_GUINewGameStart :: IORef State -> IO ()
_GUINewGameStart state' = do
state <- readIORef state'
let builder = stateBuilder state
win <- _GUIWindow builder "dialog_new_game"
widgetHide win
_GUICollectPlayerNames :: IORef State -> IO [String]
_GUICollectPlayerNames state' = do
state <- readIORef state'
let builder = stateBuilder state
getNameFunc idx = do
let entryName = "new_game_player_" ++ show idx
entry <- _GUIEntry builder entryName
entryGetText entry
names = map getNameFunc [1..maxPlayers]
names' <- sequence names
return $ filter ("" /=) names'
_GUICancelNewGame :: IORef State -> IO ()
_GUICancelNewGame state' = do
state <- readIORef state'
let builder = stateBuilder state
dialog <- _GUIWindow builder "dialog_new_game"
widgetHide dialog
_GUIEnterDoubleJeopardy :: IORef State -> IO ()
_GUIEnterDoubleJeopardy state' = do
_GUIFrobGameBoard state' "screen_doublejeopardy"
-- Manage Sensitivity
_GUISensitivityOff state' AdminJItemTable
_ <- timeoutAdd (doubleJeopardyCB state') 1000
return ()
-- Displays the query screen on the game board.
_GUIEnterQuery :: IORef State -> Bool -> IO ()
_GUIEnterQuery state' _ = do
state <- readIORef state'
assert (isJust (stateCurrentJItem state)) $ return ()
-- Extract JItem data.
let builder = stateBuilder state
jdata = stateJData state
_jitem = stateCurrentJItem state
(category, jID) = assert (isJust _jitem) $ fromJust _jitem
jitem' = M.lookup (category, jID) (jdataTable_ jdata)
jitem = assert (isJust jitem') $ fromJust jitem'
questionBS = jitemQuestion_ jitem
answerBS = jitemAnswer_ jitem
-- Reset.
clearCurrentPlayer builder
-- Convert image data into Pixbufs.
questionPB' <- byteStringToPixbuf questionBS
answerPB' <- byteStringToPixbuf answerBS
assert (isJust questionPB' && isJust answerPB') $ return ()
let answerPB = assert (isJust answerPB') $ fromJust answerPB'
questionPB = assert (isJust questionPB') $ fromJust questionPB'
-- Load images into widgets.
-- gameBoard <- _GUIWindow builder "game_board"
img <- _GUIImage builder "jitem_answer"
imgPreview <- _GUIImage builder "admin_question_preview"
imageSetFromPixbuf img answerPB
imageSetFromPixbuf imgPreview questionPB
-- Update Category name.
categoryLabel <- _GUILabel builder "query_category_name"
let categoryIndex = categoryIdx category
categoryName = jdataCategories_ (stateJData state) !! categoryIndex
categoryNameEscaped = escapeMarkup categoryName
labelSetMarkup categoryLabel $
"<span foreground='white' size='x-large' weight='bold'>"
++ categoryNameEscaped ++ "</span>"
-- Display query screen.
_GUIFrobGameBoard state' "queryscreen"
newState <- readIORef state'
-- Disable JItem table
_GUISensitivityOff state' AdminJItemTable
-- Add timeout handler
handlerId <- timeoutAdd (_STMGameQueryTimeout state'
(category, jID)) timeoutQuery
writeIORef state' $ newState { stateTimeoutHandler = Just handlerId }
logMsg' state' $ "Query: " ++ show (category, jID)
-- Change the color of the card defined by CATEGORY and PRICE.
_GUIDisableJItemCard :: IORef State ->
(Category, Price) -> PlayerID -> IO ()
_GUIDisableJItemCard state' (category, price) player = do
state <- readIORef state'
let builder = stateBuilder state
cardBoxName = cardContainerPrefix ++ category ++ show price
color = if player == -1
then colorCardBg'
else colorPlayers' !! (fromIntegral player - 1)
cardBox <- _GUIEventBox builder cardBoxName
widgetModifyBg cardBox StateNormal color
_GUIGameBuzzed' :: IORef State -> IO ()
_GUIGameBuzzed' state' = do
_GUIFrobGameBoard state' "queryscreen"
mapM_ (_GUISensitivityOn state') [ ButtonAnsweredCorrectly,
ButtonAnsweredWrong ]
_GUIGameSelectDataFile :: IORef State -> IO (Maybe FilePath)
_GUIGameSelectDataFile state' = do
state <- readIORef state'
let builder = stateBuilder state
parentWindow <- _GUIWindow builder "dialog_new_game"
res <- _GUIfileDialogOpen parentWindow
when (isJust res) $ do
label <- _GUILabel builder "data_file_to_load"
labelSetText label (fromJust res)
return res
_GUIGameSelectStateFile :: IORef State -> IO (Maybe FilePath)
_GUIGameSelectStateFile state' = do
state <- readIORef state'
let builder = stateBuilder state
parentWindow <- _GUIWindow builder "dialog_new_game"
res <- _GUIfileDialogSaveAs parentWindow
when (isJust res) $ do
label <- _GUILabel builder "statefile_to_use"
labelSetText label (fromJust res)
return res
newGamePlayerData :: IORef State -> Integer -> IO String
newGamePlayerData state' idx = do
state <- readIORef state'
let builder = stateBuilder state
entry <- _GUIEntry builder ("new_game_player_" ++ show idx)
entryGetText entry
newGameDataChanged :: IORef State -> IO ()
newGameDataChanged state' = do
state <- readIORef state'
let builder = stateBuilder state
sizes' = map (\ idx -> do
let pName = newGamePlayerData state' idx
fmap length pName)
[1..maxPlayers]
sizes <- sequence sizes'
buttonStart <- _GUIButton builder "button_start_game"
if (sum sizes > 0) && isJust (stateJDataFile state)
then do widgetSetSensitive buttonStart True
writeIORef state' $
state { statePhase = PhaseGamePrepared }
else do widgetSetSensitive buttonStart False
writeIORef state' $
state { statePhase = PhasePreGame }
setLabelFg :: Builder -> String -> Color -> IO ()
setLabelFg builder name color = do
label <- _GUILabel builder name
widgetModifyFg label StateNormal color
setPlayerColors :: Builder -> [Color] -> IO ()
setPlayerColors builder colors =
mapM_ (\ (color, i) -> do
let labelPlayer = "label_player" ++ show i
labelPlayerPoints =
"label_points_player" ++ show i
setLabelFg builder labelPlayer color
setLabelFg builder labelPlayerPoints color) $
zip colors ([1..] :: [Int])
setPlayerName :: Builder -> PlayerID -> Maybe Player -> IO ()
setPlayerName builder playerID player = do
label <- _GUILabel builder $ "label_player" ++ show playerID
if isJust player
then do let pName = playerNameEscaped (fromJust player)
labelSetMarkup label $
"<span weight='bold' size='x-large'>" ++ pName ++ "</span>"
-- foreground='white'
else labelSetMarkup label ""
setPlayerPoints :: Builder -> PlayerID -> Maybe Integer -> IO ()
setPlayerPoints builder playerID points = do
label <- _GUILabel builder $ "label_points_player" ++ show playerID
if isJust points
then labelSetMarkup label $
"<span weight='bold' size='x-large'>" ++
show (fromJust points) ++ "</span>"
-- foreground='white'
else labelSetMarkup label ""
setCategoryInfo :: Builder -> Integer -> String -> IO ()
setCategoryInfo builder idx _category = do
-- This is a hack. It makes sure that the Game board is not
-- misaligned in case some categories are unnamed.
let category' = if null _category then " " else _category
category = escapeMarkup category'
label <- _GUILabel builder $ "label_category" ++ show idx
labelSetMarkup label $
"<span size='xx-large' foreground='white' weight='bold'>"
++ category ++ "</span>"
addCategoryInfo :: IORef State -> IO ()
addCategoryInfo state' = do
state <- readIORef state'
let builder = stateBuilder state
jdata = stateJData state
categories = jdataCategories_ jdata
mapM_ (uncurry (setCategoryInfo builder)) $
zip [1..] categories
addPlayerInfo :: IORef State -> IO ()
addPlayerInfo state' = do
state <- readIORef state'
let players = statePlayers state
playerIDs = M.keys players
pointsMap = statePoints state
builder = stateBuilder state
-- Add new info
mapM_ (\ idx -> do
let player = M.lookup idx players
points = M.lookup idx pointsMap
setPlayerName builder idx player
setPlayerPoints builder idx points) playerIDs
-- Setup point table in State such that for every player the points
-- will be set to zero.
initPointTable :: IORef State -> IO ()
initPointTable state' = do
state <- readIORef state'
let players = statePlayers state
playerIDs = M.keys players
newPoints = foldr (\ idx pointTable ->
M.insert idx 0 pointTable)
M.empty playerIDs
writeIORef state' $ state { statePoints = newPoints }
playerNameEscaped :: Player -> String
playerNameEscaped player = escapeMarkup (playerName player)
printPlayers :: IORef State -> IO ()
printPlayers state' = do
state <- readIORef state'
let playerMap = statePlayers state
playerIDs = M.keys playerMap
logInfo state "Players:"
mapM_ (\ pID ->
let player' = M.lookup pID playerMap
player = assert (isJust player') $ fromJust player'
pName = playerName player
in logInfo state $ "Player " ++ show pID ++ ": " ++ pName)
playerIDs
_GUIEnterGame :: IORef State -> IO ()
_GUIEnterGame state' = do
-- Reset card colors and player/points info.
_GUIResetGameBoard state'
state <- readIORef state'
let builder = stateBuilder state
writeIORef state' $ state { statePhase = PhasePreQuery }
-- Hide Player Init Window
playerInit <- _GUIWindow builder "window_player_init"
widgetHide playerInit
_GUIFrobGameBoard state' "gamescreen"
logMsg state "Game created"
printPlayers state'
initPointTable state'
addPlayerInfo state'
addCategoryInfo state'
_GUISensitivityOn state' ButtonPickRandomPlayer
_GUISensitivityOff state' AdminJItemTable
_GUIRestoreGame :: IORef State -> IO ()
_GUIRestoreGame state' = do
state <- readIORef state'
writeIORef state' $ state { statePhase = PhasePreQuery }
-- Hide Player Init Window
_GUIFrobGameBoard state' "gamescreen"
logMsg state "Game restored"
let playerMap = statePlayers state
playerIDs = M.keys playerMap
logInfo state "Players:"
mapM_ (\ pID ->
let player' = M.lookup pID playerMap
player = assert (isJust player') $ fromJust player'
in logInfo state $
"Player " ++ show pID ++ ": " ++ playerNameEscaped player)
playerIDs
addPlayerInfo state'
addCategoryInfo state'
-- Updates the player/points data on the game board from the current
-- state.
_GUIUpdateGameBoard :: IORef State -> IO ()
_GUIUpdateGameBoard state' = do
state <- readIORef state'
let players = statePlayers state
playerIDs = M.keys players
pointsMap = statePoints state
builder = stateBuilder state
-- Add new info
mapM_ (\ idx -> do
let player = M.lookup idx players
points = M.lookup idx pointsMap
setPlayerName builder idx player
setPlayerPoints builder idx points) playerIDs
_GUIUpdateAdminPanelJData :: IORef State -> IO ()
_GUIUpdateAdminPanelJData state' = do
state <- readIORef state'
let builder = stateBuilder state
mapM_ (\ (name', suffix) -> do
let labelName = "label_category_" ++ suffix
name = escapeMarkup name'
label <- _GUILabel builder labelName
labelSetMarkup label $
"<span weight='bold'>" ++ name ++ "</span>") $
zip (jdataCategories_ (stateJData state)) _Categories
label <- _GUILabel builder "label_jdata_name"
labelSetMarkup label $
"<span weight='bold' size='large'>" ++ jdataName_ (stateJData state) ++ "</span>"
------------------------
-- Core State Machine --
------------------------
gameEnterQuery :: IORef State -> Category -> Price -> IO ()
gameEnterQuery state' category jID = do
state <- readIORef state'
let jdata = jdataTable_ (stateJData state)
jitemName = (category, jID)
jitem' = M.lookup jitemName jdata
jitem = assert (isJust jitem') $ fromJust jitem'
if jitemDouble_ jitem
then do -- We got a Double Jeopardy!
audioPlayOnce state' audioFileDouble
_GUIEnterDoubleJeopardy state'
newState <- readIORef state'
writeIORef state' $
newState { statePhase = PhasePreDoubleJeopardy,
stateCurrentJItem = Just jitemName,
stateTimeoutReached = False,
stateDoubleJeopardy = True }
else do -- Normal, i..e non-Double Jeopardy, JItem.
writeIORef state' $
state { statePhase = PhaseInQuery,
stateCurrentJItem = Just jitemName,
stateTimeoutReached = False }
_GUIEnterQuery state' False
audioPlayBackgroundFade state' audioFileTheme
queryAnswered :: IORef State -> Bool -> IO ()
queryAnswered state' correct = do
state <- readIORef state'
let builder = stateBuilder state
playerID = head (stateBuzzed state)
jitem' = stateCurrentJItem state
jitem = assert (isJust jitem') $ fromJust jitem'
-- Assemble a JAction
jaction = JAction { jactionPlayerID = playerID,
jactionCategory = fst jitem,
jactionPrice = snd jitem,
jactionCorrect = correct }
clearCurrentPlayer builder
executeAction state' jaction
newState <- readIORef state'
if correct
then queryAnsweredCorrectly state'
else if stateDoubleJeopardy newState
then queryAnsweredWrongDouble state'
else queryAnsweredWrong state'
-- Answer was correct.
queryAnsweredCorrectly :: IORef State -> IO ()
queryAnsweredCorrectly state' = do
state <- readIORef state'
-- Play music.
audioPlayOnce state' audioFileCorrect
-- Remove timeout handler for this query.
let handler' = stateTimeoutHandler state
currentP' = stateCurrentPlayer state
currentP = assert (isJust currentP') $ fromJust currentP'
forM_ handler' timeoutRemove
-- Clear other players who also buzzed
writeIORef state' $
state { stateBuzzed = [],
--stateNeedRandomPlayer = False,
stateTimeoutHandler = Nothing,
stateCurrentDecider = Just currentP }
-- Enter AdminShowAnswer
_STM AdminShowAnswer state'
-- Answer was wrong.
queryAnsweredWrong :: IORef State -> IO ()
queryAnsweredWrong state' = do
state <- readIORef state'
-- Play music.
audioPlayOnce state' audioFileWrong
let otherBuzzers = tail (stateBuzzed state)
if (not . null) otherBuzzers
-- Other players have buzzed.
then do let nextPlayerID = head otherBuzzers
players = statePlayers state
player' = M.lookup nextPlayerID players
player = assert (isJust player') $ fromJust player'
pName = playerName player
buzzerCB = _STMGameBuzzed' state' --nextPlayerID
logMsg state $ "Player " ++ pName ++ " has previously buzzed!"
logMsg state $ "Ask " ++ pName ++ " now for answer!"
-- Handle next buzzer in the queue.
_GUIGameBuzzed state' nextPlayerID player
_ <- timeoutAdd buzzerCB timeoutDisplayBuzzing
-- Frob sensitivity.
mapM_ (_GUISensitivityOff state') [ButtonAnsweredCorrectly,
ButtonAnsweredWrong]
-- Stay in PhaseQueryBuzzed.
newState <- readIORef state'
writeIORef state' $
newState { stateBuzzed = otherBuzzers,
stateCurrentPlayer = Just nextPlayerID }
-- No other buzzers pressed.
else do mapM_ (_GUISensitivityOff state') [ButtonAnsweredCorrectly,
ButtonAnsweredWrong]
if stateTimeoutReached state
-- Timeout reached while we were handling the previous
-- buzzer event. Time out now.
then queryTimeoutReached state' False
-- Continue normally.
else writeIORef state' $
state { statePhase = PhaseInQuery,
stateBuzzed = [] }
-- Answer was wrong during Double Jeopardy.
queryAnsweredWrongDouble :: IORef State -> IO ()
queryAnsweredWrongDouble state' = do
state <- readIORef state'
-- Play music.
audioPlayOnce state' audioFileWrong
-- Manage sensitivity.
mapM_ (_GUISensitivityOff state') [ButtonAnsweredCorrectly, ButtonAnsweredWrong]
mapM_ (_GUISensitivityOn state') [ButtonShowAnswer]
-- Remove timeout handler for the current double jeopardy. Note:
-- timeout handler might have been run+removed in the meantime!
let timeout' = stateTimeoutHandler state
forM_ timeout' timeoutRemove
-- Update state.
writeIORef state' $
state { statePhase = PhaseQueryTimeout, -- FIXME!! hack. Rename
-- this phase to something
-- more general.
--stateNeedRandomPlayer = False,
stateTimeoutHandler = Nothing,
stateBuzzed = [],
stateTimeoutReached = False }
_GUIAdminShowAnswer :: IORef State -> JItemCompiled -> IO ()
_GUIAdminShowAnswer state' jitem = do
state <- readIORef state'
let builder = stateBuilder state
answerBS = jitemQuestion_ jitem
answerPB' <- byteStringToPixbuf answerBS
let answerPB = assert (isJust answerPB') $ fromJust answerPB'
img <- _GUIImage builder "jitem_question"
imageSetFromPixbuf img answerPB
_GUIFrobGameBoard state' "answerscreen"
mapM_ (_GUISensitivityOff state') [ ButtonAnsweredCorrectly
, ButtonAnsweredWrong
, ButtonShowAnswer
]
mapM_ (_GUISensitivityOn state') [ ButtonContinue ]
adminShowAnswer :: IORef State -> IO ()
adminShowAnswer state' = do
state <- readIORef state'
let phase = statePhase state
jdata = stateJData state
currentJItem' = stateCurrentJItem state
currentJItem = assert (isJust currentJItem') $
fromJust currentJItem'
(category, jID) = currentJItem
jitem' = M.lookup (category, jID) (jdataTable_ jdata)
jitem = assert (isJust jitem') $ fromJust jitem'
-- FIXME: There's a bug here wrt sensitivity of the PickRandom button(?).
if phase == PhaseQueryTimeout -- && (stateDoubleJeopardy state))
then if stateDoubleJeopardy state
then writeIORef state' $ state { statePhase = PhaseShowAnswer }
else writeIORef state' $ state { statePhase = PhaseShowAnswerAfterTimeout }
else writeIORef state' $ state { statePhase = PhaseShowAnswer }
_GUIAdminShowAnswer state' jitem
hasPlayerAlreadyBuzzed :: State -> PlayerID -> Bool
hasPlayerAlreadyBuzzed state pID =
let matches = filter (pID ==) (stateBuzzed state)
in (not . null) matches
gameBuzzed :: IORef State -> PlayerID -> IO ()
gameBuzzed state' pID = do
state <- readIORef state'
if hasPlayerAlreadyBuzzed state pID
then logMsg state $ "Ignored buzzer event from player " ++ show pID
else gameBuzzed' state' pID
gameBuzzed' :: IORef State -> PlayerID -> IO ()
gameBuzzed' state' pID = do
state <- readIORef state'
let player' = lookupPlayer state pID
player = assert (isJust player') $ fromJust player'
pName = playerName player
buzzers = stateBuzzed state
buzzerCB = _STMGameBuzzed' state' --pID
logMsg state $ pName ++ " has pressed the button"
-- Keep track of buzzer press.
addBuzzEvent state' pID
if (not . null) buzzers
-- We have already received a previous buzzer press.
then logInfo state $ "too late (but remembered), "
++ playerName player
-- First buzzer press in this query phase. Change game
-- screen.
else do _GUIGameBuzzed state' pID player
logMsg state $ "Ask " ++ pName ++ " for answer!"
_ <- timeoutAdd buzzerCB timeoutDisplayBuzzing
newState <- readIORef state'
writeIORef state' $
newState { statePhase = PhaseQueryBuzzed,
stateCurrentPlayer = Just pID }
_GUIQueryTimeoutReached :: IORef State -> IO ()
_GUIQueryTimeoutReached state' = do
-- Display timeout hint.
setCurrentPlayerTimeout state'
mapM_ (_GUISensitivityOn state') [ButtonShowAnswer]
mapM_ (_GUISensitivityOff state') [ButtonAnsweredCorrectly,
ButtonAnsweredWrong]
queryTimeoutReached :: IORef State -> Bool -> IO ()
queryTimeoutReached state' isDouble = do
-- FIXME: restart music on wrong answer? Would be good, but I'm not
-- sure how to do it.
state <- readIORef state'
let currentDecider = stateCurrentDecider state
writeIORef state' $
state { stateTimeoutHandler = Nothing
, statePhase = PhaseQueryTimeout
, stateCurrentDecider = if isDouble then currentDecider else Nothing
, stateBuzzed = []
, stateTimeoutReached = True -- FIXME, correct?
}
audioSilenceBackground state'
audioPlayOnce state' audioFileTimeout
-- Create new JAction for this timeout event.
jaction <- createTimeoutJAction state'
executeAction state' jaction
newState <- readIORef state'
let actionLog = stateActionLog newState
writeIORef state' $
newState { stateActionLog = actionLog ++ [jaction] }
_GUIQueryTimeoutReached state'
createTimeoutJAction :: IORef State -> IO JAction
createTimeoutJAction state' = do
state <- readIORef state'
let jitem' = stateCurrentJItem state
jitem = assert (isJust jitem') $ fromJust jitem'
(category, price) = jitem
jactionNew = JAction { jactionPlayerID = -1,
jactionCategory = category,
jactionPrice = price,
jactionCorrect = False }
return jactionNew
adminNewGameStart :: IORef State -> IO ()
adminNewGameStart state' = do
state <- readIORef state'
let builder = stateBuilder state
dialog <- _GUIWindow builder "dialog_new_game"
-- Assumed for (PhaseGamePrepared, AdminNewGameStart):
-- stateJDataFile is Just a filename, (wrong: stateplayer contains a
-- non-zero list of uninitialized players.)
let jdataFile' = stateJDataFile state
filename = assert (isJust jdataFile') $ fromJust jdataFile'
playerNames <- _GUICollectPlayerNames state'
res <- loadJData state' filename
if res
then do let playerMap = createPlayerMap playerNames
uninitPlayer' = nextUninitPlayer playerMap
uninitPlayer = assert (isJust uninitPlayer') $
fromJust uninitPlayer'
uninitPlayerID = fst uninitPlayer
_GUIUpdateAdminPanelJData state'
_GUINewGameStart state'
-- Set current phase to Player Initialization, record the
-- player which is about to become initialized next.
newState <- readIORef state'
writeIORef state' $
newState { statePhase = PhasePlayerInit,
statePlayers = playerMap,
stateCurrentPlayer = Just uninitPlayerID }
-- Execute AdminPlayerInit action.
_STM AdminPlayerInit state'
else do logErr state "loading JData failed!"
_GUIError dialog "Jeopardy Error" "Failed to load JData file"
debugMsg :: IORef State -> String -> IO ()
debugMsg state' msg' = do
state <- readIORef state'
when (stateDebug state) $ do
let msg = "[DEBUG: " ++ msg' ++ "]"
logErr state msg
-- Being in STATE', process ACTION.
_STM :: JeopardyAction -> IORef State -> IO ()
_STM action state' = do
state <- readIORef state'
let builder = stateBuilder state
phase = statePhase state
-- Debugging.
debugMsg state' $
"STM (phase = " ++ show phase ++ ", action = " ++ show action ++ ")"
case action of
AdminGameNew -> do
when (phase /= PhasePreGame) $
-- Game already running.
_GUICancelGame state'
-- Create new 'empty' game state.
-- Show new game board, etc.
_GUIGameNew state'
AdminGameStop -> do
let reallyStopMsg = "Game already running. Sure you want to stop game?"
if phase /= PhasePreGame
then do adminWin <- _GUIWindow builder "window2"
res <- _GUIAskOkCancel adminWin "Confirmation required" reallyStopMsg
when res $ stopGame state'
else stopGame state'
AdminGameQuit -> do
-- FIXME: To do.
-- if phase /= PhasePreGame
-- then return () -- display really-quit-game-window?
-- else return ()
jeopardyAdminGameQuit state'
_GUIQuit state'
AdminHelpAbout ->
_GUIShowAbout state'
AdminNewGameSelectDataFile ->
assert (phase == PhaseGamePrepared || phase == PhasePreGame) $ do
filename <- _GUIGameSelectDataFile state'
when (isJust filename) $
-- Save new data filename in state.
writeIORef state' $ state { stateJDataFile = filename }
-- Recheck sensitity of 'Start' button
newGameDataChanged state'
AdminNewGameSelectStateFile ->
assert (phase == PhaseGamePrepared || phase == PhasePreGame) $ do
filename <- _GUIGameSelectStateFile state'
when (isJust filename) $
writeIORef state' $ state { stateStateFile = filename }
newGameDataChanged state'
AdminRestoreGame -> assert (phase == PhaseNothing) $ do
_GUIUpdateAdminPanelJData state'
writeIORef state' $ state { statePhase = PhaseGameRestored }
_STM PrepareQuery state'
AdminNewGameStart ->
assert (phase == PhaseGamePrepared && isJust (stateJDataFile state)) $
adminNewGameStart state'
-- The New Game Preparation Dialog has been cancelled.
AdminNewGameCancel ->
_GUICancelNewGame state'
AdminGameEnter -> assert (phase == PhasePlayerInit) $ do
audioPlayOnce state' audioFileStart
writeIORef state' $
state { statePhase = PhasePreQuery,
stateCurrentPlayer = Nothing }
saveState state'
_GUIEnterGame state'
logMsg state "Begin by picking a random player"
-- Initialize next uninitialized player.
AdminPlayerInit -> assert (phase == PhasePlayerInit || phase == PhasePreGame) $ do
let player' = nextUninitPlayer (statePlayers state)
if isNothing player'
-- All players initialized, enter game mode.
then _STM AdminGameEnter state'
-- One more to go.
else do let playerID = fst (fromJust player')
writeIORef state' $
state { stateCurrentPlayer = Just playerID }
_GUIInitPlayer state'
AdminCancelPlayerInit -> assert (phase == PhasePlayerInit) $ do
_GUICancelPlayerInit state'
writeIORef state' $ state { statePhase = PhasePreGame
, stateJDataFile = Nothing
, stateJData = emptyJData }
AdminPickRandomPlayer -> assert (phase == PhasePreQuery) $ do
let players = statePlayers state
playerIDs = M.keys players
playersN = length playerIDs
(r', newGen) = random (stateRandom state) :: (Int, StdGen)
r = r' `mod` playersN
randomID = playerIDs !! r
randomPlayer' = M.lookup randomID players
randomPlayer = assert (isJust randomPlayer') $ fromJust randomPlayer'
-- Update PRNG.
writeIORef state' $ state { stateRandom = newGen,
stateCurrentDecider = Just randomID }
-- Frob game window to show a 'Picking Random Player...'
-- message.
_GUIFrobGameBoard state' "randomscreen"
_ <- timeoutAdd (randomPlayerCB state' randomPlayer) timeoutRandomCB1
logMsg state $
"Randomly picked: " ++ playerName randomPlayer
mapM_ (_GUISensitivityOff state') [ButtonPickRandomPlayer]
GameQueryTimeout -> assert (phase == PhaseInQuery
|| phase == PhaseInDoubleJeopardy
|| phase == PhaseQueryBuzzed) $ do
logMsg state "Timeout reached!"
case phase of
PhaseQueryBuzzed ->
-- Remember timeout, but don't do anything now. This might
-- be handled later when all players answer the query wrong.
writeIORef state' $
state { stateTimeoutReached = True, stateTimeoutHandler = Nothing }
PhaseInQuery ->
-- Timeout reached without any buzzing activity. Handle the
-- timeout now.
queryTimeoutReached state' False
PhaseInDoubleJeopardy ->
queryTimeoutReached state' True
_ -> assert False $ return ()
GameEnterQuery category jID ->
assert (phase == PhasePreQuery) $
gameEnterQuery state' category jID
DigitPressed pID -> do
debugMsg state' $ "Button received: " ++ show pID
when ((phase == PhaseInQuery)
|| (phase == PhaseInDoubleJeopardy)
|| (phase == PhaseQueryBuzzed)) $
_STM (GameBuzzed pID) state'
GameBuzzed pID -> assert (phase == PhaseInQuery
|| phase == PhaseInDoubleJeopardy
|| phase == PhaseQueryBuzzed) $
if phase == PhaseInDoubleJeopardy
then do let decider' = stateCurrentDecider state
decider = assert (isJust decider') $ fromJust decider'
pMap = statePlayers state
player' = M.lookup pID pMap
player = assert (isJust player') $ fromJust player'
pName = playerName player
-- Only allow the 'current player' to buzz during the
-- Double Jeopardy.
logMsg state $ pName ++ " has pressed the button"
when (pID == decider) $ gameBuzzedDoubleJeopardy state'
else gameBuzzed state' pID
QueryAnswered correct -> assert (phase == PhaseQueryBuzzed) $
queryAnswered state' correct
PrepareQuery -> assert (phase == PhaseGamePrepared
|| phase == PhasePostQuery
|| phase == PhaseGameRestored) $ do
logMsg state "Waiting for query choice"
-- stateNeedRandomPlayer is False if the last answer given was
-- correct.
if isNothing (stateCurrentDecider state)
then do _GUISensitivityOn state' ButtonPickRandomPlayer
logMsg state "Pick random player"
else do _GUISensitivityOn state' AdminJItemTable
let pMap = statePlayers state
decider' = stateCurrentDecider state
decider = assert (isJust decider') $ fromJust decider'
player' = M.lookup decider pMap
player = assert (isJust player') $ fromJust player'
pName = playerName player
logMsg state $ "Player '" ++ pName ++ "' may decide!"
writeIORef state' $ state { statePhase = PhasePreQuery,
stateDoubleJeopardy = False}
if phase == PhaseGameRestored
then _GUIRestoreGame state'
else saveState state'
GameOver -> assert (phase == PhasePostQuery) $ do
audioPlayBackground state' audioFileClosing
logMsg state "Game over!"
rankingScreenUpdate state'
_GUIFrobGameBoard state' "box_ranking"
AdminShowAnswer -> assert (phase == PhaseQueryTimeout
|| phase == PhaseQueryBuzzed) $ do
assert (isJust (stateCurrentJItem state)) $ return ()
adminShowAnswer state'
AdminContinue -> assert (phase == PhaseShowAnswerAfterTimeout
|| phase == PhasePreDoubleJeopardy
|| phase == PhaseShowAnswer) $
if phase == PhasePreDoubleJeopardy
then gameContinueDoubleJeopardy state'
else gameContinue state'
_ -> return ()
stopGame :: IORef State -> IO ()
stopGame state' = do
state <- readIORef state'
-- FIXME: Disable all running timeouts.
audioSilenceBackground state'
let handler = stateTimeoutHandler state
forM_ handler timeoutRemove
_GUIStop state'
gameBuzzedDoubleJeopardy :: IORef State -> IO ()
gameBuzzedDoubleJeopardy state' = do
audioSilenceBackground state'
audioPlayOnce state' audioFileBuzzer
state <- readIORef state'
let currentP' = stateCurrentDecider state
currentP = assert (isJust currentP') $ fromJust currentP'
playerTable = statePlayers state
player' = M.lookup currentP playerTable
player = assert (isJust player') $ fromJust player'
buzzerCB = _STMGameBuzzed' state'
_GUIGameBuzzed state' currentP player
_ <- timeoutAdd buzzerCB timeoutDisplayBuzzing
addBuzzEvent state' currentP
newState <- readIORef state'
writeIORef state' $
newState { statePhase = PhaseQueryBuzzed,
stateCurrentPlayer = Just currentP }
gameContinueDoubleJeopardy :: IORef State -> IO ()
gameContinueDoubleJeopardy state' = do
audioPlayBackgroundFade state' audioFileTheme
_GUISensitivityOff state' ButtonContinue
_GUIEnterQuery state' True
state <- readIORef state'
writeIORef state' $
state { statePhase = PhaseInDoubleJeopardy }
gameContinue :: IORef State -> IO ()
gameContinue state' = do
state <- readIORef state'
let phase = statePhase state
jitemsTotal = M.size (jdataTable_ (stateJData state))
jitemsDone = length (collectJItemsProcessed state)
gameOver = jitemsDone == jitemsTotal
-- Enable ButtonPickRandomPlayer in case we need it.
when (phase == PhaseShowAnswerAfterTimeout && not gameOver) $
_GUISensitivityOn state' ButtonPickRandomPlayer
_GUIAdminContinue state'
newState <- readIORef state'
if gameOver
then do writeIORef state' $
newState { statePhase = PhasePostQuery
, stateCurrentJItem = Nothing }
_STM GameOver state'
else do writeIORef state' $
newState { statePhase = PhasePostQuery
, stateCurrentPlayer = Nothing
, stateCurrentJItem = Nothing }
_STM PrepareQuery state'
_GUIRankingScreenUpdate :: Builder ->
PlayerID -> PlayerName -> String -> Integer -> IO ()
_GUIRankingScreenUpdate builder pID name' points idx = do
let name = escapeMarkup name'
nameLabel <- _GUILabel builder $ "label_ranking_player" ++ show idx
pointsLabel <- _GUILabel builder $ "label_ranking_points_player" ++ show idx
when (pID >= 0) $ do
let pColor = colorPlayers !! (fromIntegral pID - 1)
widgetModifyFg nameLabel StateNormal pColor
widgetModifyFg pointsLabel StateNormal pColor
labelSetMarkup nameLabel $ "<span weight='bold' font='30'>" ++ name ++ "</span>"
labelSetMarkup pointsLabel $ "<span weight='bold' font='30'>" ++ points ++ "</span>"
rankingScreenUpdate :: IORef State -> IO ()
rankingScreenUpdate state' = do
state <- readIORef state'
let builder = stateBuilder state
players = statePlayers state
playerIDs = M.keys players
pointsMap = statePoints state
clearPointsFunc = _GUIRankingScreenUpdate builder (-1) "" ""
setPointsFunc pId = do
let player' = M.lookup pId players
player = assert (isJust player') $ fromJust player'
pName = playerName player
points' = M.lookup pId pointsMap
points = assert (isJust points') $ fromJust points'
_GUIRankingScreenUpdate builder pId pName (show points) pId
-- Clear everything first.
mapM_ clearPointsFunc [1..maxPlayers]
-- Add player/points data.
mapM_ setPointsFunc playerIDs
playerInitialBuzzer :: IORef State -> EventM EKey ()
playerInitialBuzzer state' = do
s <- eventKeyName
when (isDigit' (glibToString s)) $ do
state <- liftIO $ readIORef state'
let playerID' = stateCurrentPlayer state
playerID = assert (isJust playerID') $
fromJust playerID'
playerMap = statePlayers state
playerMap' = associatePlayerBuzzer
playerMap playerID (glibToString s)
liftIO $ do writeIORef state' $
state { statePlayers = playerMap' }
audioPlayOnce state' audioFileCorrect
_STM AdminPlayerInit state'
resetSensitivity :: IORef State -> IO ()
resetSensitivity state' = do
mapM_ (_GUISensitivityOff state') [ButtonAnsweredCorrectly,
ButtonAnsweredWrong,
ButtonShowAnswer,
ButtonPickRandomPlayer,
ButtonContinue]
mapM_ (_GUISensitivityOn state' . uncurry ButtonJItem) cardIndex'
_GUISensitivityOff state' AdminJItemTable
_GUIClearGameData :: IORef State -> IO ()
_GUIClearGameData state' = do
state <- readIORef state'
let builder = stateBuilder state
labelsToClear = "label_jdata_name" :
(map (\ n -> "label_category" ++ show n) ([1..5] :: [Int]) ++
map (\ c -> "label_category_" ++ (c : "")) ['a'..'e'])
-- Clear labels.
mapM_ (\ name -> do label <- _GUILabel builder name
labelSetMarkup label "")
labelsToClear
-- Reset Pictures.
let picturesToClear = ["admin_question_preview", "jitem_answer"]
mapM_ (\ name -> do image <- _GUIImage builder name
imageClear image)
picturesToClear
_GUIStop :: IORef State -> IO ()
_GUIStop state' = do
_GUIClearGameData state'
resetSensitivity state'
_GUIFrobGameBoard state' "box_boot"
state <- readIORef state'
emptyMVar <- newEmptyMVar
writeIORef state' $
state { stateLogger = emptyMVar,
statePhase = PhasePreGame,
statePlayers = M.empty,
stateActionLog = [],
statePoints = M.empty,
stateBuzzed = [],
stateJData = emptyJData,
stateJDataFile = Nothing,
stateStateFile = Nothing,
stateCurrentPlayer = Nothing,
stateCurrentDecider = Nothing,
stateCurrentJItem = Nothing,
stateTimeoutHandler = Nothing,
stateTimeoutReached = False,
stateDoubleJeopardy = False }
-- returns Nothing if all players are initialized
nextUninitPlayer :: PlayerMap -> Maybe (PlayerID, Player)
nextUninitPlayer pMap =
let playerUninit = isNothing . playerBuzzer
uninitPlayers = M.filter playerUninit pMap
in if M.null uninitPlayers
then Nothing
else let key = (head . M.keys) uninitPlayers
player' = M.lookup key uninitPlayers
player = assert (isJust player') $ fromJust player'
in Just (key, player)
createPlayerMap :: [String] -> PlayerMap
createPlayerMap playerNames =
foldr (\ (idx, name) playerMap ->
M.insert idx Player { playerName = name,
playerBuzzer = Nothing } playerMap)
M.empty $ zip [1..] playerNames
-- pID has to be a valid Player ID.
associatePlayerBuzzer :: PlayerMap ->
PlayerID -> PlayerBuzzer -> PlayerMap
associatePlayerBuzzer pMap pID pBuzzer =
let player' = M.lookup pID pMap
player = assert (isJust player') $ fromJust player'
playerNew = player { playerBuzzer = Just pBuzzer }
in M.insert pID playerNew pMap
addBuzzEvent :: IORef State -> PlayerID -> IO ()
addBuzzEvent state' player = do
state <- readIORef state'
writeIORef state' $ state { stateBuzzed = stateBuzzed state ++ [player] }
_STMGameQueryTimeout :: IORef State -> (Category, Price) -> IO Bool
_STMGameQueryTimeout state' _ = do
_STM GameQueryTimeout state'
return False
---------------------------------------
-- Game Independent Helper Functions --
---------------------------------------
------------------------------------
-- Game Specific Helper Functions --
------------------------------------
-- Lookup Player by it's Player ID.
lookupPlayer :: State -> PlayerID -> Maybe Player
lookupPlayer state pID =
let players = statePlayers state
in M.lookup pID players
-- Given a PlayerMap, lookup a player by it's PlayerBuzzer ID.
lookupPlayerByBuzzer :: PlayerMap -> PlayerBuzzer -> Maybe Player
lookupPlayerByBuzzer players buzzer =
if isDigit' buzzer
then let playerFilter player =
let pBuz = playerBuzzer player in
pBuz == Just buzzer
playersMatched = M.filter playerFilter players
in if M.size playersMatched == 1
then let keys = M.keys playersMatched
in M.lookup (head keys) playersMatched
else Nothing
else Nothing
-- Write log message to Admin Control Panel.
logMsg :: State -> String -> IO ()
logMsg state string = do
logInfo state $ "LOG: " ++ string
let builder = stateBuilder state
-- Rerieve widget
textview <- _GUITextView builder "protocol"
textbuffer <- textViewGetBuffer textview
-- Add message.
iter <- textBufferGetEndIter textbuffer
textBufferInsert textbuffer iter $ string ++ "\n"
-- Scroll Text View.
textview' <- _GUITextView builder "protocol"
mark <- textViewGetBuffer textview' >>= textBufferGetInsert
textViewScrollToMark textview' mark 0.2 (Just (0, 0.5))
logMsg' :: IORef State -> String -> IO ()
logMsg' state' string = do
state <- readIORef state'
logMsg state string
randomPlayerCB :: IORef State -> Player -> IO Bool
randomPlayerCB state' player = do
audioPlayOnce state' audioFileRandom
state <- readIORef state'
let pID = playerGetID state player
builder = stateBuilder state
pName = playerNameEscaped player
pColor = colorPlayers !! (fromIntegral pID - 1)
text = pName
_ <- timeoutAdd (randomPlayerCB2 state') timeoutRandomCB2
label <- _GUILabel builder "random_player_name"
widgetModifyFg label StateNormal pColor
labelSetMarkup label $
"<span weight='bold' font='40'>" ++
text ++ "</span>"
return False -- Destroy this timeout handler.
randomPlayerCB2 :: IORef State -> IO Bool
randomPlayerCB2 state' = do
state <- readIORef state'
let builder = stateBuilder state
-- Frob game window back
label <- _GUILabel builder "random_player_name"
labelSetText label ""
_GUIFrobGameBoard state' "gamescreen"
_GUISensitivityOn state' AdminJItemTable
return False -- Destroy this timeout handler.
_GUIExecuteActionTimeout :: IORef State -> JAction -> IO ()
_GUIExecuteActionTimeout state' action = do
let category = jactionCategory action
price = jactionPrice action
jitem = (category, price)
_GUIDisableJItemCard state' jitem (-1)
_GUISensitivityOff state' (ButtonJItem category price)
_GUIExecuteActionAnswer :: IORef State -> JAction -> IO ()
_GUIExecuteActionAnswer state' action = do
state <- readIORef state'
let category = jactionCategory action
price = jactionPrice action
jitem = (category, price)
pID = jactionPlayerID action
_GUIDisableJItemCard state' jitem pID
_GUIUpdateGameBoard state'
_GUISensitivityOff state' (ButtonJItem category price)
let playerTable = statePlayers state
playerID = jactionPlayerID action
if playerID >= 0
then do let player' = M.lookup playerID playerTable
player = assert (isJust player') $ fromJust player'
pName = playerName player
correct = if jactionCorrect action
then "correct"
else "wrong"
logMsg state $
"User " ++ pName ++ " gave " ++ correct ++ " answer."
else logMsg state "Timeout reached. FIXME."
isJItemDoubleJeopardy :: State -> (Category, Price) -> Bool
isJItemDoubleJeopardy state (category, price) =
let jdatatable = jdataTable_ (stateJData state)
jitem' = M.lookup (category, price) jdatatable
jitem = assert (isJust jitem') $ fromJust jitem'
in jitemDouble_ jitem
computeNewPoints :: Integer -> Integer -> Bool -> Bool -> Integer
computeNewPoints oldPoints price isDouble isCorrect =
if isCorrect
then oldPoints + (if isDouble then price * 2 else price)
else oldPoints - price
executeAction :: IORef State -> JAction -> IO ()
executeAction state' action = do
state <- readIORef state'
let player = jactionPlayerID action
if player >= 0
-- The action is of type 'Player X has answered Y
-- correctly/wrong'.
then do let category = jactionCategory action
price = jactionPrice action
price' = jidToPrice price
pointTable = statePoints state
oldPoints' = M.lookup player pointTable
oldPoints = assert (isJust oldPoints') $
fromJust oldPoints'
isDouble = isJItemDoubleJeopardy state (category, price)
isCorrect = jactionCorrect action
newPoints = computeNewPoints oldPoints price' isDouble isCorrect
newPointTable = M.insert player newPoints pointTable
writeIORef state' $
state { statePoints = newPointTable,
stateActionLog = stateActionLog state ++ [action] }
_GUIExecuteActionAnswer state' action
-- It's a 'Timeout action'
else do writeIORef state' $
state { stateActionLog = stateActionLog state ++ [action] }
_GUIExecuteActionTimeout state' action
executeActionLog :: IORef State -> [JAction] -> IO ()
executeActionLog state' = mapM_ (executeAction state')
_STMGameBuzzed' :: IORef State -> IO Bool
_STMGameBuzzed' state' = do
_GUIGameBuzzed' state'
-- Only need to modify sensitivity if .. FIXME! not required?
mapM_ (_GUISensitivityOn state') [ButtonAnsweredCorrectly, ButtonAnsweredWrong]
return False -- Destroy this timeout handler.
-- Convert a Player into it's PlayerID, based on the data contained in
-- State.
playerGetID :: State -> Player -> PlayerID
playerGetID state player =
let pName = playerName player
maplist = M.toList (statePlayers state)
filterFunc (_, val) = playerName val == pName
matches = filter filterFunc maplist
in fst (head matches)
-- Callback for events of buzzer presses.
eventBuzzerPressed' :: IORef State -> EventM EKey ()
eventBuzzerPressed' state' = do
state <- liftIO $ readIORef state'
s <- eventKeyName
let player = lookupPlayerByBuzzer (statePlayers state) (glibToString s)
when (isJust player) $ do
-- We have retrieved a valid buzzer press.
let playerID = playerGetID state (fromJust player)
liftIO $ _STM (DigitPressed playerID) state'
loadJData :: IORef State -> String -> IO Bool
loadJData state' filename = do
state <- readIORef state'
jdata' <- jdataImport filename
if isJust jdata'
then do let jdata = fromJust jdata'
logMsg state $
"Loaded JData from file '" ++ filename ++ "'" ++
"[name = '" ++ jdataName_ jdata ++ "']"
let newState = state { stateJData = jdata,
stateJDataFile = Just filename }
writeIORef state' newState
return True
else return False
-- Quit the game.
jeopardyAdminGameQuit :: IORef State -> IO ()
jeopardyAdminGameQuit = audioSilenceBackground
-- Initialize PRNG.
randomGenInitializer :: IO Int
randomGenInitializer =
getStdRandom (randomR (1, 100))
-- Main Jeopardy function.
jeopardyMain :: IORef State -> Maybe FilePath -> IO ()
jeopardyMain state' stateFile = do
state <- readIORef state'
let builder = stateBuilder state
logMsg state "Jeopardy running"
-- Show Game Board & Admin Panel.
_GUIWindow builder "game_board" >>= widgetShowAll
_GUIWindow builder "window2" >>= widgetShowAll
res <- if isJust stateFile
-- Restore game from state.
then do logMsg state $
"Restoring game from state file " ++
fromJust stateFile
-- Reset card colors and player/points info.
_GUIResetGameBoard state'
r <- loadStateFile state' (fromJust stateFile)
_STM AdminRestoreGame state'
return r -- True --r
else do logMsg state "Chose Game -> New to start a new game"
writeIORef state' $
state { statePhase = PhasePreGame }
return True
-- Enter GUI event loop
when res _GUIStart
-- Return a list of all JItem specifiers processed so far.
collectJItemsProcessed :: State -> [(Category, Price)]
collectJItemsProcessed state =
let jactions = stateActionLog state
in nub $ map (\ jaction -> (jactionCategory jaction,
jactionPrice jaction)) jactions
-- Initialize PRNG, Audio. Return a new ("vanilla") IORef State value.
initState :: GUICtx -> IO (IORef State)
initState guictx = do
randInit <- randomGenInitializer
audioState <- audioInit
logger <- newMVar ()
let state = State { stateLogger = logger
, stateAudio = audioState
, statePoints = M.empty
, stateRandom = mkStdGen randInit
, stateBuzzed = []
, stateBuilder = guictx
, stateJData = emptyJData
, statePhase = PhaseNothing
, stateJDataFile = Nothing
, stateStateFile = Nothing
, statePlayers = M.empty
, stateCurrentPlayer = Nothing
, stateCurrentDecider = Nothing
, stateCurrentJItem = Nothing
, stateTimeoutHandler = Nothing
, stateGameScreen = "box_boot"
, stateTimeoutReached = False
, stateDoubleJeopardy = False
, stateActionLog = []
, stateDebug = True }
newIORef state
-- Initialize game.
jeopardyInit :: IO (IORef State)
jeopardyInit = do
-- Initialize Gtk+
guictx <- _GUIInit
-- Read Glade file
state' <- initState guictx
_GUISetup state'
resetSensitivity state'
return state'
-------------------------
-- State Import/Export --
-------------------------
-- Write current game state to state file (contained in State).
saveState :: IORef State -> IO ()
saveState state' = do
state <- readIORef state'
let statefile = stateStateFile state
when (isJust statefile) $
let state_ = State_ { stateJDataFile_ = stateJDataFile state
, statePlayers_ = statePlayers state
, stateActionLog_ = stateActionLog state
, stateCurrentDecider_ = stateCurrentDecider state }
stateString = show state_
in writeFile (fromJust statefile) stateString
restoreState :: IORef State -> FilePath -> State_ -> IO Bool
restoreState state' stateFile statePers = do
state <- readIORef state'
-- Got state from disk
let actionLog = stateActionLog_ statePers
jdataFile' = stateJDataFile_ statePers
jdataFile = assert (isJust jdataFile') $ fromJust jdataFile'
players = statePlayers_ statePers
decider = stateCurrentDecider_ statePers
writeIORef state' $ state { stateJDataFile = jdataFile'
, stateStateFile = Just stateFile
, statePlayers = players
, stateCurrentDecider = decider }
-- Initialize Point Table.
initPointTable state'
res <- loadJData state' jdataFile
newState <- readIORef state'
if res
then do executeActionLog state' actionLog
if null actionLog
then do writeIORef state' $
newState { stateTimeoutReached = False } -- FIXME?
return True
else do let lastAction = last actionLog
pID = jactionPlayerID lastAction
if pID == (-1)
-- 'Timeout reached' was last action.
then do writeIORef state' $
newState { stateTimeoutReached = True }
return True
else do writeIORef state' $
newState { stateTimeoutReached = False }
-- The last action in a saved state
-- must be either a timeout or of type
-- 'Player pID answered correctly.
assert (jactionCorrect lastAction) $ return ()
return True
else do logErr newState "Failed to load JData File"
return False
--return res
-- Load game state from state file "stateFile". "state'" must be in
-- PhaseNothing.
loadStateFile :: IORef State -> FilePath -> IO Bool
loadStateFile state' stateFile = do
state <- readIORef state'
assert (statePhase state == PhaseNothing) $ return ()
content <- readFile stateFile
let statePers' = maybeRead content
if isJust statePers'
then do let statePers = fromJust statePers'
restoreState state' stateFile statePers
else return False
-----------
-- JData --
-----------
-- Import the JItem referenced by (CATEGORY, PRICE) from the directory
-- TMPDIR, store it in JDATA.
jitemImport :: FilePath -> (Category, Integer) ->
IO JDataCompiled -> IO JDataCompiled
jitemImport tmpDir (category, price) jdata = do
jdata' <- jdata
metaContent <- readFile $ tmpDir ++ "/jitem-" ++ category ++ show price
let meta' = maybeRead metaContent
meta = assert (isJust meta') $ fromJust meta'
isDouble = jitemMetaDouble meta
answer <- B.readFile $
tmpDir ++ "/jitem-" ++ category ++ show price
++ "-answer.png"
question <- B.readFile $
tmpDir ++ "/jitem-" ++ category ++ show price
++ "-question.png"
let jitem = JItemCompiled { jitemAnswer_ = answer,
jitemQuestion_ = question,
jitemDouble_ = isDouble }
newTable = M.insert (category, price)
jitem (jdataTable_ jdata')
return $ jdata' { jdataTable_ = newTable }
tarExtract :: FilePath -> FilePath -> IO Bool
tarExtract directory filename = do
res <- try (Tar.extract directory filename) :: IO (Either SomeException ())
case res of
Left e -> do putStrLn $
"Exception raised during Tar.extract: " ++ show e -- FIXME, logErr?
return False
Right _ -> return True
-- Read a .jdc (Jeopardy Data Compiled) file, convert it into a
-- JDataCompiled value.
jdataImport :: FilePath -> IO (Maybe JDataCompiled)
jdataImport filename =
withSystemTempDirectory "tmp-jeopardy.jdc"
(\ tmpDir -> do
-- Extract TAR archive into tmpDir
res <- tarExtract tmpDir filename
if res
then do meta <- readFile $ tmpDir ++ "/meta" -- Read/parse metadata file.
-- Import all the JItems.
jdataNew <- foldr (jitemImport tmpDir)
(return (read meta)) cardIndex'
return (Just jdataNew)
else return Nothing)
-----------------
-- Audio Layer --
-----------------
data AudioState_ = AudioState_ { backgroundPHs :: [ProcessHandle] }
type AudioState = MVar AudioState_
audioInit :: IO AudioState
audioInit =
newMVar AudioState_ { backgroundPHs = [] }
audioPlayOnce' :: State -> FilePath -> IO ThreadId
audioPlayOnce' state filename' =
forkIO $ do
filename <- getDataFileName ("Sounds/" ++ filename')
hDevNull <- openFile devNull ReadWriteMode
let cp = proc audioPlayer ["-q", filename]
result <- tryIOError (createProcess $ cp { close_fds = True,
std_in = UseHandle hDevNull,
std_out = UseHandle hDevNull,
std_err = UseHandle hDevNull })
ret <- case result of
Left _ -> return (ExitFailure 1)
Right (_, _, _, phandle) -> waitForProcess phandle
when (ret /= ExitSuccess) $
logErr state "Failed to spawn audio player"
hClose hDevNull
audioPlayOnce :: IORef State -> FilePath -> IO ()
audioPlayOnce state' filename = do
state <- readIORef state'
_ <- audioPlayOnce' state filename
return ()
audioPlayBackground' :: State -> FilePath -> [String] -> IO ()
audioPlayBackground' state filename' args = do
let audioState = stateAudio state
_ <- forkIO $ do
filename <- getDataFileName ("Sounds/" ++ filename')
hDevNull <- openFile devNull ReadWriteMode
let cp = proc audioPlayer (["-q", filename] ++ args)
(_, _, _, phandle) <- createProcess $ cp { close_fds = True,
std_in = UseHandle hDevNull,
std_out = UseHandle hDevNull,
std_err = UseHandle hDevNull}
audioState_ <- takeMVar audioState
let handles = backgroundPHs audioState_
handlesNew = handles ++ [phandle]
putMVar audioState $ audioState_ { backgroundPHs = handlesNew }
ret <- waitForProcess phandle
when (ret /= ExitSuccess) $
logErr state "Failed to spawn audio player"
hClose hDevNull
return ()
audioPlayBackground :: IORef State -> FilePath -> IO ()
audioPlayBackground state' filename = do
state <- readIORef state'
audioPlayBackground' state filename []
audioPlayBackgroundFade :: IORef State -> FilePath -> IO ()
audioPlayBackgroundFade state' filename = do
state <- readIORef state'
let args = ["vol", "0.2", "amplitude" ]
audioPlayBackground' state filename args
audioSilenceBackground' :: AudioState -> IO ()
audioSilenceBackground' audioState = do
audioState_ <- takeMVar audioState
let handles = backgroundPHs audioState_
mapM_ terminateProcess handles
putMVar audioState $ audioState_ { backgroundPHs = [] }
audioSilenceBackground :: IORef State -> IO ()
audioSilenceBackground state' = do
state <- readIORef state'
audioSilenceBackground' (stateAudio state)
----------
-- Main --
----------
-- Main function. Parses command line arguments, starts up the game.
main :: IO ()
main = do
args <- getArgs
state <- jeopardyInit
if length args == 1
then jeopardyMain state $ Just (head args)
else jeopardyMain state Nothing
| mtesseract/silverratio-jeopardy | src/jeopardy.hs | gpl-2.0 | 86,070 | 0 | 22 | 23,096 | 19,204 | 9,382 | 9,822 | 1,715 | 32 |
{-# OPTIONS_GHC -Wall -fwarn-tabs -Werror #-}
-------------------------------------------------------------------------------
-- |
-- Module : Window.Types
-- Copyright : Copyright (c) 2014 Michael R. Shannon
-- License : GPLv2 or Later
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : portable
--
-- Window module module types.
-------------------------------------------------------------------------------
module Window.Types
( Window(..)
) where
import Data.Word
data Window = Window
{ title :: String
, width :: Word
, height :: Word
} deriving(Eq, Show)
| mrshannon/trees | src/Window/Types.hs | gpl-2.0 | 650 | 0 | 8 | 126 | 70 | 48 | 22 | 9 | 0 |
module Logic.TextZipper where
import Prelude hiding (FilePath)
import Types.Base
import Data.Text.Zipper as Tz
replaceZipper :: Text -> b -> TextZipper Text
replaceZipper t = const $ Tz.textZipper [t] (Just 1)
| diegospd/pol | src/Logic/TextZipper.hs | gpl-3.0 | 213 | 0 | 8 | 33 | 72 | 41 | 31 | 6 | 1 |
{-|
Copyright : (c) Quivade, 2017
License : GPL-3
Maintainer : Jakub Kopański <[email protected]>
Stability : experimental
Portability : POSIX
This module provides FIRRTL Expr AST definitions.
|-}
module Language.FIRRTL.Syntax.Expr
( UnaryOp (..)
, BinaryOp (..)
, TernaryOp (..)
, Literal (..)
, Expr
, PolyTypedExpr
, TypedExpr
, ExprF (..)
, polytype
) where
import Language.FIRRTL.Annotations
import Language.FIRRTL.Syntax.Common
import Language.FIRRTL.Recursion
import Language.FIRRTL.Types (PolyType, Type)
data UnaryOp
= AndR | AsClock | AsSigned | AsUnsigned
| Cvt | Neg | Not | OrR | Xor | XorR
deriving Eq
data BinaryOp
-- | op expr expr
= Add | And | Cat | Div | DShl | DShr | Eq | Geq | Gt
| Leq | Lt | Mod | Mul | Neq | Or | Sub | Valid
-- | op expr int
| Head | Pad | Shl | Shr | Tail
deriving Eq
data TernaryOp = Bits | Mux
deriving Eq
-- | Firrtl literal value
data Literal
= Nat Int -- ^ natural integer
| UInt Int -- ^ unsigned integer
| SInt Int -- ^ signed integer
deriving Eq
data ExprF r
= Lit Literal -- ^ Ground Type or natural integer
| Ref Ident -- ^ reference to a node/var
-- moved to appropriate arity operations
-- | Valid r r
-- | Mux r r r
-- these are much more specific than mux and valid
| SubField r Ident
| SubAccess r r
| Unary UnaryOp r
| Binary BinaryOp r r
| Ternary TernaryOp r r r
deriving Eq
instance Functor ExprF where
fmap f (SubField e i) = SubField (f e) i
fmap f (Unary op e) = Unary op (f e)
fmap f (Binary op a b) = Binary op (f a) (f b)
fmap f (Ternary op a b c) = Ternary op (f a) (f b) (f c)
fmap _ (Lit l) = Lit l
fmap _ (Ref i) = Ref i
instance Foldable ExprF where
foldMap f (Lit l) = mempty
foldMap f (Ref id) = mempty
foldMap f (SubField p id) = f p `mappend` foldMap f (Ref id)
foldMap f (SubAccess p q) = f p `mappend` f q
foldMap f (Unary _ p) = f p
foldMap f (Binary _ p q) = f p `mappend` f q
foldMap f (Ternary _ p q r) = f p `mappend` f q `mappend` f r
instance Traversable ExprF where
-- traverse :: Functor f => (a -> f b) -> t a -> f (t b)
traverse g (Lit l) = pure $ Lit l
traverse g (Ref id) = pure $ Ref id
traverse g (SubField p id) = SubField <$> g p
<*> pure id
traverse g (SubAccess p q) = SubAccess <$> g p
<*> g q
traverse g (Unary op p) = Unary op <$> g p
traverse g (Binary op p q) = Binary op <$> g p
<*> g q
traverse g (Ternary op p q r) = Ternary op <$> g p
<*> g q
<*> g r
type Expr = Fix ExprF
type TypedExpr = AnnFix (Maybe Type) ExprF
type PolyTypedExpr = AnnFix PolyType ExprF
polytype :: PolyTypedExpr -> PolyType
polytype (Fix (AnnF ptype expr)) = ptype
| quivade/screwdriver | src/Language/FIRRTL/Syntax/Expr.hs | gpl-3.0 | 2,918 | 0 | 9 | 914 | 1,001 | 541 | 460 | 72 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Logging.Locations.List
-- 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)
--
-- Lists information about the supported locations for this service.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.locations.list@.
module Network.Google.Resource.Logging.Locations.List
(
-- * REST Resource
LocationsListResource
-- * Creating a Request
, locationsList
, LocationsList
-- * Request Lenses
, llXgafv
, llUploadProtocol
, llAccessToken
, llUploadType
, llName
, llFilter
, llPageToken
, llPageSize
, llCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.locations.list@ method which the
-- 'LocationsList' request conforms to.
type LocationsListResource =
"v2" :>
Capture "name" Text :>
"locations" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListLocationsResponse
-- | Lists information about the supported locations for this service.
--
-- /See:/ 'locationsList' smart constructor.
data LocationsList =
LocationsList'
{ _llXgafv :: !(Maybe Xgafv)
, _llUploadProtocol :: !(Maybe Text)
, _llAccessToken :: !(Maybe Text)
, _llUploadType :: !(Maybe Text)
, _llName :: !Text
, _llFilter :: !(Maybe Text)
, _llPageToken :: !(Maybe Text)
, _llPageSize :: !(Maybe (Textual Int32))
, _llCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LocationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'llXgafv'
--
-- * 'llUploadProtocol'
--
-- * 'llAccessToken'
--
-- * 'llUploadType'
--
-- * 'llName'
--
-- * 'llFilter'
--
-- * 'llPageToken'
--
-- * 'llPageSize'
--
-- * 'llCallback'
locationsList
:: Text -- ^ 'llName'
-> LocationsList
locationsList pLlName_ =
LocationsList'
{ _llXgafv = Nothing
, _llUploadProtocol = Nothing
, _llAccessToken = Nothing
, _llUploadType = Nothing
, _llName = pLlName_
, _llFilter = Nothing
, _llPageToken = Nothing
, _llPageSize = Nothing
, _llCallback = Nothing
}
-- | V1 error format.
llXgafv :: Lens' LocationsList (Maybe Xgafv)
llXgafv = lens _llXgafv (\ s a -> s{_llXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
llUploadProtocol :: Lens' LocationsList (Maybe Text)
llUploadProtocol
= lens _llUploadProtocol
(\ s a -> s{_llUploadProtocol = a})
-- | OAuth access token.
llAccessToken :: Lens' LocationsList (Maybe Text)
llAccessToken
= lens _llAccessToken
(\ s a -> s{_llAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
llUploadType :: Lens' LocationsList (Maybe Text)
llUploadType
= lens _llUploadType (\ s a -> s{_llUploadType = a})
-- | The resource that owns the locations collection, if applicable.
llName :: Lens' LocationsList Text
llName = lens _llName (\ s a -> s{_llName = a})
-- | A filter to narrow down results to a preferred subset. The filtering
-- language accepts strings like \"displayName=tokyo\", and is documented
-- in more detail in AIP-160 (https:\/\/google.aip.dev\/160).
llFilter :: Lens' LocationsList (Maybe Text)
llFilter = lens _llFilter (\ s a -> s{_llFilter = a})
-- | A page token received from the next_page_token field in the response.
-- Send that page token to receive the subsequent page.
llPageToken :: Lens' LocationsList (Maybe Text)
llPageToken
= lens _llPageToken (\ s a -> s{_llPageToken = a})
-- | The maximum number of results to return. If not set, the service selects
-- a default.
llPageSize :: Lens' LocationsList (Maybe Int32)
llPageSize
= lens _llPageSize (\ s a -> s{_llPageSize = a}) .
mapping _Coerce
-- | JSONP
llCallback :: Lens' LocationsList (Maybe Text)
llCallback
= lens _llCallback (\ s a -> s{_llCallback = a})
instance GoogleRequest LocationsList where
type Rs LocationsList = ListLocationsResponse
type Scopes LocationsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient LocationsList'{..}
= go _llName _llXgafv _llUploadProtocol
_llAccessToken
_llUploadType
_llFilter
_llPageToken
_llPageSize
_llCallback
(Just AltJSON)
loggingService
where go
= buildClient (Proxy :: Proxy LocationsListResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Locations/List.hs | mpl-2.0 | 5,925 | 0 | 19 | 1,458 | 970 | 561 | 409 | 133 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Logging.Projects.Logs.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes all the log entries in a log for the _Default Log Bucket. The
-- log reappears if it receives new entries. Log entries written shortly
-- before the delete operation might not be deleted. Entries received after
-- the delete operation with a timestamp before the operation will be
-- deleted.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.projects.logs.delete@.
module Network.Google.Resource.Logging.Projects.Logs.Delete
(
-- * REST Resource
ProjectsLogsDeleteResource
-- * Creating a Request
, projectsLogsDelete
, ProjectsLogsDelete
-- * Request Lenses
, pldXgafv
, pldUploadProtocol
, pldAccessToken
, pldUploadType
, pldLogName
, pldCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.projects.logs.delete@ method which the
-- 'ProjectsLogsDelete' request conforms to.
type ProjectsLogsDeleteResource =
"v2" :>
Capture "logName" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes all the log entries in a log for the _Default Log Bucket. The
-- log reappears if it receives new entries. Log entries written shortly
-- before the delete operation might not be deleted. Entries received after
-- the delete operation with a timestamp before the operation will be
-- deleted.
--
-- /See:/ 'projectsLogsDelete' smart constructor.
data ProjectsLogsDelete =
ProjectsLogsDelete'
{ _pldXgafv :: !(Maybe Xgafv)
, _pldUploadProtocol :: !(Maybe Text)
, _pldAccessToken :: !(Maybe Text)
, _pldUploadType :: !(Maybe Text)
, _pldLogName :: !Text
, _pldCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLogsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldXgafv'
--
-- * 'pldUploadProtocol'
--
-- * 'pldAccessToken'
--
-- * 'pldUploadType'
--
-- * 'pldLogName'
--
-- * 'pldCallback'
projectsLogsDelete
:: Text -- ^ 'pldLogName'
-> ProjectsLogsDelete
projectsLogsDelete pPldLogName_ =
ProjectsLogsDelete'
{ _pldXgafv = Nothing
, _pldUploadProtocol = Nothing
, _pldAccessToken = Nothing
, _pldUploadType = Nothing
, _pldLogName = pPldLogName_
, _pldCallback = Nothing
}
-- | V1 error format.
pldXgafv :: Lens' ProjectsLogsDelete (Maybe Xgafv)
pldXgafv = lens _pldXgafv (\ s a -> s{_pldXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldUploadProtocol :: Lens' ProjectsLogsDelete (Maybe Text)
pldUploadProtocol
= lens _pldUploadProtocol
(\ s a -> s{_pldUploadProtocol = a})
-- | OAuth access token.
pldAccessToken :: Lens' ProjectsLogsDelete (Maybe Text)
pldAccessToken
= lens _pldAccessToken
(\ s a -> s{_pldAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldUploadType :: Lens' ProjectsLogsDelete (Maybe Text)
pldUploadType
= lens _pldUploadType
(\ s a -> s{_pldUploadType = a})
-- | Required. The resource name of the log to delete:
-- projects\/[PROJECT_ID]\/logs\/[LOG_ID]
-- organizations\/[ORGANIZATION_ID]\/logs\/[LOG_ID]
-- billingAccounts\/[BILLING_ACCOUNT_ID]\/logs\/[LOG_ID]
-- folders\/[FOLDER_ID]\/logs\/[LOG_ID][LOG_ID] must be URL-encoded. For
-- example, \"projects\/my-project-id\/logs\/syslog\",
-- \"organizations\/123\/logs\/cloudaudit.googleapis.com%2Factivity\".For
-- more information about log names, see LogEntry.
pldLogName :: Lens' ProjectsLogsDelete Text
pldLogName
= lens _pldLogName (\ s a -> s{_pldLogName = a})
-- | JSONP
pldCallback :: Lens' ProjectsLogsDelete (Maybe Text)
pldCallback
= lens _pldCallback (\ s a -> s{_pldCallback = a})
instance GoogleRequest ProjectsLogsDelete where
type Rs ProjectsLogsDelete = Empty
type Scopes ProjectsLogsDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/logging.admin"]
requestClient ProjectsLogsDelete'{..}
= go _pldLogName _pldXgafv _pldUploadProtocol
_pldAccessToken
_pldUploadType
_pldCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy ProjectsLogsDeleteResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Projects/Logs/Delete.hs | mpl-2.0 | 5,479 | 0 | 15 | 1,162 | 713 | 423 | 290 | 102 | 1 |
module Robotics.NXT.Data (
fromUByte,
fromUWord,
fromULong,
fromSByte,
fromSWord,
fromSLong,
dataToString,
dataToString0,
toUByte,
toUWord,
toULong,
toSByte,
toSWord,
toSLong,
stringToData,
stringToData0,
nameToData,
messageToData
) where
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List
import Data.Word
import Control.Exception
-- Converts a list of bytes to an unsigned numeric value
dataToInt :: Integral a => [Word8] -> a -- least significant byte first
dataToInt = foldr addByte 0x00
where addByte x y = y' * 0x100 + x'
where x' = fromIntegral x
y' = fromIntegral y
fromUByte :: Integral a => [Word8] -> a -- one byte, unsigned
fromUByte ws@[_] = dataToInt ws
fromUByte _ = throw $ PatternMatchFail "fromUByte"
fromUWord :: Integral a => [Word8] -> a -- two bytes, unsigned, least significant byte first
fromUWord ws@[_, _] = dataToInt ws
fromUWord _ = throw $ PatternMatchFail "fromUWord"
fromULong :: Integral a => [Word8] -> a -- four bytes, unsigned, least significant byte first
fromULong ws@[_, _, _, _] = dataToInt ws
fromULong _ = throw $ PatternMatchFail "fromULong"
fromSByte :: Integral a => [Word8] -> a -- one byte, signed
fromSByte ws@[b] | b <= 0x7F = dataToInt ws
| otherwise = negate . (-) 0x100 . dataToInt $ ws
fromSByte _ = throw $ PatternMatchFail "fromSByte"
fromSWord :: Integral a => [Word8] -> a -- two bytes, signed, least significant byte first
fromSWord ws@[_, b] | b <= 0x7F = dataToInt ws
| otherwise = negate . (-) 0x10000 . dataToInt $ ws
fromSWord _ = throw $ PatternMatchFail "fromSWord"
fromSLong :: Integral a => [Word8] -> a -- four bytes, signed, least significant byte first
fromSLong ws@[_, _, _, b] | b <= 0x7F = dataToInt ws
| otherwise = negate . (-) 0x100000000 . dataToInt $ ws
fromSLong _ = throw $ PatternMatchFail "fromSLong"
-- Converts a null-terminated list of bytes to a string
dataToString0 :: [Word8] -> String
dataToString0 = dataToString . takeWhile (/= 0x00)
dataToString :: [Word8] -> String
dataToString = C.unpack . B.pack
-- Converts a numeric value to list of bytes
-- In a case of a negative number it produces an infinite list
intToData :: Integral a => a -> [Word8] -- least significant byte first
intToData 0x00 = [0x00]
intToData x = unfoldr getByte x
where getByte 0x00 = Nothing
getByte y = Just (fromIntegral $ y `mod` 0x100, y `div` 0x100)
toUByte :: (Show a, Integral a) => a -> [Word8] -- one byte, unsigned
toUByte x | x >= 0x00 && x <= 0xFF = intToData x
| otherwise = throw . PatternMatchFail $ "toUByte: " ++ show x
toUWord :: (Show a, Integral a) => a -> [Word8] -- two bytes, unsigned, least significant byte first
toUWord x | x >= 0x00 && x <= 0xFFFF = take 2 . flip (++) (repeat 0x00) . intToData $ x
| otherwise = throw . PatternMatchFail $ "toUWord: " ++ show x
toULong :: (Show a, Integral a) => a -> [Word8] -- four bytes, unsigned, least significant byte first
toULong x | x' >= 0x00 && x' <= 0xFFFFFFFF = take 4 . flip (++) (repeat 0x00) . intToData $ x'
| otherwise = throw . PatternMatchFail $ "toULong: " ++ show x
where x' = fromIntegral x :: Integer
toSByte :: (Show a, Integral a) => a -> [Word8] -- one byte, signed
toSByte x | x >= (-0x80) && x < 0x00 = intToData $ 0x100 + x
| x >= 0x00 && x <= 0x7F = intToData x
| otherwise = throw . PatternMatchFail $ "toSByte: " ++ show x
toSWord :: (Show a, Integral a) => a -> [Word8] -- two bytes, signed, least significant byte first
toSWord x | x >= (-0x8000) && x < 0x00 = take 2 . flip (++) (repeat 0x00) . intToData $ 0x10000 + x
| x >= 0x00 && x <= 0x7FFF = take 2 . flip (++) (repeat 0x00) . intToData $ x
| otherwise = throw . PatternMatchFail $ "toSWord: " ++ show x
toSLong :: (Show a, Integral a) => a -> [Word8] -- four bytes, signed, least significant byte first
toSLong x | x' >= (-0x80000000) && x' < 0x00 = take 4 . flip (++) (repeat 0x00) . intToData $ 0x100000000 + x'
| x' >= 0x00 && x' <= 0x7FFFFFFF = take 4 . flip (++) (repeat 0x00) . intToData $ x'
| otherwise = throw . PatternMatchFail $ "toSLong: " ++ show x
where x' = fromIntegral x :: Integer
-- Converts a string to a null-terminated list of bytes
stringToData0 :: String -> [Word8]
stringToData0 = stringToData . flip (++) "\0"
stringToData :: String -> [Word8]
stringToData = B.unpack . C.pack
-- Converts a name to a null-terminated list of bytes
nameToData :: String -> [Word8]
nameToData = stringToData0 . take 19 . flip (++) (repeat '\0')
-- Converts a message to a null-terminated list of bytes
messageToData :: String -> [Word8]
messageToData = stringToData0 . take 58
| mitar/nxt | lib/Robotics/NXT/Data.hs | lgpl-3.0 | 5,018 | 0 | 12 | 1,289 | 1,636 | 860 | 776 | 90 | 2 |
module Philosophers (
Philosopher,
philosophersDinner
) where
import System.IO (hFlush, stdout)
import System.Random
import Control.Monad (forever, forM, replicateM)
import Control.Concurrent (threadDelay, forkIO, yield)
import Control.Concurrent.STM
type OutputLog = TChan String
type Spoon = TMVar ()
type Philosopher = String
eat :: Philosopher -> Spoon -> Spoon -> STM ()
eat _ ls rs = takeTMVar ls >> takeTMVar rs
think :: Philosopher -> Spoon -> Spoon -> STM ()
think _ ls rs = putTMVar ls () >> putTMVar rs ()
philosopherLoop :: Philosopher -> Spoon -> Spoon -> OutputLog -> IO ()
philosopherLoop phil ls rs olog = forever (doSomething >> randomThreadDelay)
where doSomething = atomically $ tryEating `orElse` tryThinking
tryEating = eat phil ls rs >> (writeTChan olog $ phil ++ " eats")
tryThinking = think phil ls rs >> (writeTChan olog $ phil ++ " thinks")
philosophersDinner :: [Philosopher] -> IO ()
philosophersDinner phils = do
olog <- newTChanIO
spoons <- replicateM (length phils) newEmptyTMVarIO
let spoonPairs = zip (spoons) (tail $ cycle spoons)
forM (zip phils spoonPairs) $ \(phil, (ls, rs)) -> do
putStrLn $ phil ++ " joins the eternal dinner"
forkIO $ philosopherLoop phil ls rs olog
forever $ printOutputLog olog
printOutputLog olog = atomically (readTChan olog) >>= putStrLn >> hFlush stdout
randomThreadDelay = do
seconds <- getStdRandom $ randomR (1,9)
threadDelay $ seconds * 100000
| k0001/philod | Philosophers.hs | unlicense | 1,501 | 0 | 13 | 312 | 530 | 272 | 258 | 33 | 1 |
module Main where
import Types.Cards
import Types.Lists
import Types.Trees
import Types.User
main :: IO ()
main = putStrLn "SplitTests compiled"
{-
? marks are used to show where a variable will be
in the expected patterns
-}
{-
Testing Maybe - From internal type db
Expected [ Nothing & Just ? ]
-}
test0 :: Maybe Int -> Int
test0 {-SPLIT-}xs = 0
testx a = a
testx [] = []
{-
Testing List - From internal type db
Expected [ [] & (x:xs) ]
-}
test1 :: [Int] -> Int
test1 {-SPLIT-}xs = 0
{-
Testing Either - From internal type db
Expected [ Left ? & Right ? ]
-}
test2 :: Either Int Int -> Int
test2 {-SPLIT-}xs = 0
{-
Testing Bool - From internal type db
Expected [ True & False ]
-}
test3 :: Bool -> Int
test3 {-SPLIT-}xs = 0
{-
Test using a datatype declared in this module
Expected [ (Square ?) & (Rectangle ? ?) & (Circle ?) ]
-}
data Shape = Square Int
| Rectangle Int Int
| Circle Int
deriving (Eq, Show)
test4 :: Shape -> Int
test4 {-SPLIT-}s = 0
{-
Test using a datatype declared in another file
Expected [ (Student ? ? ?) | (Admin ? ?) ]
-}
test5 :: User -> String
test5 {-SPLIT-}us = ""
{-
Test multiple splits using crazy huge constructors (Pack of cards)
Expected [A constructor for every card in the pack, huge list]
-}
test6 :: Card -> Int
test6 ({-SPLIT-}suit, {-SPLIT-}val) = 0
{-
Test splitting a type which has an inline constructor
Expected [B0 & (? :< ?)]
-}
test7 :: Bwd Int -> Int
test7 {-SPLIT-}bs = 0
{-
Test splitting 2 lists
Expected [[] [] & (?:?) [] & [] (?:?) & (?:?) (?:?)]
-}
test8 :: String -> String -> String
test8 {-SPLIT-}xs {-SPLIT-}ys = ""
{-
Test splitting a pattern on an inline function
Expected [ [] & (? : ?)]
-}
test9 :: String -> String
test9 ss = foo ss
where
foo {-SPLIT-}xs = ""
{-
Test splitting a pattern on an inline function with surrounding functions
Expected [ [] & (? : ?)]
-}
test10 :: String -> String
test10 ss = foo ss ++ (show $ bar ss)
where
bar xs = length xs
foo {-SPLIT-}xs = ""
{-
Test splitting a pattern on an inline function with surrounding functions
Expected [ [] & (? : ?)]
-}
test11 :: String -> String
test11 ss = foo ss ++ (show $ bar ss)
where
foo {-SPLIT-}xs = ""
bar xs = length xs
{-
Test splitting a pattern on an inline function with surrounding functions
Expected [ [] & (? : ?)]
-}
test12 :: String -> String
test12 ss = foo ss ++ (show $ bar ss)
where
fuz xs = xs ++ xs
foo {-SPLIT-}xs = ""
bar xs = length xs
{-
Test splitting 2 patterns in an inline function block
Expected [ [] & (? : ?)] & [ [] & (? : ?)]
-}
test13 :: String -> String
test13 ss = foo ss ++ (show $ bar $ fuz ss)
where
fuz xs = xs ++ xs
foo {-SPLIT-}xs = ""
bar {-SPLIT-}xs = 0
{-
Test a complex type in an inline function
Expected [ (Student ? ? ?) | (Admin ? ?) ]
-}
test14 :: User -> String
test14 user = foo user
where
foo user = undefined
{-
Test splitting a primitive
Expected [ An error message explaining that primitives can't be split will be inserted ]
-}
test15 :: Char -> String
test15 {-SPLIT-}c = ""
{-
Test splitting a tree defined in Types.Trees
Expected [ (Branch ? ?) & (Leaf ?) ]
-}
test16 :: Tree Int -> Int
test16 {-SPLIT-}t = 0
{-
Sometimes compiler warnings are sent over STDERR
We don't care so this tests that they are ignored when
testing if a file loaded
-}
testCompilerWarningIgnoring a = a
testCompilerWarningIgnoring [] = []
| DarrenMowat/blackbox | tests/SplitTests.hs | unlicense | 3,690 | 0 | 8 | 1,052 | 673 | 364 | 309 | 61 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.