code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# OPTIONS_GHC -fno-warn-type-defaults -fno-warn-orphans -fno-warn-missing-fields #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Yage.Prelude
( module ClassyPrelude
, io, pass
, traceShowS, traceShowS', ioTime, printIOTime, traceWith, traceStack
, globFp
-- list functions
, zipWithTF
, offset0
, eqType, descending
, (<?), (?>)
, isLeft, isRight
, Identity()
, qStr
, module Text.Show
, module FilePath
, module DeepSeq
, module Default
, module Prelude
, module Proxy
, module Printf
) where
import qualified Prelude as Prelude
import ClassyPrelude
import Text.Printf as Printf (printf)
import Data.Typeable
import Data.Data
import Data.Proxy as Proxy
import Data.Traversable as Trav
import Data.Foldable as Fold
import Data.Functor.Identity ()
import Data.Default as Default
import Control.DeepSeq as DeepSeq
import Control.DeepSeq.Generics as DeepSeq
import Filesystem.Path.CurrentOS as FilePath (decodeString,
encodeString)
import Foreign.Ptr
import System.CPUTime
import System.FilePath.Glob
import Text.Printf
import Text.Show
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Debug.Trace (traceStack)
io :: (MonadIO m) => IO a -> m a
io = liftIO
pass :: IO ()
pass = return ()
traceShowS :: Show a => ShowS -> a -> a
traceShowS sf a = traceShow (sf $ show a) a
traceShowS' :: Show a => String -> a -> a
traceShowS' msg = traceShowS (msg Prelude.++)
traceWith :: Show b => (a -> b) -> a -> a
traceWith f a = traceShow (f a) a
-- | time a monadic action in seconds, the monadic value is strict evaluated
ioTime :: MonadIO m => m a -> m (a, Double)
ioTime action = do
start <- io $! getCPUTime
v <- action
end <- v `seq` io $! getCPUTime
let diff = (fromIntegral (end - start)) / (10^(12::Int))
return $! (v, diff)
printIOTime :: MonadIO m => m a -> m a
printIOTime f = do
(res, t) <- ioTime f
_ <- io $! printf "Computation time: %0.5f sec\n" t
return res
-- stolen from: Graphics-GLUtil-BufferObjects
-- |A zero-offset 'Ptr'.
offset0 :: Ptr a
offset0 = offsetPtr 0
-- |Produce a 'Ptr' value to be used as an offset of the given number
-- of bytes.
offsetPtr :: Int -> Ptr a
offsetPtr = wordPtrToPtr . fromIntegral
eqType :: (Typeable r, Typeable t) => Proxy r -> Proxy t -> Bool
eqType r t = (typeOf r) == (typeOf t)
(?>) :: a -> Maybe a -> a
l ?> mr = maybe l id mr
(<?) :: Maybe a -> a -> a
(<?) = flip (?>)
descending :: (a -> a -> Ordering) -> (a -> a -> Ordering)
descending cmp = flip cmp
isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _ = False
isRight :: Either a b -> Bool
isRight (Right _)= True
isRight _ = False
zipWithTF :: (Traversable t, Foldable f) => (a -> b -> c) -> t a -> f b -> t c
zipWithTF g t f = snd (Trav.mapAccumL map_one (Fold.toList f) t)
where map_one (x:xs) y = (xs, g y x)
map_one _ _ = error "Yage.Prelude.zipWithTF"
qStr :: QuasiQuoter
qStr = QuasiQuoter { quoteExp = stringE }
-- | utility function to glob with a 'Filesystem.Path.FilePath'
--
-- > globFp ( "foo" </> "bar" </> "*<->.jpg" )
-- > ["foo/bar/image01.jpg", "foo/bar/image02.jpg"]
globFp :: MonadIO m => FilePath -> m [FilePath]
globFp = io . fmap (map fpFromString) . glob . fpToString
{-# INLINE globFp #-}
deriving instance Data Zero
deriving instance Typeable Zero
deriving instance Data a => Data (Succ a)
deriving instance Typeable Succ
|
MaxDaten/yage-contrib
|
src/Yage/Prelude.hs
|
Haskell
|
mit
| 3,837
|
{-# LANGUAGE TemplateHaskell #-}
module PeaCoq where
import Control.Lens (makeLenses)
import Data.IORef (IORef)
import Data.IntMap (IntMap)
import Snap (Snaplet)
import Snap.Snaplet.Session (SessionManager)
import System.IO
import System.Process (ProcessHandle)
type Handles = (Handle, Handle, Handle, ProcessHandle)
data SessionState
= SessionState
Bool -- True while the session is alive
Handles -- I/O handles
-- Global state must be used in thread-safe way
data GlobalState
= GlobalState
{ gNextSession :: Int -- number to assign to the next session
, gActiveSessions :: IntMap SessionState
, gCoqtop :: String -- the command to use to run coqtop
}
type PeaCoqGlobRef = (IORef GlobalState)
type PeaCoqHash = String
type PeaCoqSession = SessionManager
-- Each thread gets a separate copy of this, fields must be read-only
data PeaCoq
= PeaCoq
{ _lGlobRef :: Snaplet PeaCoqGlobRef
, _lHash :: Snaplet PeaCoqHash
, _lSession :: Snaplet PeaCoqSession
}
-- Fields are lenses to separate concerns, use "Handler PeaCoq <Lens> a"
makeLenses ''PeaCoq
|
Ptival/peacoq-server
|
lib/PeaCoq.hs
|
Haskell
|
mit
| 1,192
|
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
-- | Reexports "Test.Hspec" from a @Trustworthy@ module.
module TestHspecTrustworthy (module Test.Hspec) where
import Test.Hspec
|
haskell-compat/base-compat
|
base-compat-batteries/test/TestHspecTrustworthy.hs
|
Haskell
|
mit
| 218
|
{-#LANGUAGE ScopedTypeVariables #-}
{-#LANGUAGe DataKinds #-}
{-#LANGUAGE DeriveGeneric #-}
{-#LANGUAGE DeriveAnyClass #-}
{-#LANGUAGE FlexibleContexts #-}
module Foreign.Storable.Generic.Internal.GStorableSpec where
-- Test tools
import Test.Hspec
import Test.QuickCheck
import GenericType
-- Tested modules
import Foreign.Storable.Generic.Internal
-- Additional data
import Foreign.Storable.Generic -- overlapping Storable
import Foreign.Storable.Generic.Instances
import Data.Int
import Data.Word
import GHC.Generics
import Foreign.Ptr (Ptr, plusPtr)
import Foreign.Marshal.Alloc (malloc, mallocBytes, free)
import Foreign.Marshal.Array (peekArray,pokeArray)
data TestData = TestData Int Int64 Int8 Int8
deriving (Show, Generic, GStorable, Eq)
instance Arbitrary TestData where
arbitrary = TestData <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
data TestData2 = TestData2 Int8 TestData Int32 Int64
deriving (Show, Generic, GStorable, Eq)
instance Arbitrary TestData2 where
arbitrary = TestData2 <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
data TestData3 = TestData3 Int64 TestData2 Int16 TestData Int8
deriving (Show, Generic, GStorable, Eq)
instance Arbitrary TestData3 where
arbitrary = TestData3 <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
sizeEquality a = do
gsizeOf a `shouldBe` internalSizeOf (from a)
alignmentEquality a = do
gsizeOf a `shouldBe` internalSizeOf (from a)
pokeEquality a = do
let size = gsizeOf a
off <- generate $ suchThat arbitrary (>=0)
ptr <- mallocBytes (off + size)
-- First poke
gpokeByteOff ptr off a
bytes1 <- peekArray (off+size) ptr :: IO [Word8]
internalPokeByteOff ptr off (from a)
bytes2 <- peekArray (off+size) ptr :: IO [Word8]
free ptr
bytes1 `shouldBe` bytes2
peekEquality (a :: t) = do
let size = gsizeOf a
off <- generate $ suchThat arbitrary (>=0)
ptr <- mallocBytes (off + size)
bytes <- generate $ ok_vector (off+size) :: IO [Word8]
-- Save random stuff to memory
pokeArray ptr bytes
-- Take a peek
v1 <- gpeekByteOff ptr off :: IO t
v2 <- internalPeekByteOff ptr off :: IO (Rep t p)
free ptr
v1 `shouldBe` to v2
peekAndPoke (a :: t)= do
ptr <- malloc :: IO (Ptr t)
gpokeByteOff ptr 0 a
(gpeekByteOff ptr 0) `shouldReturn` a
spec :: Spec
spec = do
describe "gsizeOf" $ do
it "is equal to: internalSizeOf (from a)" $ property $ do
test1 <- generate $ arbitrary :: IO TestData
test2 <- generate $ arbitrary :: IO TestData2
test3 <- generate $ arbitrary :: IO TestData3
sizeEquality test1
sizeEquality test2
sizeEquality test3
describe "galignment" $ do
it "is equal to: internalAlignment (from a)" $ property $ do
test1 <- generate $ arbitrary :: IO TestData
test2 <- generate $ arbitrary :: IO TestData2
test3 <- generate $ arbitrary :: IO TestData3
alignmentEquality test1
alignmentEquality test2
alignmentEquality test3
describe "gpokeByteOff" $ do
it "is equal to: internalPokeByteOff ptr off (from a)" $ property $ do
test1 <- generate $ arbitrary :: IO TestData
test2 <- generate $ arbitrary :: IO TestData2
test3 <- generate $ arbitrary :: IO TestData3
pokeEquality test1
pokeEquality test2
pokeEquality test3
describe "gpeekByteOff" $ do
it "is equal to: to <$> internalPeekByteOff ptr off" $ property $ do
test1 <- generate $ arbitrary :: IO TestData
test2 <- generate $ arbitrary :: IO TestData2
test3 <- generate $ arbitrary :: IO TestData3
peekEquality test1
peekEquality test2
peekEquality test3
describe "Other tests:" $ do
it "gpokeByteOff ptr 0 val >> gpeekByteOff ptr 0 == val" $ property $ do
test1 <- generate $ arbitrary :: IO TestData
test2 <- generate $ arbitrary :: IO TestData2
test3 <- generate $ arbitrary :: IO TestData3
peekAndPoke test1
peekAndPoke test2
peekAndPoke test3
|
mkloczko/derive-storable
|
test/Spec/Foreign/Storable/Generic/Internal/GStorableSpec.hs
|
Haskell
|
mit
| 4,354
|
module Drifter
(
-- * Managing Migrations
resolveDependencyOrder
, changeSequence
, migrate
-- * Types
, Drifter(..)
, ChangeName(..)
, Change(..)
, Description
, Method
, DBConnection
) where
-------------------------------------------------------------------------------
import Data.List
-------------------------------------------------------------------------------
import Drifter.Graph
import Drifter.Types
-------------------------------------------------------------------------------
-- | This is a helper for the common case of where you just want
-- dependencies to run in list order. This will take the input list
-- and set their dependencies to run in the given sequence.
changeSequence :: [Change a] -> [Change a]
changeSequence [] = []
changeSequence (x:xs) = reverse $ snd $ foldl' go (x, [x]) xs
where
go :: (Change a, [Change a]) -> Change a -> (Change a, [Change a])
go (lastChange, xs') c =
let c' = c { changeDependencies = [changeName lastChange] }
in (c', c':xs')
|
AndrewRademacher/drifter
|
src/Drifter.hs
|
Haskell
|
mit
| 1,097
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGZoomAndPan
(pattern SVG_ZOOMANDPAN_UNKNOWN, pattern SVG_ZOOMANDPAN_DISABLE,
pattern SVG_ZOOMANDPAN_MAGNIFY, js_setZoomAndPan, setZoomAndPan,
js_getZoomAndPan, getZoomAndPan, SVGZoomAndPan,
castToSVGZoomAndPan, gTypeSVGZoomAndPan)
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
pattern SVG_ZOOMANDPAN_UNKNOWN = 0
pattern SVG_ZOOMANDPAN_DISABLE = 1
pattern SVG_ZOOMANDPAN_MAGNIFY = 2
foreign import javascript unsafe "$1[\"zoomAndPan\"] = $2;"
js_setZoomAndPan :: SVGZoomAndPan -> Word -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGZoomAndPan.zoomAndPan Mozilla SVGZoomAndPan.zoomAndPan documentation>
setZoomAndPan :: (MonadIO m) => SVGZoomAndPan -> Word -> m ()
setZoomAndPan self val = liftIO (js_setZoomAndPan (self) val)
foreign import javascript unsafe "$1[\"zoomAndPan\"]"
js_getZoomAndPan :: SVGZoomAndPan -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGZoomAndPan.zoomAndPan Mozilla SVGZoomAndPan.zoomAndPan documentation>
getZoomAndPan :: (MonadIO m) => SVGZoomAndPan -> m Word
getZoomAndPan self = liftIO (js_getZoomAndPan (self))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGZoomAndPan.hs
|
Haskell
|
mit
| 1,960
|
{-# LANGUAGE TypeFamilies #-}
module Agent.PingPong.Role.Ask where
import AgentSystem.Generic
import Agent.PingPong
import qualified Agent.PingPong.Simple.Ask as Ask
import Data.IORef
--------------------------------------------------------------------------------
data PingRole = PingRole
data PongRole = PongRole
--------------------------------------------------------------------------------
instance RoleName PingRole where roleName _ = "Ping"
instance AgentRole PingRole where
type RoleState PingRole = (IORef Integer, IORef SomeAgentRef)
type RoleResult PingRole = ()
type RoleSysArgs PingRole = ()
type RoleArgs PingRole = (Integer, IORef SomeAgentRef)
instance RoleName PongRole where roleName _ = "Pong"
instance AgentRole PongRole where
type RoleState PongRole = ()
type RoleResult PongRole = ()
type RoleSysArgs PongRole = ()
type RoleArgs PongRole = ()
--------------------------------------------------------------------------------
pingRoleDescriptor = genericRoleDescriptor PingRole
(const $ return . uncurry Ask.pingDescriptor)
pongRoleDescriptor = genericRoleDescriptor PongRole
(const . const $ return Ask.pongDescriptor)
--------------------------------------------------------------------------------
runPingPong nPings = do pongRef <- newIORef undefined
putStrLn "<< CreateAgentOfRole >> "
let pingC = CreateAgentOfRole pingRoleDescriptor
(return ()) (return (nPings, pongRef))
pongC = CreateAgentOfRole pongRoleDescriptor
(return ()) (return ())
ping <- createAgentRef pingC
pong <- createAgentRef pongC
pongRef `writeIORef` someAgentRef pong
putStrLn "Starting PING"
agentStart ping
putStrLn "Starting PONG"
agentStart pong
putStrLn "Waiting PING termination"
agentWaitTermination ping
|
fehu/h-agents
|
test/Agent/PingPong/Role/Ask.hs
|
Haskell
|
mit
| 2,150
|
module JoScript.Util.Text (foldlM, readFloat, readInt) where
import Prelude (read)
import Protolude hiding (foldlM)
import qualified Data.Text as T
foldlM :: Monad m => (b -> Char -> m b) -> b -> Text -> m b
foldlM f init bsInit = impl (pure init) bsInit where
impl acc bs
| T.null bs = acc
| otherwise = impl (acc >>= \acc' -> f acc' (T.head bs)) (T.tail bs)
readInt :: Text -> Integer
readInt = read . T.unpack
readFloat :: Text -> Double
readFloat = read . T.unpack
|
AKST/jo
|
source/lib/JoScript/Util/Text.hs
|
Haskell
|
mit
| 486
|
module GHCJS.TypeScript.Convert.Types where
import Language.TypeScript
import Data.Monoid
data Config = Config
{ outputDir :: FilePath
}
data Decl
= InterfaceDecl Interface
deriving (Show)
data OutputModule = OutputModule
{ omImports :: [String]
, omDecls :: [String]
} deriving (Show)
instance Monoid OutputModule where
mempty = OutputModule [] []
mappend (OutputModule imports1 decls1)
(OutputModule imports2 decls2) =
OutputModule (imports1 <> imports2)
(decls1 <> decls2)
|
mgsloan/ghcjs-typescript
|
ghcjs-typescript-convert/GHCJS/TypeScript/Convert/Types.hs
|
Haskell
|
mit
| 530
|
module Interpreter (Val(..), Expr(..), interpret) where
import Debug.Trace
data Val = IntVal Integer
| StringVal String
| BooleanVal Bool
-- since we are implementing a Functional language, functions are
-- first class citizens.
| FunVal [String] Expr Env
deriving (Show, Eq)
-----------------------------------------------------------
data Expr = Const Val
-- represents a variable
| Var String
-- integer multiplication
| Expr :*: Expr
-- integer addition and string concatenation
| Expr :+: Expr
-- equality test. Defined for all Val except FunVal
| Expr :==: Expr
-- semantically equivalent to a Haskell `if`
| If Expr Expr Expr
-- binds a Var (the first `Expr`) to a value (the second `Expr`),
-- and makes that binding available in the third expression
| Let Expr Expr Expr
-- creates an anonymous function with an arbitrary number of parameters
| Lambda [Expr] Expr
-- calls a function with an arbitrary number values for parameters
| Apply Expr [Expr]
deriving (Show, Eq)
-----------------------------------------------------------
data Env = EmptyEnv
| ExtendEnv String Val Env
deriving (Show, Eq)
-----------------------------------------------------------
-- the evaluate function takes an environment, which holds variable
-- bindings; i.e. it stores information like `x = 42`
-- the trace there will print out the values with which the function was called,
-- you can easily uncomment it if you don't need it for debugging anymore.
evaluate:: Expr -> Env -> Val
evaluate expr env =
trace("expr= " ++ (show expr) ++ "\n env= " ++ (show env)) $
case expr of
Const v -> v
lhs :+: rhs ->
let valLhs = evaluate lhs env
valRhs = evaluate rhs env
in (IntVal $ (valToInteger valRhs) + (valToInteger valLhs))
_ -> error $ "unimplemented expression: " ++ (show expr)
-----------------------------------------------------------
valError s v = error $ "expected: " ++ s ++ "; got: " ++ (show v)
-- helper function to remove some of the clutter in the evaluate function
valToInteger:: Val -> Integer
valToInteger (IntVal n) = n
valToInteger v = valError "IntVal" v
-----------------------------------------------------------
-- the function that we test. since we always start out with an EmptyEnv.
interpret :: Expr -> Val
interpret expr = evaluate expr EmptyEnv
---------------------------------------------------------------------
---------------------------------------------------------------------
---------------------------- Tests ----------------------------------
---------------------------------------------------------------------
---------------------------------------------------------------------
testConstant =
assert result (IntVal 2) "testConstant"
where result = interpret expr
expr = Const (IntVal 2)
---------------------------------------------------------------------
testAddition =
assert result (IntVal 2) "testAddition"
where result = interpret expr
expr = (Const (IntVal 1)) :+: (Const (IntVal 1))
---------------------------------------------------------------------
testComplexAddition =
assert result (IntVal 9) "testComplexAddition"
where result = interpret expr
expr = (lhs :+: rhs)
lhs = (Const (IntVal 1)) :+: (Const (IntVal 1))
rhs = (Const (IntVal 3)) :+: (Const (IntVal 4))
---------------------------------------------------------------------
testEvenMoreComplexAddition =
assert result (IntVal 18) "testEvenMoreComplexAddition"
where result = interpret expr
expr = (l :+: r)
l = lhs :+: rhs
r = rhs :+: lhs
lhs = (Const (IntVal 1)) :+: (Const (IntVal 1))
rhs = (Const (IntVal 3)) :+: (Const (IntVal 4))
---------------------------------------------------------------------
testMultiplication =
assert result (IntVal 42) "testMultiplication"
where result = interpret expr
expr = (Const (IntVal 7)) :*: (Const (IntVal 6))
---------------------------------------------------------------------
testConcatenation =
assert result (StringVal "12") "testConcatenation"
where result = interpret expr
expr = (Const (StringVal "1")) :+: (Const (StringVal "2"))
---------------------------------------------------------------------
testEqualString =
assert resultPositive (BooleanVal True) "testEqualStringPos" &&
assert resultNegative (BooleanVal False) "testEqualStringNeg"
where resultPositive = interpret exprPositive
exprPositive = (Const (StringVal "1")) :==: (Const (StringVal "1"))
resultNegative = interpret exprNegative
exprNegative = (Const (StringVal "1")) :==: (Const (StringVal "2"))
---------------------------------------------------------------------
testEqualInt =
assert resultPositive (BooleanVal True) "testEqualIntPos" &&
assert resultNegative (BooleanVal False) "testEqualIntNeg"
where resultPositive = interpret exprPositive
exprPositive = (Const (IntVal 1)) :==: (Const (IntVal 1))
resultNegative = interpret exprNegative
exprNegative = (Const (IntVal 1)) :==: (Const (IntVal 2))
---------------------------------------------------------------------
testEqualBool =
assert resultPositive (BooleanVal True) "testEqualBoolPos" &&
assert resultNegative (BooleanVal False) "testEqualBoolNeg"
where resultPositive = interpret exprPositive
exprPositive = (Const (BooleanVal True)) :==: (Const (BooleanVal True))
resultNegative = interpret exprNegative
exprNegative = (Const (BooleanVal True)) :==: (Const (BooleanVal False))
---------------------------------------------------------------------
testIf =
assert resultThen (IntVal 42) "testIfThen" &&
assert resultElse (StringVal "42") "testIfElse"
where resultThen = interpret exprThen
exprThen = (If (Const (IntVal 1) :==: Const (IntVal 1))
(Const (IntVal 42))
(Const (StringVal "42"))
)
resultElse = interpret exprElse
exprElse = (If (Const (IntVal 1) :==: Const (IntVal 2))
(Const (IntVal 42))
(Const (StringVal "42")))
---------------------------------------------------------------------
testLet =
assert result (IntVal 42) "testLet" &&
assert resultShadow (IntVal 84) "testLetShadow"
where result = interpret expr
-- ~(let x=42 in x)
expr = Let (Var "x") (Const (IntVal 42)) (Var "x")
-- ~ (let x=42 in (let x=84 in x))
-- the second redefinition of x shadows the first one
exprShadow = (Let (Var "x") (Const (IntVal 42))
(Let (Var "x") (Const (IntVal 84)) (Var "x"))
)
resultShadow = interpret exprShadow
---------------------------------------------------------------------
testLambdaAndApply =
assert result (IntVal 42) "testLambdaAndApply"
where result = interpret expr
-- equivalent to: (\x y -> x * y) 6 7
expr = (Apply
(Lambda [Var "x", Var "y"]
((Var "x") :*: (Var "y"))
)
[Const (IntVal 6), Const (IntVal 7)]
)
---------------------------------------------------------------------
testCurrying =
assert result (IntVal 42) "testCurrying"
where result = interpret expr
--equivalent to: ((\x -> \y -> x * y) 6) 7
expr = (Apply
(Apply
(Lambda [Var "x"]
(Lambda [Var "y"]
((Var "x") :*: (Var "y"))
)
)
([Const (IntVal 6)])
)
([Const (IntVal 7)])
)
---------------------------------------------------------------------
testAll =
if (allPassed)
then "All tests passed."
else error "Failed tests."
where allPassed = testConstant &&
testAddition &&
testComplexAddition &&
testEvenMoreComplexAddition &&
testMultiplication &&
testConcatenation &&
testEqualString &&
testEqualInt &&
testEqualBool &&
testIf &&
testLet &&
testLambdaAndApply &&
testCurrying
---------------------------------------------------------------------
assert :: Val -> Val -> String -> Bool
assert expected received message =
if (expected == received)
then True
else error $ message ++ " -> expected: `" ++ (show expected) ++ "`; received: `" ++ (show received) ++ "`"
|
2015-Fall-UPT-PLDA/homework
|
02/your_full_name_here.hs
|
Haskell
|
mit
| 8,926
|
--------------------------------------------------------------------
-- |
-- Module : My.Data.Maybe
-- Copyright : 2009 (c) Dmitry Antonyuk
-- License : MIT
--
-- Maintainer: Dmitry Antonyuk <lomeo.nuke@gmail.com>
-- Stability : experimental
-- Portability: portable
--
-- 'Maybe' related utilities.
--
--------------------------------------------------------------------
module My.Data.Maybe where
import Control.Applicative (Applicative, pure, (<$>))
boolToMaybe, (?) :: Bool -> a -> Maybe a
boolToMaybe True x = Just x
boolToMaybe _ _ = Nothing
(?) = boolToMaybe
boolToMaybeM :: (Applicative f) => Bool -> f a -> f (Maybe a)
boolToMaybeM True m = Just <$> m
boolToMaybeM _ _ = pure Nothing
tryMaybe :: IO a -> IO (Maybe a)
tryMaybe act = fmap Just act `catch` (\_ -> return Nothing)
|
lomeo/my
|
src/My/Data/Maybe.hs
|
Haskell
|
mit
| 810
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Main where
import Test.Tasty
import Test.Tasty.QuickCheck as QC
import Test.QuickCheck.Monadic (assert, monadicIO, run)
import Control.Applicative
import qualified Data.ByteString as BR
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Digest.CRC16
import Data.Typeable
import Data.Word
import Foreign.C.String
import Foreign.C.Types
import GHC.Generics
newtype ITA2String = ITA2String String deriving (Eq, Generic, Ord, Show, Typeable)
instance Arbitrary ITA2String where
arbitrary = ita2String
where
ita2Char = oneof (map return "QWERTYUIOPASDFGHJKLZXCVBNM\r\n 1234567890-!&#'()\"/:;?,.")
ita2String = ITA2String <$> listOf ita2Char
foreign import ccall "crc16.h crc16" c_crc16 :: CString -> CInt -> CInt
crcReference :: ITA2String -> IO Word16
crcReference (ITA2String s) = (\x -> fromIntegral $ c_crc16 x (fromIntegral . length $ s)) <$> newCString s
crcHaskellF :: Word16 -> Bool -> Word16 -> [Word8] -> Word16
crcHaskellF poly inverse initial = BR.foldl (crc16Update poly inverse) initial . BR.pack
crcHaskell :: ITA2String -> IO Word16
crcHaskell (ITA2String s) =
return $
crcHaskellF 0x1021 False 0xffff [fromIntegral (fromEnum x) :: Word8 | x <- s]
toHex :: Word16 -> B.ByteString
toHex n = BB.toLazyByteString . BB.word16Hex $ n
prop_hask_c_crc16 :: ITA2String -> Property
prop_hask_c_crc16 s = monadicIO $ do
c <- run (toHex <$> crcReference s)
hask <- run (toHex <$> crcHaskell s)
assert $ c == hask
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [properties]
properties :: TestTree
properties = testGroup "Properties" [qcProps]
qcProps :: TestTree
qcProps = testGroup "(checked by QuickCheck)"
[ QC.testProperty "crcReference === crcHaskell ∀ ita2 strings" prop_hask_c_crc16
]
|
noexc/mapview
|
tests/test.hs
|
Haskell
|
mit
| 1,907
|
module Main where
import Control.Arrow (first)
import Control.Monad (liftM)
import qualified Crypto.Cipher as Cipher
import qualified Crypto.Cipher.AES as AES
import qualified Crypto.Cipher.Types as CipherTypes
import qualified Cryptopals.Set1 as Set1
import Cryptopals.Set2
import Data.Bits (popCount, xor)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as C8
import Data.Char (ord)
import Data.List (group, sort, transpose, unfoldr)
import qualified Data.List.Key as K
import Data.List.Split (chunksOf)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Word8 as W8
main :: IO ()
main = putStrLn "hi"
|
charlescharles/cryptopals
|
src/Main.hs
|
Haskell
|
mit
| 982
|
module ReaderT where
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
instance Functor m => Functor (ReaderT r m) where
fmap f (ReaderT rma) = ReaderT $ fmap f . rma
instance Applicative m => Applicative (ReaderT r m) where
pure a = ReaderT $ \_ -> pure a
-- fab :: r -> m (a -> b)
-- a :: r -> m a
-- f <*> x :: ReaderT r m b
(ReaderT fmab) <*> (ReaderT rma) = ReaderT $ (<*>) <$> fmab <*> rma
instance Monad m => Monad (ReaderT r m) where
return = pure
(ReaderT rma) >>= f = ReaderT $ \r -> (rma r >>= (\a -> runReaderT (f a) r))
|
JoshuaGross/haskell-learning-log
|
Code/Haskellbook/ComposeTypes/src/ReaderT.hs
|
Haskell
|
mit
| 563
|
module Colors.SolarizedDark where
colorScheme = "solarized-dark"
colorBack = "#002b36"
colorFore = "#839496"
-- Black
color00 = "#073642"
color08 = "#002b36"
-- Red
color01 = "#dc322f"
color09 = "#cb4b16"
-- Green
color02 = "#859900"
color10 = "#586e75"
-- Yellow
color03 = "#b58900"
color11 = "#657b83"
-- Blue
color04 = "#268bd2"
color12 = "#839496"
-- Magenta
color05 = "#d33682"
color13 = "#6c71c4"
-- Cyan
color06 = "#2aa198"
color14 = "#93a1a1"
-- White
color07 = "#eee8d5"
color15 = "#fdf6e3"
colorTrayer :: String
colorTrayer = "--tint 0x002b36"
|
phdenzel/dotfiles
|
.config/xmonad/lib/Colors/SolarizedDark.hs
|
Haskell
|
mit
| 558
|
module SpaceAge (Planet(..), ageOn) where
data Planet
ageOn :: Planet -> Float -> Float
ageOn planet seconds = undefined
|
parkertm/exercism
|
haskell/space-age/src/SpaceAge.hs
|
Haskell
|
mit
| 123
|
module Chain where
import UU.Parsing
import Data.Char
main = do let tokens = "s*s*C"
resultado <- parseIO pSE tokens
putStrLn . show $ resultado
instance Symbol Char
-- Sintaxis concreta
data Class = Class
deriving Show
{- pRE :: Parser Char RE
pRE = pChainl pOp pClass
pSE :: Parser Char RE
pSE = SE <$ pSym 's'
pOp :: Parser Char (RE -> Class -> RE)
pOp = (:*:) <$ pSym '*'
pClass :: Parser Char Class
pClass = Class <$ pSym 'C'
data RE = SE
| RE :*: Class
deriving Show -}
pRE = pChainl pOp pSE -- pClass
pSE :: Parser Char RE
pSE = SE <$ pSym 's'
-- pOp :: Parser Char (RE -> Class -> RE)
pOp = (:*:) <$ pSym '*'
pClass :: Parser Char Class
pClass = Class <$ pSym 'C'
data RE = SE
| RE :*: RE
deriving Show
|
andreagenso/java2scala
|
src/J2s/Chain.hs
|
Haskell
|
apache-2.0
| 855
|
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Data.Map.Justified
-- Copyright : (c) Matt Noonan 2017
-- License : BSD-style
-- Maintainer : matt.noonan@gmail.com
-- Portability : portable
--
-- = Description
--
-- Have you ever /known/ that a key could be found in a certain map? Were you tempted to
-- reach for @'fromJust'@ or @'error'@ to handle the "impossible" case, when you knew that
-- @'lookup'@ should give @'Just' v@? (and did shifting requirements ever make the impossible
-- become possible after all?)
--
-- "Data.Map.Justified" provides a zero-cost @newtype@ wrapper around "Data.Map"'s @'Data.Map.Map'@ that enables you
-- to separate the /proof that a key is present/ from the /operations using the key/. Once
-- you prove that a key is present, you can use it @Maybe@-free in any number of other
-- operations -- sometimes even operations on other maps!
--
-- None of the functions in this module can cause a run-time error, and very few
-- of the operations return a @'Maybe'@ value.
--
-- See the "Data.Map.Justified.Tutorial" module for usage examples.
--
-- === Example
-- @
-- withMap test_table $ \\table -> do
--
-- case member 1 table of
--
-- Nothing -> putStrLn "Sorry, I couldn\'t prove that the key is present."
--
-- Just key -> do
--
-- -- We have proven that the key is present, and can now use it Maybe-free...
-- putStrLn ("Found key: " ++ show key)
-- putStrLn ("Value for key: " ++ lookup key table)
--
-- -- ...even in certain other maps!
-- let table\' = reinsert key "howdy" table
-- putStrLn ("Value for key in updated map: " ++ lookup key table\')
-- @
-- Output:
--
-- @
-- Found key: Key 1
-- Value for key: hello
-- Value for key in updated map: howdy
-- @
--
-- == Motivation: "Data.Map" and @'Maybe'@ values
--
-- Suppose you have a key-value mapping using "Data.Map"'s type @'Data.Map.Map' k v@. Anybody making
-- use of @'Data.Map.Map' k v@ to look up or modify a value must take into account the possibility
-- that the given key is not present.
--
-- In "Data.Map", there are two strategies for dealing with absent keys:
--
-- 1. Cause a runtime error (e.g. "Data.Map"'s @'Data.Map.!'@ when the key is absent)
--
-- 2. Return a @'Maybe'@ value (e.g. "Data.Map"'s @'Data.Map.lookup'@)
--
-- The first option introduces partial functions, so is not very palatable. But what is
-- wrong with the second option?
--
-- To understand the problem with returning a @'Maybe'@ value, let's ask what returning
-- @Maybe v@ from @'Data.Map.lookup' :: k -> Map k v -> Maybe v@ really does for us. By returning
-- a @Maybe v@ value, @lookup key table@ is saying "Your program must account
-- for the possibility that @key@ cannot be found in @table@. I will ensure that you
-- account for this possibility by forcing you to handle the @'Nothing'@ case."
-- In effect, "Data.Map" is requiring the user to prove they have handled the
-- possibility that a key is absent whenever they use the @'Data.Map.lookup'@ function.
--
-- == Laziness (the bad kind)
--
-- Every programmer has probably had the experience of knowing, somehow, that a certain
-- key is going to be present in a map. In this case, the @'Maybe' v@ feels like a burden:
-- I already /know/ that this key is in the map, why should I have to handle the @'Nothing'@ case?
--
-- In this situation, it is tempting to reach for the partial function @'Data.Maybe.fromJust'@,
-- or a pattern match like @'Nothing' -> 'error' "The impossible happened!"@. But as parts of
-- the program are changed over time, you may find the impossible has become possible after
-- all (or perhaps you'll see the dreaded and unhelpful @*** Exception: Maybe.fromJust: Nothing@)
--
-- It is tempting to reach for partial functions or "impossible" runtime errors here, because
-- the programmer has proven that the key is a member of the map in some other way. They
-- know that @'Data.Map.lookup'@ should return a @'Just' v@ --- but the /compiler/ doesn't know this!
--
-- The idea behind "Data.Map.Justified" is to encode the programmer's knowledge that a key
-- is present /within the type system/, where it can be checked at compile-time. Once a key
-- is known to be present, @'Data.Map.Justified.lookup'@ will never fail. Your justification
-- removes the @'Just'@!
--
-- == How it works
--
-- Evidence that a key can indeed be found in a map is carried by a phantom type parameter @ph@
-- shared by both the @'Data.Map.Justified.Map'@ and @'Data.Map.Justified.Key'@ types. If you are
-- able to get your hands on a value of type @'Key' ph k@, then you must have already proven that
-- the key is present in /any/ value of type @'Map' ph k v@.
--
-- The @'Key' ph k@ type is simply a @newtype@ wrapper around @k@, but the phantom type @ph@ allows
-- @'Key' ph k@ to represent both /a key of type @k@/ __and__ /a proof that the key is present in/
-- /all maps of type @'Map' ph k v@/.
--
-- There are several ways to prove that a key belongs to a map, but the simplest is to just use
-- "Data.Map.Justified"'s @'Data.Map.Justified.member'@ function. In "Data.Map", @'Data.Map.member'@
-- has the type
--
-- @'Data.Map.member' :: 'Ord' k => k -> 'Data.Map.Map' k v -> 'Bool'@
--
-- and reports whether or not the key can be found in the map. In "Data.Map.Justified",
-- @'Data.Map.Member'@ has the type
--
-- @'member' :: 'Ord' k => k -> 'Map' ph k v -> 'Maybe' ('Key' ph k)@
--
-- Instead of a boolean, @'Data.Map.Justified.member'@ either says "the key is not present"
-- (@'Nothing'@), or gives back the same key, /augmented with evidence that they key/
-- /is present/. This key-plus-evidence can then be used to do any number of @'Maybe'@-free
-- operations on the map.
--
-- "Data.Map.Justified" uses the same rank-2 polymorphism trick used in the @'Control.Monad.ST'@ monad to
-- ensure that the @ph@ phantom type can not be extracted; in effect, the proof that a key is
-- present can't leak to contexts where the proof would no longer be valid.
--
module Data.Map.Justified (
-- * Map and Key types
Map
, Key
, Index
, theMap
, theKey
, theIndex
-- * Evaluation
, withMap
, withSingleton
, KeyInfo(..)
, MissingReference
, withRecMap
-- * Gathering evidence
, member
, keys
, lookupMay
, lookupLT
, lookupLE
, lookupGT
, lookupGE
-- * Safe lookup
, lookup
, (!)
-- * Preserving key sets
-- ** Localized updates
, adjust
, adjustWithKey
, reinsert
-- ** Mapping values
, mapWithKey
, traverseWithKey
, mapAccum
, mapAccumWithKey
-- ** Zipping
, zip
, zipWith
, zipWithKey
-- * Enlarging key sets
-- ** Inserting new keys
, inserting
, insertingWith
-- ** Unions
, unioning
, unioningWith
, unioningWithKey
-- * Reducing key sets
-- ** Removing keys
, deleting
, subtracting
-- ** Filtering
, filtering
, filteringWithKey
-- ** Intersections
, intersecting
, intersectingWith
, intersectingWithKey
-- * Mapping key sets
, mappingKeys
, mappingKnownKeys
, mappingKeysWith
, mappingKnownKeysWith
-- * Indexing
, findIndex
, elemAt
-- * Utilities
, tie
) where
import Control.Arrow ((&&&))
import Data.List (partition)
import qualified Data.Map as M
import Prelude hiding (lookup, zip, zipWith)
import Data.Roles
import Data.Type.Coercion
{--------------------------------------------------------------------
Map and Key types
--------------------------------------------------------------------}
-- | A "Data.Map" @'Data.Map.Map'@ wrapper that allows direct lookup of keys that
-- are known to exist in the map.
--
-- Here, "direct lookup" means that once a key has been proven
-- to exist in the map, it can be used to extract a value directly
-- from the map, rather than requiring a @'Maybe'@ layer.
--
-- @'Map'@ allows you to shift the burden of proof that a key exists
-- in a map from "prove at every lookup" to "prove once per key".
newtype Map ph k v = Map (M.Map k v) deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
type role Map nominal nominal representational
-- | A key that knows it can be found in certain @'Map'@s.
--
-- The evidence that the key can be found in a map is carried by
-- the type system via the phantom type parameter @ph@. Certain
-- operations such as lookup will only type-check if the @'Key'@
-- and the @'Map'@ have the same phantom type parameter.
newtype Key ph k = Key k deriving (Eq, Ord, Show)
type role Key nominal representational
-- | An index that knows it is valid in certain @'Map'@s.
--
-- The evidence that the index is valid for a map is carried by
-- the type system via the phantom type parameter @ph@. Indexing
-- operations such as `elemAt` will only type-check if the @'Index'@
-- and the @'Map'@ have the same phantom type parameter.
newtype Index ph = Index Int deriving (Eq, Ord, Show)
type role Index nominal
-- | Get the underlying "Data.Map" @'Data.Map'@ out of a @'Map'@.
theMap :: Map ph k v -> M.Map k v
theMap (Map m) = m
-- | Get a bare key out of a key-plus-evidence by forgetting
-- what map the key can be found in.
theKey :: Key ph k -> k
theKey (Key k) = k
-- | Get a bare index out of an index-plus-evidence by forgetting
-- what map the index is valid for.
theIndex :: Index ph -> Int
theIndex (Index n) = n
{--------------------------------------------------------------------
Evaluation
--------------------------------------------------------------------}
-- | Evaluate an expression using justified key lookups into the given map.
--
-- > import qualified Data.Map as M
-- >
-- > withMap (M.fromList [(1,"A"), (2,"B")]) $ \m -> do
-- >
-- > -- prints "Found Key 1 with value A"
-- > case member 1 m of
-- > Nothing -> putStrLn "Missing key 1."
-- > Just k -> putStrLn ("Found " ++ show k ++ " with value " ++ lookup k m)
-- >
-- > -- prints "Missing key 3."
-- > case member 3 m of
-- > Nothing -> putStrLn "Missing key 3."
-- > Just k -> putStrLn ("Found " ++ show k ++ " with value " ++ lookup k m)
withMap :: M.Map k v -- ^ The map to use as input
-> (forall ph. Map ph k v -> t) -- ^ The computation to apply
-> t -- ^ The resulting value
withMap m cont = cont (Map m)
-- | Like @'withMap'@, but begin with a singleton map taking @k@ to @v@.
--
-- The continuation is passed a pair consisting of:
--
-- 1. Evidence that @k@ is in the map, and
--
-- 2. The singleton map itself, of type @'Map' ph k v@.
--
-- > withSingleton 1 'a' (uncurry lookup) == 'a'
withSingleton :: k -> v -> (forall ph. (Key ph k, Map ph k v) -> t) -> t
withSingleton k v cont = cont (Key k, Map (M.singleton k v))
-- | Information about whether a key is present or missing.
-- See @'Data.Map.Justified.withRecMap'@ and "Data.Map.Justified.Tutorial"'s @'Data.Map.Justified.Tutorial.example5'@.
data KeyInfo = Present | Missing deriving (Show, Eq, Ord)
-- | A description of what key/value-containing-keys pairs failed to be found.
-- See @'Data.Map.Justified.withRecMap'@ and "Data.Map.Justified.Tutorial"'s @'Data.Map.Justified.Tutorial.example5'@.
type MissingReference k f = (k, f (k, KeyInfo))
-- | Evaluate an expression using justified key lookups into the given map,
-- when the values can contain references back to keys in the map.
--
-- Each referenced key is checked to ensure that it can be found in the map.
-- If all referenced keys are found, they are augmented with evidence and the
-- given function is applied.
-- If some referenced keys are missing, information about the missing references
-- is generated instead.
--
-- > import qualified Data.Map as M
-- >
-- > data Cell ptr = Nil | Cons ptr ptr deriving (Functor, Foldable, Traversable)
-- >
-- > memory1 = M.fromList [(1, Cons 2 1), (2, Nil)]
-- > withRecMap memory1 (const ()) -- Right ()
-- >
-- > memory2 = M.fromList [(1, Cons 2 3), (2, Nil)]
-- > withRecMap memory2 (const ()) -- Left [(1, Cons (2,Present) (3,Missing))]
--
-- See @'Data.Map.Justified.Tutorial.example5'@ for more usage examples.
withRecMap :: forall k f t . (Ord k, Traversable f, Representational f)
=> M.Map k (f k) -- ^ A map with key references
-> (forall ph. Map ph k (f (Key ph k)) -> t) -- ^ The checked continuation
-> Either [MissingReference k f] t -- ^ Resulting value, or failure report.
withRecMap m cont =
case snd (partition (allKeysPresent . snd) $ M.toList m) of
-- All referenced keys are found in the map; coerce the map's type.
[] -> Right $ cont (Map $ (coerceWith mapCoercion) m)
-- There were some dangling key references; report them.
bads -> Left (map (\(k,v) -> (k, fmap (id &&& locate) v)) bads)
where
allKeysPresent = all ((== Present) . locate)
locate k = if M.member k m then Present else Missing
nestedValueCoercion :: Coercion (f k) (f (Key ph0 k))
nestedValueCoercion = rep Coercion
mapCoercion :: Coercion (M.Map k (f k)) (M.Map k (f (Key ph0 k)))
mapCoercion = rep nestedValueCoercion
{--------------------------------------------------------------------
Gathering evidence
--------------------------------------------------------------------}
-- | /O(log n)/. Obtain evidence that the key is a member of the map.
--
-- Where "Data.Map" generally requires evidence that a key exists in a map
-- at every use of some functions (e.g. "Data.Map"'s @'Data.Map.lookup'@),
-- @'Map'@ requires the evidence up-front. After it is known that a key can be
-- found, there is no need for @'Maybe'@ types or run-time errors.
--
-- The @Maybe value@ that has to be checked at every lookup in "Data.Map"
-- is then shifted to a @Maybe (Key ph k)@ that has to be checked in order
-- to obtain evidence that a key is in the map.
--
-- Note that the "evidence" only exists at the type level, during compilation;
-- there is no runtime distinction between keys and keys-plus-evidence.
--
-- > withMap (M.fromList [(5,'a'), (3,'b')]) (isJust . member 1) == False
-- > withMap (M.fromList [(5,'a'), (3,'b')]) (isJust . member 5) == True
member :: Ord k => k -> Map ph k v -> Maybe (Key ph k)
member k (Map m) = fmap (const $ Key k) (M.lookup k m)
-- | A list of all of the keys in a map, along with proof
-- that the keys exist within the map.
keys :: Map ph k v -> [Key ph k]
keys (Map m) = map Key (M.keys m)
{--------------------------------------------------------------------
Lookup and update
--------------------------------------------------------------------}
-- | /O(log n)/. Find the value at a key. Unlike
-- "Data.Map"'s @'Data.Map.!'@, this function is total and can not fail at runtime.
(!) :: Ord k => Map ph k v -> Key ph k -> v
(!) = flip lookup
-- | /O(log n)/. Lookup the value at a key, known to be in the map.
--
-- The result is a @v@ rather than a @Maybe v@, because the
-- proof obligation that the key is in the map must already
-- have been discharged to obtain a value of type @Key ph k@.
--
lookup :: Ord k => Key ph k -> Map ph k v -> v
lookup (Key k) (Map m) = case M.lookup k m of
Just value -> value
Nothing -> error "Data.Map.Justified has been subverted!"
-- | /O(log n)/. Lookup the value at a key that is /not/ already known
-- to be in the map. Return @Just@ the value /and/ the key-with-evidence
-- if the key was present, or @Nothing@ otherwise.
lookupMay :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v)
lookupMay k (Map m) = fmap (\v -> (Key k, v)) (M.lookup k m)
-- | /O(log n)/. Find the largest key smaller than the given one
-- and return the corresponding (key,value) pair, with evidence for the key.
--
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLT 3 table == Nothing
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLT 4 table == Just (Key 3, 'a')
lookupLT :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v)
lookupLT k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupLT k m)
-- | /O(log n)/. Find the smallest key greater than the given one
-- and return the corresponding (key,value) pair, with evidence for the key.
--
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGT 4 table == Just (Key 5, 'b')
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGT 5 table == Nothing
lookupGT :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v)
lookupGT k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupGT k m)
-- | /O(log n)/. Find the largest key smaller than or equal to the given one
-- and return the corresponding (key,value) pair, with evidence for the key.
--
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLE 2 table == Nothing
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLE 4 table == Just (Key 3, 'a')
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLE 5 table == Just (Key 5, 'b')
lookupLE :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v)
lookupLE k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupLE k m)
-- | /O(log n)/. Find the smallest key greater than or equal to the given one
-- and return the corresponding (key,value) pair, with evidence for the key.
--
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGE 3 table == Just (Key 3, 'a')
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGE 4 table == Just (Key 5, 'b')
-- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGE 6 table == Nothing
lookupGE :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v)
lookupGE k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupGE k m)
-- | Adjust the valid at a key, known to be in the map,
-- using the given function.
--
-- Since the set of valid keys in the input map and output map
-- are the same, keys that were valid for the input map remain
-- valid for the output map.
adjust :: Ord k => (v -> v) -> Key ph k -> Map ph k v -> Map ph k v
adjust f (Key k) = mmap (M.adjust f k)
-- | Adjust the valid at a key, known to be in the map,
-- using the given function.
--
-- Since the set of valid keys in the input map and output map
-- are the same, keys that were valid for the input map remain
-- valid for the output map.
adjustWithKey :: Ord k => (Key ph k -> v -> v) -> Key ph k -> Map ph k v -> Map ph k v
adjustWithKey f (Key k) = mmap (M.adjustWithKey f' k)
where f' key = f (Key key)
-- | Replace the value at a key, known to be in the map.
--
-- Since the set of valid keys in the input map and output map
-- are the same, keys that were valid for the input map remain
-- valid for the output map.
reinsert :: Ord k => Key ph k -> v -> Map ph k v -> Map ph k v
reinsert (Key k) v = mmap (M.insert k v)
-- | Insert a value for a key that is /not/ known to be in the map,
-- evaluating the updated map with the given continuation.
--
-- The continuation is given three things:
--
-- 1. A proof that the inserted key exists in the new map,
--
-- 2. A function that can be used to convert evidence that a key
-- exists in the original map, to evidence that the key exists in
-- the updated map, and
--
-- 3. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/.
--
-- > withMap (M.fromList [(5,'a'), (3,'b')]) (\table -> inserting 5 'x' table $ \(_,_,table') -> theMap table') == M.fromList [(3, 'b'), (5, 'x')]
-- > withMap (M.fromList [(5,'a'), (3,'b')]) (\table -> inserting 7 'x' table $ \(_,_,table') -> theMap table') == M.fromList [(3, 'b'), (5, 'b'), (7, 'x')]
--
-- See @'Data.Map.Justified.Tutorial.example4'@ for more usage examples.
inserting :: Ord k
=> k -- ^ key to insert at
-> v -- ^ value to insert
-> Map ph k v -- ^ initial map
-> (forall ph'. (Key ph' k, Key ph k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation
-> t
inserting k v m cont = cont (Key k, qed, mmap (M.insert k v) m)
-- | /O(log n)/. Insert with a function, combining new value and old value.
-- @'insertingWith' f key value mp cont@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key /does/ exist, the function will
-- insert the pair @(key, f new_value old_value)@.
--
-- The continuation is given three things (as in @'inserting'@):
--
-- 1. A proof that the inserted key exists in the new map,
--
-- 2. A function that can be used to convert evidence that a key
-- exists in the original map, to evidence that the key exists in
-- the updated map, and
--
-- 3. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/.
--
-- > withMap (M.fromList [(5,"a"), (3,"b")]) (theMap . insertingWith (++) 5) == M.fromList [(3,"b"), (5,"xxxa")]
-- > withMap (M.fromList [(5,"a"), (3,"b")]) (theMap . insertingWith (++) 7) == M.fromList [(3,"b"), (5,"a"), (7,"xxx")]
insertingWith :: Ord k
=> (v -> v -> v) -- ^ combining function for existing keys
-> k -- ^ key to insert at
-> v -- ^ value to insert
-> Map ph k v -- ^ initial map
-> (forall ph'. (Key ph' k, Key ph k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation
-> t
insertingWith f k v m cont = cont (Key k, qed, mmap (M.insertWith f k v) m)
-- | /O(log n)/. Delete a key and its value from the map.
--
-- The continuation is given two things:
--
-- 1. A function that can be used to convert evidence that a key
-- exists in the /updated/ map, to evidence that the key exists
-- in the /original/ map. (contrast with 'inserting')
--
-- 2. The updated map itself.
--
deleting :: Ord k
=> k -- ^ key to remove
-> Map ph k v -- ^ initial map
-> (forall ph'. (Key ph' k -> Key ph k, Map ph' k v) -> t) -- ^ continuation
-> t
deleting k m cont = cont (qed, mmap (M.delete k) m)
-- | /O(log n)/. Difference of two maps.
-- Return elements of the first map not existing in the second map.
--
-- The continuation is given two things:
--
-- 1. A function that can be used to convert evidence that a key
-- exists in the difference, to evidence that the key exists
-- in the original left-hand map.
--
-- 2. The updated map itself.
--
subtracting :: Ord k
=> Map phL k a -- ^ the left-hand map
-> Map phR k b -- ^ the right-hand map
-> (forall ph'. (Key ph' k -> Key phL k, Map ph' k a) -> t) -- ^ continuation
-> t
subtracting mapL mapR cont = cont (qed, mmap2 M.difference mapL mapR)
{--------------------------------------------------------------------
Unions
--------------------------------------------------------------------}
-- | Take the left-biased union of two @'Data.Map.Justified.Map'@s, as in "Data.Map"'s
-- @'Data.Map.union'@, evaluating the unioned map with the given continuation.
--
-- The continuation is given three things:
--
-- 1. A function that can be used to convert evidence that a key exists in the left
-- map to evidence that the key exists in the union,
--
-- 2. A function that can be used to convert evidence that a key exists in the right
-- map to evidence that the key exists in the union, and
--
-- 3. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/.
--
unioning :: Ord k
=> Map phL k v -- ^ left-hand map
-> Map phR k v -- ^ right-hand map
-> (forall ph'. (Key phL k -> Key ph' k, Key phR k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation
-> t
unioning mapL mapR cont = cont (qed, qed, mmap2 M.union mapL mapR)
-- | @'unioningWith' f@ is the same as @'unioning'@, except that @f@ is used to
-- combine values that correspond to keys found in both maps.
unioningWith :: Ord k
=> (v -> v -> v) -- ^ combining function for intersection
-> Map phL k v -- ^ left-hand map
-> Map phR k v -- ^ right-hand map
-> (forall ph'. (Key phL k -> Key ph' k, Key phR k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation
-> t
unioningWith f mapL mapR cont = cont (qed, qed, mmap2 (M.unionWith f) mapL mapR)
-- | @'unioningWithKey' f@ is the same as @'unioningWith' f@, except that @f@ also
-- has access to the key and evidence that it is present in both maps.
unioningWithKey :: Ord k
=> (Key phL k -> Key phR k -> v -> v -> v) -- ^ combining function for intersection, using key evidence
-> Map phL k v -- ^ left-hand map
-> Map phR k v -- ^ right-hand map
-> (forall ph'. (Key phL k -> Key ph' k, Key phR k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation
-> t
unioningWithKey f mapL mapR cont = cont (qed, qed, mmap2 (M.unionWithKey f') mapL mapR)
where f' k = f (Key k) (Key k)
{--------------------------------------------------------------------
Filtering
--------------------------------------------------------------------}
-- | Keep only the keys and associated values in a map that satisfy
-- the predicate.
--
-- The continuation is given two things:
--
-- 1. A function that converts evidence that a key is present in
-- the filtered map into evidence that the key is present in
-- the original map, and
--
-- 2. The filtered map itself, with a new phantom type parameter.
--
filtering :: (v -> Bool) -- ^ predicate on values
-> Map ph k v -- ^ original map
-> (forall ph'. (Key ph' k -> Key ph k, Map ph' k v) -> t) -- ^ continuation
-> t
filtering f m cont = cont (qed, mmap (M.filter f) m)
-- | As 'filtering', except the filtering function also has access to
-- the key and existence evidence.
filteringWithKey :: (Key ph k -> v -> Bool) -- ^ predicate on keys and values
-> Map ph k v -- ^ original map
-> (forall ph'. (Key ph' k -> Key ph k, Map ph' k v) -> t) -- ^ continuation
-> t
filteringWithKey f m cont = cont (qed, mmap (M.filterWithKey (f . Key)) m)
{--------------------------------------------------------------------
Mapping and traversing
--------------------------------------------------------------------}
-- | /O(n)/. Map a function over all keys and values in the map.
--
mapWithKey :: (Key ph k -> a -> b)
-> Map ph k a
-> Map ph k b
mapWithKey f = mmap (M.mapWithKey f')
where f' k = f (Key k)
-- | /O(n)/. As in @'Data.Map.traverse'@: traverse the map, but give the
-- traversing function access to the key associated with each value.
traverseWithKey :: Applicative t
=> (Key ph k -> a -> t b) -- ^ traversal function
-> Map ph k a -- ^ the map to traverse
-> t (Map ph k b)
traverseWithKey f (Map m) = fmap Map (M.traverseWithKey f' m)
where f' k = f (Key k)
-- | /O(n)/. The function @'mapAccum'@ threads an accumulating
-- argument through the map in ascending order of keys.
--
mapAccum :: (a -> b -> (a,c))
-> a
-> Map ph k b
-> (a, Map ph k c)
mapAccum f a (Map m) = fmap Map (M.mapAccum f a m)
-- | /O(n)/. The function @'mapAccumWithKey'@ threads an accumulating
-- argument through the map in ascending order of keys.
--
mapAccumWithKey :: (a -> Key ph k -> b -> (a,c))
-> a
-> Map ph k b
-> (a, Map ph k c)
mapAccumWithKey f a (Map m) = fmap Map (M.mapAccumWithKey f' a m)
where f' x k = f x (Key k)
-- | /O(n*log n)/.
-- @'mappingKeys'@ evaluates a continuation with the map obtained by applying
-- @f@ to each key of @s@.
--
-- The size of the resulting map may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the value at the greatest of the
-- original keys is retained.
--
-- The continuation is passed two things:
--
-- 1. A function that converts evidence that a key belongs to the original map
-- into evidence that a key belongs to the new map.
--
-- 2. The new, possibly-smaller map.
--
--
mappingKeys :: Ord k2
=> (k1 -> k2) -- ^ key-mapping function
-> Map ph k1 v -- ^ initial map
-> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation
-> t
mappingKeys f m cont = cont (via f, mmap (M.mapKeys f) m)
-- | /O(n*log n)/.
-- Same as @'mappingKeys'@, but the key-mapping function can make use of
-- evidence that the input key belongs to the original map.
--
mappingKnownKeys :: Ord k2
=> (Key ph k1 -> k2) -- ^ key-and-evidence-mapping function
-> Map ph k1 v -- ^ initial map
-> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation
-> t
mappingKnownKeys f m cont = cont (Key . f, mmap (M.mapKeys f') m)
where f' k = f (Key k)
-- | /O(n*log n)/.
-- Same as @'mappingKeys'@, except a function is used to combine values when
-- two or more keys from the original map correspond to the same key in the
-- final map.
mappingKeysWith :: Ord k2
=> (v -> v -> v) -- ^ value-combining function
-> (k1 -> k2) -- ^ key-mapping function
-> Map ph k1 v -- ^ initial map
-> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation
-> t
mappingKeysWith op f m cont = cont (via f, mmap (M.mapKeysWith op f) m)
-- | /O(n*log n)/.
-- Same as @'mappingKnownKeys'@, except a function is used to combine values when
-- two or more keys from the original map correspond to the same key in the
-- final map.
mappingKnownKeysWith :: Ord k2
=> (v -> v -> v) -- ^ value-combining function
-> (Key ph k1 -> k2) -- ^ key-plus-evidence-mapping function
-> Map ph k1 v -- ^ initial map
-> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation
-> t
mappingKnownKeysWith op f m cont = cont (Key . f, mmap (M.mapKeysWith op f') m)
where f' k = f (Key k)
{--------------------------------------------------------------------
Intersections
--------------------------------------------------------------------}
-- | Take the left-biased intersections of two @'Data.Map.Justified.Map'@s, as in "Data.Map"'s
-- @'Data.Map.intersection'@, evaluating the intersection map with the given continuation.
--
-- The continuation is given two things:
--
-- 1. A function that can be used to convert evidence that a key exists in the intersection
-- to evidence that the key exists in each original map, and
--
-- 2. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/.
--
intersecting :: Ord k
=> Map phL k a -- ^ left-hand map
-> Map phR k b -- ^ right-hand map
-> (forall ph'. (Key ph' k -> (Key phL k, Key phR k), Map ph' k a) -> t) -- ^ continuation
-> t
intersecting mapL mapR cont = cont (qed2, mmap2 M.intersection mapL mapR)
-- | As @'intersecting'@, but uses the combining function to merge mapped values on the intersection.
intersectingWith :: Ord k
=> (a -> b -> c) -- ^ combining function
-> Map phL k a -- ^ left-hand map
-> Map phR k b -- ^ right-hand map
-> (forall ph'. (Key ph' k -> (Key phL k, Key phR k), Map ph' k c) -> t) -- ^ continuation
-> t
intersectingWith f mapL mapR cont = cont (qed2, mmap2 (M.intersectionWith f) mapL mapR)
-- | As @'intersectingWith'@, but the combining function has access to the map keys.
intersectingWithKey :: Ord k
=> (Key phL k -> Key phR k -> a -> b -> c) -- ^ combining function
-> Map phL k a -- ^ left-hand map
-> Map phR k b -- ^ right-hand map
-> (forall ph'. (Key ph' k -> (Key phL k, Key phR k), Map ph' k c) -> t) -- ^ continuation
-> t
intersectingWithKey f mapL mapR cont = cont (qed2, mmap2 (M.intersectionWithKey f') mapL mapR)
where f' k = f (Key k) (Key k)
{--------------------------------------------------------------------
Zipping
--------------------------------------------------------------------}
-- | Zip the values in two maps together. The phantom type @ph@ ensures
-- that the two maps have the same set of keys, so no elements are left out.
--
zip :: Ord k
=> Map ph k a
-> Map ph k b
-> Map ph k (a,b)
zip = zipWith (,)
-- | Combine the values in two maps together. The phantom type @ph@ ensures
-- that the two maps have the same set of keys, so no elements are left out.
zipWith :: Ord k
=> (a -> b -> c)
-> Map ph k a
-> Map ph k b
-> Map ph k c
zipWith f m1 m2 = mapWithKey (\k x -> f x (m2 ! k)) m1
-- | Combine the values in two maps together, using the key and values.
-- The phantom type @ph@ ensures that the two maps have the same set of
-- keys.
zipWithKey :: Ord k
=> (Key ph k -> a -> b -> c)
-> Map ph k a
-> Map ph k b
-> Map ph k c
zipWithKey f m1 m2 = mapWithKey (\k x -> f k x (m2 ! k)) m1
{--------------------------------------------------------------------
Indexing
--------------------------------------------------------------------}
-- | /O(log n)/. Return the /index/ of a key, which is its zero-based index in
-- the sequence sorted by keys. The index is a number from /0/ up to, but not
-- including, the size of the map. The index also carries a proof that it is
-- valid for the map.
--
-- Unlike "Data.Map"'s @'Data.Map.findIndex'@, this function can not fail at runtime.
findIndex :: Ord k => Key ph k -> Map ph k a -> Index ph
findIndex (Key k) (Map m) = Index (M.findIndex k m)
-- | /O(log n)/. Retrieve an element by its /index/, i.e. by its zero-based
-- index in the sequence sorted by keys.
--
-- Unlike "Data.Map"'s @'Data.Map.elemAt'@, this function can not fail at runtime.
elemAt :: Index ph -> Map ph k v -> (Key ph k, v)
elemAt (Index n) (Map m) = let (k,v) = M.elemAt n m in (Key k, v)
{--------------------------------------------------------------------
Utilities
--------------------------------------------------------------------}
-- | Build a value by "tying the knot" according to the references in the map.
tie :: (Functor f, Ord k)
=> (f a -> a) -- ^ folding function
-> Map ph k (f (Key ph k)) -- ^ map with recursive key references
-> Key ph k
-> a
tie phi m = go
where
go = (`lookup` table)
table = fmap (phi . fmap go) m
{--------------------------------------------------------------------
INTERNAL ONLY
These functions are used to inform the type system about
invariants of Data.Map. They cannot be available outside of
this module.
--------------------------------------------------------------------}
-- | Coerce key-existence evidence
qed :: Key ph k -> Key ph' k
qed (Key k) = Key k
-- | Coerce key-existence evidence
qed2 :: Key ph k -> (Key phL k, Key phR k)
qed2 (Key k) = (Key k, Key k)
-- | Coerce key-existence evidence transported along a function
via :: (k1 -> k2) -> Key ph k1 -> Key ph' k2
via f (Key k) = Key (f k)
-- | Coerce one map type to another, using a function on "Data.Map"'s @'Data.Map.Map'@.
mmap :: (M.Map k1 v1 -> M.Map k2 v2) -> Map ph1 k1 v1 -> Map ph2 k2 v2
mmap f (Map m) = Map (f m)
-- | Coerce one map type to another, using a binary function on "Data.Map"'s @'Data.Map.Map'@.
mmap2 :: (M.Map k1 v1 -> M.Map k2 v2 -> M.Map k3 v3)
-> Map ph1 k1 v1
-> Map ph2 k2 v2
-> Map ph3 k3 v3
mmap2 f (Map m1) (Map m2) = Map (f m1 m2)
|
matt-noonan/justified-containers
|
src/Data/Map/Justified.hs
|
Haskell
|
bsd-2-clause
| 35,649
|
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# OPTIONS_HADDOCK not-home #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Edward Kmett and Ted Cooper
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Ted Cooper <anthezium@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- STM-based RCU with concurrent writers
-----------------------------------------------------------------------------
module Control.Concurrent.RCU.STM.Internal
( SRef(..)
, RCUThread(..)
, RCU(..)
, runRCU
, ReadingRCU(..)
, WritingRCU(..)
) where
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.RCU.Class
import Control.Monad
import Control.Monad.IO.Class
import Data.Coerce
import Data.Int
import Prelude hiding (read, Read)
--------------------------------------------------------------------------------
-- * Shared References
--------------------------------------------------------------------------------
-- | Shared references
newtype SRef s a = SRef { unSRef :: TVar a }
deriving Eq
--------------------------------------------------------------------------------
-- * Read-Side Critical Sections
--------------------------------------------------------------------------------
-- | This is the basic read-side critical section for an RCU computation
newtype ReadingRCU s a = ReadingRCU { runReadingRCU :: IO a } deriving (Functor, Applicative, Monad)
instance MonadNew (SRef s) (ReadingRCU s) where
newSRef = r where
r :: forall a. a -> ReadingRCU s (SRef s a)
r = coerce (newTVarIO :: a -> IO (TVar a))
instance MonadReading (SRef s) (ReadingRCU s) where
readSRef = r where
r :: forall a. SRef s a -> ReadingRCU s a
r = coerce (readTVarIO :: TVar a -> IO a)
{-# INLINE readSRef #-}
--------------------------------------------------------------------------------
-- * Write-Side Critical Sections
--------------------------------------------------------------------------------
-- | This is the basic write-side critical section for an RCU computation
newtype WritingRCU s a = WritingRCU { runWritingRCU :: TVar Int64 -> STM a }
deriving Functor
instance Applicative (WritingRCU s) where
pure a = WritingRCU $ \ _ -> pure a
WritingRCU mf <*> WritingRCU ma = WritingRCU $ \c -> mf c <*> ma c
instance Monad (WritingRCU s) where
return a = WritingRCU $ \ _ -> pure a
WritingRCU m >>= f = WritingRCU $ \ c -> do
a <- m c
runWritingRCU (f a) c
fail s = WritingRCU $ \ _ -> fail s
instance Alternative (WritingRCU s) where
empty = WritingRCU $ \ _ -> empty
WritingRCU ma <|> WritingRCU mb = WritingRCU $ \c -> ma c <|> mb c
instance MonadPlus (WritingRCU s) where
mzero = WritingRCU $ \ _ -> mzero
WritingRCU ma `mplus` WritingRCU mb = WritingRCU $ \c -> ma c `mplus` mb c
instance MonadNew (SRef s) (WritingRCU s) where
newSRef a = WritingRCU $ \_ -> SRef <$> newTVar a
instance MonadReading (SRef s) (WritingRCU s) where
readSRef (SRef r) = WritingRCU $ \ _ -> readTVar r
{-# INLINE readSRef #-}
instance MonadWriting (SRef s) (WritingRCU s) where
writeSRef (SRef r) a = WritingRCU $ \ _ -> writeTVar r a
synchronize = WritingRCU $ \ c -> modifyTVar' c (+1)
--------------------------------------------------------------------------------
-- * RCU Context
--------------------------------------------------------------------------------
-- | This is an RCU computation. It can use 'forking' and 'joining' to form
-- new threads, and then you can use 'reading' and 'writing' to run classic
-- read-side and write-side RCU computations. Contention between multiple
-- write-side computations is managed by STM.
newtype RCU s a = RCU { unRCU :: TVar Int64 -> IO a }
deriving Functor
instance Applicative (RCU s) where
pure = return
(<*>) = ap
instance Monad (RCU s) where
return a = RCU $ \ _ -> return a
RCU m >>= f = RCU $ \s -> do
a <- m s
unRCU (f a) s
instance MonadNew (SRef s) (RCU s) where
newSRef a = RCU $ \_ -> SRef <$> newTVarIO a
-- | This is a basic 'RCU' thread. It may be embellished when running in a more
-- exotic context.
data RCUThread s a = RCUThread
{ rcuThreadId :: {-# UNPACK #-} !ThreadId
, rcuThreadVar :: {-# UNPACK #-} !(MVar a)
}
instance MonadRCU (SRef s) (RCU s) where
type Reading (RCU s) = ReadingRCU s
type Writing (RCU s) = WritingRCU s
type Thread (RCU s) = RCUThread s
forking (RCU m) = RCU $ \ c -> do
result <- newEmptyMVar
tid <- forkIO $ do
x <- m c
putMVar result x
return (RCUThread tid result)
joining (RCUThread _ m) = RCU $ \ _ -> readMVar m
reading (ReadingRCU m) = RCU $ \ _ -> m
writing (WritingRCU m) = RCU $ \ c -> atomically $ do
_ <- readTVar c -- deliberately incur a data dependency!
m c
{-# INLINE forking #-}
{-# INLINE joining #-}
{-# INLINE reading #-}
{-# INLINE writing #-}
instance MonadIO (RCU s) where
liftIO m = RCU $ \ _ -> m
{-# INLINE liftIO #-}
-- | Run an RCU computation.
runRCU :: (forall s. RCU s a) -> IO a
runRCU m = do
c <- newTVarIO 0
unRCU m c
{-# INLINE runRCU #-}
|
anthezium/rcu
|
src/Control/Concurrent/RCU/STM/Internal.hs
|
Haskell
|
bsd-2-clause
| 5,541
|
module Handler.PostNew where
import Import
import Yesod.Form.Bootstrap3
import Yesod.Text.Markdown
blogPostNewForm :: AForm Handler BlogPost
blogPostNewForm = BlogPost
<$> areq textField (bfs ("Title" :: Text)) Nothing
<*> lift (liftIO getCurrentTime)
<*> lift (liftIO getCurrentTime)
<*> areq markdownField (bfs ("Article" :: Text)) Nothing
getPostNewR :: Handler Html
getPostNewR = do
(widget, enctype) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm blogPostNewForm
defaultLayout $ do
$(widgetFile "posts/new")
-- YesodPersist master => YesodPersistBackend master ~ SqlBackend => …
postPostNewR :: Handler Html
postPostNewR = do
((res, widget), enctype) <- runFormPostNoToken $ renderBootstrap3 BootstrapBasicForm blogPostNewForm
case res of
FormSuccess blogPost -> do
blogPostId <- runDB $ insert blogPost
redirect $ PostDetailsR blogPostId
FormFailure errorMsgs -> defaultLayout $(widgetFile "errorpage")
_ -> defaultLayout $(widgetFile "posts/new")
|
roggenkamps/steveroggenkamp.com
|
Handler/PostNew.hs
|
Haskell
|
bsd-3-clause
| 1,115
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Pack7 where
import Data.Set (Set)
import qualified Data.Set as Set
import GHC.Exts (Constraint)
-- type class for abstract sets
class ISet s where
type ISetCxt (s :: * -> *) a :: Constraint
fromList :: ISetCxt s a => [a] -> s a
instance ISet [] where
type ISetCxt [] a = ()
fromList = id
instance ISet Set where
type ISetCxt Set a = Ord a
fromList = Set.fromList
-- type class for mapping sets in containers
class ISet g => SetMap s t g | t -> g where
setMap :: s -> t
instance (ISet g, ISetCxt g a, ISetCxt g b) =>
SetMap ([a], [b]) (g a, g b) g where
setMap (a, b) = (fromList a, fromList b)
p1 :: ([Int], [Bool])
p1 = ([1, 2], [True, False])
{-|
>>> testSetMap
(fromList [1,2],fromList [False,True])
-}
testSetMap :: (Set Int, Set Bool)
testSetMap = setMap p1
-- TBD: replace ISet to a type variable
|
notae/haskell-exercise
|
pack/Pack7.hs
|
Haskell
|
bsd-3-clause
| 1,188
|
module Util.Command where
import System.Exit
import Data.Tuple
import Data.Map (Map, (!))
import qualified Data.Map as M
import Data.Char
import Genome.Dna.Kmer
import Genome.Dna.Dna
data Command = Command {utility :: String,
arguments :: Map String String
}
instance Show Command where
show (Command name args) = foldl addArg ("command" ++ name) (M.toList args)
where addArg = \s xy -> s ++ " -" ++ (fst xy) ++ "=" ++ (snd xy)
emptyCommand = Command "empty" M.empty
readCommand :: [String] -> Command
readCommand [] = emptyCommand
readCommand (u:args) = if (allowedWord u)
then Command u (readArgs args)
else Command "illegal" M.empty
where
allowedWord :: String -> Bool
allowedWord [] = False
allowedWord (x:xs) = (isAlphaNum x) && all allowedChar xs
allowedChar = \c -> (c == '-') || (isAlphaNum c)
readArgs :: [String] -> Map String String
readArgs = M.fromList . (map readOneArg)
where
readOneArg s = (tail $ takeWhile (/= '=') s, tail $ dropWhile (/= '=') s)
availableCommands = M.fromList [
("ptrn-count", "-f=<file-name> -p=<ptrn>"),
("most-frequent-kmers", "-f=<file-name> -k=<kmer-size> -n=<number>")
]
usage u = if M.notMember u availableCommands
then "Exception: " ++ u ++ " is not a valid command."
else "Usage: " ++ u ++ " " ++ (availableCommands ! u)
execute :: Command -> IO()
execute (Command "hello" _) = do
putStrLn "Hello jee! What may bioalgo tool-kit do for you?"
putStrLn "Please call me with a command"
putStrLn ""
putStrLn "!!! BYE for now !!!"
execute (Command "ptrn-count" argMap) = do
text <- readFile (argMap ! "f")
pcounts <- return $ ptrnCount (argMap ! "p") text
putStr "number of appearances of "
putStr (argMap ! "p")
putStr ": "
putStrLn (show pcounts)
execute (Command "most-frequent-kmers" argMap) = do
text <- readFile f
kcounts <- return $ kmerCounts k text
putStr (show (sum kcounts))
putStr (" total ")
putStr (show k)
putStrLn "-mers found."
putStr " of which "
putStr (show (length kcounts))
putStrLn " are unique."
putStrLn $ "Top " ++ (show n) ++ " " ++ (show k) ++ "-mers: "
mapM_ (\(s, m) -> putStrLn ((show m) ++ ": " ++ s))(topFrequentKmers n kcounts)
where
k = read (argMap ! "k") :: Int
n = read (argMap ! "n") :: Int
f = argMap ! "f"
execute (Command "reverse-complement" argMap) = do
putStrLn (if (isDNA seq) then reverseComplement seq else "Not a DNA sequence")
where seq = argMap ! "s"
execute (Command "illegal" _) = do
putStrLn "Exception: illegal utility name."
cltoolsUsage >> exitWith ExitSuccess
execute (Command "empty" _) = do
putStrLn "Exception: utility not specified."
cltoolsUsage >> exitWith ExitSuccess
-- last case, when every other case unmet
execute (Command s _) = do
putStrLn $ "Exception: unknown utility " ++ s ++ "."
cltoolsUsage >> exitWith ExitSuccess
cltoolsUsage = do
putStrLn "Usage: [-vh] <utility> <arguments>"
putStrLn "Available utilities: "
mapM pcmd (M.toList availableCommands)
where pcmd = (\ua -> putStrLn ((fst ua) ++ " " ++ (snd ua)))
|
visood/bioalgo
|
src/lib/Util/Command.hs
|
Haskell
|
bsd-3-clause
| 3,189
|
{-# Language ScopedTypeVariables #-}
module Pipes.Formats where
import Control.Monad as M
import Data.Array.Accelerate as A
import Data.Array.Accelerate.IO as A
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Storable.Mutable as SM
import Pipes
import Prelude as P
vectorToArray :: (Int,Int,Int) -> Pipe (S.Vector Word8) (Array DIM3 Word8) IO ()
vectorToArray (h,w,d) =
let
dim = Z :. h :. w :. d
in
forever $ do
v <- await
yield $ fromVectors dim v
-- | Takes in vectors and 'chunks' them out as int x dim size vectors
--
vectorsToChunks
:: forall m. MonadIO m
=> Int -> (Int,Int,Int) -> Pipe (S.Vector Word8) (S.Vector Word8) m ()
vectorsToChunks limit (h,w,d) =
let
maxCubeSize = limit * imageSize
imageSize = (h*w*d)
cubeAggregator
:: Pipe (S.Vector Word8) (S.Vector Word8) m ()
cubeAggregator =
do
mem <- liftIO $ SM.new maxCubeSize
M.forM_ (P.init [0..limit]) $
(\i ->
do
arr <- await
let
sliced = SM.unsafeSlice (i*imageSize) (imageSize) mem
thawed <- liftIO $ S.unsafeThaw arr
liftIO $ SM.copy sliced thawed
)
liftIO (S.unsafeFreeze mem) >>= yield
in
forever $ cubeAggregator
-- | Takes in chunks and slices them out as int number of dim vectors
--
chunksToVectors
:: MonadIO m
=> Int -> (Int,Int,Int) -> Pipe (S.Vector Word8) (S.Vector Word8) m ()
chunksToVectors limit (h,w,d) =
let
imageSize = h*w*d
slicer =
do
chunk <- await
mapM_ yield $ P.map (\i -> S.slice (i*imageSize) imageSize chunk) $ P.init [0..limit]
in
forever slicer
|
cpdurham/accelerate-camera-sandbox
|
src/Pipes/Formats.hs
|
Haskell
|
bsd-3-clause
| 1,722
|
{-# LANGUAGE QuasiQuotes #-}
module System.Console.CmdArgs.Test.SplitJoin(test) where
import System.Console.CmdArgs.Explicit
import System.Console.CmdArgs.Test.Util
import Control.Monad
test = do
forM_ tests $ \(src,parsed) -> do
let a = splitArgs src
b1 = joinArgs parsed
b2 = joinArgs $ splitArgs b1
if a == parsed then return () else failure "splitArgs" [("Given ",src),("Expected",show parsed),("Found ",show a)]
if b1 == b2 then return () else failure "joinArgs" [("Given ",show parsed),("Expected",b1),("Found ",b2)]
success
{-
newtype CmdLine = CmdLine String deriving Show
instance Arbitrary CmdLine where
arbitrary = fmap CmdLine $ listOf $ elements "abcd \\/\'\""
generateTests :: IO ()
generateTests = withTempFile $ \src -> do
writeFile src "import System.Environment\nmain = print =<< getArgs\n"
quickCheckWith stdArgs{chatty=False} $ \(CmdLine x) -> unsafePerformIO $ do
putStr $ ",(,) " ++ (show x) ++ " "
system $ "runghc \"" ++ src ++ "\" " ++ x
return True
withTempFile :: (FilePath -> IO a) -> IO a
withTempFile f = bracket
(do (file,h) <- openTempFile "." "cmdargs.hs"; hClose h; return file)
removeFile
f
-}
-- Pregenerate the QuickCheck tests and run them through the system console
-- Not done each time for three reasons
-- * Avoids an extra dependency on QuickCheck + process
-- * Slow to run through the command line
-- * Can't figure out how to read the output, without adding more escaping (which breaks the test)
tests =
[f "" []
,f "c" ["c"]
,f "b" ["b"]
,f "\\" ["\\"]
,f "'//" ["'//"]
,f "a" ["a"]
,f "cda" ["cda"]
,f "b'" ["b'"]
,f "" []
,f " " []
,f "/b" ["/b"]
,f "\"b/\"d a'b'b" ["b/d","a'b'b"]
,f "d'c a\"/\\" ["d'c","a/\\"]
,f "d" ["d"]
,f "bb' " ["bb'"]
,f "b'\\" ["b'\\"]
,f "\"\\ac" ["\\ac"]
,f "\\'\"abbb\"c/''' \\ c" ["\\'abbbc/'''","\\","c"]
,f "/bbdbb a " ["/bbdbb","a"]
,f "b\" d" ["b d"]
,f "" []
,f "\\cc/''\\b\\ccc\\'\\b\\" ["\\cc/''\\b\\ccc\\'\\b\\"]
,f "/" ["/"]
,f "///\"b\\c/b\"cd//c'\"" ["///b\\c/bcd//c'"]
,f "\\\"d\\\\' /d\\\\/bb'a /\\d" ["\"d\\\\'","/d\\\\/bb'a","/\\d"]
,f "c/ \\''/c b\\'" ["c/","\\''/c","b\\'"]
,f "dd'b\\\\\\' /c'aaa\"" ["dd'b\\\\\\'","/c'aaa"]
,f "b'd''\\/ b\\'b'db/'cd " ["b'd''\\/","b\\'b'db/'cd"]
,f "a\"ba\\/\\ " ["aba\\/\\ "]
,f "b\"'dd'c /b/c\"bbd \"\"\\ad'\"c\\\"" ["b'dd'c /b/cbbd","\\ad'c\""]
,f "da 'c\\\\acd/'dbaaa///dccbc a \\" ["da","'c\\\\acd/'dbaaa///dccbc","a","\\"]
,f "a'ac \"da\"" ["a'ac","da"]
,f "\"'\\\"/\"\"b\\b \"'\"\"ccd'a\"/c /da " ["'\"/\"b\\b","'\"ccd'a/c /da "]
,f "d\"\\c\\\\cb c/\"aa' b\"\\/d \"'c c/" ["d\\c\\\\cb c/aa'","b\\/d 'c","c/"]
,f "dbc\\/\"\"//c/\"accda" ["dbc\\///c/accda"]
,f "aca a'' \\ c b'\\/d\\" ["aca","a''","\\","c","b'\\/d\\"]
,f "dc\"bc/a\\ccdd\\\\aad\\c'ab '\\cddcdba" ["dcbc/a\\ccdd\\\\aad\\c'ab '\\cddcdba"]
,f " c'\"ba \"b\\dc\"" ["c'ba b\\dc"]
,f "a\\acd/a \"'c /'c'" ["a\\acd/a","'c /'c'"]
,f " ac ddc/\"\"a/\\bd\\d c'cac\"c\\a/a''c" ["ac","ddc/a/\\bd\\d","c'cacc\\a/a''c"]
,f "b/cd\"//bb\"/daaab/ b b \"' d\"a\" 'd b" ["b/cd//bb/daaab/","b","b","' da 'd b"]
,f "a\"cc'cd\"\\'ad '\"dcc acb\"\\\\" ["acc'cd\\'ad","'dcc acb\\\\"]
,f "/bc/bc'/\"d \"a/\"\\ad aba\\da" ["/bc/bc'/d a/\\ad aba\\da"]
,f "b\\a" ["b\\a"]
,f "/dc ''c'a\"'/'\\ /'cd\\'d/'db/b\"' cabacaaa\"\"dd" ["/dc","''c'a'/'\\ /'cd\\'d/'db/b'","cabacaaadd"]
,f "\"ac\\\"c'/c'b\"b\"b'd\"c\"\"" ["ac\"c'/c'bbb'dc"]
,f "/ 'ccc\"d\\dc'\"'\\ b" ["/","'cccd\\dc''\\","b"]
,f " '\"/\\cc\\/c '\\\\" ["'/\\cc\\/c '\\\\"]
,f "\\ \\' ' /d \"cc\\\\//da\"d'a/a\"ca\\\\\"\\cb c\"d'b 'acb" ["\\","\\'","'","/d","cc\\\\//dad'a/aca\\\\cb","cd'b 'acb"]
,f "a\"\"d'\"a\"\\ \\c db'da/d\\c\"a/ aa c/db" ["ad'a\\","\\c","db'da/d\\ca/ aa c/db"]
,f " d\\" ["d\\"]
,f "d c b'/\\/'\"/'a'aa\"a\"/ad\\/" ["d","c","b'/\\/'/'a'aaa/ad\\/"]
,f " a \\' /" ["a","\\'","/"]
,f "'/ c" ["'/","c"]
,f "acd 'bcab /ba'daa'/ba/\"dcdadbcacb" ["acd","'bcab","/ba'daa'/ba/dcdadbcacb"]
,f "a\\\"dd'a c\"a\"\"ac\\" ["a\"dd'a","ca\"ac\\"]
,f "\"dba /'bb\\ d ba '/c' \"dd\\' cbcd c /b/\\b///" ["dba /'bb\\ d ba '/c' dd\\'","cbcd","c","/b/\\b///"]
,f "a'c/c \"ccb '/d\\abd/bc " ["a'c/c","ccb '/d\\abd/bc "]
,f "\\da\"\\//add\\\\ c" ["\\da\\//add\\\\ c"]
,f "c/\\\"// a/\"ac\"//''ba\"c/\\bc\\\"d\"bc/d" ["c/\"//","a/ac//''bac/\\bc\"dbc/d"]
,f "/d/ a dc'\\ \"" ["/d/","a","dc'\\",""]
,f " \"dc//b\\cd/ \\ac\"b\"b\"d\"\"\"dd\"\" ' a\\'/ \"/'/\\a/abd\\ddd" ["dc//b\\cd/ \\acbbd\"dd","'","a\\'/","/'/\\a/abd\\ddd"]
,f "\\' ' d\"b bbc" ["\\'","'","db bbc"]
,f "'ba\\a'db/bd d\\'b\\ \\/a'da' " ["'ba\\a'db/bd","d\\'b\\","\\/a'da'"]
,f "\\b\\cc\"\"d' dd ddcb\"d" ["\\b\\ccd'","dd","ddcbd"]
,f "d\"dc'\\d\"/'\\\"b\\c'c\" db' \\'b/\"a' / da'\"/ab'\\ c\\bc\\//dbcb\\" ["ddc'\\d/'\"b\\c'c db' \\'b/a'","/","da'/ab'\\ c\\bc\\//dbcb\\"]
,f " b ddbbbbc\"da\\c\"'\\" ["b","ddbbbbcda\\c'\\"]
,f "b/\"d dacd'/'\\\"''a a /'\\c'b ab\\ dda\\c'abdd'a\"//d \\\\\\ d\"\"" ["b/d dacd'/'\"''a a /'\\c'b ab\\ dda\\c'abdd'a//d","\\\\\\","d"]
,f "/c\"\" dd'a'/b\\/'\"'/" ["/c","dd'a'/b\\/''/"]
,f "/\"'\"\"'cc a a\\dd''\\'b" ["/'\"'cc","a","a\\dd''\\'b"]
,f "c\"dcd''aba\" \" /'" ["cdcd''aba"," /'"]
,f "'\"/''\\\\d'/ad\\baadabdca\\ /\\'''bd\\/\"'/' aca \\ \\a'\\ cd\"d /bdcd''cac" ["'/''\\\\d'/ad\\baadabdca\\ /\\'''bd\\/'/'","aca","\\","\\a'\\","cdd /bdcd''cac"]
,f "\" /\"da" [" /da"]
,f "'\"ca/'d/d/d\\ca\"/\"\" ddac cc\" ''a c''bd\"bc'dc\\/\"b\"a\\\"\"a/\\ " ["'ca/'d/d/d\\ca/","ddac","cc ''a c''bdbc'dc\\/ba\"a/\\ "]
,f "\\\\d'ad ' ''\"cd/a \"\"\\'\\\"'dc\\" ["\\\\d'ad","'","''cd/a \"\\'\"'dc\\"]
,f " ab c'\\a" ["ab","c'\\a"]
,f "b" ["b"]
,f "''c dc c\\'d'ab'd\"\\\"cca\"b'da\"dbcdbd\"cd'/d \\cd'\"d \"\"b cdc''/\\\"b'" ["''c","dc","c\\'d'ab'd\"ccab'dadbcdbdcd'/d","\\cd'd \"b","cdc''/\"b'"]
,f " \"'cb dbddbdd/" ["'cb dbddbdd/"]
,f "a/\"d// dd/cc/\"cc\"d\" d\\/a a \\c\" \\\\/\"\\ bcc'ac'\"\\c//d\"da/\\aac\\b\"c/'b\"\"bbd/\\" ["a/d// dd/cc/ccd","d\\/a","a","\\c \\\\/\\","bcc'ac'\\c//dda/\\aac\\bc/'b\"bbd/\\"]
,f "b\"ddccd\"a\"/ba\"" ["bddccda/ba"]
,f " \" c/b/'/bdd cb d'c a'\"'a d\\\\db//\\\"' c'/'c\\/aa" [" c/b/'/bdd cb d'c a''a","d\\\\db//\"'","c'/'c\\/aa"]
,f "\\caab" ["\\caab"]
,f "bb\"'\"/d'bad 'd\\/'\\b//\\\\ \\d''c\"c b\\b/\\" ["bb'/d'bad","'d\\/'\\b//\\\\","\\d''cc b\\b/\\"]
,f " c'a\" \\cab\"bd\"dcd\"/cb/\"\"b\"b'\"d" ["c'a \\cabbddcd/cb/bb'd"]
,f "\\/ \"c'ca" ["\\/","c'ca"]
,f " d' /c'bc\"'/'\\\\dca'cc\"'\"''/d cb//'a \"bd ab\"dcaadc\\\"'d\\\"/a\"a\\\"ba//b/ d/dbac/d\\caa\"bc/ " ["d'","/c'bc'/'\\\\dca'cc'''/d cb//'a bd","abdcaadc\"'d\"/aa\"ba//b/","d/dbac/d\\caabc/ "]
,f "/\"\\db'd/ ca\"ad b\\\\\"cd/a bbc\\ " ["/\\db'd/ caad","b\\cd/a bbc\\ "]
,f "cdc bd'/\"c''c d \\\"aa \\d\\ bb'b/ /b/a/c'acda\\'\"\"c \"bbbaa/'/a \\aca\"'/ac' " ["cdc","bd'/c''c d \"aa \\d\\ bb'b/ /b/a/c'acda\\'\"c","bbbaa/'/a \\aca'/ac'"]
,f "ad/'b\\d /cc\"\"ab \\ \"' ''b\\\"/\\ a\"'d\"\\ddacdbbabb b b //' acd\"c\\d'd\\b\"'\\\"aaba/bda/c'// \\b" ["ad/'b\\d","/ccab","\\","' ''b\"/\\ a'd\\ddacdbbabb b b //' acdc\\d'd\\b'\"aaba/bda/c'// \\b"]
,f "bac cc \"ac\"/ca/ '\"\" b/b d /cd'\\'bb\" \\ \"b '/ b c ' c''\"a/ad\\ " ["bac","cc","ac/ca/","'","b/b","d","/cd'\\'bb \\ b","'/","b","c","'","c''a/ad\\ "]
,f "baa' b'b''\\dab/'c" ["baa'","b'b''\\dab/'c"]
,f "cb\\\\ " ["cb\\\\"]
,f "/b'a''d\"b\" 'c'b ba\\'b\" bb" ["/b'a''db","'c'b","ba\\'b bb"]
,f "b /\"ca\\cbac " ["b","/ca\\cbac "]
,f " \"\"/\"bcaa\"\"a' \\/bb \"a\\\"'\"" ["/bcaa\"a'","\\/bb","a\"'"]
,f "\"c /''c\"\\badc/\\daa/\\ c\"a c\\ \\/cab \"b\"\\ ba\"\"/d/cd'a ad'c/ad\"' a\\d/d\\c\\'cdccd/\"a'/\"b///ac\"" ["c /''c\\badc/\\daa/\\","ca c\\ \\/cab b\\ ba\"/d/cd'a","ad'c/ad' a\\d/d\\c\\'cdccd/a'/b///ac"]
,f "/cbbd\"/b' /dd\"/c\\ca/'\"\\ cc \\d\"aca/\"b caa\\d\\'\"b'b dc\"cd\\'c\" 'd/ac\"cacc\"" ["/cbbd/b' /dd/c\\ca/'\\ cc \\daca/b caa\\d\\'b'b","dccd\\'c","'d/accacc"]
,f "bc/bd\\ca\\bcacca\"\"\\c/\\ /\"\"a/\"c'//b'\\d/a/'ab/cbd/cacb//b \\d\"aac\\d'\"/" ["bc/bd\\ca\\bcacca\\c/\\","/a/c'//b'\\d/a/'ab/cbd/cacb//b \\daac\\d'/"]
,f "bbac bdc/d\\\"/db\"dbdb\"a \" /\"/'a\\acacbcc c'//\\//b\"ca\"bcca c\\/aaa/c/bccbccaa \"\" cdccc/bddcbc c''" ["bbac","bdc/d\"/dbdbdba"," //'a\\acacbcc","c'//\\//bcabcca","c\\/aaa/c/bccbccaa","","cdccc/bddcbc","c''"]
]
where f = (,)
|
ndmitchell/cmdargs
|
System/Console/CmdArgs/Test/SplitJoin.hs
|
Haskell
|
bsd-3-clause
| 8,627
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
-- | This module is where all the routes and handlers are defined for your
-- site. The 'app' function is the initializer that combines everything
-- together and is exported by this module.
module Site
( app
) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.MVar
import Control.Lens
import Control.Monad
import Control.Monad.Reader (asks)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Acid as AS
import Data.ByteString (ByteString)
import Data.Default (def)
import Data.List (groupBy)
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Time.Clock
import Data.Time.Clock.POSIX
import qualified Network.Gravatar as G
import Snap
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.AcidState (Update, Query, update, query, acidInitManual)
import Snap.Snaplet.Auth
import Snap.Snaplet.Auth.Backends.JsonFile
import Snap.Snaplet.Heist
import Snap.Snaplet.Session.Backends.CookieSession
import Snap.Util.FileServe
import Heist
import qualified Heist.Interpreted as I
import qualified Text.XmlHtml as X
import Web.Bugzilla
------------------------------------------------------------------------------
import Application
import Bugzilla
------------------------------------------------------------------------------
-- | Render login form
handleLogin :: Maybe T.Text -> Handler App (AuthManager App) ()
handleLogin authError = heistLocal (I.bindSplices errs) $ render "login"
where
errs = maybe noSplices splice authError
splice err = "loginError" ## I.textSplice err
------------------------------------------------------------------------------
-- | Handle login submit
handleLoginSubmit :: Handler App (AuthManager App) ()
handleLoginSubmit = do
mUser <- getParam "login"
mPass <- getParam "password"
case (mUser, mPass) of
(Just user, Just pass) -> loginUser "login" "password" Nothing
(\_ -> handleLogin err)
(loginSuccess user pass)
_ -> handleLogin invalidErr
where
err = Just "Unknown user or password."
invalidErr = Just "Invalid request. Try again."
loginSuccess user pass = do
let userText = TE.decodeUtf8 user
passText = TE.decodeUtf8 pass
-- Create a Bugzilla session for this user.
session <- liftIO $ newBzSession userText (Just passText)
mvSessions <- withTop' id $ gets $ _bzSessions
liftIO $ modifyMVar_ mvSessions $
return . M.insert userText session
-- Synchronously update requests if there are none stored.
mReqs <- query $ GetRequests userText
when (isNothing mReqs) $ do
reqs <- liftIO $ bzRequests session userText
update $ UpdateRequests userText reqs
-- We're now ready to display the dashboard.
redirect "/dashboard"
------------------------------------------------------------------------------
-- | Logs out and redirects the user to the site index.
handleLogout :: Handler App (AuthManager App) ()
handleLogout = logout >> redirect "/"
------------------------------------------------------------------------------
-- | Handle new user form submit
handleNewUser :: Handler App (AuthManager App) ()
handleNewUser = method GET handleForm <|> method POST handleFormSubmit
where
handleForm = render "new_user"
handleFormSubmit = do
mUser <- getParam "login"
case mUser of
(Just user) -> do let newTime = posixSecondsToUTCTime 0
userText = TE.decodeUtf8 user
update $ AddUser userText (UserInfo newTime)
registerUser "login" "password"
redirect "/"
_ -> redirect "/new_user"
------------------------------------------------------------------------------
-- | Handle dashboard
handleDashboard :: Handler App (AuthManager App) ()
handleDashboard = do
mUser <- currentUser
case mUser of
Just user -> do
let login = userLogin user
curTime <- liftIO $ getCurrentTime
mUserInfo <- query $ GetUser login
update $ UpdateUser login (UserInfo curTime)
mReqs <- query $ GetRequests login
case (mUserInfo, mReqs) of
(Just ui, Just reqs) -> renderDashboard curTime (ui ^. uiLastSeen) reqs
(Nothing, _) -> handleLogin $ Just "You don't exist."
_ -> handleLogin $ Just "You've been logged out. Please log in again."
Nothing -> handleLogin $ Just "You need to be logged in for that."
renderDashboard :: UTCTime -> UTCTime -> [BzRequest] -> Handler App (AuthManager App) ()
renderDashboard curTime lastSeen requests = do
let (nis, rs, fs, as, ps, rds) = countRequests requests
splices = do "dashboardItems" ## I.mapSplices (dashboardItemSplice lastSeen curTime)
requests
"needinfoCount" ## (return [X.TextNode . T.pack . show $ nis])
"reviewCount" ## (return [X.TextNode . T.pack . show $ rs])
"feedbackCount" ## (return [X.TextNode . T.pack . show $ fs])
"assignedCount" ## (return [X.TextNode . T.pack . show $ as])
"pendingCount" ## (return [X.TextNode . T.pack . show $ ps])
"reviewedCount" ## (return [X.TextNode . T.pack . show $ rds])
heistLocal (I.bindSplices splices) $ render "dashboard"
dashboardItemSplice :: UTCTime -> UTCTime -> BzRequest -> I.Splice (Handler App App)
dashboardItemSplice lastSeen curTime req = return $
[divNode ["item", containerClass req] $
[ divNode [reqClass req] $
titleBadge req ++
[X.Element "h1" [classes ["card-title", reqClass req]] [title req]]
] ++ extended req ++ [
divNode ["summary"] [X.Element "p" [] [bugLink req]]
] ++ details req ++
[ lastComment req
, comments req
]
]
where
containerClass (NeedinfoRequest _ _ _) = "needinfo-container"
containerClass (ReviewRequest _ _ _) = "review-container"
containerClass (FeedbackRequest _ _ _) = "feedback-container"
containerClass (AssignedRequest _ _ _) = "assigned-container"
containerClass (PendingRequest _ _ _) = "pending-container"
containerClass (ReviewedRequest _ _ _) = "reviewed-container"
title r = linkNode (url r) [T.toUpper . reqClass $ r]
where
url (NeedinfoRequest _ _ _) = bugURL r
url (ReviewRequest _ _ att) = attURL r att
url (FeedbackRequest _ _ att) = attURL r att
url (AssignedRequest _ _ _) = bugURL r
url (PendingRequest _ _ _) = bugURL r
url (ReviewedRequest _ _ _) = bugURL r
titleBadge (NeedinfoRequest _ cs flag) = timeBadgeNode lastSeen cs curTime
(flagCreationDate flag)
titleBadge (ReviewRequest _ cs att) = timeBadgeNode lastSeen cs curTime
(attachmentCreationTime att)
titleBadge (FeedbackRequest _ cs att) = timeBadgeNode lastSeen cs curTime
(attachmentCreationTime att)
titleBadge (AssignedRequest bug cs _) = timeBadgeNode lastSeen cs curTime
(bugCreationTime bug)
titleBadge (PendingRequest bug cs _) = timeBadgeNode lastSeen cs curTime
(bugCreationTime bug)
titleBadge (ReviewedRequest bug cs _) = timeBadgeNode lastSeen cs curTime
(bugCreationTime bug)
reqClass (NeedinfoRequest _ _ _) = "needinfo"
reqClass (ReviewRequest _ _ _) = "review"
reqClass (FeedbackRequest _ _ _) = "feedback"
reqClass (AssignedRequest _ _ _) = "assigned"
reqClass (PendingRequest _ _ _) = "pending"
reqClass (ReviewedRequest _ _ _) = "reviewed"
bugLink r = linkNode (bugURL r) [bugIdText r, ": ", bugSummary . reqBug $ r]
details (NeedinfoRequest bug _ flag) = []
details (ReviewRequest bug _ att) = [ divNode ["detail"] (attachmentNode att)
]
details (FeedbackRequest bug _ att) = [ divNode ["detail"] (attachmentNode att)
]
details (AssignedRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts)
]
details (PendingRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts)
]
details (ReviewedRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts)
]
attachmentNode att =
[ X.Element "hr" [] []
, divNode ["attachment"] $
[ divNode ["attachment-icon"] []
, pNode' ["attachment-summary"] [attachmentSummary att]
] ++ map attachmentFlagNode (attachmentFlags att)
]
attachmentFlagNode f = divNode ["attachment-flag"] $
[ maybe noSmallGravatar smallGravatarImg (flagRequestee f)
, X.Element "p" [] $
[ flagNameNode [flagName f, flagStatus f]
, textNode [" " , fromMaybe "" (flagRequestee f)]
]
]
extended (NeedinfoRequest bug _ flag) = [ divNode ["extended"]
[ gravatarImg (flagSetter flag)
, pNode [flagSetter flag]
, timeNode curTime (flagCreationDate flag)
] ]
extended (ReviewRequest bug _ att) = [ divNode ["extended"]
[ gravatarImg (attachmentCreator att)
, pNode [attachmentCreator att]
, timeNode curTime (attachmentCreationTime att)
] ]
extended (FeedbackRequest bug _ att) = [ divNode ["extended"]
[ gravatarImg (attachmentCreator att)
, pNode [attachmentCreator att]
, timeNode curTime (attachmentCreationTime att)
] ]
extended (AssignedRequest bug _ _) = []
extended (PendingRequest bug _ _) = []
extended (ReviewedRequest bug _ _) = []
lastComment r = divNode ["last-comment-wrapper"] $
map (commentNode r 200) (take 1 . reqComments $ r)
comments r = divNode ["comments-wrapper"] $
[ divNode ["comments-inner-wrapper"] $
[ divNode ["comments"] $ map (commentNode r 0) (reqComments r)]]
commentNode r limit c = divNode ["comment"] $
[ divNode (commentHeaderClasses lastSeen $ commentCreationTime c) $
[ gravatarImg (commentCreator c)
, pNode [commentCreator c]
, X.Element "p" [] $
[ linkNode (commentURL r c) ["#", T.pack . show $ commentCount c]
, textNode [" (", T.pack . show $ commentCreationTime c, ")"]
]
]
] ++ (mergedComments . T.lines . applyLimit limit . commentText $ c)
mergedComments = concatMap mergeQuotes . groupBy (same numQuotes)
where
mergeQuotes [] = []
mergeQuotes ls@(l:_)
| isQuote l = if any (";" `T.isSuffixOf`) ls
then map (pQuoteNode . (:[])) ls
else [pQuoteNode [T.intercalate " " . map stripQuotes $ ls]]
| otherwise = map (pNode . (:[])) ls
commentTextNode line
| ">" `T.isPrefixOf` line = X.Element "p" [classes ["quote"]] [X.TextNode line]
| otherwise = pNode [line]
gravatarImg email = divNode ["gravatar"] [X.Element "img" [("src", url)] []]
where
url = T.pack $ G.gravatar settings email
settings = def { G.gDefault = Just G.Retro, G.gSize = Just $ G.Size 48 }
smallGravatarImg email = divNode ["small-gravatar"] [X.Element "img" [("src", url)] []]
where
url = T.pack $ G.gravatar settings email
settings = def { G.gDefault = Just G.Retro, G.gSize = Just $ G.Size 32 }
noGravatar = divNode ["no-gravatar"] []
noSmallGravatar = divNode ["no-small-gravatar"] []
attURL :: BzRequest -> Attachment -> T.Text
attURL r att = T.concat [ "https://bugzilla.mozilla.org/page.cgi?id=splinter.html&bug="
, bugIdText r
, "&attachment="
, attachmentIdText att
]
bugURL :: BzRequest -> T.Text
bugURL r = T.concat ["https://bugzilla.mozilla.org/show_bug.cgi?id=", bugIdText r]
commentURL :: BzRequest -> Comment -> T.Text
commentURL r c = T.concat [ "https://bugzilla.mozilla.org/show_bug.cgi?id="
, bugIdText r
, "#c"
, commentIdText c
]
attachmentIdText :: Attachment -> T.Text
attachmentIdText = T.pack . show . attachmentId
bugIdText :: BzRequest -> T.Text
bugIdText = T.pack . show . bugId . reqBug
commentIdText :: Comment -> T.Text
commentIdText = T.pack . show . commentCount
classes :: [T.Text] -> (T.Text, T.Text)
classes cs = ("class", T.intercalate " " cs)
textNode :: [T.Text] -> X.Node
textNode = X.TextNode . T.concat
linkNode :: T.Text -> [T.Text] -> X.Node
linkNode url ts = X.Element "a" [("href", url)] [textNode ts]
pNode :: [T.Text] -> X.Node
pNode ts = X.Element "p" [] [textNode ts]
flagNameNode :: [T.Text] -> X.Node
flagNameNode ts = X.Element "span" [classes ["flag-name"]] [textNode ts]
pNode' :: [T.Text] -> [T.Text] -> X.Node
pNode' cs ts = X.Element "p" [classes cs] [textNode ts]
pQuoteNode :: [T.Text] -> X.Node
pQuoteNode ts = X.Element "p" [classes ["quote"]] [textNode ts]
isQuote :: T.Text -> Bool
isQuote = (">" `T.isPrefixOf`)
divNode :: [T.Text] -> [X.Node] -> X.Node
divNode cs es = X.Element "div" [classes cs] es
oneWeek, twoWeeks, oneMonth :: NominalDiffTime
oneWeek = fromIntegral $ 1 * 604800
twoWeeks = fromIntegral $ 2 * 604800
oneMonth = fromIntegral $ 4 * 604800
timeNode :: UTCTime -> UTCTime -> X.Node
timeNode curTime itemTime
| timeDiff > oneWeek = node ["overdue"]
| otherwise = node []
where
timeDiff = curTime `diffUTCTime` itemTime
node cs = X.Element "p" [classes cs]
[textNode [T.pack . show $ itemTime]]
timeBadgeNode :: UTCTime -> [Comment] -> UTCTime -> UTCTime -> [X.Node]
timeBadgeNode lastSeen cs curTime itemTime = newComment cs ++ overdue
where
newComment (c:_)
| commentTimeDiff > 0 = [divNode ["left-badge"] [textNode ["+"]]]
| otherwise = []
where
commentTimeDiff = (commentCreationTime c) `diffUTCTime` lastSeen
newComment _ = []
overdue
| overdueTimeDiff > oneMonth = [overdueNode ["!!!"]]
| overdueTimeDiff > twoWeeks = [overdueNode ["!!"]]
| overdueTimeDiff > oneWeek = [overdueNode ["!"]]
| otherwise = []
where
overdueTimeDiff = curTime `diffUTCTime` itemTime
overdueNode ts = divNode ["right-badge"] [textNode ts]
commentHeaderClasses :: UTCTime -> UTCTime -> [T.Text]
commentHeaderClasses lastSeen itemTime
| timeDiff > 0 = ["comment-header", "new-comment"]
| otherwise = ["comment-header"]
where
timeDiff = itemTime `diffUTCTime` lastSeen
same :: Eq b => (a -> b) -> a -> a -> Bool
same f a b = f a == f b
numQuotes :: T.Text -> Int
numQuotes = length . takeWhile (== "> ") . T.chunksOf 2
stripQuotes :: T.Text -> T.Text
stripQuotes = T.concat . dropWhile (== "> ") . T.chunksOf 2
applyLimit :: Int -> T.Text -> T.Text
applyLimit 0 = id
applyLimit n = (`T.append` "...") . T.take n
countRequests :: [BzRequest] -> (Int, Int, Int, Int, Int, Int)
countRequests rs = go (0, 0, 0, 0, 0, 0) rs
where
go !count [] = count
go (!nis, !rvs, !fbs, !as, !ps, !rds) ((NeedinfoRequest _ _ _) : rs) = go (nis + 1, rvs, fbs, as, ps, rds) rs
go (!nis, !rvs, !fbs, !as, !ps, !rds) ((ReviewRequest _ _ _) : rs) = go (nis, rvs + 1, fbs, as, ps, rds) rs
go (!nis, !rvs, !fbs, !as, !ps, !rds) ((FeedbackRequest _ _ _) : rs) = go (nis, rvs, fbs + 1, as, ps, rds) rs
go (!nis, !rvs, !fbs, !as, !ps, !rds) ((AssignedRequest _ _ _) : rs) = go (nis, rvs, fbs, as + 1, ps, rds) rs
go (!nis, !rvs, !fbs, !as, !ps, !rds) ((PendingRequest _ _ _) : rs) = go (nis, rvs, fbs, as, ps + 1, rds) rs
go (!nis, !rvs, !fbs, !as, !ps, !rds) ((ReviewedRequest _ _ _) : rs) = go (nis, rvs, fbs, as, ps, rds + 1) rs
------------------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = [ ("/login", with auth handleLoginSubmit)
, ("/logout", with auth handleLogout)
, ("/new_user", with auth handleNewUser)
, ("/dashboard", with auth handleDashboard)
, ("", serveDirectory "static")
]
------------------------------------------------------------------------------
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
h <- nestSnaplet "" heist $ heistInit "templates"
s <- nestSnaplet "sess" sess $
initCookieSessionManager "site_key.txt" "sess" (Just 3600)
-- NOTE: We're using initJsonFileAuthManager here because it's easy and
-- doesn't require any kind of database server to run. In practice,
-- you'll probably want to change this to a more robust auth backend.
a <- nestSnaplet "auth" auth $
initJsonFileAuthManager defAuthSettings sess "users.json"
state <- liftIO $ AS.openLocalState (AppState M.empty M.empty)
onUnload (AS.closeAcidState state)
acid <- nestSnaplet "acid" acid $ acidInitManual state
addRoutes routes
addAuthSplices h auth
mvSessions <- liftIO $ newMVar M.empty
t <- liftIO $ async $ pollBugzilla mvSessions state 15
return $ App h s a acid t mvSessions
pollBugzilla :: MVar (M.Map UserLogin BugzillaSession) -> AS.AcidState AppState -> Int -> IO ()
pollBugzilla !mvSessions !state !intervalMin = do
-- Wait appropriately.
let intervalUs = 60000000 * intervalMin
threadDelay intervalUs
-- Update all users with current sessions.
sessions <- readMVar mvSessions
forM_ (M.toList sessions) $ \(user, session) -> do
putStrLn $ "Updating requests from Bugzilla for user " ++ show user
reqs <- bzRequests session user
AS.update state $ UpdateRequests user reqs
-- Do it again.
pollBugzilla mvSessions state intervalMin
|
sethfowler/bzbeaver
|
src/Site.hs
|
Haskell
|
bsd-3-clause
| 19,014
|
module Del.Parser where
import Control.Applicative
import Control.Exception
import qualified Data.Set as S
import qualified Data.MultiSet as MS
import Data.Typeable
import Text.Trifecta
import Del.Syntax
eomParser :: Parser EOM
eomParser = many equationParser
equationParser :: Parser Equation
equationParser = do
spaces
l <- symParser
spaces
char '='
spaces
r <- expParser
spaces
return $ Equation l r
expParser :: Parser Exp
expParser = expr
-- この実装は正しくない
-- `*`, `/` よりも `**` のほうが結合性が高くなっているが
-- `-c**2` を `-(c**2)` ではなく `(-c)**2` と解釈してしまう。
expr :: Parser Exp
expr = (factor `chainl1` powop) `chainl1` mulop `chainl1` addop
where addop = infixOp "+" Add <|> infixOp "-" Sub
mulop = infixOp "*" Mul <|> infixOp "/" Div
powop = infixOp "**" Pow
infixOp :: String -> (a -> a -> a) -> Parser (a -> a -> a)
infixOp op f = f <$ symbol op
factor :: Parser Exp
factor = parens expr
<|> neg
<|> symParser
<|> numParser
neg :: Parser Exp
neg = symbol "-" >> Neg <$> factor
numParser :: Parser Exp
numParser = Num . either fromIntegral id <$> integerOrDouble
symParser :: Parser Exp
symParser = do
n <- (:) <$> letter <*> many alphaNum
as <- option S.empty $ brackets args
ds <- option MS.empty $ MS.fromList <$> (char '_' *> some coord)
return $ Sym n as ds
args :: Parser Arg
args = S.fromList <$> some (coord <* optional comma)
coord :: Parser Coord
coord = (char 't' *> pure T)
<|> (char 'x' *> pure X)
<|> (char 'y' *> pure Y)
<|> (char 'z' *> pure Z)
parseEOM :: String -> Either ErrInfo EOM
parseEOM str = case parseString eomParser mempty $ filter (/=' ') str of
Success eom -> Right eom
Failure err -> Left err
getEOMFromFile :: String -> IO EOM
getEOMFromFile fn = do
str <- readFile fn
case parseEOM str of
Right eom -> return eom
Left err -> throwIO $ ParseException err
data ParseException = ParseException ErrInfo
deriving Typeable
instance Show ParseException where
show (ParseException e) = show e
instance Exception ParseException
|
ishiy1993/mk-sode1
|
src/Del/Parser.hs
|
Haskell
|
bsd-3-clause
| 2,197
|
module Trans where
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State
import Data.Functor.Identity
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import Control.Monad
rDec :: Num a => Reader a a
rDec =
fmap (flip (-) 1) ask
rShow :: Show a => ReaderT a Identity String
rShow =
show <$> ask
rPrintAndInc :: (Num a, Show a) => ReaderT a IO a
rPrintAndInc = do
a <- ask
liftIO $ print ("Hi: " ++ show a)
return (a + 1)
sPrintIncAccum :: (Num a, Show a) => StateT a IO String
sPrintIncAccum = do
state <- get
liftIO $ print ("Hi: " ++ show state)
put (state + 1)
return (show state)
isValid :: String -> Bool
isValid v = '!' `elem` v
maybeExcite :: MaybeT IO String
maybeExcite = do
v <- liftIO getLine
guard $ isValid v
return v
doExcite :: IO ()
doExcite = do
putStrLn "Say something excite!"
excite <- runMaybeT maybeExcite
case excite of
Nothing -> putStrLn "MOAR EXCITE"
Just e -> putStrLn ("Good, was very excite: " ++ e)
|
nicklawls/haskellbook
|
src/Trans.hs
|
Haskell
|
bsd-3-clause
| 998
|
module Logic.ProofNet where
|
digitalheir/net-prove
|
src/Logic/ProofNet.hs
|
Haskell
|
bsd-3-clause
| 27
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
module Language.Epilog.AST.Program
( Program (..)
) where
--------------------------------------------------------------------------------
import Language.Epilog.AST.Procedure
import Language.Epilog.Epilog (Strings, Types)
import Language.Epilog.SymbolTable
import Language.Epilog.Treelike
--------------------------------------------------------------------------------
import qualified Data.Map as Map (keys)
import Prelude hiding (Either, null)
--------------------------------------------------------------------------------
data Program = Program
{ types :: Types
, procs :: Procedures
, scope :: Scope
, strings :: Strings }
instance Treelike Program where
toTree Program { types, procs, scope, strings } =
Node "Program"
[ Node "Types" (toForest' $ fst <$> types)
, Node "Procs" (toForest procs)
, Node "Scope" [toTree scope]
, Node "Strings" (leaf <$> Map.keys strings) ]
|
adgalad/Epilog
|
src/Haskell/Language/Epilog/AST/Program.hs
|
Haskell
|
bsd-3-clause
| 1,113
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- Load information on package sources
module Stack.Build.Source
( loadSourceMap
, SourceMap
, PackageSource (..)
) where
import Network.HTTP.Client.Conduit (HasHttpManager)
import Control.Monad
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import Data.Either
import Data.Function
import Data.List
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import Data.Maybe
import Data.Monoid ((<>))
import qualified Data.Set as Set
import qualified Data.Text as T
import Path
import Prelude hiding (FilePath, writeFile)
import Stack.Build.Cache
import Stack.Build.Types
import Stack.BuildPlan (loadMiniBuildPlan,
shadowMiniBuildPlan)
import Stack.Package
import Stack.Types
import System.Directory hiding (findExecutable, findFiles)
type SourceMap = Map PackageName PackageSource
data PackageSource
= PSLocal LocalPackage
| PSUpstream Version Location (Map FlagName Bool)
instance PackageInstallInfo PackageSource where
piiVersion (PSLocal lp) = packageVersion $ lpPackage lp
piiVersion (PSUpstream v _ _) = v
piiLocation (PSLocal _) = Local
piiLocation (PSUpstream _ loc _) = loc
loadSourceMap :: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m)
=> BuildOpts
-> m (MiniBuildPlan, [LocalPackage], SourceMap)
loadSourceMap bopts = do
bconfig <- asks getBuildConfig
mbp0 <- case bcResolver bconfig of
ResolverSnapshot snapName -> do
$logDebug $ "Checking resolver: " <> renderSnapName snapName
mbp <- loadMiniBuildPlan snapName
return mbp
ResolverGhc ghc -> return MiniBuildPlan
{ mbpGhcVersion = fromMajorVersion ghc
, mbpPackages = Map.empty
}
locals <- loadLocals bopts
let shadowed = Set.fromList (map (packageName . lpPackage) locals)
<> Map.keysSet (bcExtraDeps bconfig)
(mbp, extraDeps0) = shadowMiniBuildPlan mbp0 shadowed
-- Add the extra deps from the stack.yaml file to the deps grabbed from
-- the snapshot
extraDeps1 = Map.union
(Map.map (\v -> (v, Map.empty)) (bcExtraDeps bconfig))
(Map.map (\mpi -> (mpiVersion mpi, mpiFlags mpi)) extraDeps0)
-- Overwrite any flag settings with those from the config file
extraDeps2 = Map.mapWithKey
(\n (v, f) -> PSUpstream v Local $ fromMaybe f $ Map.lookup n $ bcFlags bconfig)
extraDeps1
let sourceMap = Map.unions
[ Map.fromList $ flip map locals $ \lp ->
let p = lpPackage lp
in (packageName p, PSLocal lp)
, extraDeps2
, flip fmap (mbpPackages mbp) $ \mpi ->
(PSUpstream (mpiVersion mpi) Snap (mpiFlags mpi))
]
return (mbp, locals, sourceMap)
loadLocals :: (MonadReader env m, HasBuildConfig env, MonadIO m, MonadLogger m, MonadThrow m, MonadCatch m)
=> BuildOpts
-> m [LocalPackage]
loadLocals bopts = do
targets <- mapM parseTarget $
case boptsTargets bopts of
Left [] -> ["."]
Left x -> x
Right _ -> []
(dirs, names0) <- case partitionEithers targets of
([], targets') -> return $ partitionEithers targets'
(bad, _) -> throwM $ Couldn'tParseTargets bad
let names = Set.fromList names0
bconfig <- asks getBuildConfig
lps <- forM (Set.toList $ bcPackages bconfig) $ \dir -> do
cabalfp <- getCabalFileName dir
name <- parsePackageNameFromFilePath cabalfp
let wanted = isWanted dirs names dir name
pkg <- readPackage
PackageConfig
{ packageConfigEnableTests = wanted && boptsFinalAction bopts == DoTests
, packageConfigEnableBenchmarks = wanted && boptsFinalAction bopts == DoBenchmarks
, packageConfigFlags = localFlags bopts bconfig name
, packageConfigGhcVersion = bcGhcVersion bconfig
, packageConfigPlatform = configPlatform $ getConfig bconfig
}
cabalfp
when (packageName pkg /= name) $ throwM
$ MismatchedCabalName cabalfp (packageName pkg)
mbuildCache <- tryGetBuildCache dir
mconfigCache <- tryGetConfigCache dir
fileModTimes <- getPackageFileModTimes pkg cabalfp
return LocalPackage
{ lpPackage = pkg
, lpWanted = wanted
, lpLastConfigOpts = mconfigCache
, lpDirtyFiles =
maybe True
((/= fileModTimes) . buildCacheTimes)
mbuildCache
, lpCabalFile = cabalfp
, lpDir = dir
}
let known = Set.fromList $ map (packageName . lpPackage) lps
unknown = Set.difference names known
unless (Set.null unknown) $ throwM $ UnknownTargets $ Set.toList unknown
return lps
where
parseTarget t = do
let s = T.unpack t
isDir <- liftIO $ doesDirectoryExist s
if isDir
then liftM (Right . Left) $ liftIO (canonicalizePath s) >>= parseAbsDir
else return $ case parsePackageNameFromString s of
Left _ -> Left t
Right pname -> Right $ Right pname
isWanted dirs names dir name =
name `Set.member` names ||
any (`isParentOf` dir) dirs ||
any (== dir) dirs
-- | All flags for a local package
localFlags :: BuildOpts -> BuildConfig -> PackageName -> Map FlagName Bool
localFlags bopts bconfig name = Map.union
(fromMaybe Map.empty $ Map.lookup name $ boptsFlags bopts)
(fromMaybe Map.empty $ Map.lookup name $ bcFlags bconfig)
|
mietek/stack
|
src/Stack/Build/Source.hs
|
Haskell
|
bsd-3-clause
| 6,444
|
{-# LANGUAGE BangPatterns #-}
module Atomo.Environment where
import Control.Monad.Cont
import Control.Monad.State
import Data.IORef
import Atomo.Method
import Atomo.Pattern
import Atomo.Pretty
import Atomo.Types
-- | Evaluate an expression, yielding a value.
eval :: Expr -> VM Value
eval (EDefine { emPattern = p, eExpr = ev }) = do
define p ev
return (particle "ok")
eval (ESet { ePattern = PMessage p, eExpr = ev }) = do
v <- eval ev
define p (EPrimitive (eLocation ev) v)
return v
eval (ESet { ePattern = p, eExpr = ev }) = do
v <- eval ev
set p v
eval (EDispatch { eMessage = Single i n t [] }) = do
v <- eval t
dispatch (Single i n v [])
eval (EDispatch { eMessage = Single i n t os }) = do
v <- eval t
nos <- forM os $ \(Option oi on oe) -> do
ov <- eval oe
return (Option oi on ov)
dispatch (Single i n v nos)
eval (EDispatch { eMessage = Keyword i ns ts [] }) = do
vs <- mapM eval ts
dispatch (Keyword i ns vs [])
eval (EDispatch { eMessage = Keyword i ns ts os }) = do
vs <- mapM eval ts
nos <- forM os $ \(Option oi on e) -> do
ov <- eval e
return (Option oi on ov)
dispatch (Keyword i ns vs nos)
eval (EOperator { eNames = ns, eAssoc = a, ePrec = p }) = do
forM_ ns $ \n -> modify $ \s ->
s
{ parserState =
(parserState s)
{ psOperators =
(n, (a, p)) : psOperators (parserState s)
}
}
return (particle "ok")
eval (EPrimitive { eValue = v }) = return v
eval (EBlock { eArguments = as, eContents = es }) = do
t <- gets top
return (Block t as es)
eval (EList { eContents = es }) = do
vs <- mapM eval es
return (list vs)
eval (ETuple { eContents = es }) = do
vs <- mapM eval es
return (tuple vs)
eval (EMacro {}) = return (particle "ok")
eval (EForMacro {}) = return (particle "ok")
eval (EParticle { eParticle = Single i n mt os }) = do
nos <- forM os $ \(Option oi on me) ->
liftM (Option oi on)
(maybe (return Nothing) (liftM Just . eval) me)
nmt <- maybe (return Nothing) (liftM Just . eval) mt
return (Particle $ Single i n nmt nos)
eval (EParticle { eParticle = Keyword i ns mts os }) = do
nmts <- forM mts $
maybe (return Nothing) (liftM Just . eval)
nos <- forM os $ \(Option oi on me) ->
liftM (Option oi on)
(maybe (return Nothing) (liftM Just . eval) me)
return (Particle $ Keyword i ns nmts nos)
eval (ETop {}) = gets top
eval (EVM { eAction = x }) = x
eval (EUnquote { eExpr = e }) = raise ["out-of-quote"] [Expression e]
eval (EQuote { eExpr = qe }) = do
unquoted <- unquote 0 qe
return (Expression unquoted)
where
unquote :: Int -> Expr -> VM Expr
unquote 0 (EUnquote { eExpr = e }) = do
r <- eval e
case r of
Expression e' -> return e'
_ -> return (EPrimitive Nothing r)
unquote n u@(EUnquote { eExpr = e }) = do
ne <- unquote (n - 1) e
return (u { eExpr = ne })
unquote n q@(EQuote { eExpr = e }) = do
ne <- unquote (n + 1) e
return q { eExpr = ne }
unquote n d@(EDefine { eExpr = e }) = do
ne <- unquote n e
return (d { eExpr = ne })
unquote n s@(ESet { eExpr = e }) = do
ne <- unquote n e
return (s { eExpr = ne })
unquote n d@(EDispatch { eMessage = em }) =
case em of
Keyword { mTargets = ts } -> do
nts <- mapM (unquote n) ts
return d { eMessage = em { mTargets = nts } }
Single { mTarget = t } -> do
nt <- unquote n t
return d { eMessage = em { mTarget = nt } }
unquote n b@(EBlock { eContents = es }) = do
nes <- mapM (unquote n) es
return b { eContents = nes }
unquote n l@(EList { eContents = es }) = do
nes <- mapM (unquote n) es
return l { eContents = nes }
unquote n t@(ETuple { eContents = es }) = do
nes <- mapM (unquote n) es
return t { eContents = nes }
unquote n m@(EMacro { eExpr = e }) = do
ne <- unquote n e
return m { eExpr = ne }
unquote n p@(EParticle { eParticle = ep }) =
case ep of
Keyword { mNames = ns, mTargets = mes } -> do
nmes <- forM mes $ \me ->
case me of
Nothing -> return Nothing
Just e -> liftM Just (unquote n e)
return p { eParticle = keyword ns nmes }
_ -> return p
unquote n d@(ENewDynamic { eExpr = e }) = do
ne <- unquote n e
return d { eExpr = ne }
unquote n d@(EDefineDynamic { eExpr = e }) = do
ne <- unquote n e
return d { eExpr = ne }
unquote n d@(ESetDynamic { eExpr = e }) = do
ne <- unquote n e
return d { eExpr = ne }
unquote n p@(EPrimitive { eValue = Expression e }) = do
ne <- unquote n e
return p { eValue = Expression ne }
unquote n m@(EMatch { eTarget = t, eBranches = bs }) = do
nt <- unquote n t
nbs <- forM bs $ \(p, e) -> do
ne <- unquote n e
return (p, ne)
return m { eTarget = nt, eBranches = nbs }
unquote _ p@(EPrimitive {}) = return p
unquote _ t@(ETop {}) = return t
unquote _ v@(EVM {}) = return v
unquote _ o@(EOperator {}) = return o
unquote _ f@(EForMacro {}) = return f
unquote _ g@(EGetDynamic {}) = return g
unquote _ q@(EMacroQuote {}) = return q
eval (ENewDynamic { eBindings = bes, eExpr = e }) = do
bvs <- forM bes $ \(n, b) -> do
v <- eval b
return (n, v)
dynamicBind bvs (eval e)
eval (EDefineDynamic { eName = n, eExpr = e }) = do
v <- eval e
modify $ \env -> env
{ dynamic = newDynamic n v (dynamic env)
}
return v
eval (ESetDynamic { eName = n, eExpr = e }) = do
v <- eval e
d <- gets dynamic
if isBound n d
then modify $ \env -> env { dynamic = setDynamic n v d }
else raise ["unbound-dynamic"] [string n]
return v
eval (EGetDynamic { eName = n }) = do
mv <- gets (getDynamic n . dynamic)
maybe (raise ["unknown-dynamic"] [string n]) return mv
eval (EMacroQuote { eName = n, eRaw = r, eFlags = fs }) = do
t <- gets (psEnvironment . parserState)
dispatch $
keyword'
["quote", "as"]
[t, string r, particle n]
[option "flags" (list (map Character fs))]
eval (EMatch { eTarget = t, eBranches = bs }) = do
v <- eval t
ids <- gets primitives
matchBranches ids bs v
matchBranches :: IDs -> [(Pattern, Expr)] -> Value -> VM Value
matchBranches _ [] v = raise ["no-match-for"] [v]
matchBranches ids ((p, e):ps) v = do
p' <- matchable' p
if match ids Nothing p' v
then newScope $ set p' v >> eval e
else matchBranches ids ps v
-- | Evaluate multiple expressions, returning the last result.
evalAll :: [Expr] -> VM Value
evalAll [] = throwError NoExpressions
evalAll [e] = eval e
evalAll (e:es) = eval e >> evalAll es
-- | Create a new empty object, passing a function to initialize it.
newObject :: Delegates -> (MethodMap, MethodMap) -> VM Value
newObject ds mm = do
ms <- liftIO (newIORef mm)
return (Object ds ms)
-- | Run x with t as its toplevel object.
withTop :: Value -> VM a -> VM a
withTop !t x = do
o <- gets top
modify (\e -> e { top = t })
res <- x
modify (\e -> e { top = o })
return res
-- | Execute an action with the given dynamic bindings.
dynamicBind :: [(String, Value)] -> VM a -> VM a
dynamicBind bs x = do
modify $ \e -> e
{ dynamic = foldl (\m (n, v) -> bindDynamic n v m) (dynamic e) bs
}
res <- x
modify $ \e -> e
{ dynamic = foldl (\m (n, _) -> unbindDynamic n m) (dynamic e) bs
}
return res
-- | Execute an action with a new toplevel delegating to the old one.
newScope :: VM a -> VM a
newScope x = do
t <- gets top
nt <- newObject [t] noMethods
withTop nt x
-----------------------------------------------------------------------------
-- Define -------------------------------------------------------------------
-----------------------------------------------------------------------------
-- | Insert a method on a single value.
defineOn :: Value -> Method -> VM ()
defineOn v m' = liftIO $ do
(oss, oks) <- readIORef (oMethods v)
writeIORef (oMethods v) $
case mPattern m of
Single {} ->
(addMethod m oss, oks)
Keyword {} ->
(oss, addMethod m oks)
where
m = m' { mPattern = setSelf v (mPattern m') }
-- | Define a method on all roles involved in its pattern.
define :: Message Pattern -> Expr -> VM ()
define !p !e = do
is <- gets primitives
newp <- matchable p
m <- method newp e
os <- targets is newp
forM_ os (flip defineOn m)
where
method p' (EPrimitive _ v) = return (Slot p' v)
method p' e' = gets top >>= \t -> return (Responder p' t e')
-- | Swap out a reference match with PThis, for inserting on an object.
setSelf :: Value -> Message Pattern -> Message Pattern
setSelf v (Keyword i ns ps os) =
Keyword i ns (map (setSelf' v) ps) os
setSelf v (Single i n t os) =
Single i n (setSelf' v t) os
setSelf' :: Value -> Pattern -> Pattern
setSelf' v (PMatch x) | v == x = PThis
setSelf' v (PMessage m) = PMessage $ setSelf v m
setSelf' v (PNamed n p') =
PNamed n (setSelf' v p')
setSelf' v (PInstance p) = PInstance (setSelf' v p)
setSelf' v (PStrict p) = PStrict (setSelf' v p)
setSelf' _ p' = p'
-- | Pattern-match a value, inserting bindings into the current toplevel.
set :: Pattern -> Value -> VM Value
set p v = do
is <- gets primitives
if match is Nothing p v
then do
forM_ (bindings' p v) $ \(p', v') ->
define p' (EPrimitive Nothing v')
return v
else throwError (Mismatch p v)
-- | Turn any PObject patterns into PMatches.
matchable :: Message Pattern -> VM (Message Pattern)
matchable p'@(Single { mTarget = t }) = do
t' <- matchable' t
return p' { mTarget = t' }
matchable p'@(Keyword { mTargets = ts }) = do
ts' <- mapM matchable' ts
return p' { mTargets = ts' }
matchable' :: Pattern -> VM Pattern
matchable' PThis = liftM PMatch (gets top)
matchable' (PObject oe) = liftM PMatch (eval oe)
matchable' (PInstance p) = liftM PInstance (matchable' p)
matchable' (PStrict p) = liftM PStrict (matchable' p)
matchable' (PVariable p) = liftM PVariable (matchable' p)
matchable' (PNamed n p') = liftM (PNamed n) (matchable' p')
matchable' (PMessage m) = liftM PMessage (matchable m)
matchable' p' = return p'
-- | Find the target objects for a message pattern.
targets :: IDs -> Message Pattern -> VM [Value]
targets is (Single { mTarget = p }) = targets' is p
targets is (Keyword { mTargets = ps }) = targets' is (head ps)
-- | Find the target objects for a pattern.
targets' :: IDs -> Pattern -> VM [Value]
targets' _ (PMatch v) = liftM (: []) (objectFor v)
targets' is (PNamed _ p) = targets' is p
targets' is PAny = return [idObject is]
targets' is (PList _) = return [idList is]
targets' is (PTuple _) = return [idTuple is]
targets' is (PHeadTail h t) = do
ht <- targets' is h
tt <- targets' is t
if idCharacter is `elem` ht || idString is `elem` tt
then return [idList is, idString is]
else return [idList is]
targets' is (PPMKeyword {}) = return [idParticle is]
targets' is (PExpr _) = return [idExpression is]
targets' is (PInstance p) = targets' is p
targets' is (PStrict p) = targets' is p
targets' is (PVariable _) = return [idObject is]
targets' is (PMessage m) = targets is m
targets' _ p = error $ "no targets for " ++ show p
-----------------------------------------------------------------------------
-- Dispatch -----------------------------------------------------------------
-----------------------------------------------------------------------------
-- | Dispatch a message to all roles and return a value.
--
-- If the message is not understood, @\@did-not-understand:(at:)@ is sent to all
-- roles until one responds to it. If none of them handle it, a
-- @\@did-not-understand:@ error is raised.
dispatch :: Message Value -> VM Value
dispatch !m = do
find <- findMethod (target m) m
case find of
Just method -> runMethod method m
Nothing ->
case m of
Single { mTarget = t } -> sendDNU t
Keyword { mTargets = ts } -> sendDNUs ts 0
where
target (Single { mTarget = t }) = t
target (Keyword { mTargets = ts }) = head ts
sendDNU v = do
find <- findMethod v (dnuSingle v)
case find of
Nothing -> throwError $ DidNotUnderstand m
Just method -> runMethod method (dnuSingle v)
sendDNUs [] _ = throwError $ DidNotUnderstand m
sendDNUs (v:vs') n = do
find <- findMethod v (dnu v n)
case find of
Nothing -> sendDNUs vs' (n + 1)
Just method -> runMethod method (dnu v n)
dnu v n = keyword
["did-not-understand", "at"]
[v, Message m, Integer n]
dnuSingle v = keyword
["did-not-understand"]
[v, Message m]
-- | Find a method on an object that responds to a given message, searching
-- its delegates if necessary.
findMethod :: Value -> Message Value -> VM (Maybe Method)
findMethod v m = do
is <- gets primitives
o <- objectFor v
ms <- liftIO (readIORef (oMethods o))
case relevant is o ms m of
Nothing -> findFirstMethod m (oDelegates o)
mt -> return mt
-- | Find the first value that has a method defiend for a given message.
findFirstMethod :: Message Value -> [Value] -> VM (Maybe Method)
findFirstMethod _ [] = return Nothing
findFirstMethod m (v:vs) = do
r <- findMethod v m
case r of
Nothing -> findFirstMethod m vs
_ -> return r
-- | Find a method on an object that responds to a given message.
relevant :: IDs -> Value -> (MethodMap, MethodMap) -> Message Value -> Maybe Method
relevant ids o ms m =
lookupMap (mID m) (methods m) >>= firstMatch ids (Just o) m
where
methods (Single {}) = fst ms
methods (Keyword {}) = snd ms
firstMatch _ _ _ [] = Nothing
firstMatch ids' r' m' (mt:mts)
| match ids' r' (PMessage (mPattern mt)) (Message m') = Just mt
| otherwise = firstMatch ids' r' m' mts
-- | Evaluate a method.
--
-- Responder methods: evaluates its expression in a scope with the pattern's
-- bindings, delegating to the method's context.
--
-- Slot methods: simply returns the value.
--
-- Macro methods: evaluates its expression in a scope with the pattern's
-- bindings.
runMethod :: Method -> Message Value -> VM Value
runMethod (Slot { mValue = v }) _ = return v
runMethod (Responder { mPattern = p, mContext = c, mExpr = e }) m = do
nt <- newObject [c] (bindings p m, emptyMap)
forM_ (mOptionals p) $ \(Option i n (PObject oe)) ->
case filter (\(Option x _ _) -> x == i) (mOptionals m) of
[] -> do
d <- withTop nt (eval oe)
define (Single i n (PMatch nt) [])
(EPrimitive Nothing d)
(Option oi on ov:_) ->
define (Single oi on (PMatch nt) [])
(EPrimitive Nothing ov)
withTop nt $ eval e
runMethod (Macro { mPattern = p, mExpr = e }) m = do
t <- gets (psEnvironment . parserState)
nt <- newObject [t] (bindings p m, emptyMap)
forM_ (mOptionals p) $ \(Option i n (PExpr d)) ->
case filter (\(Option x _ _) -> x == i) (mOptionals m) of
[] ->
define (Single i n (PMatch nt) [])
(EPrimitive Nothing (Expression d))
(Option oi on ov:_) ->
define (Single oi on (PMatch nt) [])
(EPrimitive Nothing ov)
withTop nt $ eval e
-- | Get the object for a value.
objectFor :: Value -> VM Value
{-# INLINE objectFor #-}
objectFor !v = gets primitives >>= \is -> return $ objectFrom is v
-- | Raise a keyword particle as an error.
raise :: [String] -> [Value] -> VM a
{-# INLINE raise #-}
raise ns vs = throwError . Error $ keyParticleN ns vs
-- | Raise a single particle as an error.
raise' :: String -> VM a
{-# INLINE raise' #-}
raise' = throwError . Error . particle
-- | Convert an AtomoError into a value and raise it as an error.
throwError :: AtomoError -> VM a
{-throwError e = error ("panic: " ++ show (pretty e))-}
throwError e = gets top >>= \t -> do
r <- dispatch (keyword ["responds-to?"] [t, particle "Error"])
if r == Boolean True
then do
dispatch (msg t)
error ("panic: error returned normally for: " ++ show e)
else error ("panic: " ++ show (pretty e))
where
msg t = keyword ["error"] [t, asValue e]
|
vito/atomo
|
src/Atomo/Environment.hs
|
Haskell
|
bsd-3-clause
| 16,982
|
module Test where
test :: Int -> Int -> IO ()
test a b =
putStrLn $
mconcat
[ "Addition: "
, show addition
, ", Subtraction: "
, show subtraction
]
where
addition =
a + b
subtraction =
a - b
main :: IO ()
main =
output 1
where
output 0 =
test 0 0
output a =
test a 2
|
hecrj/haskell-format
|
test/specs/where/output.hs
|
Haskell
|
bsd-3-clause
| 436
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
-- | A pool of handles
module Data.Concurrent.Queue.Roq.HandlePool
(
-- * Starting the server
hroq_handle_pool_server
, hroq_handle_pool_server_closure
, hroq_handle_pool_server_pid
-- * API
, append
-- * Types
-- , CallbackFun
-- * Debug
, ping
, safeOpenFile
-- * Remote Table
, Data.Concurrent.Queue.Roq.HandlePool.__remoteTable
) where
import Control.Distributed.Process hiding (call)
import Control.Distributed.Process.Closure
import Control.Distributed.Process.Platform.ManagedProcess hiding (runProcess)
import Control.Distributed.Process.Platform.Time
import Control.Distributed.Process.Serializable()
import Control.Exception hiding (try,catch)
import Data.Binary
import Data.Concurrent.Queue.Roq.Logger
import Data.List
import Data.Typeable (Typeable)
import GHC.Generics
import System.Directory
import System.IO
import System.IO.Error
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Map as Map
--------------------------------------------------------------------------------
-- Types --
--------------------------------------------------------------------------------
{-
-define(MONITOR_INTERVAL_MS, 30000).
-}
mONITOR_INTERVAL_MS :: Delay
-- mONITOR_INTERVAL_MS = Delay $ milliSeconds 30000
mONITOR_INTERVAL_MS = Delay $ milliSeconds 9000
------------------------------------------------------------------------
-- Data Types
------------------------------------------------------------------------
-- Call operations
data AppendFile = AppendFile FilePath B.ByteString
deriving (Show,Typeable,Generic)
instance Binary AppendFile where
data CloseAppend = CloseAppend FilePath
deriving (Show,Typeable,Generic)
instance Binary CloseAppend where
-- Cast operations
data Ping = Ping
deriving (Typeable, Generic, Eq, Show)
instance Binary Ping where
-- ---------------------------------------------------------------------
data State = ST { stAppends :: Map.Map FilePath Handle
}
deriving (Show)
emptyState :: State
emptyState = ST Map.empty
--------------------------------------------------------------------------------
-- API --
--------------------------------------------------------------------------------
hroq_handle_pool_server :: Process ()
hroq_handle_pool_server = do
logm $ "HroqHandlePool:hroq_handle_pool_server entered"
start_handle_pool_server
hroq_handle_pool_server_pid :: Process ProcessId
hroq_handle_pool_server_pid = getServerPid
-- ---------------------------------------------------------------------
append :: ProcessId -> FilePath -> B.ByteString -> Process ()
append pid filename val =
call pid (AppendFile filename val)
closeAppend :: ProcessId -> FilePath -> Process ()
closeAppend pid filename =
call pid (CloseAppend filename)
ping :: Process ()
ping = do
pid <- getServerPid
cast pid Ping
-- ---------------------------------------------------------------------
getServerPid :: Process ProcessId
getServerPid = do
mpid <- whereis hroqHandlePoolServerProcessName
case mpid of
Just pid -> return pid
Nothing -> do
logm "HroqHandlePool:getServerPid failed"
error "HroqHandlePool:blow up"
-- -------------------------------------
hroqHandlePoolServerProcessName :: String
hroqHandlePoolServerProcessName = "HroqHandlePool"
-- ---------------------------------------------------------------------
start_handle_pool_server :: Process ()
start_handle_pool_server = do
logm $ "HroqHandlePool:start_handle_pool_server entered"
self <- getSelfPid
register hroqHandlePoolServerProcessName self
serve () initFunc serverDefinition
where initFunc :: InitHandler () State
initFunc _ = do
logm $ "HroqHandlePool:start.initFunc"
return $ InitOk emptyState mONITOR_INTERVAL_MS
serverDefinition :: ProcessDefinition State
serverDefinition = defaultProcess {
apiHandlers = [
handleCall handleAppendFileCall
, handleCall handleCloseAppendCall
-- , handleCast handlePublishConsumerStatsCast
, handleCast (\s Ping -> do {logm $ "HroqHandlePool:ping"; continue s })
]
, infoHandlers =
[
handleInfo handleInfoProcessMonitorNotification
]
, timeoutHandler = handleTimeout
, shutdownHandler = \_ reason -> do
{ logm $ "HroqHandlePool terminateHandler:" ++ (show reason) }
} :: ProcessDefinition State
-- ---------------------------------------------------------------------
-- Implementation
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
handleAppendFileCall :: State -> AppendFile -> Process (ProcessReply () State)
handleAppendFileCall st (AppendFile fileName val) = do
-- logm $ "HroqHandlePool.handleAppendFileCall entered for :" ++ show fileName
(st',h) <- case Map.lookup fileName (stAppends st) of
Just h -> do
-- logm $ "HroqHandlePool.handleAppendFileCall re-using handle"
return (st,h)
Nothing -> do
logm $ "HroqHandlePool.handleAppendFileCall opening file:" ++ show fileName
h <- liftIO $ safeOpenFile fileName AppendMode
return (st { stAppends = Map.insert fileName h (stAppends st) },h)
-- logm $ "HroqHandlePool.handleAppendFileCall writing:" ++ show val
liftIO $ B.hPut h val -- >> hFlush h
reply () st'
-- ---------------------------------------------------------------------
handleCloseAppendCall :: State -> CloseAppend -> Process (ProcessReply () State)
handleCloseAppendCall st (CloseAppend fileName) = do
logm $ "HroqHandlePool.handleCloseAppendCall entered for :" ++ show fileName
st' <- case Map.lookup fileName (stAppends st) of
Just h -> do
liftIO $ hClose h
return st { stAppends = Map.delete fileName (stAppends st) }
Nothing -> do
return st
reply () st'
-- ---------------------------------------------------------------------
-- |Try to open a file in the given mode, creating any required
-- directory structure if necessary
safeOpenFile :: FilePath -> IOMode -> IO Handle
safeOpenFile filename mode = handle handler (openBinaryFile filename mode)
where
handler e
| isDoesNotExistError e = do
createDirectoryIfMissing True $ take (1+(last $ elemIndices '/' filename)) filename -- maybe the path does not exist
safeOpenFile filename mode
| otherwise= if ("invalid" `isInfixOf` ioeGetErrorString e)
then
error $ "writeResource: " ++ show e ++ " defPath and/or keyResource are not suitable for a file path"
else do
hPutStrLn stderr $ "defaultWriteResource: " ++ show e ++ " in file: " ++ filename ++ " retrying"
safeOpenFile filename mode
-- ---------------------------------------------------------------------
handleTimeout :: TimeoutHandler State
handleTimeout st currDelay = do
logm $ "HroqHandlePool:handleTimeout entered"
mapM_ (\h -> liftIO $ hClose h) $ Map.elems (stAppends st)
timeoutAfter currDelay (st {stAppends = Map.empty })
-- timeoutAfter currDelay st
-- ---------------------------------------------------------------------
handleShutdown :: ShutdownHandler State
handleShutdown st reason = do
logm $ "HroqHandlePool.handleShutdown called for:" ++ show reason
return ()
-- ---------------------------------------------------------------------
handleInfoProcessMonitorNotification :: State -> ProcessMonitorNotification -> Process (ProcessAction State)
handleInfoProcessMonitorNotification st n@(ProcessMonitorNotification ref _pid _reason) = do
logm $ "HroqHandlePool:handleInfoProcessMonitorNotification called with: " ++ show n
let m = stAppends st
{-
case Map.lookup ref m of
Just key -> continue st { stMdict = Map.delete ref m
, stGdict = Map.delete key g }
Nothing -> continue st
-}
continue st
-- ---------------------------------------------------------------------
-- NOTE: the TH crap has to be a the end, as it can only see the stuff lexically before it in the file
$(remotable [ 'hroq_handle_pool_server
])
hroq_handle_pool_server_closure :: Closure (Process ())
hroq_handle_pool_server_closure = ( $(mkStaticClosure 'hroq_handle_pool_server))
-- EOF
|
alanz/hroq
|
src/Data/Concurrent/Queue/Roq/HandlePool.hs
|
Haskell
|
bsd-3-clause
| 8,601
|
--
-- An AST format for generated code in imperative languages
--
module SyntaxImp
-- Uncomment the below line to expose all top level symbols for
-- repl testing
{-
()
-- -}
where
data IId = IId [String] (Maybe Int)
deriving( Show )
data IAnnTy = INoAnn ITy
| IMut ITy -- things are immutable by default
deriving( Show )
data ITy = IBool
| IArr IAnnTy (Maybe Int)
| IByte
| IPtr IAnnTy
| IStruct IId
deriving( Show )
-- Id, type pair
data IAnnId = IAnnId IId IAnnTy
deriving( Show )
data IDecl = IFun IId [IAnnId] IAnnTy [IStmt]
| IStructure IId [IAnnId]
deriving( Show )
data IStmt = IReturn IId
deriving( Show )
|
ethanpailes/bbc
|
src/SyntaxImp.hs
|
Haskell
|
bsd-3-clause
| 707
|
{-# LANGUAGE DeriveGeneric #-}
-- | This is a wrapper around IO that permits SMT queries
module Language.Fixpoint.Solver.Monad
( -- * Type
SolveM
-- * Execution
, runSolverM
-- * Get Binds
, getBinds
-- * SMT Query
, filterValid
-- * Debug
, Stats
, tickIter
, stats
, numIter
)
where
import Control.DeepSeq
import GHC.Generics
import Language.Fixpoint.Utils.Progress
import Language.Fixpoint.Misc (groupList)
import Language.Fixpoint.Types.Config (Config, solver, real)
import qualified Language.Fixpoint.Types as F
import qualified Language.Fixpoint.Types.Errors as E
import qualified Language.Fixpoint.Smt.Theories as Thy
import Language.Fixpoint.Types.PrettyPrint
import Language.Fixpoint.Smt.Interface
import Language.Fixpoint.Solver.Validate
import Language.Fixpoint.Solver.Solution
import Data.Maybe (isJust, catMaybes)
import Text.PrettyPrint.HughesPJ (text)
import Control.Monad.State.Strict
import qualified Data.HashMap.Strict as M
---------------------------------------------------------------------------
-- | Solver Monadic API ---------------------------------------------------
---------------------------------------------------------------------------
type SolveM = StateT SolverState IO
data SolverState = SS { ssCtx :: !Context -- ^ SMT Solver Context
, ssBinds :: !F.BindEnv -- ^ All variables and types
, ssStats :: !Stats -- ^ Solver Statistics
}
data Stats = Stats { numCstr :: !Int -- ^ # Horn Constraints
, numIter :: !Int -- ^ # Refine Iterations
, numBrkt :: !Int -- ^ # smtBracket calls (push/pop)
, numChck :: !Int -- ^ # smtCheckUnsat calls
, numVald :: !Int -- ^ # times SMT said RHS Valid
} deriving (Show, Generic)
instance NFData Stats
stats0 :: F.GInfo c b -> Stats
stats0 fi = Stats nCs 0 0 0 0
where
nCs = M.size $ F.cm fi
instance PTable Stats where
ptable s = DocTable [ (text "# Constraints" , pprint (numCstr s))
, (text "# Refine Iterations" , pprint (numIter s))
, (text "# SMT Push & Pops" , pprint (numBrkt s))
, (text "# SMT Queries (Valid)" , pprint (numVald s))
, (text "# SMT Queries (Total)" , pprint (numChck s))
]
---------------------------------------------------------------------------
runSolverM :: Config -> F.GInfo c b -> Int -> SolveM a -> IO a
---------------------------------------------------------------------------
runSolverM cfg fi t act = do
ctx <- makeContext (not $ real cfg) (solver cfg) file
fst <$> runStateT (declare fi >> act) (SS ctx be $ stats0 fi)
where
be = F.bs fi
file = F.fileName fi -- (inFile cfg)
---------------------------------------------------------------------------
getBinds :: SolveM F.BindEnv
---------------------------------------------------------------------------
getBinds = ssBinds <$> get
---------------------------------------------------------------------------
getIter :: SolveM Int
---------------------------------------------------------------------------
getIter = numIter . ssStats <$> get
---------------------------------------------------------------------------
incIter, incBrkt :: SolveM ()
---------------------------------------------------------------------------
incIter = modifyStats $ \s -> s {numIter = 1 + numIter s}
incBrkt = modifyStats $ \s -> s {numBrkt = 1 + numBrkt s}
---------------------------------------------------------------------------
incChck, incVald :: Int -> SolveM ()
---------------------------------------------------------------------------
incChck n = modifyStats $ \s -> s {numChck = n + numChck s}
incVald n = modifyStats $ \s -> s {numVald = n + numVald s}
withContext :: (Context -> IO a) -> SolveM a
withContext k = (lift . k) =<< getContext
getContext :: SolveM Context
getContext = ssCtx <$> get
modifyStats :: (Stats -> Stats) -> SolveM ()
modifyStats f = modify $ \s -> s { ssStats = f (ssStats s) }
---------------------------------------------------------------------------
-- | SMT Interface --------------------------------------------------------
---------------------------------------------------------------------------
filterValid :: F.Pred -> Cand a -> SolveM [a]
---------------------------------------------------------------------------
filterValid p qs = do
qs' <- withContext $ \me ->
smtBracket me $
filterValid_ p qs me
-- stats
incBrkt
incChck (length qs)
incVald (length qs')
return qs'
filterValid_ :: F.Pred -> Cand a -> Context -> IO [a]
filterValid_ p qs me = catMaybes <$> do
smtAssert me p
forM qs $ \(q, x) ->
smtBracket me $ do
smtAssert me (F.PNot q)
valid <- smtCheckUnsat me
return $ if valid then Just x else Nothing
---------------------------------------------------------------------------
declare :: F.GInfo c a -> SolveM ()
---------------------------------------------------------------------------
declare fi = withContext $ \me -> do
xts <- either E.die return $ declSymbols fi
let ess = declLiterals fi
forM_ xts $ uncurry $ smtDecl me
forM_ ess $ smtDistinct me
declLiterals :: F.GInfo c a -> [[F.Expr]]
declLiterals fi = [es | (_, es) <- tess ]
where
notFun = not . F.isFunctionSortedReft . (`F.RR` F.trueReft)
tess = groupList [(t, F.expr x) | (x, t) <- F.toListSEnv $ F.lits fi, notFun t]
declSymbols :: F.GInfo c a -> Either E.Error [(F.Symbol, F.Sort)]
declSymbols = fmap dropThy . symbolSorts
where
dropThy = filter (not . isThy . fst)
isThy = isJust . Thy.smt2Symbol
---------------------------------------------------------------------------
stats :: SolveM Stats
---------------------------------------------------------------------------
stats = ssStats <$> get
---------------------------------------------------------------------------
tickIter :: Bool -> SolveM Int
---------------------------------------------------------------------------
tickIter newScc = progIter newScc >> incIter >> getIter
progIter :: Bool -> SolveM ()
progIter newScc = lift $ when newScc progressTick
|
gridaphobe/liquid-fixpoint
|
src/Language/Fixpoint/Solver/Monad.hs
|
Haskell
|
bsd-3-clause
| 6,560
|
{-# LANGUAGE OverloadedStrings #-}
module TW.Utils where
import Data.Char
import qualified Data.Text as T
capitalizeText :: T.Text -> T.Text
capitalizeText =
T.pack . go . T.unpack
where
go (x:xs) = toUpper x : xs
go [] = []
uncapitalizeText :: T.Text -> T.Text
uncapitalizeText =
T.pack . go . T.unpack
where
go (x:xs) = toLower x : xs
go [] = []
makeSafePrefixedFieldName :: T.Text -> T.Text
makeSafePrefixedFieldName = T.filter isAlphaNum
|
typed-wire/typed-wire
|
src/TW/Utils.hs
|
Haskell
|
mit
| 490
|
<?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="ru-RU">
<title>ViewState</title>
<maps>
<homeID>viewstate</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>
|
denniskniep/zap-extensions
|
addOns/viewstate/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
|
Haskell
|
apache-2.0
| 960
|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Streaming/Zlib.hs" #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | This is a middle-level wrapper around the zlib C API. It allows you to
-- work fully with bytestrings and not touch the FFI at all, but is still
-- low-level enough to allow you to implement high-level abstractions such as
-- enumerators. Significantly, it does not use lazy IO.
--
-- You'll probably need to reference the docs a bit to understand the
-- WindowBits parameters below, but a basic rule of thumb is 15 is for zlib
-- compression, and 31 for gzip compression.
--
-- A simple streaming compressor in pseudo-code would look like:
--
-- > def <- initDeflate ...
-- > popper <- feedDeflate def rawContent
-- > pullPopper popper
-- > ...
-- > finishDeflate def sendCompressedData
--
-- You can see a more complete example is available in the included
-- file-test.hs.
module Data.Streaming.Zlib
( -- * Inflate
Inflate
, initInflate
, initInflateWithDictionary
, feedInflate
, finishInflate
, flushInflate
, getUnusedInflate
, isCompleteInflate
-- * Deflate
, Deflate
, initDeflate
, initDeflateWithDictionary
, feedDeflate
, finishDeflate
, flushDeflate
, fullFlushDeflate
-- * Data types
, WindowBits (..)
, defaultWindowBits
, ZlibException (..)
, Popper
, PopperRes (..)
) where
import Data.Streaming.Zlib.Lowlevel
import Foreign.ForeignPtr
import Foreign.C.Types
import Data.ByteString.Unsafe
import Codec.Compression.Zlib (WindowBits(WindowBits), defaultWindowBits)
import qualified Data.ByteString as S
import Data.ByteString.Lazy.Internal (defaultChunkSize)
import Data.Typeable (Typeable)
import Control.Exception (Exception)
import Control.Monad (when)
import Data.IORef
type ZStreamPair = (ForeignPtr ZStreamStruct, ForeignPtr CChar)
-- | The state of an inflation (eg, decompression) process. All allocated
-- memory is automatically reclaimed by the garbage collector.
-- Also can contain the inflation dictionary that is used for decompression.
data Inflate = Inflate
ZStreamPair
(IORef S.ByteString) -- last ByteString fed in, needed for getUnusedInflate
(IORef Bool) -- set True when zlib indicates that inflation is complete
(Maybe S.ByteString) -- dictionary
-- | The state of a deflation (eg, compression) process. All allocated memory
-- is automatically reclaimed by the garbage collector.
newtype Deflate = Deflate ZStreamPair
-- | Exception that can be thrown from the FFI code. The parameter is the
-- numerical error code from the zlib library. Quoting the zlib.h file
-- directly:
--
-- * #define Z_OK 0
--
-- * #define Z_STREAM_END 1
--
-- * #define Z_NEED_DICT 2
--
-- * #define Z_ERRNO (-1)
--
-- * #define Z_STREAM_ERROR (-2)
--
-- * #define Z_DATA_ERROR (-3)
--
-- * #define Z_MEM_ERROR (-4)
--
-- * #define Z_BUF_ERROR (-5)
--
-- * #define Z_VERSION_ERROR (-6)
data ZlibException = ZlibException Int
deriving (Show, Typeable)
instance Exception ZlibException
-- | Some constants for the error codes, used internally
zStreamEnd :: CInt
zStreamEnd = 1
zNeedDict :: CInt
zNeedDict = 2
zBufError :: CInt
zBufError = -5
-- | Initialize an inflation process with the given 'WindowBits'. You will need
-- to call 'feedInflate' to feed compressed data to this and
-- 'finishInflate' to extract the final chunk of decompressed data.
initInflate :: WindowBits -> IO Inflate
initInflate w = do
zstr <- zstreamNew
inflateInit2 zstr w
fzstr <- newForeignPtr c_free_z_stream_inflate zstr
fbuff <- mallocForeignPtrBytes defaultChunkSize
withForeignPtr fbuff $ \buff ->
c_set_avail_out zstr buff $ fromIntegral defaultChunkSize
lastBS <- newIORef S.empty
complete <- newIORef False
return $ Inflate (fzstr, fbuff) lastBS complete Nothing
-- | Initialize an inflation process with the given 'WindowBits'.
-- Unlike initInflate a dictionary for inflation is set which must
-- match the one set during compression.
initInflateWithDictionary :: WindowBits -> S.ByteString -> IO Inflate
initInflateWithDictionary w bs = do
zstr <- zstreamNew
inflateInit2 zstr w
fzstr <- newForeignPtr c_free_z_stream_inflate zstr
fbuff <- mallocForeignPtrBytes defaultChunkSize
withForeignPtr fbuff $ \buff ->
c_set_avail_out zstr buff $ fromIntegral defaultChunkSize
lastBS <- newIORef S.empty
complete <- newIORef False
return $ Inflate (fzstr, fbuff) lastBS complete (Just bs)
-- | Initialize a deflation process with the given compression level and
-- 'WindowBits'. You will need to call 'feedDeflate' to feed uncompressed
-- data to this and 'finishDeflate' to extract the final chunks of compressed
-- data.
initDeflate :: Int -- ^ Compression level
-> WindowBits -> IO Deflate
initDeflate level w = do
zstr <- zstreamNew
deflateInit2 zstr level w 8 StrategyDefault
fzstr <- newForeignPtr c_free_z_stream_deflate zstr
fbuff <- mallocForeignPtrBytes defaultChunkSize
withForeignPtr fbuff $ \buff ->
c_set_avail_out zstr buff $ fromIntegral defaultChunkSize
return $ Deflate (fzstr, fbuff)
-- | Initialize an deflation process with the given compression level and
-- 'WindowBits'.
-- Unlike initDeflate a dictionary for deflation is set.
initDeflateWithDictionary :: Int -- ^ Compression level
-> S.ByteString -- ^ Deflate dictionary
-> WindowBits -> IO Deflate
initDeflateWithDictionary level bs w = do
zstr <- zstreamNew
deflateInit2 zstr level w 8 StrategyDefault
fzstr <- newForeignPtr c_free_z_stream_deflate zstr
fbuff <- mallocForeignPtrBytes defaultChunkSize
unsafeUseAsCStringLen bs $ \(cstr, len) -> do
c_call_deflate_set_dictionary zstr cstr $ fromIntegral len
withForeignPtr fbuff $ \buff ->
c_set_avail_out zstr buff $ fromIntegral defaultChunkSize
return $ Deflate (fzstr, fbuff)
-- | Feed the given 'S.ByteString' to the inflater. Return a 'Popper',
-- an IO action that returns the decompressed data a chunk at a time.
-- The 'Popper' must be called to exhaustion before using the 'Inflate'
-- object again.
--
-- Note that this function automatically buffers the output to
-- 'defaultChunkSize', and therefore you won't get any data from the popper
-- until that much decompressed data is available. After you have fed all of
-- the compressed data to this function, you can extract your final chunk of
-- decompressed data using 'finishInflate'.
feedInflate
:: Inflate
-> S.ByteString
-> IO Popper
feedInflate (Inflate (fzstr, fbuff) lastBS complete inflateDictionary) bs = do
-- Write the BS to lastBS for use by getUnusedInflate. This is
-- theoretically unnecessary, since we could just grab the pointer from the
-- fzstr when needed. However, in that case, we wouldn't be holding onto a
-- reference to the ForeignPtr, so the GC may decide to collect the
-- ByteString in the interim.
writeIORef lastBS bs
withForeignPtr fzstr $ \zstr ->
unsafeUseAsCStringLen bs $ \(cstr, len) ->
c_set_avail_in zstr cstr $ fromIntegral len
return $ drain fbuff fzstr (Just bs) inflate False
where
inflate zstr = do
res <- c_call_inflate_noflush zstr
res2 <- if (res == zNeedDict)
then maybe (return zNeedDict)
(\dict -> (unsafeUseAsCStringLen dict $ \(cstr, len) -> do
c_call_inflate_set_dictionary zstr cstr $ fromIntegral len
c_call_inflate_noflush zstr))
inflateDictionary
else return res
when (res2 == zStreamEnd) (writeIORef complete True)
return res2
-- | An IO action that returns the next chunk of data, returning 'Nothing' when
-- there is no more data to be popped.
type Popper = IO PopperRes
data PopperRes = PRDone
| PRNext !S.ByteString
| PRError !ZlibException
deriving (Show, Typeable)
-- | Ensure that the given @ByteString@ is not deallocated.
keepAlive :: Maybe S.ByteString -> IO a -> IO a
keepAlive Nothing = id
keepAlive (Just bs) = unsafeUseAsCStringLen bs . const
drain :: ForeignPtr CChar
-> ForeignPtr ZStreamStruct
-> Maybe S.ByteString
-> (ZStream' -> IO CInt)
-> Bool
-> Popper
drain fbuff fzstr mbs func isFinish = withForeignPtr fzstr $ \zstr -> keepAlive mbs $ do
res <- func zstr
if res < 0 && res /= zBufError
then return $ PRError $ ZlibException $ fromIntegral res
else do
avail <- c_get_avail_out zstr
let size = defaultChunkSize - fromIntegral avail
toOutput = avail == 0 || (isFinish && size /= 0)
if toOutput
then withForeignPtr fbuff $ \buff -> do
bs <- S.packCStringLen (buff, size)
c_set_avail_out zstr buff
$ fromIntegral defaultChunkSize
return $ PRNext bs
else return PRDone
-- | As explained in 'feedInflate', inflation buffers your decompressed
-- data. After you call 'feedInflate' with your last chunk of compressed
-- data, you will likely have some data still sitting in the buffer. This
-- function will return it to you.
finishInflate :: Inflate -> IO S.ByteString
finishInflate (Inflate (fzstr, fbuff) _ _ _) =
withForeignPtr fzstr $ \zstr ->
withForeignPtr fbuff $ \buff -> do
avail <- c_get_avail_out zstr
let size = defaultChunkSize - fromIntegral avail
bs <- S.packCStringLen (buff, size)
c_set_avail_out zstr buff $ fromIntegral defaultChunkSize
return bs
-- | Flush the inflation buffer. Useful for interactive application.
--
-- This is actually a synonym for 'finishInflate'. It is provided for its more
-- semantic name.
--
-- Since 0.0.3
flushInflate :: Inflate -> IO S.ByteString
flushInflate = finishInflate
-- | Retrieve any data remaining after inflating. For more information on motivation, see:
--
-- <https://github.com/fpco/streaming-commons/issues/20>
--
-- Since 0.1.11
getUnusedInflate :: Inflate -> IO S.ByteString
getUnusedInflate (Inflate (fzstr, _) ref _ _) = do
bs <- readIORef ref
len <- withForeignPtr fzstr c_get_avail_in
return $ S.drop (S.length bs - fromIntegral len) bs
-- | Returns True if the inflater has reached end-of-stream, or False if
-- it is still expecting more data.
--
-- Since 0.1.18
isCompleteInflate :: Inflate -> IO Bool
isCompleteInflate (Inflate _ _ complete _) = readIORef complete
-- | Feed the given 'S.ByteString' to the deflater. Return a 'Popper',
-- an IO action that returns the compressed data a chunk at a time.
-- The 'Popper' must be called to exhaustion before using the 'Deflate'
-- object again.
--
-- Note that this function automatically buffers the output to
-- 'defaultChunkSize', and therefore you won't get any data from the popper
-- until that much compressed data is available. After you have fed all of the
-- decompressed data to this function, you can extract your final chunks of
-- compressed data using 'finishDeflate'.
feedDeflate :: Deflate -> S.ByteString -> IO Popper
feedDeflate (Deflate (fzstr, fbuff)) bs = do
withForeignPtr fzstr $ \zstr ->
unsafeUseAsCStringLen bs $ \(cstr, len) -> do
c_set_avail_in zstr cstr $ fromIntegral len
return $ drain fbuff fzstr (Just bs) c_call_deflate_noflush False
-- | As explained in 'feedDeflate', deflation buffers your compressed
-- data. After you call 'feedDeflate' with your last chunk of uncompressed
-- data, use this to flush the rest of the data and signal end of input.
finishDeflate :: Deflate -> Popper
finishDeflate (Deflate (fzstr, fbuff)) =
drain fbuff fzstr Nothing c_call_deflate_finish True
-- | Flush the deflation buffer. Useful for interactive application.
-- Internally this passes Z_SYNC_FLUSH to the zlib library.
--
-- Unlike 'finishDeflate', 'flushDeflate' does not signal end of input,
-- meaning you can feed more uncompressed data afterward.
--
-- Since 0.0.3
flushDeflate :: Deflate -> Popper
flushDeflate (Deflate (fzstr, fbuff)) =
drain fbuff fzstr Nothing c_call_deflate_flush True
-- | Full flush the deflation buffer. Useful for interactive
-- applications where previously streamed data may not be
-- available. Using `fullFlushDeflate` too often can seriously degrade
-- compression. Internally this passes Z_FULL_FLUSH to the zlib
-- library.
--
-- Like 'flushDeflate', 'fullFlushDeflate' does not signal end of input,
-- meaning you can feed more uncompressed data afterward.
--
-- Since 0.1.5
fullFlushDeflate :: Deflate -> Popper
fullFlushDeflate (Deflate (fzstr, fbuff)) =
drain fbuff fzstr Nothing c_call_deflate_full_flush True
|
phischu/fragnix
|
tests/packages/scotty/Data.Streaming.Zlib.hs
|
Haskell
|
bsd-3-clause
| 12,910
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.ParseUtils
-- Copyright : (c) The University of Glasgow 2004
--
-- Maintainer : libraries@haskell.org
-- Stability : alpha
-- Portability : portable
--
-- Utilities for parsing PackageDescription and InstalledPackageInfo.
{- All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the University nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module UnitTest.Distribution.ParseUtils where
import Distribution.ParseUtils
import Distribution.Compiler (CompilerFlavor, parseCompilerFlavorCompat)
import Distribution.License (License)
import Distribution.Version
import Distribution.Package ( parsePackageName )
import Distribution.Compat.ReadP as ReadP hiding (get)
import Distribution.Simple.Utils (intercalate)
import Language.Haskell.Extension (Extension)
import Text.PrettyPrint hiding (braces)
import Data.Char (isSpace, isUpper, toLower, isAlphaNum, isSymbol, isDigit)
import Data.Maybe (fromMaybe)
import Data.Tree as Tree (Tree(..), flatten)
import Test.HUnit (Test(..), assertBool, Assertion, runTestTT, Counts, assertEqual)
import IO
import System.Environment ( getArgs )
import Control.Monad ( zipWithM_ )
------------------------------------------------------------------------------
-- TESTING
test_readFields = case
readFields testFile
of
ParseOk _ x -> x == expectedResult
_ -> False
where
testFile = unlines $
[ "Cabal-version: 3"
, ""
, "Description: This is a test file "
, " with a description longer than two lines. "
, "if os(windows) {"
, " License: You may not use this software"
, " ."
, " If you do use this software you will be seeked and destroyed."
, "}"
, "if os(linux) {"
, " Main-is: foo1 "
, "}"
, ""
, "if os(vista) {"
, " executable RootKit {"
, " Main-is: DRMManager.hs"
, " }"
, "} else {"
, " executable VistaRemoteAccess {"
, " Main-is: VCtrl"
, "}}"
, ""
, "executable Foo-bar {"
, " Main-is: Foo.hs"
, "}"
]
expectedResult =
[ F 1 "cabal-version" "3"
, F 3 "description"
"This is a test file\nwith a description longer than two lines."
, IfBlock 5 "os(windows) "
[ F 6 "license"
"You may not use this software\n\nIf you do use this software you will be seeked and destroyed."
]
[]
, IfBlock 10 "os(linux) "
[ F 11 "main-is" "foo1" ]
[ ]
, IfBlock 14 "os(vista) "
[ Section 15 "executable" "RootKit "
[ F 16 "main-is" "DRMManager.hs"]
]
[ Section 19 "executable" "VistaRemoteAccess "
[F 20 "main-is" "VCtrl"]
]
, Section 23 "executable" "Foo-bar "
[F 24 "main-is" "Foo.hs"]
]
test_readFieldsCompat' = case test_readFieldsCompat of
ParseOk _ fs -> mapM_ (putStrLn . show) fs
x -> putStrLn $ "Failed: " ++ show x
test_readFieldsCompat = readFields testPkgDesc
where
testPkgDesc = unlines [
"-- Required",
"Name: Cabal",
"Version: 0.1.1.1.1-rain",
"License: LGPL",
"License-File: foo",
"Copyright: Free Text String",
"Cabal-version: >1.1.1",
"-- Optional - may be in source?",
"Author: Happy Haskell Hacker",
"Homepage: http://www.haskell.org/foo",
"Package-url: http://www.haskell.org/foo",
"Synopsis: a nice package!",
"Description: a really nice package!",
"Category: tools",
"buildable: True",
"CC-OPTIONS: -g -o",
"LD-OPTIONS: -BStatic -dn",
"Frameworks: foo",
"Tested-with: GHC",
"Stability: Free Text String",
"Build-Depends: haskell-src, HUnit>=1.0.0-rain",
"Other-Modules: Distribution.Package, Distribution.Version,",
" Distribution.Simple.GHCPackageConfig",
"Other-files: file1, file2",
"Extra-Tmp-Files: file1, file2",
"C-Sources: not/even/rain.c, such/small/hands",
"HS-Source-Dirs: src, src2",
"Exposed-Modules: Distribution.Void, Foo.Bar",
"Extensions: OverlappingInstances, TypeSynonymInstances",
"Extra-Libraries: libfoo, bar, bang",
"Extra-Lib-Dirs: \"/usr/local/libs\"",
"Include-Dirs: your/slightest, look/will",
"Includes: /easily/unclose, /me, \"funky, path\\\\name\"",
"Install-Includes: /easily/unclose, /me, \"funky, path\\\\name\"",
"GHC-Options: -fTH -fglasgow-exts",
"Hugs-Options: +TH",
"Nhc-Options: ",
"Jhc-Options: ",
"",
"-- Next is an executable",
"Executable: somescript",
"Main-is: SomeFile.hs",
"Other-Modules: Foo1, Util, Main",
"HS-Source-Dir: scripts",
"Extensions: OverlappingInstances",
"GHC-Options: ",
"Hugs-Options: ",
"Nhc-Options: ",
"Jhc-Options: "
]
{-
test' = do h <- openFile "../Cabal.cabal" ReadMode
s <- hGetContents h
let r = readFields s
case r of
ParseOk _ fs -> mapM_ (putStrLn . show) fs
x -> putStrLn $ "Failed: " ++ show x
putStrLn "==================="
mapM_ (putStrLn . show) $
merge . zip [1..] . lines $ s
hClose h
-}
-- ghc -DDEBUG --make Distribution/ParseUtils.hs -o test
main :: IO ()
main = do
inputFiles <- getArgs
ok <- mapM checkResult inputFiles
zipWithM_ summary inputFiles ok
putStrLn $ show (length (filter not ok)) ++ " out of " ++ show (length ok) ++ " failed"
where summary f True = return ()
summary f False = putStrLn $ f ++ " failed :-("
checkResult :: FilePath -> IO Bool
checkResult inputFile = do
file <- readTextFile inputFile
case readFields file of
ParseOk _ result -> do
hPutStrLn stderr $ inputFile ++ " parses ok :-)"
return True
ParseFailed err -> do
hPutStrLn stderr $ inputFile ++ " parse failed:"
hPutStrLn stderr $ show err
return False
|
IreneKnapp/Faction
|
libfaction/tests/UnitTest/Distribution/ParseUtils.hs
|
Haskell
|
bsd-3-clause
| 7,904
|
-- Helper script to shadow that automatically generated by cabal, but pointing
-- to our local development directory.
--
module Paths_accelerate_cuda where
import Data.Version
import System.Directory
version :: Version
version = Version {versionBranch = [0,14,0,0], versionTags = ["dev"]}
getDataDir :: IO FilePath
getDataDir = getCurrentDirectory
|
kumasento/accelerate-cuda
|
utils/Paths_accelerate_cuda.hs
|
Haskell
|
bsd-3-clause
| 353
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Compiler
-- Copyright : Isaac Jones 2003-2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This should be a much more sophisticated abstraction than it is. Currently
-- it's just a bit of data about the compiler, like it's flavour and name and
-- version. The reason it's just data is because currently it has to be in
-- 'Read' and 'Show' so it can be saved along with the 'LocalBuildInfo'. The
-- only interesting bit of info it contains is a mapping between language
-- extensions and compiler command line flags. This module also defines a
-- 'PackageDB' type which is used to refer to package databases. Most compilers
-- only know about a single global package collection but GHC has a global and
-- per-user one and it lets you create arbitrary other package databases. We do
-- not yet fully support this latter feature.
module Distribution.Simple.Compiler (
-- * Haskell implementations
module Distribution.Compiler,
Compiler(..),
showCompilerId, showCompilerIdWithAbi,
compilerFlavor, compilerVersion,
compilerCompatFlavor,
compilerCompatVersion,
compilerInfo,
-- * Support for package databases
PackageDB(..),
PackageDBStack,
registrationPackageDB,
absolutePackageDBPaths,
absolutePackageDBPath,
-- * Support for optimisation levels
OptimisationLevel(..),
flagToOptimisationLevel,
-- * Support for debug info levels
DebugInfoLevel(..),
flagToDebugInfoLevel,
-- * Support for language extensions
Flag,
languageToFlags,
unsupportedLanguages,
extensionsToFlags,
unsupportedExtensions,
parmakeSupported,
reexportedModulesSupported,
renamingPackageFlagsSupported,
unifiedIPIDRequired,
packageKeySupported,
unitIdSupported,
coverageSupported,
profilingSupported,
backpackSupported,
arResponseFilesSupported,
libraryDynDirSupported,
-- * Support for profiling detail levels
ProfDetailLevel(..),
knownProfDetailLevels,
flagToProfDetailLevel,
showProfDetailLevel,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Compiler
import Distribution.Version
import Distribution.Text
import Language.Haskell.Extension
import Distribution.Simple.Utils
import qualified Data.Map as Map (lookup)
import System.Directory (canonicalizePath)
data Compiler = Compiler {
compilerId :: CompilerId,
-- ^ Compiler flavour and version.
compilerAbiTag :: AbiTag,
-- ^ Tag for distinguishing incompatible ABI's on the same
-- architecture/os.
compilerCompat :: [CompilerId],
-- ^ Other implementations that this compiler claims to be
-- compatible with.
compilerLanguages :: [(Language, Flag)],
-- ^ Supported language standards.
compilerExtensions :: [(Extension, Flag)],
-- ^ Supported extensions.
compilerProperties :: Map String String
-- ^ A key-value map for properties not covered by the above fields.
}
deriving (Eq, Generic, Typeable, Show, Read)
instance Binary Compiler
showCompilerId :: Compiler -> String
showCompilerId = display . compilerId
showCompilerIdWithAbi :: Compiler -> String
showCompilerIdWithAbi comp =
display (compilerId comp) ++
case compilerAbiTag comp of
NoAbiTag -> []
AbiTag xs -> '-':xs
compilerFlavor :: Compiler -> CompilerFlavor
compilerFlavor = (\(CompilerId f _) -> f) . compilerId
compilerVersion :: Compiler -> Version
compilerVersion = (\(CompilerId _ v) -> v) . compilerId
-- | Is this compiler compatible with the compiler flavour we're interested in?
--
-- For example this checks if the compiler is actually GHC or is another
-- compiler that claims to be compatible with some version of GHC, e.g. GHCJS.
--
-- > if compilerCompatFlavor GHC compiler then ... else ...
--
compilerCompatFlavor :: CompilerFlavor -> Compiler -> Bool
compilerCompatFlavor flavor comp =
flavor == compilerFlavor comp
|| flavor `elem` [ flavor' | CompilerId flavor' _ <- compilerCompat comp ]
-- | Is this compiler compatible with the compiler flavour we're interested in,
-- and if so what version does it claim to be compatible with.
--
-- For example this checks if the compiler is actually GHC-7.x or is another
-- compiler that claims to be compatible with some GHC-7.x version.
--
-- > case compilerCompatVersion GHC compiler of
-- > Just (Version (7:_)) -> ...
-- > _ -> ...
--
compilerCompatVersion :: CompilerFlavor -> Compiler -> Maybe Version
compilerCompatVersion flavor comp
| compilerFlavor comp == flavor = Just (compilerVersion comp)
| otherwise =
listToMaybe [ v | CompilerId fl v <- compilerCompat comp, fl == flavor ]
compilerInfo :: Compiler -> CompilerInfo
compilerInfo c = CompilerInfo (compilerId c)
(compilerAbiTag c)
(Just . compilerCompat $ c)
(Just . map fst . compilerLanguages $ c)
(Just . map fst . compilerExtensions $ c)
-- ------------------------------------------------------------
-- * Package databases
-- ------------------------------------------------------------
-- |Some compilers have a notion of a database of available packages.
-- For some there is just one global db of packages, other compilers
-- support a per-user or an arbitrary db specified at some location in
-- the file system. This can be used to build isloated environments of
-- packages, for example to build a collection of related packages
-- without installing them globally.
--
data PackageDB = GlobalPackageDB
| UserPackageDB
| SpecificPackageDB FilePath
deriving (Eq, Generic, Ord, Show, Read)
instance Binary PackageDB
-- | We typically get packages from several databases, and stack them
-- together. This type lets us be explicit about that stacking. For example
-- typical stacks include:
--
-- > [GlobalPackageDB]
-- > [GlobalPackageDB, UserPackageDB]
-- > [GlobalPackageDB, SpecificPackageDB "package.conf.inplace"]
--
-- Note that the 'GlobalPackageDB' is invariably at the bottom since it
-- contains the rts, base and other special compiler-specific packages.
--
-- We are not restricted to using just the above combinations. In particular
-- we can use several custom package dbs and the user package db together.
--
-- When it comes to writing, the top most (last) package is used.
--
type PackageDBStack = [PackageDB]
-- | Return the package that we should register into. This is the package db at
-- the top of the stack.
--
registrationPackageDB :: PackageDBStack -> PackageDB
registrationPackageDB [] = error "internal error: empty package db set"
registrationPackageDB dbs = last dbs
-- | Make package paths absolute
absolutePackageDBPaths :: PackageDBStack -> NoCallStackIO PackageDBStack
absolutePackageDBPaths = traverse absolutePackageDBPath
absolutePackageDBPath :: PackageDB -> NoCallStackIO PackageDB
absolutePackageDBPath GlobalPackageDB = return GlobalPackageDB
absolutePackageDBPath UserPackageDB = return UserPackageDB
absolutePackageDBPath (SpecificPackageDB db) =
SpecificPackageDB `liftM` canonicalizePath db
-- ------------------------------------------------------------
-- * Optimisation levels
-- ------------------------------------------------------------
-- | Some compilers support optimising. Some have different levels.
-- For compilers that do not the level is just capped to the level
-- they do support.
--
data OptimisationLevel = NoOptimisation
| NormalOptimisation
| MaximumOptimisation
deriving (Bounded, Enum, Eq, Generic, Read, Show)
instance Binary OptimisationLevel
flagToOptimisationLevel :: Maybe String -> OptimisationLevel
flagToOptimisationLevel Nothing = NormalOptimisation
flagToOptimisationLevel (Just s) = case reads s of
[(i, "")]
| i >= fromEnum (minBound :: OptimisationLevel)
&& i <= fromEnum (maxBound :: OptimisationLevel)
-> toEnum i
| otherwise -> error $ "Bad optimisation level: " ++ show i
++ ". Valid values are 0..2"
_ -> error $ "Can't parse optimisation level " ++ s
-- ------------------------------------------------------------
-- * Debug info levels
-- ------------------------------------------------------------
-- | Some compilers support emitting debug info. Some have different
-- levels. For compilers that do not the level is just capped to the
-- level they do support.
--
data DebugInfoLevel = NoDebugInfo
| MinimalDebugInfo
| NormalDebugInfo
| MaximalDebugInfo
deriving (Bounded, Enum, Eq, Generic, Read, Show)
instance Binary DebugInfoLevel
flagToDebugInfoLevel :: Maybe String -> DebugInfoLevel
flagToDebugInfoLevel Nothing = NormalDebugInfo
flagToDebugInfoLevel (Just s) = case reads s of
[(i, "")]
| i >= fromEnum (minBound :: DebugInfoLevel)
&& i <= fromEnum (maxBound :: DebugInfoLevel)
-> toEnum i
| otherwise -> error $ "Bad debug info level: " ++ show i
++ ". Valid values are 0..3"
_ -> error $ "Can't parse debug info level " ++ s
-- ------------------------------------------------------------
-- * Languages and Extensions
-- ------------------------------------------------------------
unsupportedLanguages :: Compiler -> [Language] -> [Language]
unsupportedLanguages comp langs =
[ lang | lang <- langs
, isNothing (languageToFlag comp lang) ]
languageToFlags :: Compiler -> Maybe Language -> [Flag]
languageToFlags comp = filter (not . null)
. catMaybes . map (languageToFlag comp)
. maybe [Haskell98] (\x->[x])
languageToFlag :: Compiler -> Language -> Maybe Flag
languageToFlag comp ext = lookup ext (compilerLanguages comp)
-- |For the given compiler, return the extensions it does not support.
unsupportedExtensions :: Compiler -> [Extension] -> [Extension]
unsupportedExtensions comp exts =
[ ext | ext <- exts
, isNothing (extensionToFlag comp ext) ]
type Flag = String
-- |For the given compiler, return the flags for the supported extensions.
extensionsToFlags :: Compiler -> [Extension] -> [Flag]
extensionsToFlags comp = nub . filter (not . null)
. catMaybes . map (extensionToFlag comp)
extensionToFlag :: Compiler -> Extension -> Maybe Flag
extensionToFlag comp ext = lookup ext (compilerExtensions comp)
-- | Does this compiler support parallel --make mode?
parmakeSupported :: Compiler -> Bool
parmakeSupported = ghcSupported "Support parallel --make"
-- | Does this compiler support reexported-modules?
reexportedModulesSupported :: Compiler -> Bool
reexportedModulesSupported = ghcSupported "Support reexported-modules"
-- | Does this compiler support thinning/renaming on package flags?
renamingPackageFlagsSupported :: Compiler -> Bool
renamingPackageFlagsSupported = ghcSupported
"Support thinning and renaming package flags"
-- | Does this compiler have unified IPIDs (so no package keys)
unifiedIPIDRequired :: Compiler -> Bool
unifiedIPIDRequired = ghcSupported "Requires unified installed package IDs"
-- | Does this compiler support package keys?
packageKeySupported :: Compiler -> Bool
packageKeySupported = ghcSupported "Uses package keys"
-- | Does this compiler support unit IDs?
unitIdSupported :: Compiler -> Bool
unitIdSupported = ghcSupported "Uses unit IDs"
-- | Does this compiler support Backpack?
backpackSupported :: Compiler -> Bool
backpackSupported = ghcSupported "Support Backpack"
-- | Does this compiler support a package database entry with:
-- "dynamic-library-dirs"?
libraryDynDirSupported :: Compiler -> Bool
libraryDynDirSupported comp = case compilerFlavor comp of
GHC ->
-- Not just v >= mkVersion [8,0,1,20161022], as there
-- are many GHC 8.1 nightlies which don't support this.
((v >= mkVersion [8,0,1,20161022] && v < mkVersion [8,1]) ||
v >= mkVersion [8,1,20161021])
_ -> False
where
v = compilerVersion comp
-- | Does this compiler's "ar" command supports response file
-- arguments (i.e. @file-style arguments).
arResponseFilesSupported :: Compiler -> Bool
arResponseFilesSupported = ghcSupported "ar supports at file"
-- | Does this compiler support Haskell program coverage?
coverageSupported :: Compiler -> Bool
coverageSupported comp =
case compilerFlavor comp of
GHC -> True
GHCJS -> True
_ -> False
-- | Does this compiler support profiling?
profilingSupported :: Compiler -> Bool
profilingSupported comp =
case compilerFlavor comp of
GHC -> True
GHCJS -> True
LHC -> True
_ -> False
-- | Utility function for GHC only features
ghcSupported :: String -> Compiler -> Bool
ghcSupported key comp =
case compilerFlavor comp of
GHC -> checkProp
GHCJS -> checkProp
_ -> False
where checkProp =
case Map.lookup key (compilerProperties comp) of
Just "YES" -> True
_ -> False
-- ------------------------------------------------------------
-- * Profiling detail level
-- ------------------------------------------------------------
-- | Some compilers (notably GHC) support profiling and can instrument
-- programs so the system can account costs to different functions. There are
-- different levels of detail that can be used for this accounting.
-- For compilers that do not support this notion or the particular detail
-- levels, this is either ignored or just capped to some similar level
-- they do support.
--
data ProfDetailLevel = ProfDetailNone
| ProfDetailDefault
| ProfDetailExportedFunctions
| ProfDetailToplevelFunctions
| ProfDetailAllFunctions
| ProfDetailOther String
deriving (Eq, Generic, Read, Show)
instance Binary ProfDetailLevel
flagToProfDetailLevel :: String -> ProfDetailLevel
flagToProfDetailLevel "" = ProfDetailDefault
flagToProfDetailLevel s =
case lookup (lowercase s)
[ (name, value)
| (primary, aliases, value) <- knownProfDetailLevels
, name <- primary : aliases ]
of Just value -> value
Nothing -> ProfDetailOther s
knownProfDetailLevels :: [(String, [String], ProfDetailLevel)]
knownProfDetailLevels =
[ ("default", [], ProfDetailDefault)
, ("none", [], ProfDetailNone)
, ("exported-functions", ["exported"], ProfDetailExportedFunctions)
, ("toplevel-functions", ["toplevel", "top"], ProfDetailToplevelFunctions)
, ("all-functions", ["all"], ProfDetailAllFunctions)
]
showProfDetailLevel :: ProfDetailLevel -> String
showProfDetailLevel dl = case dl of
ProfDetailNone -> "none"
ProfDetailDefault -> "default"
ProfDetailExportedFunctions -> "exported-functions"
ProfDetailToplevelFunctions -> "toplevel-functions"
ProfDetailAllFunctions -> "all-functions"
ProfDetailOther other -> other
|
themoritz/cabal
|
Cabal/Distribution/Simple/Compiler.hs
|
Haskell
|
bsd-3-clause
| 15,692
|
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.ParserCombinators.Parsec.Char
-- Copyright : (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : derek.a.elkins@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Parsec compatibility module
--
-----------------------------------------------------------------------------
module Text.ParserCombinators.Parsec.Char
( CharParser,
spaces,
space,
newline,
tab,
upper,
lower,
alphaNum,
letter,
digit,
hexDigit,
octDigit,
char,
string,
anyChar,
oneOf,
noneOf,
satisfy
) where
import Text.Parsec.Char
import Text.Parsec.String
type CharParser st = GenParser Char st
|
aslatter/parsec
|
src/Text/ParserCombinators/Parsec/Char.hs
|
Haskell
|
bsd-2-clause
| 870
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="bs-BA">
<title>Advanced SQLInjection Scanner</title>
<maps>
<homeID>sqliplugin</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/sqliplugin/src/main/javahelp/help_bs_BA/helpset_bs_BA.hs
|
Haskell
|
apache-2.0
| 981
|
{- Refactoring: move the definiton 'fringe' to module C1. This example aims
to test the moving of the definition and the modification of export/import -}
module D1(fringe, sumSquares) where
import C1
fringe :: Tree a -> [a]
fringe p |isLeaf p
= [(leaf1 p)]
fringe p |isBranch p
= fringe (branch1 p) ++ fringe (branch2 p)
sumSquares (x:xs) = sq x + sumSquares xs
sumSquares [] = 0
sq x = x ^pow
pow = 2
|
kmate/HaRe
|
old/testing/fromConcreteToAbstract/D1_TokOut.hs
|
Haskell
|
bsd-3-clause
| 481
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Fix
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Monadic fixpoints.
--
-- For a detailed discussion, see Levent Erkok's thesis,
-- /Value Recursion in Monadic Computations/, Oregon Graduate Institute, 2002.
--
-----------------------------------------------------------------------------
module Control.Monad.Fix (
MonadFix(mfix),
fix
) where
import Data.Either
import Data.Function ( fix )
import Data.Maybe
import Data.Monoid ( Dual(..), Sum(..), Product(..)
, First(..), Last(..), Alt(..) )
import GHC.Base ( Monad, error, (.) )
import GHC.List ( head, tail )
import GHC.ST
import System.IO
-- | Monads having fixed points with a \'knot-tying\' semantics.
-- Instances of 'MonadFix' should satisfy the following laws:
--
-- [/purity/]
-- @'mfix' ('return' . h) = 'return' ('fix' h)@
--
-- [/left shrinking/ (or /tightening/)]
-- @'mfix' (\\x -> a >>= \\y -> f x y) = a >>= \\y -> 'mfix' (\\x -> f x y)@
--
-- [/sliding/]
-- @'mfix' ('Control.Monad.liftM' h . f) = 'Control.Monad.liftM' h ('mfix' (f . h))@,
-- for strict @h@.
--
-- [/nesting/]
-- @'mfix' (\\x -> 'mfix' (\\y -> f x y)) = 'mfix' (\\x -> f x x)@
--
-- This class is used in the translation of the recursive @do@ notation
-- supported by GHC and Hugs.
class (Monad m) => MonadFix m where
-- | The fixed point of a monadic computation.
-- @'mfix' f@ executes the action @f@ only once, with the eventual
-- output fed back as the input. Hence @f@ should not be strict,
-- for then @'mfix' f@ would diverge.
mfix :: (a -> m a) -> m a
-- Instances of MonadFix for Prelude monads
instance MonadFix Maybe where
mfix f = let a = f (unJust a) in a
where unJust (Just x) = x
unJust Nothing = error "mfix Maybe: Nothing"
instance MonadFix [] where
mfix f = case fix (f . head) of
[] -> []
(x:_) -> x : mfix (tail . f)
instance MonadFix IO where
mfix = fixIO
instance MonadFix ((->) r) where
mfix f = \ r -> let a = f a r in a
instance MonadFix (Either e) where
mfix f = let a = f (unRight a) in a
where unRight (Right x) = x
unRight (Left _) = error "mfix Either: Left"
instance MonadFix (ST s) where
mfix = fixST
-- Instances of Data.Monoid wrappers
instance MonadFix Dual where
mfix f = Dual (fix (getDual . f))
instance MonadFix Sum where
mfix f = Sum (fix (getSum . f))
instance MonadFix Product where
mfix f = Product (fix (getProduct . f))
instance MonadFix First where
mfix f = First (mfix (getFirst . f))
instance MonadFix Last where
mfix f = Last (mfix (getLast . f))
instance MonadFix f => MonadFix (Alt f) where
mfix f = Alt (mfix (getAlt . f))
|
urbanslug/ghc
|
libraries/base/Control/Monad/Fix.hs
|
Haskell
|
bsd-3-clause
| 3,227
|
{-# LANGUAGE MagicHash #-}
module ShouldFail where
import GHC.Base
my_undefined :: a -- This one has kind *, not OpenKind
my_undefined = undefined
die :: Int -> ByteArray#
die _ = my_undefined
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_fail/tcfail090.hs
|
Haskell
|
bsd-3-clause
| 198
|
module Main where
newtype T = C { f :: String }
{-
hugs (Sept 2006) gives
"bc"
Program error: Prelude.undefined
hugs trac #48
-}
main = do print $ case C "abc" of
C { f = v } -> v
print $ case undefined of
C {} -> True
|
olsner/ghc
|
testsuite/tests/codeGen/should_run/cgrun062.hs
|
Haskell
|
bsd-3-clause
| 270
|
{-|
Module: Itchy.Routes
Description: Web app routes
License: MIT
-}
{-# LANGUAGE BangPatterns, LambdaCase, MultiParamTypeClasses, OverloadedLists, OverloadedStrings, QuasiQuotes, RankNTypes, TemplateHaskell, TypeFamilies, ViewPatterns #-}
module Itchy.Routes
( App(..)
) where
import Control.Monad
import Control.Monad.IO.Class
import Data.Bits
import qualified Data.ByteArray.Encoding as BA
import qualified Data.HashMap.Strict as HM
import Data.Int
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.Serialize as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Vector as V
import Data.Word
import Foreign.C.Types
import qualified Network.HTTP.Types as HT
import System.Posix.Time
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5((!))
import qualified Text.Blaze.Html5.Attributes as A
import qualified Text.Blaze.Html.Renderer.Text as H(renderHtml)
import qualified Wai.Routes as W
import qualified Web.Cookie as W
import Itchy.ItchInvestigator
import Itchy.Itch
import Itchy.ItchCache
import Itchy.Localization
import Itchy.Localization.En
import Itchy.Localization.RichText
import Itchy.Localization.Ru
import Itchy.Report
import Itchy.Report.Analysis
import Itchy.Report.Record
import Itchy.Static
data App = App
{ appItchApi :: !ItchApi
, appItchCache :: !ItchCache
, appItchInvestigator :: !ItchInvestigator
, appItchInvestigationStalePeriod :: {-# UNPACK #-} !Int64
}
localizations :: [(T.Text, Localization)]
localizations =
[ ("en", localizationEn)
, ("ru", localizationRu)
]
getLocalization :: W.HandlerM App master Localization
getLocalization = do
maybeNewLocale <- W.getParam "locale"
locale <- case maybeNewLocale of
Just newLocale -> do
W.setCookie W.def
{ W.setCookieName ="locale"
, W.setCookieValue = T.encodeUtf8 newLocale
, W.setCookiePath = Just "/"
, W.setCookieMaxAge = Just $ 365 * 24 * 3600
}
return newLocale
Nothing -> fromMaybe "en" <$> W.getCookie "locale"
return $ fromMaybe localizationEn $ lookup locale localizations
W.mkRoute "App" [W.parseRoutes|
/ HomeR GET
/game/#Word64 GameR GET
/upload/#Word64 UploadR GET
/upload/#Word64/download UploadDownloadR GET
/investigateUpload/#Word64 InvestigateUploadR POST
/auth AuthR POST
/search SearchR GET
/gamebyurl GameByUrlR GET
|]
getHomeR :: W.Handler App
getHomeR = W.runHandlerM $ do
showRoute <- W.showRouteSub
loc <- getLocalization
page (locHome loc) [(locHome loc, HomeR)] $ do
H.p $ H.toHtml $ locWelcome loc
H.form ! A.method "GET" ! A.action (H.toValue $ showRoute SearchR) $ do
H.label ! A.type_ "text" ! A.for "searchtext" $ H.toHtml $ locSearchGameByName loc
H.br
H.input ! A.type_ "text" ! A.id "searchtext" ! A.name "s"
H.input ! A.type_ "submit" ! A.value (H.toValue $ locSearch loc)
H.form ! A.method "GET" ! A.action (H.toValue $ showRoute GameByUrlR) $ do
H.label ! A.type_ "text" ! A.for "urltext" $ H.toHtml $ locGoToGameByUrl loc
H.br
H.input ! A.type_ "text" ! A.id "urltext" ! A.name "url" ! A.placeholder "[https://]creator[.itch.io]/game[/]"
H.input ! A.type_ "submit" ! A.value (H.toValue $ locGo loc)
getGameR :: Word64 -> W.Handler App
getGameR gameId = W.runHandlerM $ do
App
{ appItchCache = itchCache
, appItchInvestigator = itchInvestigator
, appItchInvestigationStalePeriod = investigationStalePeriod
} <- W.sub
showRoute <- W.showRouteSub
loc <- getLocalization
maybeGameWithUploads <- liftIO $ itchCacheGetGame itchCache (ItchGameId gameId)
case maybeGameWithUploads of
Just (game@ItchGame
{ itchGame_title = gameTitle
, itchGame_url = gameUrl
, itchGame_cover_url = maybeGameCoverUrl
, itchGame_user = ItchUser
{ itchUser_username = creatorUserName
}
, itchGame_can_be_bought = gameCanBeBought
, itchGame_in_press_system = gameInPressSystem
, itchGame_short_text = fromMaybe "" -> gameShortText
, itchGame_has_demo = gameHasDemo
, itchGame_min_price = ((* (0.01 :: Float)) . fromIntegral) -> gameMinPrice
, itchGame_p_windows = gameWindows
, itchGame_p_linux = gameLinux
, itchGame_p_osx = gameMacOS
, itchGame_p_android = gameAndroid
}, gameUploads) -> do
let gameByAuthor = locGameByAuthor loc gameTitle creatorUserName
let uploadsById = HM.fromList $ V.toList $ flip fmap gameUploads $ \(upload@ItchUpload
{ itchUpload_id = uploadId
}, _maybeBuild) -> (uploadId, upload)
let uploadName uploadId = case HM.lookup uploadId uploadsById of
Just ItchUpload
{ itchUpload_display_name = maybeDisplayName
, itchUpload_filename = fileName
} -> Just $ fromMaybe fileName maybeDisplayName
Nothing -> Nothing
investigations <- liftIO $ forM gameUploads $ \(ItchUpload
{ itchUpload_id = uploadId
, itchUpload_filename = uploadFileName
}, _maybeBuild) -> investigateItchUpload itchInvestigator uploadId uploadFileName False
CTime currentTime <- liftIO epochTime
let reinvestigateTimeCutoff = currentTime - investigationStalePeriod
page gameByAuthor [(locHome loc, HomeR), (gameByAuthor, GameR gameId)] $ H.div ! A.class_ "game_info" $ do
case maybeGameCoverUrl of
Just coverUrl -> H.img ! A.class_ "cover" ! A.src (H.toValue coverUrl)
Nothing -> mempty
H.p $ H.toHtml $ locLink loc gameUrl
H.p $ H.toHtml $ locDescription loc gameShortText
H.p $ H.toHtml (locPlatforms loc) <> ": "
<> (if gameWindows then H.span ! A.class_ "tag" $ "windows" else mempty)
<> (if gameLinux then H.span ! A.class_ "tag" $ "linux" else mempty)
<> (if gameMacOS then H.span ! A.class_ "tag" $ "macos" else mempty)
<> (if gameAndroid then H.span ! A.class_ "tag" $ "android" else mempty)
H.p $ H.toHtml $ if gameHasDemo then locHasDemo loc else locNoDemo loc
H.p $ H.toHtml $
if gameCanBeBought then
if gameMinPrice <= 0 then locFreeDonationsAllowed loc
else locMinimumPrice loc <> ": $" <> T.pack (show gameMinPrice)
else locFreePaymentsDisabled loc
H.p $ H.toHtml $ if gameInPressSystem then locOptedInPressSystem loc else locNotOptedInPressSystem loc
H.h2 $ H.toHtml $ locUploads loc
H.table $ do
H.tr $ do
H.th $ H.toHtml $ locDisplayName loc
H.th $ H.toHtml $ locFileName loc
H.th $ H.toHtml $ locSize loc
H.th $ H.toHtml $ locTags loc
H.th "Butler"
H.th $ H.toHtml $ locReportStatus loc
forM_ (V.zip gameUploads investigations) $ \((ItchUpload
{ itchUpload_id = ItchUploadId uploadId
, itchUpload_display_name = fromMaybe "" -> uploadDisplayName
, itchUpload_filename = uploadFileName
, itchUpload_demo = uploadDemo
, itchUpload_preorder = uploadPreorder
, itchUpload_size = uploadSize
, itchUpload_p_windows = uploadWindows
, itchUpload_p_linux = uploadLinux
, itchUpload_p_osx = uploadMacOS
, itchUpload_p_android = uploadAndroid
}, maybeBuild), investigation) -> H.tr ! A.class_ "upload" $ do
H.td ! A.class_ "name" $ H.toHtml uploadDisplayName
H.td ! A.class_ "filename" $ {- a ! A.href (H.toValue $ showRoute $ UploadR uploadId) $ -} H.toHtml uploadFileName
H.td $ H.toHtml $ locSizeInBytes loc uploadSize
H.td $ do
if uploadWindows then H.span ! A.class_ "tag" $ "windows" else mempty
if uploadLinux then H.span ! A.class_ "tag" $ "linux" else mempty
if uploadMacOS then H.span ! A.class_ "tag" $ "macos" else mempty
if uploadAndroid then H.span ! A.class_ "tag" $ "android" else mempty
if uploadDemo then H.span ! A.class_ "tag" $ "demo" else mempty
if uploadPreorder then H.span ! A.class_ "tag" $ "preorder" else mempty
H.td $ case maybeBuild of
Just ItchBuild
{ itchBuild_version = T.pack . show -> buildVersion
, itchBuild_user_version = fromMaybe (locNoUserVersion loc) -> buildUserVersion
} -> H.toHtml $ locBuildVersion loc buildVersion buildUserVersion
Nothing -> H.toHtml $ locDoesntUseButler loc
H.td $ case investigation of
ItchStartedInvestigation -> H.toHtml $ locInvestigationStarted loc
ItchQueuedInvestigation n -> H.toHtml $ locInvestigationQueued loc $ n + 1
ItchProcessingInvestigation -> H.toHtml $ locInvestigationProcessing loc
ItchInvestigation
{ itchInvestigationMaybeReport = maybeReport
, itchInvestigationTime = t
} -> do
if isJust maybeReport
then H.a ! A.href (H.toValue $ showRoute $ UploadR uploadId) ! A.target "_blank" $ H.toHtml $ locInvestigationSucceeded loc
else H.toHtml $ locInvestigationFailed loc
when (t < reinvestigateTimeCutoff) $ H.form ! A.class_ "formreprocess" ! A.action (H.toValue $ showRoute $ InvestigateUploadR uploadId) ! A.method "POST" $
H.input ! A.type_ "submit" ! A.value (H.toValue $ locReinvestigate loc)
H.h2 $ H.toHtml $ locReport loc
let
reportsCount = foldr (\investigation !c -> case investigation of
ItchInvestigation {} -> c + 1
_ -> c
) 0 investigations
in when (reportsCount < V.length gameUploads) $ H.p $ (H.toHtml $ locReportNotComplete loc reportsCount (V.length gameUploads)) <> " " <> (H.a ! A.href (H.toValue $ showRoute $ GameR gameId) $ H.toHtml $ locRefresh loc)
let AnalysisGame
{ analysisGame_uploads = analysisUploads
, analysisGame_release = AnalysisUploadGroup
{ analysisUploadGroup_records = releaseGroupRecords
}
, analysisGame_preorder = AnalysisUploadGroup
{ analysisUploadGroup_records = preorderGroupRecords
}
, analysisGame_demo = AnalysisUploadGroup
{ analysisUploadGroup_records = demoGroupRecords
}
, analysisGame_records = gameRecords
} = analyseGame loc game $ concat $
flip fmap (V.toList $ V.zip gameUploads investigations) $
\((u, _), inv) -> case inv of
ItchInvestigation
{ itchInvestigationMaybeReport = Just r
} -> [(u, r)]
_ -> []
let uploadsRecords = concat $ Prelude.map analysisUpload_records analysisUploads
let records = flip sortOn
( gameRecords
<> releaseGroupRecords
<> preorderGroupRecords
<> demoGroupRecords
<> uploadsRecords
) $ \Record
{ recordScope = scope
, recordSeverity = severity
, recordName = name
, recordMessage = message
} -> (severity, scope, name, message)
H.table $ do
H.tr $ do
H.th $ H.toHtml $ locRecordSeverity loc
H.th ! A.class_ "scope" $ H.toHtml $ locRecordScope loc
H.th ! A.class_ "name" $ H.toHtml $ locRecordName loc
H.th ! A.class_ "name" $ H.toHtml $ locRecordMessage loc
forM_ records $ \Record
{ recordScope = scope
, recordSeverity = severity
, recordName = name
, recordMessage = message
} -> let
(cls, ttl) = case severity of
SeverityOk -> ("ok", locSeverityOk loc)
SeverityInfo -> ("info", locSeverityInfo loc)
SeverityTip -> ("tip", locSeverityTip loc)
SeverityWarn -> ("warn", locSeverityWarn loc)
SeverityBad -> ("bad", locSeverityBad loc)
SeverityErr -> ("err", locSeverityErr loc)
in H.tr ! A.class_ cls $ do
H.td ! A.class_ "status" $ H.div $ H.toHtml ttl
H.td $ H.toHtml $ case scope of
ProjectScope -> locScopeProject loc
UploadGroupScope uploadGroup -> locScopeUploadGroup loc uploadGroup
UploadScope uploadId -> locScopeUpload loc (uploadName uploadId)
EntryScope uploadId entryPath -> locScopeEntry loc (uploadName uploadId) (T.intercalate "/" entryPath)
H.td $ H.div ! A.class_ "record" $ H.toHtml name
H.td $ unless (message == RichText []) $
H.div ! A.class_ "message" $ H.toHtml message
Nothing -> do
let gameByAuthor = locUnknownGame loc
W.header "Refresh" "3"
page gameByAuthor [(locHome loc, HomeR), (gameByAuthor, GameR gameId)] $ do
H.p $ H.toHtml $ locGameNotCached loc
H.p $ H.a ! A.href (H.toValue $ showRoute $ GameR gameId) $ H.toHtml $ locRefresh loc
getUploadR :: Word64 -> W.Handler App
getUploadR uploadId = W.runHandlerM $ do
App
{ appItchCache = itchCache
, appItchInvestigator = itchInvestigator
} <- W.sub
loc <- getLocalization
maybeUpload <- liftIO $ itchCacheGetUpload itchCache $ ItchUploadId uploadId
case maybeUpload of
Just (ItchUpload
{ itchUpload_filename = uploadFileName
, itchUpload_game_id = ItchGameId gameId
}, _maybeBuild) -> do
maybeGameWithUploads <- liftIO $ itchCacheGetGame itchCache $ ItchGameId gameId
case maybeGameWithUploads of
Just (ItchGame
{ itchGame_title = gameTitle
, itchGame_user = ItchUser
{ itchUser_username = creatorUserName
}
}, _) -> do
let gameByAuthor = locGameByAuthor loc gameTitle creatorUserName
investigation <- liftIO $ investigateItchUpload itchInvestigator (ItchUploadId uploadId) uploadFileName False
case investigation of
ItchInvestigation
{ itchInvestigationMaybeReport = maybeReport
} -> page uploadFileName [(locHome loc, HomeR), (gameByAuthor, GameR gameId), (uploadFileName, UploadR uploadId)] $ do
case maybeReport of
Just Report
{ report_unpack = ReportUnpack_succeeded rootEntries
} -> H.table ! A.class_ "entries" $ do
H.tr $ do
H.th $ H.toHtml $ locFileName loc
H.th $ H.toHtml $ locSize loc
H.th $ H.toHtml $ locAccessMode loc
H.th $ H.toHtml $ locTags loc
let
tag = H.span ! A.class_ "tag"
tagArch = \case
ReportArch_unknown -> mempty
ReportArch_x86 -> tag "x86"
ReportArch_x64 -> tag "x64"
printEntries level = mapM_ (printEntry level) . M.toAscList
printEntry level (entryName, entry) = do
H.tr $ do
H.td ! A.style ("padding-left: " <> (H.toValue $ 5 + level * 20) <> "px") $ H.toHtml entryName
H.td $ case entry of
ReportEntry_file
{ reportEntry_size = entrySize
} -> H.toHtml $ locSizeInBytes loc $ toInteger entrySize
_ -> mempty
H.td $ do
let entryMode = reportEntry_mode entry
let isDir = case entry of
ReportEntry_directory {} -> True
_ -> False
tag $ H.toHtml $
(if isDir then 'd' else '.') :
(if (entryMode .&. 0x100) > 0 then 'r' else '.') :
(if (entryMode .&. 0x80) > 0 then 'w' else '.') :
(if (entryMode .&. 0x40) > 0 then 'x' else '.') :
(if (entryMode .&. 0x20) > 0 then 'r' else '.') :
(if (entryMode .&. 0x10) > 0 then 'w' else '.') :
(if (entryMode .&. 0x8) > 0 then 'x' else '.') :
(if (entryMode .&. 0x4) > 0 then 'r' else '.') :
(if (entryMode .&. 0x2) > 0 then 'w' else '.') :
(if (entryMode .&. 0x1) > 0 then 'x' else '.') : []
H.td $ case entry of
ReportEntry_unknown {} -> mempty
ReportEntry_file
{ reportEntry_parses = entryParses
} -> forM_ entryParses $ \case
ReportParse_itchToml {} -> tag ".itch.toml"
ReportParse_binaryPe ReportBinaryPe
{ reportBinaryPe_arch = arch
, reportBinaryPe_isCLR = isCLR
} -> do
tag "PE"
when isCLR $ tag "CLR"
tagArch arch
ReportParse_binaryElf ReportBinaryElf
{ reportBinaryElf_arch = arch
} -> do
tag "ELF"
tagArch arch
ReportParse_binaryMachO ReportBinaryMachO
{ reportBinaryMachO_binaries = subBinaries
} -> do
tag "Mach-O"
forM_ subBinaries $ \ReportMachOSubBinary
{ reportMachoSubBinary_arch = arch
} -> tagArch arch
ReportParse_archive {} -> mempty
ReportParse_msi {} -> tag "msi"
ReportEntry_directory {} -> mempty
ReportEntry_symlink
{ reportEntry_link = entryLink
} -> do
tag $ H.toHtml $ locSymlink loc
H.toHtml entryLink
case entry of
ReportEntry_file
{ reportEntry_parses = parses
} -> forM_ parses $ \case
ReportParse_archive ReportArchive
{ reportArchive_entries = entryEntries
} -> printEntries (level + 1) entryEntries
ReportParse_msi ReportMsi
{ reportMsi_entries = entryEntries
} -> printEntries (level + 1) entryEntries
_ -> mempty
ReportEntry_directory
{ reportEntry_entries = entryEntries
} -> printEntries (level + 1) entryEntries
_ -> mempty
printEntries (0 :: Int) rootEntries
_ -> return ()
_ -> W.status HT.notFound404
Nothing -> W.status HT.notFound404
Nothing -> W.status HT.notFound404
getUploadDownloadR :: Word64 -> W.Handler App
getUploadDownloadR (ItchUploadId -> uploadId) = W.runHandlerM $ do
App
{ appItchApi = itchApi
} <- W.sub
maybeDownloadKeyId <- W.getParam "downloadKey"
url <- liftIO $ itchDownloadUpload itchApi uploadId (ItchDownloadKeyId . read . T.unpack <$> maybeDownloadKeyId)
W.header "Location" $ T.encodeUtf8 url
W.status HT.seeOther303
postInvestigateUploadR :: Word64 -> W.Handler App
postInvestigateUploadR (ItchUploadId -> uploadId) = W.runHandlerM $ do
App
{ appItchCache = itchCache
, appItchInvestigator = itchInvestigator
} <- W.sub
showRoute <- W.showRouteSub
maybeUpload <- liftIO $ itchCacheGetUpload itchCache uploadId
case maybeUpload of
Just (ItchUpload
{ itchUpload_filename = uploadFileName
, itchUpload_game_id = ItchGameId gameId
}, _maybeBuild) -> do
void $ liftIO $ investigateItchUpload itchInvestigator uploadId uploadFileName True
W.header "Location" (T.encodeUtf8 $ showRoute $ GameR gameId)
W.status HT.seeOther303
Nothing -> W.status HT.notFound404
postAuthR :: W.Handler App
postAuthR = W.runHandlerM $ do
App
{ appItchApi = itchApi
} <- W.sub
maybeToken <- W.getPostParam "token"
maybeUser <- case maybeToken of
Just token -> liftIO $ Just <$> itchJwtMe itchApi token
Nothing -> return Nothing
case maybeUser of
Just user -> do
W.setCookie W.def
{ W.setCookieName = "user"
, W.setCookieValue = BA.convertToBase BA.Base64URLUnpadded $ S.encode user
, W.setCookiePath = Just "/"
}
showRoute <- W.showRouteSub
W.header "Location" (T.encodeUtf8 $ showRoute HomeR)
W.status HT.seeOther303
Nothing -> W.status HT.notFound404
getSearchR :: W.Handler App
getSearchR = W.runHandlerM $ do
App
{ appItchApi = itchApi
} <- W.sub
showRoute <- W.showRouteSub
loc <- getLocalization
searchText <- fromMaybe "" <$> W.getParam "s"
Right games <- if T.null searchText then return $ Right V.empty else liftIO $ itchSearchGame itchApi searchText
page (locSearch loc) [(locHome loc, HomeR), (locSearch loc, SearchR)] $ do
H.form ! A.method "GET" ! A.action (H.toValue $ showRoute SearchR) $ do
H.input ! A.type_ "text" ! A.name "s" ! A.value (H.toValue searchText)
H.input ! A.type_ "submit" ! A.value (H.toValue $ locSearch loc)
H.div ! A.class_ "searchresults" $ forM_ games $ \ItchGameShort
{ itchGameShort_id = ItchGameId gameId
, itchGameShort_title = gameTitle
, itchGameShort_cover_url = maybeGameCoverUrl
} -> H.a ! A.class_ "game" ! A.href (H.toValue $ showRoute $ GameR gameId) ! A.target "_blank" $ do
case maybeGameCoverUrl of
Just gameCoverUrl -> H.img ! A.src (H.toValue gameCoverUrl)
Nothing -> mempty
H.span $ H.toHtml gameTitle
getGameByUrlR :: W.Handler App
getGameByUrlR = W.runHandlerM $ do
App
{ appItchApi = itchApi
} <- W.sub
showRoute <- W.showRouteSub
searchText <- fromMaybe "" <$> W.getParam "url"
-- strip various stuff, and parse
let
pref p s = fromMaybe s $ T.stripPrefix p s
suf q s = fromMaybe s $ T.stripSuffix q s
case T.splitOn "/" $ T.replace ".itch.io/" "/" $ suf "/" $ pref "https://" $ pref "http://" $ searchText of
[creator, game] -> do
maybeGameId <- liftIO $ itchGameGetByUrl itchApi creator game
case maybeGameId of
Just (ItchGameId gameId) -> do
W.header "Location" $ T.encodeUtf8 $ showRoute $ GameR gameId
W.status HT.seeOther303
Nothing -> W.status HT.notFound404
_ -> W.status HT.notFound404
page :: W.RenderRoute master => T.Text -> [(T.Text, W.Route App)] -> H.Html -> W.HandlerM App master ()
page titleText pieces bodyHtml = do
W.header HT.hCacheControl "public, max-age=1"
maybeUserCookie <- W.getCookie "user"
let maybeUser = case maybeUserCookie of
Just (BA.convertFromBase BA.Base64URLUnpadded . T.encodeUtf8 -> Right (S.decode -> Right user)) -> Just user
_ -> Nothing
showRoute <- W.showRouteSub
loc <- getLocalization
W.html $ TL.toStrict $ H.renderHtml $ H.docTypeHtml $ do
H.head $ do
H.meta ! A.charset "utf-8"
H.meta ! A.name "robots" ! A.content "index,follow"
H.link ! A.rel "stylesheet" ! A.href [staticPath|static-stylus/itchy.css|]
H.link ! A.rel "icon" ! A.type_ "image/png" ! A.href [staticPath|static/itchio.svg|]
H.script ! A.src [staticPath|static/jquery-2.1.4.min.js|] $ mempty
H.script ! A.src [staticPath|static-js/itchy.js|] $ mempty
H.title $ H.toHtml $ titleText <> " - " <> "itch.io Developer's Sanity Keeper"
H.body $ do
H.div ! A.class_ "header" $ do
H.div ! A.class_ "pieces" $ forM_ pieces $ \(pieceName, pieceRoute) -> do
void "/ "
H.a ! A.href (H.toValue $ showRoute pieceRoute) $ H.toHtml pieceName
void " "
case maybeUser of
Just ItchUser
{ itchUser_username = userName
, itchUser_url = userUrl
, itchUser_cover_url = userMaybeCoverUrl
} -> H.div ! A.class_ "user" $ do
H.a ! A.href (H.toValue userUrl) $ do
case userMaybeCoverUrl of
Just userCoverUrl -> H.img ! A.src (H.toValue userCoverUrl)
Nothing -> mempty
H.toHtml userName
Nothing -> mempty
H.h1 $ H.toHtml titleText
bodyHtml
H.div ! A.class_ "footer" $ do
H.div $ H.toHtml $ locNoAffiliation loc
H.div $ do
H.span ! A.class_ "localizations" $ forM_ localizations $ \(locale, localization) ->
H.a ! A.href ("?locale=" <> H.toValue locale) $ H.toHtml $ locLanguageName localization
H.span " | "
H.a ! A.href "https://github.com/quyse/itchy" ! A.target "_blank" $ "Github"
|
quyse/itchy
|
Itchy/Routes.hs
|
Haskell
|
mit
| 22,676
|
module Ch1010ex1 (
stops
, vowels
, nouns
, verbs
, allWords
, allWordsPrefixP
) where
import Combinatorial (comboOfN)
import Data.Monoid
stops :: [Char]
stops = "pbtdkg"
vowels :: [Char]
vowels = "aeiou"
nouns :: [String]
nouns = ["bird", "dog", "cat", "car", "Elon Musk", "the dying of the light", "my cousin vinny"]
verbs :: [String]
verbs = ["hits", "runs", "starts", "stops", "kills", "shouts at", "calls", "rolls eyes at"]
-- returns all three-character combinations of stop-vowel-stop
-- zip all beginnings with each ending vowels
allWords :: [String]
allWords = comboOfN mempty (map (map return) [stops, vowels, stops])
allWordsPrefixP :: [String]
allWordsPrefixP = filter (\(x:xs) -> x == 'p') allWords
-- returns all sentences composed of noun-verb-noun
allSentences :: [String]
allSentences = comboOfN " " [nouns, verbs, nouns]
-- get all combos of N lists of elements
-- From Combinatorial.hs
comboOfN :: Monoid a => a -> [[a]] -> [a]
comboOfN sep (z:zs) = foldl ((joinCombinations .) . makeCombinations) z zs
where
makeCombinations x y = zip (take (length y) (repeat x)) y
joinCombinations = concatMap $ \(xs, y) -> map (\x -> x <> sep <> y) xs
|
JoshuaGross/haskell-learning-log
|
Code/Haskellbook/ch10.10ex1.hs
|
Haskell
|
mit
| 1,214
|
{-# LANGUAGE RecordWildCards, TypeFamilies #-}
import Control.Monad
import qualified Data.Map as M
import Text.Printf
type FieldName = String
type Point = M.Map FieldName (Maybe Double)
type Label = Double
class DataPass a where
type Init a
create :: (Init a) -> a
update :: a -> [(Point, Label)] -> a
apply1 :: a -> Point -> Point
apply :: a -> [Point] -> [Point]
data MeanImputer = MI {fieldNames :: [FieldName],
moments :: [(Double, Int)]}
instance DataPass MeanImputer where
type Init MeanImputer = [String]
create = createMI
update = updateMI
apply datapass points = map (apply1 datapass) points
apply1 = imputeMean
imputeMean :: MeanImputer -> Point -> Point
imputeMean mi point =
foldr update point (zip (fieldNames mi) (moments mi))
where update (fname, (d, n)) pt =
case M.lookup fname pt of
(Just (Just v)) -> pt
_ -> M.insert fname (Just (d / fromIntegral n)) pt
createMI :: [FieldName] -> MeanImputer
createMI fieldNames = MI fieldNames $ replicate (length fieldNames) (0.0, 0)
updateMI1 :: MeanImputer -> (Point, Label) -> MeanImputer
updateMI1 mi@(MI {..}) (point, _) =
mi {moments = moments'}
where moments' = zipWith update fieldNames moments
update fname (d, n) =
case M.lookup fname point of
Just (Just value) -> (d + value, n + 1)
_ -> (d , n)
updateMI :: MeanImputer -> [(Point, Label)] -> MeanImputer
updateMI mi labeledPoints =
foldl updateMI1 mi labeledPoints
testData :: [Point]
testData = [M.fromList [("A", Just 0), ("B", Just 1), ("C", Nothing), ("D", Just 4)],
M.fromList [("A", Nothing), ("B", Just 2), ("C", Just 14), ("D", Just 8)],
M.fromList [("A", Just 1), ("B", Nothing), ("C", Nothing) ],
M.fromList [("A", Nothing), ("B", Just 4), ("C", Just 22), ("D", Just 3)],
M.fromList [("A", Just 0), ("B", Just 5), ("C", Just 11), ("D", Just 1)]]
testDataWithLabels :: [(Point, Label)]
testDataWithLabels = zip testData (repeat 0.0) -- labels not used here.
printDF :: [Point] -> IO ()
printDF = mapM_ printPoint
where printPoint pt = line pt >> putStrLn ""
line pt = forM_ (M.toList pt) $ \(fname, maybeVal) -> do
putStr $ fname ++ "= "
case maybeVal of
Just v -> printf "%6.2f" v
Nothing -> putStr " NA "
putStr "; "
demo :: IO ()
demo = do
let dpEmpty = create ["A", "B", "D"] :: MeanImputer
dpFull = update dpEmpty testDataWithLabels
putStrLn "Before imputation:"
printDF testData
putStrLn "After imputation: "
printDF $ apply dpFull testData
main :: IO ()
main = demo
|
michaelochurch/stats-haskell-talk-201509
|
Main.hs
|
Haskell
|
mit
| 2,739
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Test.Unit.Connection where
import qualified Test.Framework as Framework
import Test.Framework
import Test.HUnit
import Test.Framework.Providers.HUnit
import Web.SocketIO.Server
import Web.SocketIO.Types
import Web.SocketIO.Channel
import Web.SocketIO.Connection
--------------------------------------------------------------------------------
testConfig :: Configuration
testConfig = defaultConfig
{ transports = [XHRPolling]
, logLevel = 3
, logTo = stderr
, heartbeats = True
, closeTimeout = 2
, heartbeatTimeout = 60
, heartbeatInterval = 25
, pollingDuration = 20
}
makeEnvironment :: IO Env
makeEnvironment = do
tableRef <- newSessionTableRef
let handler = return ()
logChhannel <- newLogChannel
globalChannel <- newGlobalChannel
return $ Env tableRef handler testConfig logChhannel globalChannel
--------------------------------------------------------------------------------
testHandshake :: Assertion
testHandshake = do
env <- makeEnvironment
MsgHandshake _ a b t <- runConnection env Handshake
assertEqual "respond with " (expectedResponse env) (MsgHandshake "" a b t)
where expectedResponse env = MsgHandshake "" heartbeatTimeout' closeTimeout' transports'
where config = envConfiguration env
heartbeatTimeout' = if heartbeats config
then heartbeatTimeout config
else 0
closeTimeout' = closeTimeout config
transports' = transports config
--------------------------------------------------------------------------------
testConnect :: Assertion
testConnect = do
env <- makeEnvironment
MsgHandshake sessionID _ _ _ <- runConnection env Handshake
res <- runConnection env (Connect sessionID)
assertEqual "respond with (MsgConnect NoEndpoint)" (MsgConnect NoEndpoint) res
--------------------------------------------------------------------------------
testRequest :: Assertion
testRequest = do
env <- makeEnvironment
MsgHandshake sessionID _ _ _ <- runConnection env Handshake
runConnection env (Connect sessionID)
res <- runConnection env (Request sessionID (MsgEvent NoID NoEndpoint (Event "event name" (Payload ["payload"]))))
assertEqual "respond with (MsgConnect NoEndpoint)" (MsgConnect NoEndpoint) (res)
--------------------------------------------------------------------------------
testDisconnect :: Assertion
testDisconnect = do
env <- makeEnvironment
MsgHandshake sessionID _ _ _ <- runConnection env Handshake
runConnection env (Connect sessionID)
res <- runConnection env (Disconnect sessionID)
assertEqual "respond with MsgNoop" MsgNoop res
--------------------------------------------------------------------------------
test :: Framework.Test
test = testGroup "Connection"
[ testCase "Handshake" testHandshake
, testCase "Connect" testConnect
, testCase "Request" testRequest
, testCase "Disconnect" testDisconnect
]
|
banacorn/socket.io-haskell
|
test/Test/Unit/Connection.hs
|
Haskell
|
mit
| 3,318
|
module StupidBot.Bot (stupidBot) where
import Vindinium.Types
import Utils
import StupidBot.Goal
import qualified Data.Graph.AStar as AS
import Data.Maybe (fromMaybe, fromJust)
import Data.List (find)
stupidBot :: Bot
stupidBot = directionTo whereToGo
directionTo :: GPS -> State -> Dir
directionTo gps s =
let from = heroPos $ stateHero s
path = shortestPathTo s $ gps s
in case path of
(p:_) -> dirFromPos from p
[] -> Stay
shortestPathTo :: State -> Goal -> [Pos]
shortestPathTo s goal =
let board = gameBoard $ stateGame s
hero = stateHero s
path = AS.aStar (adjacentTiles board)
(stepCost s goal)
(distanceEstimateTo goal s)
(isGoal goal s)
(heroPos hero)
in fromMaybe [] path
distanceEstimateTo :: Goal -> State -> Pos -> Int
distanceEstimateTo Heal s pos =
minimum $ map (manhattan pos) (taverns (gameBoard $ stateGame s))
distanceEstimateTo (Capture _) s pos =
let board = gameBoard $ stateGame s
in minimum $ map (\p ->
let heroid = heroId $ stateHero s
Just m = tileAt board p
in if canCaptureMine m heroid then manhattan pos p else 999) (mines board)
distanceEstimateTo (Kill hid) s pos =
let heroes = gameHeroes $ stateGame s
Just h = find (\e -> heroId e == hid) heroes
in manhattan pos $ heroPos h
distanceEstimateTo Survive _ _ = 1
distanceEstimateTo _ _ _ = error "not implemented!"
stepCost :: State -> Goal -> Distance
stepCost s goal from to =
let board = gameBoard $ stateGame s
in case fromJust $ tileAt board to of
FreeTile -> dangerLevelWithin 3 s from to
_ -> if isGoal goal s to then 1 else 999
|
flyrry/phonypony
|
src/StupidBot/Bot.hs
|
Haskell
|
mit
| 1,712
|
{-# LANGUAGE MonadComprehensions #-}
module Main where
import Data.Foldable (traverse_)
import Data.Maybe (fromMaybe, listToMaybe, maybe)
import System.Environment (getArgs)
fizzbuzz :: (Integral a, Show a) => a -> String
fizzbuzz i =
fromMaybe (show i)
$ [ "fizz" | i `rem` 3 == 0 ]
<> [ "buzz" | i `rem` 5 == 0 ]
<> [ "bazz" | i `rem` 7 == 0 ]
main :: IO ()
main = do
upTo <- fmap (maybe 100 read . listToMaybe) getArgs
traverse_ putStrLn [ fizzbuzz i | i <- [1 .. upTo] ]
|
genos/Programming
|
workbench/fizzbuzzMonadComprehensions.hs
|
Haskell
|
mit
| 511
|
{-# LANGUAGE ImplicitParams #-}
-- | Based on Cruise control system from
-- http://www.cds.caltech.edu/~murray/amwiki/index.php/Cruise_control
module CruiseControl where
import Zelus
data Gear = One | Two | Three | Four | Five deriving (Eq, Show)
run :: Double -- ^ Initial speed, m/s
-> S Double -- ^ Cruise control speed setting, m/s
-> S Double -- ^ Road slope (disturbance), rad
-> S Double -- ^ Resulting speed,m/s
run v0 ref road_slope =
let
(u_a, u_b) = controller (pre v_stable) ref
acc = vehicle (pre v_stable) u_a u_b road_slope
v = integ (acc `in1t` val v0)
v_stable = (v <? 0.005) ? (0,v)
in v_stable
where
?h = 0.01
vehicle :: S Double -- ^ Velocity, m/s
-> S Double -- ^ Accelerator ratio, [0, 1]
-> S Double -- ^ Decelerator ratio, [0, 1]
-> S Double -- ^ Road slope, rad
-> S Double -- ^ Resulting acceleration, m/s^2
vehicle v u_a u_b road_slope = acc
where
t_m = 400 -- engine torque constant, Nm
omega_m = 400 -- peak torque rate, rad/sec
beta = 0.4 -- torque coefficient
cr = 0.03 -- coefficient of rolling friction
rho = 1.29 -- density of air, kg/m^3
cd = 0.28 -- drag coefficient
a = 2.8 -- car area, m^2
g = 9.81 -- gravitational constant
m = 1700 -- vehicle mass, kg
t_m_b = 2800 -- maximum brake torque, Nm
wheel_radius = 0.381 -- m
gear_ratio One = 13.52
gear_ratio Two = 7.6
gear_ratio Three = 5.08
gear_ratio Four = 3.8
gear_ratio Five = 3.08
-- engine speed, rad/s
omega = (v * map gear_ratio gear) / (wheel_radius * pi) * 60 / 9.55
t_e = u_a * t_m * (1 - beta*(omega/omega_m - 1)^2) -- engine tourque
t_b = u_b * t_m_b -- brake tourque
-- friction
f_fric = ((t_e * map gear_ratio gear) - (t_b * signum v)) / wheel_radius
f_g = m * g * sin road_slope -- gravitation
f_r = m * g * cr * signum v -- rolling resistance
f_a = 0.5 * rho * cd * a * v^2 -- air drag
acc = (f_fric - f_g - f_r - f_a) / m
up_shift = 3000 / 9.55 -- rad/s
down_shift = 1000 / 9.55 -- rad/s
gear = automaton
[ One >-- omega >? up_shift --> Two
, Two >-- omega <? down_shift --> One
, Two >-- omega >? up_shift --> Three
, Three >-- omega <? down_shift --> Two
, Three >-- omega >? up_shift --> Four
, Four >-- omega <? down_shift --> Three
, Four >-- omega >? up_shift --> Five
, Five >-- omega <? down_shift --> Four
]
controller :: (?h :: Double) => S Double -> S Double -> (S Double, S Double)
controller v ref = (u_a, u_b)
where
kp = 0.8
ki = 0.04
kd = 0.0
err = ref - v
i_err = integ $ ((abs (pre pid) >? 1) ? (0, err)) `in1t` 0
d_err = deriv err
pid = kp*err + ki*i_err + kd*d_err
-- accelerate when positive and break when negative
u_a = pid >? 0 ? (mn pid 1, 0)
u_b = pid <? 0 ? (mn (-pid) 1, 0)
|
koengit/cyphy
|
src/CruiseControl.hs
|
Haskell
|
mit
| 2,996
|
{-# LANGUAGE OverloadedStrings #-}
module Network.API.Mandrill.SubaccountsSpec where
import Test.Hspec
import Test.Hspec.Expectations.Contrib
import Network.API.Mandrill.Types
import Network.API.Mandrill.Utils
import qualified Data.Text as Text
import qualified Network.API.Mandrill.Subaccounts as Subaccounts
import System.Environment
spec :: Spec
spec = do
test_list
test_add
test_info
test_update
test_delete
test_pause
test_resume
test_resume :: Spec
test_resume =
describe "/subaccounts/resume.json" $
it "should resume a paused subaccount" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $ do
_ <- Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50
Subaccounts.resume "acc-1"
resp `shouldSatisfy` isRight
test_pause :: Spec
test_pause =
describe "/subaccounts/pause.json" $
it "should pause a subaccount" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $ do
_ <- Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50
Subaccounts.pause "acc-1"
resp `shouldSatisfy` isRight
test_delete :: Spec
test_delete =
describe "/subaccounts/delete.json" $
it "should delete a subaccount" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $
Subaccounts.delete "acc-1"
resp `shouldSatisfy` isRight
test_update :: Spec
test_update =
describe "/subaccounts/update.json" $
it "update a subaccount" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $
Subaccounts.update "acc-1" "My Acc" "yes, indeed." 50
resp `shouldSatisfy` isRight
test_info :: Spec
test_info =
describe "/subaccounts/info.json" $
it "should return some info about a subaccount" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $ do
_ <- Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50
Subaccounts.info "acc-1"
resp `shouldSatisfy` isRight
test_add :: Spec
test_add =
describe "/subaccounts/add.json" $
it "should add a subaccount" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $
Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50
resp `shouldSatisfy` isRight
test_list :: Spec
test_list =
describe "/subaccounts/list.json" $
it "should list all subaccounts" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $
Subaccounts.list "acc-1"
resp `shouldSatisfy` isRight
|
krgn/hamdrill
|
test/Network/API/Mandrill/SubaccountsSpec.hs
|
Haskell
|
mit
| 2,692
|
{-# LANGUAGE ScopedTypeVariables #-}
{-|
Module : Labyrinth.Machine2d
Description : labyrinth state machine
Copyright : (c) deweyvm 2014
License : MIT
Maintainer : deweyvm
Stability : experimental
Portability : unknown
2d state machine automata generating functions.
-}
module Labyrinth.Machine2d(
(<.>),
occuCount,
negate,
vertStrip,
clearBorder
) where
import Prelude hiding(foldr, negate)
import Data.Maybe
import Data.Foldable
import Control.Applicative
import Labyrinth.Data.Array2d
import Labyrinth.Util
-- | Apply a list of endomorphisms to an initial value
(<.>) :: Foldable t => a -> t (a -> a) -> a
(<.>) = flip (foldr (.) id)
getOccupants :: Array2d a -> Point -> [a]
getOccupants arr (i, j) =
extract [ (i + x, j + y) | x <- [-1..1], y <- [-1..1] ]
where extract = catMaybes . map (geti arr)
countOccupants :: (a -> Bool) -> Array2d a -> Point -> Int
countOccupants f = (count f) .: (getOccupants)
-- | Maps to True iff the number of occupants of a given node is >= k.
occuCount :: Int -> Array2d Bool -> Array2d Bool
occuCount k arr = (\pt _ -> (countOccupants id arr pt) >= k) <$*> arr
-- | Negates the entire array.
negate :: Array2d Bool -> Array2d Bool
negate = (<$>) not
-- | Clears vertical strips with a regular spacing.
vertStrip :: Bool -> Int -> Array2d Bool -> Array2d Bool
vertStrip b mods =
(<$*>) (\(i, j) p -> select p b (modZero i || modZero j))
where modZero k = k `mod` mods == 0
-- | Clears a border around the edge of the array.
clearBorder :: Int -> Array2d Bool -> Array2d Bool
clearBorder thick arr@(Array2d cols rows _) =
(\(i, j) p -> i < thick || j < thick || i > cols - thick - 1 || j > rows - thick - 1 || p) <$*> arr
|
deweyvm/labyrinth
|
src/Labyrinth/Machine2d.hs
|
Haskell
|
mit
| 1,724
|
module Main where
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
main :: IO()
main = do
args <- getArgs
putStrLn (readExpr (args !! 0))
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=?>@^_~#"
readExpr :: String -> String
readExpr input = case parse (spaces >> symbol) "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"
spaces :: Parser ()
spaces = skipMany1 space
|
brianj-za/wyas
|
simpleparser1.hs
|
Haskell
|
mit
| 440
|
{-|
Module : Language.GoLite.Monad.Traverse
Description : Traversing annotated syntax trees with class
Copyright : (c) Jacob Errington and Frederic Lafrance, 2016
License : MIT
Maintainer : goto@mail.jerrington.me
Stability : experimental
Defines a type family based approach for traversing general annotated syntax
trees.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module Language.Common.Monad.Traverse (
module Control.Monad.Except
, module Control.Monad.Identity
, module Control.Monad.State
, MonadTraversal (..)
, Traversal (..)
) where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.State
-- | The class of monads that perform traversals of syntax trees.
class
( Monad m
, MonadState (TraversalState m) m
, MonadError (TraversalException m) m
) => MonadTraversal m where
-- | Fatal errors that can occur during the traversal.
type TraversalException m :: *
-- | Non-fatal errors that can occur during the traversal.
type TraversalError m :: *
-- | The state of the traversal.
type TraversalState m :: *
-- | Issues a non-fatal error, but continues the traversal.
--
-- The non-fatal errors are accumulated in the state.
reportError :: TraversalError m -> m ()
-- | Extracts the non-fatal errors from the traversal state.
getErrors :: TraversalState m -> [TraversalError m]
-- | Helper for common types of traversals.
newtype Traversal e s a
= Traversal
{ runTraversal
:: ExceptT e (
StateT s
Identity
) a
-- ^ Extract the transformer stack from the 'Traversal' wrapper.
}
deriving
( Functor
, Applicative
, Monad
, MonadError e
, MonadState s
)
|
djeik/goto
|
libgoto/Language/Common/Monad/Traverse.hs
|
Haskell
|
mit
| 1,882
|
{-
H-99 Problems
Copyright 2015 (c) Adrian Nwankwo (Arcaed0x)
Problem : 14
Description : Duplicate the elements of a list.
License : MIT (See LICENSE file)
-}
copyTwice :: [a] -> [a]
copyTwice [] = []
copyTwice (x:xs) = x : x : copyTwice xs
|
Arcaed0x/H-99-Solutions
|
src/prob14.hs
|
Haskell
|
mit
| 274
|
module Parser where
import Lambda
import Type
import Control.Monad
import Data.Char
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Language
import qualified Text.Parsec.Token as Token
lexer = Token.makeTokenParser style
where operators = ["+", "-", "*", "/", "==", ">=", "<=", "<", ">", "/=", ","]
words = ["if", "then", "else", "case", "of", "true", "false", "-|>", "let", "in"]
style = haskellStyle {Token.reservedOpNames = operators,
Token.reservedNames = words}
reservedWords = Token.reserved lexer
reservedOpera = Token.reservedOp lexer
identifiers = Token.identifier lexer
parens = Token.parens lexer
idNumbers = Token.natural lexer
wSpace x = do
Token.whiteSpace lexer
r <- x
eof
return r
expLambda = do
reservedOpera "\\"
lam <- many1 identifiers
reservedOpera "."
ex1 <- build
return $ foldr Lam ex1 lam
variable = do x <- identifiers
return (Var x)
variable2 = do x <- identifiers
return x
numbers = do n <- idNumbers
return (Lit (LInt (fromIntegral n)))
boolean = do
reservedWords "true"
return (Lit (LBool True))
<|> do reservedWords "false"
return (Lit (LBool False))
ifTE = do
reservedWords "if"
ex1 <- build
reservedWords "then"
ex2 <- build
reservedWords "else"
ex3 <- build
return (If ex1 ex2 ex3)
caOf = do
reservedWords "case"
ex1 <- build
reservedWords "of"
pats <- sepBy aPats $ reservedOpera ";"
return (Case ex1 pats)
aPats = do
pat1 <- patterns
reservedWords "-|>"
ex2 <- build
return (pat1, ex2)
<|> do pat2 <- patterns
reservedWords "-|>"
ex3 <- build
return (pat2, ex3)
patterns = do
xxx <- parens bPats
return xxx
<|> do x <- variable2
return (PVar x)
<|> do n <- idNumbers
return (PLit (LInt (fromIntegral n)))
<|> do reservedWords "true"
return (PLit (LBool True))
<|> do reservedWords "false"
return (PLit (LBool False))
bPats = do
x <- identifC
patx <- many patterns
return (PCon x patx)
identifC = do
a <- upper
id <- variable2
return $ (a:id)
operator = [[Postfix ((reservedOpera "+") >> return (App (Var "+")))],
[Postfix ((reservedOpera "-") >> return (App (Var "-")))],
[Postfix ((reservedOpera "*") >> return (App (Var "*")))],
[Postfix ((reservedOpera "/") >> return (App (Var "/")))],
[Postfix ((reservedOpera "<") >> return (App (Var "<")))],
[Postfix ((reservedOpera ">") >> return (App (Var ">")))],
[Postfix ((reservedOpera "==") >> return (App (Var "==")))],
[Postfix ((reservedOpera "=<") >> return (App (Var "=<")))],
[Postfix ((reservedOpera "=>") >> return (App (Var "=>")))],
[Postfix ((reservedOpera "/=") >> return (App (Var "/=")))],
[Infix (return ((App))) AssocNone]]
build = buildExpressionParser operator build2
build2 = parens build
<|> boolean
<|> ifTE
<|> variable
<|> numbers
<|> expLambda
<|> caOf
convert = destroy . parsing
parsing iN = parse (wSpace build) "error" iN
destroy (Right o) = o
destroy (Left o) = error "verify the syntax of the expression"
|
LeonardoRigon/TypeInfer-LambdaExpressions-in-Haskell
|
Parser.hs
|
Haskell
|
mit
| 4,099
|
module Nodes.Expression where
import Data.Tree (Tree (Node))
import Nodes
data Expr
= Op { operator :: String, left :: Expr, right :: Expr }
| StrLit { str :: String }
| IntLit { int :: Int }
| FloatLit { float :: Double }
instance AstNode Expr where
ast (Op operator left right) = Node operator [ast left, ast right]
ast (StrLit str) = Node ("\"" ++ str ++ "\"") []
ast (IntLit int) = Node (show int) []
ast (FloatLit float) = Node (show float) []
|
milankinen/cbhs
|
src/nodes/Expression.hs
|
Haskell
|
mit
| 507
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
import Application.Types
import Handler.Admin
import Handler.Block
import Handler.Room
import Handler.Snapshot
import Handler.Socket
import Handler.Instances
import Import
import Control.Concurrent.STM
import Control.Monad.Logger (runStderrLoggingT)
import Control.Monad.Trans.Resource (runResourceT)
import Data.Map
import Database.Persist.Postgresql
import Yesod.Static
mkYesodDispatch "App" resourcesApp
openConnectionCount :: Int
openConnectionCount = 10
connectionString :: ConnectionString
connectionString = "host=localhost port=5432 user=creek dbname=creek password=creek"
main :: IO ()
main = runStderrLoggingT $ withPostgresqlPool connectionString openConnectionCount $ \pool -> liftIO $ do
runResourceT $ flip runSqlPool pool $ runMigration migrateAll
state <- atomically $ newTVar myState
channel <- atomically newBroadcastTChan
socketStates' <- atomically $ newTVar $ singleton (InstanceId "0") (SocketState state channel)
s <- static "static"
--warpEnv requires $PORT to be set
warpEnv $ App pool socketStates' s
|
kRITZCREEK/FROST-Backend
|
src/Main.hs
|
Haskell
|
mit
| 1,248
|
module HaskovSpec where
import Haskov (fromList,imap,hmatrix,walk,walkFrom,steady,steadyState,statesI)
import System.Random
import Test.Hspec
import qualified Data.Set as Set
import qualified Numeric.LinearAlgebra.Data as Dat
import Data.List (intercalate)
import Control.Monad (unless,when)
testTransitions =
[ (("A", "B"), 0.3)
, (("A", "A"), 0.7)
, (("B", "C"), 1.0)
, (("C", "A"), 1.0)
]
spec :: Spec
spec =
describe "haskov" $ do
-- describe "steadyState" $ do
--
-- it "should always contain positive numbers" $ do
-- let
-- transitions = [ (("A", "B"), 1.0), (("B", "C"), 1.0), (("C", "A"), 1.0)]
-- haskov = fromList transitions
-- s = steadyState haskov
-- --mapM (\(s, p) -> s `shouldSatisfy` (> 0))
-- print s
-- True `shouldBe` True
describe "A haskov walk" $ do
-- could use quickcheck for better tests
it "should never do invalid transitions when transitions are ordered" $ do
let
transitions = [(("A", "B"), 1.0), (("B", "C"), 1.0), (("C", "A"), 1.0)]
valid = map fst transitions
markov = fromList transitions
gen <- getStdGen
res <- walk 10 markov gen
expectOnlyValidTransitions transitions res
it "should never do invalid transitions when transtions are not ordered" $ do
let
transitions = [ (("C", "A"), 1.0), (("A", "B"), 1.0), (("B", "C"), 1.0)]
valid = map fst transitions
haskov = fromList transitions
gen <- getStdGen
res <- walk 3 haskov gen
expectOnlyValidTransitions transitions res
describe "A haskov walkFrom" $ do
it "starts with the head initial state" $ do
let
markov = fromList testTransitions
gen <- getStdGen
res <- walkFrom "B" 10 markov gen
head res `shouldBe` "B"
it "just some test" $ do
let
markov = fromList testTransitions
index = imap markov
matrix = hmatrix markov
start = "A"
gen <- getStdGen
res <- walkFrom "B" 10 markov gen
--putStrLn $ "index: " ++ ( show index)
--putStrLn $ "matrix: " ++ ( show matrix)
--putStrLn $ "result from " ++ start ++ ": " ++ ( show res)
return ()
expectTrue :: HasCallStack => String -> Bool -> Expectation
expectTrue msg b = unless b (expectationFailure msg)
expectOnlyValidTransitions transitions actual = do
let
valid = map fst transitions
actualTransitions = zip actual (drop 1 actual)
actualUnique = Set.fromList actualTransitions
invalid = Set.filter (\e -> not $ elem e valid) actualUnique
len = length invalid
invalidMsg inv = "invalid transitions encountered: " ++ ( intercalate ", " (Set.toList (Set.map (\(a,b) -> a ++ "->" ++ b) inv)))
expectTrue (invalidMsg invalid) $ len == 0
|
mazuschlag/haskov
|
test/HaskovSpec.hs
|
Haskell
|
mit
| 2,899
|
-- The solution of exercise 1.12
-- The following pattern of numbers is called Pascal's triangle.
--
-- 1
-- 1 1
-- 1 2 1
-- 1 3 3 1
-- 1 4 6 4 1
--
-- The numbers at the edge of the triangle are all 1, and each number
-- inside the triangle is the sum of the two numbers above it. Write a
-- procedure that computes elements of Pascal's triangle by means of a
-- recursive process.
--
-- Run 'cabal install vector' first!
import qualified Data.Vector as V
-- Compute combinarotial number by means of a recursive process
recursive_pascal :: (Eq a, Integral a) => a -> a -> a
recursive_pascal m 0 = 1
recursive_pascal m n
| m < 0 ||
n < 0 ||
m < n = error "wrong number in pascal triangle."
| n == m = 1
| otherwise = recursive_pascal (m - 1) (n - 1) +
recursive_pascal (m - 1) n
-- The procedure computes factorial numbers by means of an iterative
-- process, with linear complexity.
fact_iter product counter maxc =
if counter > maxc
then product
else fact_iter (counter * product) (counter + 1) maxc
factorial n = fact_iter 1 1 n
--
-- We can use the mathematical definition of combinatorial numbers to
-- simply computes them:
--
-- m! factorial(m)
-- C(m, n) = ------------- = -------------------------------
-- n! (m - n)! factorial(n) * factorial(m - n)
--
-- m * (m - 1) * ... * (m - n + 1)
-- = ---------------------------------
-- factorial(n)
--
-- Thus we can write a new procedure in scheme and it is very simple.
-- Notice that:
--
-- fact_iter 1 a b = a * (a + 1) * ... * (b - 1) * b
--
-- We have: C(m, n) = fact-iter(1, m - n + 1, m) / fact-iter(1, 1, n)
-- This formula only does (2 * n - 1) times of multiplication / division.
--
-- Computes the combinatorial numbers
combinatorial :: (Eq a, Integral a) => a -> a -> a
combinatorial m n =
if (n * 2) > m
then (fact_iter 1 (n + 1) m) `div`
(fact_iter 1 1 (m - n))
else (fact_iter 1 (m - n + 1) m) `div`
(fact_iter 1 1 n)
--
-- There also exists another algorithm, according to the formula given by
-- the Pascal's triangle:
--
-- C(m, n) = C(m - 1, n - 1) + C(m - 1, n) (m, n >= 1)
--
-- We make a vector v with init value #(1, 0, 0, ... , 0) with length =
-- n + 1. and then make a new vector v':
--
-- v'(n) = v(n) + v(n - 1) (1 <= n <= count)
--
-- where the variable `count` means the number of non-zero elements in the
-- vector v. After this operation, we get v' = #(1, 1, 0, ... , 0) with
-- length = n + 1. Continue doing such an operation on v', we get v'' =
-- #(1, 2, 1, ... , 0) and v''' = #(1, 3, 3, 1, ... , 0). We can get all
-- the elements on m th row in Pascal's triangle, using this algorithm.
-- Besides, the algorithm behaves well on complexity analysis, for we only
-- do O(m ^ 2) times of addition to compute all numbers C(m, k).
--
-- Now we realize this algorithm in Haskell...
--
-- _ _____ _____ _____ _ _ _____ ___ ___ _ _
-- / \|_ _|_ _| ____| \ | |_ _|_ _/ _ \| \ | |
-- / _ \ | | | | | _| | \| | | | | | | | | \| |
-- / ___ \| | | | | |___| |\ | | | | | |_| | |\ |
-- /_/ \_\_| |_| |_____|_| \_| |_| |___\___/|_| \_|
--
-- The vector package is needed here! Run
--
-- cabal install vector
--
-- first and use Vector package.
--
-- This function computes the next line (vector) in Pascal's triangle.
-- For example, it returns [1,5,10,10,5,1] if the input is [1,4,6,4,1].
pascal_updateVec :: (Eq a, Integral a) => V.Vector a -> V.Vector a
pascal_updateVec vector =
V.zipWith (+) (V.snoc vector 0) (V.cons 0 vector)
-- This function computes the (n+1)-th line (vector) in Pascal's Triangle.
-- For example, it returns [1,5,10,10,5,1] if the input is 5.
pascalList :: (Eq a, Integral a) => a -> V.Vector a
pascalList n =
let nextVec vector 0 = vector
nextVec vector count =
nextVec (pascal_updateVec vector) (count - 1)
v0 = V.fromList [1 :: Integral a => a]
in nextVec v0 n
-- The pascal number
pascal n m = (pascalList n) V.! m
|
perryleo/sicp
|
ch1/sicpc1e12.hs
|
Haskell
|
mit
| 4,245
|
{-# LANGUAGE DeriveGeneric, StandaloneDeriving, DeriveDataTypeable, FlexibleInstances, Rank2Types, FlexibleContexts #-}
module Language.Erlang.Modules where
import Language.CoreErlang.Parser as P
import Language.CoreErlang.Pretty as PP
import Language.CoreErlang.Syntax as S
import qualified Data.Map as M
import qualified Data.List as L
import Data.Char as C
import Data.Either.Utils
import Control.Monad.RWS (gets, ask)
import Control.Monad.Error (throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State (
put,
get,
modify)
import Control.Concurrent.MVar (readMVar, modifyMVarMasked)
import Language.Erlang.Core
import Language.Erlang.Lang
getModTable :: ErlProcess ModTable
getModTable = do
Left mvar <- gets mod_table
liftIO $ readMVar mvar
ensureModule :: ModName -> ErlProcess ErlModule
ensureModule moduleName = do
Left m <- gets mod_table
emodule <- liftIO $ modifyMVarMasked m $ \mt ->
case M.lookup moduleName mt of
Just emodule ->
return (mt, emodule)
Nothing -> do
Right (emodule, modTable') <- liftIO $ loadEModule mt moduleName
return (modTable', emodule)
return emodule
safeGetModule :: ModName -> ErlPure ErlModule
safeGetModule moduleName = do
Right modTable <- gets mod_table
case M.lookup moduleName modTable of
Just emodule ->
return emodule
Nothing -> do
s <- ask
throwError (ErlException { exc_type = ExcUnknown,
reason = ErlAtom "module_not_found",
stack = s})
loadEModule :: ModTable -> String -> IO (Either String (ErlModule, ModTable))
loadEModule modTable moduleName = do
res <- loadEModule0 moduleName
case res of
Left er -> return $ Left er
Right m -> do
let m' = EModule moduleName m
let modTable' = M.insert moduleName m' modTable
return $ Right (m', modTable')
loadEModule0 :: String -> IO (Either String S.Module)
loadEModule0 moduleName = do
fileContent <- readFile ("samples/" ++ moduleName ++ ".core")
case P.parseModule fileContent of
Left er -> do
return $ Left $ show er
Right m -> do
-- putStrLn $ prettyPrint m
return $ Right (unann m)
|
gleber/erlhask
|
src/Language/Erlang/Modules.hs
|
Haskell
|
apache-2.0
| 2,233
|
module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "puzzles/0-easy/onboarding/solution.hs"
, "puzzles/0-easy/kirks-quest-the-descent/solution.hs"
, "puzzles/0-easy/ragnarok-power-of-thor/solution.hs"
, "puzzles/0-easy/skynet-the-chasm/solution.hs"
, "puzzles/0-easy/temperatures/solution.hs"
, "puzzles/0-easy/mars-lander/solution.hs"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
|
lpenz/codingame-haskell-solutions
|
hlint.hs
|
Haskell
|
apache-2.0
| 568
|
module Helpers.GridPolytopes (countPolygons, Polygon (..)) where
import Helpers.ListHelpers (cartesianProduct)
import Helpers.Subsets (choose)
import Data.List (genericTake, nub)
import Math.NumberTheory.Powers.Squares (exactSquareRoot)
import Data.Set (Set)
import qualified Data.Set as Set
data Polygon = Triangle | Square | Hexagon deriving Eq
type PVector = [Integer]
type VertexSet = Set PVector
magnitudeSquared :: [Integer] -> Integer
magnitudeSquared = sum . map (^2)
magSolutions :: Integer -> [[Integer]]
magSolutions n = magSolutionsList !! fromIntegral n
magSolutionsList = map magSolutions' [0..]
-- solutions to x^2 + y^2 + z^2 = n.
magSolutions' :: Integer -> [[Integer]]
magSolutions' = recurse 3 where
-- recurse :: Int -> Int -> [[Int]]
recurse 1 n = case exactSquareRoot n of (Just rootN) -> [[rootN]]
Nothing -> []
recurse k n = concatMap (\p -> map (p:) $ recurse (k-1) (n-p^2)) validParts where
validParts = takeWhile ((<=n) . (^2)) [0..]
-- This reverses; probably this can be fixed with a fold.
-- allSigns [0,1,2] = [[-2,-1,0],[2,-1,0],[-2,1,0],[2,1,0]]
-- allSigns :: [Int] -> [[Int]]
allSigns :: (Eq a, Num a) => [a] -> [[a]]
allSigns ns = recurse ns [[]] where
recurse [] known = known
recurse (0:ks) known = recurse ks $ map (0:) known
recurse (k:ks) known = recurse ks $ concatMap (\i -> [-k:i, k:i]) known
isValid :: Polygon -> PVector -> PVector -> Bool
isValid polygon v u = magnitudesMatch && correctAngle where
magnitudesMatch = magnitudeSquared u == magnitudeSquared v
dotProduct = sum $ zipWith (*) u v
correctAngle
| polygon == Triangle = 2 * dotProduct == magnitudeSquared v
| polygon == Square = dotProduct == 0
| polygon == Hexagon = -2 * dotProduct == magnitudeSquared v
adjacentSides :: Polygon -> Integer -> [[[Integer]]]
adjacentSides polygon = filter (\[v,u] -> isValid polygon v u) . choose 2 . concatMap allSigns . magSolutions
makeShape :: Polygon -> (PVector -> PVector -> Set PVector)
makeShape Triangle = makePolygon (\u v -> [[], [u], [v]])
makeShape Square = makePolygon (\u v -> [[], [u], [v], [u,v]])
makeShape Hexagon = makePolygon (\u v -> [[], [u], [v], [u,u,v], [u,v,v], [u,u,v,v]])
makePolygon :: (PVector -> PVector -> [[PVector]]) -> PVector -> PVector -> VertexSet
makePolygon vectorCombinations u v = Set.fromList $ map (\c -> zipWith (-) c maxCoords) coords where
maxCoords = foldr1 (zipWith min) coords
coords = map (foldr (zipWith (+)) [0,0,0]) $ vectorCombinations u v
boundingBox :: VertexSet -> [Integer]
boundingBox polygon = foldr1 (zipWith max) $ Set.toList polygon
-- Hexagons with side length k, all nonnegative coordinates, and touching the coordinate planes
normalized :: Polygon -> Integer -> [VertexSet]
normalized polygon k = nub $ map (\[v,u] -> makeShape polygon v u) $ adjacentSides polygon k
-- Bounding boxes for hexagons with side length sqrt(k)
boundingBoxes :: Polygon -> Integer -> [[Integer]]
boundingBoxes shape = map boundingBox . normalized shape
allBoundingBoxes :: Polygon -> [[[Integer]]]
allBoundingBoxes Square = allSquareBoundingBoxes
allBoundingBoxes Triangle = allTriangleBoundingBoxes
allBoundingBoxes Hexagon = allHexagonBoundingBoxes
allSquareBoundingBoxes :: [[[Integer]]]
allSquareBoundingBoxes = map (boundingBoxes Square) [1..]
allTriangleBoundingBoxes :: [[[Integer]]]
allTriangleBoundingBoxes = map (boundingBoxes Triangle) [1..]
allHexagonBoundingBoxes :: [[[Integer]]]
allHexagonBoundingBoxes = map (boundingBoxes Hexagon) [1..]
countPolygons :: Polygon -> Integer -> Integer
countPolygons polygon n = sum $ map countShifts validBoundingBoxes where
countShifts = product . map (`subtract` n)
validBoundingBoxes = filter ((<n) . maximum) $ concat $ genericTake upperBound (allBoundingBoxes polygon)
upperBound
| polygon == Triangle = 3 * n^2
| polygon == Square = 3 * n^2 -- improve this bound!
| polygon == Hexagon = (3 * n^2) `div` 4 + 1
|
peterokagey/haskellOEIS
|
src/Helpers/GridPolytopes.hs
|
Haskell
|
apache-2.0
| 3,988
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.ProjectStatus where
import GHC.Generics
import Data.Text
import qualified Data.Aeson
-- |
data ProjectStatus = ProjectStatus
{ phase :: Maybe Text -- ^ phase is the current lifecycle phase of the project
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON ProjectStatus
instance Data.Aeson.ToJSON ProjectStatus
|
minhdoboi/deprecated-openshift-haskell-api
|
openshift/lib/Openshift/V1/ProjectStatus.hs
|
Haskell
|
apache-2.0
| 521
|
<?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="ru-RU">
<title>Bug Tracker</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
secdec/zap-extensions
|
addOns/bugtracker/src/main/javahelp/org/zaproxy/zap/extension/bugtracker/resources/help_ru_RU/helpset_ru_RU.hs
|
Haskell
|
apache-2.0
| 956
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Controller
( withFoundation
) where
-- standard libraries
import Control.Monad
import Control.Concurrent.MVar
import System.Directory
import System.FilePath
-- friends
import Foundation
import Settings
import Yesod.Helpers.Static
-- Import all relevant handler modules here.
import Handler.Root
import Handler.Effects
import Handler.Images
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see
-- the comments there for more details.
mkYesodDispatch "Foundation" resourcesFoundation
-- Some default handlers that ship with the Yesod site template. You will
-- very rarely need to modify this.
getFaviconR :: Handler ()
getFaviconR = sendFile "image/x-icon" "favicon.ico"
getRobotsR :: Handler RepPlain
getRobotsR = return $ RepPlain $ toContent "User-agent: *"
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
withFoundation :: (Application -> IO a) -> IO a
withFoundation f = Settings.withConnectionPool $ \p -> do
lock <- newMVar ()
wrapper <- readFile "EffectWrapper.hs"
cache <- createCache
let static = fileLookupDir Settings.staticdir typeByExt
foundation = Foundation { getStatic = static
, connPool = p
, cudaLock = lock
, effectCodeWrapper = wrapper
, cacheDir = cache }
toWaiApp foundation >>= f
where
-- Temporary directory where images and code are stored
createCache = do
cache <- getAppUserDataDirectory "funky-foto-cache"
exists <- doesDirectoryExist cache
when exists (removeDirectoryRecursive cache)
createDirectory cache
createDirectory $ cache </> "images"
createDirectory $ cache </> "code"
return cache
|
sseefried/funky-foto
|
Controller.hs
|
Haskell
|
bsd-2-clause
| 2,165
|
module Cologne.ParseNFF (parseNFF) where
import Text.ParserCombinators.Parsec
import qualified Text.ParserCombinators.Parsec.Token as PT
import Text.ParserCombinators.Parsec.Language (emptyDef)
import Data.Vect
import Graphics.Formats.Assimp (Camera(Camera))
import Control.Arrow (left)
import Control.Applicative hiding ((<|>), many)
import Control.Monad (ap)
import Cologne.Primitives
import qualified Cologne.Primitives.Sphere as S
import Cologne.Accel.List
{- Parser for NFF (Neutral File Format). This is the first scene description
- language Cologne supports. The language is not very expressive. It's like
- training wheels, really.
-
- NOTE: We're using a modified version of nff, more suited to our ray tracer.
- We may decide to implement the exact spec in the future.
-
- TODO: Expressions would be very helpful
- Comments
-
- More info on NFF:
- http://tog.acm.org/resources/Sfloat/NFF.TXT
-}
{- Let's make an instance of Applicative for GenParser like they do in Real
- World Haskell:
- http://book.realworldhaskell.org/read/using-parsec.html
-}
-- instance Applicative (GenParser s a) where
-- pure = return
-- (<*>) = ap
type ColorInfo = (Vec3, Vec3, ReflectionType)
type ObjParser a = GenParser Char ColorInfo a
type ContextType = Context [Primitive ColorInfo] ColorInfo
{-
- Use some predefined helpers from parsec for ints and floats. The only
- interesting bit is that their float parser doesn't like negatives so we have
- to be a bit more careful there.
-}
lexer :: PT.TokenParser st
lexer = PT.makeTokenParser emptyDef
int = PT.integer lexer
uFloat = PT.float lexer
float' = try (negate <$ char '-' <*> uFloat)
<|> try uFloat
<|> fromIntegral <$> int
float = realToFrac <$> float'
{- light
- format l %g %g %g [%g %g %g]
- X Y Z R G B
-
- e.g. l 3 7 8 0.9 0.8 0.7
- l 3 7 8
-
- This represents a point light source, which we just represent as a tiny
- sphere with emission.
-
- First strip off the 'l' then build the light in an applicative manner. <$>
- just lifts light to the functor level then we apply it to the parsed
- doubles.
-}
light :: ObjParser (Primitive ColorInfo)
light =
char 'l' *> spaces *>
(light' <$> float <*> float <*> float <*> float <*> float <*> float)
<* spaces
where light' x y z r g b = S.sphere (Vec3 x y z)
0.0000001
((Vec3 0 0 0), (Vec3 r g b), Diffuse)
{- sphere
- format: s %g %g %g %g
- center.x center.y center.z radius
-
- A difficulty here is that this format doesn't include the color information
- with the primitives. They're supposed to take on whatever color most
- recently preceded them, thus we must keep the previous color as state.
-
- One potentially tricky thing here is that 'spaces' reads in the end-of-line
- characters of well. This is because it's defined using isSpace from
- Data.Char, which returns true on ' ', '\t', '\n', and '\r', and possibly
- others.
-}
sphere :: ObjParser (Primitive ColorInfo)
sphere =
char 's' *> spaces *>
(sph <$> float <*> float <*> float <*> float <*> getState)
<* spaces
where sph x y z r c = S.sphere (Vec3 x y z) r c
{- color
- format f %g %g %g %g %g %g %s
- R G B R G B spec|diff|refr
-
- All of the floats should be between 0 and 1. The first triple represents the
- color and the second represents the color of the emitted light, if any.
-
- I'm sticking to this format for now, since the way it's defined in the nff
- spec doesn't suit us very well.
-}
color :: ObjParser ()
color = do
info <- (char 'f' *> spaces *>
(clr <$> float <*> float <*> float <*> float <*> float <*> float <*> reflT)
<* spaces)
setState info
where clr r1 g1 b1 r2 g2 b2 r = (Vec3 r1 g1 b1, Vec3 r2 g2 b2, r)
reflT = spaces *> (Refractive <$ string "refr"
<|> Specular <$ string "spec"
<|> Diffuse <$ string "diff"
<?> "reflection type")
background :: ObjParser Vec3
background = char 'b' *> (Vec3 <$> float <*> float <*> float) <* spaces
--background = char 'b' *> (Vec3 <$> count 3 float)
--background = char 'b' *> (Vec3 <$> (chainr1 float (<*>)))
--nToken 1 comb1 comb2 = comb1 <$> comb2
--nToken n comb1 comb2 = (nToken (n-1) comb1 comb2) <*> comb2
{- viewpoint
-
- Where the camera is located and where it points. We expect
- it at the beginning of the file.
-}
viewpoint :: ObjParser (Vec3, Vec3)
viewpoint = do
char 'v' >> spaces
from <- string "from " *> (Vec3 <$> float <*> float <*> float) <* spaces
at <- string "at " *> (Vec3 <$> float <*> float <*> float) <* spaces
return (from, normalize at)
-- If we were complying fully to the nff spec we would implement these but we
-- have no need for them yet
-- up <- string "up " *> (Vec3 <$> float <*> float <*> float) <* spaces
-- angle <- string "angle " *> float <* spaces
-- hither <- string "hither " *> float
-- return (from, at, up, angle, hither)
file :: ObjParser ContextType
file = do
(at, look) <- viewpoint
objs <- many $ (skipMany color) *> objects
eof
let camera = Camera "" at (Vec3 0 0 1) look 60 1 1000000000 1
pos <- getPosition
return $ Context defaultOptions [camera] objs
where objects = sphere <|> light
parseNFF :: String -> String ->
Either String ContextType
parseNFF input filename = (flip left) (runParser file noState filename input) show
where noState = ((Vec3 0 0 0), (Vec3 0 0 0), (Diffuse))
|
joelburget/Cologne
|
Cologne/ParseNFF.hs
|
Haskell
|
bsd-3-clause
| 5,595
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.TextureExpandNormal
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/NV/texture_expand_normal.txt NV_texture_expand_normal> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.TextureExpandNormal (
-- * Enums
gl_TEXTURE_UNSIGNED_REMAP_MODE_NV
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/NV/TextureExpandNormal.hs
|
Haskell
|
bsd-3-clause
| 688
|
--------------------------------------------------------------------------------
-- Chip16 Assembler written in Haskell
--------------------------------------------------------------------------------
module HC.Ops where
import Data.Bits
import Data.Int
import Data.List
import Data.Maybe
import Data.Word
import Control.Applicative
data Parameter
= Bit Int
| Imm4 Int
| Imm8 Int
| Imm16
| RegX
| RegY
| RegZ
| SP
deriving (Eq, Show)
type Op
= ( String, Int, [ Parameter ] )
jump :: [ ( String, Int ) ]
jump
= [ ( "z", 0x0 )
, ( "mz", 0x0 )
, ( "nz", 0x1 )
, ( "n", 0x2 )
, ( "nn", 0x3 )
, ( "p", 0x4 )
, ( "o", 0x5 )
, ( "no", 0x6 )
, ( "a", 0x7 )
, ( "ae", 0x8 )
, ( "nc", 0x8 )
, ( "b", 0x9 )
, ( "c", 0x9 )
, ( "mc", 0x9 )
, ( "be", 0xA )
, ( "g", 0xB )
, ( "ge", 0xC )
, ( "l", 0xD )
, ( "le", 0xE )
, ( "f", 0xF ) -- Reserved
]
operators :: [ Op ]
operators
= [ ( "nop", 0x00, [ ] )
, ( "cls", 0x01, [ ] )
, ( "vblnk", 0x02, [ ] )
, ( "bgc", 0x03, [ Imm4 4 ] )
, ( "spr", 0x04, [ Imm16 ] )
, ( "drw", 0x05, [ RegX, RegY, Imm16 ] )
, ( "drw", 0x06, [ RegX, RegY, RegZ ] )
, ( "rnd", 0x07, [ RegX, Imm16 ] )
, ( "flip", 0x08, [ Bit 25, Bit 24] )
, ( "snd0", 0x09, [ ] )
, ( "snd1", 0x0A, [ Imm16 ] )
, ( "snd2", 0x0B, [ Imm16 ] )
, ( "snd3", 0x0C, [ Imm16 ] )
, ( "snp", 0x0D, [ RegX, Imm16 ] )
, ( "sng", 0x0E, [ Imm8 1, Imm16 ] )
, ( "jmp", 0x10, [ Imm16 ] )
, ( "", 0x12, [ Imm16 ] ) -- special
, ( "jme", 0x13, [ RegX, RegY, Imm16 ] )
, ( "call", 0x14, [ Imm16 ] )
, ( "ret", 0x15, [ ] )
, ( "jmp", 0x16, [ RegX ] )
, ( "", 0x17, [ Imm16 ] ) -- special
, ( "call", 0x18, [ Imm16 ] )
, ( "ldi", 0x20, [ RegX, Imm16 ] )
, ( "ldi", 0x21, [ SP, Imm16 ] )
, ( "ldm", 0x22, [ RegX, Imm16] )
, ( "ldm", 0x23, [ RegX, RegY ] )
, ( "mov", 0x24, [ RegX, RegY ] )
, ( "stm", 0x30, [ RegX, Imm16 ] )
, ( "stm", 0x31, [ RegX, RegY ] )
, ( "addi", 0x40, [ RegX, Imm16 ] )
, ( "add", 0x41, [ RegX, RegY ] )
, ( "add", 0x42, [ RegX, RegY, RegZ ] )
, ( "subi", 0x50, [ RegX, Imm16 ] )
, ( "sub", 0x51, [ RegX, RegY ] )
, ( "sub", 0x52, [ RegX, RegY, RegZ ] )
, ( "cmpi", 0x53, [ RegX, Imm16 ] )
, ( "cmp", 0x54, [ RegX, RegY ] )
, ( "andi", 0x60, [ RegX, Imm16 ] )
, ( "and", 0x61, [ RegX, RegY ] )
, ( "and", 0x62, [ RegX, RegY, RegZ ] )
, ( "tsti", 0x63, [ RegX, Imm16 ] )
, ( "tst", 0x64, [ RegX, RegY ] )
, ( "ori", 0x70, [ RegX, Imm16] )
, ( "or", 0x71, [ RegX, RegY ] )
, ( "or", 0x72, [ RegX, RegY, RegZ ] )
, ( "xori", 0x80, [ RegX, Imm16 ] )
, ( "xor", 0x81, [ RegX, RegY ] )
, ( "xor", 0x82, [ RegX, RegY, RegZ ] )
, ( "muli", 0x90, [ RegX, Imm16 ] )
, ( "mul", 0x91, [ RegX, RegY ] )
, ( "mul", 0x92, [ RegX, RegY, RegZ ] )
, ( "divi", 0xA0, [ RegX, Imm16 ] )
, ( "div", 0xA1, [ RegX, RegY] )
, ( "div", 0xA2, [ RegX, RegY, RegZ ] )
, ( "shl", 0xB0, [ RegX, Imm4 4 ] )
, ( "shr", 0xB1, [ RegX, Imm4 4 ] )
, ( "sar", 0xB2, [ RegX, Imm4 4 ] )
, ( "shl", 0xB3, [ RegX, RegY ] )
, ( "shr", 0xB4, [ RegX, RegY ] )
, ( "sar", 0xB5, [ RegX, RegY ] )
, ( "push", 0xC0, [ RegX ] )
, ( "pop", 0xC1, [ RegX ] )
, ( "pushall", 0xC2, [ ] )
, ( "popall", 0xC3, [ ] )
, ( "pushf", 0xC4, [ ] )
, ( "popf", 0xC5, [ ] )
, ( "pal", 0xD0, [ Imm16 ] )
, ( "pal", 0xD1, [ RegX ] )
]
getOperatorByName :: String -> [ Op ]
getOperatorByName name
= filter (\( name', _, _ ) -> name == name') operators
getOperatorByCode :: Int -> Maybe Op
getOperatorByCode n
= find (\( _, n', _ ) -> n == n' ) operators
getJumpByCode :: Int -> String
getJumpByCode n
= fst . fromJust $ find (\( j, n' ) -> n' == n ) jump
getJumpByName :: String -> Maybe Int
getJumpByName j
= snd <$> find (\( j', n ) -> j' == j ) jump
|
nandor/hcasm
|
HC/Ops.hs
|
Haskell
|
bsd-3-clause
| 4,323
|
module Main where
import qualified Language.Modelica.Test.Lexer as Lexer
import qualified Language.Modelica.Test.Expression as Expr
import qualified Language.Modelica.Test.Modification as Mod
import qualified Language.Modelica.Test.Basic as Basic
import qualified Language.Modelica.Test.ClassDefinition as ClassDef
import qualified Language.Modelica.Test.Equation as Equation
import qualified Language.Modelica.Test.ComponentClause as CompClause
import qualified Language.Modelica.Test.Programme as Prog
import qualified Language.Modelica.Test.Utility as Utility
import Control.Monad (when)
main :: IO ()
main = do
Utility.banner "Lexer"
as <- Lexer.test
Utility.banner "Basic"
bs <- Basic.test
Utility.banner "Expression"
cs <- Expr.test
Utility.banner "Modification"
ds <- Mod.test
Utility.banner "Equation"
es <- Equation.test
Utility.banner "Component Clause"
fs <- CompClause.test
Utility.banner "Class Definition"
gs <- ClassDef.test
Utility.banner "Comment"
hs <- Prog.test
Utility.banner "QuickCheck tests"
i <- Prog.runTests
let tests = as ++ bs ++ cs ++ ds ++ es ++ fs ++ gs ++ hs ++ [i]
testsLen = length tests
passedLen = length $ filter (== True) tests
Utility.banner "Final Result"
putStrLn $ "Have we successfully passed all " ++ (show testsLen) ++ " tests? "
when (testsLen /= passedLen)
(putStrLn $ "Passed only " ++ show passedLen ++ " tests!")
Utility.printBoolOrExit (and tests)
putStrLn ""
|
xie-dongping/modelicaparser
|
test/Main.hs
|
Haskell
|
bsd-3-clause
| 1,500
|
-------------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Trans.Supply
-- Copyright : (C) 2013 Merijn Verstraaten
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Merijn Verstraaten <merijn@inconsistent.nl>
-- Stability : experimental
-- Portability : non-portable
--
-- [Computation type:] Computations that require a supply of values.
--
-- [Binding strategy:] Applicative values are functions that consume an input
-- from a supply to produce a value.
--
-- [Useful for:] Providing a supply of unique names or other values to
-- computations needing them.
--
-- [Zero and plus:] Identical to the underlying implementations (if any) of
-- 'empty', '<|>', 'mzero' and 'mplus'.
--
-- The @'Supply' s a@ monad represents a computation that consumes a supply of
-- @s@'s to produce a value of type @a@. One example use is to simplify
-- computations that require the generation of unique names. The 'Supply' monad
-- can be used to provide a stream of unique names to such a computation.
-------------------------------------------------------------------------------
module Control.Monad.Supply (
-- * The MonadSupply Class
MonadSupply (..)
, demand
-- * The Supply Monad
, Supply
, withSupply
, runSupply
, runListSupply
, runMonadSupply
-- * The Supply Monad Transformer
, SupplyT
, withSupplyT
, runSupplyT
, runListSupplyT
, runMonadSupplyT
, module Control.Monad
, module Control.Monad.Trans
) where
import Control.Monad.Supply.Class
import Control.Monad.Trans.Supply
( Supply
, SupplyT
, withSupply
, withSupplyT
, runSupply
, runSupplyT
, runListSupply
, runListSupplyT
, runMonadSupply
, runMonadSupplyT
)
import Control.Monad
import Control.Monad.Trans
|
merijn/transformers-supply
|
Control/Monad/Supply.hs
|
Haskell
|
bsd-3-clause
| 1,868
|
module Text.Velocity
(
defaultVelocityState
, Vstate(..)
, render
, pretty_ast
-- * Parsing
, parseVelocityM
, parseVelocity
, parseVelocityFile
)
where
import Control.Applicative hiding ((<|>), many)
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class
import Data.Maybe
import Control.Monad.State
import qualified Control.Monad.State.Class as State
import Text.Velocity.Context
import Text.Velocity.Parse
import Text.Velocity.Types
data Vstate
= Vstate
{
vs_template_root :: FilePath
, vs_stack :: Stack Context
}
vs_add_macro :: Macbind -> Vstate -> Vstate
vs_add_macro binding state_
= state_
{
vs_stack = stack_map_top (addMacro binding) (vs_stack state_)
}
stack_map_top :: (a -> a) -> Stack a -> Stack a
stack_map_top f stack =
case stack of
[] -> []
x : xs -> f x : xs
defaultVelocityState :: Vstate
defaultVelocityState = Vstate "/home/john/sender/templates/" []
v_get_var :: (Functor m, Monad m) => String -> StateT Vstate m (Maybe VarBind)
v_get_var name = State.gets $
vs_stack >>> concatMap co_vars >>> filter (varName >>> (name ==)) >>> listToMaybe
v_get_macro :: (Functor m, Monad m) => String -> StateT Vstate m (Maybe Macbind)
v_get_macro name = State.gets $
vs_stack >>> concatMap co_macs >>> filter (macroName >>> (name ==)) >>> listToMaybe
render :: [Node] -> StateT Vstate IO String
render = phase1 >=> phase_2
pretty_ast :: [Node] -> String
pretty_ast nodes =
case nodes of
[] -> ""
node : tail_ -> pretty 0 node ++ pretty_ast tail_
where
pretty level node =
let
level' = succ level
indent = replicate (4 * level) ' '
in
indent ++ case node of
Fragment nodes_ -> "Fragment\n" ++ concatMap (pretty level') nodes_
Call name args -> "Call " ++ name ++ "\n" ++ concatMap (pretty level') args
-- MacroDef name args body -> "MacroDef " ++ name ++ " " ++ show args ++ "\n" ++ concatMap (pretty level') body
_ -> show node ++ "\n"
-- | You can use a macro before its definition.
phase1 :: [Node] -> StateT Vstate IO [Node]
phase1 nodes =
case nodes of
[] -> return []
node : tail_ -> do
replacements <- case node of
BlockComment _ -> return []
LineComment _ -> return []
MacroDef name args body -> do
State.modify $ vs_add_macro (Macbind name args body)
return []
_ -> return [node]
(replacements ++) <$> phase1 tail_
with_context :: Context -> StateT Vstate IO a -> StateT Vstate IO a
with_context context =
withStateT (\ s -> s { vs_stack = context : vs_stack s })
-- | True if @bind@ does not occur in @macparams@.
free_var :: VarBind -> [Node] -> Bool
free_var bind macparams =
not $ elem
(varName bind)
(flip mapMaybe macparams $ \ node ->
case node of
Var name -> Just name
_ -> Nothing)
-- | This is supposed to be similar to lambda calculus beta-reduction.
replace_var :: VarBind -> [Node] -> [Node]
replace_var bind@(VarBind name content) nodes =
flip concatMap nodes $ \ node ->
case node of
Fragment nodes_ -> [Fragment (replace_var bind nodes_)]
-- Var name2 | name == name2 -> [content]
-- QuietVar name2 | name == name2 -> [content]
defn@(MacroDef mname mparams mbody) ->
if free_var bind (map (Var . maName) mparams)
-- then [MacroDef mname mparams (replace_var bind mbody)]
then undefined -- FIXME
else [defn]
Call name_ args -> [Call name_ (replace_var bind args)]
_ -> [node]
-- what to do when undefined variable?
-- * print '$var' literally
-- * throw an error
invoke :: Node -> StateT Vstate IO String
invoke (Call name argvals) = do
m_macbind <- v_get_macro name
case m_macbind of
Nothing ->
error $ "undefined macro: #" ++ name
Just macbind@(Macbind _ macargs mbody) -> do
unless (length macargs == length argvals) $ do
error $ "macro formal and actual argument count must match:\nformal: " ++ show macbind ++ "\nactual: " ++ show argvals
-- let assignment = zipWith (\ (Var m) a -> VarBind m a) (map (Var . maName) macargs) argvals
-- let mbody' = foldr (\ a b -> replace_var a b) mbody assignment
let mbody' = undefined -- FIXME
render mbody'
{-
with_context
(Context
(zipWith
(\ formal actual ->
case formal of
Var name -> VarBind name actual
_ -> error $ "macro formal argument must be variable reference; got " ++ show formal
)
macargs
argvals)
[])
(render mbody)
-}
-- | Render the parsed template into string.
phase_2 :: [Node] -> StateT Vstate IO String
phase_2 nodes_ =
action 0 nodes_
where
depth_limit = 8
action :: Integer -> [Node] -> StateT Vstate IO String
action depth nodes =
let
descend = action (succ depth)
in do
case nodes of
node : tail_ -> do
when (depth > depth_limit) $ do
error $ "possible cycle: phase_2 depth reached " ++ show depth ++ " while evaluating " ++ show node
-- liftIO $ putStrLn $ show node
result <- case node of
Literal s -> return s
Fragment nodes__ -> descend nodes__
-- Var name -> v_get_var name >>= maybe (error $ "undefined variable: $" ++ name) (descend . (: []) . varContent)
-- QuietVar name -> v_get_var name >>= maybe (return "") (descend . (: []) . varContent)
Zacall name -> do
m_macbind <- v_get_macro $ nameToString name
case m_macbind of
Nothing -> do
liftIO . putStrLn $ "warning: silently converting #" ++ nameToString name ++ " to literal"
return ('#' : nameToString name)
Just _ -> invoke (Call (nameToString name) [])
call@(Call _ _) -> invoke call
_ -> error $ "phase_2 not implemented: " ++ show node
(result ++) <$> render tail_
_ -> return ""
|
edom/velocity
|
Text/Velocity.hs
|
Haskell
|
bsd-3-clause
| 7,030
|
{-# LANGUAGE ScopedTypeVariables, FlexibleContexts, TypeFamilies,
TypeSynonymInstances, FlexibleInstances, GADTs, RankNTypes,
UndecidableInstances #-}
-- | The 'Enabled' module allows the construction of circuits that use
-- additional control logic -- an enable signal -- that externalizes whether a
-- data signal is valid.
module Language.KansasLava.Protocols.Enabled
(Enabled,
packEnabled, unpackEnabled,
enabledVal, isEnabled,
mapEnabled,
enabledS, disabledS,
) where
import Language.KansasLava.Signal
import Language.KansasLava.Rep
-- | Enabled is a synonym for Maybe.
type Enabled a = Maybe a
-- | This is lifting *Comb* because Comb is stateless, and the 'en' Bool being
-- passed on assumes no history, in the 'a -> b' function.
mapEnabled :: (Rep a, Rep b, sig ~ Signal clk)
=> (forall clk' . Signal clk' a -> Signal clk' b)
-> sig (Enabled a) -> sig (Enabled b)
mapEnabled f en = pack (en_bool,f en_val)
where (en_bool,en_val) = unpack en
-- | Lift a data signal to be an Enabled signal, that's always enabled.
enabledS :: (Rep a, sig ~ Signal clk) => sig a -> sig (Enabled a)
enabledS s = pack (pureS True,s)
-- | Create a signal that's never enabled.
disabledS :: (Rep a, sig ~ Signal clk) => sig (Enabled a)
disabledS = pack (pureS False,undefinedS)
-- | Combine a boolean control signal and an data signal into an enabled signal.
packEnabled :: (Rep a, sig ~ Signal clk) => sig Bool -> sig a -> sig (Enabled a)
packEnabled s1 s2 = pack (s1,s2)
-- | Break the representation of an Enabled signal into a Bool signal (for whether the
-- value is valid) and a signal for the data.
unpackEnabled :: (Rep a, sig ~ Signal clk) => sig (Enabled a) -> (sig Bool, sig a)
unpackEnabled = unpack
-- | Drop the Enabled control from the signal. The output signal will be Rep
-- unknown if the input signal is not enabled.
enabledVal :: (Rep a, sig ~ Signal clk) => sig (Enabled a) -> sig a
enabledVal = snd . unpackEnabled
-- | Determine if the the circuit is enabled.
isEnabled :: (Rep a, sig ~ Signal clk) => sig (Enabled a) -> sig Bool
isEnabled = fst . unpackEnabled
|
andygill/kansas-lava
|
Language/KansasLava/Protocols/Enabled.hs
|
Haskell
|
bsd-3-clause
| 2,134
|
module AssetsHelper where
import Assets
import Utils.Utils
import TypeSystem.Parser.TypeSystemParser
import TypeSystem
import Data.List
import qualified Data.Map as M
import Control.Arrow ((&&&))
import SyntaxHighlighting.Coloring
stfl = parseTypeSystem Assets._Test_STFL_language (Just "Assets/STFL.language") & either (error . show) id
stflSyntax = get tsSyntax stfl
optionsSyntax = parseTypeSystem Assets._Manual_Options_language (Just "Assets/Manual/Options.Language")
& either (error . show) id
& get tsSyntax
terminalStyle = Assets._Terminal_style
& parseColoringFile "Assets/Terminal.style"
& either error id
knownStyles :: M.Map Name FullColoring
knownStyles = Assets.allAssets & filter ((".style" `isSuffixOf`) . fst)
|> (fst &&& (\(fp, style) -> parseColoringFile ("Assets: "++fp) style & either error id))
& M.fromList
fetchStyle name
= let errMsg = "No builtin style with name "++name ++ "\nBuiltin styles are:\n"
++ (knownStyles & M.keys & unlines & indent)
in
checkExists (name++".style") knownStyles errMsg
minimalStyleTypes
= Assets._MinimalStyles_txt & validLines
|
pietervdvn/ALGT
|
src/AssetsHelper.hs
|
Haskell
|
bsd-3-clause
| 1,127
|
{-# LANGUAGE CPP
, GADTs
, Rank2Types
, DataKinds
, TypeFamilies
, FlexibleContexts
, UndecidableInstances
, LambdaCase
, MultiParamTypeClasses
, OverloadedStrings
#-}
{-# OPTIONS_GHC -Wall -fwarn-tabs -fsimpl-tick-factor=1000 #-}
module Language.Hakaru.Runtime.LogFloatPrelude where
#if __GLASGOW_HASKELL__ < 710
import Data.Functor ((<$>))
import Control.Applicative (Applicative(..))
#endif
import Data.Foldable as F
import qualified System.Random.MWC as MWC
import qualified System.Random.MWC.Distributions as MWCD
import Data.Number.Natural
import Data.Number.LogFloat hiding (sum, product)
import qualified Data.Number.LogFloat as LF
import Data.STRef
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import Control.Monad
import Control.Monad.ST
import Prelude hiding (init, sum, product, exp, log, (**), pi)
import qualified Prelude as P
type family MinBoxVec (v1 :: * -> *) (v2 :: * -> *) :: * -> *
type instance MinBoxVec V.Vector v = V.Vector
type instance MinBoxVec v V.Vector = V.Vector
type instance MinBoxVec U.Vector U.Vector = U.Vector
type family MayBoxVec a :: * -> *
type instance MayBoxVec () = U.Vector
type instance MayBoxVec Int = U.Vector
type instance MayBoxVec Double = U.Vector
type instance MayBoxVec LogFloat = U.Vector
type instance MayBoxVec Bool = U.Vector
type instance MayBoxVec (U.Vector a) = V.Vector
type instance MayBoxVec (V.Vector a) = V.Vector
type instance MayBoxVec (a,b) = MinBoxVec (MayBoxVec a) (MayBoxVec b)
newtype instance U.MVector s LogFloat = MV_LogFloat (U.MVector s Double)
newtype instance U.Vector LogFloat = V_LogFloat (U.Vector Double)
instance U.Unbox LogFloat
instance M.MVector U.MVector LogFloat where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
#if __GLASGOW_HASKELL__ > 710
{-# INLINE basicInitialize #-}
#endif
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_LogFloat v) = M.basicLength v
basicUnsafeSlice i n (MV_LogFloat v) = MV_LogFloat $ M.basicUnsafeSlice i n v
basicOverlaps (MV_LogFloat v1) (MV_LogFloat v2) = M.basicOverlaps v1 v2
basicUnsafeNew n = MV_LogFloat `liftM` M.basicUnsafeNew n
#if __GLASGOW_HASKELL__ > 710
basicInitialize (MV_LogFloat v) = M.basicInitialize v
#endif
basicUnsafeReplicate n x = MV_LogFloat `liftM` M.basicUnsafeReplicate n (logFromLogFloat x)
basicUnsafeRead (MV_LogFloat v) i = logToLogFloat `liftM` M.basicUnsafeRead v i
basicUnsafeWrite (MV_LogFloat v) i x = M.basicUnsafeWrite v i (logFromLogFloat x)
basicClear (MV_LogFloat v) = M.basicClear v
basicSet (MV_LogFloat v) x = M.basicSet v (logFromLogFloat x)
basicUnsafeCopy (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeCopy v1 v2
basicUnsafeMove (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeMove v1 v2
basicUnsafeGrow (MV_LogFloat v) n = MV_LogFloat `liftM` M.basicUnsafeGrow v n
instance G.Vector U.Vector LogFloat where
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicUnsafeFreeze (MV_LogFloat v) = V_LogFloat `liftM` G.basicUnsafeFreeze v
basicUnsafeThaw (V_LogFloat v) = MV_LogFloat `liftM` G.basicUnsafeThaw v
basicLength (V_LogFloat v) = G.basicLength v
basicUnsafeSlice i n (V_LogFloat v) = V_LogFloat $ G.basicUnsafeSlice i n v
basicUnsafeIndexM (V_LogFloat v) i
= logToLogFloat `liftM` G.basicUnsafeIndexM v i
basicUnsafeCopy (MV_LogFloat mv) (V_LogFloat v)
= G.basicUnsafeCopy mv v
elemseq _ x z = G.elemseq (undefined :: U.Vector a) (logFromLogFloat x) z
lam :: (a -> b) -> a -> b
lam = id
{-# INLINE lam #-}
app :: (a -> b) -> a -> b
app f x = f x
{-# INLINE app #-}
let_ :: a -> (a -> b) -> b
let_ x f = let x1 = x in f x1
{-# INLINE let_ #-}
ann_ :: a -> b -> b
ann_ _ a = a
{-# INLINE ann_ #-}
exp :: Double -> LogFloat
exp = logToLogFloat
{-# INLINE exp #-}
log :: LogFloat -> Double
log = logFromLogFloat
{-# INLINE log #-}
newtype Measure a = Measure { unMeasure :: MWC.GenIO -> IO (Maybe a) }
instance Functor Measure where
fmap = liftM
{-# INLINE fmap #-}
instance Applicative Measure where
pure x = Measure $ \_ -> return (Just x)
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance Monad Measure where
return = pure
{-# INLINE return #-}
m >>= f = Measure $ \g -> do
Just x <- unMeasure m g
unMeasure (f x) g
{-# INLINE (>>=) #-}
makeMeasure :: (MWC.GenIO -> IO a) -> Measure a
makeMeasure f = Measure $ \g -> Just <$> f g
{-# INLINE makeMeasure #-}
uniform :: Double -> Double -> Measure Double
uniform lo hi = makeMeasure $ MWC.uniformR (lo, hi)
{-# INLINE uniform #-}
normal :: Double -> LogFloat -> Measure Double
normal mu sd = makeMeasure $ MWCD.normal mu (fromLogFloat sd)
{-# INLINE normal #-}
beta :: LogFloat -> LogFloat -> Measure LogFloat
beta a b = makeMeasure $ \g ->
logFloat <$> MWCD.beta (fromLogFloat a) (fromLogFloat b) g
{-# INLINE beta #-}
gamma :: LogFloat -> LogFloat -> Measure LogFloat
gamma a b = makeMeasure $ \g ->
logFloat <$> MWCD.gamma (fromLogFloat a) (fromLogFloat b) g
{-# INLINE gamma #-}
categorical :: MayBoxVec LogFloat LogFloat -> Measure Int
categorical a = makeMeasure $ \g ->
fromIntegral <$> MWCD.categorical (U.map prep a) g
where prep p = fromLogFloat (p / m)
m = G.maximum a
{-# INLINE categorical #-}
plate :: (G.Vector (MayBoxVec a) a) =>
Int -> (Int -> Measure a) -> Measure (MayBoxVec a a)
plate n f = G.generateM (fromIntegral n) $ \x ->
f (fromIntegral x)
{-# INLINE plate #-}
bucket :: Int -> Int -> (forall s. Reducer () s a) -> a
bucket b e r = runST
$ case r of Reducer{init=initR,accum=accumR,done=doneR} -> do
s' <- initR ()
F.mapM_ (\i -> accumR () i s') [b .. e - 1]
doneR s'
{-# INLINE bucket #-}
data Reducer xs s a =
forall cell.
Reducer { init :: xs -> ST s cell
, accum :: xs -> Int -> cell -> ST s ()
, done :: cell -> ST s a
}
r_fanout :: Reducer xs s a
-> Reducer xs s b
-> Reducer xs s (a,b)
r_fanout Reducer{init=initA,accum=accumA,done=doneA}
Reducer{init=initB,accum=accumB,done=doneB} = Reducer
{ init = \xs -> liftM2 (,) (initA xs) (initB xs)
, accum = \bs i (s1, s2) ->
accumA bs i s1 >> accumB bs i s2
, done = \(s1, s2) -> liftM2 (,) (doneA s1) (doneB s2)
}
{-# INLINE r_fanout #-}
r_index :: (G.Vector (MayBoxVec a) a)
=> (xs -> Int)
-> ((Int, xs) -> Int)
-> Reducer (Int, xs) s a
-> Reducer xs s (MayBoxVec a a)
r_index n f Reducer{init=initR,accum=accumR,done=doneR} = Reducer
{ init = \xs -> V.generateM (n xs) (\b -> initR (b, xs))
, accum = \bs i v ->
let ov = f (i, bs) in
accumR (ov,bs) i (v V.! ov)
, done = \v -> fmap G.convert (V.mapM doneR v)
}
{-# INLINE r_index #-}
r_split :: ((Int, xs) -> Bool)
-> Reducer xs s a
-> Reducer xs s b
-> Reducer xs s (a,b)
r_split b Reducer{init=initA,accum=accumA,done=doneA}
Reducer{init=initB,accum=accumB,done=doneB} = Reducer
{ init = \xs -> liftM2 (,) (initA xs) (initB xs)
, accum = \bs i (s1, s2) ->
if (b (i,bs)) then accumA bs i s1 else accumB bs i s2
, done = \(s1, s2) -> liftM2 (,) (doneA s1) (doneB s2)
}
{-# INLINE r_split #-}
r_add :: Num a => ((Int, xs) -> a) -> Reducer xs s a
r_add e = Reducer
{ init = \_ -> newSTRef 0
, accum = \bs i s ->
modifySTRef' s (+ (e (i,bs)))
, done = readSTRef
}
{-# INLINE r_add #-}
r_nop :: Reducer xs s ()
r_nop = Reducer
{ init = \_ -> return ()
, accum = \_ _ _ -> return ()
, done = \_ -> return ()
}
{-# INLINE r_nop #-}
pair :: a -> b -> (a, b)
pair = (,)
{-# INLINE pair #-}
true, false :: Bool
true = True
false = False
nothing :: Maybe a
nothing = Nothing
just :: a -> Maybe a
just = Just
unit :: ()
unit = ()
data Pattern = PVar | PWild
newtype Branch a b =
Branch { extract :: a -> Maybe b }
ptrue, pfalse :: a -> Branch Bool a
ptrue b = Branch { extract = extractBool True b }
pfalse b = Branch { extract = extractBool False b }
{-# INLINE ptrue #-}
{-# INLINE pfalse #-}
extractBool :: Bool -> a -> Bool -> Maybe a
extractBool b a p | p == b = Just a
| otherwise = Nothing
{-# INLINE extractBool #-}
pnothing :: b -> Branch (Maybe a) b
pnothing b = Branch { extract = \ma -> case ma of
Nothing -> Just b
Just _ -> Nothing }
pjust :: Pattern -> (a -> b) -> Branch (Maybe a) b
pjust PVar c = Branch { extract = \ma -> case ma of
Nothing -> Nothing
Just x -> Just (c x) }
pjust _ _ = error "Runtime.Prelude pjust"
ppair :: Pattern -> Pattern -> (x -> y -> b) -> Branch (x,y) b
ppair PVar PVar c = Branch { extract = (\(x,y) -> Just (c x y)) }
ppair _ _ _ = error "ppair: TODO"
uncase_ :: Maybe a -> a
uncase_ (Just a) = a
uncase_ Nothing = error "case_: unable to match any branches"
{-# INLINE uncase_ #-}
case_ :: a -> [Branch a b] -> b
case_ e [c1] = uncase_ (extract c1 e)
case_ e [c1, c2] = uncase_ (extract c1 e `mplus` extract c2 e)
case_ e bs_ = go bs_
where go [] = error "case_: unable to match any branches"
go (b:bs) = case extract b e of
Just b' -> b'
Nothing -> go bs
{-# INLINE case_ #-}
branch :: (c -> Branch a b) -> c -> Branch a b
branch pat body = pat body
{-# INLINE branch #-}
dirac :: a -> Measure a
dirac = return
{-# INLINE dirac #-}
pose :: LogFloat -> Measure a -> Measure a
pose _ a = a
{-# INLINE pose #-}
superpose :: [(LogFloat, Measure a)]
-> Measure a
superpose pms = do
i <- categorical (G.fromList $ map fst pms)
snd (pms !! i)
{-# INLINE superpose #-}
reject :: Measure a
reject = Measure $ \_ -> return Nothing
nat_ :: Int -> Int
nat_ = id
int_ :: Int -> Int
int_ = id
unsafeNat :: Int -> Int
unsafeNat = id
nat2prob :: Int -> LogFloat
nat2prob = fromIntegral
fromInt :: Int -> Double
fromInt = fromIntegral
nat2int :: Int -> Int
nat2int = id
nat2real :: Int -> Double
nat2real = fromIntegral
fromProb :: LogFloat -> Double
fromProb = fromLogFloat
unsafeProb :: Double -> LogFloat
unsafeProb = logFloat
real_ :: Rational -> Double
real_ = fromRational
prob_ :: NonNegativeRational -> LogFloat
prob_ = fromRational . fromNonNegativeRational
infinity :: Double
infinity = 1/0
abs_ :: Num a => a -> a
abs_ = abs
(**) :: LogFloat -> Double -> LogFloat
(**) = pow
{-# INLINE (**) #-}
pi :: LogFloat
pi = logFloat P.pi
{-# INLINE pi #-}
thRootOf :: Int -> LogFloat -> LogFloat
thRootOf a b = b `pow` (recip $ fromIntegral a)
{-# INLINE thRootOf #-}
array
:: (G.Vector (MayBoxVec a) a)
=> Int
-> (Int -> a)
-> MayBoxVec a a
array n f = G.generate (fromIntegral n) (f . fromIntegral)
{-# INLINE array #-}
arrayLit :: (G.Vector (MayBoxVec a) a) => [a] -> MayBoxVec a a
arrayLit = G.fromList
{-# INLINE arrayLit #-}
(!) :: (G.Vector (MayBoxVec a) a) => MayBoxVec a a -> Int -> a
a ! b = a G.! (fromIntegral b)
{-# INLINE (!) #-}
size :: (G.Vector (MayBoxVec a) a) => MayBoxVec a a -> Int
size v = fromIntegral (G.length v)
{-# INLINE size #-}
class Num a => Num' a where
product :: Int -> Int -> (Int -> a) -> a
product a b f = F.foldl' (\x y -> x * f y) 1 [a .. b-1]
{-# INLINE product #-}
summate :: Int -> Int -> (Int -> a) -> a
summate a b f = F.foldl' (\x y -> x + f y) 0 [a .. b-1]
{-# INLINE summate #-}
instance Num' Int
instance Num' Double
instance Num' LogFloat where
product a b f = LF.product (map f [a .. b-1])
{-# INLINE product #-}
summate a b f = LF.sum (map f [a .. b-1])
{-# INLINE summate #-}
run :: Show a
=> MWC.GenIO
-> Measure a
-> IO ()
run g k = unMeasure k g >>= \case
Just a -> print a
Nothing -> return ()
iterateM_
:: Monad m
=> (a -> m a)
-> a
-> m b
iterateM_ f = g
where g x = f x >>= g
withPrint :: Show a => (a -> IO b) -> a -> IO b
withPrint f x = print x >> f x
|
zaxtax/hakaru
|
haskell/Language/Hakaru/Runtime/LogFloatPrelude.hs
|
Haskell
|
bsd-3-clause
| 13,161
|
module ADP.Tests.RGExample where
import ADP.Multi.All
type RG_Algebra alphabet answer = (
EPS -> answer, -- nil
answer -> answer -> answer, -- left
answer -> answer -> answer -> answer, -- pair
answer -> answer -> answer -> answer -> answer -> answer -> answer, -- knot
answer -> answer -> answer, -- knot1
answer -> answer, -- knot2
(alphabet, alphabet) -> answer, -- basepair
alphabet -> answer, -- base
[answer] -> [answer] -- h
)
data Start = Nil
| Left' Start Start
| Pair Start Start Start
| Knot Start Start Start Start Start Start
| Knot1 Start Start
| Knot2 Start
| BasePair (Char, Char)
| Base Char
deriving (Eq, Show)
enum :: RG_Algebra Char Start
enum = (\_->Nil,Left',Pair,Knot,Knot1,Knot2,BasePair,Base,id)
maxBasepairs :: RG_Algebra Char Int
maxBasepairs = (nil,left,pair,knot,knot1,knot2,basepair,base,h) where
nil _ = 0
left a b = a + b
pair a b c = a + b + c
knot a b c d e f = a + b + c + d + e + f
knot1 a b = a + b
knot2 a = a
basepair _ = 1
base _ = 0
h [] = []
h xs = [maximum xs]
|
adp-multi/adp-multi-monadiccp
|
tests/ADP/Tests/RGExample.hs
|
Haskell
|
bsd-3-clause
| 1,413
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Control.Proof.Simple where
import Control.Applicative
import Control.Arrow
import Control.Eff
import Control.Eff.Choose
import Control.Eff.Lift
import Control.Eff.State.Lazy
import Control.Lens
import Control.Monad
import Data.Function
import Data.List
import Data.Typeable
import Numeric.Natural
import qualified Data.Map as M
import System.IO (hFlush, stdout)
import Data.Name
import Data.Prop
import Data.Proof
import Control.Proof.Common
type Hypotheses = M.Map Name PropS
type Target = PropS
data Prove' = Prove
{ _hypotheses :: Hypotheses
, _target :: Target
} deriving (Typeable)
makeLenses ''Prove'
instance Show Prove' where
show x = hypos x ++ fence ++ trg x where
hypos = concatMap (\ (n,p) -> show n ++ "\t" ++ show p ++ "\n") . M.toList . (^. hypotheses)
fence = replicate 40 '-' ++ "\n"
trg = show . (^. target)
type Prove = State Prove'
getProve :: (Member Prove r) => Eff r Prove'
getProve = get
putProve :: (Member Prove r) => Prove' -> Eff r ()
putProve = put
modifyProve :: (Member Prove r) => (Prove' -> Prove') -> Eff r ()
modifyProve = modify
getHypotheses :: (Member Prove r) => Eff r Hypotheses
getHypotheses = (^. hypotheses) <$> getProve
putHypotheses :: (Member Prove r) => Hypotheses -> Eff r ()
putHypotheses = modifyProve . (hypotheses .~)
modifyHypotheses :: (Member Prove r) => (Hypotheses -> Hypotheses) -> Eff r ()
modifyHypotheses = modifyProve . (hypotheses %~)
getTarget :: (Member Prove r) => Eff r Target
getTarget = (^. target) <$> getProve
putTarget :: (Member Prove r) => Target -> Eff r ()
putTarget = modifyProve . (target .~)
modifyTarget :: (Member Prove r) => (Target -> Target) -> Eff r ()
modifyTarget = modifyProve . (target %~)
intro :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
intro cont = do
a <- getTarget
case a of
Prop _ -> mzero'
Imply p q -> do
name <- newName . M.keys <$> getHypotheses
modifyHypotheses (M.insert name p)
putTarget q
Lambda name <$> cont
intros :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
intros cont = intro cont >> (cont `mplus'` intros cont)
chooseHypothesis :: (Member Prove r, Member Choose r) => Eff r (Name, PropS)
chooseHypothesis = choose . M.toList =<< getHypotheses where
chooseImplyHypothesis :: (Member Prove r, Member Choose r) => Eff r (Name, (PropS, PropS))
chooseImplyHypothesis = do
(n, p) <- chooseHypothesis
case p of
a `Imply` b -> return (n, (a, b))
_ -> mzero'
exact :: (Member Prove r, Member Choose r) => Eff r ProofS
exact = do
(n, p) <- chooseHypothesis
q <- getTarget
if p == q
then return $ Proof n
else mzero'
apply :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
apply cont = do
(n, (p, q)) <- chooseImplyHypothesis
(ps, q') <- choose $ split (p ~> q)
r <- getTarget
if q' == r
then do
rs <- forM ps $ \ p' -> do
putTarget p'
cont
return . foldr1 Apply $ Proof n : rs
else mzero'
auto :: (Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
auto cont = join $ choose
[ intro cont
, apply cont
, exact
]
hand :: (SetMember Lift (Lift IO) r, Member Prove r, Member Choose r) => Eff r ProofS -> Eff r ProofS
hand cont = do
lift . print =<< getProve
s <- lift $ do
putStr "tactic> "
hFlush stdout
getLine
case s of
"print" -> getProve >>= (lift . print) >> cont
"intro" -> intro cont
"intros" -> intros cont
"apply" -> apply cont
"exact" -> exact
"auto" -> auto cont
_ -> lift (putStrLn $ "no such command: " ++ s) >> cont
runTactic :: Hypotheses -> Target -> (Eff (Prove :> Choose :> r) ProofS -> Eff (Prove :> Choose :> r) ProofS) -> Eff r [ProofS]
runTactic x y = ((nubBy alphaEqual . map reduceS) <$>) . runChoice . evalState (Prove x y) . fix
autoSolve :: Hypotheses -> Target -> [ProofS]
autoSolve x y = run $ runTactic x y auto
handSolve :: Hypotheses -> Target -> IO [ProofS]
handSolve x y = putStrLn "* handSolve is wroking in progress *" >> runLift (runTactic x y hand)
-- | >>> autoSolve' [] "(a -> b) -> (b -> c) -> a -> c"
-- [\ x0 x1 . x1 x0]
-- >>> autoSolve' [] "b -> (a -> b) -> a -> b"
-- [\ x0 x1 . x1,\ x0 x1 x2 . x0]
-- >>> autoSolve' [("maybe_case", "maybe_a -> b -> (a -> b) -> b1")] "b -> (a -> b) -> maybe_a -> b1"
-- [\ x0 x1 x2 . maybe_case (x2 (x0 x1)),\ x0 x1 x2 . maybe_case (x2 (x0 (\ x3 . x0)))]
autoSolve' :: [(String, String)] -> String -> [ProofS]
autoSolve' xs y = autoSolve (M.fromList $ map (toName *** readPropS) xs) (readPropS y)
|
solorab/proof-haskell
|
Control/Proof/Simple.hs
|
Haskell
|
mit
| 5,049
|
-----------------------------------------------------------------------------
-- |
-- Module : RoverTests
-- Copyright : (c) 2017 Pascal Poizat
-- License : Apache-2.0 (see the file LICENSE)
--
-- Maintainer : pascal.poizat@lip6.fr
-- Stability : experimental
-- Portability : unknown
--
-- Test file for the Veca module.
-----------------------------------------------------------------------------
module RoverTests (roverTests)
where
import Test.Tasty
import Test.Tasty.HUnit
-- import Test.Tasty.QuickCheck as QC
-- import Test.Tasty.SmallCheck as SC
import Data.Map as M (Map, fromList)
import Data.Monoid ((<>))
import qualified Data.Set as S (fromList)
import Examples.Rover.Model
import Models.Events
import Models.LabelledTransitionSystem as LTS (LabelledTransitionSystem (..),
Path (..), paths')
import Models.Name (Name (..))
import Models.Named (Named (..))
import Models.TimedAutomaton as TA (Bounds (..),
ClockConstraint (..),
ClockOperator (..),
ClockReset (..),
Edge (..),
Expression (..),
Location (..),
TimedAutomaton (..),
VariableAssignment (..),
VariableType (..),
VariableTyping (..),
relabel)
import Veca.Model
import Veca.Operations
listDone :: Int -> Map (Name String) VariableTyping
listDone n = M.fromList
[ ( Name ["done"]
, VariableTyping (Name ["done"]) (IntType bounds) (Just $ Expression "0")
)
]
where bounds = Bounds 0 n
setDone :: Int -> VariableAssignment
setDone n = VariableAssignment (Name ["done"]) (Expression (show n))
roverTests :: TestTree
roverTests = testGroup "Tests" [unittests]
unittests :: TestTree
unittests = testGroup
"Unit tests for the Rover Case Study"
[uController, uStoreUnit, uPictureUnit, uVideoUnit, uAcquisitionUnit, uRover]
uController :: TestTree
uController = testGroup
"Unit tests for Controller"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType controllerUnit)
@?= True
, testCase "TA generation" $ cToTA controllerUnit @?= controllerTA
]
uStoreUnit :: TestTree
uStoreUnit = testGroup
"Unit tests for Store Unit"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType storeUnit)
@?= True
, testCase "TA generation" $ cToTA storeUnit @?= storeUnitTA
]
uPictureUnit :: TestTree
uPictureUnit = testGroup
"Unit tests for Picture Unit"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType pictureUnit)
@?= True
, testCase "TA generation" $ cToTA pictureUnit @?= pictureUnitTA
]
uVideoUnit :: TestTree
uVideoUnit = testGroup
"Unit tests for Video Unit"
[ testCase "basic component definition is valid"
$ isValidComponent (componentType videoUnit)
@?= True
, testCase "paths" $ S.fromList computedVUPaths @?= S.fromList expectedVUPaths
, testCase "isCPaths k1" $ (isCPath vuk1 <$> expectedVUPaths) @?= resk1
, testCase "isCPaths k2" $ (isCPath vuk2 <$> expectedVUPaths) @?= resk2
, testCase "isCPaths k3" $ (isCPath vuk3 <$> expectedVUPaths) @?= resk3
, testCase "TA generation" $ cToTA videoUnit @?= videoUnitTA
]
where computedVUPaths = paths' (behavior (componentType videoUnit))
uAcquisitionUnit :: TestTree
uAcquisitionUnit = testGroup
"Unit tests for Acquisition Unit"
[ testCase "composite component definition is valid"
$ isValidComponent (componentType acquisitionUnit)
@?= True
]
uRover :: TestTree
uRover = testGroup
"Unit tests for Rover"
[ testCase "composite component definition is valid"
$ isValidComponent (componentType rover)
@?= True
, testCase "TA generation for the Rover (standalone)"
$ (cTreeToTAList . cToCTree) rover
@?= roverTAs
]
--
-- Results
--
expectedVUPaths :: [VPath]
expectedVUPaths =
Path
<$> [ []
, [vut1]
, [vut2]
, [vut3]
, [vut4]
, [vut5]
, [vut6]
, [vut7]
, [vut1, vut2]
, [vut2, vut3]
, [vut3, vut4]
, [vut3, vut5]
, [vut4, vut6]
, [vut5, vut7]
, [vut6, vut7]
, [vut1, vut2, vut3]
, [vut2, vut3, vut4]
, [vut2, vut3, vut5]
, [vut3, vut4, vut6]
, [vut3, vut5, vut7]
, [vut4, vut6, vut7]
, [vut1, vut2, vut3, vut4]
, [vut1, vut2, vut3, vut5]
, [vut2, vut3, vut4, vut6]
, [vut2, vut3, vut5, vut7]
, [vut3, vut4, vut6, vut7]
, [vut1, vut2, vut3, vut4, vut6]
, [vut1, vut2, vut3, vut5, vut7]
, [vut2, vut3, vut4, vut6, vut7]
, [vut1, vut2, vut3, vut4, vut6, vut7]
]
resk1 :: [Bool]
resk1 =
[ False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, True
, False
, True
]
resk2 :: [Bool]
resk2 =
[ False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, True
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
]
resk3 :: [Bool]
resk3 =
[ False
, False
, False
, False
, False
, False
, False
, False
, False
, True
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
, False
]
--
-- test results
--
videoUnitTA :: VTA
videoUnitTA = TimedAutomaton
v
(Location <$> ["0", "1", "2", "3", "4", "5", "6"])
(Location "0")
[]
[]
clocksVU
(listDone 6)
(alphabet . behavior . componentType $ videoUnit)
[ Edge (Location "0") (receive askVid) [] [ClockReset c1] [setDone 1] (Location "1")
, Edge (Location "1") (invoke getVid) [] [ClockReset c3] [setDone 3] (Location "2")
, Edge (Location "2")
(result getVid)
[ClockConstraint c3 GE 0]
[ClockReset c2]
[setDone 4]
(Location "3")
, Edge (Location "3") tau [] [] [setDone 6] (Location "4")
, Edge (Location "3") tau [] [] [setDone 6] (Location "5")
, Edge (Location "4")
(invoke storeVid)
[ClockConstraint c2 GE 0]
[]
[setDone 5]
(Location "5")
, Edge (Location "5")
(reply askVid)
[ClockConstraint c1 GE 44]
[]
[setDone 2]
(Location "6")
, Edge (Location "6") tau [] [] [setDone 6] (Location "6")
]
[ (Location "1", [ClockConstraint c1 LE 46])
, (Location "2", [ClockConstraint c1 LE 46, ClockConstraint c3 LE 6])
, (Location "3", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "4", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "5", [ClockConstraint c1 LE 46])
]
where
clocksVU = genClock <$> timeconstraints (componentType videoUnit)
c1 = head clocksVU
c2 = clocksVU !! 1
c3 = clocksVU !! 2
pictureUnitTA :: VTA
pictureUnitTA = TimedAutomaton
p
(Location <$> ["0", "1", "2", "3", "4", "5", "6"])
(Location "0")
[]
[]
clocksPU
(listDone 6)
(alphabet . behavior . componentType $ pictureUnit)
[ Edge (Location "0") (receive askPic) [] [ClockReset c1] [setDone 1] (Location "1")
, Edge (Location "1") (invoke getPic) [] [ClockReset c3] [setDone 3] (Location "2")
, Edge (Location "2")
(result getPic)
[ClockConstraint c3 GE 0]
[ClockReset c2]
[setDone 4]
(Location "3")
, Edge (Location "3") tau [] [] [setDone 6] (Location "4")
, Edge (Location "3") tau [] [] [setDone 6] (Location "5")
, Edge (Location "4")
(invoke storePic)
[ClockConstraint c2 GE 0]
[]
[setDone 5]
(Location "5")
, Edge (Location "5")
(reply askPic)
[ClockConstraint c1 GE 44]
[]
[setDone 2]
(Location "6")
, Edge (Location "6") tau [] [] [setDone 6] (Location "6")
]
[ (Location "1", [ClockConstraint c1 LE 46])
, (Location "2", [ClockConstraint c1 LE 46, ClockConstraint c3 LE 6])
, (Location "3", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "4", [ClockConstraint c1 LE 46, ClockConstraint c2 LE 12])
, (Location "5", [ClockConstraint c1 LE 46])
]
where
clocksPU = genClock <$> timeconstraints (componentType pictureUnit)
c1 = head clocksPU
c2 = clocksPU !! 1
c3 = clocksPU !! 2
storeUnitTA :: VTA
storeUnitTA = TimedAutomaton
s
(Location <$> ["0", "1"])
(Location "0")
[]
[]
[]
(listDone 3)
(alphabet . behavior . componentType $ storeUnit)
[ Edge (Location "0") (receive storePic) [] [] [setDone 2] (Location "1")
, Edge (Location "0") (receive storeVid) [] [] [setDone 3] (Location "1")
, Edge (Location "1") tau [] [] [setDone 1] (Location "0")
, Edge (Location "0") tau [] [] [setDone 1] (Location "0")
]
[]
controllerTA :: VTA
controllerTA = TimedAutomaton
c
(Location <$> ["0", "1", "2", "3", "4", "5", "6"])
(Location "0")
[]
[]
clocksC
(listDone 7)
((alphabet . behavior . componentType $ controllerUnit) ++ [tau])
[ Edge (Location "0")
(receive run)
[]
[ClockReset c1]
[setDone 1]
(Location "1")
, Edge (Location "1") (invoke askVid) [] [] [setDone 3] (Location "2")
, Edge (Location "2") (result askVid) [] [] [setDone 4] (Location "3")
, Edge (Location "3") (invoke askPic) [] [] [setDone 5] (Location "4")
, Edge (Location "4") (result askPic) [] [] [setDone 6] (Location "5")
, Edge (Location "5")
(reply run)
[ClockConstraint c1 GE 55]
[]
[setDone 2]
(Location "6")
, Edge (Location "6") tau [] [] [setDone 7] (Location "6")
]
[ (Location "1", [ClockConstraint c1 LE 60])
, (Location "2", [ClockConstraint c1 LE 60])
, (Location "3", [ClockConstraint c1 LE 60])
, (Location "4", [ClockConstraint c1 LE 60])
, (Location "5", [ClockConstraint c1 LE 60])
]
where
clocksC = genClock <$> timeconstraints (componentType controllerUnit)
c1 = head clocksC
roverTAs :: [VTA]
roverTAs =
[ prefixBy r $ relabel sub1 controllerTA
, prefixBy (r <> a) $ relabel sub2 pictureUnitTA
, prefixBy (r <> a) $ relabel sub3 videoUnitTA
, prefixBy r $ relabel sub4 storeUnitTA
]
where
sub1 =
lift [mksub (r <> n5) run, mksub (r <> n1) askPic, mksub (r <> n2) askVid]
sub2 = lift
[mksub (r <> n1) askPic, mksub (r <> n6) getPic, mksub (r <> n3) storePic]
sub3 = lift
[mksub (r <> n2) askVid, mksub (r <> n7) getVid, mksub (r <> n4) storeVid]
sub4 = lift [mksub (r <> n3) storePic, mksub (r <> n4) storeVid]
lift = foldMap (fLift [CReceive, CReply, CInvoke, CResult])
mksub i o = (o, indexBy i o)
|
pascalpoizat/veca-haskell
|
test/RoverTests.hs
|
Haskell
|
apache-2.0
| 11,809
|
{-# LANGUAGE Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.IntSet.Lens
-- Copyright : (C) 2012-16 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : portable
--
----------------------------------------------------------------------------
module Data.IntSet.Lens
( members
, setmapped
, setOf
) where
import Control.Lens
import Data.IntSet as IntSet
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- | IntSet isn't Foldable, but this 'Fold' can be used to access the members of an 'IntSet'.
--
-- >>> sumOf members $ setOf folded [1,2,3,4]
-- 10
members :: Fold IntSet Int
members = folding IntSet.toAscList
{-# INLINE members #-}
-- | This 'Setter' can be used to change the contents of an 'IntSet' by mapping
-- the elements to new values.
--
-- Sadly, you can't create a valid 'Traversal' for a 'Set', because the number of
-- elements might change but you can manipulate it by reading using 'folded' and
-- reindexing it via 'setmapped'.
--
-- >>> over setmapped (+1) (fromList [1,2,3,4])
-- fromList [2,3,4,5]
setmapped :: IndexPreservingSetter' IntSet Int
setmapped = setting IntSet.map
{-# INLINE setmapped #-}
-- | Construct an 'IntSet' from a 'Getter', 'Fold', 'Traversal', 'Lens' or 'Iso'.
--
-- >>> setOf folded [1,2,3,4]
-- fromList [1,2,3,4]
--
-- >>> setOf (folded._2) [("hello",1),("world",2),("!!!",3)]
-- fromList [1,2,3]
--
-- @
-- 'setOf' :: 'Getter' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Fold' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Iso'' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Lens'' s 'Int' -> s -> 'IntSet'
-- 'setOf' :: 'Traversal'' s 'Int' -> s -> 'IntSet'
-- @
setOf :: Getting IntSet s Int -> s -> IntSet
setOf l = views l IntSet.singleton
{-# INLINE setOf #-}
|
ddssff/lens
|
src/Data/IntSet/Lens.hs
|
Haskell
|
bsd-3-clause
| 1,938
|
{-# LANGUAGE PatternGuards, ExistentialQuantification, CPP #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Core.Execute (execute) where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import IRTS.Lang(FDesc(..), FType(..))
import Idris.Primitives(Prim(..), primitives)
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.CaseTree
import Idris.Error
import Debug.Trace
import Util.DynamicLinker
import Util.System
import Control.Applicative hiding (Const)
import Control.Exception
import Control.Monad.Trans
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
import Control.Monad hiding (forM)
import Data.Maybe
import Data.Bits
import Data.Traversable (forM)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Data.Map as M
#ifdef IDRIS_FFI
import Foreign.LibFFI
import Foreign.C.String
import Foreign.Marshal.Alloc (free)
import Foreign.Ptr
#endif
import System.IO
#ifndef IDRIS_FFI
execute :: Term -> Idris Term
execute tm = fail "libffi not supported, rebuild Idris with -f FFI"
#else
-- else is rest of file
readMay :: (Read a) => String -> Maybe a
readMay s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show
data ExecState = ExecState { exec_dynamic_libs :: [DynamicLib] -- ^ Dynamic libs from idris monad
, binderNames :: [Name] -- ^ Used to uniquify binders when converting to TT
}
data ExecVal = EP NameType Name ExecVal
| EV Int
| EBind Name (Binder ExecVal) (ExecVal -> Exec ExecVal)
| EApp ExecVal ExecVal
| EType UExp
| EUType Universe
| EErased
| EConstant Const
| forall a. EPtr (Ptr a)
| EThunk Context ExecEnv Term
| EHandle Handle
instance Show ExecVal where
show (EP _ n _) = show n
show (EV i) = "!!V" ++ show i ++ "!!"
show (EBind n b body) = "EBind " ++ show b ++ " <<fn>>"
show (EApp e1 e2) = show e1 ++ " (" ++ show e2 ++ ")"
show (EType _) = "Type"
show (EUType _) = "UType"
show EErased = "[__]"
show (EConstant c) = show c
show (EPtr p) = "<<ptr " ++ show p ++ ">>"
show (EThunk _ env tm) = "<<thunk " ++ show env ++ "||||" ++ show tm ++ ">>"
show (EHandle h) = "<<handle " ++ show h ++ ">>"
toTT :: ExecVal -> Exec Term
toTT (EP nt n ty) = (P nt n) <$> (toTT ty)
toTT (EV i) = return $ V i
toTT (EBind n b body) = do n' <- newN n
body' <- body $ EP Bound n' EErased
b' <- fixBinder b
Bind n' b' <$> toTT body'
where fixBinder (Lam t) = Lam <$> toTT t
fixBinder (Pi i t k) = Pi i <$> toTT t <*> toTT k
fixBinder (Let t1 t2) = Let <$> toTT t1 <*> toTT t2
fixBinder (NLet t1 t2) = NLet <$> toTT t1 <*> toTT t2
fixBinder (Hole t) = Hole <$> toTT t
fixBinder (GHole i t) = GHole i <$> toTT t
fixBinder (Guess t1 t2) = Guess <$> toTT t1 <*> toTT t2
fixBinder (PVar t) = PVar <$> toTT t
fixBinder (PVTy t) = PVTy <$> toTT t
newN n = do (ExecState hs ns) <- lift get
let n' = uniqueName n ns
lift (put (ExecState hs (n':ns)))
return n'
toTT (EApp e1 e2) = do e1' <- toTT e1
e2' <- toTT e2
return $ App Complete e1' e2'
toTT (EType u) = return $ TType u
toTT (EUType u) = return $ UType u
toTT EErased = return Erased
toTT (EConstant c) = return (Constant c)
toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env
return $ normalise ctxt env' tm
where toBinder (n, v) = do v' <- toTT v
return (n, Let Erased v')
toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution."
toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution."
unApplyV :: ExecVal -> (ExecVal, [ExecVal])
unApplyV tm = ua [] tm
where ua args (EApp f a) = ua (a:args) f
ua args t = (t, args)
mkEApp :: ExecVal -> [ExecVal] -> ExecVal
mkEApp f [] = f
mkEApp f (a:args) = mkEApp (EApp f a) args
initState :: Idris ExecState
initState = do ist <- getIState
return $ ExecState (idris_dynamic_libs ist) []
type Exec = ExceptT Err (StateT ExecState IO)
runExec :: Exec a -> ExecState -> IO (Either Err a)
runExec ex st = fst <$> runStateT (runExceptT ex) st
getExecState :: Exec ExecState
getExecState = lift get
putExecState :: ExecState -> Exec ()
putExecState = lift . put
execFail :: Err -> Exec a
execFail = throwE
execIO :: IO a -> Exec a
execIO = lift . lift
execute :: Term -> Idris Term
execute tm = do est <- initState
ctxt <- getContext
res <- lift . lift . flip runExec est $
do res <- doExec [] ctxt tm
toTT res
case res of
Left err -> ierror err
Right tm' -> return tm'
ioWrap :: ExecVal -> ExecVal
ioWrap tm = mkEApp (EP (DCon 0 2 False) (sUN "prim__IO") EErased) [EErased, tm]
ioUnit :: ExecVal
ioUnit = ioWrap (EP Ref unitCon EErased)
type ExecEnv = [(Name, ExecVal)]
doExec :: ExecEnv -> Context -> Term -> Exec ExecVal
doExec env ctxt p@(P Ref n ty) | Just v <- lookup n env = return v
doExec env ctxt p@(P Ref n ty) =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> doExec env ctxt tm
[TyDecl _ _] -> return (EP Ref n EErased) -- abstract def
[Operator tp arity op] -> return (EP Ref n EErased) -- will be special-cased later
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
doExec env ctxt tm
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> return (EP Ref n EErased)
[] -> execFail . Msg $ "Could not find " ++ show n ++ " in definitions."
other | length other > 1 -> execFail . Msg $ "Multiple definitions found for " ++ show n
| otherwise -> execFail . Msg . take 500 $ "got to " ++ show other ++ " lookup up " ++ show n
doExec env ctxt p@(P Bound n ty) =
case lookup n env of
Nothing -> execFail . Msg $ "not found"
Just tm -> return tm
doExec env ctxt (P (DCon a b u) n _) = return (EP (DCon a b u) n EErased)
doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased)
doExec env ctxt v@(V i) | i < length env = return (snd (env !! i))
| otherwise = execFail . Msg $ "env too small"
doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v
doExec ((n, v'):env) ctxt body
doExec env ctxt (Bind n (NLet t v) body) = trace "NLet" $ undefined
doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt)
return $
EBind n b' (\arg -> doExec ((n, arg):env) ctxt body)
doExec env ctxt a@(App _ _ _) =
do let (f, args) = unApply a
f' <- doExec env ctxt f
args' <- case f' of
(EP _ d _) | d == delay ->
case args of
[t,a,tm] -> do t' <- doExec env ctxt t
a' <- doExec env ctxt a
return [t', a', EThunk ctxt env tm]
_ -> mapM (doExec env ctxt) args -- partial applications are fine to evaluate
fun' -> do mapM (doExec env ctxt) args
execApp env ctxt f' args'
doExec env ctxt (Constant c) = return (EConstant c)
doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in
doExec env ctxt ((x:xs) !! i)
doExec env ctxt Erased = return EErased
doExec env ctxt Impossible = fail "Tried to execute an impossible case"
doExec env ctxt (TType u) = return (EType u)
doExec env ctxt (UType u) = return (EUType u)
execApp :: ExecEnv -> Context -> ExecVal -> [ExecVal] -> Exec ExecVal
execApp env ctxt v [] = return v -- no args is just a constant! can result from function calls
execApp env ctxt (EP _ f _) (t:a:delayed:rest)
| f == force
, (_, [_, _, EThunk tmCtxt tmEnv tm]) <- unApplyV delayed =
do tm' <- doExec tmEnv tmCtxt tm
execApp env ctxt tm' rest
execApp env ctxt (EP _ fp _) (ty:action:rest)
| fp == upio,
(prim__IO, [_, v]) <- unApplyV action
= execApp env ctxt v rest
execApp env ctxt (EP _ fp _) args@(_:_:v:k:rest)
| fp == piobind,
(prim__IO, [_, v']) <- unApplyV v =
do res <- execApp env ctxt k [v']
execApp env ctxt res rest
execApp env ctxt con@(EP _ fp _) args@(tp:v:rest)
| fp == pioret = execApp env ctxt (mkEApp con [tp, v]) rest
-- Special cases arising from not having access to the C RTS in the interpreter
execApp env ctxt f@(EP _ fp _) args@(xs:_:_:_:args')
| fp == mkfprim,
(ty : fn : w : rest) <- reverse args' =
execForeign env ctxt getArity ty fn rest (mkEApp f args)
where getArity = case unEList xs of
Just as -> length as
_ -> 0
execApp env ctxt c@(EP (DCon _ arity _) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt c@(EP (TCon _ arity) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt f@(EP _ n _) args
| Just (res, rest) <- getOp n args = do r <- res
execApp env ctxt r rest
execApp env ctxt f@(EP _ n _) args =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> fail "should already have been eval'd"
[TyDecl nt ty] -> return $ mkEApp f args
[Operator tp arity op] ->
if length args >= arity
then let args' = take arity args in
case getOp n args' of
Just (res, []) -> do r <- res
execApp env ctxt r (drop arity args)
_ -> return (mkEApp f args)
else return (mkEApp f args)
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
do rhs <- doExec env ctxt tm
execApp env ctxt rhs args
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] ->
do res <- execCase env ctxt ns sc args
return $ fromMaybe (mkEApp f args) res
thing -> return $ mkEApp f args
execApp env ctxt bnd@(EBind n b body) (arg:args) = do ret <- body arg
let (f', as) = unApplyV ret
execApp env ctxt f' (as ++ args)
execApp env ctxt app@(EApp _ _) args2 | (f, args1) <- unApplyV app = execApp env ctxt f (args1 ++ args2)
execApp env ctxt f args = return (mkEApp f args)
execForeign env ctxt arity ty fn xs onfail
| Just (FFun "putStr" [(_, str)] _) <- foreignFromTT arity ty fn xs
= case str of
EConstant (Str arg) -> do execIO (putStr arg)
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to putStr should be a constant string, but it was " ++
show str ++
". Are all cases covered?"
| Just (FFun "putchar" [(_, ch)] _) <- foreignFromTT arity ty fn xs
= case ch of
EConstant (Ch c) -> do execIO (putChar c)
execApp env ctxt ioUnit (drop arity xs)
EConstant (I i) -> do execIO (putChar (toEnum i))
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to putchar should be a constant character, but it was " ++
show str ++
". Are all cases covered?"
| Just (FFun "idris_readStr" [_, (_, handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do contents <- execIO $ hGetLine h
execApp env ctxt (EConstant (Str (contents ++ "\n"))) (drop arity xs)
_ -> execFail . Msg $
"The argument to idris_readStr should be a handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "getchar" _ _) <- foreignFromTT arity ty fn xs
= do -- The C API returns an Int which Idris library code
-- converts; thus, we must make an int here.
ch <- execIO $ fmap (ioWrap . EConstant . I . fromEnum) getChar
execApp env ctxt ch xs
| Just (FFun "idris_time" _ _) <- foreignFromTT arity ty fn xs
= do execIO $ fmap (ioWrap . EConstant . I . round) getPOSIXTime
| Just (FFun "fileOpen" [(_,fileStr), (_,modeStr)] _) <- foreignFromTT arity ty fn xs
= case (fileStr, modeStr) of
(EConstant (Str f), EConstant (Str mode)) ->
do f <- execIO $
catch (do let m = case mode of
"r" -> Right ReadMode
"w" -> Right WriteMode
"a" -> Right AppendMode
"rw" -> Right ReadWriteMode
"wr" -> Right ReadWriteMode
"r+" -> Right ReadWriteMode
_ -> Left ("Invalid mode for " ++ f ++ ": " ++ mode)
case fmap (openFile f) m of
Right h -> do h' <- h
hSetBinaryMode h' True
return $ Right (ioWrap (EHandle h'), drop arity xs)
Left err -> return $ Left err)
(\e -> let _ = ( e::SomeException)
in return $ Right (ioWrap (EPtr nullPtr), drop arity xs))
case f of
Left err -> execFail . Msg $ err
Right (res, rest) -> execApp env ctxt res rest
_ -> execFail . Msg $
"The arguments to fileOpen should be constant strings, but they were " ++
show fileStr ++ " and " ++ show modeStr ++
". Are all cases covered?"
| Just (FFun "fileEOF" [(_,handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do eofp <- execIO $ hIsEOF h
let res = ioWrap (EConstant (I $ if eofp then 1 else 0))
execApp env ctxt res (drop arity xs)
_ -> execFail . Msg $
"The argument to fileEOF should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "fileClose" [(_,handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do execIO $ hClose h
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to fileClose should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "isNull" [(_, ptr)] _) <- foreignFromTT arity ty fn xs
= case ptr of
EPtr p -> let res = ioWrap . EConstant . I $
if p == nullPtr then 1 else 0
in execApp env ctxt res (drop arity xs)
-- Handles will be checked as null pointers sometimes - but if we got a
-- real Handle, then it's valid, so just return 1.
EHandle h -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
-- A foreign-returned char* has to be tested for NULL sometimes
EConstant (Str s) -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
_ -> execFail . Msg $
"The argument to isNull should be a pointer or file handle or string, but it was " ++
show ptr ++
". Are all cases covered?"
-- Right now, there's no way to send command-line arguments to the executor,
-- so just return 0.
execForeign env ctxt arity ty fn xs onfail
| Just (FFun "idris_numArgs" _ _) <- foreignFromTT arity ty fn xs
= let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
execForeign env ctxt arity ty fn xs onfail
= case foreignFromTT arity ty fn xs of
Just ffun@(FFun f argTs retT) | length xs >= arity ->
do let (args', xs') = (take arity xs, -- foreign args
drop arity xs) -- rest
res <- call ffun (map snd argTs)
case res of
Nothing -> fail $ "Could not call foreign function \"" ++ f ++
"\" with args " ++ show (map snd argTs)
Just r -> return (mkEApp r xs')
_ -> return onfail
splitArg tm | (_, [_,_,l,r]) <- unApplyV tm -- pair, two implicits
= Just (toFDesc l, r)
splitArg _ = Nothing
toFDesc tm
| (EP _ n _, []) <- unApplyV tm = FCon (deNS n)
| (EP _ n _, as) <- unApplyV tm = FApp (deNS n) (map toFDesc as)
toFDesc _ = FUnknown
deNS (NS n _) = n
deNS n = n
prf = sUN "prim__readFile"
pwf = sUN "prim__writeFile"
prs = sUN "prim__readString"
pws = sUN "prim__writeString"
pbm = sUN "prim__believe_me"
pstdin = sUN "prim__stdin"
pstdout = sUN "prim__stdout"
mkfprim = sUN "mkForeignPrim"
pioret = sUN "prim_io_return"
piobind = sUN "prim_io_bind"
upio = sUN "unsafePerformPrimIO"
delay = sUN "Delay"
force = sUN "Force"
-- | Look up primitive operations in the global table and transform
-- them into ExecVal functions
getOp :: Name -> [ExecVal] -> Maybe (Exec ExecVal, [ExecVal])
getOp fn (_ : _ : x : xs) | fn == pbm = Just (return x, xs)
getOp fn (_ : EConstant (Str n) : xs)
| fn == pws =
Just (do execIO $ putStr n
return (EConstant (I 0)), xs)
getOp fn (_:xs)
| fn == prs =
Just (do line <- execIO getLine
return (EConstant (Str line)), xs)
getOp fn (_ : EP _ fn' _ : EConstant (Str n) : xs)
| fn == pwf && fn' == pstdout =
Just (do execIO $ putStr n
return (EConstant (I 0)), xs)
getOp fn (_ : EP _ fn' _ : xs)
| fn == prf && fn' == pstdin =
Just (do line <- execIO getLine
return (EConstant (Str line)), xs)
getOp fn (_ : EHandle h : EConstant (Str n) : xs)
| fn == pwf =
Just (do execIO $ hPutStr h n
return (EConstant (I 0)), xs)
getOp fn (_ : EHandle h : xs)
| fn == prf =
Just (do contents <- execIO $ hGetLine h
return (EConstant (Str (contents ++ "\n"))), xs)
getOp fn (_ : arg : xs)
| fn == prf =
Just $ (execFail (Msg "Can't use prim__readFile on a raw pointer in the executor."), xs)
getOp n args = do (arity, prim) <- getPrim n primitives
if (length args >= arity)
then do res <- applyPrim prim (take arity args)
Just (res, drop arity args)
else Nothing
where getPrim :: Name -> [Prim] -> Maybe (Int, [ExecVal] -> Maybe ExecVal)
getPrim n [] = Nothing
getPrim n ((Prim pn _ arity def _ _) : prims)
| n == pn = Just (arity, execPrim def)
| otherwise = getPrim n prims
execPrim :: ([Const] -> Maybe Const) -> [ExecVal] -> Maybe ExecVal
execPrim f args = EConstant <$> (mapM getConst args >>= f)
getConst (EConstant c) = Just c
getConst _ = Nothing
applyPrim :: ([ExecVal] -> Maybe ExecVal) -> [ExecVal] -> Maybe (Exec ExecVal)
applyPrim fn args = return <$> fn args
-- | Overall wrapper for case tree execution. If there are enough arguments, it takes them,
-- evaluates them, then begins the checks for matching cases.
execCase :: ExecEnv -> Context -> [Name] -> SC -> [ExecVal] -> Exec (Maybe ExecVal)
execCase env ctxt ns sc args =
let arity = length ns in
if arity <= length args
then do let amap = zip ns args
-- trace ("Case " ++ show sc ++ "\n in " ++ show amap ++"\n in env " ++ show env ++ "\n\n" ) $ return ()
caseRes <- execCase' env ctxt amap sc
case caseRes of
Just res -> Just <$> execApp (map (\(n, tm) -> (n, tm)) amap ++ env) ctxt res (drop arity args)
Nothing -> return Nothing
else return Nothing
-- | Take bindings and a case tree and examines them, executing the matching case if possible.
execCase' :: ExecEnv -> Context -> [(Name, ExecVal)] -> SC -> Exec (Maybe ExecVal)
execCase' env ctxt amap (UnmatchedCase _) = return Nothing
execCase' env ctxt amap (STerm tm) =
Just <$> doExec (map (\(n, v) -> (n, v)) amap ++ env) ctxt tm
execCase' env ctxt amap (Case sh n alts) | Just tm <- lookup n amap =
case chooseAlt tm alts of
Just (newCase, newBindings) ->
let amap' = newBindings ++ (filter (\(x,_) -> not (elem x (map fst newBindings))) amap) in
execCase' env ctxt amap' newCase
Nothing -> return Nothing
execCase' _ _ _ cse = fail $ "The impossible happened: tried to exec " ++ show cse
chooseAlt :: ExecVal -> [CaseAlt] -> Maybe (SC, [(Name, ExecVal)])
chooseAlt tm (DefaultCase sc : alts) | ok tm = Just (sc, [])
| otherwise = Nothing
where -- Default cases should only work on applications of constructors or on constants
ok (EApp f x) = ok f
ok (EP Bound _ _) = False
ok (EP Ref _ _) = False
ok _ = True
chooseAlt (EConstant c) (ConstCase c' sc : alts) | c == c' = Just (sc, [])
chooseAlt tm (ConCase n i ns sc : alts) | ((EP _ cn _), args) <- unApplyV tm
, cn == n = Just (sc, zip ns args)
| otherwise = chooseAlt tm alts
chooseAlt tm (_:alts) = chooseAlt tm alts
chooseAlt _ [] = Nothing
data Foreign = FFun String [(FDesc, ExecVal)] FDesc deriving Show
toFType :: FDesc -> FType
toFType (FCon c)
| c == sUN "C_Str" = FString
| c == sUN "C_Float" = FArith ATFloat
| c == sUN "C_Ptr" = FPtr
| c == sUN "C_MPtr" = FManagedPtr
| c == sUN "C_Unit" = FUnit
toFType (FApp c [_,ity])
| c == sUN "C_IntT" = FArith (toAType ity)
where toAType (FCon i)
| i == sUN "C_IntChar" = ATInt ITChar
| i == sUN "C_IntNative" = ATInt ITNative
| i == sUN "C_IntBits8" = ATInt (ITFixed IT8)
| i == sUN "C_IntBits16" = ATInt (ITFixed IT16)
| i == sUN "C_IntBits32" = ATInt (ITFixed IT32)
| i == sUN "C_IntBits64" = ATInt (ITFixed IT64)
toAType t = error (show t ++ " not defined in toAType")
toFType (FApp c [_])
| c == sUN "C_Any" = FAny
toFType t = error (show t ++ " not defined in toFType")
call :: Foreign -> [ExecVal] -> Exec (Maybe ExecVal)
call (FFun name argTypes retType) args =
do fn <- findForeign name
maybe (return Nothing)
(\f -> Just . ioWrap <$> call' f args (toFType retType)) fn
where call' :: ForeignFun -> [ExecVal] -> FType -> Exec ExecVal
call' (Fun _ h) args (FArith (ATInt ITNative)) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (I (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT8))) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (B8 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT16))) = do
res <- execIO $ callFFI h retCWchar (prepArgs args)
return (EConstant (B16 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT32))) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (B32 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT64))) = do
res <- execIO $ callFFI h retCLong (prepArgs args)
return (EConstant (B64 (fromIntegral res)))
call' (Fun _ h) args (FArith ATFloat) = do
res <- execIO $ callFFI h retCDouble (prepArgs args)
return (EConstant (Fl (realToFrac res)))
call' (Fun _ h) args (FArith (ATInt ITChar)) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (Ch (castCCharToChar res)))
call' (Fun _ h) args FString = do res <- execIO $ callFFI h retCString (prepArgs args)
if res == nullPtr
then return (EPtr res)
else do hStr <- execIO $ peekCString res
return (EConstant (Str hStr))
call' (Fun _ h) args FPtr = EPtr <$> (execIO $ callFFI h (retPtr retVoid) (prepArgs args))
call' (Fun _ h) args FUnit = do _ <- execIO $ callFFI h retVoid (prepArgs args)
return $ EP Ref unitCon EErased
call' _ _ _ = fail "the impossible happened in call' in Execute.hs"
prepArgs = map prepArg
prepArg (EConstant (I i)) = argCInt (fromIntegral i)
prepArg (EConstant (B8 i)) = argCChar (fromIntegral i)
prepArg (EConstant (B16 i)) = argCWchar (fromIntegral i)
prepArg (EConstant (B32 i)) = argCInt (fromIntegral i)
prepArg (EConstant (B64 i)) = argCLong (fromIntegral i)
prepArg (EConstant (Fl f)) = argCDouble (realToFrac f)
prepArg (EConstant (Ch c)) = argCChar (castCharToCChar c) -- FIXME - castCharToCChar only safe for first 256 chars
-- Issue #1720 on the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1720
prepArg (EConstant (Str s)) = argString s
prepArg (EPtr p) = argPtr p
prepArg other = trace ("Could not use " ++ take 100 (show other) ++ " as FFI arg.") undefined
foreignFromTT :: Int -> ExecVal -> ExecVal -> [ExecVal] -> Maybe Foreign
foreignFromTT arity ty (EConstant (Str name)) args
= do argFTyVals <- mapM splitArg (take arity args)
return $ FFun name argFTyVals (toFDesc ty)
foreignFromTT arity ty fn args = trace ("failed to construct ffun from " ++ show (ty,fn,args)) Nothing
getFTy :: ExecVal -> Maybe FType
getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _))
| fi == txt "FIntT" =
case str intTy of
"ITNative" -> Just (FArith (ATInt ITNative))
"ITChar" -> Just (FArith (ATInt ITChar))
"IT8" -> Just (FArith (ATInt (ITFixed IT8)))
"IT16" -> Just (FArith (ATInt (ITFixed IT16)))
"IT32" -> Just (FArith (ATInt (ITFixed IT32)))
"IT64" -> Just (FArith (ATInt (ITFixed IT64)))
_ -> Nothing
getFTy (EP _ (UN t) _) =
case str t of
"FFloat" -> Just (FArith ATFloat)
"FString" -> Just FString
"FPtr" -> Just FPtr
"FUnit" -> Just FUnit
_ -> Nothing
getFTy _ = Nothing
unEList :: ExecVal -> Maybe [ExecVal]
unEList tm = case unApplyV tm of
(nil, [_]) -> Just []
(cons, ([_, x, xs])) ->
do rest <- unEList xs
return $ x:rest
(f, args) -> Nothing
toConst :: Term -> Maybe Const
toConst (Constant c) = Just c
toConst _ = Nothing
mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f [] = return []
mapMaybeM f (x:xs) = do rest <- mapMaybeM f xs
maybe rest (:rest) <$> f x
findForeign :: String -> Exec (Maybe ForeignFun)
findForeign fn = do est <- getExecState
let libs = exec_dynamic_libs est
fns <- mapMaybeM getFn libs
case fns of
[f] -> return (Just f)
[] -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" not found"
return Nothing
fs -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" is ambiguous. Found " ++
show (length fs) ++ " occurrences."
return Nothing
where getFn lib = execIO $ catchIO (tryLoadFn fn lib) (\_ -> return Nothing)
#endif
|
athanclark/Idris-dev
|
src/Idris/Core/Execute.hs
|
Haskell
|
bsd-3-clause
| 29,467
|
{-# LANGUAGE Rank2Types #-}
module Opaleye.Internal.PackMap where
import qualified Opaleye.Internal.Tag as T
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
import Control.Applicative (Applicative, pure, (<*>), liftA2)
import qualified Control.Monad.Trans.State as State
import Data.Profunctor (Profunctor, dimap)
import Data.Profunctor.Product (ProductProfunctor, empty, (***!))
import qualified Data.Profunctor.Product as PP
import qualified Data.Functor.Identity as I
-- This is rather like a Control.Lens.Traversal with the type
-- parameters switched but I'm not sure if it should be required to
-- obey the same laws.
--
-- TODO: We could attempt to generalise this to
--
-- data LensLike f a b s t = LensLike ((a -> f b) -> s -> f t)
--
-- i.e. a wrapped, argument-flipped Control.Lens.LensLike
--
-- This would allow us to do the Profunctor and ProductProfunctor
-- instances (requiring just Functor f and Applicative f respectively)
-- and share them between many different restrictions of f. For
-- example, TableColumnMaker is like a Setter so we would restrict f
-- to the Distributive case.
-- | A 'PackMap' @a@ @b@ @s@ @t@ encodes how an @s@ contains an
-- updatable sequence of @a@ inside it. Each @a@ in the sequence can
-- be updated to a @b@ (and the @s@ changes to a @t@ to reflect this
-- change of type).
--
-- 'PackMap' is just like a @Traversal@ from the lens package.
-- 'PackMap' has a different order of arguments to @Traversal@ because
-- it typically needs to be made a 'Profunctor' (and indeed
-- 'ProductProfunctor') in @s@ and @t@. It is unclear at this point
-- whether we want the same @Traversal@ laws to hold or not. Our use
-- cases may be much more general.
data PackMap a b s t = PackMap (Applicative f =>
(a -> f b) -> s -> f t)
-- | Replaces the targeted occurences of @a@ in @s@ with @b@ (changing
-- the @s@ to a @t@ in the process). This can be done via an
-- 'Applicative' action.
--
-- 'traversePM' is just like @traverse@ from the @lens@ package.
-- 'traversePM' used to be called @packmap@.
traversePM :: Applicative f => PackMap a b s t -> (a -> f b) -> s -> f t
traversePM (PackMap f) = f
-- | Modify the targeted occurrences of @a@ in @s@ with @b@ (changing
-- the @s@ to a @t@ in the process).
--
-- 'overPM' is just like @over@ from the @lens@ pacakge.
overPM :: PackMap a b s t -> (a -> b) -> s -> t
overPM p f = I.runIdentity . traversePM p (I.Identity . f)
-- {
-- | A helpful monad for writing columns in the AST
type PM a = State.State (a, Int)
new :: PM a String
new = do
(a, i) <- State.get
State.put (a, i + 1)
return (show i)
write :: a -> PM [a] ()
write a = do
(as, i) <- State.get
State.put (as ++ [a], i)
run :: PM [a] r -> (r, [a])
run m = (r, as)
where (r, (as, _)) = State.runState m ([], 0)
-- }
-- { General functions for writing columns in the AST
-- | Make a fresh name for an input value (the variable @primExpr@
-- type is typically actually a 'HPQ.PrimExpr') based on the supplied
-- function and the unique 'T.Tag' that is used as part of our
-- @QueryArr@.
--
-- Add the fresh name and the input value it refers to to the list in
-- the state parameter.
extractAttrPE :: (primExpr -> String -> String) -> T.Tag -> primExpr
-> PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr
extractAttrPE mkName t pe = do
i <- new
let s = HPQ.Symbol (mkName pe i) t
write (s, pe)
return (HPQ.AttrExpr s)
-- | As 'extractAttrPE' but ignores the 'primExpr' when making the
-- fresh column name and just uses the supplied 'String' and 'T.Tag'.
extractAttr :: String -> T.Tag -> primExpr
-> PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr
extractAttr s = extractAttrPE (const (s ++))
-- }
eitherFunction :: Functor f
=> (a -> f b)
-> (a' -> f b')
-> Either a a'
-> f (Either b b')
eitherFunction f g = fmap (either (fmap Left) (fmap Right)) (f PP.+++! g)
-- {
-- Boilerplate instance definitions. There's no choice here apart
-- from the order in which the applicative is applied.
instance Functor (PackMap a b s) where
fmap f (PackMap g) = PackMap ((fmap . fmap . fmap) f g)
instance Applicative (PackMap a b s) where
pure x = PackMap (pure (pure (pure x)))
PackMap f <*> PackMap x = PackMap (liftA2 (liftA2 (<*>)) f x)
instance Profunctor (PackMap a b) where
dimap f g (PackMap q) = PackMap (fmap (dimap f (fmap g)) q)
instance ProductProfunctor (PackMap a b) where
empty = PP.defaultEmpty
(***!) = PP.defaultProfunctorProduct
instance PP.SumProfunctor (PackMap a b) where
f +++! g = (PackMap (\x -> eitherFunction (f' x) (g' x)))
where PackMap f' = f
PackMap g' = g
-- }
|
alanz/haskell-opaleye
|
src/Opaleye/Internal/PackMap.hs
|
Haskell
|
bsd-3-clause
| 4,764
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Stack.FileWatch
( fileWatch
, fileWatchPoll
, printExceptionStderr
) where
import Blaze.ByteString.Builder (toLazyByteString, copyByteString)
import Blaze.ByteString.Builder.Char.Utf8 (fromShow)
import Control.Concurrent.Async (race_)
import Control.Concurrent.STM
import Control.Exception (Exception)
import Control.Exception.Enclosed (tryAny)
import Control.Monad (forever, unless, when)
import qualified Data.ByteString.Lazy as L
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String (fromString)
import Data.Traversable (forM)
import Ignore
import Path
import System.FSNotify
import System.IO (stderr)
-- | Print an exception to stderr
printExceptionStderr :: Exception e => e -> IO ()
printExceptionStderr e =
L.hPut stderr $ toLazyByteString $ fromShow e <> copyByteString "\n"
fileWatch :: IO (Path Abs Dir)
-> ((Set (Path Abs File) -> IO ()) -> IO ())
-> IO ()
fileWatch = fileWatchConf defaultConfig
fileWatchPoll :: IO (Path Abs Dir)
-> ((Set (Path Abs File) -> IO ()) -> IO ())
-> IO ()
fileWatchPoll = fileWatchConf $ defaultConfig { confUsePolling = True }
-- | Run an action, watching for file changes
--
-- The action provided takes a callback that is used to set the files to be
-- watched. When any of those files are changed, we rerun the action again.
fileWatchConf :: WatchConfig
-> IO (Path Abs Dir)
-> ((Set (Path Abs File) -> IO ()) -> IO ())
-> IO ()
fileWatchConf cfg getProjectRoot inner = withManagerConf cfg $ \manager -> do
allFiles <- newTVarIO Set.empty
dirtyVar <- newTVarIO True
watchVar <- newTVarIO Map.empty
projRoot <- getProjectRoot
mChecker <- findIgnoreFiles [VCSGit, VCSMercurial, VCSDarcs] projRoot >>= buildChecker
(FileIgnoredChecker isFileIgnored) <-
case mChecker of
Left err ->
do putStrLn $ "Failed to parse VCS's ignore file: " ++ err
return $ FileIgnoredChecker (const False)
Right chk -> return chk
let onChange event = atomically $ do
files <- readTVar allFiles
when (eventPath event `Set.member` files) (writeTVar dirtyVar True)
setWatched :: Set (Path Abs File) -> IO ()
setWatched files = do
atomically $ writeTVar allFiles $ Set.map toFilePath files
watch0 <- readTVarIO watchVar
let actions = Map.mergeWithKey
keepListening
stopListening
startListening
watch0
newDirs
watch1 <- forM (Map.toList actions) $ \(k, mmv) -> do
mv <- mmv
return $
case mv of
Nothing -> Map.empty
Just v -> Map.singleton k v
atomically $ writeTVar watchVar $ Map.unions watch1
where
newDirs = Map.fromList $ map (, ())
$ Set.toList
$ Set.map parent files
keepListening _dir listen () = Just $ return $ Just listen
stopListening = Map.map $ \f -> do
() <- f
return Nothing
startListening = Map.mapWithKey $ \dir () -> do
let dir' = fromString $ toFilePath dir
listen <- watchDir manager dir' (not . isFileIgnored . eventPath) onChange
return $ Just listen
let watchInput = do
line <- getLine
unless (line == "quit") $ do
case line of
"help" -> do
putStrLn ""
putStrLn "help: display this help"
putStrLn "quit: exit"
putStrLn "build: force a rebuild"
putStrLn "watched: display watched directories"
"build" -> atomically $ writeTVar dirtyVar True
"watched" -> do
watch <- readTVarIO watchVar
mapM_ (putStrLn . toFilePath) (Map.keys watch)
_ -> putStrLn $ concat
[ "Unknown command: "
, show line
, ". Try 'help'"
]
watchInput
race_ watchInput $ forever $ do
atomically $ do
dirty <- readTVar dirtyVar
check dirty
eres <- tryAny $ inner setWatched
-- Clear dirtiness flag after the build to avoid an infinite
-- loop caused by the build itself triggering dirtiness. This
-- could be viewed as a bug, since files changed during the
-- build will not trigger an extra rebuild, but overall seems
-- like better behavior. See
-- https://github.com/commercialhaskell/stack/issues/822
atomically $ writeTVar dirtyVar False
case eres of
Left e -> printExceptionStderr e
Right () -> putStrLn "Success! Waiting for next file change."
putStrLn "Type help for available commands"
|
robstewart57/stack
|
src/Stack/FileWatch.hs
|
Haskell
|
bsd-3-clause
| 5,294
|
import Sudoku
import Control.Exception
import System.Environment
import Data.Maybe
main :: IO ()
main = do
[f] <- getArgs
grids <- fmap lines $ readFile f
print (length (filter isJust (map solve grids)))
|
lywaterman/parconc-examples
|
sudoku-par1.hs
|
Haskell
|
bsd-3-clause
| 217
|
{-# LANGUAGE ImplicitParams, TypeFamilies #-}
module T3540 where
thing :: (a~Int)
thing = undefined
thing1 :: Int -> (a~Int)
thing1 = undefined
thing2 :: (a~Int) -> Int
thing2 = undefined
thing3 :: (?dude :: Int) -> Int
thing3 = undefined
thing4:: (Eq a) -> Int
thing4 = undefined
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/typecheck/should_fail/T3540.hs
|
Haskell
|
bsd-3-clause
| 288
|
module Main where
import Data.Functor ((<$>))
import Data.Maybe (isJust, fromJust)
import System.Cmd (rawSystem)
import System.Exit (ExitCode(..))
import System.IO (hFlush, stdout)
import System.Posix.Process (forkProcess, getProcessStatus)
import Hackonad.LineParser
typePrompt :: IO ()
typePrompt = putStr "> " >> hFlush stdout
readCommand :: IO (String, [String])
readCommand = parseInputLine <$> getLine
while :: (Monad m) => (a -> m (Bool, a)) -> a -> m ()
while action initialValue = action initialValue >>= \ (res, iterVal) -> if res then while action iterVal else return ()
proccessExitCode :: ExitCode -> String -> Int -> IO ()
proccessExitCode ExitSuccess _ _ = return ()
proccessExitCode (ExitFailure code) command sessionLine = case code of
127 -> putStrLn $ "Hackonad: " ++ show sessionLine ++ ": " ++ command ++ ": not found"
otherwise -> putStrLn $ "Hackonad: " ++ show code ++ ": " ++ command
mainLoop :: Int -> IO (Bool, Int)
mainLoop sessionLine = do
typePrompt
(command, parameters) <- readCommand
if command == "exit"
then return (False, sessionLine)
else do
pid <- forkProcess $ do
exitCode <- rawSystem command parameters
proccessExitCode exitCode command sessionLine
status <- getProcessStatus True False pid
if isJust status
then do
putStrLn $ "Base +" ++ show ( fromJust status )
return (True, sessionLine + 1)
else do
putStrLn "Base +"
return (True, sessionLine + 1)
main :: IO ()
main = while mainLoop 0
|
triplepointfive/Hackonad
|
src/Main.hs
|
Haskell
|
mit
| 1,671
|
module Main where
import Data.Monoid
import Test.Framework
import qualified Test.Parser as Parser
import qualified Test.Eval as Eval
main :: IO ()
main = defaultMainWithOpts tests mempty
tests = concat
[ Parser.tests
, Eval.tests
]
|
forestbelton/anima
|
Test/Main.hs
|
Haskell
|
mit
| 250
|
module Main where
import Reddit.TheButton.Connection
import Reddit.TheButton.Types
import Reddit.TheButton.AnyBar
import Reddit.TheButton.Utility
import Control.Monad (forever)
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan (readChan, dupChan)
import System.IO (hSetBuffering, BufferMode(..), stdout)
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
chan1 <- getTicks
chan2 <- mapChan btnColor chan1
forkIO $ abUpdateFromChan "1738" chan2
forever $ do
tick <- readChan chan1
putStrLn (btnColor tick)
where
btnColor = show . secToColor . bSecondsLeft
|
romac/thebutton.hs
|
src/Main.hs
|
Haskell
|
mit
| 624
|
-- | This file defines 'FormulaTree', the type used for modeling the calculation trees.
--
-- Author: Thorsten Rangwich. See file <../LICENSE> for details.
module Tree.FormulaTree
(
FormulaTree(..),
TreeError(..),
NamedFunction(..) -- FIXME: Export creater and exporters, not type
)
where
import qualified Data.Plain as P
import qualified Data.SheetLayout as L
-- | Type to mark error in tree
data TreeError = NamedError String -- ^ Named error - this should be used
| CircularReference -- ^ Circular reference in tree.
| UnspecifiedError -- ^ Unspecified error - not useful, better add more specific errors
deriving Show
-- | Wrapper to be used in the trees.
data NamedFunction = NamedFunction { funcName :: String, funcCall :: P.PlainFunction }
-- | Compiled representation of a formula
data FormulaTree = Raw P.Plain -- ^ Node is plain result value
| Reference L.Address
| Funcall NamedFunction [FormulaTree] -- ^ Node is a formula
| TreeError TreeError -- ^ Node is evaluated to an error
-- This makes sense for errors affecting the tree like circular references
-- in contrast to plain value errors like div/0.
|
tnrangwi/grill
|
src/Tree/FormulaTree.hs
|
Haskell
|
mit
| 1,303
|
{-# LANGUAGE Rank2Types #-}
module Statistics
where
import Data.Foldable
import Control.Monad.State
import System.Random
import Data.List
type Rnd a = (RandomGen g) => State g a
randomRM :: (Random a) => (a, a) -> Rnd a
randomRM v = do
g <- get
(x, g') <- return $ randomR v g
put g'
return x
choose :: [a] -> Rnd a
choose l = do
let n = length l
i <- randomRM (0, n - 1)
return (l !! i)
chooseIO :: (Foldable f) => f a -> IO a
chooseIO l = do
let l' = toList l
n = length l'
i <- randomRIO (0, n - 1)
return (l' !! i)
stdNormal :: (Random a, Ord a, Floating a) => Rnd a
stdNormal = do
u1 <- randomRM (-1, 1)
u2 <- randomRM (-1, 1)
let m = stdNormalMarsaglia u1 u2
case m of
Nothing -> stdNormal
Just (z1, _) -> return z1
stdNormalMarsaglia :: (Ord a, Floating a) => a -> a -> Maybe (a, a)
stdNormalMarsaglia y1 y2 =
if q > 1 then Nothing else Just (z1, z2)
where z1 = y1 * p
z2 = y2 * p
q = y1 * y1 + y2 * y2
p = sqrt ((-2) * log q / q)
normal :: (Random a, Ord a, Floating a) => a -> a -> Rnd a
normal mu sigma = do
n <- stdNormal
return $ mu + n * sigma
normalR :: (Random a, Ord a, Floating a) => (a, a) -> a -> a -> Rnd a
normalR (mn, mx) mu sigma = do
n <- normal mu sigma
if n < mn
then return mn
else if n > mx
then return mx else return n
normalIO :: (Random a, Ord a, Floating a) => a -> a -> IO a
normalIO mu sigma = newStdGen >>= return . evalState (normal mu sigma)
normalRIO :: (Random a, Ord a, Floating a) => (a, a) -> a -> a -> IO a
normalRIO limits mu sigma = newStdGen >>= return . evalState (normalR limits mu sigma)
average :: (Fractional a) => [a] -> a
average l = go 0 0 l
where go acc len [] = acc / len
go acc len (x:xs) = go (acc + x) (len + 1) xs
averageInt :: [Int] -> Int
averageInt l = go 0 0 l
where go acc len [] = acc `div` len
go acc len (x:xs) = go (acc + x) (len + 1) xs
median :: (Ord a, Num a) => [a] -> a
median [] = error "Median on empty list"
median l = (sort l) !! (length l `div` 2)
-- chance of a to b
chance :: Int -> Int -> Rnd Bool
chance a b = do
v <- randomRM (1, b)
if a <= v - 1
then return True
else return False
-- shuffle :: [a] -> Rnd [a]
shuffle l = shuffle' l [] -- >>= reverse >>= flip shuffle' []
where shuffle' [] bs = return bs
shuffle' as bs = do
el <- choose as
shuffle' (delete el as) (el : bs)
|
anttisalonen/starrover2
|
src/Statistics.hs
|
Haskell
|
mit
| 2,451
|
{-# LANGUAGE FlexibleInstances #-}
module TermSpec where
import Data.Text as T
import Test.QuickCheck
import Faun.Term
import TextGen
instance Arbitrary Term where
arbitrary = oneof [genVar, genConst, genFun]
genTerms :: Gen [Term]
genTerms = sized $ \n -> do
size <- choose (0, n `mod` 6) -- Huge lists of arguments make the test result hard to read / interpret.
vectorOf size arbitrary
genVar :: Gen Term
genVar = do
name <- genCamelString
return $ Variable $ T.pack name
genConst :: Gen Term
genConst = do
name <- genPascalString
return $ Constant $ T.pack name
genFun :: Gen Term
genFun = do
name <- genPascalString
args <- genTerms
return $ Function (T.pack name) args
|
PhDP/Sphinx-AI
|
tests/TermSpec.hs
|
Haskell
|
mit
| 701
|
-- |
-- Module: BigE.Attribute.Vert_P_N
-- Copyright: (c) 2017 Patrik Sandahl
-- Licence: MIT
-- Maintainer: Patrik Sandahl <patrik.sandahl@gmail.com>
-- Stability: experimental
-- Portability: portable
-- Language: Haskell2010
module BigE.Attribute.Vert_P_N
( Vertex (..)
) where
import BigE.Attribute (Attribute (..), allocBoundBuffers,
fillBoundVBO, pointerOffset)
import Control.Monad (unless)
import qualified Data.Vector.Storable as Vector
import Foreign (Storable (..), castPtr, plusPtr)
import Graphics.GL (GLfloat)
import qualified Graphics.GL as GL
import Linear (V3)
-- | A convenience definition of a vertex containing two attributes.
-- The vertex position and the vertex normal.
data Vertex = Vertex
{ position :: !(V3 GLfloat)
, normal :: !(V3 GLfloat)
} deriving (Eq, Show)
-- | Storable instance.
instance Storable Vertex where
sizeOf v = sizeOf (position v) + sizeOf (normal v)
alignment v = alignment $ position v
peek ptr = do
p <- peek $ castPtr ptr
let nPtr = castPtr (ptr `plusPtr` sizeOf p)
n <- peek nPtr
return Vertex { position = p, normal = n }
poke ptr v = do
let pPtr = castPtr ptr
nPtr = castPtr (pPtr `plusPtr` sizeOf (position v))
poke pPtr $ position v
poke nPtr $ normal v
-- | Attribute instance.
instance Attribute Vertex where
initAttributes bufferUsage vertices = do
buffers <- allocBoundBuffers
unless (Vector.null vertices) $ do
item <- fillBoundVBO vertices bufferUsage
let itemSize = fromIntegral $ sizeOf item
-- Position.
GL.glEnableVertexAttribArray 0
GL.glVertexAttribPointer 0 3 GL.GL_FLOAT GL.GL_FALSE
itemSize
(pointerOffset 0)
-- Normal.
GL.glEnableVertexAttribArray 1
GL.glVertexAttribPointer 1 3 GL.GL_FLOAT GL.GL_FALSE
itemSize
(pointerOffset $ sizeOf (position item))
return buffers
|
psandahl/big-engine
|
src/BigE/Attribute/Vert_P_N.hs
|
Haskell
|
mit
| 2,273
|
{-# LANGUAGE CPP, OverloadedStrings #-}
module NewAccount (newAccountSpecs) where
import Data.Monoid
import Yesod.Auth
import Yesod.Test
import Foundation
import Text.XML.Cursor (attribute)
import qualified Data.Text as T
redirectCode :: Int
#if MIN_VERSION_yesod_test(1,4,0)
redirectCode = 303
#else
redirectCode = 302
#endif
-- In 9f379bc219bd1fdf008e2c179b03e98a05b36401 (which went into yesod-form-1.3.9)
-- the numbering of fields was changed. We normally wouldn't care because fields
-- can be set via 'byLabel', but hidden fields have no label so we must use the id
-- directly. We temporarily support both versions of yesod form with the following.
f1, f2 :: T.Text
#if MIN_VERSION_yesod_form(1,3,9)
f1 = "f1"
f2 = "f2"
#else
f1 = "f2"
f2 = "f3"
#endif
newAccountSpecs :: YesodSpec MyApp
newAccountSpecs =
ydescribe "New account tests" $ do
yit "new account with mismatched passwords" $ do
get' "/auth/page/account/newaccount"
statusIs 200
bodyContains "Register"
post'"/auth/page/account/newaccount" $ do
addNonce
byLabel "Username" "abc"
byLabel "Email" "test@example.com"
byLabel "Password" "xxx"
byLabel "Confirm" "yyy"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Passwords did not match"
yit "creates a new account" $ do
get' "/auth/page/account/newaccount"
statusIs 200
post'"/auth/page/account/newaccount" $ do
addNonce
byLabel "Username" "abc"
byLabel "Email" "test@example.com"
byLabel "Password" "xxx"
byLabel "Confirm" "xxx"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "A confirmation e-mail has been sent to test@example.com"
(username, email, verify) <- lastVerifyEmail
assertEqual "username" username "abc"
assertEqual "email" email "test@example.com"
get' "/auth/page/account/verify/abc/zzzzzz"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "invalid verification key"
-- try login
get' "/auth/login"
statusIs 200
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "yyy"
statusIs redirectCode
get' "/auth/login"
statusIs 200
bodyContains "Invalid username/password combination"
-- valid login
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "xxx"
statusIs 200
bodyContains "Your email has not yet been verified"
-- valid login with email
get' "/auth/login"
statusIs 200
post'"/auth/page/account/login" $ do
byLabel "Username" "test@example.com"
byLabel "Password" "xxx"
statusIs 200
bodyContains "Your email has not yet been verified"
-- resend verify email
post'"/auth/page/account/resendverifyemail" $ do
addNonce
addPostParam f1 "abc" -- username is also a hidden field
statusIs redirectCode
get' "/"
bodyContains "A confirmation e-mail has been sent to test@example.com"
(username', email', verify') <- lastVerifyEmail
assertEqual "username" username' "abc"
assertEqual "email" email' "test@example.com"
assertEqual "verify" True (verify /= verify')
-- verify email
get' verify'
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "You are logged in as abc"
post $ AuthR LogoutR
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Please visit the <a href=\"/auth/login\">Login page"
-- valid login
get' "/auth/login"
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "xxx"
statusIs redirectCode
get' "/"
bodyContains "You are logged in as abc"
-- logout
post $ AuthR LogoutR
-- valid login with email
get' "/auth/login"
post'"/auth/page/account/login" $ do
byLabel "Username" "test@example.com"
byLabel "Password" "xxx"
statusIs 302
get' "/"
bodyContains "You are logged in as abc"
-- logout
post $ AuthR LogoutR
-- reset password
get' "/auth/page/account/resetpassword"
statusIs 200
bodyContains "Send password reset email"
post'"/auth/page/account/resetpassword" $ do
byLabel "Username" "abc"
addNonce
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "A password reset email has been sent to your email address"
(username'', email'', newpwd) <- lastNewPwdEmail
assertEqual "User" username'' "abc"
assertEqual "Email" email'' "test@example.com"
-- bad key
get' newpwd
statusIs 200
post'"/auth/page/account/setpassword" $ do
addNonce
byLabel "New password" "www"
byLabel "Confirm" "www"
addPostParam f1 "abc"
addPostParam f2 "qqqqqqqqqqqqqq"
statusIs 403
bodyContains "Invalid key"
-- good key
get' newpwd
statusIs 200
matches <- htmlQuery $ "input[name=" <> f2 <> "][type=hidden][value]"
post'"/auth/page/account/setpassword" $ do
addNonce
byLabel "New password" "www"
byLabel "Confirm" "www"
addPostParam f1 "abc"
key <- case matches of
[] -> error "Unable to find set password key"
element:_ -> return $ head $ attribute "value" $ parseHTML element
addPostParam f2 key
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Password updated"
bodyContains "You are logged in as abc"
post $ AuthR LogoutR
-- check new password
get' "/auth/login"
post'"/auth/page/account/login" $ do
byLabel "Username" "abc"
byLabel "Password" "www"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "You are logged in as abc"
yit "errors with a username with a period" $ do
get' "/auth/page/account/newaccount"
statusIs 200
post' "/auth/page/account/newaccount" $ do
addNonce
byLabel "Username" "x.y"
byLabel "Email" "xy@example.com"
byLabel "Password" "hunter2"
byLabel "Confirm" "hunter2"
statusIs redirectCode
get' "/"
statusIs 200
bodyContains "Invalid username" -- Issue #2: a valid username was not checked on creation
|
jasonzoladz/yesod-auth-account-fork
|
tests/NewAccount.hs
|
Haskell
|
mit
| 7,624
|
module Hamming (distance) where
distance :: String -> String -> Maybe Int
distance xs ys = error "You need to implement this function."
|
exercism/xhaskell
|
exercises/practice/hamming/src/Hamming.hs
|
Haskell
|
mit
| 137
|
import Data.Digits
lend = length . digits 10
bases = [1..9] -- lend (10^x) > 10 for all x
exponents = [1..30] -- lend (9^x) > x for x>30
pairs = [(base,exponent) | base <- bases, exponent <- exponents]
isValid (base,exponent) = (lend (base^exponent) == exponent)
valid = filter isValid pairs
answer = length valid
|
gumgl/project-euler
|
63/63.hs
|
Haskell
|
mit
| 319
|
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
-- | The basic typeclass for a Yesod application.
module Yesod.Internal.Core
( -- * Type classes
Yesod (..)
, YesodDispatch (..)
, RenderRoute (..)
-- ** Breadcrumbs
, YesodBreadcrumbs (..)
, breadcrumbs
-- * Utitlities
, maybeAuthorized
, widgetToPageContent
-- * Defaults
, defaultErrorHandler
-- * Data types
, AuthResult (..)
-- * Sessions
, SessionBackend (..)
, defaultClientSessionBackend
, clientSessionBackend
, loadClientSession
, BackendSession
-- * jsLoader
, ScriptLoadPosition (..)
, BottomOfHeadAsync
, loadJsYepnope
-- * Misc
, yesodVersion
, yesodRender
, resolveApproot
, Approot (..)
, FileUpload (..)
, runFakeHandler
) where
import Yesod.Content
import Yesod.Handler hiding (lift, getExpires)
import Yesod.Routes.Class
import Data.Word (Word64)
import Control.Arrow ((***))
import Control.Monad (forM)
import Yesod.Widget
import Yesod.Request
import qualified Network.Wai as W
import Yesod.Internal
import Yesod.Internal.Session
import Yesod.Internal.Request
import qualified Web.ClientSession as CS
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import qualified Data.IORef as I
import Data.Monoid
import Text.Hamlet
import Text.Julius
import Text.Blaze ((!), customAttribute, textTag, toValue, unsafeLazyByteString)
import qualified Text.Blaze.Html5 as TBH
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy.Encoding (encodeUtf8)
import Data.Maybe (fromMaybe, isJust)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Trans.Resource (runResourceT)
import Web.Cookie (parseCookies)
import qualified Data.Map as Map
import Data.Time
import Network.HTTP.Types (encodePath)
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Encoding.Error as TEE
import Blaze.ByteString.Builder (Builder, toByteString)
import Blaze.ByteString.Builder.Char.Utf8 (fromText)
import Data.List (foldl')
import qualified Network.HTTP.Types as H
import Web.Cookie (SetCookie (..))
import Language.Haskell.TH.Syntax (Loc (..))
import Text.Blaze (preEscapedToMarkup)
import Data.Aeson (Value (Array, String))
import Data.Aeson.Encode (encode)
import qualified Data.Vector as Vector
import Network.Wai.Middleware.Gzip (GzipSettings, def)
import Network.Wai.Parse (tempFileBackEnd, lbsBackEnd)
import qualified Paths_yesod_core
import Data.Version (showVersion)
import System.Log.FastLogger (Logger, mkLogger, loggerDate, LogStr (..), loggerPutStr)
import Control.Monad.Logger (LogLevel (LevelInfo, LevelOther), LogSource)
import System.Log.FastLogger.Date (ZonedDate)
import System.IO (stdout)
yesodVersion :: String
yesodVersion = showVersion Paths_yesod_core.version
-- | This class is automatically instantiated when you use the template haskell
-- mkYesod function. You should never need to deal with it directly.
class YesodDispatch sub master where
yesodDispatch
:: Yesod master
=> Logger
-> master
-> sub
-> (Route sub -> Route master)
-> (Maybe (SessionBackend master) -> W.Application) -- ^ 404 handler
-> (Route sub -> Maybe (SessionBackend master) -> W.Application) -- ^ 405 handler
-> Text -- ^ request method
-> [Text] -- ^ pieces
-> Maybe (SessionBackend master)
-> W.Application
yesodRunner :: Yesod master
=> Logger
-> GHandler sub master ChooseRep
-> master
-> sub
-> Maybe (Route sub)
-> (Route sub -> Route master)
-> Maybe (SessionBackend master)
-> W.Application
yesodRunner = defaultYesodRunner
-- | How to determine the root of the application for constructing URLs.
--
-- Note that future versions of Yesod may add new constructors without bumping
-- the major version number. As a result, you should /not/ pattern match on
-- @Approot@ values.
data Approot master = ApprootRelative -- ^ No application root.
| ApprootStatic Text
| ApprootMaster (master -> Text)
| ApprootRequest (master -> W.Request -> Text)
type ResolvedApproot = Text
-- | Define settings for a Yesod applications. All methods have intelligent
-- defaults, and therefore no implementation is required.
class RenderRoute a => Yesod a where
-- | An absolute URL to the root of the application. Do not include
-- trailing slash.
--
-- Default value: 'ApprootRelative'. This is valid under the following
-- conditions:
--
-- * Your application is served from the root of the domain.
--
-- * You do not use any features that require absolute URLs, such as Atom
-- feeds and XML sitemaps.
--
-- If this is not true, you should override with a different
-- implementation.
approot :: Approot a
approot = ApprootRelative
-- | Output error response pages.
errorHandler :: ErrorResponse -> GHandler sub a ChooseRep
errorHandler = defaultErrorHandler
-- | Applies some form of layout to the contents of a page.
defaultLayout :: GWidget sub a () -> GHandler sub a RepHtml
defaultLayout w = do
p <- widgetToPageContent w
mmsg <- getMessage
hamletToRepHtml [hamlet|
$newline never
$doctype 5
<html>
<head>
<title>#{pageTitle p}
^{pageHead p}
<body>
$maybe msg <- mmsg
<p .message>#{msg}
^{pageBody p}
|]
-- | Override the rendering function for a particular URL. One use case for
-- this is to offload static hosting to a different domain name to avoid
-- sending cookies.
urlRenderOverride :: a -> Route a -> Maybe Builder
urlRenderOverride _ _ = Nothing
-- | Determine if a request is authorized or not.
--
-- Return 'Authorized' if the request is authorized,
-- 'Unauthorized' a message if unauthorized.
-- If authentication is required, return 'AuthenticationRequired'.
isAuthorized :: Route a
-> Bool -- ^ is this a write request?
-> GHandler s a AuthResult
isAuthorized _ _ = return Authorized
-- | Determines whether the current request is a write request. By default,
-- this assumes you are following RESTful principles, and determines this
-- from request method. In particular, all except the following request
-- methods are considered write: GET HEAD OPTIONS TRACE.
--
-- This function is used to determine if a request is authorized; see
-- 'isAuthorized'.
isWriteRequest :: Route a -> GHandler s a Bool
isWriteRequest _ = do
wai <- waiRequest
return $ W.requestMethod wai `notElem`
["GET", "HEAD", "OPTIONS", "TRACE"]
-- | The default route for authentication.
--
-- Used in particular by 'isAuthorized', but library users can do whatever
-- they want with it.
authRoute :: a -> Maybe (Route a)
authRoute _ = Nothing
-- | A function used to clean up path segments. It returns 'Right' with a
-- clean path or 'Left' with a new set of pieces the user should be
-- redirected to. The default implementation enforces:
--
-- * No double slashes
--
-- * There is no trailing slash.
--
-- Note that versions of Yesod prior to 0.7 used a different set of rules
-- involing trailing slashes.
cleanPath :: a -> [Text] -> Either [Text] [Text]
cleanPath _ s =
if corrected == s
then Right $ map dropDash s
else Left corrected
where
corrected = filter (not . T.null) s
dropDash t
| T.all (== '-') t = T.drop 1 t
| otherwise = t
-- | Builds an absolute URL by concatenating the application root with the
-- pieces of a path and a query string, if any.
-- Note that the pieces of the path have been previously cleaned up by 'cleanPath'.
joinPath :: a
-> T.Text -- ^ application root
-> [T.Text] -- ^ path pieces
-> [(T.Text, T.Text)] -- ^ query string
-> Builder
joinPath _ ar pieces' qs' =
fromText ar `mappend` encodePath pieces qs
where
pieces = if null pieces' then [""] else map addDash pieces'
qs = map (TE.encodeUtf8 *** go) qs'
go "" = Nothing
go x = Just $ TE.encodeUtf8 x
addDash t
| T.all (== '-') t = T.cons '-' t
| otherwise = t
-- | This function is used to store some static content to be served as an
-- external file. The most common case of this is stashing CSS and
-- JavaScript content in an external file; the "Yesod.Widget" module uses
-- this feature.
--
-- The return value is 'Nothing' if no storing was performed; this is the
-- default implementation. A 'Just' 'Left' gives the absolute URL of the
-- file, whereas a 'Just' 'Right' gives the type-safe URL. The former is
-- necessary when you are serving the content outside the context of a
-- Yesod application, such as via memcached.
addStaticContent :: Text -- ^ filename extension
-> Text -- ^ mime-type
-> L.ByteString -- ^ content
-> GHandler sub a (Maybe (Either Text (Route a, [(Text, Text)])))
addStaticContent _ _ _ = return Nothing
{- Temporarily disabled until we have a better interface.
-- | Whether or not to tie a session to a specific IP address. Defaults to
-- 'False'.
--
-- Note: This setting has two known problems: it does not work correctly
-- when behind a reverse proxy (including load balancers), and it may not
-- function correctly if the user is behind a proxy.
sessionIpAddress :: a -> Bool
sessionIpAddress _ = False
-}
-- | The path value to set for cookies. By default, uses \"\/\", meaning
-- cookies will be sent to every page on the current domain.
cookiePath :: a -> S8.ByteString
cookiePath _ = "/"
-- | The domain value to set for cookies. By default, the
-- domain is not set, meaning cookies will be sent only to
-- the current domain.
cookieDomain :: a -> Maybe S8.ByteString
cookieDomain _ = Nothing
-- | Maximum allowed length of the request body, in bytes.
--
-- Default: 2 megabytes.
maximumContentLength :: a -> Maybe (Route a) -> Word64
maximumContentLength _ _ = 2 * 1024 * 1024 -- 2 megabytes
-- | Returns a @Logger@ to use for log messages.
--
-- Default: Sends to stdout and automatically flushes on each write.
getLogger :: a -> IO Logger
getLogger _ = mkLogger True stdout
-- | Send a message to the @Logger@ provided by @getLogger@.
--
-- Note: This method is no longer used. Instead, you should override
-- 'messageLoggerSource'.
messageLogger :: a
-> Logger
-> Loc -- ^ position in source code
-> LogLevel
-> LogStr -- ^ message
-> IO ()
messageLogger a logger loc = messageLoggerSource a logger loc ""
-- | Send a message to the @Logger@ provided by @getLogger@.
messageLoggerSource :: a
-> Logger
-> Loc -- ^ position in source code
-> LogSource
-> LogLevel
-> LogStr -- ^ message
-> IO ()
messageLoggerSource a logger loc source level msg =
if shouldLog a source level
then formatLogMessage (loggerDate logger) loc source level msg >>= loggerPutStr logger
else return ()
-- | The logging level in place for this application. Any messages below
-- this level will simply be ignored.
logLevel :: a -> LogLevel
logLevel _ = LevelInfo
-- | GZIP settings.
gzipSettings :: a -> GzipSettings
gzipSettings _ = def
-- | Where to Load sripts from. We recommend the default value,
-- 'BottomOfBody'. Alternatively use the built in async yepnope loader:
--
-- > BottomOfHeadAsync $ loadJsYepnope $ Right $ StaticR js_modernizr_js
--
-- Or write your own async js loader: see 'loadJsYepnope'
jsLoader :: a -> ScriptLoadPosition a
jsLoader _ = BottomOfBody
-- | Create a session backend. Returning `Nothing' disables sessions.
--
-- Default: Uses clientsession with a 2 hour timeout.
makeSessionBackend :: a -> IO (Maybe (SessionBackend a))
makeSessionBackend _ = do
key <- CS.getKey CS.defaultKeyFile
return $ Just $ clientSessionBackend key 120
-- | How to store uploaded files.
--
-- Default: Whe nthe request body is greater than 50kb, store in a temp
-- file. Otherwise, store in memory.
fileUpload :: a
-> Word64 -- ^ request body size
-> FileUpload
fileUpload _ size
| size > 50000 = FileUploadDisk tempFileBackEnd
| otherwise = FileUploadMemory lbsBackEnd
-- | Should we log the given log source/level combination.
--
-- Default: Logs everything at or above 'logLevel'
shouldLog :: a -> LogSource -> LogLevel -> Bool
shouldLog a _ level = level >= logLevel a
{-# DEPRECATED messageLogger "Please use messageLoggerSource (since yesod-core 1.1.2)" #-}
formatLogMessage :: IO ZonedDate
-> Loc
-> LogSource
-> LogLevel
-> LogStr -- ^ message
-> IO [LogStr]
formatLogMessage getdate loc src level msg = do
now <- getdate
return
[ LB now
, LB " ["
, LS $
case level of
LevelOther t -> T.unpack t
_ -> drop 5 $ show level
, LS $
if T.null src
then ""
else "#" ++ T.unpack src
, LB "] "
, msg
, LB " @("
, LS $ fileLocationToString loc
, LB ")\n"
]
-- taken from file-location package
-- turn the TH Loc loaction information into a human readable string
-- leaving out the loc_end parameter
fileLocationToString :: Loc -> String
fileLocationToString loc = (loc_package loc) ++ ':' : (loc_module loc) ++
' ' : (loc_filename loc) ++ ':' : (line loc) ++ ':' : (char loc)
where
line = show . fst . loc_start
char = show . snd . loc_start
defaultYesodRunner :: Yesod master
=> Logger
-> GHandler sub master ChooseRep
-> master
-> sub
-> Maybe (Route sub)
-> (Route sub -> Route master)
-> Maybe (SessionBackend master)
-> W.Application
defaultYesodRunner logger handler master sub murl toMasterRoute msb req
| maximumContentLength master (fmap toMasterRoute murl) < len =
return $ W.responseLBS
(H.Status 413 "Too Large")
[("Content-Type", "text/plain")]
"Request body too large to be processed."
| otherwise = do
now <- liftIO getCurrentTime
let dontSaveSession _ _ = return []
(session, saveSession) <- liftIO $
maybe (return ([], dontSaveSession)) (\sb -> sbLoadSession sb master req now) msb
rr <- liftIO $ parseWaiRequest req session (isJust msb) len
let h = {-# SCC "h" #-} do
case murl of
Nothing -> handler
Just url -> do
isWrite <- isWriteRequest $ toMasterRoute url
ar <- isAuthorized (toMasterRoute url) isWrite
case ar of
Authorized -> return ()
AuthenticationRequired ->
case authRoute master of
Nothing ->
permissionDenied "Authentication required"
Just url' -> do
setUltDestCurrent
redirect url'
Unauthorized s' -> permissionDenied s'
handler
let sessionMap = Map.fromList . filter ((/=) tokenKey . fst) $ session
let ra = resolveApproot master req
let log' = messageLoggerSource master logger
yar <- handlerToYAR master sub (fileUpload master) log' toMasterRoute
(yesodRender master ra) errorHandler rr murl sessionMap h
extraHeaders <- case yar of
(YARPlain _ _ ct _ newSess) -> do
let nsToken = Map.toList $ maybe
newSess
(\n -> Map.insert tokenKey (TE.encodeUtf8 n) newSess)
(reqToken rr)
sessionHeaders <- liftIO (saveSession nsToken now)
return $ ("Content-Type", ct) : map headerToPair sessionHeaders
_ -> return []
return $ yarToResponse yar extraHeaders
where
len = fromMaybe 0 $ lookup "content-length" (W.requestHeaders req) >>= readMay
readMay s =
case reads $ S8.unpack s of
[] -> Nothing
(x, _):_ -> Just x
data AuthResult = Authorized | AuthenticationRequired | Unauthorized Text
deriving (Eq, Show, Read)
-- | A type-safe, concise method of creating breadcrumbs for pages. For each
-- resource, you declare the title of the page and the parent resource (if
-- present).
class YesodBreadcrumbs y where
-- | Returns the title and the parent resource, if available. If you return
-- a 'Nothing', then this is considered a top-level page.
breadcrumb :: Route y -> GHandler sub y (Text , Maybe (Route y))
-- | Gets the title of the current page and the hierarchy of parent pages,
-- along with their respective titles.
breadcrumbs :: YesodBreadcrumbs y => GHandler sub y (Text, [(Route y, Text)])
breadcrumbs = do
x' <- getCurrentRoute
tm <- getRouteToMaster
let x = fmap tm x'
case x of
Nothing -> return ("Not found", [])
Just y -> do
(title, next) <- breadcrumb y
z <- go [] next
return (title, z)
where
go back Nothing = return back
go back (Just this) = do
(title, next) <- breadcrumb this
go ((this, title) : back) next
applyLayout' :: Yesod master
=> Html -- ^ title
-> HtmlUrl (Route master) -- ^ body
-> GHandler sub master ChooseRep
applyLayout' title body = fmap chooseRep $ defaultLayout $ do
setTitle title
toWidget body
-- | The default error handler for 'errorHandler'.
defaultErrorHandler :: Yesod y => ErrorResponse -> GHandler sub y ChooseRep
defaultErrorHandler NotFound = do
r <- waiRequest
let path' = TE.decodeUtf8With TEE.lenientDecode $ W.rawPathInfo r
applyLayout' "Not Found"
[hamlet|
$newline never
<h1>Not Found
<p>#{path'}
|]
defaultErrorHandler (PermissionDenied msg) =
applyLayout' "Permission Denied"
[hamlet|
$newline never
<h1>Permission denied
<p>#{msg}
|]
defaultErrorHandler (InvalidArgs ia) =
applyLayout' "Invalid Arguments"
[hamlet|
$newline never
<h1>Invalid Arguments
<ul>
$forall msg <- ia
<li>#{msg}
|]
defaultErrorHandler (InternalError e) =
applyLayout' "Internal Server Error"
[hamlet|
$newline never
<h1>Internal Server Error
<p>#{e}
|]
defaultErrorHandler (BadMethod m) =
applyLayout' "Bad Method"
[hamlet|
$newline never
<h1>Method Not Supported
<p>Method "#{S8.unpack m}" not supported
|]
-- | Return the same URL if the user is authorized to see it.
--
-- Built on top of 'isAuthorized'. This is useful for building page that only
-- contain links to pages the user is allowed to see.
maybeAuthorized :: Yesod a
=> Route a
-> Bool -- ^ is this a write request?
-> GHandler s a (Maybe (Route a))
maybeAuthorized r isWrite = do
x <- isAuthorized r isWrite
return $ if x == Authorized then Just r else Nothing
jsToHtml :: Javascript -> Html
jsToHtml (Javascript b) = preEscapedToMarkup $ toLazyText b
jelper :: JavascriptUrl url -> HtmlUrl url
jelper = fmap jsToHtml
-- | Convert a widget to a 'PageContent'.
widgetToPageContent :: (Eq (Route master), Yesod master)
=> GWidget sub master ()
-> GHandler sub master (PageContent (Route master))
widgetToPageContent w = do
master <- getYesod
((), GWData (Body body) (Last mTitle) scripts' stylesheets' style jscript (Head head')) <- unGWidget w
let title = maybe mempty unTitle mTitle
scripts = runUniqueList scripts'
stylesheets = runUniqueList stylesheets'
render <- getUrlRenderParams
let renderLoc x =
case x of
Nothing -> Nothing
Just (Left s) -> Just s
Just (Right (u, p)) -> Just $ render u p
css <- forM (Map.toList style) $ \(mmedia, content) -> do
let rendered = toLazyText $ content render
x <- addStaticContent "css" "text/css; charset=utf-8"
$ encodeUtf8 rendered
return (mmedia,
case x of
Nothing -> Left $ preEscapedToMarkup rendered
Just y -> Right $ either id (uncurry render) y)
jsLoc <-
case jscript of
Nothing -> return Nothing
Just s -> do
x <- addStaticContent "js" "text/javascript; charset=utf-8"
$ encodeUtf8 $ renderJavascriptUrl render s
return $ renderLoc x
-- modernizr should be at the end of the <head> http://www.modernizr.com/docs/#installing
-- the asynchronous loader means your page doesn't have to wait for all the js to load
let (mcomplete, asyncScripts) = asyncHelper render scripts jscript jsLoc
regularScriptLoad = [hamlet|
$newline never
$forall s <- scripts
^{mkScriptTag s}
$maybe j <- jscript
$maybe s <- jsLoc
<script src="#{s}">
$nothing
<script>^{jelper j}
|]
headAll = [hamlet|
$newline never
\^{head'}
$forall s <- stylesheets
^{mkLinkTag s}
$forall s <- css
$maybe t <- right $ snd s
$maybe media <- fst s
<link rel=stylesheet media=#{media} href=#{t}>
$nothing
<link rel=stylesheet href=#{t}>
$maybe content <- left $ snd s
$maybe media <- fst s
<style media=#{media}>#{content}
$nothing
<style>#{content}
$case jsLoader master
$of BottomOfBody
$of BottomOfHeadAsync asyncJsLoader
^{asyncJsLoader asyncScripts mcomplete}
$of BottomOfHeadBlocking
^{regularScriptLoad}
|]
let bodyScript = [hamlet|
$newline never
^{body}
^{regularScriptLoad}
|]
return $ PageContent title headAll (case jsLoader master of
BottomOfBody -> bodyScript
_ -> body)
where
renderLoc' render' (Local url) = render' url []
renderLoc' _ (Remote s) = s
addAttr x (y, z) = x ! customAttribute (textTag y) (toValue z)
mkScriptTag (Script loc attrs) render' =
foldl' addAttr TBH.script (("src", renderLoc' render' loc) : attrs) $ return ()
mkLinkTag (Stylesheet loc attrs) render' =
foldl' addAttr TBH.link
( ("rel", "stylesheet")
: ("href", renderLoc' render' loc)
: attrs
)
data ScriptLoadPosition master
= BottomOfBody
| BottomOfHeadBlocking
| BottomOfHeadAsync (BottomOfHeadAsync master)
type BottomOfHeadAsync master
= [Text] -- ^ urls to load asynchronously
-> Maybe (HtmlUrl (Route master)) -- ^ widget of js to run on async completion
-> (HtmlUrl (Route master)) -- ^ widget to insert at the bottom of <head>
left :: Either a b -> Maybe a
left (Left x) = Just x
left _ = Nothing
right :: Either a b -> Maybe b
right (Right x) = Just x
right _ = Nothing
jsonArray :: [Text] -> Html
jsonArray = unsafeLazyByteString . encode . Array . Vector.fromList . map String
-- | For use with setting 'jsLoader' to 'BottomOfHeadAsync'
loadJsYepnope :: Yesod master => Either Text (Route master) -> [Text] -> Maybe (HtmlUrl (Route master)) -> (HtmlUrl (Route master))
loadJsYepnope eyn scripts mcomplete =
[hamlet|
$newline never
$maybe yn <- left eyn
<script src=#{yn}>
$maybe yn <- right eyn
<script src=@{yn}>
$maybe complete <- mcomplete
<script>yepnope({load:#{jsonArray scripts},complete:function(){^{complete}}});
$nothing
<script>yepnope({load:#{jsonArray scripts}});
|]
asyncHelper :: (url -> [x] -> Text)
-> [Script (url)]
-> Maybe (JavascriptUrl (url))
-> Maybe Text
-> (Maybe (HtmlUrl url), [Text])
asyncHelper render scripts jscript jsLoc =
(mcomplete, scripts'')
where
scripts' = map goScript scripts
scripts'' =
case jsLoc of
Just s -> scripts' ++ [s]
Nothing -> scripts'
goScript (Script (Local url) _) = render url []
goScript (Script (Remote s) _) = s
mcomplete =
case jsLoc of
Just{} -> Nothing
Nothing ->
case jscript of
Nothing -> Nothing
Just j -> Just $ jelper j
yesodRender :: Yesod y
=> y
-> ResolvedApproot
-> Route y
-> [(Text, Text)] -- ^ url query string
-> Text
yesodRender y ar url params =
TE.decodeUtf8 $ toByteString $
fromMaybe
(joinPath y ar ps
$ params ++ params')
(urlRenderOverride y url)
where
(ps, params') = renderRoute url
resolveApproot :: Yesod master => master -> W.Request -> ResolvedApproot
resolveApproot master req =
case approot of
ApprootRelative -> ""
ApprootStatic t -> t
ApprootMaster f -> f master
ApprootRequest f -> f master req
defaultClientSessionBackend :: Yesod master => IO (SessionBackend master)
defaultClientSessionBackend = do
key <- CS.getKey CS.defaultKeyFile
let timeout = 120 -- 120 minutes
return $ clientSessionBackend key timeout
clientSessionBackend :: Yesod master
=> CS.Key -- ^ The encryption key
-> Int -- ^ Inactive session valitity in minutes
-> SessionBackend master
clientSessionBackend key timeout = SessionBackend
{ sbLoadSession = loadClientSession key timeout "_SESSION"
}
loadClientSession :: Yesod master
=> CS.Key
-> Int -- ^ timeout
-> S8.ByteString -- ^ session name
-> master
-> W.Request
-> UTCTime
-> IO (BackendSession, SaveSession)
loadClientSession key timeout sessionName master req now = return (sess, save)
where
sess = fromMaybe [] $ do
raw <- lookup "Cookie" $ W.requestHeaders req
val <- lookup sessionName $ parseCookies raw
let host = "" -- fixme, properly lock sessions to client address
decodeClientSession key now host val
save sess' now' = do
-- We should never cache the IV! Be careful!
iv <- liftIO CS.randomIV
return [AddCookie def
{ setCookieName = sessionName
, setCookieValue = sessionVal iv
, setCookiePath = Just (cookiePath master)
, setCookieExpires = Just expires
, setCookieDomain = cookieDomain master
, setCookieHttpOnly = True
}]
where
host = "" -- fixme, properly lock sessions to client address
expires = fromIntegral (timeout * 60) `addUTCTime` now'
sessionVal iv = encodeClientSession key iv expires host sess'
-- | Run a 'GHandler' completely outside of Yesod. This
-- function comes with many caveats and you shouldn't use it
-- unless you fully understand what it's doing and how it works.
--
-- As of now, there's only one reason to use this function at
-- all: in order to run unit tests of functions inside 'GHandler'
-- but that aren't easily testable with a full HTTP request.
-- Even so, it's better to use @wai-test@ or @yesod-test@ instead
-- of using this function.
--
-- This function will create a fake HTTP request (both @wai@'s
-- 'W.Request' and @yesod@'s 'Request') and feed it to the
-- @GHandler@. The only useful information the @GHandler@ may
-- get from the request is the session map, which you must supply
-- as argument to @runFakeHandler@. All other fields contain
-- fake information, which means that they can be accessed but
-- won't have any useful information. The response of the
-- @GHandler@ is completely ignored, including changes to the
-- session, cookies or headers. We only return you the
-- @GHandler@'s return value.
runFakeHandler :: (Yesod master, MonadIO m) =>
SessionMap
-> (master -> Logger)
-> master
-> GHandler master master a
-> m (Either ErrorResponse a)
runFakeHandler fakeSessionMap logger master handler = liftIO $ do
ret <- I.newIORef (Left $ InternalError "runFakeHandler: no result")
let handler' = do liftIO . I.writeIORef ret . Right =<< handler
return ()
let YesodApp yapp =
runHandler
handler'
(yesodRender master "")
Nothing
id
master
master
(fileUpload master)
(messageLoggerSource master $ logger master)
errHandler err =
YesodApp $ \_ _ _ session -> do
liftIO $ I.writeIORef ret (Left err)
return $ YARPlain
H.status500
[]
typePlain
(toContent ("runFakeHandler: errHandler" :: S8.ByteString))
session
fakeWaiRequest =
W.Request
{ W.requestMethod = "POST"
, W.httpVersion = H.http11
, W.rawPathInfo = "/runFakeHandler/pathInfo"
, W.rawQueryString = ""
, W.serverName = "runFakeHandler-serverName"
, W.serverPort = 80
, W.requestHeaders = []
, W.isSecure = False
, W.remoteHost = error "runFakeHandler-remoteHost"
, W.pathInfo = ["runFakeHandler", "pathInfo"]
, W.queryString = []
, W.requestBody = mempty
, W.vault = mempty
}
fakeRequest =
Request
{ reqGetParams = []
, reqCookies = []
, reqWaiRequest = fakeWaiRequest
, reqLangs = []
, reqToken = Just "NaN" -- not a nonce =)
, reqBodySize = 0
}
fakeContentType = []
_ <- runResourceT $ yapp errHandler fakeRequest fakeContentType fakeSessionMap
I.readIORef ret
{-# WARNING runFakeHandler "Usually you should *not* use runFakeHandler unless you really understand how it works and why you need it." #-}
|
piyush-kurur/yesod
|
yesod-core/Yesod/Internal/Core.hs
|
Haskell
|
mit
| 31,135
|
module MiniSequel.Adapter.PostgreSQL.Log
where
import qualified MiniSequel.Adapter.PostgreSQL as Adapter
--
-- exec con query = do
-- print query
-- Adapter.exec con query
--
-- takeModel con model = do
-- print model
-- Adapter.takeModel con model
|
TachoMex/MiniSequel
|
src/MiniSequel/Adapter/Log.hs
|
Haskell
|
mit
| 276
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.