code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS_GHC -F -pgmF htfpp #-}
{-# LANGUAGE ScopedTypeVariables #-}
module PlatesGenerationTest where
import Test.Framework
import PlatesGeneration
import qualified Data.Array.Repa as R
import qualified HeightMap.Base as HB
import qualified Data.Map.Strict as M
import qualified Data.List as L
import Geometry
import Control.Monad
test_generateInitialHeightMap = do
heightMap :: HB.HeightMap (HB.Point Float) <- generateInitialHeightMap 1 512 512
-- I would expect to hae 512x512 points all beteen 0.0 and 1.0
let points :: [HB.Point Float] = R.toList heightMap
let values :: [Float] = map HB.getHeight points
assertEqual (512 * 512) (length points)
let ma :: Float = maximum values
let mi :: Float = minimum values
assertEqual True (ma <= 1.0)
assertEqual True (mi >= 0.0)
test_toElevationMap = do
heightMap <- generateInitialHeightMap 1 100 200
let elevationMap = toElevationMap heightMap
let keys = L.sort $ M.keys elevationMap
let expectedKeys = L.sort [Point x y | x <- [0..99], y <- [0..199] ]
assertEqual (100*200) (length keys)
forM expectedKeys (\ek ->
assertEqualVerbose ("Missing "++ show ek) True (ek `elem` keys))
test_hbMapWidth = do
heightMap <- generateInitialHeightMap 1 123 456
assertEqual 123 (hbMapWidth heightMap)
test_hbMapHeight = do
heightMap <- generateInitialHeightMap 1 123 456
assertEqual 456 (hbMapHeight heightMap) | ftomassetti/hplatetectonics | test/PlatesGenerationTest.hs | apache-2.0 | 1,447 | 0 | 14 | 290 | 457 | 229 | 228 | 34 | 1 |
import Helpers.Factorials (binomial, factorial)
import Data.List (permutations, genericLength, sort, (\\))
import qualified Data.MemoCombinators as Memo
a332709T :: Integer -> Integer -> Integer
a332709T n k
| k < 3 = 0
| k > n = 0
| otherwise = sum $ map f [0..n-1] where
f i = coefficient * sum (map g [lower..upper]) where
lower = max 0 (i + k - n - 1)
upper = min i (k - 2)
coefficient = factorial (n - i - 1) * (-1)^i
g j = binomial (2*k-j-4) j * binomial (2*(n-k+1)-i+j) (i-j)
a332710 n = a332709T n $ (n + 3) `div` 2
(.+.) :: [Integer] -> [Integer] -> [Integer]
(.+.) p1 [] = p1
(.+.) [] p2 = p2
(.+.) (a:p1) (b:p2) = (a + b) : (p1 .+. p2)
(.*.) :: [Integer] -> [Integer] -> [Integer]
(.*.) p1 [] = []
(.*.) [] p2 = []
(.*.) p1 p2 = foldr1 (.+.) termwiseProduct where
termwiseProduct = map (\(i,x) -> replicate i 0 ++ map (*x) p2) $ zip [0..] p1
poly :: Integer -> [Integer]
poly = Memo.integral poly' where
poly' 0 = [1]
poly' 1 = [1,1]
poly' n = poly (n - 1) .+. ([0,1] .*. poly (n-2))
-- Takes a prefix (in ascending order) and gives the sizes of the blocks.
partitionFrom :: Integer -> [Integer] -> [Integer]
partitionFrom n prefix = lowerTriangular : upperTriangular : map exes regions where
prefix' = sort prefix
a_1 = head prefix'
a_n = last prefix'
m = genericLength prefix
exes (a, b)
| m < a = 2*b - 2*a - 2
| m < b - 1 = 2*b - 2*m - 3
| otherwise = 0
lowerTriangular
| a_1 /= 1 = 2*(n - a_n) + 1
| m < a_n = 2*(n - a_n)
| otherwise = 2*(n - a_n) - 1
upperTriangular = exes (1, a_1)
regions = zip prefix' (tail prefix')
-- Takes a prefix and gives the sizes of the blocks.
partitionFrom' n prefix = dropWhile (==0) $ sort $ partitionFrom n (sort prefix)
countPermutations :: Integer -> [Integer] -> Integer
countPermutations n prefix
| menageFailure = 0
| otherwise = altSeries $ zipWith (*) (map factorial [m,m-1..0]) boardPolynomial where
menageFailure = isIllegalMenage n prefix
m = n - genericLength prefix
restrictionPartition = dropWhile (<1) $ sort $ partitionFrom n prefix
boardPolynomial = foldr ((.*.) . poly) [1] restrictionPartition
altSeries :: Num a => [a] -> a
altSeries xs = sum (zipWith (*) (cycle [1, -1]) xs)
isIllegalMenage :: Integral a => a -> [a] -> Bool
isIllegalMenage n prefix = any illegalLetter $ zip [1..] prefix where
illegalLetter (i, a_i) = i == a_i || (a_i - i) `mod` n == 1
nextDerangement :: Integer -> [Integer] -> [Integer]
nextDerangement n prefix
| null candidates = nextDerangement n knownPrefix
| otherwise = knownPrefix ++ [head candidates] where
x = last prefix
knownPrefix = init prefix
index = genericLength prefix
illegalLetters = map (\i -> (i - 1) `mod` n + 1) [index, index + 1]
candidates = foldl (\\) [x+1..n] [knownPrefix] --, illegalLetters]
appendNewLetter :: Integer -> [Integer] -> [Integer]
appendNewLetter n prefix
| null candidates = nextDerangement n $ init prefix
| otherwise = prefix ++ [head candidates] where
index = genericLength prefix + 1
illegalLetters = map (\i -> (i - 1) `mod` n + 1) [index, index + 1]
candidates = foldl (\\) [1..n] [prefix, illegalLetters]
-- Finds the i-th menage permutation in S_n.
richardsFunction :: Integer -> Integer -> [Integer]
richardsFunction n k = recurse 0 [3] where
recurse c known
| c' < k = recurse c' $ nextDerangement n known
| c' == k && genericLength known == n = known
| otherwise = recurse c $ appendNewLetter n known where
c' = c + countPermutations n known
-- 1: [3,1,5,2,4]
-- 2: [3,4,5,1,2]
-- 3: [3,5,1,2,4]
-- 4: [3,5,2,1,4]
-- 5: [4,1,5,2,3]
-- 6: [4,1,5,3,2]
-- 7: [4,5,1,2,3]
-- 8: [4,5,1,3,2]
-- 9: [4,5,2,1,3]
-- 10: [5,1,2,3,4]
-- 11: [5,4,1,2,3]
-- 12: [5,4,1,3,2]
-- 13: [5,4,2,1,3]
| peterokagey/haskellOEIS | src/Sandbox/Richard/menage.hs | apache-2.0 | 3,806 | 0 | 17 | 854 | 1,689 | 897 | 792 | 81 | 3 |
{-# LANGUAGE Haskell2010 #-}
module Simple (foo) where
-- | This is foo.
foo :: t
foo = undefined
| haskell/haddock | latex-test/src/Simple/Simple.hs | bsd-2-clause | 99 | 0 | 4 | 20 | 21 | 14 | 7 | 4 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
module Objective.C.Selector
(
-- * Selectors
Selector(..)
, isMapped
-- * Arbitrary selectors
, Sel(..)
) where
import Control.Monad
import Data.Data
import Data.Hashable
import Foreign.C.String
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable
import Objective.C.Prim
import Objective.C.Util
import qualified System.IO.Unsafe as Unsafe
import Text.Read
foreign import ccall unsafe "objc/objc.h" sel_isMapped :: Sel -> IO CBool
foreign import ccall unsafe "objc/objc.h" sel_getName :: Sel -> CString
foreign import ccall unsafe "objc/objc.h" sel_getUid :: CString -> IO Sel
-- Selectors
class Named a => Selector a where
sel :: a -> Sel
isMapped :: Selector a => a -> IO Bool
isMapped = fmap toBool . sel_isMapped . sel
instance Selector String where
sel n = Unsafe.unsafePerformIO $ withCString n sel_getUid
-- An unknown Selector
newtype Sel = Sel (Ptr ObjcSelector) deriving (Eq,Ord,Typeable,Data,Nil,Storable)
instance Hashable Sel where
hashWithSalt n (Sel s) = n `hashWithSalt` (fromIntegral (ptrToIntPtr s) :: Int)
instance Named Sel where
name = Unsafe.unsafePerformIO . peekCString . sel_getName
instance Selector Sel where
sel = id
instance Show Sel where
showsPrec d s
| isNil s = showString "nil"
| otherwise = showParen (d > 10) $ showString "sel " . showsPrec 10 (name s)
instance Read Sel where
readPrec = parens
( prec 10 $ do
Ident "sel" <- lexP
s <- readPrec
return $! sel (s :: String)
`mplus` do
Ident "nil" <- lexP
return nil
)
| ekmett/objective-c | Objective/C/Selector.hs | bsd-3-clause | 1,764 | 0 | 14 | 350 | 519 | 277 | 242 | 50 | 1 |
module Sexy.Functions.Bool (
fromBool
, toBool
, (&&)
, (||)
, not
) where
import Sexy.Core
fromBool :: (BoolC b, BoolC b') => b -> b'
fromBool = bool true false
toBool :: (BoolC b) => b -> Bool
toBool = fromBool
(&&) :: BoolC b => b -> b -> b
x && y = bool y x x
(||) :: BoolC b => b -> b -> b
x || y = bool x y x
not :: BoolC b => b -> b
not = bool false true
| DanBurton/sexy | src/Sexy/Functions/Bool.hs | bsd-3-clause | 382 | 0 | 7 | 111 | 196 | 107 | 89 | 17 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Fragment.SystemFw.Rules.Type.Infer.SyntaxDirected (
SystemFwInferTypeConstraint
, systemFwInferTypeInput
) where
import Data.Proxy (Proxy(..))
import Bound (abstract1, instantiate1)
import Control.Monad.State (MonadState)
import Control.Monad.Reader (MonadReader, local)
import Control.Monad.Except (MonadError)
import Control.Lens (review, preview, (%~))
import Control.Lens.Wrapped (_Wrapped)
import Data.Functor.Classes (Eq1)
import Rules.Kind.Infer.Common
import Rules.Type.Infer.Common
import Rules.Type.Infer.SyntaxDirected
import Ast.Kind
import Ast.Type
import Ast.Type.Var
import Ast.Term
import Ast.Term.Var
import Ast.Error.Common
import Context.Type
import Context.Term
import Data.Functor.Rec
import Fragment.SystemFw.Ast.Type
import Fragment.SystemFw.Ast.Error
import Fragment.SystemFw.Ast.Term
inferTmLam :: SystemFwInferTypeConstraint e w s r m ki ty pt tm a
=> Proxy (MonadProxy e w s r m)
-> (Term ki ty pt tm a -> m (Type ki ty a))
-> Term ki ty pt tm a
-> Maybe (m (Type ki ty a))
inferTmLam _ inferFn tm = do
(tyArg, s) <- preview _TmLam tm
return $ do
v <- freshTmVar
let tmF = review _Wrapped $ instantiate1 (review (_AVar . _ATmVar) v) s
tyRet <- local (termContext %~ insertTerm v tyArg) $ inferFn tmF
return $ review _TyArr (tyArg, tyRet)
inferTmApp :: SystemFwInferTypeConstraint e w s r m ki ty pt tm a
=> Proxy (MonadProxy e w s r m)
-> (Term ki ty pt tm a -> m (Type ki ty a))
-> Term ki ty pt tm a
-> Maybe (m (Type ki ty a))
inferTmApp m inferFn tm = do
(tmF, tmX) <- preview _TmApp tm
return $ do
tyF <- inferFn tmF
(tyArg, tyRet) <- expectTyArr tyF
tyX <- inferFn tmX
expectTypeEq m (Proxy :: Proxy ITSyntax) tyArg tyX
return tyRet
inferTmLamTy :: SystemFwInferTypeConstraint e w s r m ki ty pt tm a
=> Proxy (MonadProxy e w s r m)
-> (Term ki ty pt tm a -> m (Type ki ty a))
-> Term ki ty pt tm a
-> Maybe (m (Type ki ty a))
inferTmLamTy _ inferFn tm = do
(ki, tmF) <- preview _TmLamTy tm
return $ do
v <- freshTyVar
ty <- local (typeContext %~ insertType v ki) $ inferFn (review _Wrapped . instantiate1 (review (_AVar . _ATyVar) v) $ tmF)
return . review _TyAll $ (ki, abstract1 v ty)
inferTmAppTy :: SystemFwInferTypeConstraint e w s r m ki ty pt tm a
=> Proxy (MonadProxy e w s r m)
-> (Type ki ty a -> m (Kind ki))
-> (Term ki ty pt tm a -> m (Type ki ty a))
-> Term ki ty pt tm a
-> Maybe (m (Type ki ty a))
inferTmAppTy m inferKindFn inferTypeFn tm = do
(tmF, tyX) <- preview _TmAppTy tm
return $ do
tyF <- inferTypeFn tmF
(ki, s) <- expectTyAll tyF
mkCheckKind m (Proxy :: Proxy ki) (Proxy :: Proxy ty) (Proxy :: Proxy a) _ inferKindFn tyX ki
return $ instantiate1 tyX s
type SystemFwInferTypeConstraint e w s r m ki ty pt tm a = (Ord a, EqRec (ty ki), Eq1 ki, MonadState s m, HasTmVarSupply s, ToTmVar a, HasTyVarSupply s, ToTyVar a, MonadReader r m, HasTypeContext r ki a, HasTermContext r ki ty a, AsTySystemFw ki ty, MonadError e m, AsUnexpectedKind e (Kind ki), AsExpectedTypeEq e ki ty a, AsExpectedTyArr e ki ty a, AsExpectedTyAll e ki ty a, AsTmSystemFw ki ty pt tm, AsUnknownTypeError e, AsUnexpectedType e ki ty a, AsExpectedTypeAllEq e ki ty a)
systemFwInferTypeInput :: SystemFwInferTypeConstraint e w s r m ki ty pt tm a
=> Proxy (MonadProxy e w s r m)
-> Proxy i
-> InferTypeInput e w s r m m ki ty pt tm a
systemFwInferTypeInput m _ =
InferTypeInput
[]
[ InferTypeRecurse $ inferTmLam m
, InferTypeRecurse $ inferTmLamTy m
, InferTypeRecurse $ inferTmApp m
, InferTypeRecurseKind $ inferTmAppTy m
]
[]
| dalaing/type-systems | src/Fragment/SystemFw/Rules/Type/Infer/SyntaxDirected.hs | bsd-3-clause | 4,182 | 0 | 20 | 1,050 | 1,556 | 798 | 758 | 93 | 1 |
{-# LANGUAGE LambdaCase #-}
module Transformations.CountVariableUse where
import Data.Functor.Foldable as Foldable
import Data.Set (Set)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Monoid
import qualified Data.Foldable
import Transformations.Util
import Grin.Grin
countVariableUse :: Exp -> Map Name Int
countVariableUse exp = appEndo (cata folder exp) mempty where
folder e = Data.Foldable.fold e `mappend` foldNameUseExpF (\name -> Endo $ Map.unionWith (+) $ Map.singleton name 1) e
nonlinearVariables :: Exp -> Set Name
nonlinearVariables = Map.keysSet . Map.filter (>1) . countVariableUse
| andorp/grin | grin/src/Transformations/CountVariableUse.hs | bsd-3-clause | 624 | 0 | 14 | 87 | 192 | 108 | 84 | 15 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Main where
import Control.Concurrent.MVar
import Control.Concurrent.STM.TQueue
( newTQueueIO
, readTQueue
, writeTQueue
)
import Control.Exception (SomeException)
import Control.DeepSeq (NFData)
import Control.Distributed.Process hiding (call, send, catch, sendChan, wrapMessage)
import Control.Distributed.Process.Node
import Control.Distributed.Process.Extras hiding (__remoteTable, monitor)
import Control.Distributed.Process.Async hiding (check)
import Control.Distributed.Process.ManagedProcess hiding (reject, Message)
import qualified Control.Distributed.Process.ManagedProcess.Server.Priority as P (Message)
import Control.Distributed.Process.ManagedProcess.Server.Priority hiding (Message)
import qualified Control.Distributed.Process.ManagedProcess.Server.Gen as Gen
( dequeue
, continue
, lift
)
import Control.Distributed.Process.SysTest.Utils
import Control.Distributed.Process.Extras.Time
import Control.Distributed.Process.Extras.Timer hiding (runAfter)
import Control.Distributed.Process.Serializable()
import Control.Monad
import Control.Monad.Catch (catch)
import Data.Binary
import Data.Either (rights)
import Data.List (isInfixOf)
import Data.Maybe (isNothing, isJust)
import Data.Typeable (Typeable)
#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import TestUtils
import ManagedProcessCommon
import qualified Network.Transport as NT
import GHC.Generics (Generic)
-- utilities
server :: Process (ProcessId, (MVar ExitReason))
server = mkServer Terminate
mkServer :: UnhandledMessagePolicy
-> Process (ProcessId, (MVar ExitReason))
mkServer policy =
let s = standardTestServer policy
p = s `prioritised` ([] :: [DispatchPriority ()])
in do
exitReason <- liftIO $ newEmptyMVar
pid <- spawnLocal $ do
catch ((pserve () (statelessInit Infinity) p >> stash exitReason ExitNormal)
`catchesExit` [
(\_ msg -> do
mEx <- unwrapMessage msg :: Process (Maybe ExitReason)
case mEx of
Nothing -> return Nothing
Just r -> stash exitReason r >>= return . Just
)
])
(\(e :: SomeException) -> stash exitReason $ ExitOther (show e))
return (pid, exitReason)
explodingServer :: ProcessId
-> Process (ProcessId, MVar ExitReason)
explodingServer pid =
let srv = explodingTestProcess pid
pSrv = srv `prioritised` ([] :: [DispatchPriority s])
in do
exitReason <- liftIO newEmptyMVar
spid <- spawnLocal $ do
catch (pserve () (statelessInit Infinity) pSrv >> stash exitReason ExitNormal)
(\(e :: SomeException) -> do
-- say "died in handler..."
stash exitReason $ ExitOther (show e))
return (spid, exitReason)
data GetState = GetState
deriving (Typeable, Generic, Show, Eq)
instance Binary GetState where
instance NFData GetState where
data MyAlarmSignal = MyAlarmSignal
deriving (Typeable, Generic, Show, Eq)
instance Binary MyAlarmSignal where
instance NFData MyAlarmSignal where
mkPrioritisedServer :: Process ProcessId
mkPrioritisedServer =
let p = procDef `prioritised` ([
prioritiseInfo_ (\MyAlarmSignal -> setPriority 10)
, prioritiseCast_ (\(_ :: String) -> setPriority 2)
, prioritiseCall_ (\(cmd :: String) -> (setPriority (length cmd)) :: Priority ())
] :: [DispatchPriority [Either MyAlarmSignal String]]
) :: PrioritisedProcessDefinition [(Either MyAlarmSignal String)]
in spawnLocal $ pserve () (initWait Infinity) p
where
initWait :: Delay
-> InitHandler () [Either MyAlarmSignal String]
initWait d () = do
() <- expect
return $ InitOk [] d
procDef :: ProcessDefinition [(Either MyAlarmSignal String)]
procDef =
defaultProcess {
apiHandlers = [
handleCall (\s GetState -> reply (reverse s) s)
, handleCall (\s (cmd :: String) -> reply () ((Right cmd):s))
, handleCast (\s (cmd :: String) -> continue ((Right cmd):s))
]
, infoHandlers = [
handleInfo (\s (sig :: MyAlarmSignal) -> continue ((Left sig):s))
]
, unhandledMessagePolicy = Drop
, timeoutHandler = \_ _ -> stop $ ExitOther "timeout"
} :: ProcessDefinition [(Either MyAlarmSignal String)]
mkOverflowHandlingServer :: (PrioritisedProcessDefinition Int ->
PrioritisedProcessDefinition Int)
-> Process ProcessId
mkOverflowHandlingServer modIt =
let p = procDef `prioritised` ([
prioritiseCall_ (\GetState -> setPriority 99 :: Priority Int)
, prioritiseCast_ (\(_ :: String) -> setPriority 1)
] :: [DispatchPriority Int]
) :: PrioritisedProcessDefinition Int
in spawnLocal $ pserve () (initWait Infinity) (modIt p)
where
initWait :: Delay
-> InitHandler () Int
initWait d () = return $ InitOk 0 d
procDef :: ProcessDefinition Int
procDef =
defaultProcess {
apiHandlers = [
handleCall (\s GetState -> reply s s)
, handleCast (\s (_ :: String) -> continue $ s + 1)
]
} :: ProcessDefinition Int
launchStmServer :: CallHandler () String String -> Process StmServer
launchStmServer handler = do
(inQ, replyQ) <- liftIO $ do
cIn <- newTQueueIO
cOut <- newTQueueIO
return (cIn, cOut)
let procDef = statelessProcess {
externHandlers = [
handleCallExternal
(readTQueue inQ)
(writeTQueue replyQ)
handler
]
, apiHandlers = [
action (\() -> stop_ ExitNormal)
]
}
let p = procDef `prioritised` ([
prioritiseCast_ (\() -> setPriority 99 :: Priority ())
, prioritiseCast_ (\(_ :: String) -> setPriority 100)
] :: [DispatchPriority ()]
) :: PrioritisedProcessDefinition ()
pid <- spawnLocal $ pserve () (statelessInit Infinity) p
return $ StmServer pid inQ replyQ
launchStmOverloadServer :: Process (ProcessId, ControlPort String)
launchStmOverloadServer = do
cc <- newControlChan :: Process (ControlChannel String)
let cp = channelControlPort cc
let procDef = statelessProcess {
externHandlers = [
handleControlChan_ cc (\(_ :: String) -> continue_)
]
, apiHandlers = [
handleCast (\s sp -> sendChan sp () >> continue s)
]
}
let p = procDef `prioritised` ([
prioritiseCast_ (\() -> setPriority 99 :: Priority ())
] :: [DispatchPriority ()]
) :: PrioritisedProcessDefinition ()
pid <- spawnLocal $ pserve () (statelessInit Infinity) p
return (pid, cp)
data Foo = Foo deriving (Show)
launchFilteredServer :: ProcessId -> Process (ProcessId, ControlPort (SendPort Int))
launchFilteredServer us = do
cc <- newControlChan :: Process (ControlChannel (SendPort Int))
let cp = channelControlPort cc
let procDef = defaultProcess {
externHandlers = [
handleControlChan cc (\s (p :: SendPort Int) -> sendChan p s >> continue s)
]
, apiHandlers = [
handleCast (\s sp -> sendChan sp () >> continue s)
, handleCall_ (\(s :: String) -> return s)
, handleCall_ (\(i :: Int) -> return i)
]
, unhandledMessagePolicy = DeadLetter us
} :: ProcessDefinition Int
let p = procDef `prioritised` ([
prioritiseCast_ (\() -> setPriority 1 :: Priority ())
, prioritiseCall_ (\(_ :: String) -> setPriority 100 :: Priority String)
] :: [DispatchPriority Int]
) :: PrioritisedProcessDefinition Int
let rejectUnchecked =
rejectApi Foo :: Int -> P.Message String String -> Process (Filter Int)
let p' = p {
filters = [
store (+1)
, ensure (>0) -- a bit pointless, but we're just checking the API
, check $ api_ (\(s :: String) -> return $ "checked-" `isInfixOf` s) rejectUnchecked
, check $ info (\_ (_ :: MonitorRef, _ :: ProcessId) -> return False) $ reject Foo
, refuse ((> 10) :: Int -> Bool)
]
}
pid <- spawnLocal $ pserve 0 (\c -> return $ InitOk c Infinity) p'
return (pid, cp)
testStupidInfiniteLoop :: TestResult Bool -> Process ()
testStupidInfiniteLoop result = do
let def = statelessProcess {
apiHandlers = [
handleCast (\_ sp -> eval $ do q <- processQueue
m <- Gen.dequeue
Gen.lift $ sendChan sp (length q, m)
Gen.continue)
]
, infoHandlers = [
handleInfo (\_ (m :: String) -> eval $ do enqueue (wrapMessage m)
Gen.continue)
]
} :: ProcessDefinition ()
let prio = def `prioritised` []
pid <- spawnLocal $ pserve () (statelessInit Infinity) prio
-- this message should create an infinite loop
send pid "fooboo"
(sp, rp) <- newChan :: Process (SendPort (Int, Maybe Message), ReceivePort (Int, Maybe Message))
cast pid sp
(i, m) <- receiveChan rp
cast pid sp
(i', m') <- receiveChan rp
stash result $ (i == 1 && isJust m && i' == 0 && isNothing m')
testFilteringBehavior :: TestResult Bool -> Process ()
testFilteringBehavior result = do
us <- getSelfPid
(sp, rp) <- newChan
(pid, cp) <- launchFilteredServer us
mRef <- monitor pid
sendControlMessage cp sp
r <- receiveChan rp :: Process Int
when (r > 1) $ stash result False >> die "we're done..."
Left _ <- safeCall pid "bad-input" :: Process (Either ExitReason String)
send pid (mRef, us) -- server doesn't like this, dead letters it...
-- back to us
void $ receiveWait [ matchIf (\(m, p) -> m == mRef && p == us) return ]
sendControlMessage cp sp
r2 <- receiveChan rp :: Process Int
when (r2 < 3) $ stash result False >> die "we're done again..."
-- server also doesn't like this, and sends it right back (via \DeadLetter us/)
send pid (25 :: Int)
m <- receiveWait [ matchIf (== 25) return ] :: Process Int
stash result $ m == 25
kill pid "done"
testServerSwap :: TestResult Bool -> Process ()
testServerSwap result = do
us <- getSelfPid
let def2 = statelessProcess { apiHandlers = [ handleCast (\s (i :: Int) -> send us (i, i+1) >> continue s)
, handleCall_ (\(i :: Int) -> return (i * 5))
]
, unhandledMessagePolicy = Drop -- otherwise `call` would fail
}
let def = statelessProcess
{ apiHandlers = [ handleCall_ (\(m :: String) -> return m) ]
, infoHandlers = [ handleInfo (\s () -> become def2 s) ]
} `prioritised` []
pid <- spawnLocal $ pserve () (statelessInit Infinity) def
m1 <- call pid "hello there"
let a1 = m1 == "hello there"
send pid () --changeover
m2 <- callTimeout pid "are you there?" (seconds 5) :: Process (Maybe String)
let a2 = isNothing m2
cast pid (45 :: Int)
res <- receiveWait [ matchIf (\(i :: Int) -> i == 45) (return . Left)
, match (\(_ :: Int, j :: Int) -> return $ Right j) ]
let a3 = res == (Right 46)
m4 <- call pid (20 :: Int) :: Process Int
let a4 = m4 == 100
stash result $ a1 && a2 && a3 && a4
testSafeExecutionContext :: TestResult Bool -> Process ()
testSafeExecutionContext result = do
let t = (asTimeout $ seconds 5)
(sigSp, rp) <- newChan
(wp, lp) <- newChan
let def = statelessProcess
{ apiHandlers = [ handleCall_ (\(m :: String) -> stranded rp wp Nothing >> return m) ]
, infoHandlers = [ handleInfo (\s (m :: String) -> stranded rp wp (Just m) >> continue s) ]
, exitHandlers = [ handleExit (\_ s (_ :: String) -> continue s) ]
} `prioritised` []
let spec = def { filters = [
safe (\_ (_ :: String) -> True)
, apiSafe (\_ (_ :: String) (_ :: Maybe String) -> True)
]
}
pid <- spawnLocal $ pserve () (statelessInit Infinity) spec
send pid "hello" -- pid can't process this as it's stuck waiting on rp
sleep $ seconds 3
exit pid "ooops" -- now we force an exit signal once the receiveWait finishes
sendChan sigSp () -- and allow the receiveWait to complete
send pid "hi again"
-- at this point, "hello" should still be in the backing queue/mailbox
sleep $ seconds 3
-- We should still be seeing "hello", since the 'safe' block saved us from
-- losing a message when we handled and swallowed the exit signal.
-- We should not see "hi again" until after "hello" has been processed
h <- receiveChanTimeout t lp
-- say $ "first response: " ++ (show h)
let a1 = h == (Just "hello")
sleep $ seconds 3
-- now we should have "hi again" waiting in the mailbox...
sendChan sigSp () -- we must release the handler a second time...
h2 <- receiveChanTimeout t lp
-- say $ "second response: " ++ (show h2)
let a2 = h2 == (Just "hi again")
void $ spawnLocal $ call pid "reply-please" >>= sendChan wp
-- the call handler should be stuck waiting on rp
Nothing <- receiveChanTimeout (asTimeout $ seconds 2) lp
-- now let's force an exit, then release the handler to see if it runs again...
exit pid "ooops2"
sleep $ seconds 2
sendChan sigSp ()
h3 <- receiveChanTimeout t lp
-- say $ "third response: " ++ (show h3)
let a3 = h3 == (Just "reply-please")
stash result $ a1 && a2 && a3
where
stranded :: ReceivePort () -> SendPort String -> Maybe String -> Process ()
stranded gate chan str = do
-- say $ "stranded with " ++ (show str)
void $ receiveWait [ matchChan gate return ]
sleep $ seconds 1
case str of
Nothing -> return ()
Just s -> sendChan chan s
testExternalTimedOverflowHandling :: TestResult Bool -> Process ()
testExternalTimedOverflowHandling result = do
(pid, cp) <- launchStmOverloadServer -- default 10k mailbox drain limit
wrk <- spawnLocal $ mapM_ (sendControlMessage cp . show) ([1..500000] :: [Int])
sleep $ milliSeconds 250 -- give the worker time to start spamming the server...
(sp, rp) <- newChan
cast pid sp -- tell the server we're expecting a reply
-- it might take "a while" for us to get through the first 10k messages
-- from our chatty friend wrk, before we finally get our control message seen
-- by the reader/listener loop, and in fact timing wise we don't even know when
-- our message will arrive, since we're racing with wrk to communicate with
-- the server. It's important therefore to give sufficient time for the right
-- conditions to occur so that our message is finally received and processed,
-- yet we don't want to lock up the build for 10-20 mins either. This value
-- of 30 seconds seems like a reasonable compromise.
answer <- receiveChanTimeout (asTimeout $ seconds 30) rp
stash result $ answer == Just ()
kill wrk "done"
kill pid "done"
testExternalCall :: TestResult Bool -> Process ()
testExternalCall result = do
let txt = "hello stm-call foo"
srv <- launchStmServer (\st (msg :: String) -> reply msg st)
echoStm srv txt >>= stash result . (== Right txt)
killProc srv "done"
testTimedOverflowHandling :: TestResult Bool -> Process ()
testTimedOverflowHandling result = do
pid <- mkOverflowHandlingServer (\s -> s { recvTimeout = RecvTimer $ within 3 Seconds })
wrk <- spawnLocal $ mapM_ (cast pid . show) ([1..500000] :: [Int])
sleep $ seconds 1 -- give the worker time to start spamming us...
cast pid "abc" -- just getting in line here...
st <- call pid GetState :: Process Int
-- the result of GetState is a list of messages in reverse insertion order
stash result $ st > 0
kill wrk "done"
kill pid "done"
testOverflowHandling :: TestResult Bool -> Process ()
testOverflowHandling result = do
pid <- mkOverflowHandlingServer (\s -> s { recvTimeout = RecvMaxBacklog 100 })
wrk <- spawnLocal $ mapM_ (cast pid . show) ([1..50000] :: [Int])
sleep $ seconds 1
cast pid "abc" -- just getting in line here...
st <- call pid GetState :: Process Int
-- the result of GetState is a list of messages in reverse insertion order
stash result $ st > 0
kill wrk "done"
kill pid "done"
testInfoPrioritisation :: TestResult Bool -> Process ()
testInfoPrioritisation result = do
pid <- mkPrioritisedServer
-- the server (pid) is configured to wait for () during its init
-- so we can fill up its mailbox with String messages, and verify
-- that the alarm signal (which is prioritised *above* these)
-- actually gets processed first despite the delivery order
cast pid "hello"
cast pid "prioritised"
cast pid "world"
-- note that these have to be a "bare send"
send pid MyAlarmSignal
-- tell the server it can move out of init and start processing messages
send pid ()
st <- call pid GetState :: Process [Either MyAlarmSignal String]
-- the result of GetState is a list of messages in reverse insertion order
case head st of
Left MyAlarmSignal -> stash result True
_ -> stash result False
testUserTimerHandling :: TestResult Bool -> Process ()
testUserTimerHandling result = do
us <- getSelfPid
let p = (procDef us) `prioritised` ([
prioritiseInfo_ (\MyAlarmSignal -> setPriority 100)
] :: [DispatchPriority ()]
) :: PrioritisedProcessDefinition ()
pid <- spawnLocal $ pserve () (statelessInit Infinity) p
cast pid ()
expect >>= stash result . (== MyAlarmSignal)
kill pid "goodbye..."
where
procDef :: ProcessId -> ProcessDefinition ()
procDef us =
statelessProcess {
apiHandlers = [
handleCast (\s () -> evalAfter (seconds 5) MyAlarmSignal s)
]
, infoHandlers = [
handleInfo (\s (sig :: MyAlarmSignal) -> send us sig >> continue s)
]
, unhandledMessagePolicy = Drop
} :: ProcessDefinition ()
testCallPrioritisation :: TestResult Bool -> Process ()
testCallPrioritisation result = do
pid <- mkPrioritisedServer
asyncRefs <- (mapM (callAsync pid)
["first", "the longest", "commands", "we do prioritise"])
:: Process [Async ()]
-- NB: This sleep is really important - the `init' function is waiting
-- (selectively) on the () signal to go, and if it receives this *before*
-- the async worker has had a chance to deliver the longest string message,
-- our test will fail. Such races are /normal/ given that the async worker
-- runs in another process and delivery order between multiple processes
-- is undefined (and in practise, partially depenendent on the scheduler)
sleep $ seconds 1
send pid ()
_ <- mapM wait asyncRefs :: Process [AsyncResult ()]
st <- call pid GetState :: Process [Either MyAlarmSignal String]
let ms = rights st
stash result $ ms == ["we do prioritise", "the longest", "commands", "first"]
tests :: NT.Transport -> IO [Test]
tests transport = do
localNode <- newLocalNode transport initRemoteTable
return [
testGroup "basic server functionality matches un-prioritised processes" [
testCase "basic call with explicit server reply"
(delayedAssertion
"expected a response from the server"
localNode (Just "foo") (testBasicCall $ wrap server))
, testCase "basic call with implicit server reply"
(delayedAssertion
"expected n * 2 back from the server"
localNode (Just 4) (testBasicCall_ $ wrap server))
, testCase "basic deferred call handling"
(delayedAssertion "expected a response sent via replyTo"
localNode (AsyncDone "Hello There") testDeferredCallResponse)
, testCase "basic cast with manual send and explicit server continue"
(delayedAssertion
"expected pong back from the server"
localNode (Just "pong") (testBasicCast $ wrap server))
, testCase "cast and explicit server timeout"
(delayedAssertion
"expected the server to stop after the timeout"
localNode (Just $ ExitOther "timeout") (testControlledTimeout $ wrap server))
, testCase "unhandled input when policy = Terminate"
(delayedAssertion
"expected the server to stop upon receiving unhandled input"
localNode (Just $ ExitOther "UnhandledInput")
(testTerminatePolicy $ wrap server))
, testCase "unhandled input when policy = Drop"
(delayedAssertion
"expected the server to ignore unhandled input and exit normally"
localNode Nothing (testDropPolicy $ wrap (mkServer Drop)))
, testCase "unhandled input when policy = DeadLetter"
(delayedAssertion
"expected the server to forward unhandled messages"
localNode (Just ("UNSOLICITED_MAIL", 500 :: Int))
(testDeadLetterPolicy $ \p -> mkServer (DeadLetter p)))
, testCase "incoming messages are ignored whilst hibernating"
(delayedAssertion
"expected the server to remain in hibernation"
localNode True (testHibernation $ wrap server))
, testCase "long running call cancellation"
(delayedAssertion "expected to get AsyncCancelled"
localNode True (testKillMidCall $ wrap server))
, testCase "server rejects call"
(delayedAssertion "expected server to send CallRejected"
localNode (ExitOther "invalid-call") (testServerRejectsMessage $ wrap server))
, testCase "simple exit handling"
(delayedAssertion "expected handler to catch exception and continue"
localNode Nothing (testSimpleErrorHandling $ explodingServer))
, testCase "alternative exit handlers"
(delayedAssertion "expected handler to catch exception and continue"
localNode Nothing (testAlternativeErrorHandling $ explodingServer))
]
, testGroup "Prioritised Mailbox Handling" [
testCase "Info Message Prioritisation"
(delayedAssertion "expected the info handler to be prioritised"
localNode True testInfoPrioritisation)
, testCase "Call Message Prioritisation"
(delayedAssertion "expected the longest strings to be prioritised"
localNode True testCallPrioritisation)
, testCase "Size-Based Mailbox Overload Management"
(delayedAssertion "expected the server loop to stop reading the mailbox"
localNode True testOverflowHandling)
, testCase "Timeout-Based Mailbox Overload Management"
(delayedAssertion "expected the server loop to stop reading the mailbox"
localNode True testTimedOverflowHandling)
]
, testGroup "Advanced Server Interactions" [
testCase "using callSTM to manage non-CH interactions"
(delayedAssertion
"expected the server to reply back via the TQueue"
localNode True testExternalCall)
, testCase "Timeout-Based Overload Management with Control Channels"
(delayedAssertion "expected the server loop to reply"
localNode True testExternalTimedOverflowHandling)
, testCase "Complex pre/before filters"
(delayedAssertion "expected verifiable filter actions"
localNode True testFilteringBehavior)
, testCase "Firing internal timeouts"
(delayedAssertion "expected our info handler to run after the timeout"
localNode True testUserTimerHandling)
, testCase "Creating 'Safe' Handlers"
(delayedAssertion "expected our handler to run on the old message"
localNode True testSafeExecutionContext)
, testCase "Swapping ProcessDefinitions at runtime"
(delayedAssertion "expected our handler to exist in the new handler list"
localNode True testServerSwap)
, testCase "Accessing the internal process implementation"
(delayedAssertion "it should allow us to modify the internal q"
localNode True testStupidInfiniteLoop)
]
]
main :: IO ()
main = testMain $ tests
| haskell-distributed/distributed-process-client-server | tests/TestPrioritisedProcess.hs | bsd-3-clause | 25,244 | 3 | 26 | 7,188 | 6,493 | 3,320 | 3,173 | 468 | 2 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Web.RTBBidder.Protocol.Adx.BidRequest.Video.VideoProtocol (VideoProtocol(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified GHC.Generics as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data VideoProtocol = UNKNOWN_VIDEO_PROTOCOL
| VAST_1_0
| VAST_2_0
| VAST_3_0
| VAST_1_0_WRAPPER
| VAST_2_0_WRAPPER
| VAST_3_0_WRAPPER
| VAST_4_0
| VAST_4_0_WRAPPER
| DAAST_1_0
| DAAST_1_0_WRAPPER
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data,
Prelude'.Generic)
instance P'.Mergeable VideoProtocol
instance Prelude'.Bounded VideoProtocol where
minBound = UNKNOWN_VIDEO_PROTOCOL
maxBound = DAAST_1_0_WRAPPER
instance P'.Default VideoProtocol where
defaultValue = UNKNOWN_VIDEO_PROTOCOL
toMaybe'Enum :: Prelude'.Int -> P'.Maybe VideoProtocol
toMaybe'Enum 0 = Prelude'.Just UNKNOWN_VIDEO_PROTOCOL
toMaybe'Enum 1 = Prelude'.Just VAST_1_0
toMaybe'Enum 2 = Prelude'.Just VAST_2_0
toMaybe'Enum 3 = Prelude'.Just VAST_3_0
toMaybe'Enum 4 = Prelude'.Just VAST_1_0_WRAPPER
toMaybe'Enum 5 = Prelude'.Just VAST_2_0_WRAPPER
toMaybe'Enum 6 = Prelude'.Just VAST_3_0_WRAPPER
toMaybe'Enum 7 = Prelude'.Just VAST_4_0
toMaybe'Enum 8 = Prelude'.Just VAST_4_0_WRAPPER
toMaybe'Enum 9 = Prelude'.Just DAAST_1_0
toMaybe'Enum 10 = Prelude'.Just DAAST_1_0_WRAPPER
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum VideoProtocol where
fromEnum UNKNOWN_VIDEO_PROTOCOL = 0
fromEnum VAST_1_0 = 1
fromEnum VAST_2_0 = 2
fromEnum VAST_3_0 = 3
fromEnum VAST_1_0_WRAPPER = 4
fromEnum VAST_2_0_WRAPPER = 5
fromEnum VAST_3_0_WRAPPER = 6
fromEnum VAST_4_0 = 7
fromEnum VAST_4_0_WRAPPER = 8
fromEnum DAAST_1_0 = 9
fromEnum DAAST_1_0_WRAPPER = 10
toEnum
= P'.fromMaybe
(Prelude'.error "hprotoc generated code: toEnum failure for type Web.RTBBidder.Protocol.Adx.BidRequest.Video.VideoProtocol")
. toMaybe'Enum
succ UNKNOWN_VIDEO_PROTOCOL = VAST_1_0
succ VAST_1_0 = VAST_2_0
succ VAST_2_0 = VAST_3_0
succ VAST_3_0 = VAST_1_0_WRAPPER
succ VAST_1_0_WRAPPER = VAST_2_0_WRAPPER
succ VAST_2_0_WRAPPER = VAST_3_0_WRAPPER
succ VAST_3_0_WRAPPER = VAST_4_0
succ VAST_4_0 = VAST_4_0_WRAPPER
succ VAST_4_0_WRAPPER = DAAST_1_0
succ DAAST_1_0 = DAAST_1_0_WRAPPER
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Web.RTBBidder.Protocol.Adx.BidRequest.Video.VideoProtocol"
pred VAST_1_0 = UNKNOWN_VIDEO_PROTOCOL
pred VAST_2_0 = VAST_1_0
pred VAST_3_0 = VAST_2_0
pred VAST_1_0_WRAPPER = VAST_3_0
pred VAST_2_0_WRAPPER = VAST_1_0_WRAPPER
pred VAST_3_0_WRAPPER = VAST_2_0_WRAPPER
pred VAST_4_0 = VAST_3_0_WRAPPER
pred VAST_4_0_WRAPPER = VAST_4_0
pred DAAST_1_0 = VAST_4_0_WRAPPER
pred DAAST_1_0_WRAPPER = DAAST_1_0
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Web.RTBBidder.Protocol.Adx.BidRequest.Video.VideoProtocol"
instance P'.Wire VideoProtocol where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB VideoProtocol
instance P'.MessageAPI msg' (msg' -> VideoProtocol) VideoProtocol where
getVal m' f' = f' m'
instance P'.ReflectEnum VideoProtocol where
reflectEnum
= [(0, "UNKNOWN_VIDEO_PROTOCOL", UNKNOWN_VIDEO_PROTOCOL), (1, "VAST_1_0", VAST_1_0), (2, "VAST_2_0", VAST_2_0),
(3, "VAST_3_0", VAST_3_0), (4, "VAST_1_0_WRAPPER", VAST_1_0_WRAPPER), (5, "VAST_2_0_WRAPPER", VAST_2_0_WRAPPER),
(6, "VAST_3_0_WRAPPER", VAST_3_0_WRAPPER), (7, "VAST_4_0", VAST_4_0), (8, "VAST_4_0_WRAPPER", VAST_4_0_WRAPPER),
(9, "DAAST_1_0", DAAST_1_0), (10, "DAAST_1_0_WRAPPER", DAAST_1_0_WRAPPER)]
reflectEnumInfo _
= P'.EnumInfo
(P'.makePNF (P'.pack ".Adx.BidRequest.Video.VideoProtocol") ["Web", "RTBBidder", "Protocol"] ["Adx", "BidRequest", "Video"]
"VideoProtocol")
["Web", "RTBBidder", "Protocol", "Adx", "BidRequest", "Video", "VideoProtocol.hs"]
[(0, "UNKNOWN_VIDEO_PROTOCOL"), (1, "VAST_1_0"), (2, "VAST_2_0"), (3, "VAST_3_0"), (4, "VAST_1_0_WRAPPER"),
(5, "VAST_2_0_WRAPPER"), (6, "VAST_3_0_WRAPPER"), (7, "VAST_4_0"), (8, "VAST_4_0_WRAPPER"), (9, "DAAST_1_0"),
(10, "DAAST_1_0_WRAPPER")]
instance P'.TextType VideoProtocol where
tellT = P'.tellShow
getT = P'.getRead | hiratara/hs-rtb-bidder | src/Web/RTBBidder/Protocol/Adx/BidRequest/Video/VideoProtocol.hs | bsd-3-clause | 4,969 | 0 | 11 | 902 | 1,185 | 657 | 528 | 106 | 1 |
module Diff.Compare where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (zipWithM)
import Data.Function (on)
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Catalog
import qualified Elm.Compiler.Module as Module
import qualified Elm.Compiler.Type as Type
import qualified Elm.Docs as Docs
import qualified Elm.Package as Package
import qualified Manager
computeChanges
:: [Docs.Documentation]
-> Package.Name
-> Package.Version
-> Manager.Manager PackageChanges
computeChanges newDocs name version =
do oldDocs <- Catalog.documentation name version
return (diffPackages oldDocs newDocs)
-- CHANGE MAGNITUDE
data Magnitude
= PATCH
| MINOR
| MAJOR
deriving (Eq, Ord, Show)
bumpBy :: PackageChanges -> Package.Version -> Package.Version
bumpBy changes version =
case packageChangeMagnitude changes of
PATCH ->
Package.bumpPatch version
MINOR ->
Package.bumpMinor version
MAJOR ->
Package.bumpMajor version
packageChangeMagnitude :: PackageChanges -> Magnitude
packageChangeMagnitude pkgChanges =
maximum (added : removed : map moduleChangeMagnitude moduleChanges)
where
moduleChanges =
Map.elems (modulesChanged pkgChanges)
removed =
if null (modulesRemoved pkgChanges) then
PATCH
else
MAJOR
added =
if null (modulesAdded pkgChanges) then
PATCH
else
MINOR
moduleChangeMagnitude :: ModuleChanges -> Magnitude
moduleChangeMagnitude moduleChanges =
maximum
[ changeMagnitude (adtChanges moduleChanges)
, changeMagnitude (aliasChanges moduleChanges)
, changeMagnitude (valueChanges moduleChanges)
]
changeMagnitude :: Changes k v -> Magnitude
changeMagnitude (Changes added changed removed)
| Map.size removed > 0 = MAJOR
| Map.size changed > 0 = MAJOR
| Map.size added > 0 = MINOR
| otherwise = PATCH
-- DETECT CHANGES
data PackageChanges = PackageChanges
{ modulesAdded :: [String]
, modulesChanged :: Map.Map String ModuleChanges
, modulesRemoved :: [String]
}
data ModuleChanges = ModuleChanges
{ adtChanges :: Changes String ([String], Map.Map String [Type.Type])
, aliasChanges :: Changes String ([String], Type.Type)
, valueChanges :: Changes String Type.Type
}
data Changes k v = Changes
{ added :: Map.Map k v
, changed :: Map.Map k (v,v)
, removed :: Map.Map k v
}
diffPackages :: [Docs.Documentation] -> [Docs.Documentation] -> PackageChanges
diffPackages oldDocs newDocs =
let
filterOutPatches chngs =
Map.filter (\chng -> moduleChangeMagnitude chng /= PATCH) chngs
(Changes added changed removed) =
getChanges
(\_ _ -> False)
(docsToModules oldDocs)
(docsToModules newDocs)
in
PackageChanges
(Map.keys added)
(filterOutPatches (Map.map (uncurry diffModule) changed))
(Map.keys removed)
data Module = Module
{ adts :: Map.Map String ([String], Map.Map String [Type.Type])
, aliases :: Map.Map String ([String], Type.Type)
, values :: Map.Map String Type.Type
, version :: Docs.Version
}
docsToModules :: [Docs.Documentation] -> Map.Map String Module
docsToModules docs =
Map.fromList (map docToModule docs)
docToModule :: Docs.Documentation -> (String, Module)
docToModule (Docs.Documentation name _ aliases' unions' values' generatedByVersion) =
(,) (Module.nameToString name) $ Module
{ adts =
Map.fromList $ flip map unions' $ \union ->
( Docs.unionName union
, (Docs.unionArgs union, Map.fromList (Docs.unionCases union))
)
, aliases =
Map.fromList $ flip map aliases' $ \alias ->
(Docs.aliasName alias, (Docs.aliasArgs alias, Docs.aliasType alias))
, values =
Map.fromList $ flip map values' $ \value ->
(Docs.valueName value, Docs.valueType value)
, version =
generatedByVersion
}
diffModule :: Module -> Module -> ModuleChanges
diffModule (Module adts aliases values version) (Module adts' aliases' values' version') =
let
ignoreOrigin =
case (version, version') of
(Docs.NonCanonicalTypes, _) -> True
(_, Docs.NonCanonicalTypes) -> True
(_, _) -> False
in
ModuleChanges
(getChanges (isEquivalentAdt ignoreOrigin) adts adts')
(getChanges (isEquivalentType ignoreOrigin) aliases aliases')
(getChanges (\t t' -> isEquivalentType ignoreOrigin ([],t) ([],t')) values values')
getChanges :: (Ord k) => (v -> v -> Bool) -> Map.Map k v -> Map.Map k v -> Changes k v
getChanges isEquivalent old new =
Changes
{ added =
Map.difference new old
, changed =
Map.filter
(not . uncurry isEquivalent)
(Map.intersectionWith (,) old new)
, removed =
Map.difference old new
}
isEquivalentAdt
:: Bool
-> ([String], Map.Map String [Type.Type])
-> ([String], Map.Map String [Type.Type])
-> Bool
isEquivalentAdt ignoreOrigin (oldVars, oldCtors) (newVars, newCtors) =
Map.size oldCtors == Map.size newCtors
&& and (zipWith (==) (Map.keys oldCtors) (Map.keys newCtors))
&& and (Map.elems (Map.intersectionWith equiv oldCtors newCtors))
where
equiv :: [Type.Type] -> [Type.Type] -> Bool
equiv oldTypes newTypes =
let
allEquivalent =
zipWith
(isEquivalentType ignoreOrigin)
(map ((,) oldVars) oldTypes)
(map ((,) newVars) newTypes)
in
length oldTypes == length newTypes
&& and allEquivalent
isEquivalentType :: Bool -> ([String], Type.Type) -> ([String], Type.Type) -> Bool
isEquivalentType ignoreOrigin (oldVars, oldType) (newVars, newType) =
case diffType ignoreOrigin oldType newType of
Nothing ->
False
Just renamings ->
length oldVars == length newVars
&& isEquivalentRenaming (zip oldVars newVars ++ renamings)
-- TYPES
diffType :: Bool -> Type.Type -> Type.Type -> Maybe [(String,String)]
diffType ignoreOrigin oldType newType =
let
go = diffType ignoreOrigin
in
case (oldType, newType) of
(Type.Var oldName, Type.Var newName) ->
Just [(oldName, newName)]
(Type.Type oldName, Type.Type newName) ->
let
format =
if ignoreOrigin then dropOrigin else id
in
if format oldName == format newName then
Just []
else
Nothing
(Type.Lambda a b, Type.Lambda a' b') ->
(++)
<$> go a a'
<*> go b b'
(Type.App t ts, Type.App t' ts') ->
if length ts /= length ts' then
Nothing
else
(++)
<$> go t t'
<*> (concat <$> zipWithM go ts ts')
(Type.Record fields maybeExt, Type.Record fields' maybeExt') ->
case (maybeExt, maybeExt') of
(Nothing, Just _) ->
Nothing
(Just _, Nothing) ->
Nothing
(Nothing, Nothing) ->
diffFields ignoreOrigin fields fields'
(Just ext, Just ext') ->
(++)
<$> go ext ext'
<*> diffFields ignoreOrigin fields fields'
(_, _) ->
Nothing
diffFields :: Bool -> [(String, Type.Type)] -> [(String, Type.Type)] -> Maybe [(String,String)]
diffFields ignoreOrigin rawFields rawFields'
| length rawFields /= length rawFields' = Nothing
| or (zipWith ((/=) `on` fst) fields fields') = Nothing
| otherwise =
concat <$> zipWithM (diffType ignoreOrigin `on` snd) fields fields'
where
fields = sort rawFields
fields' = sort rawFields'
sort =
List.sortBy (compare `on` fst)
dropOrigin :: String -> String
dropOrigin name =
Text.unpack (snd (Text.breakOnEnd (Text.pack ".") (Text.pack name)))
-- TYPE VARIABLES
isEquivalentRenaming :: [(String,String)] -> Bool
isEquivalentRenaming varPairs =
case mapM verify renamings of
Nothing ->
False
Just verifiedRenamings ->
allUnique (map snd verifiedRenamings)
where
renamings =
Map.toList (foldr insert Map.empty varPairs)
insert (old,new) dict =
Map.insertWith (++) old [new] dict
verify (old, news) =
case news of
[] -> Nothing
new : rest ->
if all (new ==) rest then
Just (old, new)
else
Nothing
allUnique list =
length list == Set.size (Set.fromList list)
compatableVars :: String -> String -> Bool
compatableVars old new =
case (categorizeVar old, categorizeVar new) of
(Comparable, Comparable) -> True
(Appendable, Appendable) -> True
(Number , Number ) -> True
(Comparable, Appendable) -> True
(Number , Comparable) -> True
(_, Var) -> True
(_, _) -> False
data TypeVarCategory
= Comparable
| Appendable
| Number
| Var
categorizeVar :: String -> TypeVarCategory
categorizeVar varName
| any (/= '\'') primes = Var
| name == "comparable" = Comparable
| name == "appendable" = Appendable
| name == "number" = Number
| otherwise = Var
where
(name, primes) =
break (=='\'') varName
| laszlopandy/elm-package | src/Diff/Compare.hs | bsd-3-clause | 9,455 | 0 | 16 | 2,635 | 3,039 | 1,611 | 1,428 | 255 | 12 |
module Web.Handler.HomePage
(handleMonad)
where
import qualified Web.View.HomePage as HomePageView
import qualified Service.Users
import qualified Web.WebHandler
handleMonad :: Web.WebHandler.HandlerMonad ()
handleMonad = do
user <- Web.WebHandler.callService Service.Users.getUser
Web.WebHandler.renderView $ HomePageView.render $ user
return ()
| stevechy/HaskellCakeStore | Web/Handler/HomePage.hs | bsd-3-clause | 372 | 0 | 9 | 58 | 91 | 52 | 39 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import ECC.Tester
import ECC.Types
import Data.Monoid
import qualified ECC.Code.Unencoded as Unencoded
import qualified ECC.Code.LDPC.Reference.Orig as OrigReference
import qualified ECC.Code.LDPC.Reference.Sparse as Sparse
import qualified ECC.Code.LDPC.Reference.Min as Min
import qualified ECC.Code.LDPC.Reference.SparseMin as SparseMin
import qualified ECC.Code.LDPC.Model as Model
import qualified ECC.Code.LDPC.ElimTanh as ElimTanh
import qualified ECC.Code.LDPC.Fast.Arraylet as Arraylet
import qualified ECC.Code.LDPC.Fast.ArrayletMin as ArrayletMin
import qualified ECC.Code.LDPC.Fast.CachedMult as CachedMult
import qualified ECC.Code.LDPC.GPU.CachedMult as GPUCachedMult
import qualified ECC.Code.LDPC.GPU.Reference as GPUReference
import qualified ECC.Code.LDPC.Zero as Zero
import qualified ECC.Code.LDPC.GPU.CUDA.CachedMult as CUDACachedMult
import qualified ECC.Code.LDPC.GPU.CUDA.Arraylet1 as CUDAArraylet1
import qualified ECC.Code.LDPC.GPU.CUDA.Arraylet2 as CUDAArraylet2
import qualified ECC.Code.LDPC.GPU.CUDA.TwoArrays as TwoArrays
import Data.Array.Accelerate.LLVM.PTX
import Data.Array.Accelerate.Debug
import System.Metrics
import System.Remote.Monitoring
codes :: Code
codes = Unencoded.code <> OrigReference.code <> Sparse.code <> Min.code <> SparseMin.code <> Model.code <> ElimTanh.code
<> Arraylet.code <> ArrayletMin.code <> CachedMult.code <> GPUCachedMult.code <> GPUReference.code <> Zero.code <> CUDACachedMult.code <> CUDAArraylet1.code <> CUDAArraylet2.code <> TwoArrays.code
-- usage: ./Main 0 2 4 6 8 0 bpsk
-- or, to run the LDPC reference implementation, at a single EBNO = 2.2
-- ./Main 2.2 ldpc/reference/jpl.1K/20
main :: IO ()
main = do
-- store <- initAccMetrics
-- registerGcMetrics store
-- server <- forkServerWith store "localhost" 8000
-- registerPinnedAllocator
eccMain codes eccPrinter
| ku-fpg/ecc-ldpc | main/Main.hs | bsd-3-clause | 1,930 | 0 | 21 | 237 | 370 | 256 | 114 | 32 | 1 |
module Data.Set.AsSet
( module Data.Set.AsSet
) where
-- generated by https://github.com/rvion/ride/tree/master/jetpack-gen
import qualified Data.Set as I
-- set_delete :: forall a. Ord a => a -> Set a -> Set a
set_delete = I.delete
-- set_deleteAt :: forall a. Int -> Set a -> Set a
set_deleteAt = I.deleteAt
-- set_deleteFindMax :: forall a. Set a -> (a, Set a)
set_deleteFindMax = I.deleteFindMax
-- set_deleteFindMin :: forall a. Set a -> (a, Set a)
set_deleteFindMin = I.deleteFindMin
-- set_deleteMax :: forall a. Set a -> Set a
set_deleteMax = I.deleteMax
-- set_deleteMin :: forall a. Set a -> Set a
set_deleteMin = I.deleteMin
-- set_difference :: forall a. Ord a => Set a -> Set a -> Set a
set_difference = I.difference
-- set_elemAt :: forall a. Int -> Set a -> a
set_elemAt = I.elemAt
-- set_elems :: forall a. Set a -> [a]
set_elems = I.elems
-- set_empty :: forall a. Set a
set_empty = I.empty
-- set_filter :: forall a. (a -> Bool) -> Set a -> Set a
set_filter = I.filter
-- set_findIndex :: forall a. Ord a => a -> Set a -> Int
set_findIndex = I.findIndex
-- set_findMax :: forall a. Set a -> a
set_findMax = I.findMax
-- set_findMin :: forall a. Set a -> a
set_findMin = I.findMin
-- set_fold :: forall a b. (a -> b -> b) -> b -> Set a -> b
set_fold = I.fold
-- set_foldl :: forall a b. (a -> b -> a) -> a -> Set b -> a
set_foldl = I.foldl
-- set_foldl' :: forall a b. (a -> b -> a) -> a -> Set b -> a
set_foldl' = I.foldl'
-- set_foldr :: forall a b. (a -> b -> b) -> b -> Set a -> b
set_foldr = I.foldr
-- set_foldr' :: forall a b. (a -> b -> b) -> b -> Set a -> b
set_foldr' = I.foldr'
-- set_fromAscList :: forall a. Eq a => [a] -> Set a
set_fromAscList = I.fromAscList
-- set_fromDistinctAscList :: forall a. [a] -> Set a
set_fromDistinctAscList = I.fromDistinctAscList
-- set_fromList :: forall a. Ord a => [a] -> Set a
set_fromList = I.fromList
-- set_insert :: forall a. Ord a => a -> Set a -> Set a
set_insert = I.insert
-- set_intersection :: forall a. Ord a => Set a -> Set a -> Set a
set_intersection = I.intersection
-- set_isProperSubsetOf :: forall a. Ord a => Set a -> Set a -> Bool
set_isProperSubsetOf = I.isProperSubsetOf
-- set_isSubsetOf :: forall a. Ord a => Set a -> Set a -> Bool
set_isSubsetOf = I.isSubsetOf
-- set_lookupGE :: forall a. Ord a => a -> Set a -> Maybe a
set_lookupGE = I.lookupGE
-- set_lookupGT :: forall a. Ord a => a -> Set a -> Maybe a
set_lookupGT = I.lookupGT
-- set_lookupIndex :: forall a. Ord a => a -> Set a -> Maybe Int
set_lookupIndex = I.lookupIndex
-- set_lookupLE :: forall a. Ord a => a -> Set a -> Maybe a
set_lookupLE = I.lookupLE
-- set_lookupLT :: forall a. Ord a => a -> Set a -> Maybe a
set_lookupLT = I.lookupLT
-- set_map :: forall a b. Ord b => (a -> b) -> Set a -> Set b
set_map = I.map
-- set_mapMonotonic :: forall a b. (a -> b) -> Set a -> Set b
set_mapMonotonic = I.mapMonotonic
-- set_maxView :: forall a. Set a -> Maybe (a, Set a)
set_maxView = I.maxView
-- set_member :: forall a. Ord a => a -> Set a -> Bool
set_member = I.member
-- set_minView :: forall a. Set a -> Maybe (a, Set a)
set_minView = I.minView
-- set_notMember :: forall a. Ord a => a -> Set a -> Bool
set_notMember = I.notMember
-- set_null :: forall a. Set a -> Bool
set_null = I.null
-- set_partition :: forall a. (a -> Bool) -> Set a -> (Set a, Set a)
set_partition = I.partition
-- set_showTree :: forall a. Show a => Set a -> String
set_showTree = I.showTree
-- set_showTreeWith :: forall a. Show a => Bool -> Bool -> Set a -> String
set_showTreeWith = I.showTreeWith
-- set_singleton :: forall a. a -> Set a
set_singleton = I.singleton
-- set_size :: forall a. Set a -> Int
set_size = I.size
-- set_split :: forall a. Ord a => a -> Set a -> (Set a, Set a)
set_split = I.split
-- set_splitMember :: forall a. Ord a => a -> Set a -> (Set a, Bool, Set a)
set_splitMember = I.splitMember
-- set_splitRoot :: forall a. Set a -> [Set a]
set_splitRoot = I.splitRoot
-- set_toAscList :: forall a. Set a -> [a]
set_toAscList = I.toAscList
-- set_toDescList :: forall a. Set a -> [a]
set_toDescList = I.toDescList
-- set_toList :: forall a. Set a -> [a]
set_toList = I.toList
-- set_union :: forall a. Ord a => Set a -> Set a -> Set a
set_union = I.union
-- set_unions :: forall a. Ord a => [Set a] -> Set a
set_unions = I.unions
-- set_valid :: forall a. Ord a => Set a -> Bool
set_valid = I.valid
type SetSet a = I.Set a
| rvion/ride | jetpack/src/Data/Set/AsSet.hs | bsd-3-clause | 4,434 | 0 | 6 | 923 | 453 | 285 | 168 | 56 | 1 |
module Main where
import Animations (
Behavior(AndThen))
import Animations.Pure (
Push(Wait), wait, waitForever, race,
Pull, at, sample, Time(Time))
import Animations.Prelude (
unfold)
import Linear (
(*^), (^+^), V2(V2))
import Data.These (
These(This,That,These))
import Control.Concurrent (
threadDelay)
data Ball = Ball (V2 Rational) (V2 Rational)
deriving (Show, Eq)
data Wall = HorizontalWall Rational | VerticalWall Rational
deriving (Show, Eq)
data Collision = NoCollision | HorizontalCollision | VerticalCollision
deriving (Show, Eq)
rolling :: Ball -> Pull Ball
rolling (Ball x v) = at (\t -> Ball (x ^+^ t *^ v) v)
ballRadius :: Rational
ballRadius = 1
collision :: Wall -> Ball -> Push Collision
collision (HorizontalWall p1) (Ball (V2 x1 _) (V2 v1 _)) =
case compare v1 0 of
GT -> let t = (p1 - x1 - ballRadius) / v1
in waitForeverIfPast t HorizontalCollision
EQ -> waitForever
LT -> let t = (p1 - x1 + ballRadius) / v1
in waitForeverIfPast t HorizontalCollision
collision (VerticalWall p2) (Ball (V2 _ x2) (V2 _ v2)) =
case compare v2 0 of
GT -> let t = (p2 - x2 - ballRadius) / v2
in waitForeverIfPast t VerticalCollision
EQ -> waitForever
LT -> let t = (p2 - x2 + ballRadius) / v2
in waitForeverIfPast t VerticalCollision
waitForeverIfPast :: Rational -> a -> Push a
waitForeverIfPast t a
| t > 0 = wait t a
| otherwise = waitForever
collide :: Collision -> Ball -> Ball
collide NoCollision ball =
ball
collide HorizontalCollision (Ball x (V2 v1 v2)) =
Ball x (V2 (negate v1) v2)
collide VerticalCollision (Ball x (V2 v1 v2)) =
Ball x (V2 v1 (negate v2))
collideList :: [Collision] -> Ball -> Ball
collideList collisions ball = foldr collide ball collisions
raceList :: [Push a] -> Push [a]
raceList [] = waitForever
raceList (p : ps) = fmap theseLists (race p (raceList ps)) where
theseLists :: These a [a] -> [a]
theseLists (This a) = [a]
theseLists (That as) = as
theseLists (These a as) = a : as
bouncing :: Ball -> Push Ball
bouncing ball =
fmap (uncurry collideList) (
sample nextCollisions (rolling ball)) where
nextCollisions = raceList [
collision wall1 ball,
collision wall2 ball,
collision wall3 ball,
collision wall4 ball]
wall1 :: Wall
wall1 = HorizontalWall 10
wall2 :: Wall
wall2 = HorizontalWall (negate 10)
wall3 :: Wall
wall3 = VerticalWall 10
wall4 :: Wall
wall4 = VerticalWall (negate 10)
ball1 :: Ball
ball1 = Ball (V2 0 0) (V2 7 3)
runPushBehavior :: (Show a) => Behavior Push a -> IO x
runPushBehavior (a `AndThen` (Wait (Time t) ab)) = do
threadDelay (round (t * 1000000))
putStrLn (show t ++ ": " ++ show a)
runPushBehavior ab
main :: IO ()
main = runPushBehavior (unfold bouncing ball1)
| phischu/animations | src/BallExample.hs | bsd-3-clause | 2,793 | 0 | 15 | 618 | 1,184 | 616 | 568 | 85 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Language.Wart.Type.Graphic
( module Language.Wart.Graphic
, module Language.Wart.Type.Syntax
, Node (..)
, Binder (..)
, kind
, bot
, app
, extend
) where
import Control.Applicative (Applicative, (<$>), (<*>))
import qualified Control.Applicative as Applicative
import Control.Lens (Choice, Effective, Lens', _1, _2, act, view)
#ifndef HLINT
import Control.Lens.Operators
#endif
import qualified Control.Lens.Tuple.Generics as Tuple
import Control.Monad.Reader
import Control.Monad.Supply
import Control.Monad.UnionFind
import Data.Functor.Identity
import Data.Proxy
import Data.Tagged
import Data.Traversable (sequenceA)
import GHC.Generics (Generic)
import Language.Wart.BindingFlag
import Language.Wart.Graphic
import Language.Wart.Kind.Graphic (Kind, (~>), row, star)
import Language.Wart.Scheme.Syntax (Scheme)
import Language.Wart.Type.Syntax
import Type.Nat
data instance Node Type v =
Node
{-# UNPACK #-} !Int
(Type (v (Node Type v)))
(v BindingFlag)
(v (Binder Type v))
(v (Node Kind v)) deriving Generic
instance Functor f => HasLabel f (Node Type v)
instance HasTerm (Node Type)
instance Functor f => HasBindingFlag (->) f (Node Type v) (v BindingFlag)
instance Functor f => HasBinder (->) f (Node Type v) (v (Binder Type v))
data instance Binder Type v
= Scheme (Node Scheme v)
| Type (v (Node Type v)) deriving Generic
instance (Choice p, Applicative f) => AsScheme p f (Binder Type)
instance AsType (Binder Type)
instance (Effective m r f, MonadUnionFind v m,
HasLabel (Applicative.Const Int) (Node Scheme v))
=> HasLabel f (Binder Type v) where
label = act $ \ case
Scheme s -> return $ s^.label
Type v_t -> v_t^!contents.label
kind :: Lens' (Node Type v) (v (Node Kind v))
kind = Tuple.ix (Proxy :: Proxy N4)
bot :: (MonadSupply Int m, MonadUnionFind v m)
=> ReaderT (BindingFlag, Binder Kind v) m (v (Node Kind v))
-> ReaderT (BindingFlag, Binder Type v) m (v (Node Type v))
bot = type' Bot
const' :: (MonadSupply Int m, MonadUnionFind v m)
=> Const
-> ReaderT (BindingFlag, Binder Kind v) m (v (Node Kind v))
-> ReaderT (BindingFlag, Binder Type v) m (v (Node Type v))
const' = type' . Const
app :: (MonadSupply Int m, MonadUnionFind v m)
=> ReaderT (BindingFlag, Binder Type v) m (v (Node Type v))
-> ReaderT (BindingFlag, Binder Type v) m (v (Node Type v))
-> ReaderT (BindingFlag, Binder Kind v) m (v (Node Kind v))
-> ReaderT (BindingFlag, Binder Type v) m (v (Node Type v))
app m_f m_a = type' $ App m_f m_a
extend :: (MonadSupply Int m, MonadUnionFind v m)
=> Label -> ReaderT (BindingFlag, Binder Type v) m (v (Node Type v))
extend l = const' (Extend l) (star ~> row ~> row)
type' :: (MonadSupply Int m, MonadUnionFind v m)
=> Type (ReaderT (BindingFlag, Binder Type v) m (v (Node Type v)))
-> ReaderT (BindingFlag, Binder Kind v) m (v (Node Kind v))
-> ReaderT (BindingFlag, Binder Type v) m (v (Node Type v))
type' c m_k =
new =<<
Node <$>
supply <*>
sequenceA c <*>
(new =<< view _1) <*>
(new =<< view _2) <*>
withReaderT (_2 %~ cloneBinder) m_k
#ifndef HLINT
cloneBinder :: (AsScheme Tagged Identity s, AsType s) => Binder Type v -> s v
cloneBinder = \ case
Scheme n_s -> _Scheme#n_s
Type v_t -> _Type#v_t
#endif
| sonyandy/wart | src/Language/Wart/Type/Graphic.hs | bsd-3-clause | 3,647 | 0 | 13 | 746 | 1,447 | 774 | 673 | -1 | -1 |
module Network.Riak.HTTP (
put, tryPut, putWithRandomKey, putWithIndexes, get, tryGet, delete,
tryDelete, lookupIndex, lookupIndexRange, tryClients, getListOfKeys,
defaultClient, Types.host, Types.port, Client,
Bucket, Key, IndexKey, IndexValue (..), IndexTag,
module Network.Riak.HTTP.MapReduce
) where
import Network.Riak.HTTP.Types
import Network.Riak.HTTP.Types as Types
import Network.Riak.HTTP.Internal
import Network.Riak.HTTP.MapReduce
import Network.HTTP
import Network.HTTP.Base
import Network.URI
import Data.ByteString.Lazy.Char8 (ByteString)
put :: Client -> Bucket -> Key -> ByteString -> IO (Either String ())
put client bucket key value = putWithIndexes client bucket key [] value
putWithRandomKey :: Client -> Bucket -> ByteString -> IO (Either String Key)
putWithRandomKey = putWithContentTypeWithRandomKey "text/plain"
-- | Try a put, finding a client where it succeeds
tryPut :: [Client] -> Bucket -> Key -> ByteString -> IO (Either String ())
tryPut clients bucket key value = tryClients clients $ \client ->
put client bucket key value
putWithIndexes :: Client -> Bucket -> Key -> [IndexTag] -> ByteString
-> IO (Either String ())
putWithIndexes = putWithContentType "text/plain"
| ThoughtLeadr/Riak-Haskell-HTTP-Client | src/Network/Riak/HTTP.hs | bsd-3-clause | 1,246 | 0 | 13 | 195 | 365 | 209 | 156 | 24 | 1 |
module GraphDraw.TestFgl where
import Data.Graph.Inductive.Example
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive
import System.Random
import Control.Monad
import Data.List
import Data.Maybe
import System.IO.Unsafe
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
initGraph :: a -> ((Double,Double),(Double,Double))
initGraph x = ((0.0,0.0),(lx,ly))
where
(x,y) = unsafePerformIO randomPos
(lx,ly) = (fromIntegral x/1.0 , fromIntegral y/1.0)
randomList :: Int -> StdGen -> [Int]
randomList n = take n . unfoldr (Just . random)
randomPos = do
seed1 <- newStdGen
seed2 <- newStdGen
let [l1] = randomList 1 seed1
let [l2] = randomList 1 seed2
let ps = (fromIntegral (l1 `mod` 50), fromIntegral (l2 `mod` 50))
return ps
funGraphMap :: DynGraph gr => a -> gr ((Double,Double),(Double,Double)) b-> Int ->((Double,Double),(Double,Double))
funGraphMap old g n = ((fx,fy),(lx,ly))
where
neighborNodes = neighbors g n
nonNeighborNodes = (nodes g) \\ neighborNodes
attF = foldr tupleAdd (0.0,0.0)(map (\x -> attForce g n x 2) neighborNodes)
repF = foldr tupleAdd (0.0,0.0)(map (\x -> attForce g x n 1) nonNeighborNodes)
(fx,fy) = tupleAdd attF repF
Just ((fx1,fy1),(lx,ly)) = lab g n
-- (lx,ly) = (3.5,3.9)
tupleAdd :: (Double,Double) -> (Double,Double) -> (Double,Double)
tupleAdd (x1,y1) (x2,y2) = (x1+x2,y1+y2)
nmapMod :: DynGraph gr => (a -> gr a b -> Node -> c) ->gr a b -> gr a b -> gr c b
nmapMod f g = gmap (\(p,v,l,s)->(p,v,f l g v,s))
attForce :: DynGraph gr => gr ((Double,Double),(Double,Double)) b -> Int -> Int -> Int -> (Double,Double)
attForce g n1 n2 typeOf = force
where Just ((fx1,fy1),(x1,y1)) = lab g n1
Just ((fx2,fy2),(x2,y2)) = lab g n2
dist = sqrt ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
d = if (dist/=0) then dist else 2
effect = if(typeOf==1)then -1*(2*log d) else (1/sqrt d)
force = (effect*(x1-x2)/d ,effect*(y1-y2)/d)
updateGraph :: DynGraph gr => gr ((Double,Double),(Double,Double)) b -> Int -> gr ((Double,Double),(Double,Double)) b
updateGraph inGraph 0 = inGraph
updateGraph inGraph n = outGraph
where outFGraph = nmapMod funGraphMap inGraph inGraph
outGraphloop = nmap updateLoc outFGraph
outGraph = updateGraph outGraphloop (n-1)
updateLoc :: ((Double,Double),(Double,Double)) -> ((Double,Double),(Double,Double))
updateLoc l = newl
where
((f1,f2),(x,y)) = l
newl = ((f1,f2),(f1,f2))
repeatGraphUpdate :: DynGraph gr => gr a b -> Int -> gr ((Double,Double),(Double,Double)) b
repeatGraphUpdate g n = retGraph
where fstGraph = nmap initGraph g
retGraph = updateGraph fstGraph n
repeatUpdate update 0 = return update
repeatUpdate update n =
do
updated <- updateGraph update
repeatUpdate updated (n-1)
giveList :: DynGraph gr => gr a b -> Int -> [(Double,Double)]
giveList graph n = list
where
g = repeatGraphUpdate graph n
list = map (\(Just (x,y))-> y) (map (lab g) (nodes g))
| prash471/GraphDraw | GraphDraw/TestFgl.hs | bsd-3-clause | 3,057 | 0 | 13 | 646 | 1,501 | 830 | 671 | 67 | 3 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.BeginEnd
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : sven.panne@aedion.de
-- Stability : provisional
-- Portability : portable
--
-- This module corresponds to section 2.6 (Begin\/End Paradigm) of the
-- OpenGL 1.5 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.BeginEnd (
-- * Begin and End Objects
PrimitiveMode(..),
renderPrimitive, unsafeRenderPrimitive, primitiveRestart,
-- * Polygon Edges
EdgeFlag(..),
edgeFlag
) where
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLboolean )
import Graphics.Rendering.OpenGL.GL.EdgeFlag (
EdgeFlag(..), marshalEdgeFlag, unmarshalEdgeFlag )
import Graphics.Rendering.OpenGL.GL.Exception ( bracket_, unsafeBracket_ )
import Graphics.Rendering.OpenGL.GL.Extensions (
FunPtr, unsafePerformIO, Invoker, getProcAddress )
import Graphics.Rendering.OpenGL.GL.PrimitiveMode (
PrimitiveMode(..), marshalPrimitiveMode )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
getBoolean1, GetPName(GetEdgeFlag) )
import Graphics.Rendering.OpenGL.GL.StateVar ( StateVar, makeStateVar )
--------------------------------------------------------------------------------
#include "HsOpenGLExt.h"
--------------------------------------------------------------------------------
-- | Delimit the vertices that define a primitive or a group of like primitives.
--
-- Only a subset of GL commands can be used in the delimited action:
-- Those for specifying vertex coordinates
-- ('Graphics.Rendering.OpenGL.GL.VertexSpec.vertex',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.vertexv'),
-- vertex colors
-- ('Graphics.Rendering.OpenGL.GL.VertexSpec.color',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.colorv',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.secondaryColor',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.secondaryColorv',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.index',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.indexv'),
-- normal
-- ('Graphics.Rendering.OpenGL.GL.VertexSpec.normal',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.normalv'),
-- texture coordinates
-- ('Graphics.Rendering.OpenGL.GL.VertexSpec.texCoord',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.texCoordv',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.multiTexCoord',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.multiTexCoordv'),
-- and fog coordinates
-- ('Graphics.Rendering.OpenGL.GL.VertexSpec.fogCoord',
-- 'Graphics.Rendering.OpenGL.GL.VertexSpec.fogCoordv').
-- Additionally,
-- 'Graphics.Rendering.OpenGL.GL.Evaluators.evalPoint1',
-- 'Graphics.Rendering.OpenGL.GL.Evaluators.evalPoint2',
-- 'Graphics.Rendering.OpenGL.GL.Evaluators.evalCoord1',
-- 'Graphics.Rendering.OpenGL.GL.Evaluators.evalCoord1v',
-- 'Graphics.Rendering.OpenGL.GL.Evaluators.evalCoord2',
-- 'Graphics.Rendering.OpenGL.GL.Evaluators.evalCoord2v',
-- 'Graphics.Rendering.OpenGL.GL.Colors.materialAmbient',
-- 'Graphics.Rendering.OpenGL.GL.Colors.materialDiffuse',
-- 'Graphics.Rendering.OpenGL.GL.Colors.materialAmbientAndDiffuse',
-- 'Graphics.Rendering.OpenGL.GL.Colors.materialSpecular',
-- 'Graphics.Rendering.OpenGL.GL.Colors.materialEmission',
-- 'Graphics.Rendering.OpenGL.GL.Colors.materialShininess',
-- 'Graphics.Rendering.OpenGL.GL.DisplayLists.callList',
-- 'Graphics.Rendering.OpenGL.GL.DisplayLists.callLists',
-- and setting 'edgeFlag' are allowed. Writing the respective state variables
-- is allowed in the delimited action, too.
--
-- Regardless of the chosen 'PrimitiveMode', there is no limit to the number of
-- vertices that can be defined during a single 'renderPrimitive'. Lines,
-- triangles, quadrilaterals, and polygons that are incompletely specified are
-- not drawn. Incomplete specification results when either too few vertices are
-- provided to specify even a single primitive or when an incorrect multiple of
-- vertices is specified. The incomplete primitive is ignored; the rest are
-- drawn.
--
-- The minimum specification of vertices for each primitive is as follows: 1
-- for a point, 2 for a line, 3 for a triangle, 4 for a quadrilateral, and 3 for
-- a polygon. Modes that require a certain multiple of vertices are 'Lines' (2),
-- 'Triangles' (3), 'Quads' (4), and 'QuadStrip' (2).
renderPrimitive :: PrimitiveMode -> IO a -> IO a
renderPrimitive = renderPrim bracket_
-- | A more efficient, but potentially dangerous version of 'renderPrimitive':
-- The given action is not allowed to throw an exception.
unsafeRenderPrimitive :: PrimitiveMode -> IO a -> IO a
unsafeRenderPrimitive = renderPrim unsafeBracket_
{-# INLINE renderPrim #-}
renderPrim :: (IO () -> IO () -> IO a -> IO a) -> PrimitiveMode -> IO a -> IO a
renderPrim brack_ beginMode =
brack_ (glBegin (marshalPrimitiveMode beginMode)) glEnd
foreign import CALLCONV unsafe "glBegin" glBegin :: GLenum -> IO ()
foreign import CALLCONV unsafe "glEnd" glEnd :: IO ()
--------------------------------------------------------------------------------
primitiveRestart :: IO ()
primitiveRestart = glPrimitiveRestartNV
EXTENSION_ENTRY("GL_NV_primitive_restart",glPrimitiveRestartNV,IO ())
--------------------------------------------------------------------------------
-- | Each vertex of a polygon, separate triangle, or separate quadrilateral
-- specified during 'renderPrimitive' is marked as the start of either a boundary
-- or nonboundary (interior) edge.
--
-- The vertices of connected triangles and connected quadrilaterals are always
-- marked as boundary, regardless of the value of the edge flag.
--
-- Boundary and nonboundary edge flags on vertices are significant only if
-- 'Graphics.Rendering.OpenGL.GL.Polygons.polygonMode' is set to
-- 'Graphics.Rendering.OpenGL.GL.Polygons.Point' or
-- 'Graphics.Rendering.OpenGL.GL.Polygons.Line'.
--
-- Note that the current edge flag can be updated at any time, in particular
-- during 'renderPrimitive'.
edgeFlag :: StateVar EdgeFlag
edgeFlag =
makeStateVar (getBoolean1 unmarshalEdgeFlag GetEdgeFlag)
(glEdgeFlag . marshalEdgeFlag)
foreign import CALLCONV unsafe "glEdgeFlag" glEdgeFlag :: GLboolean -> IO ()
| FranklinChen/hugs98-plus-Sep2006 | packages/OpenGL/Graphics/Rendering/OpenGL/GL/BeginEnd.hs | bsd-3-clause | 6,344 | 9 | 11 | 720 | 532 | 343 | 189 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, TypeSynonymInstances #-}
-- |This module provides a 'List' widget for rendering a list of
-- arbitrary widgets. A 'List' shows a number of elements and
-- highlights the currently-selected widget. It supports key events
-- to navigate the list and will automatically scroll based on the
-- space available to the list along with the size of the widgets in
-- the list.
module Graphics.Vty.Widgets.List
( List
, ListItem
, ListError(..)
, NewItemEvent(..)
, RemoveItemEvent(..)
, SelectionEvent(..)
, ActivateItemEvent(..)
-- ** List creation
, newTextList
, newList
, addToList
, insertIntoList
, removeFromList
, setSelectedFocusedAttr
, setSelectedUnfocusedAttr
-- ** List manipulation
, scrollBy
, scrollUp
, scrollDown
, scrollToEnd
, scrollToBeginning
, pageUp
, pageDown
, onSelectionChange
, onItemAdded
, onItemRemoved
, onItemActivated
, activateCurrentItem
, clearList
, setSelected
-- ** List inspection
, listFindFirst
, listFindFirstBy
, listFindAll
, listFindAllBy
, getListSize
, getSelected
, getListItem
)
where
import Data.Typeable
import Control.Exception hiding (Handler)
import Control.Monad
import qualified Data.Text as T
import qualified Data.Vector as V
import Graphics.Vty
import Graphics.Vty.Widgets.Core
import Graphics.Vty.Widgets.Text
import Graphics.Vty.Widgets.Fixed
import Graphics.Vty.Widgets.Limits
import Graphics.Vty.Widgets.Events
import Graphics.Vty.Widgets.Util
data ListError = BadItemIndex Int
-- ^The specified position could not be used to remove
-- an item from the list.
| ResizeError
deriving (Show, Typeable)
instance Exception ListError
-- |A list item. Each item contains an arbitrary internal value @a@
-- and a 'Widget' representing it.
type ListItem a b = (a, Widget b)
data SelectionEvent a b = SelectionOn Int a (Widget b)
-- ^An item at the specified position with the
-- specified internal value and widget was
-- selected.
| SelectionOff
-- ^No item was selected, which means the
-- list is empty.
-- |A new item was added to the list at the specified position with
-- the specified value and widget.
data NewItemEvent a b = NewItemEvent Int a (Widget b)
-- |An item was removed from the list at the specified position with
-- the specified value and widget.
data RemoveItemEvent a b = RemoveItemEvent Int a (Widget b)
-- |An item in the list was activated at the specified position with
-- the specified value and widget.
data ActivateItemEvent a b = ActivateItemEvent Int a (Widget b)
-- |The list widget type. Lists are parameterized over the /internal/
-- /value type/ @a@, the type of internal values used to refer to the
-- visible representations of the list contents, and the /widget type/
-- @b@, the type of widgets used to represent the list visually.
data List a b = List { selectedUnfocusedAttr :: Maybe Attr
, selectedFocusedAttr :: Maybe Attr
, selectedIndex :: !Int
-- ^The currently selected list index.
, scrollTopIndex :: !Int
-- ^The start index of the window of visible list
-- items.
, scrollWindowSize :: !Int
-- ^The size of the window of visible list items.
, listItems :: V.Vector (ListItem a b)
-- ^The items in the list.
, selectionChangeHandlers :: Handlers (SelectionEvent a b)
, itemAddHandlers :: Handlers (NewItemEvent a b)
, itemRemoveHandlers :: Handlers (RemoveItemEvent a b)
, itemActivateHandlers :: Handlers (ActivateItemEvent a b)
, itemHeight :: !Int
}
instance Show (List a b) where
show lst = concat [ "List { "
, "selectedUnfocusedAttr = ", show $ selectedUnfocusedAttr lst
, ", selectedFocusedAttr = ", show $ selectedFocusedAttr lst
, ", selectedIndex = ", show $ selectedIndex lst
, ", scrollTopIndex = ", show $ scrollTopIndex lst
, ", scrollWindowSize = ", show $ scrollWindowSize lst
, ", listItems = <", show $ V.length $ listItems lst, " items>"
, ", itemHeight = ", show $ itemHeight lst
, " }"
]
newListData :: Int -- ^Item widget height in rows
-> IO (List a b)
newListData h = do
schs <- newHandlers
iahs <- newHandlers
irhs <- newHandlers
iacths <- newHandlers
return $ List { selectedUnfocusedAttr = Nothing
, selectedFocusedAttr = Nothing
, selectedIndex = -1
, scrollTopIndex = 0
, scrollWindowSize = 0
, listItems = V.empty
, selectionChangeHandlers = schs
, itemAddHandlers = iahs
, itemRemoveHandlers = irhs
, itemActivateHandlers = iacths
, itemHeight = h
}
-- |Get the length of the list in elements.
getListSize :: Widget (List a b) -> IO Int
getListSize = ((V.length . listItems) <~~)
-- |Remove an element from the list at the specified position. May
-- throw 'BadItemIndex'.
removeFromList :: Widget (List a b) -> Int -> IO (ListItem a b)
removeFromList list pos = do
st <- getState list
foc <- focused <~ list
let numItems = V.length $ listItems st
oldScr = scrollTopIndex st
when (pos < 0 || pos >= numItems) $
throw $ BadItemIndex pos
-- Get the item from the list.
let (label, w) = (listItems st) V.! pos
sel = selectedIndex st
newScrollTop = if pos <= oldScr
then if oldScr == 0
then oldScr
else oldScr - 1
else oldScr
-- If that item is currently selected, select a different item.
newSelectedIndex = if pos > sel
then sel
else if pos < sel
then if sel == 0
then 0
else sel - 1
else if sel == 0
then if numItems == 1
then (-1)
else 0
else if sel == numItems - 1
then sel - 1
else sel
updateWidgetState list $ \s -> s { selectedIndex = newSelectedIndex
, listItems = V.take pos (listItems st) V.++
V.drop (pos + 1) (listItems st)
, scrollTopIndex = newScrollTop
}
when foc $ do
-- Unfocus the item we are about to remove if it's currently
-- selected
when (pos == sel) $ do
unfocus w
-- Focus the newly-selected item, if any
cur <- getSelected list
case cur of
Nothing -> return ()
Just (_, (_, w')) -> focus w'
-- Notify the removal handler.
notifyItemRemoveHandler list pos label w
-- Notify the selection handler, but only if the position we deleted
-- from is the selected position; that means the selection changed.
--
-- XXX this should probably be ==, not <=. Do some testing.
when (pos <= selectedIndex st) $
notifySelectionHandler list
-- Return the removed item.
return (label, w)
-- |Sets the attributes to be merged on the selected list item when the list
-- widget has the focus.
setSelectedFocusedAttr :: Widget (List a b) -> Maybe Attr -> IO ()
setSelectedFocusedAttr w attr = do
updateWidgetState w $ \l -> l { selectedFocusedAttr = attr }
-- |Sets the attributes to be merged on the selected list item when the list
-- widget does not have the focus.
setSelectedUnfocusedAttr :: Widget (List a b) -> Maybe Attr -> IO ()
setSelectedUnfocusedAttr w attr = do
updateWidgetState w $ \l -> l { selectedUnfocusedAttr = attr }
-- |Add an item to the list. Its widget will be constructed from the
-- specified internal value using the widget constructor passed to
-- 'newList'.
addToList :: (Show b) => Widget (List a b) -> a -> Widget b -> IO ()
addToList list key w = do
numItems <- (V.length . listItems) <~~ list
insertIntoList list key w numItems
-- |Insert an element into the list at the specified position. If the
-- position exceeds the length of the list, it is inserted at the end.
insertIntoList :: (Show b) => Widget (List a b) -> a -> Widget b -> Int -> IO ()
insertIntoList list key w pos = do
numItems <- (V.length . listItems) <~~ list
-- Calculate the new selected index.
oldSel <- selectedIndex <~~ list
oldScr <- scrollTopIndex <~~ list
swSize <- scrollWindowSize <~~ list
let newSelIndex = if numItems == 0
then 0
else if pos <= oldSel
then oldSel + 1
else oldSel
newScrollTop = if pos <= oldSel
then if (oldSel - oldScr + 1) == swSize
then oldScr + 1
else oldScr
else oldScr
let vInject atPos a as = let (hd, t) = (V.take atPos as, V.drop atPos as)
in hd V.++ (V.cons a t)
-- Optimize the append case.
let newItems s = if pos >= numItems
then V.snoc (listItems s) (key, w)
else vInject pos (key, w) (listItems s)
updateWidgetState list $ \s -> s { listItems = V.force $ newItems s
, selectedIndex = newSelIndex
, scrollTopIndex = newScrollTop
}
notifyItemAddHandler list (min numItems pos) key w
when (numItems == 0) $
do
foc <- focused <~ list
when foc $ focus w
when (oldSel /= newSelIndex) $ notifySelectionHandler list
-- |Register event handlers to be invoked when the list's selected
-- item changes.
onSelectionChange :: Widget (List a b)
-> (SelectionEvent a b -> IO ())
-> IO ()
onSelectionChange = addHandler (selectionChangeHandlers <~~)
-- |Register event handlers to be invoked when a new item is added to
-- the list.
onItemAdded :: Widget (List a b)
-> (NewItemEvent a b -> IO ()) -> IO ()
onItemAdded = addHandler (itemAddHandlers <~~)
-- |Register event handlers to be invoked when an item is removed from
-- the list.
onItemRemoved :: Widget (List a b)
-> (RemoveItemEvent a b -> IO ()) -> IO ()
onItemRemoved = addHandler (itemRemoveHandlers <~~)
-- |Register event handlers to be invoked when an item is activated,
-- which happens when the user presses Enter on a selected element
-- while the list has the focus.
onItemActivated :: Widget (List a b)
-> (ActivateItemEvent a b -> IO ()) -> IO ()
onItemActivated = addHandler (itemActivateHandlers <~~)
-- |Clear the list, removing all elements. Does not invoke any
-- handlers.
clearList :: Widget (List a b) -> IO ()
clearList w = do
updateWidgetState w $ \l ->
l { selectedIndex = (-1)
, scrollTopIndex = 0
, listItems = V.empty
}
-- |Create a new list. The list's item widgets will be rendered using the
-- specified height in rows.
newList :: (Show b) =>
Int -- ^Height of list item widgets in rows
-> IO (Widget (List a b))
newList ht = do
list <- newListData ht
wRef <- newWidget list $ \w ->
w { keyEventHandler = listKeyEvent
, growVertical_ = const $ return True
, growHorizontal_ = const $ return True
, getCursorPosition_ =
\this -> do
sel <- getSelected this
case sel of
Nothing -> return Nothing
Just (_, (_, e)) -> getCursorPosition e
, render_ =
\this sz ctx -> do
-- Get the item height *before* a potential resize, then
-- get the list state below, after the resize.
h <- itemHeight <~~ this
-- Resize the list based on the available space and the
-- height of each item.
when (h > 0) $
resizeList this (max 1 ((fromEnum $ regionHeight sz) `div` h))
renderListWidget this sz ctx
, setCurrentPosition_ =
\this pos -> do
ih <- itemHeight <~~ this
items <- getVisibleItems this
forM_ (zip [0..] items) $ \(i, ((_, iw), _)) ->
setCurrentPosition iw (pos `plusHeight` (toEnum $ i * ih))
}
wRef `onGainFocus` \_ ->
do
val <- getSelected wRef
case val of
Nothing -> return ()
Just (_, (_, w)) -> focus w
wRef `onLoseFocus` \_ ->
do
val <- getSelected wRef
case val of
Nothing -> return ()
Just (_, (_, w)) -> unfocus w
return wRef
listKeyEvent :: Widget (List a b) -> Key -> [Modifier] -> IO Bool
listKeyEvent w KUp _ = scrollUp w >> return True
listKeyEvent w KDown _ = scrollDown w >> return True
listKeyEvent w KPageUp _ = pageUp w >> return True
listKeyEvent w KPageDown _ = pageDown w >> return True
listKeyEvent w KEnter _ = activateCurrentItem w >> return True
listKeyEvent w k mods = do
val <- getSelected w
case val of
Nothing -> return False
Just (_, (_, e)) -> handleKeyEvent e k mods
renderListWidget :: (Show b) => Widget (List a b) -> DisplayRegion -> RenderContext -> IO Image
renderListWidget this s ctx = do
list <- getState this
foc <- focused <~ this
let items = map (\((_, w), sel) -> (w, sel)) $ getVisibleItems_ list
childSelFocAttr = (maybe (focusAttr ctx) id) $ selectedFocusedAttr list
childSelUnfocAttr = (maybe (focusAttr ctx) id) $ selectedUnfocusedAttr list
defaultAttr = mergeAttrs [ overrideAttr ctx
, normalAttr ctx
]
renderVisible [] = return []
renderVisible ((w, sel):ws) = do
let att = if sel
then if foc
then mergeAttrs [ childSelFocAttr, defaultAttr ]
else mergeAttrs [ childSelUnfocAttr, defaultAttr ]
else defaultAttr
-- Height-limit the widget by wrapping it with a VFixed/VLimit
limited <- vLimit (itemHeight list) =<< vFixed (itemHeight list) w
img <- render limited s $ ctx { overrideAttr = att }
let actualHeight = min (regionHeight s) (toEnum $ itemHeight list)
img' = img <|> charFill att ' '
(regionWidth s - imageWidth img)
actualHeight
imgs <- renderVisible ws
return (img':imgs)
let filler = charFill defaultAttr ' ' (regionWidth s) fill_height
fill_height = if scrollWindowSize list == 0
then regionHeight s
else toEnum $ ((scrollWindowSize list - length items) * itemHeight list)
visible_imgs <- renderVisible items
return $ vertCat (visible_imgs ++ [filler])
-- |A convenience function to create a new list using 'Text' values as
-- the internal values and 'FormattedText' widgets to represent those
-- strings.
newTextList :: [T.Text] -- ^The list items
-> Int -- ^Maximum number of rows of text to show per list item
-> IO (Widget (List T.Text FormattedText))
newTextList labels h = do
list <- newList h
forM_ labels $ \l ->
(addToList list l =<< plainText l)
return list
-- |Programmatically activate the currently-selected item in the list,
-- if any.
activateCurrentItem :: Widget (List a b) -> IO ()
activateCurrentItem wRef = do
mSel <- getSelected wRef
case mSel of
Nothing -> return ()
Just (pos, (val, w)) ->
fireEvent wRef (itemActivateHandlers <~~) $ ActivateItemEvent pos val w
-- note that !! here will always succeed because selectedIndex will
-- never be out of bounds and the list will always be non-empty.
-- |Get the currently-selected list item.
getSelected :: Widget (List a b) -> IO (Maybe (Int, ListItem a b))
getSelected wRef = do
list <- state <~ wRef
case selectedIndex list of
(-1) -> return Nothing
i -> return $ Just (i, (listItems list) V.! i)
-- |Get the list item at the specified position.
getListItem :: Widget (List a b) -> Int -> IO (Maybe (ListItem a b))
getListItem wRef pos = do
list <- state <~ wRef
case pos >= 0 && pos < (V.length $ listItems list) of
False -> return Nothing
True -> return $ Just ((listItems list) V.! pos)
-- |Set the currently-selected list index.
setSelected :: Widget (List a b) -> Int -> IO ()
setSelected wRef newPos = do
list <- state <~ wRef
case selectedIndex list of
(-1) -> return ()
curPos -> scrollBy wRef (newPos - curPos)
-- |Find the first index of the specified key in the list. If the key does not
-- exist, return Nothing.
listFindFirst :: (Eq a) => Widget (List a b) -> a -> IO (Maybe Int)
listFindFirst wRef item = listFindFirstBy (== item) wRef
-- |Find the first index in the list for which the predicate is true.
-- If no item in the list matches the given predicate, return Nothing.
listFindFirstBy :: (a -> Bool) -> Widget (List a b) -> IO (Maybe Int)
listFindFirstBy p wRef = do
list <- state <~ wRef
return $ V.findIndex matcher (listItems list)
where
matcher = \(match, _) -> p match
-- |Find all indicies of the specified key in the list.
listFindAll :: (Eq a) => Widget (List a b) -> a -> IO [Int]
listFindAll wRef item = listFindAllBy (== item) wRef
-- |Find all indices in the list matching the given predicate.
listFindAllBy :: (a -> Bool) -> Widget (List a b) -> IO [Int]
listFindAllBy p wRef = do
list <- state <~ wRef
return $ V.toList $ V.findIndices matcher (listItems list)
where
matcher = \(match, _) -> p match
resizeList :: Widget (List a b) -> Int -> IO ()
resizeList wRef newSize = do
when (newSize == 0) $ throw ResizeError
size <- (scrollWindowSize . state) <~ wRef
case compare newSize size of
EQ -> return () -- Do nothing if the window size isn't changing.
GT -> updateWidgetState wRef $ \list ->
list { scrollWindowSize = newSize
, scrollTopIndex = max 0 (scrollTopIndex list - (newSize - scrollWindowSize list))
}
-- Otherwise it's smaller, so we need to look at which item is
-- selected and decide whether to change the scrollTopIndex.
LT -> do
list <- state <~ wRef
-- If the currently selected item would be out of view in the
-- new size, then we need to move the display top down to keep
-- it visible.
let newBottomPosition = scrollTopIndex list + newSize - 1
current = selectedIndex list
newScrollTopIndex = if current > newBottomPosition
then current - newSize + 1
else scrollTopIndex list
updateWidgetState wRef $ const $ list { scrollWindowSize = newSize
, scrollTopIndex = newScrollTopIndex
}
-- |Scroll a list up or down by the specified number of positions.
-- Scrolling by a positive amount scrolls downward and scrolling by a
-- negative amount scrolls upward. This automatically takes care of
-- managing internal list state and invoking event handlers.
scrollBy :: Widget (List a b) -> Int -> IO ()
scrollBy wRef amount = do
foc <- focused <~ wRef
-- Unfocus the currently-selected item.
old <- getSelected wRef
case old of
Nothing -> return ()
Just (_, (_, w)) -> when foc $ unfocus w
updateWidgetState wRef $ scrollBy' amount
-- Focus the newly-selected item.
new <- getSelected wRef
case new of
Nothing -> return ()
Just (_, (_, w)) -> when foc $ focus w
notifySelectionHandler wRef
scrollBy' :: Int -> List a b -> List a b
scrollBy' amt list =
case selectedIndex list of
(-1) -> list
i -> let dest = i + amt
sz = V.length $ listItems list
newDest = if dest < 0
then 0
else if dest >= sz
then sz - 1
else dest
in scrollTo newDest list
scrollTo :: Int -> List a b -> List a b
scrollTo newSelected list =
let bottomPosition = min (scrollTopIndex list + scrollWindowSize list - 1)
((V.length $ listItems list) - 1)
topPosition = scrollTopIndex list
windowPositions = [topPosition..bottomPosition]
adjustedTop = if newSelected `elem` windowPositions
then topPosition
else if newSelected >= bottomPosition
then newSelected - scrollWindowSize list + 1
else newSelected
in list { scrollTopIndex = adjustedTop
, selectedIndex = newSelected
}
notifySelectionHandler :: Widget (List a b) -> IO ()
notifySelectionHandler wRef = do
sel <- getSelected wRef
case sel of
Nothing ->
fireEvent wRef (selectionChangeHandlers <~~) SelectionOff
Just (pos, (a, b)) ->
fireEvent wRef (selectionChangeHandlers <~~) $ SelectionOn pos a b
notifyItemRemoveHandler :: Widget (List a b) -> Int -> a -> Widget b -> IO ()
notifyItemRemoveHandler wRef pos k w =
fireEvent wRef (itemRemoveHandlers <~~) $ RemoveItemEvent pos k w
notifyItemAddHandler :: Widget (List a b) -> Int -> a -> Widget b -> IO ()
notifyItemAddHandler wRef pos k w =
fireEvent wRef (itemAddHandlers <~~) $ NewItemEvent pos k w
-- |Scroll to the last list position.
scrollToEnd :: Widget (List a b) -> IO ()
scrollToEnd wRef = do
cur <- getSelected wRef
sz <- getListSize wRef
case cur of
Nothing -> return ()
Just (pos, _) -> scrollBy wRef (sz - pos)
-- |Scroll to the first list position.
scrollToBeginning :: Widget (List a b) -> IO ()
scrollToBeginning wRef = do
cur <- getSelected wRef
case cur of
Nothing -> return ()
Just (pos, _) -> scrollBy wRef (-1 * pos)
-- |Scroll a list down by one position.
scrollDown :: Widget (List a b) -> IO ()
scrollDown wRef = scrollBy wRef 1
-- |Scroll a list up by one position.
scrollUp :: Widget (List a b) -> IO ()
scrollUp wRef = scrollBy wRef (-1)
-- |Scroll a list down by one page from the current cursor position.
pageDown :: Widget (List a b) -> IO ()
pageDown wRef = do
amt <- scrollWindowSize <~~ wRef
scrollBy wRef amt
-- |Scroll a list up by one page from the current cursor position.
pageUp :: Widget (List a b) -> IO ()
pageUp wRef = do
amt <- scrollWindowSize <~~ wRef
scrollBy wRef (-1 * amt)
getVisibleItems :: Widget (List a b) -> IO [(ListItem a b, Bool)]
getVisibleItems wRef = do
list <- state <~ wRef
return $ getVisibleItems_ list
getVisibleItems_ :: List a b -> [(ListItem a b, Bool)]
getVisibleItems_ list =
let start = scrollTopIndex list
stop = scrollTopIndex list + scrollWindowSize list
adjustedStop = (min stop $ V.length $ listItems list) - 1
in [ (listItems list V.! i, i == selectedIndex list)
| i <- [start..adjustedStop] ]
| KommuSoft/vty-ui | src/Graphics/Vty/Widgets/List.hs | bsd-3-clause | 23,889 | 0 | 23 | 7,711 | 6,031 | 3,123 | 2,908 | 444 | 10 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module LambdaLudo
( Square
, Step
, Handle
, Config(..)
, Color(..)
, EngineEvent(..)
, runGame
, RWS.get
, RWS.put
, RWS.modify
, module LambdaLudo.EDSL
, module SDL.Input.Keyboard.Codes
) where
import LambdaLudo.EDSL
import LambdaLudo.Types
import SDL
import SDL.Image (loadTexture)
import SDL.Input.Keyboard.Codes
import Control.Concurrent (threadDelay)
import Control.Monad.Random (runRand)
import qualified Control.Monad.RWS as RWS
import qualified Control.Monad.State as S
import Data.List (partition)
import Data.Maybe (catMaybes)
import Data.Text (unpack)
import Data.Word (Word8)
import Foreign.C.Types (CInt)
import GHC.Exts (sortWith)
import System.Random (getStdGen)
runGame :: Config a -> IO ()
runGame c@(Config _ _ i _ a col row size) = do
initializeAll
w <- createWindow "Game" $ defaultWindow
{windowInitialSize = V2 (toEnum $ col * size) (toEnum $ row * size)}
r <- createRenderer w (-1) defaultRenderer
rendererDrawBlendMode r $= BlendAlphaBlend
s <- initState c r
fst <$> S.runStateT (loop r) (S.execState (runStep i) s)
initState :: Config s -> Renderer -> IO (EngineState s)
initState conf r = do
let tName = map (takeWhile (/= '.')) (assets conf)
texture' <- zip tName <$> mapM (loadTexture r) (map ("img/" ++) $ assets conf)
randomState' <- getStdGen
let frame' = 0
sprite' = []
boardWidth' = columns conf
boardHeight' = rows conf
squareSize' = size conf
board' = [
Square x y "" 0 Transparent
| x <- [0..boardWidth' - 1]
, y <- [0..boardHeight' - 1]
]
gameStepper' = stepper conf
gameHandler' = handler conf
gameState' = memory conf
gameBg' = BgColor $ Color 0 0 0
return $ EngineState
frame' randomState' texture' sprite'
board' boardWidth' boardHeight' squareSize'
gameStepper' gameHandler' gameState' gameBg'
loop :: Renderer -> S.StateT (EngineState s) IO ()
loop r = do
events <- getEngineEvents
if elem Quit events then return ()
else do
mapM_ (\e -> (gameHandler <$> S.get <*> pure e) >>= runStep) events
(gameStepper <$> S.get) >>= runStep
incFrame
buildScene r
present r
S.liftIO $ waitForNext
loop r
getEngineEvents :: S.StateT (EngineState s) IO [EngineEvent]
getEngineEvents = do
e <- map eventPayload <$> S.liftIO pollEvents
ee <- mapM sdlToEE e
return $ catMaybes ee
sdlToEE (KeyboardEvent (KeyboardEventData _ Pressed _ k)) =
return $ Just $ KeyPress $ keysymKeycode k
sdlToEE (MouseButtonEvent(MouseButtonEventData _ Pressed _ ButtonLeft _ p)) = do
let (P (V2 x y)) = p
s <- squareSize <$> S.get
return $ Just $ MouseClick (div (fromEnum x) s, div (fromEnum y) s)
sdlToEE (MouseMotionEvent(MouseMotionEventData _ _ _ p _)) = do
let (P (V2 x y)) = p
s <- squareSize <$> S.get
return $ Just $ MouseHover (div (fromEnum x) s, div (fromEnum y) s)
sdlToEE QuitEvent = return $ Just Quit
sdlToEE _ = return Nothing
runStep :: S.MonadState (EngineState s) m => Step s () -> m ()
runStep step = do
st <- S.get
let ((gs,as),r) = runRand
(RWS.execRWST step st (gameState st))
(randomState st)
S.put $ st {gameState = gs, randomState = r}
mapM_ (\a -> S.modify $ evalAction a) as
incFrame :: S.MonadState (EngineState s) m => m ()
incFrame = do
s <- S.get
let f = frame s
S.put $ s {frame = succ f}
buildScene :: Renderer -> S.StateT (EngineState s) IO ()
buildScene r = do
clear r
size <- squareSize <$> S.get
b <- board <$> S.get
s <- sprite <$> S.get
w <- boardWidth <$> S.get
h <- boardHeight <$> S.get
bg <- gameBg <$> S.get
S.liftIO $ do
drawBackground size w h r bg
mapM_ (drawSquare size r) b
mapM_ (drawSprite size r) $ sortWith (\(_,x,_,_) -> x) s
drawBackground :: Int -> Int -> Int -> Renderer -> GameBg -> IO ()
drawBackground s w h r (BgTexture tx) =
copy r tx Nothing $ Just $ mkRect 0 0 (w * s) (h * s)
drawBackground s w h r (BgColor c) = do
rendererDrawColor r $= mkColor c
fillRect r $ Just $ mkRect 0 0 (w * s) (h * s)
drawSquare :: Int -> Renderer -> Square -> IO ()
drawSquare _ _ (Square _ _ _ _ Transparent) = return ()
drawSquare size r s@(Square x y _ _ c) = do
rendererDrawColor r $= mkColor c
fillRect r $ Just $ mkRect x y size size
drawSprite :: Int -> Renderer -> Sprite -> IO ()
drawSprite size r ((x,y),z,_,t) =
copy r t Nothing $ Just $ mkRect x y size size
mkRect :: Int -> Int -> Int -> Int -> Rectangle CInt
mkRect x y sx sy = Rectangle (P $ V2 x' y') (V2 sx' sy') where
x' = toEnum $ x * sx
y' = toEnum $ y * sy
sx' = toEnum sx
sy' = toEnum sy
mkColor :: Color -> V4 Word8
mkColor Transparent = V4 1 1 1 0
mkColor (Color r g b) = V4 (toEnum r) (toEnum g) (toEnum b) 255
transToBlack :: Color -> Color
transToBlack Transparent = Color 0 0 0
transToBlack c = c
evalAction :: Action s -> EngineState s -> EngineState s
evalAction (PaintSquare (x,y) c) s = modSquare (x,y) (setColor c) s
evalAction (CreateSprite xy z name) s =
case lookup name (texture s) of
Nothing -> error ("texture: " ++ name ++ " not found")
Just t -> s {sprite = (xy,z,name,t) : sprite s}
evalAction (DeleteSprite (x,y) name) s =
s {sprite = filter (not . isSprite (x,y) name) $ sprite s}
evalAction (MoveSprite (x,y) (x',y') name) s =
let (found,rest) = partition (isSprite (x,y) name) $ sprite s
in s {sprite = map (\(_,z,n,t) -> ((x',y'),z,n,t)) found ++ rest}
evalAction (ChangeStepper s) st = st {gameStepper = s}
evalAction (ChangeHandler h) st = st {gameHandler = h}
evalAction (ChangeBgImage name) st =
case lookup name (texture st) of
Nothing -> error ("texture: " ++ name ++ " not found")
Just t -> st {gameBg = BgTexture t}
evalAction (ChangeBgColor c) st = st {gameBg = BgColor c}
isSprite :: (Int,Int) -> String -> Sprite -> Bool
isSprite (x',y') name' ((x,y),_,name,t) = x == x' && y == y' && name == name'
modSquare :: (Int,Int) -> (Square -> Square) -> EngineState s -> EngineState s
modSquare (x,y) f st = st {board = modSquare' (board st)} where
modSquare' (s@(Square x' y' _ _ _):ss) = if x == x' && y == y'
then f s : ss
else s : modSquare' ss
modSquare' [] = []
setColor :: Color -> Square -> Square
setColor c s = s {color = c}
fps :: Integral a => a
fps = 30
frameTime :: Float
frameTime = 1000 / fromIntegral fps
waitForNext :: IO ()
waitForNext = do
t <- ticks
let f = (fromIntegral $ floor (fromIntegral t / frameTime)) * frameTime
w = round $ frameTime - (fromIntegral t - f)
w' = if w == 0 then 16 else w
threadDelay $ 1000 * w
| tauli/LambdaLudo | src/LambdaLudo.hs | bsd-3-clause | 6,761 | 0 | 17 | 1,650 | 3,049 | 1,554 | 1,495 | 181 | 3 |
module SimulationDSL.Data.ExpType ( ExpType(..)
) where
data ExpType = ExpTypeScalar
| ExpTypeVector
deriving Eq
instance Show ExpType where
show ExpTypeScalar = "Scalar"
show ExpTypeVector = "Vector"
| takagi/SimulationDSL | SimulationDSL/SimulationDSL/Data/ExpType.hs | bsd-3-clause | 256 | 0 | 6 | 81 | 53 | 31 | 22 | 7 | 0 |
-- | Needleman/Wunsch global alignment of two sequences
module ADP.Tests.AlignmentExample where
import ADP.Debug
import ADP.Multi.All
import ADP.Multi.Rewriting.All
type Alignment_Algebra alphabet answer = (
(EPS,EPS) -> answer, -- nil
alphabet -> answer -> answer, -- del
alphabet -> answer -> answer, -- ins
alphabet -> alphabet -> answer -> answer, -- match
[answer] -> [answer] -- h
)
infixl ***
(***) :: (Eq b, Eq c) => Alignment_Algebra a b -> Alignment_Algebra a c -> Alignment_Algebra a (b,c)
alg1 *** alg2 = (nil,del,ins,match,h) where
(nil',del',ins',match',h') = alg1
(nil'',del'',ins'',match'',h'') = alg2
nil a = (nil' a, nil'' a)
del a (s1,s2) = (del' a s1, del'' a s2)
ins a (s1,s2) = (ins' a s1, ins'' a s2)
match a b (s1,s2) = (match' a b s1, match'' a b s2)
h xs = [ (x1,x2) |
x1 <- h' [ y1 | (y1,_) <- xs]
, x2 <- h'' [ y2 | (y1,y2) <- xs, y1 == x1]
]
data Start = Nil
| Del Char Start
| Ins Char Start
| Match Char Char Start
deriving (Eq, Show)
enum :: Alignment_Algebra Char Start
enum = (\_ -> Nil,Del,Ins,Match,id)
count :: Alignment_Algebra Char Int
count = (nil,del,ins,match,h) where
nil _ = 1
del _ s = s
ins _ s = s
match _ _ s = s
h [] = []
h x = [sum x]
unit :: Alignment_Algebra Char Int
unit = (nil,del,ins,match,h) where
nil _ = 0
del _ s = s-1
ins _ s = s-1
match a b s = if (a==b) then s+1 else s-1
h [] = []
h x = [maximum x]
alignmentGr :: Alignment_Algebra Char answer -> (String,String) -> [answer]
alignmentGr _ inp | trace ("running alignmentGr on " ++ show inp) False = undefined
alignmentGr algebra (inp1,inp2) =
let
(nil,del,ins,match,h) = algebra
rewriteDel, rewriteIns, rewriteMatch :: Dim2
rewriteDel [c,a1,a2] = ([c,a1],[a2])
rewriteIns [c,a1,a2] = ([a1],[c,a2])
rewriteMatch [c1,c2,a1,a2] = ([c1,a1],[c2,a2])
a = tabulated2 $
yieldSize2 (0,Nothing) (0,Nothing) $
nil <<< (EPS,EPS) >>> id2 |||
del <<< anychar ~~~ a >>> rewriteDel |||
ins <<< anychar ~~~ a >>> rewriteIns |||
match <<< anychar ~~~ anychar ~~~ a >>> rewriteMatch
... h
z = mkTwoTrack inp1 inp2
tabulated2 = table2 z
in axiomTwoTrack z inp1 inp2 a | adp-multi/adp-multi | tests/ADP/Tests/AlignmentExample.hs | bsd-3-clause | 2,438 | 0 | 28 | 750 | 1,072 | 599 | 473 | 64 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Module : Numeric.AERN.Basics.Interval.RefinementOrder
Description : interval instances of refinement-ordered structures
Copyright : (c) Michal Konecny, Jan Duracz
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Interval instances of refinement-ordered structures.
This is a hidden module reexported via its parent.
-}
module Numeric.AERN.Basics.Interval.RefinementOrder where
import Prelude hiding (EQ, LT, GT)
import Numeric.AERN.Basics.Consistency
import Numeric.AERN.Basics.Arbitrary
import Numeric.AERN.Basics.PartialOrdering
import Numeric.AERN.Basics.Interval.Basics
import Numeric.AERN.Basics.Interval.NumericOrder ()
import qualified Numeric.AERN.NumericOrder as NumOrd
import Numeric.AERN.NumericOrder.Operators
import qualified Numeric.AERN.RefinementOrder as RefOrd
import Numeric.AERN.RefinementOrder
(
GetEndpointsEffortIndicator,
FromEndpointsEffortIndicator,
PartialCompareEffortIndicator,
PartialJoinEffortIndicator,
JoinMeetEffortIndicator
)
import Numeric.AERN.Misc.List
import Test.QuickCheck
import Data.Maybe
instance
(RefOrd.IntervalLike (Interval e))
where
type GetEndpointsEffortIndicator (Interval e) = ()
type FromEndpointsEffortIndicator (Interval e) = ()
getEndpointsDefaultEffort _ = ()
fromEndpointsDefaultEffort _ = ()
-- getEndpointsInEff _ (Interval l r) = (Interval l l,Interval r r)
getEndpointsOutEff _ (Interval l r) = (Interval l l,Interval r r)
fromEndpointsInEff _ (Interval _ll lr, Interval rl _rr) = (Interval lr rl)
fromEndpointsOutEff _ (Interval ll _lr, Interval _rl rr) = (Interval ll rr)
instance
(NumOrd.PartialComparison e, NumOrd.RoundedLatticeEffort e)
=>
(RefOrd.PartialComparison (Interval e))
where
type PartialCompareEffortIndicator (Interval e) =
IntervalOrderEffort e
pCompareDefaultEffort i =
defaultIntervalOrderEffort i
pCompareEff effort i1 i2 =
case partialInfo2PartialOrdering $ RefOrd.pCompareInFullEff effort i1 i2 of
[ord] -> Just ord
_ -> Nothing
pCompareInFullEff effort (Interval l1 r1) (Interval l2 r2)
=
refordPCompareInFullIntervalsEff effComp (l1, r1) (l2, r2)
where
effComp = intordeff_eComp effort
refordPCompareInFullIntervalsEff ::
(NumOrd.PartialComparison t)
=>
NumOrd.PartialCompareEffortIndicator t
-> (t, t)
-> (t, t)
-> PartialOrderingPartialInfo
refordPCompareInFullIntervalsEff effort (l1, r1) (l2, r2)
=
PartialOrderingPartialInfo
{
pOrdInfEQ = fromD (eqD, neqD),
pOrdInfLT = fromD (ltD, nltD),
pOrdInfLEQ = fromD (leqD, nleqD),
pOrdInfGT = fromD (gtD, ngtD),
pOrdInfGEQ = fromD (geqD, ngeqD),
pOrdInfNC = fromD (nleqD && ngeqD, leqD || geqD)
}
-- case (c l1 l2, c r1 r2) of
-- (Just EQ, Just EQ) -> Just EQ
-- (Just LT, Just GT) -> Just LT
-- (Just LT, Just EQ) -> Just LT
-- (Just EQ, Just GT) -> Just LT
-- (Just GT, Just LT) -> Just GT
-- (Just GT, Just EQ) -> Just GT
-- (Just EQ, Just LT) -> Just GT
-- (Just _, Just _) -> Just NC
-- _ -> Nothing
where
fromD (definitelyTrue, definitelyFalse) =
case (definitelyTrue, definitelyFalse) of
(True, _) -> Just True
(_, True) -> Just False
_ -> Nothing
eqD = leftEQ == jt && rightEQ == jt
neqD = leftEQ == jf || rightEQ == jf
leqD = leftLEQ == jt && rightGEQ == jt
nleqD = leftLEQ == jf || rightGEQ == jf
ltD = leqD && neqD
nltD = nleqD || eqD
gtD = geqD && neqD
ngtD = ngeqD || eqD
geqD = leftGEQ == jt && rightLEQ == jt
ngeqD = leftGEQ == jf || rightLEQ == jf
leftEQ = pOrdInfEQ leftInfo
-- leftLT = pOrdInfLT leftInfo
leftLEQ = pOrdInfLEQ leftInfo
-- leftGT = pOrdInfGT leftInfo
leftGEQ = pOrdInfGEQ leftInfo
leftInfo = NumOrd.pCompareInFullEff effort l1 l2
rightEQ = pOrdInfEQ rightInfo
-- rightLT = pOrdInfLT rightInfo
rightLEQ = pOrdInfLEQ rightInfo
-- rightGT = pOrdInfGT rightInfo
rightGEQ = pOrdInfGEQ rightInfo
rightInfo = NumOrd.pCompareInFullEff effort r1 r2
jt = Just True
jf = Just False
{-
Beware, the following instance does not test inclusion of the two approximated intervals.
This instance compares that one approximation permits a subset of intervals
that the other approximation permits.
-}
instance
(NumOrd.PartialComparison e, NumOrd.RoundedLatticeEffort e)
=>
(RefOrd.PartialComparison (IntervalApprox e))
where
type PartialCompareEffortIndicator (IntervalApprox e) =
IntervalOrderEffort e
pCompareDefaultEffort (IntervalApprox o _) =
defaultIntervalOrderEffort o
pCompareEff effort ia1 ia2 =
case partialInfo2PartialOrdering $ RefOrd.pCompareInFullEff effort ia1 ia2 of
[ord] -> Just ord
_ -> Nothing
pCompareInFullEff effort (IntervalApprox o1 i1) (IntervalApprox o2 i2)
=
compOuter `partialOrderingPartialInfoAnd` compInner
where
compOuter = RefOrd.pCompareInFullEff effort o1 o2
compInner = RefOrd.pCompareInFullEff effort i2 i1
intervalApproxIncludedInEff ::
(NumOrd.RoundedLatticeEffort t, NumOrd.PartialComparison t)
=>
IntervalOrderEffort t ->
IntervalApprox t -> IntervalApprox t -> Maybe Bool
intervalApproxIncludedInEff eff (IntervalApprox o1 _i1) (IntervalApprox o2 i2) =
case (o1 `includedIn` i2, o1 `includedIn` o2) of
(Just True, _) -> Just True -- outer inside inner -> inclusion proved
(_,Just False) -> Just False -- outer definitely not inside outer, ie outers are disjoint somewhere -> inclusion disproved
_ -> Nothing
where
includedIn = RefOrd.pGeqEff eff
intervalApproxIncludedIn ::
(NumOrd.RoundedLatticeEffort t, NumOrd.PartialComparison t)
=>
IntervalApprox t -> IntervalApprox t -> Maybe Bool
intervalApproxIncludedIn ia1@(IntervalApprox o _) =
intervalApproxIncludedInEff eff ia1
where
eff = RefOrd.pCompareDefaultEffort o
instance (NumOrd.HasExtrema e) => (RefOrd.HasTop (Interval e))
where
top (Interval sampleE _) =
Interval (NumOrd.greatest sampleE) (NumOrd.least sampleE)
instance (NumOrd.HasExtrema e) => (RefOrd.HasBottom (Interval e))
where
bottom (Interval sampleE _) =
Interval (NumOrd.least sampleE) (NumOrd.greatest sampleE)
instance (NumOrd.HasExtrema e) => (RefOrd.HasExtrema (Interval e))
instance
(NumOrd.RoundedLatticeEffort e, NumOrd.PartialComparison e)
=> RefOrd.RoundedBasisEffort (Interval e)
where
type PartialJoinEffortIndicator (Interval e) =
IntervalOrderEffort e
partialJoinDefaultEffort i =
defaultIntervalOrderEffort i
instance
(NumOrd.RoundedLattice e, NumOrd.PartialComparison e)
=>
RefOrd.RoundedBasis (Interval e)
where
partialJoinOutEff effort (Interval l1 r1) (Interval l2 r2) =
case l <=? r of
Just True -> Just $ Interval l r
_ -> Nothing
where
(<=?) = NumOrd.pLeqEff effortComp
l = NumOrd.maxDnEff effortMinmax l1 l2
r = NumOrd.minUpEff effortMinmax r1 r2
effortMinmax = intordeff_eMinmax effort
effortComp = intordeff_eComp effort
partialJoinInEff effort (Interval l1 r1) (Interval l2 r2) =
case l <=? r of
Just True -> Just $ Interval l r
_ -> Nothing
where
(<=?) = NumOrd.pLeqEff effortComp
l = NumOrd.maxUpEff effortMinmax l1 l2
r = NumOrd.minDnEff effortMinmax r1 r2
effortMinmax = intordeff_eMinmax effort
effortComp = intordeff_eComp effort
instance
(NumOrd.RoundedLattice e, NumOrd.PartialComparison e)
=>
(RefOrd.RoundedLatticeEffort (Interval e))
where
type JoinMeetEffortIndicator (Interval e) =
IntervalOrderEffort e
joinmeetDefaultEffort i =
defaultIntervalOrderEffort i
instance
(NumOrd.RoundedLattice e, NumOrd.PartialComparison e)
=>
(RefOrd.RoundedLattice (Interval e))
where
joinOutEff effort (Interval l1 r1) (Interval l2 r2) =
Interval l r
where
l = NumOrd.maxDnEff effMinmax l1 l2
r = NumOrd.minUpEff effMinmax r1 r2
effMinmax = intordeff_eMinmax effort
meetOutEff effort (Interval l1 r1) (Interval l2 r2) =
Interval l r
where
l = NumOrd.minDnEff effMinmax l1 l2
r = NumOrd.maxUpEff effMinmax r1 r2
effMinmax = intordeff_eMinmax effort
joinInEff effort (Interval l1 r1) (Interval l2 r2) =
Interval l r
where
l = NumOrd.maxUpEff effMinmax l1 l2
r = NumOrd.minDnEff effMinmax r1 r2
effMinmax = intordeff_eMinmax effort
meetInEff effort (Interval l1 r1) (Interval l2 r2) =
Interval l r
where
l = NumOrd.minUpEff effMinmax l1 l2
r = NumOrd.maxDnEff effMinmax r1 r2
effMinmax = intordeff_eMinmax effort
intervalApproxUnionEff ::
(NumOrd.PartialComparison e, NumOrd.RoundedLattice e)
=>
IntervalOrderEffort e
-> IntervalApprox e -> IntervalApprox e -> IntervalApprox e
intervalApproxUnionEff effort (IntervalApprox o1 i1) (IntervalApprox o2 i2) =
IntervalApprox
(RefOrd.meetOutEff effort o1 o2)
(RefOrd.meetInEff effort i1 i2)
intervalApproxUnion ::
(NumOrd.PartialComparison e, NumOrd.RoundedLattice e)
=>
IntervalApprox e -> IntervalApprox e -> IntervalApprox e
intervalApproxUnion ia1@(IntervalApprox o _) ia2 =
intervalApproxUnionEff effort ia1 ia2
where
effort = RefOrd.joinmeetDefaultEffort o
instance
(NumOrd.AreaHasBoundsConstraints e)
=>
(RefOrd.AreaHasBoundsConstraints (Interval e))
where
areaSetOuterBound (Interval l r) (areaEndpt, consistency) =
(NumOrd.areaSetUpperBound (r, False) $ NumOrd.areaSetLowerBound (l, False) areaEndpt,
consistency)
instance
(NumOrd.ArbitraryOrderedTuple e,
NumOrd.RoundedLattice e,
AreaHasForbiddenValues e,
NumOrd.PartialComparison e)
=>
RefOrd.ArbitraryOrderedTuple (Interval e)
where
arbitraryTupleInAreaRelatedBy area =
arbitraryIntervalTupleInAreaRefinementRelatedBy (Just area)
arbitraryTupleRelatedBy =
arbitraryIntervalTupleInAreaRefinementRelatedBy Nothing
instance AreaHasConsistencyConstraint (Interval e)
where
areaSetConsistencyConstraint _ constraint (areaEndpt, _) = (areaEndpt, constraint)
arbitraryIntervalTupleInAreaRefinementRelatedBy maybeArea indices constraints =
case endpointGens of
[] -> Nothing
_ -> Just $
do
gen <- elements endpointGens
avoidForbidden gen 100 -- maximum tries
where
avoidForbidden gen maxTries =
do
endpointTuple <- gen
let results = endpointsToIntervals endpointTuple
case nothingForbiddenInsideIntervals results of
True -> return results
_ | maxTries > 0 -> avoidForbidden gen $ maxTries - 1
_ -> error "aern-interval: internal error in arbitraryIntervalTupleInAreaRefinementRelatedBy: failed to avoid forbidden values"
nothingForbiddenInsideIntervals intervals =
case maybeArea of
Nothing -> True
Just (areaEndpt, _) ->
and $ map (nothingForbiddenInsideInterval areaEndpt) intervals
nothingForbiddenInsideInterval areaEndpt interval =
and $ map (notInside interval) $ areaGetForbiddenValues areaEndpt
where
notInside (Interval l r) value =
((value <? l) == Just True)
||
((value >? r) == Just True)
endpointGens =
case maybeArea of
(Just (areaEndpt, _areaConsistency)) ->
catMaybes $
map (NumOrd.arbitraryTupleInAreaRelatedBy areaEndpt endpointIndices)
endpointConstraintsVersions
Nothing ->
catMaybes $
map (NumOrd.arbitraryTupleRelatedBy endpointIndices)
endpointConstraintsVersions
endpointIndices =
concat $ map (\ix -> [(ix,-1), (ix,1)]) indices
endpointsToIntervals [] = []
endpointsToIntervals (l : r : rest) =
(Interval l r) : (endpointsToIntervals rest)
endpointConstraintsVersions =
-- unsafePrintReturn
-- ("arbitraryIntervalTupleRelatedBy:"
-- ++ "\n indices = " ++ show indices
-- ++ "\n constraints = " ++ show constraints
-- ++ "\n endpointIndices = " ++ show endpointIndices
-- ++ "\n endpointConstraintsVersions = "
-- ) $
map concat $
-- map ((++ thinnessConstraints) . concat) $
combinations $ map intervalConstraintsToEndpointConstraints constraints
-- thinnessConstraints = map (\ix -> (((ix,-1),(ix,1)),[EQ])) thinIndices
allowedEndpointRelations =
case maybeArea of
Just (_, AreaMaybeAllowOnlyWithConsistencyStatus (Just Consistent)) -> [EQ,LT]
Just (_, AreaMaybeAllowOnlyWithConsistencyStatus (Just Anticonsistent)) -> [EQ,GT]
Just (_, AreaMaybeAllowOnlyWithConsistencyStatus (Just Exact)) -> [EQ]
_ -> [EQ,LT,GT]
intervalConstraintsToEndpointConstraints ::
((ix, ix), [PartialOrdering]) -> [[(((ix,Int), (ix,Int)), [PartialOrdering])]]
intervalConstraintsToEndpointConstraints ((ix1, ix2),rels) =
concat $ map forEachRel rels
where
endpoints1Comparable = [(((ix1,-1),(ix1, 1)), allowedEndpointRelations)]
endpoints2Comparable = [(((ix2,-1),(ix2, 1)), allowedEndpointRelations)]
endpointsComparable = endpoints1Comparable ++ endpoints2Comparable
forEachRel EQ = -- both endpoints agree
[
endpointsComparable ++
[(((ix1,-1),(ix2,-1)), [EQ]), (((ix1,1),(ix2,1)), [EQ])]
]
forEachRel GT =
-- the interval ix1 is indide ix2, but not equal
[
endpointsComparable ++
[(((ix1,-1),(ix2,-1)), [GT])] ++
[(((ix1,1),(ix2,1)), [EQ, LT])]
]
++
[
endpointsComparable ++
[(((ix1,-1),(ix2,-1)), [EQ, GT])] ++
[(((ix1,1),(ix2,1)), [LT])]
]
forEachRel LT =
-- the interval ix2 is indide ix1, but not equal
[
endpointsComparable ++
[(((ix2,-1),(ix1,-1)), [GT])] ++
[(((ix2,1),(ix1,1)), [EQ, LT])]
]
++
[
endpointsComparable ++
[(((ix2,-1),(ix1,-1)), [EQ, GT])] ++
[(((ix2,1),(ix1,1)), [LT])]
]
forEachRel NC =
-- either some pair of endpoints is NC:
[ endpointsComparable ++ [(((ix1,side1), (ix2, side2)),[NC])]
| side1 <- [-1,1], side2 <- [-1,1]
]
++
-- or the interval ix1 is to the left of ix2
[
endpointsComparable ++
[(((ix1,-1),(ix2,-1)), [LT]),
(((ix1,1),(ix2,1)), [LT])]
]
++
-- or the interval ix2 is to the left of ix1
[
endpointsComparable ++
[(((ix2,-1),(ix1,-1)), [LT]),
(((ix2,1),(ix1,1)), [LT])]
]
-- forEachRel _ = []
| michalkonecny/aern | aern-interval/src/Numeric/AERN/Basics/Interval/RefinementOrder.hs | bsd-3-clause | 16,233 | 30 | 17 | 4,817 | 3,921 | 2,153 | 1,768 | 311 | 13 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoMonoPatBinds #-}
module Example where
import Data.Piso
import Data.Piso.TH
data Person = Person
{ name :: String
, gender :: Gender
, age :: Int
, location :: Coords
} deriving (Eq, Show)
data Gender = Male | Female
deriving (Eq, Show)
data Coords = Coords { lat :: Float, lng :: Float }
deriving (Eq, Show)
person :: Piso (String :- Gender :- Int :- Coords :- t) (Person :- t)
person = $(derivePisos ''Person)
male :: Piso t (Gender :- t)
female :: Piso t (Gender :- t)
(male, female) = $(derivePisos ''Gender)
coords :: Piso (Float :- Float :- t) (Coords :- t)
coords = $(derivePisos ''Coords)
| MedeaMelana/Piso | ExampleTH.hs | bsd-3-clause | 711 | 0 | 10 | 156 | 262 | 148 | 114 | 23 | 1 |
import System.Time.Monotonic.Direct
import Data.Word (Word32)
import Data.Time.Clock (DiffTime)
test :: DiffTime -> Word32 -> Word32 -> IO Bool
test expected new old =
return $ diffMSec32 new old == expected
&& diffMSec32 old new == -expected
where
diffMSec32 = systemClockDiffTime systemClock_GetTickCount
main :: IO ()
main = do
True <- test 0 100 100
True <- test 0 0 0
True <- test 0 maxBound maxBound
True <- test 0.001 101 100
True <- test (-0.001) 100 101
True <- test 2000000 3000000000 1000000000
True <- test (-2000000) 1000000000 3000000000
True <- test 0.001 minBound maxBound
True <- test (-0.001) maxBound minBound
putStrLn "All tests passed"
| joeyadams/haskell-system-time-monotonic | testing/diffMSec32.hs | bsd-3-clause | 740 | 0 | 10 | 189 | 261 | 125 | 136 | 20 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
import Control.Lens ((^.), (.~), (%~), (&), ix, over, mapping)
import Control.Monad (forM, forM_, when, foldM, join, (>>))
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Lazy as LBS
import Data.Text (Text)
import qualified Data.Text as T
import Data.Vector ((!))
import qualified Data.Vector as V
import Data.Vector.Lens (toVectorOf)
import Data.Yaml (FromJSON(..), (.:))
import qualified Data.Yaml as Y
import qualified Data.Csv as Csv
import Linear.V3 (V3, _x, _y, _z)
import Numeric.Units.Dimensional ((*~))
import qualified Numeric.Units.Dimensional as D
import System.Exit (exitFailure)
import System.IO (withFile, IOMode(WriteMode))
import TensorFlow.Core as TF
import Orbits.System (System, name, bodies, names, time, velocity, position)
import Orbits.Units (simTime, simEnergy, simVelocity, simLength, day, year, inUnit)
import Orbits.Simulation (getBodies, getEnergy, doStep)
import Orbits.Simulation.TensorFlow (createSimulation)
-- | Save the history of a single body to a CSV file
saveBodyHistory :: (Floating a, Csv.ToField a)
=> FilePath -- ^ Path to CSV file to save. This file will be overwritten if it exists.
-> Text -- ^ Name of body
-> Int -- ^ Index of body in each system system of the history.
-- This must be the same for each system.
-> [System a] -- ^ System history.
-> IO ()
saveBodyHistory fileName bodyName bodyId history =
withFile fileName WriteMode $ \file ->
forM_ history $ \sys ->
let t = sys^.time.inUnit simTime
body = (sys^.bodies) ! bodyId
position' = body^.position.mapping (inUnit simLength)
velocity' = body^.velocity.mapping (inUnit simVelocity)
in LBS.hPut file $ Csv.encode
[( t, position'^._x, position'^._y, position'^._z
, velocity'^._x, velocity'^._y, velocity'^._z)]
main :: IO ()
main = TF.runSession $ do
system0 <- liftIO $
Y.decodeFileEither "solar_system.yaml" >>=
either (\err -> putStrLn (Y.prettyPrintParseException err) >> exitFailure) return
sim <- TF.build $ createSimulation $ system0^.bodies
let dt = 0.1 *~ day
outputPeriod = 10 *~ day
totalTime = 10 *~ year
totalSteps = (totalTime D./ dt)^.inUnit D.one
stepsPerOutput = ceiling $ (outputPeriod D./ dt)^.inUnit D.one
numOutputs = ceiling $ totalSteps / fromIntegral stepsPerOutput
printEnergy system energy =
liftIO $ putStrLn $
"energy at time " ++ D.showIn simTime (system^.time) ++
" = " ++ D.showIn simEnergy energy
energy0 <- sim^.getEnergy
printEnergy system0 energy0
systems <- forM ([0..numOutputs] :: [Int]) $ \i -> do
forM_ ([0..stepsPerOutput] :: [Int]) $ \j -> (sim^.doStep) dt
newBodies <- sim^.getBodies
return $ system0 & time %~ (D.+ (fromIntegral (i*stepsPerOutput) *~ D.one) D.* dt)
& bodies .~ newBodies
let system1 = last systems
energy1 <- sim^.getEnergy
printEnergy system1 energy1
liftIO $ (system0^.names) & V.imapM_ (\i name ->
saveBodyHistory
(T.unpack name ++ ".csv")
name i (system0 : systems))
| bjoeris/orbits-haskell-tensorflow | app/Main.hs | bsd-3-clause | 3,407 | 0 | 22 | 808 | 1,051 | 591 | 460 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Numeral.FR.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Numeral.FR.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "FR Tests"
[ makeCorpusTest [This Numeral] corpus
]
| rfranek/duckling | tests/Duckling/Numeral/FR/Tests.hs | bsd-3-clause | 600 | 0 | 9 | 96 | 80 | 51 | 29 | 11 | 1 |
-- | Handler that allows looking up video's on YouTube
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.YouTube
( handler
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import Text.XmlHtml
import Text.XmlHtml.Cursor
--------------------------------------------------------------------------------
import NumberSix.Bang
import NumberSix.Irc
import NumberSix.Message
import NumberSix.Util.BitLy
import NumberSix.Util.Error
import NumberSix.Util.Http
--------------------------------------------------------------------------------
youTube :: Text -> IO Text
youTube query = do
result <- httpScrape Xml url id $ \cursor -> do
-- Find entry and title, easy...
entry <- findChild (byTagName "entry") cursor
title <- nodeText . current <$> findChild (byTagName "title") entry
-- Also drop the '&feature...' part from the URL
link <- findChild (byTagNameAttrs "link" [("rel", "alternate")]) entry
href <- T.takeWhile (/= '&') <$> getAttribute "href" (current link)
return (title, href)
case result of
Just (text, href) -> textAndUrl text href
Nothing -> randomError
where
url = "http://gdata.youtube.com/feeds/api/videos?q=" <> urlEncode query
--------------------------------------------------------------------------------
handler :: UninitializedHandler
handler = makeBangHandler "YouTube" ["!youtube", "!y"] $ liftIO . youTube
| itkovian/number-six | src/NumberSix/Handlers/YouTube.hs | bsd-3-clause | 1,755 | 0 | 17 | 409 | 340 | 187 | 153 | 29 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
--
-- The register liveness determinator
--
-- (c) The University of Glasgow 2004-2013
--
-----------------------------------------------------------------------------
module RegAlloc.Liveness (
RegSet,
RegMap, emptyRegMap,
BlockMap, emptyBlockMap,
LiveCmmDecl,
InstrSR (..),
LiveInstr (..),
Liveness (..),
LiveInfo (..),
LiveBasicBlock,
mapBlockTop, mapBlockTopM, mapSCCM,
mapGenBlockTop, mapGenBlockTopM,
stripLive,
stripLiveBlock,
slurpConflicts,
slurpReloadCoalesce,
eraseDeltasLive,
patchEraseLive,
patchRegsLiveInstr,
reverseBlocksInTops,
regLiveness,
natCmmTopToLive
) where
import Reg
import Instruction
import BlockId
import Cmm hiding (RegSet)
import PprCmm()
import Digraph
import DynFlags
import MonadUtils
import Outputable
import Platform
import UniqSet
import UniqFM
import UniqSupply
import Bag
import State
import Data.List
import Data.Maybe
import Data.Map (Map)
import Data.Set (Set)
import qualified Data.Map as Map
-----------------------------------------------------------------------------
type RegSet = UniqSet Reg
type RegMap a = UniqFM a
emptyRegMap :: UniqFM a
emptyRegMap = emptyUFM
type BlockMap a = BlockEnv a
-- | A top level thing which carries liveness information.
type LiveCmmDecl statics instr
= GenCmmDecl
statics
LiveInfo
[SCC (LiveBasicBlock instr)]
-- | The register allocator also wants to use SPILL/RELOAD meta instructions,
-- so we'll keep those here.
data InstrSR instr
-- | A real machine instruction
= Instr instr
-- | spill this reg to a stack slot
| SPILL Reg Int
-- | reload this reg from a stack slot
| RELOAD Int Reg
instance Instruction instr => Instruction (InstrSR instr) where
regUsageOfInstr platform i
= case i of
Instr instr -> regUsageOfInstr platform instr
SPILL reg _ -> RU [reg] []
RELOAD _ reg -> RU [] [reg]
patchRegsOfInstr i f
= case i of
Instr instr -> Instr (patchRegsOfInstr instr f)
SPILL reg slot -> SPILL (f reg) slot
RELOAD slot reg -> RELOAD slot (f reg)
isJumpishInstr i
= case i of
Instr instr -> isJumpishInstr instr
_ -> False
jumpDestsOfInstr i
= case i of
Instr instr -> jumpDestsOfInstr instr
_ -> []
patchJumpInstr i f
= case i of
Instr instr -> Instr (patchJumpInstr instr f)
_ -> i
mkSpillInstr = error "mkSpillInstr[InstrSR]: Not making SPILL meta-instr"
mkLoadInstr = error "mkLoadInstr[InstrSR]: Not making LOAD meta-instr"
takeDeltaInstr i
= case i of
Instr instr -> takeDeltaInstr instr
_ -> Nothing
isMetaInstr i
= case i of
Instr instr -> isMetaInstr instr
_ -> False
mkRegRegMoveInstr platform r1 r2
= Instr (mkRegRegMoveInstr platform r1 r2)
takeRegRegMoveInstr i
= case i of
Instr instr -> takeRegRegMoveInstr instr
_ -> Nothing
mkJumpInstr target = map Instr (mkJumpInstr target)
mkStackAllocInstr platform amount =
Instr (mkStackAllocInstr platform amount)
mkStackDeallocInstr platform amount =
Instr (mkStackDeallocInstr platform amount)
-- | An instruction with liveness information.
data LiveInstr instr
= LiveInstr (InstrSR instr) (Maybe Liveness)
-- | Liveness information.
-- The regs which die are ones which are no longer live in the *next* instruction
-- in this sequence.
-- (NB. if the instruction is a jump, these registers might still be live
-- at the jump target(s) - you have to check the liveness at the destination
-- block to find out).
data Liveness
= Liveness
{ liveBorn :: RegSet -- ^ registers born in this instruction (written to for first time).
, liveDieRead :: RegSet -- ^ registers that died because they were read for the last time.
, liveDieWrite :: RegSet } -- ^ registers that died because they were clobbered by something.
-- | Stash regs live on entry to each basic block in the info part of the cmm code.
data LiveInfo
= LiveInfo
(BlockEnv CmmStatics) -- cmm info table static stuff
[BlockId] -- entry points (first one is the
-- entry point for the proc).
(Maybe (BlockMap RegSet)) -- argument locals live on entry to this block
(Map BlockId (Set Int)) -- stack slots live on entry to this block
-- | A basic block with liveness information.
type LiveBasicBlock instr
= GenBasicBlock (LiveInstr instr)
instance Outputable instr
=> Outputable (InstrSR instr) where
ppr (Instr realInstr)
= ppr realInstr
ppr (SPILL reg slot)
= hcat [
text "\tSPILL",
char ' ',
ppr reg,
comma,
text "SLOT" <> parens (int slot)]
ppr (RELOAD slot reg)
= hcat [
text "\tRELOAD",
char ' ',
text "SLOT" <> parens (int slot),
comma,
ppr reg]
instance Outputable instr
=> Outputable (LiveInstr instr) where
ppr (LiveInstr instr Nothing)
= ppr instr
ppr (LiveInstr instr (Just live))
= ppr instr
$$ (nest 8
$ vcat
[ pprRegs (text "# born: ") (liveBorn live)
, pprRegs (text "# r_dying: ") (liveDieRead live)
, pprRegs (text "# w_dying: ") (liveDieWrite live) ]
$+$ space)
where pprRegs :: SDoc -> RegSet -> SDoc
pprRegs name regs
| isEmptyUniqSet regs = empty
| otherwise = name <> (pprUFM regs (hcat . punctuate space . map ppr))
instance Outputable LiveInfo where
ppr (LiveInfo mb_static entryIds liveVRegsOnEntry liveSlotsOnEntry)
= (ppr mb_static)
$$ text "# entryIds = " <> ppr entryIds
$$ text "# liveVRegsOnEntry = " <> ppr liveVRegsOnEntry
$$ text "# liveSlotsOnEntry = " <> text (show liveSlotsOnEntry)
-- | map a function across all the basic blocks in this code
--
mapBlockTop
:: (LiveBasicBlock instr -> LiveBasicBlock instr)
-> LiveCmmDecl statics instr -> LiveCmmDecl statics instr
mapBlockTop f cmm
= evalState (mapBlockTopM (\x -> return $ f x) cmm) ()
-- | map a function across all the basic blocks in this code (monadic version)
--
mapBlockTopM
:: Monad m
=> (LiveBasicBlock instr -> m (LiveBasicBlock instr))
-> LiveCmmDecl statics instr -> m (LiveCmmDecl statics instr)
mapBlockTopM _ cmm@(CmmData{})
= return cmm
mapBlockTopM f (CmmProc header label live sccs)
= do sccs' <- mapM (mapSCCM f) sccs
return $ CmmProc header label live sccs'
mapSCCM :: Monad m => (a -> m b) -> SCC a -> m (SCC b)
mapSCCM f (AcyclicSCC x)
= do x' <- f x
return $ AcyclicSCC x'
mapSCCM f (CyclicSCC xs)
= do xs' <- mapM f xs
return $ CyclicSCC xs'
-- map a function across all the basic blocks in this code
mapGenBlockTop
:: (GenBasicBlock i -> GenBasicBlock i)
-> (GenCmmDecl d h (ListGraph i) -> GenCmmDecl d h (ListGraph i))
mapGenBlockTop f cmm
= evalState (mapGenBlockTopM (\x -> return $ f x) cmm) ()
-- | map a function across all the basic blocks in this code (monadic version)
mapGenBlockTopM
:: Monad m
=> (GenBasicBlock i -> m (GenBasicBlock i))
-> (GenCmmDecl d h (ListGraph i) -> m (GenCmmDecl d h (ListGraph i)))
mapGenBlockTopM _ cmm@(CmmData{})
= return cmm
mapGenBlockTopM f (CmmProc header label live (ListGraph blocks))
= do blocks' <- mapM f blocks
return $ CmmProc header label live (ListGraph blocks')
-- | Slurp out the list of register conflicts and reg-reg moves from this top level thing.
-- Slurping of conflicts and moves is wrapped up together so we don't have
-- to make two passes over the same code when we want to build the graph.
--
slurpConflicts
:: Instruction instr
=> LiveCmmDecl statics instr
-> (Bag (UniqSet Reg), Bag (Reg, Reg))
slurpConflicts live
= slurpCmm (emptyBag, emptyBag) live
where slurpCmm rs CmmData{} = rs
slurpCmm rs (CmmProc info _ _ sccs)
= foldl' (slurpSCC info) rs sccs
slurpSCC info rs (AcyclicSCC b)
= slurpBlock info rs b
slurpSCC info rs (CyclicSCC bs)
= foldl' (slurpBlock info) rs bs
slurpBlock info rs (BasicBlock blockId instrs)
| LiveInfo _ _ (Just blockLive) _ <- info
, Just rsLiveEntry <- mapLookup blockId blockLive
, (conflicts, moves) <- slurpLIs rsLiveEntry rs instrs
= (consBag rsLiveEntry conflicts, moves)
| otherwise
= panic "Liveness.slurpConflicts: bad block"
slurpLIs rsLive (conflicts, moves) []
= (consBag rsLive conflicts, moves)
slurpLIs rsLive rs (LiveInstr _ Nothing : lis)
= slurpLIs rsLive rs lis
slurpLIs rsLiveEntry (conflicts, moves) (LiveInstr instr (Just live) : lis)
= let
-- regs that die because they are read for the last time at the start of an instruction
-- are not live across it.
rsLiveAcross = rsLiveEntry `minusUniqSet` (liveDieRead live)
-- regs live on entry to the next instruction.
-- be careful of orphans, make sure to delete dying regs _after_ unioning
-- in the ones that are born here.
rsLiveNext = (rsLiveAcross `unionUniqSets` (liveBorn live))
`minusUniqSet` (liveDieWrite live)
-- orphan vregs are the ones that die in the same instruction they are born in.
-- these are likely to be results that are never used, but we still
-- need to assign a hreg to them..
rsOrphans = intersectUniqSets
(liveBorn live)
(unionUniqSets (liveDieWrite live) (liveDieRead live))
--
rsConflicts = unionUniqSets rsLiveNext rsOrphans
in case takeRegRegMoveInstr instr of
Just rr -> slurpLIs rsLiveNext
( consBag rsConflicts conflicts
, consBag rr moves) lis
Nothing -> slurpLIs rsLiveNext
( consBag rsConflicts conflicts
, moves) lis
-- | For spill\/reloads
--
-- SPILL v1, slot1
-- ...
-- RELOAD slot1, v2
--
-- If we can arrange that v1 and v2 are allocated to the same hreg it's more likely
-- the spill\/reload instrs can be cleaned and replaced by a nop reg-reg move.
--
--
slurpReloadCoalesce
:: forall statics instr. Instruction instr
=> LiveCmmDecl statics instr
-> Bag (Reg, Reg)
slurpReloadCoalesce live
= slurpCmm emptyBag live
where
slurpCmm :: Bag (Reg, Reg)
-> GenCmmDecl t t1 [SCC (LiveBasicBlock instr)]
-> Bag (Reg, Reg)
slurpCmm cs CmmData{} = cs
slurpCmm cs (CmmProc _ _ _ sccs)
= slurpComp cs (flattenSCCs sccs)
slurpComp :: Bag (Reg, Reg)
-> [LiveBasicBlock instr]
-> Bag (Reg, Reg)
slurpComp cs blocks
= let (moveBags, _) = runState (slurpCompM blocks) emptyUFM
in unionManyBags (cs : moveBags)
slurpCompM :: [LiveBasicBlock instr]
-> State (UniqFM [UniqFM Reg]) [Bag (Reg, Reg)]
slurpCompM blocks
= do -- run the analysis once to record the mapping across jumps.
mapM_ (slurpBlock False) blocks
-- run it a second time while using the information from the last pass.
-- We /could/ run this many more times to deal with graphical control
-- flow and propagating info across multiple jumps, but it's probably
-- not worth the trouble.
mapM (slurpBlock True) blocks
slurpBlock :: Bool -> LiveBasicBlock instr
-> State (UniqFM [UniqFM Reg]) (Bag (Reg, Reg))
slurpBlock propagate (BasicBlock blockId instrs)
= do -- grab the slot map for entry to this block
slotMap <- if propagate
then getSlotMap blockId
else return emptyUFM
(_, mMoves) <- mapAccumLM slurpLI slotMap instrs
return $ listToBag $ catMaybes mMoves
slurpLI :: UniqFM Reg -- current slotMap
-> LiveInstr instr
-> State (UniqFM [UniqFM Reg]) -- blockId -> [slot -> reg]
-- for tracking slotMaps across jumps
( UniqFM Reg -- new slotMap
, Maybe (Reg, Reg)) -- maybe a new coalesce edge
slurpLI slotMap li
-- remember what reg was stored into the slot
| LiveInstr (SPILL reg slot) _ <- li
, slotMap' <- addToUFM slotMap slot reg
= return (slotMap', Nothing)
-- add an edge between the this reg and the last one stored into the slot
| LiveInstr (RELOAD slot reg) _ <- li
= case lookupUFM slotMap slot of
Just reg2
| reg /= reg2 -> return (slotMap, Just (reg, reg2))
| otherwise -> return (slotMap, Nothing)
Nothing -> return (slotMap, Nothing)
-- if we hit a jump, remember the current slotMap
| LiveInstr (Instr instr) _ <- li
, targets <- jumpDestsOfInstr instr
, not $ null targets
= do mapM_ (accSlotMap slotMap) targets
return (slotMap, Nothing)
| otherwise
= return (slotMap, Nothing)
-- record a slotmap for an in edge to this block
accSlotMap slotMap blockId
= modify (\s -> addToUFM_C (++) s blockId [slotMap])
-- work out the slot map on entry to this block
-- if we have slot maps for multiple in-edges then we need to merge them.
getSlotMap blockId
= do map <- get
let slotMaps = fromMaybe [] (lookupUFM map blockId)
return $ foldr mergeSlotMaps emptyUFM slotMaps
mergeSlotMaps :: UniqFM Reg -> UniqFM Reg -> UniqFM Reg
mergeSlotMaps map1 map2
= listToUFM
$ [ (k, r1)
| (k, r1) <- nonDetUFMToList map1
-- This is non-deterministic but we do not
-- currently support deterministic code-generation.
-- See Note [Unique Determinism and code generation]
, case lookupUFM map2 k of
Nothing -> False
Just r2 -> r1 == r2 ]
-- | Strip away liveness information, yielding NatCmmDecl
stripLive
:: (Outputable statics, Outputable instr, Instruction instr)
=> DynFlags
-> LiveCmmDecl statics instr
-> NatCmmDecl statics instr
stripLive dflags live
= stripCmm live
where stripCmm :: (Outputable statics, Outputable instr, Instruction instr)
=> LiveCmmDecl statics instr -> NatCmmDecl statics instr
stripCmm (CmmData sec ds) = CmmData sec ds
stripCmm (CmmProc (LiveInfo info (first_id:_) _ _) label live sccs)
= let final_blocks = flattenSCCs sccs
-- make sure the block that was first in the input list
-- stays at the front of the output. This is the entry point
-- of the proc, and it needs to come first.
((first':_), rest')
= partition ((== first_id) . blockId) final_blocks
in CmmProc info label live
(ListGraph $ map (stripLiveBlock dflags) $ first' : rest')
-- procs used for stg_split_markers don't contain any blocks, and have no first_id.
stripCmm (CmmProc (LiveInfo info [] _ _) label live [])
= CmmProc info label live (ListGraph [])
-- If the proc has blocks but we don't know what the first one was, then we're dead.
stripCmm proc
= pprPanic "RegAlloc.Liveness.stripLive: no first_id on proc" (ppr proc)
-- | Strip away liveness information from a basic block,
-- and make real spill instructions out of SPILL, RELOAD pseudos along the way.
stripLiveBlock
:: Instruction instr
=> DynFlags
-> LiveBasicBlock instr
-> NatBasicBlock instr
stripLiveBlock dflags (BasicBlock i lis)
= BasicBlock i instrs'
where (instrs', _)
= runState (spillNat [] lis) 0
spillNat acc []
= return (reverse acc)
spillNat acc (LiveInstr (SPILL reg slot) _ : instrs)
= do delta <- get
spillNat (mkSpillInstr dflags reg delta slot : acc) instrs
spillNat acc (LiveInstr (RELOAD slot reg) _ : instrs)
= do delta <- get
spillNat (mkLoadInstr dflags reg delta slot : acc) instrs
spillNat acc (LiveInstr (Instr instr) _ : instrs)
| Just i <- takeDeltaInstr instr
= do put i
spillNat acc instrs
spillNat acc (LiveInstr (Instr instr) _ : instrs)
= spillNat (instr : acc) instrs
-- | Erase Delta instructions.
eraseDeltasLive
:: Instruction instr
=> LiveCmmDecl statics instr
-> LiveCmmDecl statics instr
eraseDeltasLive cmm
= mapBlockTop eraseBlock cmm
where
eraseBlock (BasicBlock id lis)
= BasicBlock id
$ filter (\(LiveInstr i _) -> not $ isJust $ takeDeltaInstr i)
$ lis
-- | Patch the registers in this code according to this register mapping.
-- also erase reg -> reg moves when the reg is the same.
-- also erase reg -> reg moves when the destination dies in this instr.
patchEraseLive
:: Instruction instr
=> (Reg -> Reg)
-> LiveCmmDecl statics instr -> LiveCmmDecl statics instr
patchEraseLive patchF cmm
= patchCmm cmm
where
patchCmm cmm@CmmData{} = cmm
patchCmm (CmmProc info label live sccs)
| LiveInfo static id (Just blockMap) mLiveSlots <- info
= let
patchRegSet set = mkUniqSet $ map patchF $ nonDetEltsUFM set
-- See Note [Unique Determinism and code generation]
blockMap' = mapMap patchRegSet blockMap
info' = LiveInfo static id (Just blockMap') mLiveSlots
in CmmProc info' label live $ map patchSCC sccs
| otherwise
= panic "RegAlloc.Liveness.patchEraseLive: no blockMap"
patchSCC (AcyclicSCC b) = AcyclicSCC (patchBlock b)
patchSCC (CyclicSCC bs) = CyclicSCC (map patchBlock bs)
patchBlock (BasicBlock id lis)
= BasicBlock id $ patchInstrs lis
patchInstrs [] = []
patchInstrs (li : lis)
| LiveInstr i (Just live) <- li'
, Just (r1, r2) <- takeRegRegMoveInstr i
, eatMe r1 r2 live
= patchInstrs lis
| otherwise
= li' : patchInstrs lis
where li' = patchRegsLiveInstr patchF li
eatMe r1 r2 live
-- source and destination regs are the same
| r1 == r2 = True
-- destination reg is never used
| elementOfUniqSet r2 (liveBorn live)
, elementOfUniqSet r2 (liveDieRead live) || elementOfUniqSet r2 (liveDieWrite live)
= True
| otherwise = False
-- | Patch registers in this LiveInstr, including the liveness information.
--
patchRegsLiveInstr
:: Instruction instr
=> (Reg -> Reg)
-> LiveInstr instr -> LiveInstr instr
patchRegsLiveInstr patchF li
= case li of
LiveInstr instr Nothing
-> LiveInstr (patchRegsOfInstr instr patchF) Nothing
LiveInstr instr (Just live)
-> LiveInstr
(patchRegsOfInstr instr patchF)
(Just live
{ -- WARNING: have to go via lists here because patchF changes the uniq in the Reg
liveBorn = mkUniqSet $ map patchF $ nonDetEltsUFM $ liveBorn live
, liveDieRead = mkUniqSet $ map patchF $ nonDetEltsUFM $ liveDieRead live
, liveDieWrite = mkUniqSet $ map patchF $ nonDetEltsUFM $ liveDieWrite live })
-- See Note [Unique Determinism and code generation]
--------------------------------------------------------------------------------
-- | Convert a NatCmmDecl to a LiveCmmDecl, with empty liveness information
natCmmTopToLive
:: Instruction instr
=> NatCmmDecl statics instr
-> LiveCmmDecl statics instr
natCmmTopToLive (CmmData i d)
= CmmData i d
natCmmTopToLive (CmmProc info lbl live (ListGraph []))
= CmmProc (LiveInfo info [] Nothing Map.empty) lbl live []
natCmmTopToLive proc@(CmmProc info lbl live (ListGraph blocks@(first : _)))
= let first_id = blockId first
all_entry_ids = entryBlocks proc
sccs = sccBlocks blocks all_entry_ids
entry_ids = filter (/= first_id) all_entry_ids
sccsLive = map (fmap (\(BasicBlock l instrs) ->
BasicBlock l (map (\i -> LiveInstr (Instr i) Nothing) instrs)))
$ sccs
in CmmProc (LiveInfo info (first_id : entry_ids) Nothing Map.empty)
lbl live sccsLive
--
-- Compute the liveness graph of the set of basic blocks. Important:
-- we also discard any unreachable code here, starting from the entry
-- points (the first block in the list, and any blocks with info
-- tables). Unreachable code arises when code blocks are orphaned in
-- earlier optimisation passes, and may confuse the register allocator
-- by referring to registers that are not initialised. It's easy to
-- discard the unreachable code as part of the SCC pass, so that's
-- exactly what we do. (#7574)
--
sccBlocks
:: Instruction instr
=> [NatBasicBlock instr]
-> [BlockId]
-> [SCC (NatBasicBlock instr)]
sccBlocks blocks entries = map (fmap get_node) sccs
where
-- nodes :: [(NatBasicBlock instr, Unique, [Unique])]
nodes = [ (block, id, getOutEdges instrs)
| block@(BasicBlock id instrs) <- blocks ]
g1 = graphFromEdgedVerticesUniq nodes
reachable :: BlockSet
reachable = setFromList [ id | (_,id,_) <- reachablesG g1 roots ]
g2 = graphFromEdgedVerticesUniq [ node | node@(_,id,_) <- nodes
, id `setMember` reachable ]
sccs = stronglyConnCompG g2
get_node (n, _, _) = n
getOutEdges :: Instruction instr => [instr] -> [BlockId]
getOutEdges instrs = concat $ map jumpDestsOfInstr instrs
-- This is truly ugly, but I don't see a good alternative.
-- Digraph just has the wrong API. We want to identify nodes
-- by their keys (BlockId), but Digraph requires the whole
-- node: (NatBasicBlock, BlockId, [BlockId]). This takes
-- advantage of the fact that Digraph only looks at the key,
-- even though it asks for the whole triple.
roots = [(panic "sccBlocks",b,panic "sccBlocks") | b <- entries ]
--------------------------------------------------------------------------------
-- Annotate code with register liveness information
--
regLiveness
:: (Outputable instr, Instruction instr)
=> Platform
-> LiveCmmDecl statics instr
-> UniqSM (LiveCmmDecl statics instr)
regLiveness _ (CmmData i d)
= return $ CmmData i d
regLiveness _ (CmmProc info lbl live [])
| LiveInfo static mFirst _ _ <- info
= return $ CmmProc
(LiveInfo static mFirst (Just mapEmpty) Map.empty)
lbl live []
regLiveness platform (CmmProc info lbl live sccs)
| LiveInfo static mFirst _ liveSlotsOnEntry <- info
= let (ann_sccs, block_live) = computeLiveness platform sccs
in return $ CmmProc (LiveInfo static mFirst (Just block_live) liveSlotsOnEntry)
lbl live ann_sccs
-- -----------------------------------------------------------------------------
-- | Check ordering of Blocks
-- The computeLiveness function requires SCCs to be in reverse
-- dependent order. If they're not the liveness information will be
-- wrong, and we'll get a bad allocation. Better to check for this
-- precondition explicitly or some other poor sucker will waste a
-- day staring at bad assembly code..
--
checkIsReverseDependent
:: Instruction instr
=> [SCC (LiveBasicBlock instr)] -- ^ SCCs of blocks that we're about to run the liveness determinator on.
-> Maybe BlockId -- ^ BlockIds that fail the test (if any)
checkIsReverseDependent sccs'
= go emptyUniqSet sccs'
where go _ []
= Nothing
go blocksSeen (AcyclicSCC block : sccs)
= let dests = slurpJumpDestsOfBlock block
blocksSeen' = unionUniqSets blocksSeen $ mkUniqSet [blockId block]
badDests = dests `minusUniqSet` blocksSeen'
in case nonDetEltsUFM badDests of
-- See Note [Unique Determinism and code generation]
[] -> go blocksSeen' sccs
bad : _ -> Just bad
go blocksSeen (CyclicSCC blocks : sccs)
= let dests = unionManyUniqSets $ map slurpJumpDestsOfBlock blocks
blocksSeen' = unionUniqSets blocksSeen $ mkUniqSet $ map blockId blocks
badDests = dests `minusUniqSet` blocksSeen'
in case nonDetEltsUFM badDests of
-- See Note [Unique Determinism and code generation]
[] -> go blocksSeen' sccs
bad : _ -> Just bad
slurpJumpDestsOfBlock (BasicBlock _ instrs)
= unionManyUniqSets
$ map (mkUniqSet . jumpDestsOfInstr)
[ i | LiveInstr i _ <- instrs]
-- | If we've compute liveness info for this code already we have to reverse
-- the SCCs in each top to get them back to the right order so we can do it again.
reverseBlocksInTops :: LiveCmmDecl statics instr -> LiveCmmDecl statics instr
reverseBlocksInTops top
= case top of
CmmData{} -> top
CmmProc info lbl live sccs -> CmmProc info lbl live (reverse sccs)
-- | Computing liveness
--
-- On entry, the SCCs must be in "reverse" order: later blocks may transfer
-- control to earlier ones only, else `panic`.
--
-- The SCCs returned are in the *opposite* order, which is exactly what we
-- want for the next pass.
--
computeLiveness
:: (Outputable instr, Instruction instr)
=> Platform
-> [SCC (LiveBasicBlock instr)]
-> ([SCC (LiveBasicBlock instr)], -- instructions annotated with list of registers
-- which are "dead after this instruction".
BlockMap RegSet) -- blocks annontated with set of live registers
-- on entry to the block.
computeLiveness platform sccs
= case checkIsReverseDependent sccs of
Nothing -> livenessSCCs platform emptyBlockMap [] sccs
Just bad -> pprPanic "RegAlloc.Liveness.computeLivenss"
(vcat [ text "SCCs aren't in reverse dependent order"
, text "bad blockId" <+> ppr bad
, ppr sccs])
livenessSCCs
:: Instruction instr
=> Platform
-> BlockMap RegSet
-> [SCC (LiveBasicBlock instr)] -- accum
-> [SCC (LiveBasicBlock instr)]
-> ( [SCC (LiveBasicBlock instr)]
, BlockMap RegSet)
livenessSCCs _ blockmap done []
= (done, blockmap)
livenessSCCs platform blockmap done (AcyclicSCC block : sccs)
= let (blockmap', block') = livenessBlock platform blockmap block
in livenessSCCs platform blockmap' (AcyclicSCC block' : done) sccs
livenessSCCs platform blockmap done
(CyclicSCC blocks : sccs) =
livenessSCCs platform blockmap' (CyclicSCC blocks':done) sccs
where (blockmap', blocks')
= iterateUntilUnchanged linearLiveness equalBlockMaps
blockmap blocks
iterateUntilUnchanged
:: (a -> b -> (a,c)) -> (a -> a -> Bool)
-> a -> b
-> (a,c)
iterateUntilUnchanged f eq a b
= head $
concatMap tail $
groupBy (\(a1, _) (a2, _) -> eq a1 a2) $
iterate (\(a, _) -> f a b) $
(a, panic "RegLiveness.livenessSCCs")
linearLiveness
:: Instruction instr
=> BlockMap RegSet -> [LiveBasicBlock instr]
-> (BlockMap RegSet, [LiveBasicBlock instr])
linearLiveness = mapAccumL (livenessBlock platform)
-- probably the least efficient way to compare two
-- BlockMaps for equality.
equalBlockMaps a b
= a' == b'
where a' = map f $ mapToList a
b' = map f $ mapToList b
f (key,elt) = (key, nonDetEltsUFM elt)
-- See Note [Unique Determinism and code generation]
-- | Annotate a basic block with register liveness information.
--
livenessBlock
:: Instruction instr
=> Platform
-> BlockMap RegSet
-> LiveBasicBlock instr
-> (BlockMap RegSet, LiveBasicBlock instr)
livenessBlock platform blockmap (BasicBlock block_id instrs)
= let
(regsLiveOnEntry, instrs1)
= livenessBack platform emptyUniqSet blockmap [] (reverse instrs)
blockmap' = mapInsert block_id regsLiveOnEntry blockmap
instrs2 = livenessForward platform regsLiveOnEntry instrs1
output = BasicBlock block_id instrs2
in ( blockmap', output)
-- | Calculate liveness going forwards,
-- filling in when regs are born
livenessForward
:: Instruction instr
=> Platform
-> RegSet -- regs live on this instr
-> [LiveInstr instr] -> [LiveInstr instr]
livenessForward _ _ [] = []
livenessForward platform rsLiveEntry (li@(LiveInstr instr mLive) : lis)
| Nothing <- mLive
= li : livenessForward platform rsLiveEntry lis
| Just live <- mLive
, RU _ written <- regUsageOfInstr platform instr
= let
-- Regs that are written to but weren't live on entry to this instruction
-- are recorded as being born here.
rsBorn = mkUniqSet
$ filter (\r -> not $ elementOfUniqSet r rsLiveEntry) written
rsLiveNext = (rsLiveEntry `unionUniqSets` rsBorn)
`minusUniqSet` (liveDieRead live)
`minusUniqSet` (liveDieWrite live)
in LiveInstr instr (Just live { liveBorn = rsBorn })
: livenessForward platform rsLiveNext lis
-- | Calculate liveness going backwards,
-- filling in when regs die, and what regs are live across each instruction
livenessBack
:: Instruction instr
=> Platform
-> RegSet -- regs live on this instr
-> BlockMap RegSet -- regs live on entry to other BBs
-> [LiveInstr instr] -- instructions (accum)
-> [LiveInstr instr] -- instructions
-> (RegSet, [LiveInstr instr])
livenessBack _ liveregs _ done [] = (liveregs, done)
livenessBack platform liveregs blockmap acc (instr : instrs)
= let (liveregs', instr') = liveness1 platform liveregs blockmap instr
in livenessBack platform liveregs' blockmap (instr' : acc) instrs
-- don't bother tagging comments or deltas with liveness
liveness1
:: Instruction instr
=> Platform
-> RegSet
-> BlockMap RegSet
-> LiveInstr instr
-> (RegSet, LiveInstr instr)
liveness1 _ liveregs _ (LiveInstr instr _)
| isMetaInstr instr
= (liveregs, LiveInstr instr Nothing)
liveness1 platform liveregs blockmap (LiveInstr instr _)
| not_a_branch
= (liveregs1, LiveInstr instr
(Just $ Liveness
{ liveBorn = emptyUniqSet
, liveDieRead = mkUniqSet r_dying
, liveDieWrite = mkUniqSet w_dying }))
| otherwise
= (liveregs_br, LiveInstr instr
(Just $ Liveness
{ liveBorn = emptyUniqSet
, liveDieRead = mkUniqSet r_dying_br
, liveDieWrite = mkUniqSet w_dying }))
where
!(RU read written) = regUsageOfInstr platform instr
-- registers that were written here are dead going backwards.
-- registers that were read here are live going backwards.
liveregs1 = (liveregs `delListFromUniqSet` written)
`addListToUniqSet` read
-- registers that are not live beyond this point, are recorded
-- as dying here.
r_dying = [ reg | reg <- read, reg `notElem` written,
not (elementOfUniqSet reg liveregs) ]
w_dying = [ reg | reg <- written,
not (elementOfUniqSet reg liveregs) ]
-- union in the live regs from all the jump destinations of this
-- instruction.
targets = jumpDestsOfInstr instr -- where we go from here
not_a_branch = null targets
targetLiveRegs target
= case mapLookup target blockmap of
Just ra -> ra
Nothing -> emptyRegMap
live_from_branch = unionManyUniqSets (map targetLiveRegs targets)
liveregs_br = liveregs1 `unionUniqSets` live_from_branch
-- registers that are live only in the branch targets should
-- be listed as dying here.
live_branch_only = live_from_branch `minusUniqSet` liveregs
r_dying_br = nonDetEltsUFM (mkUniqSet r_dying `unionUniqSets`
live_branch_only)
-- See Note [Unique Determinism and code generation]
| sgillespie/ghc | compiler/nativeGen/RegAlloc/Liveness.hs | bsd-3-clause | 37,132 | 0 | 22 | 13,677 | 7,717 | 3,944 | 3,773 | 628 | 6 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Data.Bool (module M) where
import "base" Data.Bool as M
| Ye-Yong-Chi/codeworld | codeworld-base/src/Data/Bool.hs | apache-2.0 | 733 | 0 | 4 | 136 | 23 | 17 | 6 | 4 | 0 |
{-# LANGUAGE DoRec #-}
-- | Make sure this program runs without leaking memory
import FRP.Sodium
import Data.Maybe
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.DeepSeq
import System.Timeout
verbose = False
flam :: Event () -> Behavior Int -> Reactive (Behavior (Maybe Int))
flam e time = do
-- Test that this arrangement...
--
-- updates time
-- |
-- v
-- eStop <-- SNAPSHOT (timer)
-- | ^
-- v |
-- e --> eStart --> GATE --> HOLD |
-- ^ | |
-- | v |
-- notRunning <-- mRunning --> * ---> OUT
--
-- ...get cleaned up when 'flam' is switched out. The issue is the
-- GATE/HOLD cycle at the bottom left.
let eStart = snapshot (\() t -> Just t) e time
rec
let notRunning = fmap (not . isJust) mRunning
-- Only allow eStart through when we're not already running
mRunning <- hold Nothing $ merge (eStart `gate` notRunning) eStop
-- Stop it when it's been running for 5 ticks.
let eStop = filterJust $ snapshot (\t mRunning ->
case mRunning of
Just t0 | (t - t0) >= 5 -> Just Nothing
_ -> Nothing
) (updates time) mRunning
return mRunning
main = do
(e, push) <- sync newEvent
(eFlip, pushFlip) <- sync newEvent
(time, pushTime) <- sync $ newBehavior 0
out <- sync $ do
eInit <- flam e time
eFlam <- hold eInit (execute ((const $ flam e time) <$> eFlip))
switch eFlam
kill <- sync $ listen (value out) $ \x ->
if verbose then print x else (evaluate (rnf x) >> return ())
let loop t = do
sync $ pushTime t
sync $ push ()
when (t `mod` 18 == 0) $ sync $ pushFlip ()
loop (t+1)
timeout 4000000 $ loop 0
kill
| kevintvh/sodium | haskell/examples/tests/memory-test-8.hs | bsd-3-clause | 2,260 | 0 | 24 | 1,016 | 549 | 274 | 275 | 38 | 2 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1996-1998
Printing of Core syntax
-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module PprCore (
pprCoreExpr, pprParendExpr,
pprCoreBinding, pprCoreBindings, pprCoreAlt,
pprRules
) where
import CoreSyn
import Literal( pprLiteral )
import Name( pprInfixName, pprPrefixName )
import Var
import Id
import IdInfo
import Demand
import DataCon
import TyCon
import Type
import Coercion
import DynFlags
import BasicTypes
import Util
import Outputable
import FastString
import SrcLoc ( pprUserRealSpan )
{-
************************************************************************
* *
\subsection{Public interfaces for Core printing (excluding instances)}
* *
************************************************************************
@pprParendCoreExpr@ puts parens around non-atomic Core expressions.
-}
pprCoreBindings :: OutputableBndr b => [Bind b] -> SDoc
pprCoreBinding :: OutputableBndr b => Bind b -> SDoc
pprCoreExpr :: OutputableBndr b => Expr b -> SDoc
pprParendExpr :: OutputableBndr b => Expr b -> SDoc
pprCoreBindings = pprTopBinds
pprCoreBinding = pprTopBind
instance OutputableBndr b => Outputable (Bind b) where
ppr bind = ppr_bind bind
instance OutputableBndr b => Outputable (Expr b) where
ppr expr = pprCoreExpr expr
{-
************************************************************************
* *
\subsection{The guts}
* *
************************************************************************
-}
pprTopBinds :: OutputableBndr a => [Bind a] -> SDoc
pprTopBinds binds = vcat (map pprTopBind binds)
pprTopBind :: OutputableBndr a => Bind a -> SDoc
pprTopBind (NonRec binder expr)
= ppr_binding (binder,expr) $$ blankLine
pprTopBind (Rec [])
= ptext (sLit "Rec { }")
pprTopBind (Rec (b:bs))
= vcat [ptext (sLit "Rec {"),
ppr_binding b,
vcat [blankLine $$ ppr_binding b | b <- bs],
ptext (sLit "end Rec }"),
blankLine]
ppr_bind :: OutputableBndr b => Bind b -> SDoc
ppr_bind (NonRec val_bdr expr) = ppr_binding (val_bdr, expr)
ppr_bind (Rec binds) = vcat (map pp binds)
where
pp bind = ppr_binding bind <> semi
ppr_binding :: OutputableBndr b => (b, Expr b) -> SDoc
ppr_binding (val_bdr, expr)
= pprBndr LetBind val_bdr $$
hang (ppr val_bdr <+> equals) 2 (pprCoreExpr expr)
pprParendExpr expr = ppr_expr parens expr
pprCoreExpr expr = ppr_expr noParens expr
noParens :: SDoc -> SDoc
noParens pp = pp
ppr_expr :: OutputableBndr b => (SDoc -> SDoc) -> Expr b -> SDoc
-- The function adds parens in context that need
-- an atomic value (e.g. function args)
ppr_expr _ (Var name) = ppr name
ppr_expr add_par (Type ty) = add_par (ptext (sLit "TYPE") <+> ppr ty) -- Weird
ppr_expr add_par (Coercion co) = add_par (ptext (sLit "CO") <+> ppr co)
ppr_expr add_par (Lit lit) = pprLiteral add_par lit
ppr_expr add_par (Cast expr co)
= add_par $
sep [pprParendExpr expr,
ptext (sLit "`cast`") <+> pprCo co]
where
pprCo co = sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressCoercions dflags
then ptext (sLit "...")
else parens $
sep [ppr co, dcolon <+> ppr (coercionType co)]
ppr_expr add_par expr@(Lam _ _)
= let
(bndrs, body) = collectBinders expr
in
add_par $
hang (ptext (sLit "\\") <+> sep (map (pprBndr LambdaBind) bndrs) <+> arrow)
2 (pprCoreExpr body)
ppr_expr add_par expr@(App {})
= case collectArgs expr of { (fun, args) ->
let
pp_args = sep (map pprArg args)
val_args = dropWhile isTypeArg args -- Drop the type arguments for tuples
pp_tup_args = pprWithCommas pprCoreExpr val_args
in
case fun of
Var f -> case isDataConWorkId_maybe f of
-- Notice that we print the *worker*
-- for tuples in paren'd format.
Just dc | saturated
, Just sort <- tyConTuple_maybe tc
-> tupleParens sort pp_tup_args
where
tc = dataConTyCon dc
saturated = val_args `lengthIs` idArity f
_ -> add_par (hang (ppr f) 2 pp_args)
_ -> add_par (hang (pprParendExpr fun) 2 pp_args)
}
ppr_expr add_par (Case expr var ty [(con,args,rhs)])
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PprCaseAsLet dflags
then add_par $ -- See Note [Print case as let]
sep [ sep [ ptext (sLit "let! {")
<+> ppr_case_pat con args
<+> ptext (sLit "~")
<+> ppr_bndr var
, ptext (sLit "<-") <+> ppr_expr id expr
<+> ptext (sLit "} in") ]
, pprCoreExpr rhs
]
else add_par $
sep [sep [ptext (sLit "case") <+> pprCoreExpr expr,
ifPprDebug (braces (ppr ty)),
sep [ptext (sLit "of") <+> ppr_bndr var,
char '{' <+> ppr_case_pat con args <+> arrow]
],
pprCoreExpr rhs,
char '}'
]
where
ppr_bndr = pprBndr CaseBind
ppr_expr add_par (Case expr var ty alts)
= add_par $
sep [sep [ptext (sLit "case")
<+> pprCoreExpr expr
<+> ifPprDebug (braces (ppr ty)),
ptext (sLit "of") <+> ppr_bndr var <+> char '{'],
nest 2 (vcat (punctuate semi (map pprCoreAlt alts))),
char '}'
]
where
ppr_bndr = pprBndr CaseBind
-- special cases: let ... in let ...
-- ("disgusting" SLPJ)
{-
ppr_expr add_par (Let bind@(NonRec val_bdr rhs@(Let _ _)) body)
= add_par $
vcat [
hsep [ptext (sLit "let {"), (pprBndr LetBind val_bdr $$ ppr val_bndr), equals],
nest 2 (pprCoreExpr rhs),
ptext (sLit "} in"),
pprCoreExpr body ]
ppr_expr add_par (Let bind@(NonRec val_bdr rhs) expr@(Let _ _))
= add_par
(hang (ptext (sLit "let {"))
2 (hsep [ppr_binding (val_bdr,rhs),
ptext (sLit "} in")])
$$
pprCoreExpr expr)
-}
-- General case (recursive case, too)
ppr_expr add_par (Let bind expr)
= add_par $
sep [hang (ptext keyword) 2 (ppr_bind bind <+> ptext (sLit "} in")),
pprCoreExpr expr]
where
keyword = case bind of
Rec _ -> (sLit "letrec {")
NonRec _ _ -> (sLit "let {")
ppr_expr add_par (Tick tickish expr)
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PprShowTicks dflags
then add_par (sep [ppr tickish, pprCoreExpr expr])
else ppr_expr add_par expr
pprCoreAlt :: OutputableBndr a => (AltCon, [a] , Expr a) -> SDoc
pprCoreAlt (con, args, rhs)
= hang (ppr_case_pat con args <+> arrow) 2 (pprCoreExpr rhs)
ppr_case_pat :: OutputableBndr a => AltCon -> [a] -> SDoc
ppr_case_pat (DataAlt dc) args
| Just sort <- tyConTuple_maybe tc
= tupleParens sort (pprWithCommas ppr_bndr args)
where
ppr_bndr = pprBndr CaseBind
tc = dataConTyCon dc
ppr_case_pat con args
= ppr con <+> (fsep (map ppr_bndr args))
where
ppr_bndr = pprBndr CaseBind
-- | Pretty print the argument in a function application.
pprArg :: OutputableBndr a => Expr a -> SDoc
pprArg (Type ty)
= sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressTypeApplications dflags
then empty
else ptext (sLit "@") <+> pprParendType ty
pprArg (Coercion co) = ptext (sLit "@~") <+> pprParendCo co
pprArg expr = pprParendExpr expr
{-
Note [Print case as let]
~~~~~~~~~~~~~~~~~~~~~~~~
Single-branch case expressions are very common:
case x of y { I# x' ->
case p of q { I# p' -> ... } }
These are, in effect, just strict let's, with pattern matching.
With -dppr-case-as-let we print them as such:
let! { I# x' ~ y <- x } in
let! { I# p' ~ q <- p } in ...
Other printing bits-and-bobs used with the general @pprCoreBinding@
and @pprCoreExpr@ functions.
-}
instance OutputableBndr Var where
pprBndr = pprCoreBinder
pprInfixOcc = pprInfixName . varName
pprPrefixOcc = pprPrefixName . varName
pprCoreBinder :: BindingSite -> Var -> SDoc
pprCoreBinder LetBind binder
| isTyVar binder = pprKindedTyVarBndr binder
| otherwise = pprTypedLetBinder binder $$
ppIdInfo binder (idInfo binder)
-- Lambda bound type variables are preceded by "@"
pprCoreBinder bind_site bndr
= getPprStyle $ \ sty ->
pprTypedLamBinder bind_site (debugStyle sty) bndr
pprUntypedBinder :: Var -> SDoc
pprUntypedBinder binder
| isTyVar binder = ptext (sLit "@") <+> ppr binder -- NB: don't print kind
| otherwise = pprIdBndr binder
pprTypedLamBinder :: BindingSite -> Bool -> Var -> SDoc
-- For lambda and case binders, show the unfolding info (usually none)
pprTypedLamBinder bind_site debug_on var
= sdocWithDynFlags $ \dflags ->
case () of
_
| not debug_on -- Even dead binders can be one-shot
, isDeadBinder var -> char '_' <+> ppWhen (isId var)
(pprIdBndrInfo (idInfo var))
| not debug_on -- No parens, no kind info
, CaseBind <- bind_site -> pprUntypedBinder var
| suppress_sigs dflags -> pprUntypedBinder var
| isTyVar var -> parens (pprKindedTyVarBndr var)
| otherwise -> parens (hang (pprIdBndr var)
2 (vcat [ dcolon <+> pprType (idType var)
, pp_unf]))
where
suppress_sigs = gopt Opt_SuppressTypeSignatures
unf_info = unfoldingInfo (idInfo var)
pp_unf | hasSomeUnfolding unf_info = ptext (sLit "Unf=") <> ppr unf_info
| otherwise = empty
pprTypedLetBinder :: Var -> SDoc
-- Print binder with a type or kind signature (not paren'd)
pprTypedLetBinder binder
= sdocWithDynFlags $ \dflags ->
case () of
_
| isTyVar binder -> pprKindedTyVarBndr binder
| gopt Opt_SuppressTypeSignatures dflags -> pprIdBndr binder
| otherwise -> hang (pprIdBndr binder) 2 (dcolon <+> pprType (idType binder))
pprKindedTyVarBndr :: TyVar -> SDoc
-- Print a type variable binder with its kind (but not if *)
pprKindedTyVarBndr tyvar
= ptext (sLit "@") <+> pprTvBndr tyvar
-- pprIdBndr does *not* print the type
-- When printing any Id binder in debug mode, we print its inline pragma and one-shot-ness
pprIdBndr :: Id -> SDoc
pprIdBndr id = ppr id <+> pprIdBndrInfo (idInfo id)
pprIdBndrInfo :: IdInfo -> SDoc
pprIdBndrInfo info
= sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressIdInfo dflags
then empty
else megaSeqIdInfo info `seq` doc -- The seq is useful for poking on black holes
where
prag_info = inlinePragInfo info
occ_info = occInfo info
dmd_info = demandInfo info
lbv_info = oneShotInfo info
has_prag = not (isDefaultInlinePragma prag_info)
has_occ = not (isNoOcc occ_info)
has_dmd = not $ isTopDmd dmd_info
has_lbv = not (hasNoOneShotInfo lbv_info)
doc = showAttributes
[ (has_prag, ptext (sLit "InlPrag=") <> ppr prag_info)
, (has_occ, ptext (sLit "Occ=") <> ppr occ_info)
, (has_dmd, ptext (sLit "Dmd=") <> ppr dmd_info)
, (has_lbv , ptext (sLit "OS=") <> ppr lbv_info)
]
{-
-----------------------------------------------------
-- IdDetails and IdInfo
-----------------------------------------------------
-}
ppIdInfo :: Id -> IdInfo -> SDoc
ppIdInfo id info
= sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressIdInfo dflags
then empty
else
showAttributes
[ (True, pp_scope <> ppr (idDetails id))
, (has_arity, ptext (sLit "Arity=") <> int arity)
, (has_called_arity, ptext (sLit "CallArity=") <> int called_arity)
, (has_caf_info, ptext (sLit "Caf=") <> ppr caf_info)
, (True, ptext (sLit "Str=") <> pprStrictness str_info)
, (has_unf, ptext (sLit "Unf=") <> ppr unf_info)
, (not (null rules), ptext (sLit "RULES:") <+> vcat (map pprRule rules))
] -- Inline pragma, occ, demand, one-shot info
-- printed out with all binders (when debug is on);
-- see PprCore.pprIdBndr
where
pp_scope | isGlobalId id = ptext (sLit "GblId")
| isExportedId id = ptext (sLit "LclIdX")
| otherwise = ptext (sLit "LclId")
arity = arityInfo info
has_arity = arity /= 0
called_arity = callArityInfo info
has_called_arity = called_arity /= 0
caf_info = cafInfo info
has_caf_info = not (mayHaveCafRefs caf_info)
str_info = strictnessInfo info
unf_info = unfoldingInfo info
has_unf = hasSomeUnfolding unf_info
rules = specInfoRules (specInfo info)
showAttributes :: [(Bool,SDoc)] -> SDoc
showAttributes stuff
| null docs = empty
| otherwise = brackets (sep (punctuate comma docs))
where
docs = [d | (True,d) <- stuff]
{-
-----------------------------------------------------
-- Unfolding and UnfoldingGuidance
-----------------------------------------------------
-}
instance Outputable UnfoldingGuidance where
ppr UnfNever = ptext (sLit "NEVER")
ppr (UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok })
= ptext (sLit "ALWAYS_IF") <>
parens (ptext (sLit "arity=") <> int arity <> comma <>
ptext (sLit "unsat_ok=") <> ppr unsat_ok <> comma <>
ptext (sLit "boring_ok=") <> ppr boring_ok)
ppr (UnfIfGoodArgs { ug_args = cs, ug_size = size, ug_res = discount })
= hsep [ ptext (sLit "IF_ARGS"),
brackets (hsep (map int cs)),
int size,
int discount ]
instance Outputable UnfoldingSource where
ppr InlineCompulsory = ptext (sLit "Compulsory")
ppr InlineStable = ptext (sLit "InlineStable")
ppr InlineRhs = ptext (sLit "<vanilla>")
instance Outputable Unfolding where
ppr NoUnfolding = ptext (sLit "No unfolding")
ppr (OtherCon cs) = ptext (sLit "OtherCon") <+> ppr cs
ppr (DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args })
= hang (ptext (sLit "DFun:") <+> ptext (sLit "\\")
<+> sep (map (pprBndr LambdaBind) bndrs) <+> arrow)
2 (ppr con <+> sep (map ppr args))
ppr (CoreUnfolding { uf_src = src
, uf_tmpl=rhs, uf_is_top=top, uf_is_value=hnf
, uf_is_conlike=conlike, uf_is_work_free=wf
, uf_expandable=exp, uf_guidance=g })
= ptext (sLit "Unf") <> braces (pp_info $$ pp_rhs)
where
pp_info = fsep $ punctuate comma
[ ptext (sLit "Src=") <> ppr src
, ptext (sLit "TopLvl=") <> ppr top
, ptext (sLit "Value=") <> ppr hnf
, ptext (sLit "ConLike=") <> ppr conlike
, ptext (sLit "WorkFree=") <> ppr wf
, ptext (sLit "Expandable=") <> ppr exp
, ptext (sLit "Guidance=") <> ppr g ]
pp_tmpl = ptext (sLit "Tmpl=") <+> ppr rhs
pp_rhs | isStableSource src = pp_tmpl
| otherwise = empty
-- Don't print the RHS or we get a quadratic
-- blowup in the size of the printout!
{-
-----------------------------------------------------
-- Rules
-----------------------------------------------------
-}
instance Outputable CoreRule where
ppr = pprRule
pprRules :: [CoreRule] -> SDoc
pprRules rules = vcat (map pprRule rules)
pprRule :: CoreRule -> SDoc
pprRule (BuiltinRule { ru_fn = fn, ru_name = name})
= ptext (sLit "Built in rule for") <+> ppr fn <> colon <+> doubleQuotes (ftext name)
pprRule (Rule { ru_name = name, ru_act = act, ru_fn = fn,
ru_bndrs = tpl_vars, ru_args = tpl_args,
ru_rhs = rhs })
= hang (doubleQuotes (ftext name) <+> ppr act)
4 (sep [ptext (sLit "forall") <+>
sep (map (pprCoreBinder LambdaBind) tpl_vars) <> dot,
nest 2 (ppr fn <+> sep (map pprArg tpl_args)),
nest 2 (ptext (sLit "=") <+> pprCoreExpr rhs)
])
{-
-----------------------------------------------------
-- Tickish
-----------------------------------------------------
-}
instance Outputable id => Outputable (Tickish id) where
ppr (HpcTick modl ix) =
hcat [ptext (sLit "hpc<"),
ppr modl, comma,
ppr ix,
ptext (sLit ">")]
ppr (Breakpoint ix vars) =
hcat [ptext (sLit "break<"),
ppr ix,
ptext (sLit ">"),
parens (hcat (punctuate comma (map ppr vars)))]
ppr (ProfNote { profNoteCC = cc,
profNoteCount = tick,
profNoteScope = scope }) =
case (tick,scope) of
(True,True) -> hcat [ptext (sLit "scctick<"), ppr cc, char '>']
(True,False) -> hcat [ptext (sLit "tick<"), ppr cc, char '>']
_ -> hcat [ptext (sLit "scc<"), ppr cc, char '>']
ppr (SourceNote span _) =
hcat [ ptext (sLit "src<"), pprUserRealSpan True span, char '>']
{-
-----------------------------------------------------
-- Vectorisation declarations
-----------------------------------------------------
-}
instance Outputable CoreVect where
ppr (Vect var e) = hang (ptext (sLit "VECTORISE") <+> ppr var <+> char '=')
4 (pprCoreExpr e)
ppr (NoVect var) = ptext (sLit "NOVECTORISE") <+> ppr var
ppr (VectType False var Nothing) = ptext (sLit "VECTORISE type") <+> ppr var
ppr (VectType True var Nothing) = ptext (sLit "VECTORISE SCALAR type") <+> ppr var
ppr (VectType False var (Just tc)) = ptext (sLit "VECTORISE type") <+> ppr var <+> char '=' <+>
ppr tc
ppr (VectType True var (Just tc)) = ptext (sLit "VECTORISE SCALAR type") <+> ppr var <+>
char '=' <+> ppr tc
ppr (VectClass tc) = ptext (sLit "VECTORISE class") <+> ppr tc
ppr (VectInst var) = ptext (sLit "VECTORISE SCALAR instance") <+> ppr var
| fmthoma/ghc | compiler/coreSyn/PprCore.hs | bsd-3-clause | 18,693 | 0 | 20 | 5,649 | 5,185 | 2,594 | 2,591 | 336 | 7 |
{-
(c) The University of Glasgow 2006-2008
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
-}
{-# LANGUAGE CPP, NondecreasingIndentation #-}
-- | Module for constructing @ModIface@ values (interface files),
-- writing them to disk and comparing two versions to see if
-- recompilation is required.
module MkIface (
mkUsedNames,
mkDependencies,
mkIface, -- Build a ModIface from a ModGuts,
-- including computing version information
mkIfaceTc,
writeIfaceFile, -- Write the interface file
checkOldIface, -- See if recompilation is required, by
-- comparing version information
RecompileRequired(..), recompileRequired,
tyThingToIfaceDecl -- Converting things to their Iface equivalents
) where
{-
-----------------------------------------------
Recompilation checking
-----------------------------------------------
A complete description of how recompilation checking works can be
found in the wiki commentary:
http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
Please read the above page for a top-down description of how this all
works. Notes below cover specific issues related to the implementation.
Basic idea:
* In the mi_usages information in an interface, we record the
fingerprint of each free variable of the module
* In mkIface, we compute the fingerprint of each exported thing A.f.
For each external thing that A.f refers to, we include the fingerprint
of the external reference when computing the fingerprint of A.f. So
if anything that A.f depends on changes, then A.f's fingerprint will
change.
Also record any dependent files added with
* addDependentFile
* #include
* -optP-include
* In checkOldIface we compare the mi_usages for the module with
the actual fingerprint for all each thing recorded in mi_usages
-}
#include "HsVersions.h"
import IfaceSyn
import LoadIface
import FlagChecker
import Id
import IdInfo
import Demand
import Coercion( tidyCo )
import Annotations
import CoreSyn
import Class
import Kind
import TyCon
import CoAxiom
import ConLike
import DataCon
import PatSyn
import Type
import TcType
import TysPrim ( alphaTyVars )
import InstEnv
import FamInstEnv
import TcRnMonad
import HsSyn
import HscTypes
import Finder
import DynFlags
import VarEnv
import VarSet
import Var
import Name
import Avail
import RdrName
import NameEnv
import NameSet
import Module
import BinIface
import ErrUtils
import Digraph
import SrcLoc
import Outputable
import BasicTypes hiding ( SuccessFlag(..) )
import UniqFM
import Unique
import Util hiding ( eqListBy )
import FastString
import Maybes
import ListSetOps
import Binary
import Fingerprint
import Bag
import Exception
import Control.Monad
import Data.Function
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Ord
import Data.IORef
import System.Directory
import System.FilePath
{-
************************************************************************
* *
\subsection{Completing an interface}
* *
************************************************************************
-}
mkIface :: HscEnv
-> Maybe Fingerprint -- The old fingerprint, if we have it
-> ModDetails -- The trimmed, tidied interface
-> ModGuts -- Usages, deprecations, etc
-> IO (Messages,
Maybe (ModIface, -- The new one
Bool)) -- True <=> there was an old Iface, and the
-- new one is identical, so no need
-- to write it
mkIface hsc_env maybe_old_fingerprint mod_details
ModGuts{ mg_module = this_mod,
mg_hsc_src = hsc_src,
mg_used_names = used_names,
mg_used_th = used_th,
mg_deps = deps,
mg_dir_imps = dir_imp_mods,
mg_rdr_env = rdr_env,
mg_fix_env = fix_env,
mg_warns = warns,
mg_hpc_info = hpc_info,
mg_safe_haskell = safe_mode,
mg_trust_pkg = self_trust,
mg_dependent_files = dependent_files
}
= mkIface_ hsc_env maybe_old_fingerprint
this_mod hsc_src used_names used_th deps rdr_env fix_env
warns hpc_info dir_imp_mods self_trust dependent_files
safe_mode mod_details
-- | make an interface from the results of typechecking only. Useful
-- for non-optimising compilation, or where we aren't generating any
-- object code at all ('HscNothing').
mkIfaceTc :: HscEnv
-> Maybe Fingerprint -- The old fingerprint, if we have it
-> SafeHaskellMode -- The safe haskell mode
-> ModDetails -- gotten from mkBootModDetails, probably
-> TcGblEnv -- Usages, deprecations, etc
-> IO (Messages, Maybe (ModIface, Bool))
mkIfaceTc hsc_env maybe_old_fingerprint safe_mode mod_details
tc_result@TcGblEnv{ tcg_mod = this_mod,
tcg_src = hsc_src,
tcg_imports = imports,
tcg_rdr_env = rdr_env,
tcg_fix_env = fix_env,
tcg_warns = warns,
tcg_hpc = other_hpc_info,
tcg_th_splice_used = tc_splice_used,
tcg_dependent_files = dependent_files
}
= do
let used_names = mkUsedNames tc_result
deps <- mkDependencies tc_result
let hpc_info = emptyHpcInfo other_hpc_info
used_th <- readIORef tc_splice_used
dep_files <- (readIORef dependent_files)
mkIface_ hsc_env maybe_old_fingerprint
this_mod hsc_src used_names
used_th deps rdr_env
fix_env warns hpc_info (imp_mods imports)
(imp_trust_own_pkg imports) dep_files safe_mode mod_details
mkUsedNames :: TcGblEnv -> NameSet
mkUsedNames TcGblEnv{ tcg_dus = dus } = allUses dus
-- | Extract information from the rename and typecheck phases to produce
-- a dependencies information for the module being compiled.
mkDependencies :: TcGblEnv -> IO Dependencies
mkDependencies
TcGblEnv{ tcg_mod = mod,
tcg_imports = imports,
tcg_th_used = th_var
}
= do
-- Template Haskell used?
th_used <- readIORef th_var
let dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
-- M.hi-boot can be in the imp_dep_mods, but we must remove
-- it before recording the modules on which this one depends!
-- (We want to retain M.hi-boot in imp_dep_mods so that
-- loadHiBootInterface can see if M's direct imports depend
-- on M.hi-boot, and hence that we should do the hi-boot consistency
-- check.)
pkgs | th_used = insertList thPackageKey (imp_dep_pkgs imports)
| otherwise = imp_dep_pkgs imports
-- Set the packages required to be Safe according to Safe Haskell.
-- See Note [RnNames . Tracking Trust Transitively]
sorted_pkgs = sortBy stablePackageKeyCmp pkgs
trust_pkgs = imp_trust_pkgs imports
dep_pkgs' = map (\x -> (x, x `elem` trust_pkgs)) sorted_pkgs
return Deps { dep_mods = sortBy (stableModuleNameCmp `on` fst) dep_mods,
dep_pkgs = dep_pkgs',
dep_orphs = sortBy stableModuleCmp (imp_orphs imports),
dep_finsts = sortBy stableModuleCmp (imp_finsts imports) }
-- sort to get into canonical order
-- NB. remember to use lexicographic ordering
mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> HscSource
-> NameSet -> Bool -> Dependencies -> GlobalRdrEnv
-> NameEnv FixItem -> Warnings -> HpcInfo
-> ImportedMods -> Bool
-> [FilePath]
-> SafeHaskellMode
-> ModDetails
-> IO (Messages, Maybe (ModIface, Bool))
mkIface_ hsc_env maybe_old_fingerprint
this_mod hsc_src used_names used_th deps rdr_env fix_env src_warns
hpc_info dir_imp_mods pkg_trust_req dependent_files safe_mode
ModDetails{ md_insts = insts,
md_fam_insts = fam_insts,
md_rules = rules,
md_anns = anns,
md_vect_info = vect_info,
md_types = type_env,
md_exports = exports }
-- NB: notice that mkIface does not look at the bindings
-- only at the TypeEnv. The previous Tidy phase has
-- put exactly the info into the TypeEnv that we want
-- to expose in the interface
= do
usages <- mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
let entities = typeEnvElts type_env
decls = [ tyThingToIfaceDecl entity
| entity <- entities,
let name = getName entity,
not (isImplicitTyThing entity),
-- No implicit Ids and class tycons in the interface file
not (isWiredInName name),
-- Nor wired-in things; the compiler knows about them anyhow
nameIsLocalOrFrom this_mod name ]
-- Sigh: see Note [Root-main Id] in TcRnDriver
fixities = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
warns = src_warns
iface_rules = map coreRuleToIfaceRule rules
iface_insts = map instanceToIfaceInst $ fixSafeInstances safe_mode insts
iface_fam_insts = map famInstToIfaceFamInst fam_insts
iface_vect_info = flattenVectInfo vect_info
trust_info = setSafeMode safe_mode
annotations = map mkIfaceAnnotation anns
sig_of = getSigOf dflags (moduleName this_mod)
intermediate_iface = ModIface {
mi_module = this_mod,
mi_sig_of = sig_of,
mi_hsc_src = hsc_src,
mi_deps = deps,
mi_usages = usages,
mi_exports = mkIfaceExports exports,
-- Sort these lexicographically, so that
-- the result is stable across compilations
mi_insts = sortBy cmp_inst iface_insts,
mi_fam_insts = sortBy cmp_fam_inst iface_fam_insts,
mi_rules = sortBy cmp_rule iface_rules,
mi_vect_info = iface_vect_info,
mi_fixities = fixities,
mi_warns = warns,
mi_anns = annotations,
mi_globals = maybeGlobalRdrEnv rdr_env,
-- Left out deliberately: filled in by addFingerprints
mi_iface_hash = fingerprint0,
mi_mod_hash = fingerprint0,
mi_flag_hash = fingerprint0,
mi_exp_hash = fingerprint0,
mi_used_th = used_th,
mi_orphan_hash = fingerprint0,
mi_orphan = False, -- Always set by addFingerprints, but
-- it's a strict field, so we can't omit it.
mi_finsts = False, -- Ditto
mi_decls = deliberatelyOmitted "decls",
mi_hash_fn = deliberatelyOmitted "hash_fn",
mi_hpc = isHpcUsed hpc_info,
mi_trust = trust_info,
mi_trust_pkg = pkg_trust_req,
-- And build the cached values
mi_warn_fn = mkIfaceWarnCache warns,
mi_fix_fn = mkIfaceFixCache fixities }
(new_iface, no_change_at_all)
<- {-# SCC "versioninfo" #-}
addFingerprints hsc_env maybe_old_fingerprint
intermediate_iface decls
-- Warn about orphans
-- See Note [Orphans and auto-generated rules]
let warn_orphs = wopt Opt_WarnOrphans dflags
warn_auto_orphs = wopt Opt_WarnAutoOrphans dflags
orph_warnings --- Laziness means no work done unless -fwarn-orphans
| warn_orphs || warn_auto_orphs = rule_warns `unionBags` inst_warns
| otherwise = emptyBag
errs_and_warns = (orph_warnings, emptyBag)
unqual = mkPrintUnqualified dflags rdr_env
inst_warns = listToBag [ instOrphWarn dflags unqual d
| (d,i) <- insts `zip` iface_insts
, isOrphan (ifInstOrph i) ]
rule_warns = listToBag [ ruleOrphWarn dflags unqual this_mod r
| r <- iface_rules
, isOrphan (ifRuleOrph r)
, if ifRuleAuto r then warn_auto_orphs
else warn_orphs ]
if errorsFound dflags errs_and_warns
then return ( errs_and_warns, Nothing )
else do
-- Debug printing
dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
(pprModIface new_iface)
-- bug #1617: on reload we weren't updating the PrintUnqualified
-- correctly. This stems from the fact that the interface had
-- not changed, so addFingerprints returns the old ModIface
-- with the old GlobalRdrEnv (mi_globals).
let final_iface = new_iface{ mi_globals = maybeGlobalRdrEnv rdr_env }
return (errs_and_warns, Just (final_iface, no_change_at_all))
where
cmp_rule = comparing ifRuleName
-- Compare these lexicographically by OccName, *not* by unique,
-- because the latter is not stable across compilations:
cmp_inst = comparing (nameOccName . ifDFun)
cmp_fam_inst = comparing (nameOccName . ifFamInstTcName)
dflags = hsc_dflags hsc_env
-- We only fill in mi_globals if the module was compiled to byte
-- code. Otherwise, the compiler may not have retained all the
-- top-level bindings and they won't be in the TypeEnv (see
-- Desugar.addExportFlagsAndRules). The mi_globals field is used
-- by GHCi to decide whether the module has its full top-level
-- scope available. (#5534)
maybeGlobalRdrEnv :: GlobalRdrEnv -> Maybe GlobalRdrEnv
maybeGlobalRdrEnv rdr_env
| targetRetainsAllBindings (hscTarget dflags) = Just rdr_env
| otherwise = Nothing
deliberatelyOmitted :: String -> a
deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
ifFamInstTcName = ifFamInstFam
flattenVectInfo (VectInfo { vectInfoVar = vVar
, vectInfoTyCon = vTyCon
, vectInfoParallelVars = vParallelVars
, vectInfoParallelTyCons = vParallelTyCons
}) =
IfaceVectInfo
{ ifaceVectInfoVar = [Var.varName v | (v, _ ) <- varEnvElts vVar]
, ifaceVectInfoTyCon = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t /= t_v]
, ifaceVectInfoTyConReuse = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t == t_v]
, ifaceVectInfoParallelVars = [Var.varName v | v <- varSetElems vParallelVars]
, ifaceVectInfoParallelTyCons = nameSetElems vParallelTyCons
}
-----------------------------
writeIfaceFile :: DynFlags -> FilePath -> ModIface -> IO ()
writeIfaceFile dflags hi_file_path new_iface
= do createDirectoryIfMissing True (takeDirectory hi_file_path)
writeBinIface dflags hi_file_path new_iface
-- -----------------------------------------------------------------------------
-- Look up parents and versions of Names
-- This is like a global version of the mi_hash_fn field in each ModIface.
-- Given a Name, it finds the ModIface, and then uses mi_hash_fn to get
-- the parent and version info.
mkHashFun
:: HscEnv -- needed to look up versions
-> ExternalPackageState -- ditto
-> (Name -> Fingerprint)
mkHashFun hsc_env eps
= \name ->
let
mod = ASSERT2( isExternalName name, ppr name ) nameModule name
occ = nameOccName name
iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
pprPanic "lookupVers2" (ppr mod <+> ppr occ)
in
snd (mi_hash_fn iface occ `orElse`
pprPanic "lookupVers1" (ppr mod <+> ppr occ))
where
hpt = hsc_HPT hsc_env
pit = eps_PIT eps
-- ---------------------------------------------------------------------------
-- Compute fingerprints for the interface
addFingerprints
:: HscEnv
-> Maybe Fingerprint -- the old fingerprint, if any
-> ModIface -- The new interface (lacking decls)
-> [IfaceDecl] -- The new decls
-> IO (ModIface, -- Updated interface
Bool) -- True <=> no changes at all;
-- no need to write Iface
addFingerprints hsc_env mb_old_fingerprint iface0 new_decls
= do
eps <- hscEPS hsc_env
let
-- The ABI of a declaration represents everything that is made
-- visible about the declaration that a client can depend on.
-- see IfaceDeclABI below.
declABI :: IfaceDecl -> IfaceDeclABI
declABI decl = (this_mod, decl, extras)
where extras = declExtras fix_fn ann_fn non_orph_rules non_orph_insts
non_orph_fis decl
edges :: [(IfaceDeclABI, Unique, [Unique])]
edges = [ (abi, getUnique (ifName decl), out)
| decl <- new_decls
, let abi = declABI decl
, let out = localOccs $ freeNamesDeclABI abi
]
name_module n = ASSERT2( isExternalName n, ppr n ) nameModule n
localOccs = map (getUnique . getParent . getOccName)
. filter ((== this_mod) . name_module)
. nameSetElems
where getParent occ = lookupOccEnv parent_map occ `orElse` occ
-- maps OccNames to their parents in the current module.
-- e.g. a reference to a constructor must be turned into a reference
-- to the TyCon for the purposes of calculating dependencies.
parent_map :: OccEnv OccName
parent_map = foldr extend emptyOccEnv new_decls
where extend d env =
extendOccEnvList env [ (b,n) | b <- ifaceDeclImplicitBndrs d ]
where n = ifName d
-- strongly-connected groups of declarations, in dependency order
groups = stronglyConnCompFromEdgedVertices edges
global_hash_fn = mkHashFun hsc_env eps
-- how to output Names when generating the data to fingerprint.
-- Here we want to output the fingerprint for each top-level
-- Name, whether it comes from the current module or another
-- module. In this way, the fingerprint for a declaration will
-- change if the fingerprint for anything it refers to (transitively)
-- changes.
mk_put_name :: (OccEnv (OccName,Fingerprint))
-> BinHandle -> Name -> IO ()
mk_put_name local_env bh name
| isWiredInName name = putNameLiterally bh name
-- wired-in names don't have fingerprints
| otherwise
= ASSERT2( isExternalName name, ppr name )
let hash | nameModule name /= this_mod = global_hash_fn name
| otherwise = snd (lookupOccEnv local_env (getOccName name)
`orElse` pprPanic "urk! lookup local fingerprint"
(ppr name)) -- (undefined,fingerprint0))
-- This panic indicates that we got the dependency
-- analysis wrong, because we needed a fingerprint for
-- an entity that wasn't in the environment. To debug
-- it, turn the panic into a trace, uncomment the
-- pprTraces below, run the compile again, and inspect
-- the output and the generated .hi file with
-- --show-iface.
in put_ bh hash
-- take a strongly-connected group of declarations and compute
-- its fingerprint.
fingerprint_group :: (OccEnv (OccName,Fingerprint),
[(Fingerprint,IfaceDecl)])
-> SCC IfaceDeclABI
-> IO (OccEnv (OccName,Fingerprint),
[(Fingerprint,IfaceDecl)])
fingerprint_group (local_env, decls_w_hashes) (AcyclicSCC abi)
= do let hash_fn = mk_put_name local_env
decl = abiDecl abi
-- pprTrace "fingerprinting" (ppr (ifName decl) ) $ do
hash <- computeFingerprint hash_fn abi
env' <- extend_hash_env local_env (hash,decl)
return (env', (hash,decl) : decls_w_hashes)
fingerprint_group (local_env, decls_w_hashes) (CyclicSCC abis)
= do let decls = map abiDecl abis
local_env1 <- foldM extend_hash_env local_env
(zip (repeat fingerprint0) decls)
let hash_fn = mk_put_name local_env1
-- pprTrace "fingerprinting" (ppr (map ifName decls) ) $ do
let stable_abis = sortBy cmp_abiNames abis
-- put the cycle in a canonical order
hash <- computeFingerprint hash_fn stable_abis
let pairs = zip (repeat hash) decls
local_env2 <- foldM extend_hash_env local_env pairs
return (local_env2, pairs ++ decls_w_hashes)
-- we have fingerprinted the whole declaration, but we now need
-- to assign fingerprints to all the OccNames that it binds, to
-- use when referencing those OccNames in later declarations.
--
extend_hash_env :: OccEnv (OccName,Fingerprint)
-> (Fingerprint,IfaceDecl)
-> IO (OccEnv (OccName,Fingerprint))
extend_hash_env env0 (hash,d) = do
return (foldr (\(b,fp) env -> extendOccEnv env b (b,fp)) env0
(ifaceDeclFingerprints hash d))
--
(local_env, decls_w_hashes) <-
foldM fingerprint_group (emptyOccEnv, []) groups
-- when calculating fingerprints, we always need to use canonical
-- ordering for lists of things. In particular, the mi_deps has various
-- lists of modules and suchlike, so put these all in canonical order:
let sorted_deps = sortDependencies (mi_deps iface0)
-- the export hash of a module depends on the orphan hashes of the
-- orphan modules below us in the dependency tree. This is the way
-- that changes in orphans get propagated all the way up the
-- dependency tree. We only care about orphan modules in the current
-- package, because changes to orphans outside this package will be
-- tracked by the usage on the ABI hash of package modules that we import.
let orph_mods
= filter (/= this_mod) -- Note [Do not update EPS with your own hi-boot]
. filter ((== this_pkg) . modulePackageKey)
$ dep_orphs sorted_deps
dep_orphan_hashes <- getOrphanHashes hsc_env orph_mods
-- Note [Do not update EPS with your own hi-boot]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- (See also Trac #10182). When your hs-boot file includes an orphan
-- instance declaration, you may find that the dep_orphs of a module you
-- import contains reference to yourself. DO NOT actually load this module
-- or add it to the orphan hashes: you're going to provide the orphan
-- instances yourself, no need to consult hs-boot; if you do load the
-- interface into EPS, you will see a duplicate orphan instance.
orphan_hash <- computeFingerprint (mk_put_name local_env)
(map ifDFun orph_insts, orph_rules, orph_fis)
-- the export list hash doesn't depend on the fingerprints of
-- the Names it mentions, only the Names themselves, hence putNameLiterally.
export_hash <- computeFingerprint putNameLiterally
(mi_exports iface0,
orphan_hash,
dep_orphan_hashes,
dep_pkgs (mi_deps iface0),
-- dep_pkgs: see "Package Version Changes" on
-- wiki/Commentary/Compiler/RecompilationAvoidance
mi_trust iface0)
-- Make sure change of Safe Haskell mode causes recomp.
-- put the declarations in a canonical order, sorted by OccName
let sorted_decls = Map.elems $ Map.fromList $
[(ifName d, e) | e@(_, d) <- decls_w_hashes]
-- the flag hash depends on:
-- - (some of) dflags
-- it returns two hashes, one that shouldn't change
-- the abi hash and one that should
flag_hash <- fingerprintDynFlags dflags this_mod putNameLiterally
-- the ABI hash depends on:
-- - decls
-- - export list
-- - orphans
-- - deprecations
-- - vect info
-- - flag abi hash
mod_hash <- computeFingerprint putNameLiterally
(map fst sorted_decls,
export_hash, -- includes orphan_hash
mi_warns iface0,
mi_vect_info iface0)
-- The interface hash depends on:
-- - the ABI hash, plus
-- - the module level annotations,
-- - usages
-- - deps (home and external packages, dependent files)
-- - hpc
iface_hash <- computeFingerprint putNameLiterally
(mod_hash,
ann_fn (mkVarOcc "module"), -- See mkIfaceAnnCache
mi_usages iface0,
sorted_deps,
mi_hpc iface0)
let
no_change_at_all = Just iface_hash == mb_old_fingerprint
final_iface = iface0 {
mi_mod_hash = mod_hash,
mi_iface_hash = iface_hash,
mi_exp_hash = export_hash,
mi_orphan_hash = orphan_hash,
mi_flag_hash = flag_hash,
mi_orphan = not ( all ifRuleAuto orph_rules
-- See Note [Orphans and auto-generated rules]
&& null orph_insts
&& null orph_fis
&& isNoIfaceVectInfo (mi_vect_info iface0)),
mi_finsts = not . null $ mi_fam_insts iface0,
mi_decls = sorted_decls,
mi_hash_fn = lookupOccEnv local_env }
--
return (final_iface, no_change_at_all)
where
this_mod = mi_module iface0
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
(non_orph_insts, orph_insts) = mkOrphMap ifInstOrph (mi_insts iface0)
(non_orph_rules, orph_rules) = mkOrphMap ifRuleOrph (mi_rules iface0)
(non_orph_fis, orph_fis) = mkOrphMap ifFamInstOrph (mi_fam_insts iface0)
fix_fn = mi_fix_fn iface0
ann_fn = mkIfaceAnnCache (mi_anns iface0)
getOrphanHashes :: HscEnv -> [Module] -> IO [Fingerprint]
getOrphanHashes hsc_env mods = do
eps <- hscEPS hsc_env
let
hpt = hsc_HPT hsc_env
pit = eps_PIT eps
dflags = hsc_dflags hsc_env
get_orph_hash mod =
case lookupIfaceByModule dflags hpt pit mod of
Nothing -> pprPanic "moduleOrphanHash" (ppr mod)
Just iface -> mi_orphan_hash iface
--
return (map get_orph_hash mods)
sortDependencies :: Dependencies -> Dependencies
sortDependencies d
= Deps { dep_mods = sortBy (compare `on` (moduleNameFS.fst)) (dep_mods d),
dep_pkgs = sortBy (stablePackageKeyCmp `on` fst) (dep_pkgs d),
dep_orphs = sortBy stableModuleCmp (dep_orphs d),
dep_finsts = sortBy stableModuleCmp (dep_finsts d) }
-- | Creates cached lookup for the 'mi_anns' field of ModIface
-- Hackily, we use "module" as the OccName for any module-level annotations
mkIfaceAnnCache :: [IfaceAnnotation] -> OccName -> [AnnPayload]
mkIfaceAnnCache anns
= \n -> lookupOccEnv env n `orElse` []
where
pair (IfaceAnnotation target value) =
(case target of
NamedTarget occn -> occn
ModuleTarget _ -> mkVarOcc "module"
, [value])
-- flipping (++), so the first argument is always short
env = mkOccEnv_C (flip (++)) (map pair anns)
{-
Note [Orphans and auto-generated rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we specialise an INLINEABLE function, or when we have
-fspecialise-aggressively, we auto-generate RULES that are orphans.
We don't want to warn about these, at least not by default, or we'd
generate a lot of warnings. Hence -fwarn-auto-orphans.
Indeed, we don't even treat the module as an oprhan module if it has
auto-generated *rule* orphans. Orphan modules are read every time we
compile, so they are pretty obtrusive and slow down every compilation,
even non-optimised ones. (Reason: for type class instances it's a
type correctness issue.) But specialisation rules are strictly for
*optimisation* only so it's fine not to read the interface.
What this means is that a SPEC rules from auto-specialisation in
module M will be used in other modules only if M.hi has been read for
some other reason, which is actually pretty likely.
************************************************************************
* *
The ABI of an IfaceDecl
* *
************************************************************************
Note [The ABI of an IfaceDecl]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ABI of a declaration consists of:
(a) the full name of the identifier (inc. module and package,
because these are used to construct the symbol name by which
the identifier is known externally).
(b) the declaration itself, as exposed to clients. That is, the
definition of an Id is included in the fingerprint only if
it is made available as an unfolding in the interface.
(c) the fixity of the identifier
(d) for Ids: rules
(e) for classes: instances, fixity & rules for methods
(f) for datatypes: instances, fixity & rules for constrs
Items (c)-(f) are not stored in the IfaceDecl, but instead appear
elsewhere in the interface file. But they are *fingerprinted* with
the declaration itself. This is done by grouping (c)-(f) in IfaceDeclExtras,
and fingerprinting that as part of the declaration.
-}
type IfaceDeclABI = (Module, IfaceDecl, IfaceDeclExtras)
data IfaceDeclExtras
= IfaceIdExtras IfaceIdExtras
| IfaceDataExtras
Fixity -- Fixity of the tycon itself
[IfaceInstABI] -- Local class and family instances of this tycon
-- See Note [Orphans] in InstEnv
[AnnPayload] -- Annotations of the type itself
[IfaceIdExtras] -- For each constructor: fixity, RULES and annotations
| IfaceClassExtras
Fixity -- Fixity of the class itself
[IfaceInstABI] -- Local instances of this class *or*
-- of its associated data types
-- See Note [Orphans] in InstEnv
[AnnPayload] -- Annotations of the type itself
[IfaceIdExtras] -- For each class method: fixity, RULES and annotations
| IfaceSynonymExtras Fixity [AnnPayload]
| IfaceFamilyExtras Fixity [IfaceInstABI] [AnnPayload]
| IfaceOtherDeclExtras
data IfaceIdExtras
= IdExtras
Fixity -- Fixity of the Id
[IfaceRule] -- Rules for the Id
[AnnPayload] -- Annotations for the Id
-- When hashing a class or family instance, we hash only the
-- DFunId or CoAxiom, because that depends on all the
-- information about the instance.
--
type IfaceInstABI = IfExtName -- Name of DFunId or CoAxiom that is evidence for the instance
abiDecl :: IfaceDeclABI -> IfaceDecl
abiDecl (_, decl, _) = decl
cmp_abiNames :: IfaceDeclABI -> IfaceDeclABI -> Ordering
cmp_abiNames abi1 abi2 = ifName (abiDecl abi1) `compare`
ifName (abiDecl abi2)
freeNamesDeclABI :: IfaceDeclABI -> NameSet
freeNamesDeclABI (_mod, decl, extras) =
freeNamesIfDecl decl `unionNameSet` freeNamesDeclExtras extras
freeNamesDeclExtras :: IfaceDeclExtras -> NameSet
freeNamesDeclExtras (IfaceIdExtras id_extras)
= freeNamesIdExtras id_extras
freeNamesDeclExtras (IfaceDataExtras _ insts _ subs)
= unionNameSets (mkNameSet insts : map freeNamesIdExtras subs)
freeNamesDeclExtras (IfaceClassExtras _ insts _ subs)
= unionNameSets (mkNameSet insts : map freeNamesIdExtras subs)
freeNamesDeclExtras (IfaceSynonymExtras _ _)
= emptyNameSet
freeNamesDeclExtras (IfaceFamilyExtras _ insts _)
= mkNameSet insts
freeNamesDeclExtras IfaceOtherDeclExtras
= emptyNameSet
freeNamesIdExtras :: IfaceIdExtras -> NameSet
freeNamesIdExtras (IdExtras _ rules _) = unionNameSets (map freeNamesIfRule rules)
instance Outputable IfaceDeclExtras where
ppr IfaceOtherDeclExtras = Outputable.empty
ppr (IfaceIdExtras extras) = ppr_id_extras extras
ppr (IfaceSynonymExtras fix anns) = vcat [ppr fix, ppr anns]
ppr (IfaceFamilyExtras fix finsts anns) = vcat [ppr fix, ppr finsts, ppr anns]
ppr (IfaceDataExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns,
ppr_id_extras_s stuff]
ppr (IfaceClassExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns,
ppr_id_extras_s stuff]
ppr_insts :: [IfaceInstABI] -> SDoc
ppr_insts _ = ptext (sLit "<insts>")
ppr_id_extras_s :: [IfaceIdExtras] -> SDoc
ppr_id_extras_s stuff = vcat (map ppr_id_extras stuff)
ppr_id_extras :: IfaceIdExtras -> SDoc
ppr_id_extras (IdExtras fix rules anns) = ppr fix $$ vcat (map ppr rules) $$ vcat (map ppr anns)
-- This instance is used only to compute fingerprints
instance Binary IfaceDeclExtras where
get _bh = panic "no get for IfaceDeclExtras"
put_ bh (IfaceIdExtras extras) = do
putByte bh 1; put_ bh extras
put_ bh (IfaceDataExtras fix insts anns cons) = do
putByte bh 2; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh cons
put_ bh (IfaceClassExtras fix insts anns methods) = do
putByte bh 3; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh methods
put_ bh (IfaceSynonymExtras fix anns) = do
putByte bh 4; put_ bh fix; put_ bh anns
put_ bh (IfaceFamilyExtras fix finsts anns) = do
putByte bh 5; put_ bh fix; put_ bh finsts; put_ bh anns
put_ bh IfaceOtherDeclExtras = putByte bh 6
instance Binary IfaceIdExtras where
get _bh = panic "no get for IfaceIdExtras"
put_ bh (IdExtras fix rules anns)= do { put_ bh fix; put_ bh rules; put_ bh anns }
declExtras :: (OccName -> Fixity)
-> (OccName -> [AnnPayload])
-> OccEnv [IfaceRule]
-> OccEnv [IfaceClsInst]
-> OccEnv [IfaceFamInst]
-> IfaceDecl
-> IfaceDeclExtras
declExtras fix_fn ann_fn rule_env inst_env fi_env decl
= case decl of
IfaceId{} -> IfaceIdExtras (id_extras n)
IfaceData{ifCons=cons} ->
IfaceDataExtras (fix_fn n)
(map ifFamInstAxiom (lookupOccEnvL fi_env n) ++
map ifDFun (lookupOccEnvL inst_env n))
(ann_fn n)
(map (id_extras . ifConOcc) (visibleIfConDecls cons))
IfaceClass{ifSigs=sigs, ifATs=ats} ->
IfaceClassExtras (fix_fn n)
(map ifDFun $ (concatMap at_extras ats)
++ lookupOccEnvL inst_env n)
-- Include instances of the associated types
-- as well as instances of the class (Trac #5147)
(ann_fn n)
[id_extras op | IfaceClassOp op _ _ <- sigs]
IfaceSynonym{} -> IfaceSynonymExtras (fix_fn n)
(ann_fn n)
IfaceFamily{} -> IfaceFamilyExtras (fix_fn n)
(map ifFamInstAxiom (lookupOccEnvL fi_env n))
(ann_fn n)
_other -> IfaceOtherDeclExtras
where
n = ifName decl
id_extras occ = IdExtras (fix_fn occ) (lookupOccEnvL rule_env occ) (ann_fn occ)
at_extras (IfaceAT decl _) = lookupOccEnvL inst_env (ifName decl)
lookupOccEnvL :: OccEnv [v] -> OccName -> [v]
lookupOccEnvL env k = lookupOccEnv env k `orElse` []
-- used when we want to fingerprint a structure without depending on the
-- fingerprints of external Names that it refers to.
putNameLiterally :: BinHandle -> Name -> IO ()
putNameLiterally bh name = ASSERT( isExternalName name )
do
put_ bh $! nameModule name
put_ bh $! nameOccName name
{-
-- for testing: use the md5sum command to generate fingerprints and
-- compare the results against our built-in version.
fp' <- oldMD5 dflags bh
if fp /= fp' then pprPanic "computeFingerprint" (ppr fp <+> ppr fp')
else return fp
oldMD5 dflags bh = do
tmp <- newTempName dflags "bin"
writeBinMem bh tmp
tmp2 <- newTempName dflags "md5"
let cmd = "md5sum " ++ tmp ++ " >" ++ tmp2
r <- system cmd
case r of
ExitFailure _ -> throwGhcExceptionIO (PhaseFailed cmd r)
ExitSuccess -> do
hash_str <- readFile tmp2
return $! readHexFingerprint hash_str
-}
instOrphWarn :: DynFlags -> PrintUnqualified -> ClsInst -> WarnMsg
instOrphWarn dflags unqual inst
= mkWarnMsg dflags (getSrcSpan inst) unqual $
hang (ptext (sLit "Orphan instance:")) 2 (pprInstanceHdr inst)
$$ text "To avoid this"
$$ nest 4 (vcat possibilities)
where
possibilities =
text "move the instance declaration to the module of the class or of the type, or" :
text "wrap the type with a newtype and declare the instance on the new type." :
[]
ruleOrphWarn :: DynFlags -> PrintUnqualified -> Module -> IfaceRule -> WarnMsg
ruleOrphWarn dflags unqual mod rule
= mkWarnMsg dflags silly_loc unqual $
ptext (sLit "Orphan rule:") <+> ppr rule
where
silly_loc = srcLocSpan (mkSrcLoc (moduleNameFS (moduleName mod)) 1 1)
-- We don't have a decent SrcSpan for a Rule, not even the CoreRule
-- Could readily be fixed by adding a SrcSpan to CoreRule, if we wanted to
----------------------
-- mkOrphMap partitions instance decls or rules into
-- (a) an OccEnv for ones that are not orphans,
-- mapping the local OccName to a list of its decls
-- (b) a list of orphan decls
mkOrphMap :: (decl -> IsOrphan) -- Extract orphan status from decl
-> [decl] -- Sorted into canonical order
-> (OccEnv [decl], -- Non-orphan decls associated with their key;
-- each sublist in canonical order
[decl]) -- Orphan decls; in canonical order
mkOrphMap get_key decls
= foldl go (emptyOccEnv, []) decls
where
go (non_orphs, orphs) d
| NotOrphan occ <- get_key d
= (extendOccEnv_Acc (:) singleton non_orphs occ d, orphs)
| otherwise = (non_orphs, d:orphs)
{-
************************************************************************
* *
Keeping track of what we've slurped, and fingerprints
* *
************************************************************************
-}
mkUsageInfo :: HscEnv -> Module -> ImportedMods -> NameSet -> [FilePath] -> IO [Usage]
mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
= do
eps <- hscEPS hsc_env
hashes <- mapM getFileHash dependent_files
let mod_usages = mk_mod_usage_info (eps_PIT eps) hsc_env this_mod
dir_imp_mods used_names
let usages = mod_usages ++ [ UsageFile { usg_file_path = f
, usg_file_hash = hash }
| (f, hash) <- zip dependent_files hashes ]
usages `seqList` return usages
-- seq the list of Usages returned: occasionally these
-- don't get evaluated for a while and we can end up hanging on to
-- the entire collection of Ifaces.
mk_mod_usage_info :: PackageIfaceTable
-> HscEnv
-> Module
-> ImportedMods
-> NameSet
-> [Usage]
mk_mod_usage_info pit hsc_env this_mod direct_imports used_names
= mapMaybe mkUsage usage_mods
where
hpt = hsc_HPT hsc_env
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
used_mods = moduleEnvKeys ent_map
dir_imp_mods = moduleEnvKeys direct_imports
all_mods = used_mods ++ filter (`notElem` used_mods) dir_imp_mods
usage_mods = sortBy stableModuleCmp all_mods
-- canonical order is imported, to avoid interface-file
-- wobblage.
-- ent_map groups together all the things imported and used
-- from a particular module
ent_map :: ModuleEnv [OccName]
ent_map = foldNameSet add_mv emptyModuleEnv used_names
where
add_mv name mv_map
| isWiredInName name = mv_map -- ignore wired-in names
| otherwise
= case nameModule_maybe name of
Nothing -> ASSERT2( isSystemName name, ppr name ) mv_map
-- See Note [Internal used_names]
Just mod -> -- This lambda function is really just a
-- specialised (++); originally came about to
-- avoid quadratic behaviour (trac #2680)
extendModuleEnvWith (\_ xs -> occ:xs) mv_map mod [occ]
where occ = nameOccName name
-- We want to create a Usage for a home module if
-- a) we used something from it; has something in used_names
-- b) we imported it, even if we used nothing from it
-- (need to recompile if its export list changes: export_fprint)
mkUsage :: Module -> Maybe Usage
mkUsage mod
| isNothing maybe_iface -- We can't depend on it if we didn't
-- load its interface.
|| mod == this_mod -- We don't care about usages of
-- things in *this* module
= Nothing
| modulePackageKey mod /= this_pkg
= Just UsagePackageModule{ usg_mod = mod,
usg_mod_hash = mod_hash,
usg_safe = imp_safe }
-- for package modules, we record the module hash only
| (null used_occs
&& isNothing export_hash
&& not is_direct_import
&& not finsts_mod)
= Nothing -- Record no usage info
-- for directly-imported modules, we always want to record a usage
-- on the orphan hash. This is what triggers a recompilation if
-- an orphan is added or removed somewhere below us in the future.
| otherwise
= Just UsageHomeModule {
usg_mod_name = moduleName mod,
usg_mod_hash = mod_hash,
usg_exports = export_hash,
usg_entities = Map.toList ent_hashs,
usg_safe = imp_safe }
where
maybe_iface = lookupIfaceByModule dflags hpt pit mod
-- In one-shot mode, the interfaces for home-package
-- modules accumulate in the PIT not HPT. Sigh.
Just iface = maybe_iface
finsts_mod = mi_finsts iface
hash_env = mi_hash_fn iface
mod_hash = mi_mod_hash iface
export_hash | depend_on_exports = Just (mi_exp_hash iface)
| otherwise = Nothing
(is_direct_import, imp_safe)
= case lookupModuleEnv direct_imports mod of
Just ((_,_,_,safe):_xs) -> (True, safe)
Just _ -> pprPanic "mkUsage: empty direct import" Outputable.empty
Nothing -> (False, safeImplicitImpsReq dflags)
-- Nothing case is for implicit imports like 'System.IO' when 'putStrLn'
-- is used in the source code. We require them to be safe in Safe Haskell
used_occs = lookupModuleEnv ent_map mod `orElse` []
-- Making a Map here ensures that (a) we remove duplicates
-- when we have usages on several subordinates of a single parent,
-- and (b) that the usages emerge in a canonical order, which
-- is why we use Map rather than OccEnv: Map works
-- using Ord on the OccNames, which is a lexicographic ordering.
ent_hashs :: Map OccName Fingerprint
ent_hashs = Map.fromList (map lookup_occ used_occs)
lookup_occ occ =
case hash_env occ of
Nothing -> pprPanic "mkUsage" (ppr mod <+> ppr occ <+> ppr used_names)
Just r -> r
depend_on_exports = is_direct_import
{- True
Even if we used 'import M ()', we have to register a
usage on the export list because we are sensitive to
changes in orphan instances/rules.
False
In GHC 6.8.x we always returned true, and in
fact it recorded a dependency on *all* the
modules underneath in the dependency tree. This
happens to make orphans work right, but is too
expensive: it'll read too many interface files.
The 'isNothing maybe_iface' check above saved us
from generating many of these usages (at least in
one-shot mode), but that's even more bogus!
-}
mkIfaceAnnotation :: Annotation -> IfaceAnnotation
mkIfaceAnnotation (Annotation { ann_target = target, ann_value = payload })
= IfaceAnnotation {
ifAnnotatedTarget = fmap nameOccName target,
ifAnnotatedValue = payload
}
mkIfaceExports :: [AvailInfo] -> [IfaceExport] -- Sort to make canonical
mkIfaceExports exports
= sortBy stableAvailCmp (map sort_subs exports)
where
sort_subs :: AvailInfo -> AvailInfo
sort_subs (Avail n) = Avail n
sort_subs (AvailTC n []) = AvailTC n []
sort_subs (AvailTC n (m:ms))
| n==m = AvailTC n (m:sortBy stableNameCmp ms)
| otherwise = AvailTC n (sortBy stableNameCmp (m:ms))
-- Maintain the AvailTC Invariant
{-
Note [Orignal module]
~~~~~~~~~~~~~~~~~~~~~
Consider this:
module X where { data family T }
module Y( T(..) ) where { import X; data instance T Int = MkT Int }
The exported Avail from Y will look like
X.T{X.T, Y.MkT}
That is, in Y,
- only MkT is brought into scope by the data instance;
- but the parent (used for grouping and naming in T(..) exports) is X.T
- and in this case we export X.T too
In the result of MkIfaceExports, the names are grouped by defining module,
so we may need to split up a single Avail into multiple ones.
Note [Internal used_names]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Most of the used_names are External Names, but we can have Internal
Names too: see Note [Binders in Template Haskell] in Convert, and
Trac #5362 for an example. Such Names are always
- Such Names are always for locally-defined things, for which we
don't gather usage info, so we can just ignore them in ent_map
- They are always System Names, hence the assert, just as a double check.
************************************************************************
* *
Load the old interface file for this module (unless
we have it already), and check whether it is up to date
* *
************************************************************************
-}
data RecompileRequired
= UpToDate
-- ^ everything is up to date, recompilation is not required
| MustCompile
-- ^ The .hs file has been touched, or the .o/.hi file does not exist
| RecompBecause String
-- ^ The .o/.hi files are up to date, but something else has changed
-- to force recompilation; the String says what (one-line summary)
deriving Eq
recompileRequired :: RecompileRequired -> Bool
recompileRequired UpToDate = False
recompileRequired _ = True
-- | Top level function to check if the version of an old interface file
-- is equivalent to the current source file the user asked us to compile.
-- If the same, we can avoid recompilation. We return a tuple where the
-- first element is a bool saying if we should recompile the object file
-- and the second is maybe the interface file, where Nothng means to
-- rebuild the interface file not use the exisitng one.
checkOldIface
:: HscEnv
-> ModSummary
-> SourceModified
-> Maybe ModIface -- Old interface from compilation manager, if any
-> IO (RecompileRequired, Maybe ModIface)
checkOldIface hsc_env mod_summary source_modified maybe_iface
= do let dflags = hsc_dflags hsc_env
showPass dflags $
"Checking old interface for " ++
(showPpr dflags $ ms_mod mod_summary)
initIfaceCheck hsc_env $
check_old_iface hsc_env mod_summary source_modified maybe_iface
check_old_iface
:: HscEnv
-> ModSummary
-> SourceModified
-> Maybe ModIface
-> IfG (RecompileRequired, Maybe ModIface)
check_old_iface hsc_env mod_summary src_modified maybe_iface
= let dflags = hsc_dflags hsc_env
getIface =
case maybe_iface of
Just _ -> do
traceIf (text "We already have the old interface for" <+>
ppr (ms_mod mod_summary))
return maybe_iface
Nothing -> loadIface
loadIface = do
let iface_path = msHiFilePath mod_summary
read_result <- readIface (ms_mod mod_summary) iface_path
case read_result of
Failed err -> do
traceIf (text "FYI: cannot read old interface file:" $$ nest 4 err)
return Nothing
Succeeded iface -> do
traceIf (text "Read the interface file" <+> text iface_path)
return $ Just iface
src_changed
| gopt Opt_ForceRecomp (hsc_dflags hsc_env) = True
| SourceModified <- src_modified = True
| otherwise = False
in do
when src_changed $
traceHiDiffs (nest 4 $ text "Source file changed or recompilation check turned off")
case src_changed of
-- If the source has changed and we're in interactive mode,
-- avoid reading an interface; just return the one we might
-- have been supplied with.
True | not (isObjectTarget $ hscTarget dflags) ->
return (MustCompile, maybe_iface)
-- Try and read the old interface for the current module
-- from the .hi file left from the last time we compiled it
True -> do
maybe_iface' <- getIface
return (MustCompile, maybe_iface')
False -> do
maybe_iface' <- getIface
case maybe_iface' of
-- We can't retrieve the iface
Nothing -> return (MustCompile, Nothing)
-- We have got the old iface; check its versions
-- even in the SourceUnmodifiedAndStable case we
-- should check versions because some packages
-- might have changed or gone away.
Just iface -> checkVersions hsc_env mod_summary iface
-- | Check if a module is still the same 'version'.
--
-- This function is called in the recompilation checker after we have
-- determined that the module M being checked hasn't had any changes
-- to its source file since we last compiled M. So at this point in general
-- two things may have changed that mean we should recompile M:
-- * The interface export by a dependency of M has changed.
-- * The compiler flags specified this time for M have changed
-- in a manner that is significant for recompilaiton.
-- We return not just if we should recompile the object file but also
-- if we should rebuild the interface file.
checkVersions :: HscEnv
-> ModSummary
-> ModIface -- Old interface
-> IfG (RecompileRequired, Maybe ModIface)
checkVersions hsc_env mod_summary iface
= do { traceHiDiffs (text "Considering whether compilation is required for" <+>
ppr (mi_module iface) <> colon)
; recomp <- checkFlagHash hsc_env iface
; if recompileRequired recomp then return (recomp, Nothing) else do {
; if getSigOf (hsc_dflags hsc_env) (moduleName (mi_module iface))
/= mi_sig_of iface
then return (RecompBecause "sig-of changed", Nothing) else do {
; recomp <- checkDependencies hsc_env mod_summary iface
; if recompileRequired recomp then return (recomp, Just iface) else do {
-- Source code unchanged and no errors yet... carry on
--
-- First put the dependent-module info, read from the old
-- interface, into the envt, so that when we look for
-- interfaces we look for the right one (.hi or .hi-boot)
--
-- It's just temporary because either the usage check will succeed
-- (in which case we are done with this module) or it'll fail (in which
-- case we'll compile the module from scratch anyhow).
--
-- We do this regardless of compilation mode, although in --make mode
-- all the dependent modules should be in the HPT already, so it's
-- quite redundant
; updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
; recomp <- checkList [checkModUsage this_pkg u | u <- mi_usages iface]
; return (recomp, Just iface)
}}}}
where
this_pkg = thisPackage (hsc_dflags hsc_env)
-- This is a bit of a hack really
mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
mod_deps = mkModDeps (dep_mods (mi_deps iface))
-- | Check the flags haven't changed
checkFlagHash :: HscEnv -> ModIface -> IfG RecompileRequired
checkFlagHash hsc_env iface = do
let old_hash = mi_flag_hash iface
new_hash <- liftIO $ fingerprintDynFlags (hsc_dflags hsc_env)
(mi_module iface)
putNameLiterally
case old_hash == new_hash of
True -> up_to_date (ptext $ sLit "Module flags unchanged")
False -> out_of_date_hash "flags changed"
(ptext $ sLit " Module flags have changed")
old_hash new_hash
-- If the direct imports of this module are resolved to targets that
-- are not among the dependencies of the previous interface file,
-- then we definitely need to recompile. This catches cases like
-- - an exposed package has been upgraded
-- - we are compiling with different package flags
-- - a home module that was shadowing a package module has been removed
-- - a new home module has been added that shadows a package module
-- See bug #1372.
--
-- Returns True if recompilation is required.
checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
checkDependencies hsc_env summary iface
= checkList (map dep_missing (ms_imps summary ++ ms_srcimps summary))
where
prev_dep_mods = dep_mods (mi_deps iface)
prev_dep_pkgs = dep_pkgs (mi_deps iface)
this_pkg = thisPackage (hsc_dflags hsc_env)
dep_missing (L _ (ImportDecl { ideclName = L _ mod, ideclPkgQual = pkg })) = do
find_res <- liftIO $ findImportedModule hsc_env mod (fmap sl_fs pkg)
let reason = moduleNameString mod ++ " changed"
case find_res of
FoundModule h -> check_mod reason (fr_mod h)
FoundSigs hs _backing -> check_mods reason (map fr_mod hs)
_otherwise -> return (RecompBecause reason)
check_mods _ [] = return UpToDate
check_mods reason (m:ms) = do
r <- check_mod reason m
case r of
UpToDate -> check_mods reason ms
_otherwise -> return r
check_mod reason mod
| pkg == this_pkg
= if moduleName mod `notElem` map fst prev_dep_mods
then do traceHiDiffs $
text "imported module " <> quotes (ppr mod) <>
text " not among previous dependencies"
return (RecompBecause reason)
else
return UpToDate
| otherwise
= if pkg `notElem` (map fst prev_dep_pkgs)
then do traceHiDiffs $
text "imported module " <> quotes (ppr mod) <>
text " is from package " <> quotes (ppr pkg) <>
text ", which is not among previous dependencies"
return (RecompBecause reason)
else
return UpToDate
where pkg = modulePackageKey mod
needInterface :: Module -> (ModIface -> IfG RecompileRequired)
-> IfG RecompileRequired
needInterface mod continue
= do -- Load the imported interface if possible
let doc_str = sep [ptext (sLit "need version info for"), ppr mod]
traceHiDiffs (text "Checking usages for module" <+> ppr mod)
mb_iface <- loadInterface doc_str mod ImportBySystem
-- Load the interface, but don't complain on failure;
-- Instead, get an Either back which we can test
case mb_iface of
Failed _ -> do
traceHiDiffs (sep [ptext (sLit "Couldn't load interface for module"),
ppr mod])
return MustCompile
-- Couldn't find or parse a module mentioned in the
-- old interface file. Don't complain: it might
-- just be that the current module doesn't need that
-- import and it's been deleted
Succeeded iface -> continue iface
-- | Given the usage information extracted from the old
-- M.hi file for the module being compiled, figure out
-- whether M needs to be recompiled.
checkModUsage :: PackageKey -> Usage -> IfG RecompileRequired
checkModUsage _this_pkg UsagePackageModule{
usg_mod = mod,
usg_mod_hash = old_mod_hash }
= needInterface mod $ \iface -> do
let reason = moduleNameString (moduleName mod) ++ " changed"
checkModuleFingerprint reason old_mod_hash (mi_mod_hash iface)
-- We only track the ABI hash of package modules, rather than
-- individual entity usages, so if the ABI hash changes we must
-- recompile. This is safe but may entail more recompilation when
-- a dependent package has changed.
checkModUsage this_pkg UsageHomeModule{
usg_mod_name = mod_name,
usg_mod_hash = old_mod_hash,
usg_exports = maybe_old_export_hash,
usg_entities = old_decl_hash }
= do
let mod = mkModule this_pkg mod_name
needInterface mod $ \iface -> do
let
new_mod_hash = mi_mod_hash iface
new_decl_hash = mi_hash_fn iface
new_export_hash = mi_exp_hash iface
reason = moduleNameString mod_name ++ " changed"
-- CHECK MODULE
recompile <- checkModuleFingerprint reason old_mod_hash new_mod_hash
if not (recompileRequired recompile)
then return UpToDate
else do
-- CHECK EXPORT LIST
checkMaybeHash reason maybe_old_export_hash new_export_hash
(ptext (sLit " Export list changed")) $ do
-- CHECK ITEMS ONE BY ONE
recompile <- checkList [ checkEntityUsage reason new_decl_hash u
| u <- old_decl_hash]
if recompileRequired recompile
then return recompile -- This one failed, so just bail out now
else up_to_date (ptext (sLit " Great! The bits I use are up to date"))
checkModUsage _this_pkg UsageFile{ usg_file_path = file,
usg_file_hash = old_hash } =
liftIO $
handleIO handle $ do
new_hash <- getFileHash file
if (old_hash /= new_hash)
then return recomp
else return UpToDate
where
recomp = RecompBecause (file ++ " changed")
handle =
#ifdef DEBUG
\e -> pprTrace "UsageFile" (text (show e)) $ return recomp
#else
\_ -> return recomp -- if we can't find the file, just recompile, don't fail
#endif
------------------------
checkModuleFingerprint :: String -> Fingerprint -> Fingerprint
-> IfG RecompileRequired
checkModuleFingerprint reason old_mod_hash new_mod_hash
| new_mod_hash == old_mod_hash
= up_to_date (ptext (sLit "Module fingerprint unchanged"))
| otherwise
= out_of_date_hash reason (ptext (sLit " Module fingerprint has changed"))
old_mod_hash new_mod_hash
------------------------
checkMaybeHash :: String -> Maybe Fingerprint -> Fingerprint -> SDoc
-> IfG RecompileRequired -> IfG RecompileRequired
checkMaybeHash reason maybe_old_hash new_hash doc continue
| Just hash <- maybe_old_hash, hash /= new_hash
= out_of_date_hash reason doc hash new_hash
| otherwise
= continue
------------------------
checkEntityUsage :: String
-> (OccName -> Maybe (OccName, Fingerprint))
-> (OccName, Fingerprint)
-> IfG RecompileRequired
checkEntityUsage reason new_hash (name,old_hash)
= case new_hash name of
Nothing -> -- We used it before, but it ain't there now
out_of_date reason (sep [ptext (sLit "No longer exported:"), ppr name])
Just (_, new_hash) -- It's there, but is it up to date?
| new_hash == old_hash -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_hash))
return UpToDate
| otherwise -> out_of_date_hash reason (ptext (sLit " Out of date:") <+> ppr name)
old_hash new_hash
up_to_date :: SDoc -> IfG RecompileRequired
up_to_date msg = traceHiDiffs msg >> return UpToDate
out_of_date :: String -> SDoc -> IfG RecompileRequired
out_of_date reason msg = traceHiDiffs msg >> return (RecompBecause reason)
out_of_date_hash :: String -> SDoc -> Fingerprint -> Fingerprint -> IfG RecompileRequired
out_of_date_hash reason msg old_hash new_hash
= out_of_date reason (hsep [msg, ppr old_hash, ptext (sLit "->"), ppr new_hash])
----------------------
checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
-- This helper is used in two places
checkList [] = return UpToDate
checkList (check:checks) = do recompile <- check
if recompileRequired recompile
then return recompile
else checkList checks
{-
************************************************************************
* *
Converting things to their Iface equivalents
* *
************************************************************************
-}
tyThingToIfaceDecl :: TyThing -> IfaceDecl
tyThingToIfaceDecl (AnId id) = idToIfaceDecl id
tyThingToIfaceDecl (ATyCon tycon) = snd (tyConToIfaceDecl emptyTidyEnv tycon)
tyThingToIfaceDecl (ACoAxiom ax) = coAxiomToIfaceDecl ax
tyThingToIfaceDecl (AConLike cl) = case cl of
RealDataCon dc -> dataConToIfaceDecl dc -- for ppr purposes only
PatSynCon ps -> patSynToIfaceDecl ps
--------------------------
idToIfaceDecl :: Id -> IfaceDecl
-- The Id is already tidied, so that locally-bound names
-- (lambdas, for-alls) already have non-clashing OccNames
-- We can't tidy it here, locally, because it may have
-- free variables in its type or IdInfo
idToIfaceDecl id
= IfaceId { ifName = getOccName id,
ifType = toIfaceType (idType id),
ifIdDetails = toIfaceIdDetails (idDetails id),
ifIdInfo = toIfaceIdInfo (idInfo id) }
--------------------------
dataConToIfaceDecl :: DataCon -> IfaceDecl
dataConToIfaceDecl dataCon
= IfaceId { ifName = getOccName dataCon,
ifType = toIfaceType (dataConUserType dataCon),
ifIdDetails = IfVanillaId,
ifIdInfo = NoInfo }
--------------------------
patSynToIfaceDecl :: PatSyn -> IfaceDecl
patSynToIfaceDecl ps
= IfacePatSyn { ifName = getOccName . getName $ ps
, ifPatMatcher = to_if_pr (patSynMatcher ps)
, ifPatBuilder = fmap to_if_pr (patSynBuilder ps)
, ifPatIsInfix = patSynIsInfix ps
, ifPatUnivTvs = toIfaceTvBndrs univ_tvs'
, ifPatExTvs = toIfaceTvBndrs ex_tvs'
, ifPatProvCtxt = tidyToIfaceContext env2 prov_theta
, ifPatReqCtxt = tidyToIfaceContext env2 req_theta
, ifPatArgs = map (tidyToIfaceType env2) args
, ifPatTy = tidyToIfaceType env2 rhs_ty
}
where
(univ_tvs, ex_tvs, prov_theta, req_theta, args, rhs_ty) = patSynSig ps
(env1, univ_tvs') = tidyTyVarBndrs emptyTidyEnv univ_tvs
(env2, ex_tvs') = tidyTyVarBndrs env1 ex_tvs
to_if_pr (id, needs_dummy) = (idName id, needs_dummy)
--------------------------
coAxiomToIfaceDecl :: CoAxiom br -> IfaceDecl
-- We *do* tidy Axioms, because they are not (and cannot
-- conveniently be) built in tidy form
coAxiomToIfaceDecl ax@(CoAxiom { co_ax_tc = tycon, co_ax_branches = branches
, co_ax_role = role })
= IfaceAxiom { ifName = name
, ifTyCon = toIfaceTyCon tycon
, ifRole = role
, ifAxBranches = brListMap (coAxBranchToIfaceBranch tycon
(brListMap coAxBranchLHS branches))
branches }
where
name = getOccName ax
-- 2nd parameter is the list of branch LHSs, for conversion from incompatible branches
-- to incompatible indices
-- See Note [Storing compatibility] in CoAxiom
coAxBranchToIfaceBranch :: TyCon -> [[Type]] -> CoAxBranch -> IfaceAxBranch
coAxBranchToIfaceBranch tc lhs_s
branch@(CoAxBranch { cab_incomps = incomps })
= (coAxBranchToIfaceBranch' tc branch) { ifaxbIncomps = iface_incomps }
where
iface_incomps = map (expectJust "iface_incomps"
. (flip findIndex lhs_s
. eqTypes)
. coAxBranchLHS) incomps
-- use this one for standalone branches without incompatibles
coAxBranchToIfaceBranch' :: TyCon -> CoAxBranch -> IfaceAxBranch
coAxBranchToIfaceBranch' tc (CoAxBranch { cab_tvs = tvs, cab_lhs = lhs
, cab_roles = roles, cab_rhs = rhs })
= IfaceAxBranch { ifaxbTyVars = toIfaceTvBndrs tv_bndrs
, ifaxbLHS = tidyToIfaceTcArgs env1 tc lhs
, ifaxbRoles = roles
, ifaxbRHS = tidyToIfaceType env1 rhs
, ifaxbIncomps = [] }
where
(env1, tv_bndrs) = tidyTyClTyVarBndrs emptyTidyEnv tvs
-- Don't re-bind in-scope tyvars
-- See Note [CoAxBranch type variables] in CoAxiom
-----------------
tyConToIfaceDecl :: TidyEnv -> TyCon -> (TidyEnv, IfaceDecl)
-- We *do* tidy TyCons, because they are not (and cannot
-- conveniently be) built in tidy form
-- The returned TidyEnv is the one after tidying the tyConTyVars
tyConToIfaceDecl env tycon
| Just clas <- tyConClass_maybe tycon
= classToIfaceDecl env clas
| Just syn_rhs <- synTyConRhs_maybe tycon
= ( tc_env1
, IfaceSynonym { ifName = getOccName tycon,
ifTyVars = if_tc_tyvars,
ifRoles = tyConRoles tycon,
ifSynRhs = if_syn_type syn_rhs,
ifSynKind = tidyToIfaceType tc_env1 (tyConResKind tycon)
})
| Just fam_flav <- famTyConFlav_maybe tycon
= ( tc_env1
, IfaceFamily { ifName = getOccName tycon,
ifTyVars = if_tc_tyvars,
ifResVar = if_res_var,
ifFamFlav = to_if_fam_flav fam_flav,
ifFamKind = tidyToIfaceType tc_env1 (tyConResKind tycon),
ifFamInj = familyTyConInjectivityInfo tycon
})
| isAlgTyCon tycon
= ( tc_env1
, IfaceData { ifName = getOccName tycon,
ifCType = tyConCType tycon,
ifTyVars = if_tc_tyvars,
ifRoles = tyConRoles tycon,
ifCtxt = tidyToIfaceContext tc_env1 (tyConStupidTheta tycon),
ifCons = ifaceConDecls (algTyConRhs tycon),
ifRec = boolToRecFlag (isRecursiveTyCon tycon),
ifGadtSyntax = isGadtSyntaxTyCon tycon,
ifPromotable = isJust (promotableTyCon_maybe tycon),
ifParent = parent })
| otherwise -- FunTyCon, PrimTyCon, promoted TyCon/DataCon
-- For pretty printing purposes only.
= ( env
, IfaceData { ifName = getOccName tycon,
ifCType = Nothing,
ifTyVars = funAndPrimTyVars,
ifRoles = tyConRoles tycon,
ifCtxt = [],
ifCons = IfDataTyCon [],
ifRec = boolToRecFlag False,
ifGadtSyntax = False,
ifPromotable = False,
ifParent = IfNoParent })
where
(tc_env1, tc_tyvars) = tidyTyClTyVarBndrs env (tyConTyVars tycon)
if_tc_tyvars = toIfaceTvBndrs tc_tyvars
if_syn_type ty = tidyToIfaceType tc_env1 ty
if_res_var = getFS `fmap` tyConFamilyResVar_maybe tycon
funAndPrimTyVars = toIfaceTvBndrs $ take (tyConArity tycon) alphaTyVars
parent = case tyConFamInstSig_maybe tycon of
Just (tc, ty, ax) -> IfDataInstance (coAxiomName ax)
(toIfaceTyCon tc)
(tidyToIfaceTcArgs tc_env1 tc ty)
Nothing -> IfNoParent
to_if_fam_flav OpenSynFamilyTyCon = IfaceOpenSynFamilyTyCon
to_if_fam_flav (ClosedSynFamilyTyCon (Just ax))
= IfaceClosedSynFamilyTyCon (Just (axn, ibr))
where defs = fromBranchList $ coAxiomBranches ax
ibr = map (coAxBranchToIfaceBranch' tycon) defs
axn = coAxiomName ax
to_if_fam_flav (ClosedSynFamilyTyCon Nothing)
= IfaceClosedSynFamilyTyCon Nothing
to_if_fam_flav AbstractClosedSynFamilyTyCon
= IfaceAbstractClosedSynFamilyTyCon
to_if_fam_flav (BuiltInSynFamTyCon {})
= IfaceBuiltInSynFamTyCon
ifaceConDecls (NewTyCon { data_con = con }) = IfNewTyCon (ifaceConDecl con)
ifaceConDecls (DataTyCon { data_cons = cons }) = IfDataTyCon (map ifaceConDecl cons)
ifaceConDecls (DataFamilyTyCon {}) = IfDataFamTyCon
ifaceConDecls (TupleTyCon { data_con = con }) = IfDataTyCon [ifaceConDecl con]
ifaceConDecls (AbstractTyCon distinct) = IfAbstractTyCon distinct
-- The AbstractTyCon case happens when a TyCon has been trimmed
-- during tidying.
-- Furthermore, tyThingToIfaceDecl is also used in TcRnDriver
-- for GHCi, when browsing a module, in which case the
-- AbstractTyCon and TupleTyCon cases are perfectly sensible.
-- (Tuple declarations are not serialised into interface files.)
ifaceConDecl data_con
= IfCon { ifConOcc = getOccName (dataConName data_con),
ifConInfix = dataConIsInfix data_con,
ifConWrapper = isJust (dataConWrapId_maybe data_con),
ifConExTvs = toIfaceTvBndrs ex_tvs',
ifConEqSpec = map to_eq_spec eq_spec,
ifConCtxt = tidyToIfaceContext con_env2 theta,
ifConArgTys = map (tidyToIfaceType con_env2) arg_tys,
ifConFields = map getOccName
(dataConFieldLabels data_con),
ifConStricts = map (toIfaceBang con_env2)
(dataConImplBangs data_con),
ifConSrcStricts = map toIfaceSrcBang
(dataConSrcBangs data_con)}
where
(univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _) = dataConFullSig data_con
-- Tidy the univ_tvs of the data constructor to be identical
-- to the tyConTyVars of the type constructor. This means
-- (a) we don't need to redundantly put them into the interface file
-- (b) when pretty-printing an Iface data declaration in H98-style syntax,
-- we know that the type variables will line up
-- The latter (b) is important because we pretty-print type constructors
-- by converting to IfaceSyn and pretty-printing that
con_env1 = (fst tc_env1, mkVarEnv (zipEqual "ifaceConDecl" univ_tvs tc_tyvars))
-- A bit grimy, perhaps, but it's simple!
(con_env2, ex_tvs') = tidyTyVarBndrs con_env1 ex_tvs
to_eq_spec (tv,ty) = (toIfaceTyVar (tidyTyVar con_env2 tv), tidyToIfaceType con_env2 ty)
toIfaceBang :: TidyEnv -> HsImplBang -> IfaceBang
toIfaceBang _ HsLazy = IfNoBang
toIfaceBang _ (HsUnpack Nothing) = IfUnpack
toIfaceBang env (HsUnpack (Just co)) = IfUnpackCo (toIfaceCoercion (tidyCo env co))
toIfaceBang _ HsStrict = IfStrict
toIfaceSrcBang :: HsSrcBang -> IfaceSrcBang
toIfaceSrcBang (HsSrcBang _ unpk bang) = IfSrcBang unpk bang
classToIfaceDecl :: TidyEnv -> Class -> (TidyEnv, IfaceDecl)
classToIfaceDecl env clas
= ( env1
, IfaceClass { ifCtxt = tidyToIfaceContext env1 sc_theta,
ifName = getOccName (classTyCon clas),
ifTyVars = toIfaceTvBndrs clas_tyvars',
ifRoles = tyConRoles (classTyCon clas),
ifFDs = map toIfaceFD clas_fds,
ifATs = map toIfaceAT clas_ats,
ifSigs = map toIfaceClassOp op_stuff,
ifMinDef = fmap getFS (classMinimalDef clas),
ifRec = boolToRecFlag (isRecursiveTyCon tycon) })
where
(clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff)
= classExtraBigSig clas
tycon = classTyCon clas
(env1, clas_tyvars') = tidyTyVarBndrs env clas_tyvars
toIfaceAT :: ClassATItem -> IfaceAT
toIfaceAT (ATI tc def)
= IfaceAT if_decl (fmap (tidyToIfaceType env2) def)
where
(env2, if_decl) = tyConToIfaceDecl env1 tc
toIfaceClassOp (sel_id, def_meth)
= ASSERT(sel_tyvars == clas_tyvars)
IfaceClassOp (getOccName sel_id) (toDmSpec def_meth)
(tidyToIfaceType env1 op_ty)
where
-- Be careful when splitting the type, because of things
-- like class Foo a where
-- op :: (?x :: String) => a -> a
-- and class Baz a where
-- op :: (Ord a) => a -> a
(sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
op_ty = funResultTy rho_ty
toDmSpec NoDefMeth = NoDM
toDmSpec (GenDefMeth _) = GenericDM
toDmSpec (DefMeth _) = VanillaDM
toIfaceFD (tvs1, tvs2) = (map (getFS . tidyTyVar env1) tvs1,
map (getFS . tidyTyVar env1) tvs2)
--------------------------
tidyToIfaceType :: TidyEnv -> Type -> IfaceType
tidyToIfaceType env ty = toIfaceType (tidyType env ty)
tidyToIfaceTcArgs :: TidyEnv -> TyCon -> [Type] -> IfaceTcArgs
tidyToIfaceTcArgs env tc tys = toIfaceTcArgs tc (tidyTypes env tys)
tidyToIfaceContext :: TidyEnv -> ThetaType -> IfaceContext
tidyToIfaceContext env theta = map (tidyToIfaceType env) theta
tidyTyClTyVarBndrs :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyTyClTyVarBndrs env tvs = mapAccumL tidyTyClTyVarBndr env tvs
tidyTyClTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
-- If the type variable "binder" is in scope, don't re-bind it
-- In a class decl, for example, the ATD binders mention
-- (amd must mention) the class tyvars
tidyTyClTyVarBndr env@(_, subst) tv
| Just tv' <- lookupVarEnv subst tv = (env, tv')
| otherwise = tidyTyVarBndr env tv
tidyTyVar :: TidyEnv -> TyVar -> TyVar
tidyTyVar (_, subst) tv = lookupVarEnv subst tv `orElse` tv
-- TcType.tidyTyVarOcc messes around with FlatSkols
getFS :: NamedThing a => a -> FastString
getFS x = occNameFS (getOccName x)
--------------------------
instanceToIfaceInst :: ClsInst -> IfaceClsInst
instanceToIfaceInst (ClsInst { is_dfun = dfun_id, is_flag = oflag
, is_cls_nm = cls_name, is_cls = cls
, is_tcs = mb_tcs
, is_orphan = orph })
= ASSERT( cls_name == className cls )
IfaceClsInst { ifDFun = dfun_name,
ifOFlag = oflag,
ifInstCls = cls_name,
ifInstTys = map do_rough mb_tcs,
ifInstOrph = orph }
where
do_rough Nothing = Nothing
do_rough (Just n) = Just (toIfaceTyCon_name n)
dfun_name = idName dfun_id
--------------------------
famInstToIfaceFamInst :: FamInst -> IfaceFamInst
famInstToIfaceFamInst (FamInst { fi_axiom = axiom,
fi_fam = fam,
fi_tcs = roughs })
= IfaceFamInst { ifFamInstAxiom = coAxiomName axiom
, ifFamInstFam = fam
, ifFamInstTys = map do_rough roughs
, ifFamInstOrph = orph }
where
do_rough Nothing = Nothing
do_rough (Just n) = Just (toIfaceTyCon_name n)
fam_decl = tyConName $ coAxiomTyCon axiom
mod = ASSERT( isExternalName (coAxiomName axiom) )
nameModule (coAxiomName axiom)
is_local name = nameIsLocalOrFrom mod name
lhs_names = filterNameSet is_local (orphNamesOfCoCon axiom)
orph | is_local fam_decl
= NotOrphan (nameOccName fam_decl)
| otherwise
= chooseOrphanAnchor $ nameSetElems lhs_names
--------------------------
toIfaceLetBndr :: Id -> IfaceLetBndr
toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id))
(toIfaceType (idType id))
(toIfaceIdInfo (idInfo id))
-- Put into the interface file any IdInfo that CoreTidy.tidyLetBndr
-- has left on the Id. See Note [IdInfo on nested let-bindings] in IfaceSyn
--------------------------
toIfaceIdDetails :: IdDetails -> IfaceIdDetails
toIfaceIdDetails VanillaId = IfVanillaId
toIfaceIdDetails (DFunId {}) = IfDFunId
toIfaceIdDetails (RecSelId { sel_naughty = n
, sel_tycon = tc }) = IfRecSelId (toIfaceTyCon tc) n
-- Currently we don't persist these three "advisory" IdInfos
-- through interface files. We easily could if it mattered
toIfaceIdDetails PatSynId = IfVanillaId
toIfaceIdDetails ReflectionId = IfVanillaId
toIfaceIdDetails DefMethId = IfVanillaId
-- The remaining cases are all "implicit Ids" which don't
-- appear in interface files at all
toIfaceIdDetails other = pprTrace "toIfaceIdDetails" (ppr other)
IfVanillaId -- Unexpected; the other
toIfaceIdInfo :: IdInfo -> IfaceIdInfo
toIfaceIdInfo id_info
= case catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
inline_hsinfo, unfold_hsinfo] of
[] -> NoInfo
infos -> HasInfo infos
-- NB: strictness and arity must appear in the list before unfolding
-- See TcIface.tcUnfolding
where
------------ Arity --------------
arity_info = arityInfo id_info
arity_hsinfo | arity_info == 0 = Nothing
| otherwise = Just (HsArity arity_info)
------------ Caf Info --------------
caf_info = cafInfo id_info
caf_hsinfo = case caf_info of
NoCafRefs -> Just HsNoCafRefs
_other -> Nothing
------------ Strictness --------------
-- No point in explicitly exporting TopSig
sig_info = strictnessInfo id_info
strict_hsinfo | not (isNopSig sig_info) = Just (HsStrictness sig_info)
| otherwise = Nothing
------------ Unfolding --------------
unfold_hsinfo = toIfUnfolding loop_breaker (unfoldingInfo id_info)
loop_breaker = isStrongLoopBreaker (occInfo id_info)
------------ Inline prag --------------
inline_prag = inlinePragInfo id_info
inline_hsinfo | isDefaultInlinePragma inline_prag = Nothing
| otherwise = Just (HsInline inline_prag)
--------------------------
toIfUnfolding :: Bool -> Unfolding -> Maybe IfaceInfoItem
toIfUnfolding lb (CoreUnfolding { uf_tmpl = rhs
, uf_src = src
, uf_guidance = guidance })
= Just $ HsUnfold lb $
case src of
InlineStable
-> case guidance of
UnfWhen {ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
-> IfInlineRule arity unsat_ok boring_ok if_rhs
_other -> IfCoreUnfold True if_rhs
InlineCompulsory -> IfCompulsory if_rhs
InlineRhs -> IfCoreUnfold False if_rhs
-- Yes, even if guidance is UnfNever, expose the unfolding
-- If we didn't want to expose the unfolding, TidyPgm would
-- have stuck in NoUnfolding. For supercompilation we want
-- to see that unfolding!
where
if_rhs = toIfaceExpr rhs
toIfUnfolding lb (DFunUnfolding { df_bndrs = bndrs, df_args = args })
= Just (HsUnfold lb (IfDFunUnfold (map toIfaceBndr bndrs) (map toIfaceExpr args)))
-- No need to serialise the data constructor;
-- we can recover it from the type of the dfun
toIfUnfolding _ _
= Nothing
--------------------------
coreRuleToIfaceRule :: CoreRule -> IfaceRule
coreRuleToIfaceRule (BuiltinRule { ru_fn = fn})
= pprTrace "toHsRule: builtin" (ppr fn) $
bogusIfaceRule fn
coreRuleToIfaceRule (Rule { ru_name = name, ru_fn = fn,
ru_act = act, ru_bndrs = bndrs,
ru_args = args, ru_rhs = rhs,
ru_orphan = orph, ru_auto = auto })
= IfaceRule { ifRuleName = name, ifActivation = act,
ifRuleBndrs = map toIfaceBndr bndrs,
ifRuleHead = fn,
ifRuleArgs = map do_arg args,
ifRuleRhs = toIfaceExpr rhs,
ifRuleAuto = auto,
ifRuleOrph = orph }
where
-- For type args we must remove synonyms from the outermost
-- level. Reason: so that when we read it back in we'll
-- construct the same ru_rough field as we have right now;
-- see tcIfaceRule
do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
do_arg (Coercion co) = IfaceCo (toIfaceCoercion co)
do_arg arg = toIfaceExpr arg
bogusIfaceRule :: Name -> IfaceRule
bogusIfaceRule id_name
= IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive,
ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
ifRuleRhs = IfaceExt id_name, ifRuleOrph = IsOrphan,
ifRuleAuto = True }
---------------------
toIfaceExpr :: CoreExpr -> IfaceExpr
toIfaceExpr (Var v) = toIfaceVar v
toIfaceExpr (Lit l) = IfaceLit l
toIfaceExpr (Type ty) = IfaceType (toIfaceType ty)
toIfaceExpr (Coercion co) = IfaceCo (toIfaceCoercion co)
toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x, toIfaceOneShot x) (toIfaceExpr b)
toIfaceExpr (App f a) = toIfaceApp f [a]
toIfaceExpr (Case s x ty as)
| null as = IfaceECase (toIfaceExpr s) (toIfaceType ty)
| otherwise = IfaceCase (toIfaceExpr s) (getFS x) (map toIfaceAlt as)
toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e)
toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (toIfaceCoercion co)
toIfaceExpr (Tick t e)
| Just t' <- toIfaceTickish t = IfaceTick t' (toIfaceExpr e)
| otherwise = toIfaceExpr e
toIfaceOneShot :: Id -> IfaceOneShot
toIfaceOneShot id | isId id
, OneShotLam <- oneShotInfo (idInfo id)
= IfaceOneShot
| otherwise
= IfaceNoOneShot
---------------------
toIfaceTickish :: Tickish Id -> Maybe IfaceTickish
toIfaceTickish (ProfNote cc tick push) = Just (IfaceSCC cc tick push)
toIfaceTickish (HpcTick modl ix) = Just (IfaceHpcTick modl ix)
toIfaceTickish (SourceNote src names) = Just (IfaceSource src names)
toIfaceTickish (Breakpoint {}) = Nothing
-- Ignore breakpoints, since they are relevant only to GHCi, and
-- should not be serialised (Trac #8333)
---------------------
toIfaceBind :: Bind Id -> IfaceBinding
toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
---------------------
toIfaceAlt :: (AltCon, [Var], CoreExpr)
-> (IfaceConAlt, [FastString], IfaceExpr)
toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
---------------------
toIfaceCon :: AltCon -> IfaceConAlt
toIfaceCon (DataAlt dc) = IfaceDataAlt (getName dc)
toIfaceCon (LitAlt l) = IfaceLitAlt l
toIfaceCon DEFAULT = IfaceDefault
---------------------
toIfaceApp :: Expr CoreBndr -> [Arg CoreBndr] -> IfaceExpr
toIfaceApp (App f a) as = toIfaceApp f (a:as)
toIfaceApp (Var v) as
= case isDataConWorkId_maybe v of
-- We convert the *worker* for tuples into IfaceTuples
Just dc | saturated
, Just tup_sort <- tyConTuple_maybe tc
-> IfaceTuple tup_sort tup_args
where
val_args = dropWhile isTypeArg as
saturated = val_args `lengthIs` idArity v
tup_args = map toIfaceExpr val_args
tc = dataConTyCon dc
_ -> mkIfaceApps (toIfaceVar v) as
toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
mkIfaceApps :: IfaceExpr -> [CoreExpr] -> IfaceExpr
mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
---------------------
toIfaceVar :: Id -> IfaceExpr
toIfaceVar v
| Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
-- Foreign calls have special syntax
| isExternalName name = IfaceExt name
| otherwise = IfaceLcl (getFS name)
where name = idName v
| acowley/ghc | compiler/iface/MkIface.hs | bsd-3-clause | 88,502 | 963 | 24 | 28,074 | 11,814 | 7,194 | 4,620 | -1 | -1 |
module Main where
import Lib
main :: IO ()
main = undefined
| joranvar/StandupMaths-FourHasFourLetters | app/Main.hs | gpl-3.0 | 62 | 0 | 6 | 14 | 22 | 13 | 9 | 4 | 1 |
module Foo () where
{-@ foo :: forall a <p :: x0:Int -> x1:a -> Prop>.
(i:Int -> j : Int-> a<p (i+j)>) ->
ii:Int -> jj:Int
-> a <p (ii+jj)>
@-}
foo :: (Int -> Int -> a) -> Int -> Int -> a
foo f i j = f i j
| mightymoose/liquidhaskell | tests/pos/pargs1.hs | bsd-3-clause | 258 | 0 | 8 | 105 | 53 | 29 | 24 | 3 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Encoding
-- Copyright : (c) The University of Glasgow, 2008-2009
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- Text codecs for I/O
--
-----------------------------------------------------------------------------
module GHC.IO.Encoding (
BufferCodec(..), TextEncoding(..), TextEncoder, TextDecoder, CodingProgress(..),
latin1, latin1_encode, latin1_decode,
utf8, utf8_bom,
utf16, utf16le, utf16be,
utf32, utf32le, utf32be,
initLocaleEncoding,
getLocaleEncoding, getFileSystemEncoding, getForeignEncoding,
setLocaleEncoding, setFileSystemEncoding, setForeignEncoding,
char8,
mkTextEncoding,
) where
import GHC.Base
import GHC.IO.Exception
import GHC.IO.Buffer
import GHC.IO.Encoding.Failure
import GHC.IO.Encoding.Types
#if !defined(mingw32_HOST_OS)
import qualified GHC.IO.Encoding.Iconv as Iconv
#else
import qualified GHC.IO.Encoding.CodePage as CodePage
import Text.Read (reads)
#endif
import qualified GHC.IO.Encoding.Latin1 as Latin1
import qualified GHC.IO.Encoding.UTF8 as UTF8
import qualified GHC.IO.Encoding.UTF16 as UTF16
import qualified GHC.IO.Encoding.UTF32 as UTF32
import GHC.List
import GHC.Word
import Data.IORef
import Data.Char (toUpper)
import System.IO.Unsafe (unsafePerformIO)
-- -----------------------------------------------------------------------------
-- | The Latin1 (ISO8859-1) encoding. This encoding maps bytes
-- directly to the first 256 Unicode code points, and is thus not a
-- complete Unicode encoding. An attempt to write a character greater than
-- '\255' to a 'Handle' using the 'latin1' encoding will result in an error.
latin1 :: TextEncoding
latin1 = Latin1.latin1_checked
-- | The UTF-8 Unicode encoding
utf8 :: TextEncoding
utf8 = UTF8.utf8
-- | The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte
-- sequence 0xEF 0xBB 0xBF). This encoding behaves like 'utf8',
-- except that on input, the BOM sequence is ignored at the beginning
-- of the stream, and on output, the BOM sequence is prepended.
--
-- The byte-order-mark is strictly unnecessary in UTF-8, but is
-- sometimes used to identify the encoding of a file.
--
utf8_bom :: TextEncoding
utf8_bom = UTF8.utf8_bom
-- | The UTF-16 Unicode encoding (a byte-order-mark should be used to
-- indicate endianness).
utf16 :: TextEncoding
utf16 = UTF16.utf16
-- | The UTF-16 Unicode encoding (litte-endian)
utf16le :: TextEncoding
utf16le = UTF16.utf16le
-- | The UTF-16 Unicode encoding (big-endian)
utf16be :: TextEncoding
utf16be = UTF16.utf16be
-- | The UTF-32 Unicode encoding (a byte-order-mark should be used to
-- indicate endianness).
utf32 :: TextEncoding
utf32 = UTF32.utf32
-- | The UTF-32 Unicode encoding (litte-endian)
utf32le :: TextEncoding
utf32le = UTF32.utf32le
-- | The UTF-32 Unicode encoding (big-endian)
utf32be :: TextEncoding
utf32be = UTF32.utf32be
-- | The Unicode encoding of the current locale
--
-- @since 4.5.0.0
getLocaleEncoding :: IO TextEncoding
-- | The Unicode encoding of the current locale, but allowing arbitrary
-- undecodable bytes to be round-tripped through it.
--
-- This 'TextEncoding' is used to decode and encode command line arguments
-- and environment variables on non-Windows platforms.
--
-- On Windows, this encoding *should not* be used if possible because
-- the use of code pages is deprecated: Strings should be retrieved
-- via the "wide" W-family of UTF-16 APIs instead
--
-- @since 4.5.0.0
getFileSystemEncoding :: IO TextEncoding
-- | The Unicode encoding of the current locale, but where undecodable
-- bytes are replaced with their closest visual match. Used for
-- the 'CString' marshalling functions in "Foreign.C.String"
--
-- @since 4.5.0.0
getForeignEncoding :: IO TextEncoding
-- | @since 4.5.0.0
setLocaleEncoding, setFileSystemEncoding, setForeignEncoding :: TextEncoding -> IO ()
(getLocaleEncoding, setLocaleEncoding) = mkGlobal initLocaleEncoding
(getFileSystemEncoding, setFileSystemEncoding) = mkGlobal initFileSystemEncoding
(getForeignEncoding, setForeignEncoding) = mkGlobal initForeignEncoding
mkGlobal :: a -> (IO a, a -> IO ())
mkGlobal x = unsafePerformIO $ do
x_ref <- newIORef x
return (readIORef x_ref, writeIORef x_ref)
-- | @since 4.5.0.0
initLocaleEncoding, initFileSystemEncoding, initForeignEncoding :: TextEncoding
#if !defined(mingw32_HOST_OS)
-- It is rather important that we don't just call Iconv.mkIconvEncoding here
-- because some iconvs (in particular GNU iconv) will brokenly UTF-8 encode
-- lone surrogates without complaint.
--
-- By going through our Haskell implementations of those encodings, we are
-- guaranteed to catch such errors.
--
-- FIXME: this is not a complete solution because if the locale encoding is one
-- which we don't have a Haskell-side decoder for, iconv might still ignore the
-- lone surrogate in the input.
initLocaleEncoding = unsafePerformIO $ mkTextEncoding' ErrorOnCodingFailure Iconv.localeEncodingName
initFileSystemEncoding = unsafePerformIO $ mkTextEncoding' RoundtripFailure Iconv.localeEncodingName
initForeignEncoding = unsafePerformIO $ mkTextEncoding' IgnoreCodingFailure Iconv.localeEncodingName
#else
initLocaleEncoding = CodePage.localeEncoding
initFileSystemEncoding = CodePage.mkLocaleEncoding RoundtripFailure
initForeignEncoding = CodePage.mkLocaleEncoding IgnoreCodingFailure
#endif
-- | An encoding in which Unicode code points are translated to bytes
-- by taking the code point modulo 256. When decoding, bytes are
-- translated directly into the equivalent code point.
--
-- This encoding never fails in either direction. However, encoding
-- discards information, so encode followed by decode is not the
-- identity.
--
-- @since 4.4.0.0
char8 :: TextEncoding
char8 = Latin1.latin1
-- | Look up the named Unicode encoding. May fail with
--
-- * 'isDoesNotExistError' if the encoding is unknown
--
-- The set of known encodings is system-dependent, but includes at least:
--
-- * @UTF-8@
--
-- * @UTF-16@, @UTF-16BE@, @UTF-16LE@
--
-- * @UTF-32@, @UTF-32BE@, @UTF-32LE@
--
-- There is additional notation (borrowed from GNU iconv) for specifying
-- how illegal characters are handled:
--
-- * a suffix of @\/\/IGNORE@, e.g. @UTF-8\/\/IGNORE@, will cause
-- all illegal sequences on input to be ignored, and on output
-- will drop all code points that have no representation in the
-- target encoding.
--
-- * a suffix of @\/\/TRANSLIT@ will choose a replacement character
-- for illegal sequences or code points.
--
-- * a suffix of @\/\/ROUNDTRIP@ will use a PEP383-style escape mechanism
-- to represent any invalid bytes in the input as Unicode codepoints (specifically,
-- as lone surrogates, which are normally invalid in UTF-32).
-- Upon output, these special codepoints are detected and turned back into the
-- corresponding original byte.
--
-- In theory, this mechanism allows arbitrary data to be roundtripped via
-- a 'String' with no loss of data. In practice, there are two limitations
-- to be aware of:
--
-- 1. This only stands a chance of working for an encoding which is an ASCII
-- superset, as for security reasons we refuse to escape any bytes smaller
-- than 128. Many encodings of interest are ASCII supersets (in particular,
-- you can assume that the locale encoding is an ASCII superset) but many
-- (such as UTF-16) are not.
--
-- 2. If the underlying encoding is not itself roundtrippable, this mechanism
-- can fail. Roundtrippable encodings are those which have an injective mapping
-- into Unicode. Almost all encodings meet this criteria, but some do not. Notably,
-- Shift-JIS (CP932) and Big5 contain several different encodings of the same
-- Unicode codepoint.
--
-- On Windows, you can access supported code pages with the prefix
-- @CP@; for example, @\"CP1250\"@.
--
mkTextEncoding :: String -> IO TextEncoding
mkTextEncoding e = case mb_coding_failure_mode of
Nothing -> unknownEncodingErr e
Just cfm -> mkTextEncoding' cfm enc
where
(enc, suffix) = span (/= '/') e
mb_coding_failure_mode = case suffix of
"" -> Just ErrorOnCodingFailure
"//IGNORE" -> Just IgnoreCodingFailure
"//TRANSLIT" -> Just TransliterateCodingFailure
"//ROUNDTRIP" -> Just RoundtripFailure
_ -> Nothing
mkTextEncoding' :: CodingFailureMode -> String -> IO TextEncoding
mkTextEncoding' cfm enc =
case [toUpper c | c <- enc, c /= '-'] of
-- UTF-8 and friends we can handle ourselves
"UTF8" -> return $ UTF8.mkUTF8 cfm
"UTF16" -> return $ UTF16.mkUTF16 cfm
"UTF16LE" -> return $ UTF16.mkUTF16le cfm
"UTF16BE" -> return $ UTF16.mkUTF16be cfm
"UTF32" -> return $ UTF32.mkUTF32 cfm
"UTF32LE" -> return $ UTF32.mkUTF32le cfm
"UTF32BE" -> return $ UTF32.mkUTF32be cfm
-- On AIX, we want to avoid iconv, because it is either
-- a) totally broken, or b) non-reentrant, or c) actually works.
-- Detecting b) is difficult as you'd have to trigger the reentrancy
-- corruption.
-- Therefore, on AIX, we handle the popular ASCII and latin1 encodings
-- ourselves. For consistency, we do the same on other platforms.
-- We use `mkLatin1_checked` instead of `mkLatin1`, since the latter
-- completely ignores the CodingFailureMode (TEST=encoding005).
_ | isAscii -> return (Latin1.mkAscii cfm)
_ | isLatin1 -> return (Latin1.mkLatin1_checked cfm)
#if defined(mingw32_HOST_OS)
'C':'P':n | [(cp,"")] <- reads n -> return $ CodePage.mkCodePageEncoding cfm cp
_ -> unknownEncodingErr (enc ++ codingFailureModeSuffix cfm)
#else
-- Otherwise, handle other encoding needs via iconv.
-- Unfortunately there is no good way to determine whether iconv is actually
-- functional without telling it to do something.
_ -> do res <- Iconv.mkIconvEncoding cfm enc
case res of
Just e -> return e
Nothing -> unknownEncodingErr (enc ++ codingFailureModeSuffix cfm)
#endif
where
isAscii = enc `elem` asciiEncNames
isLatin1 = enc `elem` latin1EncNames
asciiEncNames = -- ASCII aliases specified by RFC 1345 and RFC 3808.
[ "ANSI_X3.4-1968", "iso-ir-6", "ANSI_X3.4-1986", "ISO_646.irv:1991"
, "US-ASCII", "us", "IBM367", "cp367", "csASCII", "ASCII", "ISO646-US"
]
latin1EncNames = -- latin1 aliases specified by RFC 1345 and RFC 3808.
[ "ISO_8859-1:1987", "iso-ir-100", "ISO_8859-1", "ISO-8859-1", "latin1",
"l1", "IBM819", "CP819", "csISOLatin1"
]
latin1_encode :: CharBuffer -> Buffer Word8 -> IO (CharBuffer, Buffer Word8)
latin1_encode input output = fmap (\(_why,input',output') -> (input',output')) $ Latin1.latin1_encode input output -- unchecked, used for char8
--latin1_encode = unsafePerformIO $ do mkTextEncoder Iconv.latin1 >>= return.encode
latin1_decode :: Buffer Word8 -> CharBuffer -> IO (Buffer Word8, CharBuffer)
latin1_decode input output = fmap (\(_why,input',output') -> (input',output')) $ Latin1.latin1_decode input output
--latin1_decode = unsafePerformIO $ do mkTextDecoder Iconv.latin1 >>= return.encode
unknownEncodingErr :: String -> IO a
unknownEncodingErr e = ioException (IOError Nothing NoSuchThing "mkTextEncoding"
("unknown encoding:" ++ e) Nothing Nothing)
| snoyberg/ghc | libraries/base/GHC/IO/Encoding.hs | bsd-3-clause | 11,778 | 0 | 13 | 2,190 | 1,374 | 828 | 546 | 106 | 11 |
import Data.IORef
main :: IO ()
main = do
ref <- newIORef 10000
n <- readIORef ref
print $ length $ [0::Int, 2 .. n]
| ezyang/ghc | testsuite/tests/perf/should_run/T13001.hs | bsd-3-clause | 124 | 0 | 8 | 32 | 64 | 32 | 32 | 6 | 1 |
import CabalMessage (message)
import System.Exit
import System.IO
main = hPutStrLn stderr message >> exitFailure
| mydaum/cabal | cabal-testsuite/PackageTests/Regression/T3932/Setup.hs | bsd-3-clause | 114 | 0 | 6 | 15 | 33 | 18 | 15 | 4 | 1 |
{-# LANGUAGE CPP #-}
-------------------------------------------------------------------------------
--
-- | Platform constants
--
-- (c) The University of Glasgow 2013
--
-------------------------------------------------------------------------------
module PlatformConstants (PlatformConstants(..)) where
#include "../includes/dist-derivedconstants/header/GHCConstantsHaskellType.hs"
| urbanslug/ghc | compiler/main/PlatformConstants.hs | bsd-3-clause | 390 | 0 | 5 | 30 | 22 | 18 | 4 | 2 | 0 |
import System.IO
main = do
hGetBuffering stdin >>= print
hGetBuffering stdout >>= print
| ghc-android/ghc | testsuite/tests/ghc-e/should_run/T2228.hs | bsd-3-clause | 92 | 0 | 8 | 17 | 31 | 14 | 17 | 4 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Data.Array.Accelerate.TypeLits.System.Random.MWC
( rndMatrixWith
, rndVectorWith
, module Distributions
) where
import Data.Array.Accelerate.TypeLits.Internal
import GHC.TypeLits
import Data.Proxy
import qualified Data.Array.Accelerate as A
import Data.Array.Accelerate (Elt, Z(..), (:.)(..))
import Data.Array.Accelerate.System.Random.MWC
import System.Random.MWC.Distributions as Distributions
rndMatrixWith :: forall m n e. (KnownNat m, KnownNat n, Elt e) => (GenIO -> IO e) -> IO (AccMatrix m n e)
-- | mwc random provides a fast and "statistically-safe" random distribution to
-- work with this
rndMatrixWith cdf = do r <- randomArray (const cdf) sh
return $ AccMatrix $ A.use r
where m' = fromInteger $ natVal (Proxy :: Proxy m)
n' = fromInteger $ natVal (Proxy :: Proxy n)
sh = Z:.m':.n'
rndVectorWith :: forall n e. (KnownNat n, Elt e) => (GenIO -> IO e) -> IO (AccVector n e)
-- | mwc random provides a fast and "statistically-safe" random distribution to
-- work with this
rndVectorWith cdf = do r <- randomArray (const cdf) sh
return $ AccVector $ A.use r
where n' = fromInteger $ natVal (Proxy :: Proxy n)
sh = Z:.n'
| epsilonhalbe/accelerate-typelits | src/Data/Array/Accelerate/TypeLits/System/Random/MWC.hs | isc | 1,489 | 0 | 10 | 403 | 387 | 221 | 166 | 26 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign
import Foreign.C.Types
foreign import ccall "math.h sin"
c_sin :: CDouble -> CDouble
fastsin :: Double -> Double
fastsin x = realToFrac (c_sin (realToFrac x))
main = mapM_ (print . fastsin) [0/10, 1/10 .. 10/10]
| zhangjiji/real-world-haskell | ch17/SimpleFFI.hs | mit | 275 | 0 | 9 | 46 | 97 | 53 | 44 | 8 | 1 |
{-# LANGUAGE CPP #-}
-- | Parser module for NBP3
module KD8ZRC.Flight.NBP3.Parser where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>))
#endif
import qualified Data.ByteString.Char8 as BRC
import Data.Char (digitToInt)
import Data.Geo.Coordinate
import Data.List (dropWhileEnd, foldl')
import qualified Data.Text as T
import Data.Thyme.Format
import KD8ZRC.Flight.NBP3.CRC
import KD8ZRC.Flight.NBP3.Types
import KD8ZRC.Mapview.Utility.CRC
import Text.Trifecta
import System.Locale
-- | The parser for our telemetry packets. Uses the @parsers@ package and should
-- work with any supported parser combinator library.
--
-- See <https://noexc.org/wiki/NBP/RTTY_Telemetry_Format_v2> for more details.
parser :: (Monad m, DeltaParsing m, Errable m) => m TelemetryLine
parser = do
_ <- colon
callsign' <- manyTill anyChar (try colon)
lat' <- eitherToNum <$> integerOrDouble
_ <- colon
lon' <- eitherToNum <$> integerOrDouble
_ <- colon
altitude' <- eitherToNum <$> integerOrDouble
_ <- colon
time' <- many (token digit)
_ <- colon
voltage' <- eitherToNum <$> integerOrDouble
_ <- colon
crc16T <- number 16 hexDigit
_ <- colon
crc16C <- crcHaskell . dropWhileEnd (/= ':') . init . tail . BRC.unpack <$> line
raw <- line
case lat' <°> lon' of
Nothing ->
raiseErr $ failed "Unable to produce a Coordinate from the given lat/lon pair."
Just coordinate -> do
let crcConfirmation = validateCRC (TelemetryCRC crc16T) crc16C
case crcConfirmation of
CRCMismatch (TelemetryCRC t) (CalculatedCRC c) ->
raiseErr $ failed ("CRC Mismatch: Downlink=" ++
show t ++ " Expected=" ++ show c)
_ -> return $ TelemetryLine
raw
(T.pack callsign')
coordinate
altitude'
(readTime defaultTimeLocale "%H%M%S" time')
(rawVoltageToRealVoltage voltage')
crc16T
where
number base baseDigit =
foldl' (\x d -> base * x + toInteger (digitToInt d)) 0 <$> some baseDigit
eitherToNum :: (Num b, Integral a) => Either a b -> b
eitherToNum = either fromIntegral id
rawVoltageToRealVoltage x = roundToN 3 ((x + 477) / 339)
roundToN :: Integer -> Double -> Double
roundToN n f = (fromInteger $ round $ f * (10^n)) / (10.0^^n)
| noexc/mapview-noexc | src/KD8ZRC/Flight/NBP3/Parser.hs | mit | 2,344 | 0 | 22 | 555 | 661 | 342 | 319 | 56 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Graphics.UI.FLTK.LowLevel.FL as FL
import Graphics.UI.FLTK.LowLevel.FLTKHS
main :: IO ()
main = do
w1 <- doubleWindowNew (Size (Width 220) (Height 220)) Nothing (Just "clock")
begin w1
c1 <- clockNew (toRectangle (0,0,220,220)) Nothing
setResizable w1 (Just c1)
end w1
w2 <- doubleWindowNew (Size (Width 220) (Height 220)) Nothing (Just "Rounded Clock")
begin w2
c2 <- clockNew (toRectangle (0,0,220,220)) Nothing
setType c2 RoundClock
setResizable w2 (Just c2)
end w2
setXclass w1 "Fl_Clock"
setXclass w2 "Fl_Clock"
showWidget w1
showWidget w2
_ <- FL.run
return ()
| deech/fltkhs-demos | src/Examples/clock.hs | mit | 672 | 0 | 12 | 125 | 284 | 137 | 147 | 23 | 1 |
module StringCalculator.Split (split) where
import Text.Regex.Posix
import StringCalculator.Input
import StringCalculator.Models.DelimitedInput
split input = _split numbers delimiter []
where (DelimitedInput delimiter numbers) = refine input
_split "" _ acc = acc
_split input delimiter acc = _split tail delimiter $ acc ++ [head]
where (head, tail) = input // delimiter
takeUntil input delimiter = (head, tail)
where (head, _, tail) = input =~ delimiter :: (String, String, String)
(//) = takeUntil -- alias for takeUntil
| jtrim/string-calculator-hs | src/StringCalculator/Split.hs | mit | 554 | 0 | 8 | 105 | 179 | 100 | 79 | -1 | -1 |
import Data.ObjectName (genObjectNames)
import Graphics.Rendering.OpenGL.GL.Texturing.Objects (textureBinding)
import Graphics.Rendering.OpenGL.GL.Texturing.Specification (TextureTarget(..))
-- ...
-- Generate 1 texture object
[texObject] <- genObjectNames 1
-- Make it the "currently bound 2D texture"
textureBinding Texture2D $= Just texObject
import Data.Vector.Storable (unsafeWith)
import Graphics.Rendering.OpenGL.GL.Texturing.Specification (texImage2D, Level, Border, TextureSize2D(..))
import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable (Proxy(..), PixelInternalFormat(..))
import Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization (PixelData(..))
-- ...
loadImage :: IO ()
loadImage = do image <- readPng "data/Picture.png"
case image of
(Left s) -> do print s
exitWith (ExitFailure 1)
(Right d) -> do case (ImageRGBA8 (Image width height dat)) ->
-- Access the data vector pointer
unsafeWith dat $ \ ptr
-- Generate the texture
texImage2D
-- No cube map
Nothing
-- No proxy
NoProxy
-- No mipmaps
0
-- Internal storage format: use R8G8B8A8 as internal storage
RGBA8
-- Size of the image
(TextureSize2D width height)
-- No borders
0
-- The pixel data: the vector contains Bytes, in RGBA order
(PixelData RGBA UnsignedByte ptr)
| spetz911/progames | _src/lab4.hs | mit | 1,442 | 3 | 9 | 338 | 296 | 177 | 119 | -1 | -1 |
module Config where
width = 640 :: Int
height = 480 :: Int | mdietz94/haskellgame | src/Config.hs | mit | 59 | 0 | 4 | 13 | 20 | 13 | 7 | 3 | 1 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, TypeFamilies, ViewPatterns, MultiParamTypeClasses, FlexibleInstances #-}
module Main where
{-
A demonstration of streaming response body.
Note: Most browsers will NOT display the streaming contents as is.
Try CURL to see the effect of streaming. "curl localhost:8080"
-}
import Wai.Routes
import Network.Wai.Handler.Warp
import Network.Wai.Application.Static
import Control.Monad (forM_)
import Control.Monad.IO.Class (liftIO)
import Control.Concurrent (threadDelay)
import Data.ByteString.Builder (intDec)
-- The Master Site argument
data MyRoute = MyRoute
-- Generate routing code
mkRoute "MyRoute" [parseRoutes|
/ HomeR GET
|]
-- Handlers
-- Homepage
getHomeR :: Handler MyRoute
getHomeR = runHandlerM $ stream $ \write flush -> do
write "Starting Countdown\n"
flush
forM_ (reverse [1..10]) $ \n -> do
liftIO $ threadDelay 1000000
write $ intDec n
write "\n"
flush
write "Done!\n"
-- The application that uses our route
-- NOTE: We use the Route Monad to simplify routing
application :: RouteM ()
application = do
middleware logStdoutDev
route MyRoute
catchall $ staticApp $ defaultFileServerSettings "static"
-- Run the application
main :: IO ()
main = do
putStrLn "Starting server on port 8080"
run 8080 $ waiApp application
| ajnsit/wai-routes | examples/streaming-response/src/Main.hs | mit | 1,363 | 0 | 14 | 249 | 267 | 140 | 127 | 30 | 1 |
module Sandbox.DataStructures.Tree (Tree(Node, EmptyTree),
treeHeight) where
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
treeHeight :: (Tree a) -> Int
treeHeight EmptyTree = 0
treeHeight (Node a left right) = 1 + max (treeHeight left) (treeHeight right) | olkinn/my-haskell-sandbox | src/Sandbox/DataStructures/Tree.hs | mit | 327 | 0 | 8 | 85 | 127 | 70 | 57 | 8 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
module PostgREST.Middleware where
import Crypto.JWT
import Data.Aeson (Value (..))
import qualified Data.HashMap.Strict as M
import qualified Hasql.Transaction as H
import Network.HTTP.Types.Status (unauthorized401, status500)
import Network.Wai (Application, Response)
import Network.Wai.Middleware.Cors (cors)
import Network.Wai.Middleware.Gzip (def, gzip)
import Network.Wai.Middleware.Static (only, staticPolicy)
import PostgREST.ApiRequest (ApiRequest(..))
import PostgREST.Auth (JWTAttempt(..))
import PostgREST.Config (AppConfig (..), corsPolicy)
import PostgREST.Error (simpleError)
import PostgREST.QueryBuilder (pgFmtLit, unquoted, pgFmtEnvVar)
import Protolude hiding (concat, null)
runWithClaims :: AppConfig -> JWTAttempt ->
(ApiRequest -> H.Transaction Response) ->
ApiRequest -> H.Transaction Response
runWithClaims conf eClaims app req =
case eClaims of
JWTInvalid JWTExpired -> return $ unauthed "JWT expired"
JWTInvalid e -> return $ unauthed $ show e
JWTMissingSecret -> return $ simpleError status500 [] "Server lacks JWT secret"
JWTClaims claims -> do
H.sql $ toS.mconcat $ setRoleSql ++ claimsSql ++ headersSql ++ cookiesSql
mapM_ H.sql customReqCheck
app req
where
headersSql = map (pgFmtEnvVar "request.header.") $ iHeaders req
cookiesSql = map (pgFmtEnvVar "request.cookie.") $ iCookies req
claimsSql = map (pgFmtEnvVar "request.jwt.claim.") [(c,unquoted v) | (c,v) <- M.toList claimsWithRole]
setRoleSql = maybeToList $
(\r -> "set local role " <> r <> ";") . toS . pgFmtLit . unquoted <$> M.lookup "role" claimsWithRole
-- role claim defaults to anon if not specified in jwt
claimsWithRole = M.union claims (M.singleton "role" anon)
anon = String . toS $ configAnonRole conf
customReqCheck = (\f -> "select " <> toS f <> "();") <$> configReqCheck conf
where
unauthed message = simpleError
unauthorized401
[( "WWW-Authenticate"
, "Bearer error=\"invalid_token\", " <>
"error_description=" <> show message
)]
message
defaultMiddle :: Application -> Application
defaultMiddle =
gzip def
. cors corsPolicy
. staticPolicy (only [("favicon.ico", "static/favicon.ico")])
| ruslantalpa/postgrest | src/PostgREST/Middleware.hs | mit | 2,688 | 0 | 18 | 763 | 653 | 357 | 296 | 50 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import Lib
import System.Console.CmdArgs
data MakeDictArgs = MakeDictArgs {
url :: String
} deriving (Show, Data, Typeable)
makedictargs = MakeDictArgs
{
url = "https://downloads.haskell.org/~ghc/latest/docs/html/libraries/" &= args &= typ "String"
}
main :: IO ()
main = do
opts <- cmdArgs makedictargs
n <- parseURL (url opts)
let (Just n') = n
putStrLn $ unlines $ map (\x -> let (LibName y) = x in y) n'
| yasukun/make-ac-dict-ghc | app/Main.hs | mit | 513 | 0 | 16 | 124 | 167 | 86 | 81 | 15 | 1 |
module Helpers.TestWebServer
( module Helpers.RequestSpecHelpers
, app
, testAppConfig
, with
, withWebServer
) where
import App (AppT, AppConfig (..), getAppConfig, runAppT)
import Config.Environment (Environment (Test))
import Helpers.RequestSpecHelpers
import LoadEnv
import Network.Wai (Application)
import Routing (API, server, api)
import Servant
import Test.Hspec.Wai (with)
withWebServer :: SpecWith Application -> Spec
withWebServer = with (testAppConfig >>= app)
testAppConfig :: IO AppConfig
testAppConfig =
loadEnvFrom "./env/test.env" >> getAppConfig "dummy" Test
app :: AppConfig -> IO Application
app cfg = do
return $ serve api (readerServer cfg)
readerServer :: AppConfig -> Server API
readerServer cfg = enter (readerToEither cfg) server
readerToEither :: AppConfig -> AppT :~> Handler
readerToEither cfg = Nat $ \appT -> runAppT cfg appT
| gust/feature-creature | auth-service/test/Helpers/TestWebServer.hs | mit | 879 | 0 | 10 | 135 | 263 | 146 | 117 | -1 | -1 |
-- | Allow reading, merging and writing Erlang terms.
module B9.Artifact.Content.ErlangPropList
( ErlangPropList (..),
textToErlangAst,
stringToErlangAst,
)
where
import B9.Artifact.Content
import B9.Artifact.Content.AST
import B9.Artifact.Content.ErlTerms
import B9.Artifact.Content.StringTemplate
import B9.Text
import Control.Parallel.Strategies
import Data.Data
import Data.Function
import Data.Hashable
import Data.List (partition, sortBy)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Test.QuickCheck
import Text.Printf
-- | A wrapper type around erlang terms with a Semigroup instance useful for
-- combining sys.config files with OTP-application configurations in a list of
-- the form of a proplist.
newtype ErlangPropList
= ErlangPropList SimpleErlangTerm
deriving (Read, Eq, Show, Data, Typeable, Generic)
instance Hashable ErlangPropList
instance NFData ErlangPropList
instance Arbitrary ErlangPropList where
arbitrary = ErlangPropList <$> arbitrary
instance Semigroup ErlangPropList where
(ErlangPropList v1) <> (ErlangPropList v2) = ErlangPropList (combine v1 v2)
where
combine (ErlList l1) (ErlList l2) = ErlList (l1Only <> merged <> l2Only)
where
l1Only = l1NonPairs <> l1NotL2
l2Only = l2NonPairs <> l2NotL1
(l1Pairs, l1NonPairs) = partition isPair l1
(l2Pairs, l2NonPairs) = partition isPair l2
merged = zipWith merge il1 il2
where
merge (ErlTuple [_k, pv1]) (ErlTuple [k, pv2]) = ErlTuple [k, pv1 `combine` pv2]
merge _ _ = error "unreachable"
(l1NotL2, il1, il2, l2NotL1) = partitionByKey l1Sorted l2Sorted ([], [], [], [])
where
partitionByKey [] ys (exs, cxs, cys, eys) = (reverse exs, reverse cxs, reverse cys, reverse eys <> ys)
partitionByKey xs [] (exs, cxs, cys, eys) = (reverse exs <> xs, reverse cxs, reverse cys, reverse eys)
partitionByKey (x : xs) (y : ys) (exs, cxs, cys, eys)
| equalKey x y = partitionByKey xs ys (exs, x : cxs, y : cys, eys)
| x `keyLessThan` y = partitionByKey xs (y : ys) (x : exs, cxs, cys, eys)
| otherwise = partitionByKey (x : xs) ys (exs, cxs, cys, y : eys)
l1Sorted = sortByKey l1Pairs
l2Sorted = sortByKey l2Pairs
sortByKey = sortBy (compare `on` getKey)
keyLessThan = (<) `on` getKey
equalKey = (==) `on` getKey
getKey (ErlTuple (x : _)) = x
getKey x = x
isPair (ErlTuple [_, _]) = True
isPair _ = False
combine (ErlList pl1) t2 = ErlList (pl1 <> [t2])
combine t1 (ErlList pl2) = ErlList ([t1] <> pl2)
combine t1 t2 = ErlList [t1, t2]
instance Textual ErlangPropList where
parseFromText txt = do
str <- parseFromText txt
t <- parseErlTerm "" str
return (ErlangPropList t)
renderToText (ErlangPropList t) = renderToText (renderErlTerm t)
instance FromAST ErlangPropList where
fromAST (AST a) = pure a
fromAST (ASTObj pairs) = ErlangPropList . ErlList <$> mapM makePair pairs
where
makePair (k, ast) = do
(ErlangPropList second) <- fromAST ast
return $ ErlTuple [ErlAtom k, second]
fromAST (ASTArr xs) =
ErlangPropList . ErlList
<$> mapM
( \x -> do
(ErlangPropList x') <- fromAST x
return x'
)
xs
fromAST (ASTString s) = pure $ ErlangPropList $ ErlString s
fromAST (ASTInt i) = pure $ ErlangPropList $ ErlString (show i)
fromAST (ASTEmbed c) = ErlangPropList . ErlString . T.unpack <$> toContentGenerator c
fromAST (ASTMerge []) = error "ASTMerge MUST NOT be used with an empty list!"
fromAST (ASTMerge asts) = foldl1 (<>) <$> mapM fromAST asts
fromAST (ASTParse src@(Source _ srcPath)) = do
c <- readTemplateFile src
case parseFromTextWithErrorMessage srcPath c of
Right s -> return s
Left e -> error (printf "could not parse erlang source file: '%s'\n%s\n" srcPath e)
-- * Misc. utilities
-- | Parse a text containing an @Erlang@ expression ending with a @.@ and Return
-- an 'AST'.
--
-- @since 0.5.67
textToErlangAst :: Text -> AST c ErlangPropList
textToErlangAst txt =
either
(error . ((unsafeParseFromText txt ++ "\n: ") ++))
AST
(parseFromTextWithErrorMessage "textToErlangAst" txt)
-- | Parse a string containing an @Erlang@ expression ending with a @.@ and Return
-- an 'AST'.
--
-- @since 0.5.67
stringToErlangAst :: String -> AST c ErlangPropList
stringToErlangAst = textToErlangAst . unsafeRenderToText
| sheyll/b9-vm-image-builder | src/lib/B9/Artifact/Content/ErlangPropList.hs | mit | 4,619 | 9 | 24 | 1,144 | 1,446 | 766 | 680 | 91 | 1 |
{-# LANGUAGE NoMonomorphismRestriction, RelaxedPolyRec #-}
module Atomo.Parser where
import Atomo.Error
import Atomo.Internals
import Atomo.Primitive
import Control.Monad
import Control.Monad.Error
import Control.Monad.Identity
import Data.List (intercalate, nub, sort, sortBy, groupBy)
import Data.Char (isAlpha, toLower, toUpper, isUpper, isLower, digitToInt)
import Debug.Trace
import Text.Parsec hiding (sepBy, sepBy1)
import Text.Parsec.Expr
import qualified Text.Parsec.Token as P
type Parser = Parsec String [[(String, Assoc)]]
sepBy p sep = sepBy1 p sep <|> return []
sepBy1 p sep = do x <- p
xs <- many (try (whiteSpace >> sep >> whiteSpace >> p))
return (x:xs)
instance Show Assoc where
show AssocNone = "AssocNone"
show AssocLeft = "AssocLeft"
show AssocRight = "AssocRight"
instance Show (Operator s u m a) where
show (Infix _ a) = "Infix (...) " ++ show a
show (Prefix _) = "Prefix (...)"
show (Postfix _) = "Postfix (...)"
-- Custom makeTokenParser with tweaked whiteSpace rules
makeTokenParser languageDef
= P.TokenParser{ P.identifier = identifier
, P.reserved = reserved
, P.operator = operator
, P.reservedOp = reservedOp
, P.charLiteral = charLiteral
, P.stringLiteral = stringLiteral
, P.natural = natural
, P.integer = integer
, P.float = float
, P.naturalOrFloat = naturalOrFloat
, P.decimal = decimal
, P.hexadecimal = hexadecimal
, P.octal = octal
, P.symbol = symbol
, P.lexeme = lexeme
, P.whiteSpace = whiteSpace
, P.parens = parens
, P.braces = braces
, P.angles = angles
, P.brackets = brackets
, P.squares = brackets
, P.semi = semi
, P.comma = comma
, P.colon = colon
, P.dot = dot
, P.semiSep = semiSep
, P.semiSep1 = semiSep1
, P.commaSep = commaSep
, P.commaSep1 = commaSep1
}
where
-----------------------------------------------------------
-- Bracketing
-----------------------------------------------------------
parens p = between (symbol "(") (symbol ")") p
braces p = between (symbol "{") (symbol "}") p
angles p = between (symbol "<") (symbol ">") p
brackets p = between (symbol "[") (symbol "]") p
semi = symbol ";"
comma = symbol ","
dot = symbol "."
colon = symbol ":"
commaSep p = sepBy p comma
semiSep p = sepBy p semi
commaSep1 p = sepBy1 p comma
semiSep1 p = sepBy1 p semi
-----------------------------------------------------------
-- Chars & Strings
-----------------------------------------------------------
charLiteral = lexeme (between (char '\'')
(char '\'' <?> "end of character")
characterChar )
<?> "character"
characterChar = charLetter <|> charEscape
<?> "literal character"
charEscape = do{ char '\\'; escapeCode }
charLetter = satisfy (\c -> (c /= '\'') && (c /= '\\') && (c > '\026'))
stringLiteral = lexeme (
do{ str <- between (char '"')
(char '"' <?> "end of string")
(many stringChar)
; return (foldr (maybe id (:)) "" str)
}
<?> "literal string")
stringChar = do{ c <- stringLetter; return (Just c) }
<|> stringEscape
<?> "string character"
stringLetter = satisfy (\c -> (c /= '"') && (c /= '\\') && (c > '\026'))
stringEscape = do{ char '\\'
; do{ escapeGap ; return Nothing }
<|> do{ escapeEmpty; return Nothing }
<|> do{ esc <- escapeCode; return (Just esc) }
}
escapeEmpty = char '&'
escapeGap = do{ many1 space
; char '\\' <?> "end of string gap"
}
-- escape codes
escapeCode = charEsc <|> charNum <|> charAscii <|> charControl
<?> "escape code"
charControl = do{ char '^'
; code <- upper
; return (toEnum (fromEnum code - fromEnum 'A'))
}
charNum = do{ code <- decimal
<|> do{ char 'o'; number 8 octDigit }
<|> do{ char 'x'; number 16 hexDigit }
; return (toEnum (fromInteger code))
}
charEsc = choice (map parseEsc escMap)
where
parseEsc (c,code) = do{ char c; return code }
charAscii = choice (map parseAscii asciiMap)
where
parseAscii (asc,code) = try (do{ string asc; return code })
-- escape code tables
escMap = zip ("abfnrtv\\\"\'") ("\a\b\f\n\r\t\v\\\"\'")
asciiMap = zip (ascii3codes ++ ascii2codes) (ascii3 ++ ascii2)
ascii2codes = ["BS","HT","LF","VT","FF","CR","SO","SI","EM",
"FS","GS","RS","US","SP"]
ascii3codes = ["NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL",
"DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB",
"CAN","SUB","ESC","DEL"]
ascii2 = ['\BS','\HT','\LF','\VT','\FF','\CR','\SO','\SI',
'\EM','\FS','\GS','\RS','\US','\SP']
ascii3 = ['\NUL','\SOH','\STX','\ETX','\EOT','\ENQ','\ACK',
'\BEL','\DLE','\DC1','\DC2','\DC3','\DC4','\NAK',
'\SYN','\ETB','\CAN','\SUB','\ESC','\DEL']
-----------------------------------------------------------
-- Numbers
-----------------------------------------------------------
naturalOrFloat = lexeme (natFloat) <?> "number"
float = lexeme floating <?> "float"
integer = lexeme int <?> "integer"
natural = lexeme nat <?> "natural"
-- floats
floating = do{ n <- decimal
; fractExponent n
}
natFloat = do{ char '0'
; zeroNumFloat
}
<|> decimalFloat
zeroNumFloat = do{ n <- hexadecimal <|> octal
; return (Left n)
}
<|> decimalFloat
<|> fractFloat 0
<|> return (Left 0)
decimalFloat = do{ n <- decimal
; option (Left n)
(fractFloat n)
}
fractFloat n = do{ f <- fractExponent n
; return (Right f)
}
fractExponent n = do{ fract <- fraction
; expo <- option 1.0 exponent'
; return ((fromInteger n + fract)*expo)
}
<|>
do{ expo <- exponent'
; return ((fromInteger n)*expo)
}
fraction = do{ char '.'
; digits <- many1 digit <?> "fraction"
; return (foldr op 0.0 digits)
}
<?> "fraction"
where
op d f = (f + fromIntegral (digitToInt d))/10.0
exponent' = do{ oneOf "eE"
; f <- sign
; e <- decimal <?> "exponent"
; return (power (f e))
}
<?> "exponent"
where
power e | e < 0 = 1.0/power(-e)
| otherwise = fromInteger (10^e)
-- integers and naturals
int = do{ f <- sign
; n <- nat
; return (f n)
}
sign = (char '-' >> return negate)
<|> (char '+' >> return id)
<|> return id
nat = zeroNumber <|> decimal
zeroNumber = do{ char '0'
; hexadecimal <|> octal <|> decimal <|> return 0
}
<?> ""
decimal = number 10 digit
hexadecimal = do{ oneOf "xX"; number 16 hexDigit }
octal = do{ oneOf "oO"; number 8 octDigit }
number base baseDigit
= do{ digits <- many1 baseDigit
; let n = foldl (\x d -> base*x + toInteger (digitToInt d)) 0 digits
; seq n (return n)
}
-----------------------------------------------------------
-- Operators & reserved ops
-----------------------------------------------------------
reservedOp name =
lexeme $ try $
do{ string name
; notFollowedBy (P.opLetter languageDef) <?> ("end of " ++ show name)
}
operator =
lexeme $ try $
do{ name <- oper
; if (isReservedOp name)
then unexpected ("reserved operator " ++ show name)
else return name
}
oper =
do{ c <- (P.opStart languageDef)
; cs <- many (P.opLetter languageDef)
; return (c:cs)
}
<?> "operator"
isReservedOp name =
isReserved (sort (P.reservedOpNames languageDef)) name
-----------------------------------------------------------
-- Identifiers & Reserved words
-----------------------------------------------------------
reserved name =
lexeme $ try $
do{ caseString name
; notFollowedBy (P.identLetter languageDef) <?> ("end of " ++ show name)
}
caseString name
| P.caseSensitive languageDef = string name
| otherwise = do{ walk name; return name }
where
walk [] = return ()
walk (c:cs) = do{ caseChar c <?> msg; walk cs }
caseChar c | isAlpha c = char (toLower c) <|> char (toUpper c)
| otherwise = char c
msg = show name
identifier =
lexeme $ try $
do{ name <- ident
; if (isReservedName name)
then unexpected ("reserved word " ++ show name)
else return name
}
ident
= do{ c <- P.identStart languageDef
; cs <- many (P.identLetter languageDef)
; return (c:cs)
}
<?> "identifier"
isReservedName name
= isReserved theReservedNames caseName
where
caseName | P.caseSensitive languageDef = name
| otherwise = map toLower name
isReserved names name
= scan names
where
scan [] = False
scan (r:rs) = case (compare r name) of
LT -> scan rs
EQ -> True
GT -> False
theReservedNames
| P.caseSensitive languageDef = sortedNames
| otherwise = map (map toLower) sortedNames
where
sortedNames = sort (P.reservedNames languageDef)
-----------------------------------------------------------
-- White space & symbols
-----------------------------------------------------------
symbol name
= lexeme (string name)
lexeme p
= do{ x <- p; spacing; return x }
--whiteSpace
whiteSpace = do spacing
skipMany (try $ spacing >> newline)
spacing
-- Atomo parser
atomo :: P.TokenParser st
atomo = makeTokenParser atomoDef
-- Atomo language definition
atomoDef :: P.LanguageDef st
atomoDef = P.LanguageDef { P.commentStart = "{-"
, P.commentEnd = "-}"
, P.commentLine = "--"
, P.nestedComments = True
, P.identStart = letter
, P.identLetter = alphaNum <|> satisfy ((> 0x80) . fromEnum) <|> oneOf "'?"
, P.opStart = letter <|> P.opLetter atomoDef
, P.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~"
, P.reservedOpNames = ["=", "=>", "->", "::", ":=", ":"]
, P.reservedNames = ["if", "else", "elseif", "while",
"do", "class", "data", "type",
"where", "module", "infix",
"infixl", "infixr", "import",
"return", "receive", "spawn"]
, P.caseSensitive = True
}
whiteSpace = P.whiteSpace atomo
simpleSpace = skipMany1 $ satisfy (`elem` " \t\f\v\xa0")
spacing = skipMany spacing1
spacing1 | noLine && noMulti = simpleSpace <?> ""
| noLine = simpleSpace <|> multiLineComment <?> ""
| noMulti = simpleSpace <|> oneLineComment <?> ""
| otherwise = simpleSpace <|> oneLineComment <|> multiLineComment <?> ""
where
noLine = null (P.commentLine atomoDef)
noMulti = null (P.commentStart atomoDef)
oneLineComment = try (string (P.commentLine atomoDef)) >> skipMany (satisfy (/= '\n'))
multiLineComment = try (string (P.commentStart atomoDef)) >> inComment
inComment | P.nestedComments atomoDef = inCommentMulti
| otherwise = inCommentSingle
inCommentMulti = (try (string (P.commentEnd atomoDef)) >> return ())
<|> (multiLineComment >> inCommentMulti)
<|> (skipMany1 (noneOf startEnd) >> inCommentMulti)
<|> (oneOf startEnd >> inCommentMulti)
<?> "end of comment"
where
startEnd = nub (P.commentEnd atomoDef ++ P.commentStart atomoDef)
inCommentSingle = (try (string (P.commentEnd atomoDef)) >> return ())
<|> (skipMany1 (noneOf startEnd) >> inCommentSingle)
<|> (oneOf startEnd >> inCommentSingle)
<?> "end of comment"
where
startEnd = nub (P.commentEnd atomoDef ++ P.commentStart atomoDef)
lexeme = P.lexeme atomo
capIdent = do c <- satisfy isUpper
cs <- many (P.identLetter atomoDef)
return (c:cs)
lowIdent = do c <- satisfy isLower
cs <- many (P.identLetter atomoDef)
return (c:cs)
capIdentifier = lexeme capIdent
lowIdentifier = lexeme lowIdent
parens = P.parens atomo
brackets = P.brackets atomo
braces = P.braces atomo
comma = P.comma atomo
commaSep = P.commaSep atomo
commaSep1 = P.commaSep1 atomo
colon = char ':'
eol = newline >> return ()
dot = P.dot atomo
identifier = P.identifier atomo
ident = do c <- P.identStart atomoDef
cs <- many (P.identLetter atomoDef)
return (c:cs)
operator = P.operator atomo <|> between (char '`') (char '`') identifier
reserved = P.reserved atomo
reservedOp = P.reservedOp atomo
integer = P.integer atomo
float = P.float atomo
charLit = P.charLiteral atomo
natural = P.natural atomo
symbol = P.symbol atomo
stringLiteral = P.stringLiteral atomo
charLiteral = P.charLiteral atomo
-- Returns the current column
getIndent :: Parser Int
getIndent = do pos <- getPosition
return $ sourceColumn pos
-- All possible expressions in the Atomo language.
-- Expressions that begin with a reserved word (e.g.)
-- `data' or `type' or `return') go first.
aExpr :: Parser AtomoVal
aExpr = aLambda
<|> aData
<|> aNewType
<|> aReturn
<|> aIf
<|> aClass
<|> aImport
<|> aAtom
<|> aReceive
<|> aFixity
<|> try aBind
<|> try aAnnot
<|> try aSpawn
<|> try aDefine
<|> try aInfix
<|> try aCall
<|> try aAttribute
<|> try aDouble
<|> aList
<|> aHash
<|> aTuple
<|> aNumber
<|> aString
<|> aChar
<|> aVariable
aSimpleExpr :: Parser AtomoVal
aSimpleExpr = aAtom
<|> try aBind
<|> try aInfix
<|> try aCall
<|> try aAttribute
<|> try aDouble
<|> aList
<|> aHash
<|> aTuple
<|> aNumber
<|> aString
<|> aChar
<|> aVariable
aMainExpr :: Parser AtomoVal
aMainExpr = aImport
<|> aData
<|> aNewType
<|> aClass
<|> aTypeclass
<|> aInstance
<|> aFixity
<|> try aDefine
<|> try aBind
<|> try aAnnot
aScriptExpr :: Parser (SourcePos, AtomoVal)
aScriptExpr = do pos <- getPosition
expr <- aMainExpr
return (pos, expr)
-- Reference (variable lookup)
aReference :: Parser String
aReference = identifier <|> try (parens operator)
-- Variable reference
aVariable :: Parser AtomoVal
aVariable = aReference >>= return . AVariable
<?> "variable reference"
aModule :: Parser String
aModule = do path <- capIdentifier `sepBy1` char '.'
return (intercalate "." path)
-- Import
aImport :: Parser AtomoVal
aImport = do reserved "import"
from <- option "" (symbol "from" >> aModule)
colon
whiteSpace
targets <- case from of
"" -> commaSep1 aModule
_ -> commaSep1 (aReference <|> symbol "*")
return $ AImport from targets
<?> "import"
-- Atom (@foo)
aAtom :: Parser AtomoVal
aAtom = do char '@'
name <- lowIdentifier
return $ AAtom name
<?> "atom"
-- Receive
aReceive :: Parser AtomoVal
aReceive = do reserved "receive"
matches <- aBlockOf (do atom <- aPattern
code <- aBlock
return $ APattern atom code)
return $ AReceive matches
<?> "receive"
-- Fixity declaration
aFixity :: Parser AtomoVal
aFixity = do decl <- try (symbol "infixl") <|> try (symbol "infixr") <|> symbol "infix"
level <- natural
colon
spacing
ops <- commaSep1 operator
modifyState (insLevel level (map (\o -> (o, assoc decl)) ops))
return ANone
where
assoc "infix" = AssocNone
assoc "infixl" = AssocLeft
assoc "infixr" = AssocRight
insLevel n os t = insLevel' n os t
insLevel' 9 os (t:ts) = (os ++ t) : ts
insLevel' n os (t:ts) = t : insLevel' (n + 1) os ts
call op a b = callify [a, b] (AVariable op)
-- Class
aClass :: Parser AtomoVal
aClass = do reserved "class"
name <- aSimpleType
code <- aBlockOf (try aStaticAnnot <|> try aAnnot <|> try aStatic <|> try aMethod)
return $ ADefine (Class name) $ AClass name (static code) (public code)
<?> "class"
-- Static definition
aStatic :: Parser AtomoVal
aStatic = do string "self"
dot
name <- lowIdentifier <|> parens operator
args <- many aPattern
code <- aBlock
return $ AStatic name $ lambdify args code
<?> "static definition"
-- Method definition
aMethod :: Parser AtomoVal
aMethod = do col <- getIndent
name <- lowIdentifier <|> parens operator
args <- many aPattern
code <- aBlockOf (try aDefAttr <|> aExpr)
others <- many (try (do newline
replicateM (col - 1) anyToken
symbol name
args <- many aPattern
code <- aBlockOf (try aDefAttr <|> aExpr)
return $ lambdify args code))
return $ ADefine (Define name) (AFunction $ (lambdify args code : others))
<?> "definition"
-- Data field definition
aDefAttr :: Parser AtomoVal
aDefAttr = do object <- aVariable
dot
name <- lowIdentifier <|> parens operator
reservedOp ":="
val <- aExpr
return $ ADefAttr object name $ val
<?> "data definition"
-- Attribute
aAttribute :: Parser AtomoVal
aAttribute = do attr <- aAttribute'
return $ ACall attr ANone
where
aAttribute' = do target <- target
dot
attr <- try aAttribute' <|> aVariable
return $ attribute target attr
target = try (parens aExpr)
<|> try aVariable
<|> aNumber
<|> aChar
<|> aString
<|> aList
<|> aHash
<|> aTuple
-- Typeclass
aTypeclass :: Parser AtomoVal
aTypeclass = do reserved "typeclass"
name <- capIdentifier
var <- lowIdentifier
code <- aBlockOf (aFixity <|> try aAnnot <|> try aDefine)
return $ ATypeclass name (Poly var) code
-- Typeclass instance
aInstance :: Parser AtomoVal
aInstance = do reserved "instance"
name <- capIdentifier
inst <- capIdentifier <|> (brackets spacing >> return "[]")
code <- aBlockOf (try aAnnot <|> try aDefine)
return $ AInstance name inst code
-- Type, excluding functions
aSimpleType :: Parser Type
aSimpleType = try (do con <- (capIdentifier >>= return . Name)
<|> (lowIdentifier >>= return . Poly)
args <- aSubType `sepBy1` spacing1
return $ Type con args)
<|> aSubType
<?> "type"
aSubType = try (do con <- (capIdentifier >>= return . Name)
args <- aSubType `sepBy1` spacing1
return $ Type con args)
<|> try (do theType <- brackets aType
return $ Type (Name "[]") [theType])
<|> try (parens aSimpleType)
<|> try (parens aType)
<|> try (do theTypes <- parens (commaSep aType)
return $ Type (Name "()") theTypes)
<|> (capIdentifier >>= return . Name)
<|> (lowIdentifier >>= return . Poly)
<?> "type"
-- Type
aType :: Parser Type
aType = do types <- (aSimpleType <|> parens aType) `sepBy1` (symbol "->")
return $ toFunc types
<?> "type declaration"
-- Static type header (self.foo)
aStaticAnnot :: Parser AtomoVal
aStaticAnnot = do string "self"
dot
aAnnot
-- Type header
aAnnot :: Parser AtomoVal
aAnnot = do name <- identifier <|> parens operator
symbol "::"
types <- aType
return $ AAnnot name types
<?> "type annotation"
-- Type composition
aNewType :: Parser AtomoVal
aNewType = do reserved "type"
name <- identifier
colon
whiteSpace
theType <- aType
return $ AType name theType
<?> "type"
-- Lambda
aLambda :: Parser AtomoVal
aLambda = do reserved "do"
params <- many aPattern
code <- aBlock
return $ lambdify params code
<?> "lambda"
-- Pattern matching
aPattern :: Parser PatternMatch
aPattern = (symbol "_" >> return PAny)
<|> try (do name <- lowIdentifier
char '@'
pattern <- aPattern
return $ PNamed name pattern)
<|> (lowIdentifier >>= return . PName)
<|> (do c <- capIdentifier
return $ PCons c [])
<|> try (parens (do c <- capIdentifier
as <- many aPattern
return $ PCons c as))
<|> try (do tup <- parens (commaSep aPattern)
return $ PTuple tup)
<|> try (do list <- brackets (commaSep aPattern)
return $ PList list)
<|> try (parens (do h <- aPattern
symbol "|"
t <- aPattern
return $ PHeadTail h t))
<|> (do val <- aChar
<|> aString
<|> aNumber
<|> aDouble
<|> aAtom
return $ PMatch val)
<?> "pattern match"
-- Return statement
aReturn :: Parser AtomoVal
aReturn = do reserved "return"
expr <- option ANone (aExpr <|> parens aExpr)
return $ AReturn expr
<?> "return"
-- Block
aBlock :: Parser AtomoVal
aBlock = aBlockOf aExpr
aBlockOf :: Parser AtomoVal -> Parser AtomoVal
aBlockOf p = do colon
exprs <- (do newline
whiteSpace
i <- getIndent
aBlock' i i [])
<|> (spacing >> aExpr >>= return . (: []))
return $ ABlock exprs
<?> "block"
where
aBlock' :: Int -> Int -> [AtomoVal] -> Parser [AtomoVal]
aBlock' o i es = try (do x <- p
new <- lookAhead (whiteSpace >> getIndent)
if new == o
then do whiteSpace
next <- aBlock' o new es
return $ x : next
else return $ x : es) <|> return es
-- Data constructor
aConstructor :: Parser (AtomoVal -> AtomoVal)
aConstructor = do name <- capIdentifier
params <- many aSubType
return $ AConstruct name params
-- New data declaration
aData :: Parser AtomoVal
aData = do reserved "data"
name <- capIdentifier
params <- many aSimpleType
colon
whiteSpace
constructors <- aConstructor `sepBy` (symbol "|")
let d = AData name params
return $ ABlock (map (\c -> ADefine (Define $ fromAConstruct c) (cons c)) (map ($ d) constructors))
<?> "data"
where
cons c@(AConstruct n ts d) = lambdify (map PName as) (AValue n (map AVariable as) c)
where as = map (\c -> [c]) $ take (length ts) ['a'..]
-- If/If-Else
aIf :: Parser AtomoVal
aIf = do reserved "if"
cond <- aSimpleExpr
code <- aBlock
other <- try (whiteSpace >> reserved "else" >> aBlock) <|> (return $ ABlock [])
return $ AIf cond code other
<?> "if statement"
-- Variable assignment
aDefine :: Parser AtomoVal
aDefine = do (name, args) <- try (do n <- lowIdentifier <|> parens operator
a <- many aPattern
lookAhead colon
return (n, a))
<|> (do a <- aPattern
n <- operator
as <- many aPattern
return (n, a:as))
code <- aBlock
others <- many (try (do whiteSpace
reserved name <|> parens (reserved name)
args <- many1 aPattern
code <- aBlock
return $ lambdify args code)
<|> try (do whiteSpace
a <- aPattern
reserved name
as <- many1 aPattern
code <- aBlock
return $ lambdify (a:as) code))
return $ ADefine (Define name) (AFunction $ (lambdify args code : others))
<?> "function definition"
-- Variable definition
aBind :: Parser AtomoVal
aBind = do name <- lowIdentifier <|> parens operator
reservedOp ":="
val <- aExpr
return $ ADefine (Define name) val
<?> "variable definition"
-- Parse a list (mutable list of values of one type)
aList :: Parser AtomoVal
aList = do contents <- brackets $ commaSep aExpr
return $ AList contents
-- Parse a tuple (immutable list of values of any type)
-- A tuple must contain 2 or more values.
aTuple :: Parser AtomoVal
aTuple = do contents <- parens $ (do a <- aExpr
symbol ","
bs <- commaSep1 aExpr
return (a:bs))
return $ ATuple contents
-- Parse a hash (mutable, named contents of any type)
aHash :: Parser AtomoVal
aHash = do contents <- braces $ commaSep (do theType <- aType
name <- lowIdentifier
colon
whiteSpace
expr <- aExpr
return (name, (theType, expr)))
return $ AHash contents
-- Parse a number
aNumber :: Parser AtomoVal
aNumber = integer >>= return . intToPrim
<?> "integer"
-- Parse a floating-point number
aDouble :: Parser AtomoVal
aDouble = float >>= return . doubleToPrim
<?> "double"
-- Parse a string
aString :: Parser AtomoVal
aString = stringLiteral >>= return . toAString
<?> "string"
-- Parse a single character
aChar :: Parser AtomoVal
aChar = charLiteral >>= return . charToPrim
<?> "character"
-- Thread spawning
aSpawn :: Parser AtomoVal
aSpawn = do reserved "spawn"
call <- aCall
return $ ASpawn call
<?> "spawn"
-- Function call (prefix)
aCall :: Parser AtomoVal
aCall = do name <- try aAttribute <|> aVariable <|> try (parens aExpr)
pos <- getPosition
args <- many $ try arg
return $ callify args name
<?> "function call"
where
arg = try aAttribute
<|> try aDouble
<|> try (parens aIf)
<|> try (parens aInfix)
<|> try (parens aCall)
<|> try (parens aExpr)
<|> try aVariable
<|> aLambda
<|> aAtom
<|> aList
<|> aHash
<|> aTuple
<|> aString
<|> aChar
<|> aNumber
-- Call to predefined primitive function
aInfix :: Parser AtomoVal
aInfix = do st <- getState
val <- buildExpressionParser (table st) targets
return val
<?> "infix call"
where
table st = (any st : head table') : tail table'
where
table' = map (map (\(o, a) -> Infix (reservedOp o >> return (call o)) a)) st
any st = Infix (try (do op <- operator
if op `elem` map fst (concat st)
then fail "Reserved operator"
else return (call op) <?> "any operator")) AssocLeft
call op a b = callify [a, b] (AVariable op)
targets :: Parser AtomoVal
targets = try aCall
<|> try (parens aExpr)
<|> try aDouble
<|> aAtom
<|> aList
<|> aTuple
<|> aHash
<|> aNumber
<|> aString
<|> aChar
<|> try aAttribute
<|> aVariable
-- Parse a string or throw any errors
readOrThrow :: Parser a -> String -> ThrowsError a
readOrThrow p s = case runP (do whiteSpace
x <- p
eof
return x) (replicate 10 []) "" s of
Left err -> throwError $ Parser err
Right val -> return val
-- Read a single expression
readExpr :: String -> ThrowsError AtomoVal
readExpr = readOrThrow aExpr
-- Read all expressions in a string
readExprs :: String -> ThrowsError [AtomoVal]
readExprs es = readOrThrow (many $ do x <- aExpr
spacing
eol <|> eof
whiteSpace
return x) es
readScript :: String -> ThrowsError [(SourcePos, AtomoVal)]
readScript es = readOrThrow (many $ do x <- aScriptExpr
spacing
eol <|> eof
whiteSpace
return x) es
| vito/atomo-old | Atomo/Parser.hs | mit | 33,906 | 0 | 28 | 14,614 | 8,809 | 4,374 | 4,435 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module IHaskell.Display.Widgets.Int.IntText
( -- * The IntText Widget
IntText
-- * Constructor
, mkIntText
) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (void)
import Data.Aeson
import Data.IORef (newIORef)
import qualified Data.Scientific as Sci
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
import IHaskell.Display.Widgets.Layout.LayoutWidget
import IHaskell.Display.Widgets.Style.DescriptionStyle
-- | 'IntText' represents an IntText widget from IPython.html.widgets.
type IntText = IPythonWidget 'IntTextType
-- | Create a new widget
mkIntText :: IO IntText
mkIntText = do
-- Default properties, with a random uuid
wid <- U.random
layout <- mkLayout
dstyle <- mkDescriptionStyle
let intAttrs = defaultIntWidget "IntTextView" "IntTextModel" layout $ StyleWidget dstyle
textAttrs = (Disabled =:: False)
:& (ContinuousUpdate =:: False)
:& (StepInt =:: Just 1)
:& RNil
widgetState = WidgetState $ intAttrs <+> textAttrs
stateIO <- newIORef widgetState
let widget = IPythonWidget wid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellWidget IntText where
getCommUUID = uuid
comm widget val _ =
case nestedObjectLookup val ["state", "value"] of
Just (Number value) -> do
void $ setField' widget IntValue (Sci.coefficient value)
triggerChange widget
_ -> pure ()
| gibiansky/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Int/IntText.hs | mit | 2,048 | 0 | 15 | 502 | 396 | 221 | 175 | 46 | 1 |
module Util.StringBuffer(StringBuffer, newSB, appendSB, readSB) where
import Data.IORef
import Control.Monad
data StringBuffer = StringBuffer (IORef [String])
newSB = liftM StringBuffer $ newIORef []
appendSB sb s = modifyIORef sb (s :)
readSB = readIORef >=> return . concat
| raimohanska/rump | src/Util/StringBuffer.hs | gpl-3.0 | 278 | 0 | 9 | 40 | 97 | 54 | 43 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Protocol where
import Prelude hiding (catch)
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import System.IO.Unsafe
import System.Random
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Digest.Pure.MD5
import Rabin
type Key = Integer
type Name = String
type Messages = Word32
type Payload = Integer
data Protocol = Hello Key Name | --0xFFFA
Dossier Messages | --0xFFFB
Message Payload | --0xFFFC Payload will always be 255 bytes
Done | --0xFFFD
Ack --0xFFFE
deriving Show
instance Binary Protocol where
get = do
flag <- getWord16le
case (flag) of
0xFFFA -> do
key <- get
name <- get
return $ Hello key name
0xFFFB -> do
msg <- getWord32le
return $ Dossier msg
0xFFFC -> do
msg <- get
return $ Message msg
0xFFFD -> do
return Done
0xFFFE -> do
return Ack
_ -> error "Unknown frame received."
put (Hello key name) = do
putWord16le (0xFFFA::Word16)
put key
put name
put (Dossier msgs) = do
putWord16le (0xFFFB::Word16)
putWord32le msgs
put (Message pyld) = do
putWord16le (0xFFFC::Word16)
put pyld
put (Done) = do
putWord16le (0xFFFD::Word16)
put (Ack) = do
putWord16le (0xFFFE::Word16)
--Testing
--
randWord8 :: Int -> [Word8]
randWord8 0 = []
randWord8 n = let r = unsafePerformIO $ getStdRandom (randomR (0,255::Int))
in
(fromIntegral r) : (randWord8 (n-1))
--Network helpers
getFrame :: Socket -> IO Protocol
getFrame sock = do
lenbytes <- recv sock 4
let l = runGet getWord32le $ repacklbs lenbytes
--putStr $ "Frame size: " ++ (show l) ++ "\n"
msgbytes <- recv sock (fromIntegral l)
let msg = runGet (get::Get Protocol) $ repacklbs msgbytes
return msg
sendKey :: Socket -> Integer -> IO ()
sendKey sock n = do
let msg = Hello n "Rabin-Server"
smsg = runPut (put msg)
len = (fromIntegral $ LBS.length smsg)::Word32
lbytes = runPut $ putWord32le len
_ <- send sock $ repackbs lbytes
_ <- send sock $ repackbs smsg
return ()
--Repack the bytestring to a lazy bytestring
repacklbs :: BS.ByteString -> LBS.ByteString
repacklbs = LBS.pack . BS.unpack
repackbs :: LBS.ByteString -> BS.ByteString
repackbs = BS.pack . LBS.unpack
--Encoding and decoding messages for the message payload
encodemsg :: String -> LBS.ByteString
encodemsg m = let bs = runPut $ put m
digst = md5 bs
msg = runPut $ put (digst,m)
in
msg
decodemsg :: LBS.ByteString -> IO (Maybe (MD5Digest,String))
decodemsg m = (return $ Just $ (\z y -> runGet y z) m $ do
(digest,msg) <- get
return (digest,msg))
processMsg :: Integer -> Integer -> Integer -> IO String
processMsg p q ct = do
(ms) <- (decrypt p q ct)
res <- findbss ms
return res
where
findbss :: [LBS.ByteString] -> IO String
findbss [] = error "No valid message received"
findbss (x:xs) = do
valid <- bigtest x
case valid of
True -> do
Just (_,m) <- (decodemsg x)
(return m)
False -> findbss xs
bigtest bs = do
let (a,bs', _) = runGetState (get::Get MD5Digest) bs 0
return $ a == md5 bs'
encryptMsg :: Integer -> String -> IO BS.ByteString
encryptMsg n msg = if length msg > 200
then do
encryptLongMsg n msg
else do
encryptPackageMsg n msg
encryptPackageMsg :: Integer -> String -> IO BS.ByteString
encryptPackageMsg n msg = do
let prpmsg = encodemsg msg
epyld <- encrypt n $ prpmsg
let pmsg = Message $ epyld
let bytes = repackbs $ runPut $ put pmsg
let size = repackbs $ runPut $ putWord32le ((fromIntegral $ BS.length bytes)::Word32)
return $ BS.append size bytes
encryptLongMsg :: Integer -> String -> IO BS.ByteString
encryptLongMsg n msg = do
let strs = chunkStr msg
msgs <- mapM (encryptPackageMsg n) strs
let doss = repackbs $ runPut $ put $ Dossier (fromIntegral $ length msgs)
let dsize = repackbs $ runPut $ putWord32le ((fromIntegral $ BS.length doss))
let doss' = BS.append dsize doss
let msgs' = foldr BS.append BS.empty msgs
return $ BS.append doss' msgs'
chunkStr :: String -> [String]
chunkStr str = chunk str []
where chunk [] r = r
chunk s r = let s' = drop 200 s
r' = take 200 s
in
chunk s' (r ++ [r'])
| igraves/rabin-haskell | Protocol.hs | gpl-3.0 | 6,339 | 0 | 16 | 2,981 | 1,679 | 839 | 840 | 136 | 3 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Engine where
import qualified Data.Vector.Storable as S
import Graphics.Rendering.OpenGL.Raw
import Graphics.Rendering.FTGL
import Foreign.C
import Foreign
import Geometry (vec3, V)
import Uniform
import Shader
import Model
import Menu
import Util
clear :: IO ()
clear = glClear (gl_COLOR_BUFFER_BIT .|. gl_DEPTH_BUFFER_BIT)
--------------------------------------------------------------------------------
-- Models
loadModel :: FilePath
-> IO GLmodel
loadModel model = do
mesh <- loadMesh model
meshToGL mesh
vertexAttribute, uvAttribute, normalAttribute :: GLuint
vertexAttribute = 0
uvAttribute = 1
normalAttribute = 2
data GLmodel = GLmodel
{ vertArray :: !GLuint
, normArray :: !GLuint
, uvArray :: !GLuint
, ixArray :: !GLuint
, arrSize :: !GLsizei
}
meshToGL :: Mesh -> IO GLmodel
meshToGL (Mesh v n u f) = newGLmodel
(S.map realToFrac v) (S.map realToFrac n) (S.map realToFrac u)
f
-- | 'newGLmodel' vertices normals uvs indices vertexShader fragmentShader
newGLmodel :: S.Vector GLfloat
-> S.Vector GLfloat
-> S.Vector GLfloat
-> S.Vector GLushort
-> IO GLmodel
newGLmodel !vert !norm !uv !elems = do
vertArray <- staticArray vert
normArray <- staticArray norm
uvArray <- staticArray uv
ixArray <- staticElementArray elems
return GLmodel{ arrSize = fromIntegral (S.length elems), .. }
{-# INLINE renderText' #-}
renderText' :: Font -> GLfloat -> GLfloat -> CString -> IO ()
renderText' f x y s = do
glRasterPos2f x y
frenderFont f s 0
{-# INLINE renderLabel #-}
renderLabel :: Font -> GLfloat -> GLfloat -> Label -> IO ()
renderLabel f x y l = withLabel l (renderText f x y)
{-# INLINE renderText #-}
renderText :: Font -> GLfloat -> GLfloat -> CString -> IO ()
renderText f x y t' = do
glColor3f 1 1 1
renderText' f x y t
glColor3f 0 0 0
renderText' f (x+0.002) y t
renderText' f (x-0.002) y t
renderText' f x (y+0.002) t
renderText' f x (y-0.002) t
where
t = castPtr t'
{-# INLINE drawModel #-}
drawModel :: Uploadable s r => GLmodel -> Shaders s -> r
drawModel GLmodel{..} shaders = runShaders shaders $ do
-- Vertice attribute buffer
glEnableVertexAttribArray vertexAttribute
glBindBuffer gl_ARRAY_BUFFER vertArray
glVertexAttribPointer
vertexAttribute
3
gl_FLOAT
0
0
nullPtr
-- UV attribute buffer
glEnableVertexAttribArray uvAttribute
glBindBuffer gl_ARRAY_BUFFER uvArray
glVertexAttribPointer
uvAttribute
2
gl_FLOAT
0
0
nullPtr
-- Normal attribute buffer
glEnableVertexAttribArray normalAttribute
glBindBuffer gl_ARRAY_BUFFER normArray
glVertexAttribPointer
normalAttribute
3
gl_FLOAT
0
0
nullPtr
-- Vertex indices
glBindBuffer gl_ELEMENT_ARRAY_BUFFER ixArray
glDrawElements gl_TRIANGLES arrSize gl_UNSIGNED_SHORT 0
-- Clean up
glDisableVertexAttribArray vertexAttribute
glDisableVertexAttribArray uvAttribute
glDisableVertexAttribArray normalAttribute
glUseProgram 0
--------------------------------------------------------------------------------
-- Buffer creation
newBuffer :: Storable a => GLenum -> GLenum -> S.Vector a -> IO GLuint
newBuffer target hint (buf :: S.Vector a) = do
gid <- alloca' (glGenBuffers 1)
glBindBuffer target gid
S.unsafeWith buf (\ptr -> glBufferData target size ptr hint)
glBindBuffer target 0
return gid
where
size = fromIntegral (sizeOf (undefined :: a) * S.length buf)
staticArray :: Storable a => S.Vector a -> IO GLuint
staticArray = newBuffer gl_ARRAY_BUFFER gl_STATIC_DRAW
staticElementArray :: Storable a => S.Vector a -> IO GLuint
staticElementArray = newBuffer gl_ELEMENT_ARRAY_BUFFER gl_STATIC_DRAW
--------------------------------------------------------------------------------
-- Generated models
grid3D :: V
grid3D = S.concat (map ygrid boundsA ++ map xgrid boundsA)
where
boundsA = [-1, -0.8 .. 1]
boundsB = [-1, 1]
ygrid y = S.fromList $ do
x <- boundsA
z <- boundsB
[x, y, z]
xgrid x = S.fromList $ do
y <- boundsA
z <- boundsB
[x, y, z]
| mikeplus64/plissken | src/Engine.hs | gpl-3.0 | 4,475 | 0 | 13 | 1,079 | 1,228 | 605 | 623 | 137 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Directory List v2.3 LC</title>
<maps>
<homeID>directorylistv2_3_lc</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/directorylistv2_3_lc/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 984 | 83 | 52 | 158 | 397 | 210 | 187 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Blockchain.Node.RestApi
-- Copyright : (c) carbolymer
-- License : Apache-2.0
--
-- Stability : experimental
-- Portability : POSIX
--
-- Defines REST API for the node
--
--------------------------------------------------------------------------------
module Blockchain.Node.RestApi (
RestApi
, restApi
) where
import Servant ((:>), (:<|>)(..), Get, JSON, Post, Proxy(..), ReqBody)
import Blockchain.Node.Core (Block, Node)
import Blockchain.Node.Service (HealthCheck, StatusMessage)
import Blockchain.Node.Transaction (NewTransactionRequest, Transaction)
-- | The definition of the node API
type RestApi = "healthcheck" :> Get '[JSON] HealthCheck
-- new transaction
:<|> "transactions" :> "new" :> ReqBody '[JSON] NewTransactionRequest :> Post '[JSON] StatusMessage
-- list of confirmed transactions in the chain
:<|> "transactions" :> "confirmed" :> Get '[JSON] [Transaction]
-- list of not confirmed transactions
:<|> "transactions" :> "unconfirmed" :> Get '[JSON] [Transaction]
-- mines a new block
:<|> "mine" :> Post '[JSON] (Maybe Block)
-- returns whole blochchain
:<|> "chain" :> Get '[JSON] [Block]
-- returns a list of nodes known to this one
:<|> "nodes" :> "list" :> Get '[JSON] [Node]
-- accepts a list of new nodes
:<|> "nodes" :> "register" :> ReqBody '[JSON] [Node] :> Post '[JSON] StatusMessage
-- checks and sets the correct chain in the current node
:<|> "nodes" :> "resolve" :> Post '[JSON] StatusMessage
-- | A proxy to the RestApi
restApi :: Proxy RestApi
restApi = Proxy
| carbolymer/blockchain | blockchain-node/src/Blockchain/Node/RestApi.hs | apache-2.0 | 1,785 | 0 | 32 | 409 | 367 | 215 | 152 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TupleSections #-}
-- | Utility functions.
module Data.DAWG.Gen.Util
( binarySearch
, findLastLE
, combine
) where
import Control.Applicative ((<$>))
import Data.Bits (shiftR, xor)
import Data.Vector.Unboxed (Unbox)
import qualified Control.Monad.ST as ST
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
-- | Given a vector of length @n@ strictly ascending with respect to
-- a given comparison function, find an index at which the given
-- element could be inserted while preserving sortedness. The 'Left'
-- result indicates, that the 'EQ' element has been found, while the
-- 'Right' result means otherwise. Value of the 'Right' result is in
-- the [0,n] range.
binarySearch :: Unbox a => (a -> Ordering) -> U.Vector a -> Either Int Int
binarySearch cmp v = ST.runST $ do
w <- U.unsafeThaw v
search w
where
search w =
loop 0 (UM.length w)
where
loop !l !u
| u <= l = return (Right l)
| otherwise = do
let k = (u + l) `shiftR` 1
x <- UM.unsafeRead w k
case cmp x of
LT -> loop (k+1) u
EQ -> return (Left k)
GT -> loop l k
{-# INLINE binarySearch #-}
-- | Given a vector sorted with respect to some underlying comparison
-- function, find last element which is not 'GT' with respect to the
-- comparison function.
findLastLE :: Unbox a => (a -> Ordering) -> U.Vector a -> Maybe (Int, a)
findLastLE cmp v =
let k' = binarySearch cmp v
k = either id (\x -> x-1) k'
in (k,) <$> v U.!? k
{-# INLINE findLastLE #-}
-- | Combine two given hash values. 'combine' has zero as a left
-- identity.
combine :: Int -> Int -> Int
combine h1 h2 = (h1 * 16777619) `xor` h2
{-# INLINE combine #-}
| kawu/dawg-ord | src/Data/DAWG/Gen/Util.hs | bsd-2-clause | 1,871 | 0 | 18 | 506 | 468 | 254 | 214 | 37 | 3 |
-- |The parser for the C-Minus compiler. This converts the token
-- stream produced by Compiler.Scanner into an abstract syntax tree.
module Compiler.Parser(program) where
import Monad
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Prim
import Text.ParserCombinators.Parsec.Expr hiding (Operator)
import Compiler.Syntax
import Compiler.Scanner
import Compiler.Positioned
-- |The top parser. This parses an entire C-Minus source file
program = do { whiteSpace
; syms <- many1 toplevel_decl
; return $ Program syms
}
-- |Parser for one top-level declaration (either a global variable or a function)
toplevel_decl = function_declaration <|> global_variable
function_declaration = try (do t <- typeSpec
id <- identifier
args <- parens params
<?> "function arguments"
body <- braces compound_stmt
<?> "function body"
returnWithPosition $ FuncSymbol Unknown $ Function t id args body)
<?> "function declaration"
global_variable = try (do t <- typeSpec
id <- identifier
size <- squares (integer <?> "array size")
<?> "array bounds"
semi
returnWithPosition $ VarSymbol Unknown (Variable (Array t (fromInteger size)) id))
<|>
try (do t <- typeSpec
id <- identifier
semi
returnWithPosition $ VarSymbol Unknown (Variable t id))
<?> "global variable"
var_declaration = do { p <- param
; semi
; return p
}
param = try (do t <- typeSpec
id <- identifier
size <- squares (integer <?> "array size")
<?> "array bounds"
returnWithPosition $ Variable (Array t (fromInteger size)) id)
<|>
try (do t <- typeSpec
id <- identifier
squares whiteSpace
returnWithPosition $ Variable (Pointer t) id)
<|>
try (do t <- typeSpec
id <- identifier
returnWithPosition $ Variable t id)
params = (reserved "void" >> return []) <|> commaSep1 param
statement = do var_declaration
unexpected "variable declaration (variables must be declared before any statements)"
<|> return_stmt
<|> braces compound_stmt
<|> selection_stmt
<|> iteration_stmt
<|> expression_stmt
<?> "statement"
expression_stmt = do expr <- expression
semi
returnWithPosition $ ExpressionStatement expr
compound_stmt = do vars <- many (var_declaration <?> "local variable")
stmts <- many statement
returnWithPosition $ CompoundStatement vars stmts
selection_stmt = do reserved "if"
condExpr <- parens expression
thenClause <- statement
elseClause <- else_clause
returnWithPosition $ SelectionStatement condExpr
thenClause
elseClause
where else_clause = do reserved "else"
stmt <- statement
return stmt
<|> returnWithPosition NullStatement
iteration_stmt = do reserved "while"
condExpr <- parens expression
body <- statement
returnWithPosition $ IterationStatement condExpr body
return_stmt = do reserved "return"
x <- return_value
return x
where return_value = (semi >> returnWithPosition ReturnStatement)
<|> do expr <- simple_expression
semi
returnWithPosition $ ValueReturnStatement expr
expression = try (do { ident <- lvalue
; reservedOp "="
; value <- simple_expression
; return $ AssignmentExpr ident value
})
<|> simple_expression
where lvalue = do { ident <- identifier
; x <- maybeindex ident
; return x
}
maybeindex ident = do { index <- squares expression
; return $ ArrayRef ident index
}
<|> do { return $ VariableRef ident }
simple_expression = buildExpressionParser table factor
where table = [[op ">=" (ArithmeticExpr GreaterOrEqual) AssocNone,
op ">" (ArithmeticExpr Greater) AssocNone,
op "<=" (ArithmeticExpr LessOrEqual) AssocNone,
op "<" (ArithmeticExpr Less) AssocNone,
op "==" (ArithmeticExpr Equal) AssocNone,
op "!=" (ArithmeticExpr NotEqual) AssocNone],
[op "*" (ArithmeticExpr Multiply) AssocLeft,
op "/" (ArithmeticExpr Divide) AssocLeft],
[op "+" (ArithmeticExpr Add) AssocLeft,
op "-" (ArithmeticExpr Subtract) AssocLeft]]
op s f assoc = Infix (do{ reservedOp s; return f}) assoc
factor = (parens simple_expression)
<|> value_expression
value_expression = do val <- value
return $ ValueExpr val
value = do { num <- integer; return $ IntValue (fromInteger num) }
<|> do { ident <- identifier
; x <- variableOrCall ident
; return x
}
where variableOrCall ident = do { index <- squares simple_expression
; return $ ArrayRef ident index
}
<|> do { args <- parens (commaSep simple_expression)
; return $ FunctionCall ident args
}
<|> do { return $ VariableRef ident }
| michaelmelanson/cminus-compiler | Compiler/Parser.hs | bsd-2-clause | 7,189 | 0 | 18 | 3,547 | 1,360 | 657 | 703 | 122 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Utils.Vigilance.Client.Config ( Command(..)
, Options(..)
, ClientConfig(..)
, ClientCtxT
, defaultHost
, readClientConfig
, defaultPort'
, defaultConfigPath ) where
import Prelude (FilePath)
import ClassyPrelude hiding (FilePath)
import Control.Monad ((<=<))
import Control.Monad.Trans.Reader
import Data.Configurator (load, Worth(Optional))
import qualified Data.Configurator as C
import qualified Data.Configurator.Types as CT
import Network.Http.Client ( Hostname
, Port )
import Utils.Vigilance.Types
data Command = List |
Pause WatchName |
UnPause WatchName |
CheckIn WatchName |
Info WatchName |
Test WatchName deriving (Show, Eq)
data Options = Options { optCommand :: Command
, configPath :: FilePath } deriving (Show, Eq)
defaultConfigPath :: FilePath
defaultConfigPath = vigilanceDir <> "/client.conf"
data ClientConfig = ClientConfig { serverHost :: Hostname
, serverPort :: Port } deriving (Show, Eq)
type ClientCtxT m a = ReaderT ClientConfig m a
defaultHost :: Hostname
defaultHost = "localhost"
defaultPort' :: Port
defaultPort' = fromInteger . toInteger $ defaultPort
readClientConfig :: FilePath -> IO ClientConfig
readClientConfig = convertClientConfig <=< loadConfig
loadConfig :: FilePath -> IO CT.Config
loadConfig pth = load [Optional pth]
convertClientConfig :: CT.Config -> IO ClientConfig
convertClientConfig cfg = ClientConfig <$> lookupHost <*> lookupPort
where lookupHost = C.lookupDefault defaultHost cfg "vigilance.host"
lookupPort = C.lookupDefault defaultPort' cfg "vigilance.port"
| MichaelXavier/vigilance | src/Utils/Vigilance/Client/Config.hs | bsd-2-clause | 2,048 | 0 | 8 | 656 | 414 | 247 | 167 | 45 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Evaluate where
import Bound
import Bound.Name
import Control.Comonad
import Control.Monad.Except
import Core
import Environment
newtype Eval a = Eval (Except String a)
deriving (Functor, Applicative, Monad, MonadError String)
eval :: Env Eval (Term n) (Value Eval n) a
-> Term n a
-> Eval (Value Eval n)
eval env (Var x) = do
k <- lookupDef env x
case k of
Cloj tm -> eval env tm
Val v -> return v
eval _ Type = return VType
quote :: (Eq n, Monad m) => (n -> Term n a) -> Value m n -> m (Term n a)
quote k = quote' 0 k undefined
quote' :: (Eq n, Monad m)
=> Int -> (n -> Term n a) -> (Int -> Term n a) -> Value m n
-> m (Term n a)
quote' q k l (Neutral n) = quoteNeutral q k l n
quote' q _ _ VType = return Type
quote' q k l (VTmp n) = return (l (q-n-1))
quote' q k l (VBind (Pi v) f) = do
v' <- quote' q k l (extract v)
s <- f (VTmp q)
let n a = Name (name v) a
s' <- quote' (q+1) (Var . F . k) (intToVar (n ()) l) s
return (Bind (Pi (n v')) (Scope s'))
quoteNeutral :: (Eq n, Monad m)
=> Int -> (n -> Term n a) -> (Int -> Term n a) -> Neutral m n
-> m (Term n a)
quoteNeutral _ k _ (NVar n) = return (k n)
quoteNeutral q k l (NApp e u) = App <$> quoteNeutral q k l e <*> quote' q k l u
intToVar :: Monad f => b -> (Int -> f a) -> Int -> f (Var b (f a))
intToVar n f i
| i == 0 = return (B n)
| otherwise = return . F $ f (i - 1)
| christiaanb/DepCore | src/Evaluate.hs | bsd-2-clause | 1,492 | 0 | 13 | 434 | 860 | 422 | 438 | 42 | 2 |
module Drasil.NoPCM.Requirements (funcReqs, inputInitValsTable) where
import Language.Drasil
import Drasil.DocLang (mkInputPropsTable)
import Utils.Drasil
import Data.Drasil.Concepts.Documentation (funcReqDom, input_, value)
import Data.Drasil.Quantities.Math (pi_)
import Data.Drasil.Quantities.PhysicalProperties (mass)
import Drasil.SWHS.DataDefs (balanceDecayRate)
import Drasil.SWHS.Requirements (calcTempWtrOverTime, calcChgHeatEnergyWtrOverTime,
checkWithPhysConsts, findMassConstruct, inReqDesc, oIDQConstruct)
import Drasil.SWHS.Unitals (diam, tankLength, wDensity, wMass, wVol)
import Drasil.NoPCM.IMods (eBalanceOnWtr)
import Drasil.NoPCM.Unitals (inputs)
--------------------------
--Section 5 : REQUIREMENTS
--------------------------
---------------------------------------
--Section 5.1 : FUNCTIONAL REQUIREMENTS
---------------------------------------
--
inputInitVals :: ConceptInstance
inputInitVals = cic "inputInitVals" ( foldlSent [
titleize input_, S "the following", plural value, S "described in",
makeRef2S inputInitValsTable `sC` S "which define", inReqDesc])
"Input-Initial-Values" funcReqDom
--
findMassExpr :: Expr
findMassExpr = sy wMass $= sy wVol * sy wDensity $=
(sy pi_ * ((sy diam / 2) $^ 2) * sy tankLength * sy wDensity)
findMass :: ConceptInstance
findMass = findMassConstruct inputInitVals (phrase mass) [eBalanceOnWtr]
(E findMassExpr) (ch wVol `isThe` phrase wVol)
--
oIDQVals :: [Sentence]
oIDQVals = map foldlSent_ [
[S "the", plural value, S "from", makeRef2S inputInitVals],
[S "the", phrase mass, S "from", makeRef2S findMass],
[ch balanceDecayRate, sParen (S "from" +:+ makeRef2S balanceDecayRate)]
]
inputInitValsTable :: LabelledContent
inputInitValsTable = mkInputPropsTable inputs inputInitVals
funcReqs :: [ConceptInstance]
funcReqs = [inputInitVals, findMass, checkWithPhysConsts,
oIDQConstruct oIDQVals, calcTempWtrOverTime, calcChgHeatEnergyWtrOverTime]
-------------------------------------------
--Section 5.2 : NON-FUNCTIONAL REQUIREMENTS
-------------------------------------------
--imports from SWHS
| JacquesCarette/literate-scientific-software | code/drasil-example/Drasil/NoPCM/Requirements.hs | bsd-2-clause | 2,116 | 0 | 14 | 256 | 511 | 294 | 217 | 34 | 1 |
-- |
-- Module : Main
-- Copyright : (c) Radek Micek 2010
-- License : BSD3
-- Stability : experimental
--
-- Generates formulas representing pigeonhole principle.
import Control.Applicative ((<$>))
import Data.Maybe
import Data.List
import System.Environment
-- Total number of holes.
type HolesCnt = Int
type Clause = String
-- Returns variable name for proposition "pigeon p is in hole h".
pl :: Int -> Int -> String
pl p h = "p[" ++ show p ++ "," ++ show h ++ "]"
-- Generated clause assures that pigeon p is in some hole.
--
-- Call this for each pigeon.
pigeonIsInHole :: Int -> HolesCnt -> Clause
pigeonIsInHole p n = intercalate "+" [pl p hole | hole <- [1..n]]
-- Assures that hole h is inhabited by no more than one pigeon.
--
-- Call this for each hole.
atMostOnePigeonInHole :: Int -> HolesCnt -> [Clause]
atMostOnePigeonInHole h n =
['~':pl p h ++ "+" ++ '~':pl p' h | p <- [1..(n+1)], p' <- [(p+1)..(n+1)]]
-- Generates CNF formula for pigeonhole principle
php :: HolesCnt -> String
php n = concatMap (\cl -> '(':cl ++ ")") clauses
where
clauses = [pigeonIsInHole p n | p <- [1..(n+1)]] ++
concat [atMostOnePigeonInHole h n | h <- [1..n]]
main :: IO ()
main = do
nHolesArg <- listToMaybe <$> getArgs
prog <- getProgName
case nHolesArg of
Nothing -> putStrLn $ usage prog
Just nHoles -> putStrLn $ php $ read nHoles
where
usage p = intercalate "\n"
[ "Usage: " ++ p ++ " NUM-OF-PIGEONHOLES"
, "Returns CNF formula which represents pigeonhole principle."
, "Variable p[i,j] in the formula represents proposition"
, "that pigeon i is in pigeonhole j." ]
| radekm/simple-prop-prover | PHPGenerator.hs | bsd-3-clause | 1,692 | 0 | 13 | 409 | 461 | 248 | 213 | 29 | 2 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
-----------------------------------------------------------------
-- Auto-generated by regenClassifiers
--
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ranking.Classifiers.TR (classifiers) where
import Prelude
import Duckling.Ranking.Types
import qualified Data.HashMap.Strict as HashMap
import Data.String
classifiers :: Classifiers
classifiers = HashMap.fromList [] | rfranek/duckling | Duckling/Ranking/Classifiers/TR.hs | bsd-3-clause | 825 | 0 | 6 | 105 | 66 | 47 | 19 | 8 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Core.Floating
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Implementation of floating-point operations mapping to SMT-Lib2 floats
-----------------------------------------------------------------------------
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.SBV.Core.Floating (
IEEEFloating(..), IEEEFloatConvertable(..)
, sFloatAsSWord32, sDoubleAsSWord64, sWord32AsSFloat, sWord64AsSDouble
, blastSFloat, blastSDouble
) where
import Control.Monad (join)
import qualified Data.Binary.IEEE754 as DB (wordToFloat, wordToDouble, floatToWord, doubleToWord)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Word (Word8, Word16, Word32, Word64)
import Data.SBV.Core.Data
import Data.SBV.Core.Model
import Data.SBV.Core.AlgReals (isExactRational)
import Data.SBV.Utils.Boolean
import Data.SBV.Utils.Numeric
-- | A class of floating-point (IEEE754) operations, some of
-- which behave differently based on rounding modes. Note that unless
-- the rounding mode is concretely RoundNearestTiesToEven, we will
-- not concretely evaluate these, but rather pass down to the SMT solver.
class (SymWord a, RealFloat a) => IEEEFloating a where
-- | Compute the floating point absolute value.
fpAbs :: SBV a -> SBV a
-- | Compute the unary negation. Note that @0 - x@ is not equivalent to @-x@ for floating-point, since @-0@ and @0@ are different.
fpNeg :: SBV a -> SBV a
-- | Add two floating point values, using the given rounding mode
fpAdd :: SRoundingMode -> SBV a -> SBV a -> SBV a
-- | Subtract two floating point values, using the given rounding mode
fpSub :: SRoundingMode -> SBV a -> SBV a -> SBV a
-- | Multiply two floating point values, using the given rounding mode
fpMul :: SRoundingMode -> SBV a -> SBV a -> SBV a
-- | Divide two floating point values, using the given rounding mode
fpDiv :: SRoundingMode -> SBV a -> SBV a -> SBV a
-- | Fused-multiply-add three floating point values, using the given rounding mode. @fpFMA x y z = x*y+z@ but with only
-- one rounding done for the whole operation; not two. Note that we will never concretely evaluate this function since
-- Haskell lacks an FMA implementation.
fpFMA :: SRoundingMode -> SBV a -> SBV a -> SBV a -> SBV a
-- | Compute the square-root of a float, using the given rounding mode
fpSqrt :: SRoundingMode -> SBV a -> SBV a
-- | Compute the remainder: @x - y * n@, where @n@ is the truncated integer nearest to x/y. The rounding mode
-- is implicitly assumed to be @RoundNearestTiesToEven@.
fpRem :: SBV a -> SBV a -> SBV a
-- | Round to the nearest integral value, using the given rounding mode.
fpRoundToIntegral :: SRoundingMode -> SBV a -> SBV a
-- | Compute the minimum of two floats, respects @infinity@ and @NaN@ values
fpMin :: SBV a -> SBV a -> SBV a
-- | Compute the maximum of two floats, respects @infinity@ and @NaN@ values
fpMax :: SBV a -> SBV a -> SBV a
-- | Are the two given floats exactly the same. That is, @NaN@ will compare equal to itself, @+0@ will /not/ compare
-- equal to @-0@ etc. This is the object level equality, as opposed to the semantic equality. (For the latter, just use '.=='.)
fpIsEqualObject :: SBV a -> SBV a -> SBool
-- | Is the floating-point number a normal value. (i.e., not denormalized.)
fpIsNormal :: SBV a -> SBool
-- | Is the floating-point number a subnormal value. (Also known as denormal.)
fpIsSubnormal :: SBV a -> SBool
-- | Is the floating-point number 0? (Note that both +0 and -0 will satisfy this predicate.)
fpIsZero :: SBV a -> SBool
-- | Is the floating-point number infinity? (Note that both +oo and -oo will satisfy this predicate.)
fpIsInfinite :: SBV a -> SBool
-- | Is the floating-point number a NaN value?
fpIsNaN :: SBV a -> SBool
-- | Is the floating-point number negative? Note that -0 satisfies this predicate but +0 does not.
fpIsNegative :: SBV a -> SBool
-- | Is the floating-point number positive? Note that +0 satisfies this predicate but -0 does not.
fpIsPositive :: SBV a -> SBool
-- | Is the floating point number -0?
fpIsNegativeZero :: SBV a -> SBool
-- | Is the floating point number +0?
fpIsPositiveZero :: SBV a -> SBool
-- | Is the floating-point number a regular floating point, i.e., not NaN, nor +oo, nor -oo. Normals or denormals are allowed.
fpIsPoint :: SBV a -> SBool
-- Default definitions. Minimal complete definition: None! All should be taken care by defaults
-- Note that we never evaluate FMA concretely, as there's no fma operator in Haskell
fpAbs = lift1 FP_Abs (Just abs) Nothing
fpNeg = lift1 FP_Neg (Just negate) Nothing
fpAdd = lift2 FP_Add (Just (+)) . Just
fpSub = lift2 FP_Sub (Just (-)) . Just
fpMul = lift2 FP_Mul (Just (*)) . Just
fpDiv = lift2 FP_Div (Just (/)) . Just
fpFMA = lift3 FP_FMA Nothing . Just
fpSqrt = lift1 FP_Sqrt (Just sqrt) . Just
fpRem = lift2 FP_Rem (Just fpRemH) Nothing
fpRoundToIntegral = lift1 FP_RoundToIntegral (Just fpRoundToIntegralH) . Just
fpMin = liftMM FP_Min (Just fpMinH) Nothing
fpMax = liftMM FP_Max (Just fpMaxH) Nothing
fpIsEqualObject = lift2B FP_ObjEqual (Just fpIsEqualObjectH) Nothing
fpIsNormal = lift1B FP_IsNormal fpIsNormalizedH
fpIsSubnormal = lift1B FP_IsSubnormal isDenormalized
fpIsZero = lift1B FP_IsZero (== 0)
fpIsInfinite = lift1B FP_IsInfinite isInfinite
fpIsNaN = lift1B FP_IsNaN isNaN
fpIsNegative = lift1B FP_IsNegative (\x -> x < 0 || isNegativeZero x)
fpIsPositive = lift1B FP_IsPositive (\x -> x >= 0 && not (isNegativeZero x))
fpIsNegativeZero x = fpIsZero x &&& fpIsNegative x
fpIsPositiveZero x = fpIsZero x &&& fpIsPositive x
fpIsPoint x = bnot (fpIsNaN x ||| fpIsInfinite x)
-- | SFloat instance
instance IEEEFloating Float
-- | SDouble instance
instance IEEEFloating Double
-- | Capture convertability from/to FloatingPoint representations
-- NB. 'fromSFloat' and 'fromSDouble' are underspecified when given
-- when given a @NaN@, @+oo@, or @-oo@ value that cannot be represented
-- in the target domain. For these inputs, we define the result to be +0, arbitrarily.
class IEEEFloatConvertable a where
fromSFloat :: SRoundingMode -> SFloat -> SBV a
toSFloat :: SRoundingMode -> SBV a -> SFloat
fromSDouble :: SRoundingMode -> SDouble -> SBV a
toSDouble :: SRoundingMode -> SBV a -> SDouble
-- | A generic converter that will work for most of our instances. (But not all!)
genericFPConverter :: forall a r. (SymWord a, HasKind r, SymWord r, Num r) => Maybe (a -> Bool) -> Maybe (SBV a -> SBool) -> (a -> r) -> SRoundingMode -> SBV a -> SBV r
genericFPConverter mbConcreteOK mbSymbolicOK converter rm f
| Just w <- unliteral f, Just RoundNearestTiesToEven <- unliteral rm, check w
= literal $ converter w
| Just symCheck <- mbSymbolicOK
= ite (symCheck f) result (literal 0)
| True
= result
where result = SBV (SVal kTo (Right (cache y)))
check w = maybe True ($ w) mbConcreteOK
kFrom = kindOf f
kTo = kindOf (undefined :: r)
y st = do msw <- sbvToSW st rm
xsw <- sbvToSW st f
newExpr st kTo (SBVApp (IEEEFP (FP_Cast kFrom kTo msw)) [xsw])
-- | Check that a given float is a point
ptCheck :: IEEEFloating a => Maybe (SBV a -> SBool)
ptCheck = Just fpIsPoint
instance IEEEFloatConvertable Int8 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Int16 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Int32 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Int64 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Word8 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Word16 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Word32 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Word64 where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
instance IEEEFloatConvertable Float where
fromSFloat _ f = f
toSFloat _ f = f
fromSDouble = genericFPConverter Nothing Nothing fp2fp
toSDouble = genericFPConverter Nothing Nothing fp2fp
instance IEEEFloatConvertable Double where
fromSFloat = genericFPConverter Nothing Nothing fp2fp
toSFloat = genericFPConverter Nothing Nothing fp2fp
fromSDouble _ d = d
toSDouble _ d = d
instance IEEEFloatConvertable Integer where
fromSFloat = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Float -> Integer))
toSFloat = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
fromSDouble = genericFPConverter Nothing ptCheck (fromIntegral . (fpRound0 :: Double -> Integer))
toSDouble = genericFPConverter Nothing Nothing (fromRational . fromIntegral)
-- For AlgReal; be careful to only process exact rationals concretely
instance IEEEFloatConvertable AlgReal where
fromSFloat = genericFPConverter Nothing ptCheck (fromRational . fpRatio0)
toSFloat = genericFPConverter (Just isExactRational) Nothing (fromRational . toRational)
fromSDouble = genericFPConverter Nothing ptCheck (fromRational . fpRatio0)
toSDouble = genericFPConverter (Just isExactRational) Nothing (fromRational . toRational)
-- | Concretely evaluate one arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data
concEval1 :: SymWord a => Maybe (a -> a) -> Maybe SRoundingMode -> SBV a -> Maybe (SBV a)
concEval1 mbOp mbRm a = do op <- mbOp
v <- unliteral a
case join (unliteral `fmap` mbRm) of
Nothing -> (Just . literal) (op v)
Just RoundNearestTiesToEven -> (Just . literal) (op v)
_ -> Nothing
-- | Concretely evaluate two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data
concEval2 :: SymWord a => Maybe (a -> a -> a) -> Maybe SRoundingMode -> SBV a -> SBV a -> Maybe (SBV a)
concEval2 mbOp mbRm a b = do op <- mbOp
v1 <- unliteral a
v2 <- unliteral b
case join (unliteral `fmap` mbRm) of
Nothing -> (Just . literal) (v1 `op` v2)
Just RoundNearestTiesToEven -> (Just . literal) (v1 `op` v2)
_ -> Nothing
-- | Concretely evaluate a bool producing two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data
concEval2B :: SymWord a => Maybe (a -> a -> Bool) -> Maybe SRoundingMode -> SBV a -> SBV a -> Maybe SBool
concEval2B mbOp mbRm a b = do op <- mbOp
v1 <- unliteral a
v2 <- unliteral b
case join (unliteral `fmap` mbRm) of
Nothing -> (Just . literal) (v1 `op` v2)
Just RoundNearestTiesToEven -> (Just . literal) (v1 `op` v2)
_ -> Nothing
-- | Concretely evaluate two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data
concEval3 :: SymWord a => Maybe (a -> a -> a -> a) -> Maybe SRoundingMode -> SBV a -> SBV a -> SBV a -> Maybe (SBV a)
concEval3 mbOp mbRm a b c = do op <- mbOp
v1 <- unliteral a
v2 <- unliteral b
v3 <- unliteral c
case join (unliteral `fmap` mbRm) of
Nothing -> (Just . literal) (op v1 v2 v3)
Just RoundNearestTiesToEven -> (Just . literal) (op v1 v2 v3)
_ -> Nothing
-- | Add the converted rounding mode if given as an argument
addRM :: State -> Maybe SRoundingMode -> [SW] -> IO [SW]
addRM _ Nothing as = return as
addRM st (Just rm) as = do swm <- sbvToSW st rm
return (swm : as)
-- | Lift a 1 arg FP-op
lift1 :: SymWord a => FPOp -> Maybe (a -> a) -> Maybe SRoundingMode -> SBV a -> SBV a
lift1 w mbOp mbRm a
| Just cv <- concEval1 mbOp mbRm a
= cv
| True
= SBV $ SVal k $ Right $ cache r
where k = kindOf a
r st = do swa <- sbvToSW st a
args <- addRM st mbRm [swa]
newExpr st k (SBVApp (IEEEFP w) args)
-- | Lift an FP predicate
lift1B :: SymWord a => FPOp -> (a -> Bool) -> SBV a -> SBool
lift1B w f a
| Just v <- unliteral a = literal $ f v
| True = SBV $ SVal KBool $ Right $ cache r
where r st = do swa <- sbvToSW st a
newExpr st KBool (SBVApp (IEEEFP w) [swa])
-- | Lift a 2 arg FP-op
lift2 :: SymWord a => FPOp -> Maybe (a -> a -> a) -> Maybe SRoundingMode -> SBV a -> SBV a -> SBV a
lift2 w mbOp mbRm a b
| Just cv <- concEval2 mbOp mbRm a b
= cv
| True
= SBV $ SVal k $ Right $ cache r
where k = kindOf a
r st = do swa <- sbvToSW st a
swb <- sbvToSW st b
args <- addRM st mbRm [swa, swb]
newExpr st k (SBVApp (IEEEFP w) args)
-- | Lift min/max: Note that we protect against constant folding if args are alternating sign 0's, since
-- SMTLib is deliberately nondeterministic in this case
liftMM :: (SymWord a, RealFloat a) => FPOp -> Maybe (a -> a -> a) -> Maybe SRoundingMode -> SBV a -> SBV a -> SBV a
liftMM w mbOp mbRm a b
| Just v1 <- unliteral a
, Just v2 <- unliteral b
, not ((isN0 v1 && isP0 v2) || (isP0 v1 && isN0 v2)) -- If not +0/-0 or -0/+0
, Just cv <- concEval2 mbOp mbRm a b
= cv
| True
= SBV $ SVal k $ Right $ cache r
where isN0 = isNegativeZero
isP0 x = x == 0 && not (isN0 x)
k = kindOf a
r st = do swa <- sbvToSW st a
swb <- sbvToSW st b
args <- addRM st mbRm [swa, swb]
newExpr st k (SBVApp (IEEEFP w) args)
-- | Lift a 2 arg FP-op, producing bool
lift2B :: SymWord a => FPOp -> Maybe (a -> a -> Bool) -> Maybe SRoundingMode -> SBV a -> SBV a -> SBool
lift2B w mbOp mbRm a b
| Just cv <- concEval2B mbOp mbRm a b
= cv
| True
= SBV $ SVal KBool $ Right $ cache r
where r st = do swa <- sbvToSW st a
swb <- sbvToSW st b
args <- addRM st mbRm [swa, swb]
newExpr st KBool (SBVApp (IEEEFP w) args)
-- | Lift a 3 arg FP-op
lift3 :: SymWord a => FPOp -> Maybe (a -> a -> a -> a) -> Maybe SRoundingMode -> SBV a -> SBV a -> SBV a -> SBV a
lift3 w mbOp mbRm a b c
| Just cv <- concEval3 mbOp mbRm a b c
= cv
| True
= SBV $ SVal k $ Right $ cache r
where k = kindOf a
r st = do swa <- sbvToSW st a
swb <- sbvToSW st b
swc <- sbvToSW st c
args <- addRM st mbRm [swa, swb, swc]
newExpr st k (SBVApp (IEEEFP w) args)
-- | Convert an 'SFloat' to an 'SWord32', preserving the bit-correspondence. Note that since the
-- representation for @NaN@s are not unique, this function will return a symbolic value when given a
-- concrete @NaN@.
--
-- Implementation note: Since there's no corresponding function in SMTLib for conversion to
-- bit-representation due to partiality, we use a translation trick by allocating a new word variable,
-- converting it to float, and requiring it to be equivalent to the input. In code-generation mode, we simply map
-- it to a simple conversion.
sFloatAsSWord32 :: SFloat -> SWord32
sFloatAsSWord32 fVal
| Just f <- unliteral fVal, not (isNaN f)
= literal (DB.floatToWord f)
| True
= SBV (SVal w32 (Right (cache y)))
where w32 = KBounded False 32
y st = do cg <- isCodeGenMode st
if cg
then do f <- sbvToSW st fVal
newExpr st w32 (SBVApp (IEEEFP (FP_Reinterpret KFloat w32)) [f])
else do n <- internalVariable st w32
ysw <- newExpr st KFloat (SBVApp (IEEEFP (FP_Reinterpret w32 KFloat)) [n])
internalConstraint st Nothing $ unSBV $ fVal `fpIsEqualObject` SBV (SVal KFloat (Right (cache (\_ -> return ysw))))
return n
-- | Convert an 'SDouble' to an 'SWord64', preserving the bit-correspondence. Note that since the
-- representation for @NaN@s are not unique, this function will return a symbolic value when given a
-- concrete @NaN@.
--
-- See the implementation note for 'sFloatAsSWord32', as it applies here as well.
sDoubleAsSWord64 :: SDouble -> SWord64
sDoubleAsSWord64 fVal
| Just f <- unliteral fVal, not (isNaN f)
= literal (DB.doubleToWord f)
| True
= SBV (SVal w64 (Right (cache y)))
where w64 = KBounded False 64
y st = do cg <- isCodeGenMode st
if cg
then do f <- sbvToSW st fVal
newExpr st w64 (SBVApp (IEEEFP (FP_Reinterpret KDouble w64)) [f])
else do n <- internalVariable st w64
ysw <- newExpr st KDouble (SBVApp (IEEEFP (FP_Reinterpret w64 KDouble)) [n])
internalConstraint st Nothing $ unSBV $ fVal `fpIsEqualObject` SBV (SVal KDouble (Right (cache (\_ -> return ysw))))
return n
-- | Extract the sign\/exponent\/mantissa of a single-precision float. The output will have
-- 8 bits in the second argument for exponent, and 23 in the third for the mantissa.
blastSFloat :: SFloat -> (SBool, [SBool], [SBool])
blastSFloat = extract . sFloatAsSWord32
where extract x = (sTestBit x 31, sExtractBits x [30, 29 .. 23], sExtractBits x [22, 21 .. 0])
-- | Extract the sign\/exponent\/mantissa of a single-precision float. The output will have
-- 11 bits in the second argument for exponent, and 52 in the third for the mantissa.
blastSDouble :: SDouble -> (SBool, [SBool], [SBool])
blastSDouble = extract . sDoubleAsSWord64
where extract x = (sTestBit x 63, sExtractBits x [62, 61 .. 52], sExtractBits x [51, 50 .. 0])
-- | Reinterpret the bits in a 32-bit word as a single-precision floating point number
sWord32AsSFloat :: SWord32 -> SFloat
sWord32AsSFloat fVal
| Just f <- unliteral fVal = literal $ DB.wordToFloat f
| True = SBV (SVal KFloat (Right (cache y)))
where y st = do xsw <- sbvToSW st fVal
newExpr st KFloat (SBVApp (IEEEFP (FP_Reinterpret (kindOf fVal) KFloat)) [xsw])
-- | Reinterpret the bits in a 32-bit word as a single-precision floating point number
sWord64AsSDouble :: SWord64 -> SDouble
sWord64AsSDouble dVal
| Just d <- unliteral dVal = literal $ DB.wordToDouble d
| True = SBV (SVal KDouble (Right (cache y)))
where y st = do xsw <- sbvToSW st dVal
newExpr st KDouble (SBVApp (IEEEFP (FP_Reinterpret (kindOf dVal) KDouble)) [xsw])
{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
| josefs/sbv | Data/SBV/Core/Floating.hs | bsd-3-clause | 22,869 | 0 | 22 | 6,592 | 5,798 | 2,916 | 2,882 | 296 | 3 |
{-# Language CPP, OverloadedStrings, GeneralizedNewtypeDeriving #-}
module Haste.Binary.Get (
Get,
getWord8, getWord16le, getWord32le,
getInt8, getInt16le, getInt32le,
getFloat32le, getFloat64le,
getBytes, skip,
runGet
) where
import Data.Int
import Data.Word
import Haste.Prim
import Haste.Foreign
import Haste.Binary.Types
import Control.Applicative
import Control.Monad
import System.IO.Unsafe
#ifndef __HASTE__
import qualified Data.Binary as B
import qualified Data.Binary.IEEE754 as BI
import qualified Data.Binary.Get as BG
import qualified Control.Exception as Ex
#endif
#ifdef __HASTE__
data Get a = Get {unG :: Unpacked -> Int -> Either String (Int, a)}
instance Functor Get where
fmap f (Get m) = Get $ \buf next -> fmap (fmap f) (m buf next)
instance Applicative Get where
(<*>) = ap
pure = return
instance Monad Get where
return x = Get $ \_ next -> Right (next, x)
(Get m) >>= f = Get $ \buf next ->
case m buf next of
Right (next', x) -> unG (f x) buf next'
Left e -> Left e
fail s = Get $ \_ _ -> Left s
{-# NOINLINE getW8 #-}
getW8 :: Unpacked -> Int -> IO Word8
getW8 = ffi "(function(b,i){return b.getUint8(i);})"
getWord8 :: Get Word8
getWord8 =
Get $ \buf next -> Right (next+1, unsafePerformIO $ getW8 buf next)
{-# NOINLINE getW16le #-}
getW16le :: Unpacked -> Int -> IO Word16
getW16le = ffi "(function(b,i){return b.getUint16(i,true);})"
getWord16le :: Get Word16
getWord16le =
Get $ \buf next -> Right (next+2, unsafePerformIO $ getW16le buf next)
{-# NOINLINE getW32le #-}
getW32le :: Unpacked -> Int -> IO Word32
getW32le = ffi "(function(b,i){return b.getUint32(i,true);})"
getWord32le :: Get Word32
getWord32le =
Get $ \buf next -> Right (next+4, unsafePerformIO $ getW32le buf next)
{-# NOINLINE getI8 #-}
getI8 :: Unpacked -> Int -> IO Int8
getI8 = ffi "(function(b,i){return b.getInt8(i);})"
getInt8 :: Get Int8
getInt8 =
Get $ \buf next -> Right (next+1, unsafePerformIO $ getI8 buf next)
{-# NOINLINE getI16le #-}
getI16le :: Unpacked -> Int -> IO Int16
getI16le = ffi "(function(b,i){return b.getInt16(i,true);})"
getInt16le :: Get Int16
getInt16le =
Get $ \buf next -> Right (next+2, unsafePerformIO $ getI16le buf next)
{-# NOINLINE getI32le #-}
getI32le :: Unpacked -> Int -> IO Int32
getI32le = ffi "(function(b,i){return b.getInt32(i,true);})"
getInt32le :: Get Int32
getInt32le =
Get $ \buf next -> Right (next+4, unsafePerformIO $ getI32le buf next)
{-# NOINLINE getF32le #-}
getF32le :: Unpacked -> Int -> IO Float
getF32le = ffi "(function(b,i){return b.getFloat32(i,true);})"
getFloat32le :: Get Float
getFloat32le =
Get $ \buf next -> Right (next+4, unsafePerformIO $ getF32le buf next)
{-# NOINLINE getF64le #-}
getF64le :: Unpacked -> Int -> IO Double
getF64le = ffi "(function(b,i){return b.getFloat64(i,true);})"
getFloat64le :: Get Double
getFloat64le =
Get $ \buf next -> Right (next+8, unsafePerformIO $ getF64le buf next)
getBytes :: Int -> Get BlobData
getBytes len = Get $ \buf next -> Right (next+len, BlobData next len buf)
-- | Skip n bytes of input.
skip :: Int -> Get ()
skip len = Get $ \buf next -> Right (next+len, ())
-- | Run a Get computation.
runGet :: Get a -> BlobData -> Either String a
runGet (Get p) (BlobData off len bd) = do
(consumed, x) <- p bd off
if consumed <= len
then Right x
else Left "Not enough data!"
#else
newtype Get a = Get (BG.Get a) deriving (Functor, Applicative, Monad)
runGet :: Get a -> BlobData -> Either String a
runGet (Get g) (BlobData bd) = unsafePerformIO $ do
Ex.catch (Right <$> (return $! BG.runGet g bd)) mEx
mEx :: Ex.SomeException -> IO (Either String a)
mEx ex = return . Left $ show ex
getWord8 :: Get Word8
getWord8 = Get BG.getWord8
getWord16le :: Get Word16
getWord16le = Get BG.getWord16le
getWord32le :: Get Word32
getWord32le = Get BG.getWord32le
getInt8 :: Get Int8
getInt8 = Get B.get
getInt16le :: Get Int16
getInt16le = fromIntegral <$> getWord16le
getInt32le :: Get Int32
getInt32le = fromIntegral <$> getWord32le
getFloat32le :: Get Float
getFloat32le = Get BI.getFloat32le
getFloat64le :: Get Double
getFloat64le = Get BI.getFloat64le
getBytes :: Int -> Get BlobData
getBytes len = Get $ do
bs <- BG.getLazyByteString (fromIntegral len)
return (BlobData bs)
-- | Skip n bytes of input.
skip :: Int -> Get ()
skip = Get . BG.skip
#endif
| joelburget/haste-compiler | libraries/haste-lib/src/Haste/Binary/Get.hs | bsd-3-clause | 4,404 | 0 | 13 | 837 | 1,126 | 605 | 521 | 48 | 1 |
atom :: (Delta d) => d -> aam -> Atom -> M d aam (Val d aam)
atom d aam (LitA l) = return $ lit d l
atom d aam (Var x) = do
e <- get $ E aam
s <- get $ S d aam
case mapLookup x e of
Nothing -> mzero
Just l -> setMSum $ mapLookup l s
atom d aam (Prim o a) = do
v <- atom d aam a
mFromMaybe $ op d o v
atom d aam (Lam xs c) = do
e <- get $ E aam
return $ clo d xs c e
| davdar/quals | writeup-old/sections/04MonadicAAM/00MonadicStyle/01State/08Atom.hs | bsd-3-clause | 388 | 0 | 11 | 127 | 251 | 117 | 134 | 14 | 2 |
module Compile (compile) where
import qualified Data.Map as Map
import Text.PrettyPrint (Doc)
import qualified AST.Module as Module
import qualified Parse.Helpers as Parse
import qualified Parse.Parse as Parse
import qualified Transform.AddDefaultImports as DefaultImports
import qualified Transform.Check as Check
import qualified Type.Inference as TI
import qualified Transform.Canonicalize as Canonical
import Elm.Utils ((|>))
compile
:: String
-> String
-> Module.Interfaces
-> String
-> Either [Doc] Module.CanonicalModule
compile user projectName interfaces source =
do
-- Parse the source code
parsedModule <-
Parse.program (getOpTable interfaces) source
-- determine if default imports should be added
-- only elm-lang/core is exempt
let needsDefaults =
not (user == "elm-lang" && projectName == "core")
-- add default imports if necessary
let rawModule =
DefaultImports.add needsDefaults parsedModule
-- validate module (e.g. all variables exist)
case Check.mistakes (Module.body rawModule) of
[] -> return ()
ms -> Left ms
-- Canonicalize all variables, pinning down where they came from.
canonicalModule <- Canonical.module' interfaces rawModule
-- Run type inference on the program.
types <- TI.infer interfaces canonicalModule
-- Add the real list of tyes
let body = (Module.body canonicalModule) { Module.types = types }
return $ canonicalModule { Module.body = body }
getOpTable :: Module.Interfaces -> Parse.OpTable
getOpTable interfaces =
Map.elems interfaces
|> concatMap Module.iFixities
|> map (\(assoc,lvl,op) -> (op,(lvl,assoc)))
|> Map.fromList | avh4/elm-compiler | src/Compile.hs | bsd-3-clause | 1,763 | 0 | 14 | 404 | 404 | 225 | 179 | 38 | 2 |
{-# LANGUAGE PatternGuards, FlexibleContexts, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Eval
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Andrea Rossato <andrea.rossato@unitn.it>
-- Stability : unstable
-- Portability : unportable
--
-- The CSL implementation
--
-----------------------------------------------------------------------------
module Text.CSL.Eval
( evalLayout
, evalSorting
, module Text.CSL.Eval.Common
, module Text.CSL.Eval.Output
) where
import Control.Arrow
import Control.Monad.State
import Data.Monoid (Any(..))
import Data.Char ( toLower, isDigit, isLetter )
import Data.Maybe
import Data.String ( fromString )
import Text.Pandoc.Definition (Inline(Str, Link), nullAttr)
import Text.Pandoc.Walk (walk)
import Text.Pandoc.Shared (stringify)
import qualified Data.Text as T
import Text.CSL.Eval.Common
import Text.CSL.Eval.Output
import Text.CSL.Eval.Date
import Text.CSL.Eval.Names
import Text.CSL.Output.Plain
import Text.CSL.Reference
import Text.CSL.Style hiding (Any)
import Text.CSL.Util ( readNum, last', proc, proc', query, betterThan,
safeRead, isRange )
-- | Produce the output with a 'Layout', the 'EvalMode', a 'Bool'
-- 'True' if the evaluation happens for disambiguation purposes, the
-- 'Locale', the 'MacroMap', the position of the cite and the
-- 'Reference'.
evalLayout :: Layout -> EvalMode -> Bool -> [Locale] -> [MacroMap]
-> [Option] -> Abbreviations -> Maybe Reference -> [Output]
evalLayout (Layout _ _ es) em b l m o a mbr
= cleanOutput evalOut
where
evalOut = case evalState job initSt of
x | isNothing mbr -> [noBibDataError cit]
| null x -> []
| otherwise -> suppTC x
locale = case l of
[x] -> x
_ -> Locale [] [] [] [] []
job = evalElements es
cit = case em of
EvalCite c -> c
EvalSorting c -> c
EvalBiblio c -> c
initSt = EvalState (mkRefMap mbr) (Env cit (localeTerms locale) m
(localeDate locale) o [] a) [] em b False [] [] False [] [] []
suppTC = let getLang = take 2 . map toLower in
case (getLang $ localeLang locale,
getLang . unLiteral . language <$> mbr) of
(_, Just "en") -> id
(_, Nothing) -> id
("en", Just "") -> id
_ -> proc' rmTitleCase
evalSorting :: EvalMode -> [Locale] -> [MacroMap] -> [Option] ->
[Sort] -> Abbreviations -> Maybe Reference -> [Sorting]
evalSorting m l ms opts ss as mbr
= map (format . sorting) ss
where
render = renderPlain . formatOutputList
format (s,e) = applaySort s . render $ uncurry eval e
eval o e = evalLayout (Layout emptyFormatting [] [e]) m False l ms o as mbr
applaySort c s
| Ascending {} <- c = Ascending s
| otherwise = Descending s
unsetOpts ("et-al-min" ,_) = ("et-al-min" ,"")
unsetOpts ("et-al-use-first" ,_) = ("et-al-use-first" ,"")
unsetOpts ("et-al-subsequent-min" ,_) = ("et-al-subsequent-min","")
unsetOpts ("et-al-subsequent-use-first",_) = ("et-al-subsequent-use-first","")
unsetOpts x = x
setOpts s i = if i /= 0 then (s, show i) else ([],[])
sorting s
= case s of
SortVariable str s' -> (s', ( ("name-as-sort-order","all") : opts
, Variable [str] Long emptyFormatting []))
SortMacro str s' a b c -> (s', ( setOpts "et-al-min" a : ("et-al-use-last",c) :
setOpts "et-al-use-first" b : proc unsetOpts opts
, Macro str emptyFormatting))
evalElements :: [Element] -> State EvalState [Output]
evalElements = concatMapM evalElement
evalElement :: Element -> State EvalState [Output]
evalElement el
| Const s fm <- el = return $ addSpaces s
$ if fm == emptyFormatting
then [OPan (readCSLString s)]
else [Output [OPan (readCSLString s)] fm]
-- NOTE: this conditional seems needed for
-- locator_SimpleLocators.json:
| Number s f fm <- el = if s == "locator"
then getLocVar >>= formatRange fm . snd
else formatNumber f fm s =<<
getStringVar s
| Variable s f fm d <- el = return . addDelim d =<< concatMapM (getVariable f fm) s
| Group fm d l <- el = outputList fm d <$> tryGroup l
| Date _ _ _ _ _ _ <- el = evalDate el
| Label s f fm _ <- el = formatLabel f fm True s -- FIXME !!
| Term s f fm p <- el = formatTerm f fm p s
| Names s n fm d sub <- el = modify (\st -> st { contNum = [] }) >>
ifEmpty (evalNames False s n d)
(withNames s el $ evalElements sub)
(appendOutput fm)
| Substitute (e:els) <- el = do
res <- consuming $ substituteWith e
if null res
then if null els
then return [ONull]
else evalElement (Substitute els)
else return res
-- All macros and conditionals should have been expanded
| Choose i ei xs <- el = do
res <- evalIfThen i ei xs
evalElements res
| Macro s fm <- el = do
ms <- gets (macros . env)
case lookup s ms of
Nothing -> error $ "Macro " ++ show s ++ " not found!"
Just els -> do
res <- concat <$> mapM evalElement els
if null res
then return []
else return [Output res fm]
| otherwise = return []
where
addSpaces strng = (if take 1 strng == " " then (OSpace:) else id) .
(if last' strng == " " then (++[OSpace]) else id)
substituteWith e = head <$> gets (names . env) >>= \(Names _ ns fm d _) -> do
case e of
Names rs [Name NotSet fm'' [] [] []] fm' d' []
-> let nfm = mergeFM fm'' $ mergeFM fm' fm in
evalElement $ Names rs ns nfm (d' `betterThan` d) []
_ -> evalElement e
-- from citeproc documentation: "cs:group implicitly acts as a
-- conditional: cs:group and its child elements are suppressed if
-- a) at least one rendering element in cs:group calls a variable
-- (either directly or via a macro), and b) all variables that are
-- called are empty. This accommodates descriptive cs:text elements."
-- TODO: problem, this approach gives wrong results when the variable
-- is in a conditional and the other branch is followed. the term
-- provided by the other branch (e.g. 'n.d.') is not printed. we
-- should ideally expand conditionals when we expand macros.
tryGroup l = if getAny $ query hasVar l
then do
oldState <- get
res <- evalElements (rmTermConst l)
put oldState
let numVars = [s | Number s _ _ <- l]
nums <- mapM getStringVar numVars
let pluralizeTerm (Term s f fm _) = Term s f fm $
case numVars of
["number-of-volumes"] -> not $ any (== "1") nums
["number-of-pages"] -> not $ any (== "1") nums
_ -> any isRange nums
pluralizeTerm x = x
if null res
then return []
else evalElements $ map pluralizeTerm l
else evalElements l
hasVar e
| Variable {} <- e = Any True
| Date {} <- e = Any True
| Names {} <- e = Any True
| Number {} <- e = Any True
| otherwise = Any False
rmTermConst = proc $ filter (not . isTermConst)
isTermConst e
| Term {} <- e = True
| Const {} <- e = True
| otherwise = False
ifEmpty p t e = p >>= \r -> if r == [] then t else return (e r)
withNames e n f = modify (\s -> s { authSub = e ++ authSub s
, env = (env s)
{names = n : names (env s)}}) >> f >>= \r ->
modify (\s -> s { authSub = filter (not . flip elem e) (authSub s)
, env = (env s)
{names = tail $ names (env s)}}) >> return r
getVariable f fm s
| isTitleVar s || isTitleShortVar s =
consumeVariable s >> formatTitle s f fm
| otherwise =
case map toLower s of
"year-suffix" -> getStringVar "ref-id" >>= \k ->
return . return $ OYearSuf [] k [] fm
"page" -> getStringVar "page" >>= formatRange fm
"locator" -> getLocVar >>= formatRange fm . snd
"url" -> getStringVar "url" >>= \k ->
if null k then return [] else return [Output [OPan [Link nullAttr [Str k] (k,"")]] fm]
"doi" -> do d <- getStringVar "doi"
let (prefixPart, linkPart) = T.breakOn (T.pack "http") (T.pack (prefix fm))
let u = if T.null linkPart
then "https://doi.org/" ++ d
else T.unpack linkPart ++ d
if null d
then return []
else return [Output [OPan [Link nullAttr [Str (T.unpack linkPart ++ d)] (u, "")]]
fm{ prefix = T.unpack prefixPart, suffix = suffix fm }]
"pmid" -> getStringVar "pmid" >>= \d ->
if null d
then return []
else return [Output [OPan [Link nullAttr [Str d] ("http://www.ncbi.nlm.nih.gov/pubmed/" ++ d, "")]] fm]
"pmcid" -> getStringVar "pmcid" >>= \d ->
if null d
then return []
else return [Output [OPan [Link nullAttr [Str d] ("http://www.ncbi.nlm.nih.gov/pmc/articles/" ++ d, "")]] fm]
_ -> do (opts, as) <- gets (env >>> options &&& abbrevs)
r <- getVar []
(getFormattedValue opts as f fm s) s
consumeVariable s
return r
evalIfThen :: IfThen -> [IfThen] -> [Element] -> State EvalState [Element]
evalIfThen (IfThen c' m' el') ei e = whenElse (evalCond m' c') (return el') rest
where
rest = case ei of
[] -> return e
(x:xs) -> evalIfThen x xs e
evalCond m c = do t <- checkCond chkType isType c m
v <- checkCond isVarSet isSet c m
n <- checkCond chkNumeric isNumeric c m
d <- checkCond chkDate isUncertainDate c m
p <- checkCond chkPosition isPosition c m
a <- checkCond chkDisambiguate disambiguation c m
l <- checkCond chkLocator isLocator c m
return $ match m $ concat [t,v,n,d,p,a,l]
checkCond a f c m = case f c of
[] -> case m of
All -> return [True]
_ -> return [False]
xs -> mapM a xs
chkType t = let chk = (==) (formatVariable t) . show . fromMaybe NoType . fromValue
in getVar False chk "ref-type"
chkNumeric v = do val <- getStringVar v
as <- gets (abbrevs . env)
let val' = if getAbbreviation as v val == [] then val else getAbbreviation as v val
return (isNumericString val')
chkDate v = getDateVar v >>= return . not . null . filter circa
chkPosition s = if s == "near-note"
then gets (nearNote . cite . env)
else gets (citePosition . cite . env) >>= return . compPosition s
chkDisambiguate s = gets disamb >>= return . (==) (formatVariable s) . map toLower . show
chkLocator v = getLocVar >>= return . (==) v . fst
isIbid s = not (s == "first" || s == "subsequent")
compPosition a b
| "first" <- a = b == "first"
| "subsequent" <- a = b /= "first"
| "ibid-with-locator" <- a = b == "ibid-with-locator" ||
b == "ibid-with-locator-c"
| otherwise = isIbid b
getFormattedValue :: [Option] -> Abbreviations -> Form -> Formatting -> String -> Value -> [Output]
getFormattedValue o as f fm s val
| Just v <- fromValue val :: Maybe Formatted =
if v == mempty
then []
else let ys = maybe (unFormatted v) (unFormatted . fromString)
$ getAbbr (stringify $ unFormatted v)
in if null ys
then []
else [Output [OPan $ walk value' ys] fm]
| Just v <- fromValue val :: Maybe String = (:[]) . flip OStr fm . maybe v id . getAbbr $ value v
| Just v <- fromValue val :: Maybe Literal = (:[]) . flip OStr fm . maybe (unLiteral v) id . getAbbr $ value $ unLiteral v
| Just v <- fromValue val :: Maybe Int = output fm (if v == 0 then [] else show v)
| Just v <- fromValue val :: Maybe Int = output fm (if v == 0 then [] else show v)
| Just v <- fromValue val :: Maybe CNum = if v == 0 then [] else [OCitNum (unCNum v) fm]
| Just v <- fromValue val :: Maybe [RefDate] = formatDate (EvalSorting emptyCite) [] [] sortDate v
| Just v <- fromValue val :: Maybe [Agent] = concatMap (formatName (EvalSorting emptyCite) True f
fm nameOpts []) v
| otherwise = []
where
value = if stripPeriods fm then filter (/= '.') else id
value' (Str x) = Str (value x)
value' x = x
getAbbr v = if f == Short
then case getAbbreviation as s v of
[] -> Nothing
y -> Just y
else Nothing
nameOpts = ("name-as-sort-order","all") : o
sortDate = [ DatePart "year" "numeric-leading-zeros" "" emptyFormatting
, DatePart "month" "numeric-leading-zeros" "" emptyFormatting
, DatePart "day" "numeric-leading-zeros" "" emptyFormatting]
formatTitle :: String -> Form -> Formatting -> State EvalState [Output]
formatTitle s f fm
| Short <- f
, isTitleVar s = try (getIt $ s ++ "-short") $ getIt s
| isTitleShortVar s = try (getIt s) $ return . (:[]) . flip OStr fm =<< getTitleShort s
| otherwise = getIt s
where
try g h = g >>= \r -> if r == [] then h else return r
getIt x = do
o <- gets (options . env)
a <- gets (abbrevs . env)
getVar [] (getFormattedValue o a f fm x) x
formatNumber :: NumericForm -> Formatting -> String -> String -> State EvalState [Output]
formatNumber f fm v n
= gets (abbrevs . env) >>= \as ->
if isNumericString (getAbbr as n)
then gets (terms . env) >>=
return . output fm . flip process (getAbbr as n)
else return . output fm . getAbbr as $ n
where
getAbbr as = if getAbbreviation as v n == [] then id else getAbbreviation as v
checkRange' ts = if v == "page" then checkRange ts else id
process ts = checkRange' ts . printNumStr . map (renderNumber ts) .
breakNumericString . words
renderNumber ts x = if isTransNumber x then format ts x else x
format tm = case f of
Ordinal -> ordinal tm v
LongOrdinal -> longOrdinal tm v
Roman -> if readNum n < 6000 then roman else id
_ -> id
roman = foldr (++) [] . reverse . map (uncurry (!!)) . zip romanList .
map (readNum . return) . take 4 . reverse
romanList = [[ "", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix" ]
,[ "", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc" ]
,[ "", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm" ]
,[ "", "m", "mm", "mmm", "mmmm", "mmmmm"]
]
checkRange :: [CslTerm] -> String -> String
checkRange _ [] = []
checkRange ts (x:xs) = if x == '-' || x == '\x2013'
then pageRange ts ++ checkRange ts xs
else x : checkRange ts xs
printNumStr :: [String] -> String
printNumStr [] = []
printNumStr (x:[]) = x
printNumStr (x:"-":y:xs) = x ++ "-" ++ y ++ printNumStr xs
printNumStr (x:",":y:xs) = x ++ ", " ++ y ++ printNumStr xs
printNumStr (x:xs)
| x == "-" = x ++ printNumStr xs
| otherwise = x ++ " " ++ printNumStr xs
pageRange :: [CslTerm] -> String
pageRange = maybe "\x2013" termPlural . findTerm "page-range-delimiter" Long
isNumericString :: String -> Bool
isNumericString [] = False
isNumericString s = all (\c -> isNumber c || isSpecialChar c) $ words s
isTransNumber, isSpecialChar,isNumber :: String -> Bool
isTransNumber = all isDigit
isSpecialChar = all (`elem` "&-,.\x2013")
isNumber cs = case [c | c <- cs
, not (isLetter c)
, not (c `elem` "&-.,\x2013")] of
[] -> False
xs -> all isDigit xs
breakNumericString :: [String] -> [String]
breakNumericString [] = []
breakNumericString (x:xs)
| isTransNumber x = x : breakNumericString xs
| otherwise = let (a,b) = break (`elem` "&-\x2013,") x
(c,d) = if null b
then ("","")
else span (`elem` "&-\x2013,") b
in filter (/= []) $ a : c : breakNumericString (d : xs)
formatRange :: Formatting -> String -> State EvalState [Output]
formatRange _ [] = return []
formatRange fm p = do
ops <- gets (options . env)
ts <- gets (terms . env)
let opt = getOptionVal "page-range-format" ops
pages = tupleRange . breakNumericString . words $ p
tupleRange [] = []
tupleRange (x:cs:[] )
| cs `elem` ["-", "--", "\x2013"] = return (x,[])
tupleRange (x:cs:y:xs)
| cs `elem` ["-", "--", "\x2013"] = (x, y) : tupleRange xs
tupleRange (x: xs) = (x,[]) : tupleRange xs
joinRange (a, []) = a
joinRange (a, b) = a ++ "-" ++ b
process = checkRange ts . printNumStr . case opt of
"expanded" -> map (joinRange . expandedRange)
"chicago" -> map (joinRange . chicagoRange )
"minimal" -> map (joinRange . minimalRange 1)
"minimal-two" -> map (joinRange . minimalRange 2)
_ -> map joinRange
return [flip OLoc fm $ [OStr (process pages) emptyFormatting]]
-- Abbreviated page ranges are expanded to their non-abbreviated form:
-- 42–45, 321–328, 2787–2816
expandedRange :: (String, String) -> (String, String)
expandedRange (sa, []) = (sa,[])
expandedRange (sa, sb)
| length sb < length sa =
case (safeRead sa, safeRead sb) of
-- check to make sure we have regular numbers
(Just (_ :: Int), Just (_ :: Int)) ->
(sa, take (length sa - length sb) sa ++ sb)
_ -> (sa, sb)
| otherwise = (sa, sb)
-- All digits repeated in the second number are left out:
-- 42–5, 321–8, 2787–816. The minDigits parameter indicates
-- a minimum number of digits for the second number; thus, with
-- minDigits = 2, we have 328-28.
minimalRange :: Int -> (String, String) -> (String, String)
minimalRange minDigits ((a:as), (b:bs))
| a == b
, length as == length bs
, length bs >= minDigits =
let (_, bs') = minimalRange minDigits (as, bs)
in (a:as, bs')
minimalRange _ (as, bs) = (as, bs)
-- Page ranges are abbreviated according to the Chicago Manual of Style-rules:
-- First number Second number Examples
-- Less than 100 Use all digits 3–10; 71–72
-- 100 or multiple of 100 Use all digits 100–104; 600–613; 1100–1123
-- 101 through 109 (in multiples of 100) Use changed part only 10002-6, 505-17
-- 110 through 199 Use 2 digits or more 321-25, 415-532
-- if numbers are 4 digits long or more and 3 digits change, use all digits
-- 1496-1504
chicagoRange :: (String, String) -> (String, String)
chicagoRange (sa, sb)
= case (safeRead sa :: Maybe Int) of
Just n | n < 100 -> expandedRange (sa, sb)
| n `mod` 100 == 0 -> expandedRange (sa, sb)
| n >= 1000 -> let (sa', sb') = minimalRange 1 (sa, sb)
in if length sb' >= 3
then expandedRange (sa, sb)
else (sa', sb')
| n > 100 -> if n `mod` 100 < 10
then minimalRange 1 (sa, sb)
else minimalRange 2 (sa, sb)
_ -> expandedRange (sa, sb)
| jkr/pandoc-citeproc | src/Text/CSL/Eval.hs | bsd-3-clause | 22,995 | 8 | 26 | 9,405 | 7,104 | 3,629 | 3,475 | 379 | 28 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
module Onedrive.Types.LocationFacet where
import Control.Lens (makeLensesWith, camelCaseFields)
import Data.Aeson (FromJSON(parseJSON), Value(Object), (.:))
data LocationFacet =
LocationFacet
{ locationFacetAttitude :: Double
, locationFacetLatitude :: Double
, locationFacetLongitude :: Double
} deriving (Show)
instance FromJSON LocationFacet where
parseJSON (Object o) =
LocationFacet <$> o .: "attitude" <*> o .: "latitude" <*> o .: "longitude"
parseJSON _ =
error "Invalid LocationFacet JSON"
makeLensesWith camelCaseFields ''LocationFacet
| asvyazin/hs-onedrive | src/Onedrive/Types/LocationFacet.hs | bsd-3-clause | 722 | 0 | 11 | 108 | 151 | 88 | 63 | 19 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Fiber
( Path
, Fiber (..)
, equal
, include
) where
import Data.Aeson (FromJSON (..), ToJSON (..), Value (..),
object, (.:), (.=))
import Data.Aeson.Types (Parser)
import Data.Text (Text)
-- | Path
type Path = Text
-- | Fiber
data Fiber = Equal !Path !Value
| Include !Path !Value
deriving (Eq, Show)
instance FromJSON Fiber where
parseJSON (Object v) = do
typ <- v .: "type" :: Parser Text
case typ of
"equal" -> Equal <$> v .: "path" <*> v .: "value"
"include" -> Include <$> v .: "path" <*> v .: "value"
_ -> fail "parseJSON: unknown declaration type"
parseJSON _ = fail "parseJSON: failed to parse a JSON into Fiber"
instance ToJSON Fiber where
toJSON (Equal path value) = object [ "type" .= ("equal" :: Text)
, "path" .= path
, "value" .= value ]
toJSON (Include path value) = object [ "type" .= ("include" :: Text)
, "path" .= path
, "value" .= value ]
equal :: ToJSON a => Path -> a -> Fiber
equal path value = Equal path (toJSON value)
include :: ToJSON a => Path -> a -> Fiber
include path value = Include path (toJSON value)
| yuttie/fibers | Fiber.hs | bsd-3-clause | 1,449 | 0 | 14 | 572 | 418 | 227 | 191 | 41 | 1 |
module Clipboard
( copyToClipboard
)
where
import Prelude ()
import Prelude.MH
import Control.Exception ( try )
import qualified Data.Text as T
import System.Hclip ( setClipboard, ClipboardException(..) )
import Types
copyToClipboard :: Text -> MH ()
copyToClipboard txt = do
result <- liftIO (try (setClipboard (T.unpack txt)))
case result of
Left e -> do
let errMsg = case e of
UnsupportedOS _ ->
"Matterhorn does not support yanking on this operating system."
NoTextualData ->
"Textual data is required to set the clipboard."
MissingCommands cmds ->
"Could not set clipboard due to missing one of the " <>
"required program(s): " <> (T.pack $ show cmds)
mhError $ ClipboardError errMsg
Right () ->
return ()
| aisamanra/matterhorn | src/Clipboard.hs | bsd-3-clause | 892 | 0 | 21 | 294 | 209 | 108 | 101 | 24 | 4 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.State.Strict
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (multi-param classes, functional dependencies)
--
-- Strict state monads.
--
-- This module is inspired by the paper
-- /Functional Programming with Overloading and Higher-Order Polymorphism/,
-- Mark P Jones (<http://web.cecs.pdx.edu/~mpj/>)
-- Advanced School of Functional Programming, 1995.
-----------------------------------------------------------------------------
module Control.Monad.State.Strict (
-- * MonadState class
MonadState(..),
modify,
gets,
-- * The State monad
State,
runState,
evalState,
execState,
mapState,
withState,
-- * The StateT monad transformer
StateT(..),
evalStateT,
execStateT,
mapStateT,
withStateT,
module Control.Monad,
module Control.Monad.Fix,
module Control.Monad.Trans,
-- * Examples
-- $examples
) where
import Control.Monad.State.Class
import Control.Monad.Trans
import Control.Monad.Trans.State.Strict
(State, runState, evalState, execState, mapState, withState,
StateT(..), evalStateT, execStateT, mapStateT, withStateT)
import Control.Monad
import Control.Monad.Fix
-- ---------------------------------------------------------------------------
-- $examples
-- A function to increment a counter. Taken from the paper
-- /Generalising Monads to Arrows/, John
-- Hughes (<http://www.math.chalmers.se/~rjmh/>), November 1998:
--
-- > tick :: State Int Int
-- > tick = do n <- get
-- > put (n+1)
-- > return n
--
-- Add one to the given number using the state monad:
--
-- > plusOne :: Int -> Int
-- > plusOne n = execState tick n
--
-- A contrived addition example. Works only with positive numbers:
--
-- > plus :: Int -> Int -> Int
-- > plus n x = execState (sequence $ replicate n tick) x
--
-- An example from /The Craft of Functional Programming/, Simon
-- Thompson (<http://www.cs.kent.ac.uk/people/staff/sjt/>),
-- Addison-Wesley 1999: \"Given an arbitrary tree, transform it to a
-- tree of integers in which the original elements are replaced by
-- natural numbers, starting from 0. The same element has to be
-- replaced by the same number at every occurrence, and when we meet
-- an as-yet-unvisited element we have to find a \'new\' number to match
-- it with:\"
--
-- > data Tree a = Nil | Node a (Tree a) (Tree a) deriving (Show, Eq)
-- > type Table a = [a]
--
-- > numberTree :: Eq a => Tree a -> State (Table a) (Tree Int)
-- > numberTree Nil = return Nil
-- > numberTree (Node x t1 t2)
-- > = do num <- numberNode x
-- > nt1 <- numberTree t1
-- > nt2 <- numberTree t2
-- > return (Node num nt1 nt2)
-- > where
-- > numberNode :: Eq a => a -> State (Table a) Int
-- > numberNode x
-- > = do table <- get
-- > (newTable, newPos) <- return (nNode x table)
-- > put newTable
-- > return newPos
-- > nNode:: (Eq a) => a -> Table a -> (Table a, Int)
-- > nNode x table
-- > = case (findIndexInList (== x) table) of
-- > Nothing -> (table ++ [x], length table)
-- > Just i -> (table, i)
-- > findIndexInList :: (a -> Bool) -> [a] -> Maybe Int
-- > findIndexInList = findIndexInListHelp 0
-- > findIndexInListHelp _ _ [] = Nothing
-- > findIndexInListHelp count f (h:t)
-- > = if (f h)
-- > then Just count
-- > else findIndexInListHelp (count+1) f t
--
-- numTree applies numberTree with an initial state:
--
-- > numTree :: (Eq a) => Tree a -> Tree Int
-- > numTree t = evalState (numberTree t) []
--
-- > testTree = Node "Zero" (Node "One" (Node "Two" Nil Nil) (Node "One" (Node "Zero" Nil Nil) Nil)) Nil
-- > numTree testTree => Node 0 (Node 1 (Node 2 Nil Nil) (Node 1 (Node 0 Nil Nil) Nil)) Nil
--
-- sumTree is a little helper function that does not use the State monad:
--
-- > sumTree :: (Num a) => Tree a -> a
-- > sumTree Nil = 0
-- > sumTree (Node e t1 t2) = e + (sumTree t1) + (sumTree t2)
| davnils/minijava-compiler | lib/mtl-2.1.3.1/Control/Monad/State/Strict.hs | bsd-3-clause | 4,395 | 0 | 6 | 1,055 | 248 | 200 | 48 | 25 | 0 |
{-# language CPP #-}
-- No documentation found for Chapter "OpenXR"
module OpenXR ( module OpenXR.CStruct
, module OpenXR.Core10
, module OpenXR.Extensions
, module OpenXR.NamedType
, module OpenXR.Version
) where
import OpenXR.CStruct
import OpenXR.Core10
import OpenXR.Extensions
import OpenXR.NamedType
import OpenXR.Version
| expipiplus1/vulkan | openxr/src/OpenXR.hs | bsd-3-clause | 405 | 0 | 5 | 117 | 63 | 41 | 22 | 11 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Feldspar.Software.Marshal where -- based on raw-feldspar/run/marshal
import Feldspar.Frontend (Finite(..), Indexed(..), Arrays(..), IArrays(..), value, shareM, for)
import Feldspar.Array.Vector (Manifest(..))
import Feldspar.Software (Syntax, Internal, Software, SType', SExp)
import Feldspar.Software.Primitive (SoftwarePrimType)
import Feldspar.Software.Representation (Arr, IArr)
import Feldspar.Software.Frontend (fput, fget, fprintf)
import Language.Embedded.Imperative.CMD (Formattable, Handle, stdout, stdin)
import Data.Typeable
import Data.Int
import Data.Word
import Control.Monad (ap, replicateM)
import qualified Prelude as P
import Prelude hiding (length)
--------------------------------------------------------------------------------
-- *
--------------------------------------------------------------------------------
newtype Parser a = Parser {runParser :: String -> (a,String)}
instance Functor Parser
where
fmap = (<$>)
instance Applicative Parser
where
pure = return
(<*>) = ap
instance Monad Parser
where
return a = Parser $ \s -> (a,s)
(>>=) p k = Parser $ \s -> let (a,s') = runParser p s in runParser (k a) s'
readParser :: forall a . (Read a, Typeable a) => Parser a
readParser = Parser $ \s -> case reads s of
[(a,s')] -> (a,s')
_ -> error $ "cannot read " ++ show s
parse :: Parser a -> String -> a
parse = (fst .) . runParser
--------------------------------------------------------------------------------
-- **
class MarshalHaskell a
where
fromHaskell :: a -> String
default fromHaskell :: Show a => a -> String
fromHaskell = show
toHaskell :: Parser a
default toHaskell :: (Read a, Typeable a) => Parser a
toHaskell = readParser
instance MarshalHaskell Int
instance MarshalHaskell Int8
instance MarshalHaskell Int16
instance MarshalHaskell Int32
instance MarshalHaskell Int64
instance MarshalHaskell Word
instance MarshalHaskell Word8
instance MarshalHaskell Word16
instance MarshalHaskell Word32
instance MarshalHaskell Word64
instance (MarshalHaskell a, MarshalHaskell b) => MarshalHaskell (a,b)
where
fromHaskell (a,b) = unwords [fromHaskell a, fromHaskell b]
toHaskell = (,) <$> toHaskell <*> toHaskell
instance MarshalHaskell a => MarshalHaskell [a]
where
fromHaskell as = unwords $ show (P.length as) : map fromHaskell as
toHaskell = do
len <- toHaskell
replicateM len toHaskell
--------------------------------------------------------------------------------
-- **
class MarshalHaskell (Haskelly a) => MarshalFeldspar a
where
type Haskelly a
fwrite :: Handle -> a -> Software ()
default fwrite :: (SType' b, Formattable b, a ~ SExp b) => Handle -> a -> Software ()
fwrite h i = fput h "" i ""
fread :: Handle -> Software a
default fread :: (SType' b, Formattable b, a ~ SExp b) => Handle -> Software a
fread = fget
writeStd :: MarshalFeldspar a => a -> Software ()
writeStd = fwrite stdout
readStd :: MarshalFeldspar a => Software a
readStd = fread stdin
instance MarshalFeldspar (SExp Int8) where type Haskelly (SExp Int8) = Int8
instance MarshalFeldspar (SExp Int16) where type Haskelly (SExp Int16) = Int16
instance MarshalFeldspar (SExp Int32) where type Haskelly (SExp Int32) = Int32
instance MarshalFeldspar (SExp Int64) where type Haskelly (SExp Int64) = Int64
instance MarshalFeldspar (SExp Word8) where type Haskelly (SExp Word8) = Word8
instance MarshalFeldspar (SExp Word16) where type Haskelly (SExp Word16) = Word16
instance MarshalFeldspar (SExp Word32) where type Haskelly (SExp Word32) = Word32
instance MarshalFeldspar (SExp Word64) where type Haskelly (SExp Word64) = Word64
instance (MarshalFeldspar a, MarshalFeldspar b) => MarshalFeldspar (a,b)
where
type Haskelly (a,b) = (Haskelly a, Haskelly b)
fwrite h (a,b) = fwrite h a >> fprintf h " " >> fwrite h b
fread h = (,) <$> fread h <*> fread h
--------------------------------------------------------------------------------
-- **
instance (MarshalHaskell (Internal a), MarshalFeldspar a, Syntax SExp a) => MarshalFeldspar (Arr a)
where
type Haskelly (Arr a) = [Internal a]
fwrite h arr = do
len :: SExp Word32 <- shareM (length arr)
fput h "" len ""
for 0 1 (len-1) $ \i -> do
a <- getArr arr i
fwrite h a
fprintf h " "
fread h = do
len <- fget h
arr <- newArr len
for 0 1 (len-1) $ \i -> do
a <- fread h
setArr arr i a
return arr
instance (MarshalHaskell (Internal a), MarshalFeldspar a, Syntax SExp a) => MarshalFeldspar (IArr a)
where
type Haskelly (IArr a) = [Internal a]
fwrite h arr = do
len :: SExp Word32 <- shareM (length arr)
fput h "" len ""
for 0 1 (len-1) $ \i -> do
fwrite h ((!) arr i)
fprintf h " "
fread h = do
len <- fget h
arr <- newArr len
for 0 1 (len-1) $ \i -> do
a <- fread h
setArr arr i a
iarr <- unsafeFreezeArr arr
return iarr
instance (MarshalHaskell (Internal a), MarshalFeldspar a, Syntax SExp a) => MarshalFeldspar (Manifest Software a)
where
type Haskelly (Manifest Software a) = [Internal a]
fwrite h arr = do
len :: SExp Word32 <- shareM (length arr)
fput h "" len ""
for 0 1 (len-1) $ \i -> do
let iarr = manifest arr
fwrite h ((!) iarr i)
fprintf h " "
fread h = do
len <- fget h
arr <- newArr len
for 0 1 (len-1) $ \i -> do
a <- fread h
setArr arr i a
iarr <- unsafeFreezeArr arr
return (M iarr)
--------------------------------------------------------------------------------
-- **
connectStdIO :: (MarshalFeldspar a, MarshalFeldspar b) => (a -> Software b) -> Software ()
connectStdIO f = (readStd >>= f) >>= writeStd
--------------------------------------------------------------------------------
| markus-git/co-feldspar | src/Feldspar/Software/Marshal.hs | bsd-3-clause | 6,182 | 0 | 15 | 1,370 | 2,162 | 1,112 | 1,050 | 135 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
module River.Source.Analysis.Scope (
Scope(..)
, scopedProgram
, scopedBlock
, scopedStatement
) where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import River.Map
import River.Source.Annotation
import River.Source.Syntax
data Scope a =
Scope {
scopeDeclared :: !(Map Identifier a)
, scopeDefined :: !(Map Identifier (Set a))
, scopeLive :: !(Map Identifier (Set a))
, scopeTail :: !a
} deriving (Eq, Ord, Show)
replaceTail :: a -> Scope a -> Scope a
replaceTail a scope =
scope {
scopeTail = a
}
scopedProgram :: Ord a => Program a -> Program (Scope a)
scopedProgram = \case
Program a0 b0 ->
let
b =
scopedBlock Map.empty b0
a =
replaceTail a0 (annotOfBlock b)
in
Program a b
scopedBlock :: Ord a => Map Identifier a -> Block a -> Block (Scope a)
scopedBlock declared = \case
Block a0 [] ->
let
a =
Scope declared Map.empty Map.empty a0
in
Block a []
Block a0 (s0 : t0) ->
let
s =
scopedStatement declared s0
s_scope =
annotOfStatement s
Block t_scope t =
scopedBlock declared (Block a0 t0)
-- Defined Variables --
s_defined =
scopeDefined s_scope
t_defined =
scopeDefined t_scope
defined =
s_defined `mapSetUnion` t_defined
-- Live Variables --
s_live =
scopeLive s_scope
t_live =
scopeLive t_scope `Map.difference` s_defined
live =
s_live `mapSetUnion` t_live
-- Complete Scope --
a =
Scope declared defined live a0
in
Block a (s : t)
scopedStatement :: Ord a => Map Identifier a -> Statement a -> Statement (Scope a)
scopedStatement declared = \case
Declare a0 t n b0 ->
let
b =
scopedBlock (Map.insert n a0 declared) b0
b_scope =
annotOfBlock b
defined =
Map.delete n $ scopeDefined b_scope
live =
Map.delete n $ scopeLive b_scope
a =
Scope declared defined live a0
in
Declare a t n b
Assign a0 n x0 ->
let
x =
scopedExpression declared x0
x_scope =
annotOfExpression x
defined =
mapSetSingleton n a0
live =
scopeLive x_scope
a =
Scope declared defined live a0
in
Assign a n x
If a0 i0 t0 e0 ->
let
i =
scopedExpression declared i0
t =
scopedBlock declared t0
e =
scopedBlock declared e0
i_scope =
annotOfExpression i
t_scope =
annotOfBlock t
e_scope =
annotOfBlock e
defined =
scopeDefined t_scope `mapSetIntersection`
scopeDefined e_scope
live =
scopeLive i_scope `mapSetUnion`
scopeLive t_scope `mapSetUnion`
scopeLive e_scope
a =
Scope declared defined live a0
in
If a i t e
While a0 x0 b0 ->
let
x =
scopedExpression declared x0
b =
scopedBlock declared b0
x_scope =
annotOfExpression x
b_scope =
annotOfBlock b
defined =
Map.empty
live =
scopeLive x_scope `mapSetUnion`
scopeLive b_scope
a =
Scope declared defined live a0
in
While a x b
Return a0 x0 ->
let
x =
scopedExpression declared x0
x_scope =
annotOfExpression x
-- Returning defines all variables in scope, because it transfers control
-- out of the scope.
defined =
Map.map (const $ Set.singleton a0) declared
live =
scopeLive x_scope
a =
Scope declared defined live a0
in
Return a x
scopedExpression :: Ord a => Map Identifier a -> Expression a -> Expression (Scope a)
scopedExpression declared = \case
Literal a0 l ->
let
a =
Scope declared Map.empty Map.empty a0
in
Literal a l
Variable a0 n ->
let
live =
mapSetSingleton n a0
a =
Scope declared Map.empty live a0
in
Variable a n
Unary a0 op x0 ->
let
x =
scopedExpression declared x0
live =
scopeLive (annotOfExpression x)
a =
Scope declared Map.empty live a0
in
Unary a op x
Binary a0 op x0 y0 ->
let
x =
scopedExpression declared x0
y =
scopedExpression declared y0
live =
scopeLive (annotOfExpression x) `mapSetUnion`
scopeLive (annotOfExpression y)
a =
Scope declared Map.empty live a0
in
Binary a op x y
Conditional a0 i0 t0 e0 ->
let
i =
scopedExpression declared i0
t =
scopedExpression declared t0
e =
scopedExpression declared e0
live =
scopeLive (annotOfExpression i) `mapSetUnion`
scopeLive (annotOfExpression t) `mapSetUnion`
scopeLive (annotOfExpression e)
a =
Scope declared Map.empty live a0
in
Conditional a i t e
| jystic/river | src/River/Source/Analysis/Scope.hs | bsd-3-clause | 5,280 | 0 | 16 | 1,963 | 1,518 | 757 | 761 | 205 | 5 |
module Main where
-- References:
--
-- https://hackage.haskell.org/package/implicit-0.0.5/docs/Graphics-Implicit.html
-- https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/The_OpenSCAD_Language
import Graphics.Implicit
import Graphics.Implicit.Definitions
import Graphics.Implicit.Primitives (rotate3)
import Control.Monad (join)
import Options.Applicative
import qualified Options.Applicative as A
import Paths_haskmas (version)
import Data.Version (showVersion)
data BaubleLocation = R | L
main :: IO ()
main = join $ execParser optsInfo
optsInfo :: ParserInfo (IO ())
optsInfo = info (helper <*> opts)
( fullDesc
<> header "Haskmas generates the Haskmas logo of arbitrary size.")
opts :: Parser (IO ())
opts = go <$> versionArg <*> sizeArg <*> classicTreeTypeArg
sizeArg :: Parser Integer
sizeArg = A.option auto
( long "size"
<> short 'n'
<> value 3
<> metavar "N"
<> help "The number of components of tree to generate.")
versionArg :: Parser Bool
versionArg = A.switch
( long "version"
<> short 'v'
<> help "Display the version."
)
classicTreeTypeArg :: Parser Bool
classicTreeTypeArg = A.switch
( long "classic"
<> short 'c'
<> help "Output the \"classic\" tree (size will be ignored)."
)
-- | Using OpenSCAD to generate STL for now until https://github.com/colah/ImplicitCAD/pull/67
-- is fixed.
go :: Bool -- display version
-> Integer -- size
-> Bool -- output "classic" tree
-> IO ()
go True _ _ = putStrLn (showVersion version)
go _ _ True = writeSCAD3 1 "haskmas.scad" (rotate3deg (0,0,90) tree)
go _ n _ = writeSCAD3 1 "haskmas.scad" (rotate3deg (0,0,90) (ntree n))
height = 10
-- | Rotate but specify degrees instead of radians.
rotate3deg (x, y, z) = rotate3 rads
where
f x = x * (pi/180)
rads = (f x, f y, f z)
-- | the typical haskell logo with some additional connectedness so it prints
-- as a single object.
logo :: SymbolicObj3
logo = union [
-- /\
translate (-6.5, 0, 0) $ rotate3deg (0, 0, -16.2) bar
, translate ( 0, 19, 0) $ rotate3deg (0, 0, 16.2) bar
-- connecting bars.
, translate ( 1, 10, 0) $ rect3R 0 (0,0,0) (8, 2, 3)
, translate ( 3, 25, 0) $ rect3R 0 (0,0,0) (8, 2, 3)
-- λ
, translate ( 4, 0, 0) $ rotate3deg (0, 0, -16.2) bar
, translate ( 18, -1, 0) $ rotate3deg (0, 0, 16.2) longBar
-- equals
, translate ( 15, 10, 0) $ rect3R 0 (0,0,0) (24, 6, height)
, translate ( 13, 22, 0) $ rect3R 0 (0,0,0) (26, 6, height)
]
where
bar = rect3R 0 (0, 0, 0) (6, 24, height)
longBar = rect3R 0 (0, 0, 0) (6, 44, height)
tree :: SymbolicObj3
tree = union [
-- build the tree
logoBauble R
, translate (40, 4, 0) $ scale ( 0.8, 0.8, 0.8) (logoBauble L)
, translate (72, 5, 0) $ scale (0.64, 0.64, 0.64) (logoBauble L)
-- put the star on top.
, translate (92, 17.5, 0) star
]
-- | Build a tree of an arbitrary depth.
ntree :: Integer -> SymbolicObj3
ntree k = finalObj
where
dec = 0.8
ratios = 0 : [dec^j | j <- [0..(k-2)]]
-- build up logo structure
((lx, ly, lz), objs) = foldl f ((0, 0, 0), []) (zip [0..(k-1)] ratios)
-- position of logos
(x,y,z) = (40, 4, 0)
f :: ((ℝ, ℝ, ℝ), [SymbolicObj3]) -> (Integer, Float) -> ((ℝ, ℝ, ℝ), [SymbolicObj3])
f ((x', y', z'), xs) (j, r) =
let newPos = (x' + r*x, y' + r*y, z' + r*z)
s = dec ^ j
loc = if (even j) then R else L
obj3 = translate newPos $ scale (s, s, s) (logoBauble loc)
in (newPos, obj3 : xs)
-- star
(a,b,c) = (40.5, 24.5, 0)
starScale = dec ** (fromIntegral (k-3))
posScale = dec ** (fromIntegral k)
starObj = translate (lx + (posScale * a), ly + (posScale * b), lz + (posScale * c))
$ scale (starScale, starScale, starScale) star
finalObj = union (starObj : objs)
logoBauble :: BaubleLocation -> SymbolicObj3
logoBauble loc =
case loc of
R -> union [logo, translate (14, 1, 4) bauble]
L -> union [logo, translate (-8, 38, 4) bauble]
bauble = sphere 4
-- | Hand-drawn star in 2d.
star2d :: SymbolicObj2
star2d = polygon [
( 0, 8)
, ( 8, 2)
, ( 3.6, 11)
, ( 10, 18)
, ( 2, 14)
, ( 0, 25)
, ( -2, 14)
, ( -10, 18)
, (-3.5, 10)
, ( -7, 2.3)
]
-- | Extrude to three dimensions, also rotate around
-- so that it is facing the way we want.
star :: SymbolicObj3
star = rotate3deg (0, 0, -90) $ extrudeR 0 star2d height
| silky/haskmas | src/Main.hs | bsd-3-clause | 4,847 | 0 | 14 | 1,495 | 1,753 | 997 | 756 | 103 | 2 |
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module Network.IRC.Bot.Commands where
import Control.Applicative
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Data
import Data.List (isPrefixOf)
import Data.Monoid ((<>))
import Network (PortID(PortNumber))
import Network.IRC
import Network.IRC.Bot.BotMonad
type HostName = ByteString
-- * Commands
cmd :: (Functor m, MonadPlus m, BotMonad m) => Command -> m ()
cmd cmdName =
do command <- msg_command <$> askMessage
if cmdName == command
then return ()
else mzero
data Ping
= Ping HostName
deriving (Eq, Ord, Read, Show, Data, Typeable)
ping :: (Functor m, MonadPlus m, BotMonad m) => m Ping
ping =
do cmd "PING"
params <- msg_params <$> askMessage
case params of
(hostName:_) -> return $ Ping hostName
_ -> mzero
data PrivMsg
= PrivMsg { prefix :: (Maybe Prefix)
, receivers :: [ByteString]
, msg :: ByteString
}
deriving (Eq, Read, Show)
privMsg :: (Functor m, MonadPlus m, BotMonad m) => m PrivMsg
privMsg =
do msg <- askMessage
maybe mzero return (toPrivMsg msg)
toPrivMsg :: Message -> Maybe PrivMsg
toPrivMsg msg =
let cmd = msg_command msg
params = msg_params msg
prefix = msg_prefix msg
in case cmd of
"PRIVMSG" -> Just $ PrivMsg prefix (init params) (last params)
_ -> Nothing
class ToMessage a where
toMessage :: a -> Message
sendCommand :: (ToMessage c, BotMonad m, Functor m) => c -> m ()
sendCommand c = sendMessage (toMessage c)
data Pong
= Pong HostName
deriving (Eq, Ord, Read, Show, Data, Typeable)
instance ToMessage Pong where
toMessage (Pong hostName) = Message Nothing "PONG" [hostName]
instance ToMessage PrivMsg where
toMessage (PrivMsg prefix receivers msg) = Message prefix "PRIVMSG" (receivers <> [msg])
-- | get the nickname of the user who sent the message
askSenderNickName :: (BotMonad m) => m (Maybe ByteString)
askSenderNickName =
do msg <- askMessage
case msg_prefix msg of
(Just (NickName nick _ _)) -> return (Just nick)
_ -> return Nothing
-- | figure out who to reply to for a given `Message`
--
-- If message was sent to a #channel reply to the channel. Otherwise reply to the sender.
replyTo :: (BotMonad m) => m (Maybe ByteString)
replyTo =
do priv <- privMsg
let receiver = head (receivers priv)
if ("#" `B.isPrefixOf` receiver)
then return (Just receiver)
else askSenderNickName
-- | returns the receiver of a message
--
-- if multiple receivers, it returns only the first
askReceiver :: (Alternative m, BotMonad m) => m (Maybe ByteString)
askReceiver =
do priv <- privMsg
return (Just (head $ receivers priv))
<|>
do return Nothing
| eigengrau/haskell-ircbot | Network/IRC/Bot/Commands.hs | bsd-3-clause | 2,873 | 0 | 13 | 696 | 916 | 479 | 437 | 76 | 2 |
module OtherStaff where
import Data.List
import Data.Char
import Data.Array
import Data.Scientific (fromRationalRepetend, formatScientific, FPFormat(..))
import Data.Ratio
import Data.Function (on)
import Numeric (showIntAtBase)
-- $setup
-- >>> import Control.Applicative
-- >>> import Test.QuickCheck
-- >>> newtype Small = Small Int deriving Show
-- >>> instance Arbitrary Small where arbitrary = Small . (`mod` 100) <$> arbitrary
primes :: [Integer]
primes = 2:3:(filter isprime [5,7..])
where isprime m =
let limit = floor . sqrt . fromIntegral $ m
lessThan = takeWhile (<= limit) primes
in all ((/=0) . (m `rem`)) lessThan
fact :: Integer -> [Integer]
fact n = filter ((==0) . (n `rem`)) (takeWhile (<n) primes)
-- problem 45
p45 :: [Integer]
p45 =
-- too slow
-- let tri = [div (n*(n+1)) 2 | n <- [1..] ]
-- pen = [div (n*(3*n-1)) 2 | n <- [1..]]
-- hex = [n*(2*n-1) | n <- [1..]]
-- check xs n = let (x:_) = dropWhile (< n) xs in x == n
-- in [n | n <- [1..]
-- , check tri n
-- , check pen n
-- , check hex n]
[h*(2*h-1) | pvalue <- map (\x -> 3*x^2 - x) [1..]
, let delta = floor . sqrt . fromIntegral $ (1+4*pvalue)
, let h = quot (1+delta) 4
, delta^2 == 1+4*pvalue
, rem (-1+delta) 2 == 0
, rem (1+delta) 4 == 0]
-- problem 46
p46 :: [Integer]
p46 = [n | n <- [3,5..]
, let xs = takeWhile (<=n) primes
, check n xs]
where primes = 2:3:(filter isprime [5,7..])
where isprime n =
let limitn = floor . sqrt . fromIntegral $ n
lessThann = takeWhile (<= limitn) primes
in all ((/=0) . (n `rem`)) lessThann
test y x = let minus = y - x
delta = sqrt . fromIntegral . (`div` 2) $ minus
in (even minus) && ((floor delta)^2 == (div minus 2))
check m ys = (last ys) /= m && not (any (test m) ys)
-- problem 47
-- consume too much time, but it works fine ORZ
p47 :: Int -> [(Int, Int)]
p47 n =
head . dropWhile test . groupBy ((==) `on` snd) . zip [1..] . map countFactors $ [1..]
where test al@((_, m):_) = (m /= n) || (length al /= n)
primes :: [Integer]
primes = 2:3:(filter isprime [5,7..])
where isprime m =
let limit = floor . sqrt . fromIntegral $ m
lessThan = takeWhile (<= limit) primes
in all ((/=0) . (m `rem`)) lessThan
countFactors m =
length . filter (\x -> rem m x == 0) . takeWhile (<m) $ primes
-- problem 48
-- this is cheating ....
-- thank haskell's Integer type
p48 :: Integer
p48 = sum $ map (\n -> read . reverse . take 10 . reverse . show $ n^n) [1..1000]
-- problem 50 TODO
-- consecutivePrime :: Integer -> Integer
-- consecutivePrime n =
-- let xli = takeWhile (<=n) primes
-- cumsum [] = []
-- cumsum (x:xs) = x : (map (+x) (cumsum xs))
-- step xs =
-- step xs = filter (<=n) (reverse . cumsum $ xs)
-- go xs =
-- let out = dropWhile (`notElem` xli) (step xs)
-- in if null out then go (tail xs) else head out
-- in go xli
-- problem 52
-- permuted multiples
p52 :: [Integer] -> [Integer]
p52 ns = map fst . filter hep . map (\m -> (m, (*m) <$> ns)) $ [1..]
where hep (x, ys) = let x' = sort . show $ x
ys' = map (sort . show) ys
in all (==x') ys'
-- problem 53
p53 :: Int
p53 = length . filter (>1000000). concatMap combine $ [1..100]
where fact :: Integer -> Integer
fact n = product [1..n]
combine :: Integer -> [Integer]
combine n = map comb [0..n] where
comb i = fact n `div` (fact i * fact (n-i))
data Card =
Card Int | Jack | Queen | King | Ace deriving (Eq, Ord, Show)
-- problem 64
p64 :: Int -> Int
p64 num =
length . filter snd . map f $ [1..num]
where
gen s1 =
let generate now@(n, a, b) ns old =
let w = (n-a^2) `div` b
k = div (a+floor (sqrt (fromIntegral n))) w
in if now `elem` old
then (ns, old)
else generate (n, k*w-a, w) (k:ns) (now:old)
in generate s1 [] []
periodSquare n =
let n' = floor . sqrt . fromIntegral $ n
(left, _) = gen (n, n',1)
in if n'^2 == n
then (n', [])
else (n', left)
f n = let (a, b) = periodSquare n
in (a, odd . length $ b)
-- problem 65
p65 :: Int -> Int
p65 n = sum . map (\n -> read [n]) . show . denominator . compose . take n $ es
where
es = 2:1:2:(concat [[1,1,2*k] | k <- [2..]])
compose :: [Ratio Integer] -> Ratio Integer -- this is necessary, because int won't be enough to store the data
compose = foldr (\x acc -> 1 / (x + acc)) 0
-- problem 66
solve :: Integer -> (Integer, Integer)
solve d =
-- given d, output (x, y)
head [(x, y) | y <- [1..],
let delta = (d*y^2 + 1),
let x = floor . sqrt . fromIntegral $ delta,
x^2 == delta]
{-p66 :: Int -> [(Int, Int, Int)]-}
{-p66 num = sort . map de $ ns -}
{- where ns = [n | n <- [1..num], (floor . sqrt . fromIntegral $ n)^2 /= n]-}
{- de d = let (x, y) = solve d in (x, y, d) -}
{- take3 (a, b, c) = c-}
-- problem 69
p68 :: Integer
p68 = maximum . filter ((==16) . length . show) . fmap convert . filter check . fmap reform . permutations $ [1..10]
where reform xs =
let (a, b) = splitAt 5 xs
in rearange $ zip3' a b (tail b ++ [head b]) -- trick here, clockwise and starting from minimum
zip3' (x:xs) (y:ys) (z:zs) = [x,y,z] : zip3' xs ys zs
zip3' _ _ _ = []
rearange xs =
let small = minimum . fmap head $ xs
(a, b) = span ((/= small) . head) xs
in b ++ a
check ys =
let y : yy = fmap sum ys
in all (== y) yy
convert = read . concatMap show . concat
-- problem 69
p69 n =
foldl' (\al@(_, acc) x -> if f x > acc then (x, f x) else al) (0, 0) [2..n]
where
f m = (fromIntegral m) / (fromIntegral (phi m))
phi m = length . filter (\q -> all ((/=0) . rem q) (fact m)) $ [1..m-1]
-- | Just fun | niexshao/Exercises | src/OtherStaff.hs | bsd-3-clause | 6,304 | 3 | 24 | 2,117 | 2,443 | 1,328 | 1,115 | 114 | 3 |
-- List
-- List can contain only the same type
[1,2,3,4] ++ [9,10,11,12] -- [1,2,3,4,9,10,11,12]
"hello" ++ " " ++ "world" -- "hello world"
-- NOTE: Haskell has to walk through the whole list on the left side of ++
[1, 2, 3, 4] !! 0 -- reference index 0 in the list
100 : [1, 2, 3, 4] -- add one item at the first in the list
[3, 4, 2] > [2, 4] -- True
-- {head}{-----tail-----}
-- (-__-)( )( )( )
-- {-----init-----}{last}
head [5, 4, 3, 2, 1] -- get the first item
last [5, 4, 3, 2, 1] -- get the last item
init [5, 4, 3, 2, 1] -- [5, 4, 3, 2] remove the last item
tail [5, 4, 3, 2, 1] -- [4, 3, 2, 1] remove the first item
null [] -- check if it's empty
length [] -- get a length of the list
reverse [] -- get reverse list
take 5 [] -- get 5 items from index 0
drop 10 [] -- get items after dropping 10 items from index 0
maximum [] -- max item
minimum [] -- min item
sum [] -- total
product [] -- multiply all items
4 `elem` [] -- 4 exists in the list?
[1..20] -- [1,2,3,4......19,20]
['a'..'z'] -- "abcdefghijklmnopqrstuvwxyz"
[3,6..20] -- [3,6,9,12,15,18]
[20,19..1] -- NOTE: [20..1] doesn't work
take 24 [13,26..] -- get 24 items from index 0 using unlimited list
take 10 (cycle [1,2,3]) -- [1,2,3,1,2,3,1,2,3,1]
repeat 5 -- [5,5,5,5,5......]
replicate 3 10 -- [10,10,10]
-- NOTE: List Comprehension [output, input, filter]
[ x * 2 | x <- [1..10]] -- [2,4,6,8,10,12,14,16,18,20]
[ x * 2 | x <- [1..10], x*2 >= 12] -- [12,14,16,18,20]
[ x | x <- [1,2,3], y <- [4,5]] -- always create 3 * 2 length list
[ x * y | x <- [1,2,3], y <- [2,3,4], x < 2, y > 2] -- [3,4]
-- [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
-- [1 | _ <- list] // _ means we will never use a value from the list
let xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]]
[ [ x | x <- xs, even x ] | xs <- xxs] -- [[2,2,4],[2,4,6,8],[2,4,2,6,2,6]]
| kyk0704/haskell-test | src/List.hs | bsd-3-clause | 1,961 | 4 | 11 | 470 | 699 | 397 | 302 | -1 | -1 |
module Data.Rope (
-- * Size
Rope
, length -- :: Rope -> Int
, null -- :: Rope -> Bool
-- * Slicing
, Breakable(..)
, splitAt -- :: Int -> Rope -> (Rope, Rope)
, take -- :: Int -> Rope -> Rope
, drop -- :: Int -> Rope -> Rope
-- * Walking
-- ** construction
, Packable(..)
, empty -- :: Rope
, fromByteString -- :: ByteString -> Rope
, fromChunks -- :: [ByteString] -> Rope
, fromLazyByteString -- :: L.ByteString -> Rope
, fromWords -- :: [Word8] -> Rope
, fromChar -- :: Char -> Rope
, fromWord8 -- :: Word8 -> Rope
, fromString -- :: String -> Rope
-- * Deconstructing 'Rope's
, Unpackable(..)
, toChunks -- :: Rope -> [ByteString]
, toLazyByteString -- :: Rope -> L.ByteString
, toString -- :: Rope -> String
) where
import Prelude () -- hiding (null,head,length,drop,take,splitAt, last)
import Data.Rope.Internal
( Rope
, empty
, length
, null
, fromChunks
, fromByteString
, fromLazyByteString
, fromWords
, fromChar
, fromWord8
, fromString
, toString
, toChunks
, toLazyByteString
, Packable(..)
, Breakable(..)
, Unpackable(..)
, splitAt
, take
, drop)
| ekmett/rope | Data/Rope.hs | bsd-3-clause | 1,354 | 0 | 6 | 486 | 188 | 134 | 54 | 43 | 0 |
module Tree where
data Tree a = Leaf | Node a (Tree a) (Tree a)
map :: (a -> b) -> Tree a -> Tree b
map f Leaf = Leaf
map f (Node v l r) = Node (f v) (map f l) (map f r)
| rodrigogribeiro/mptc | test/classless/Tree.hs | bsd-3-clause | 172 | 0 | 8 | 49 | 118 | 61 | 57 | 5 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Pact.Types.RowData
-- Copyright : (C) 2021 Stuart Popejoy
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Stuart Popejoy <stuart@kadena.io>
--
-- Versioned persistence for 'PactValue'.
--
module Pact.Types.RowData
( RowData(..)
, RowDataVersion(..)
, RowDataValue(..)
, pactValueToRowData
, rowDataToPactValue
) where
import Control.Applicative
import Control.DeepSeq (NFData)
import Data.Aeson
import Data.Default
import Data.Maybe(fromMaybe)
import Data.Text (Text)
import Data.Vector (Vector)
import GHC.Generics
import Test.QuickCheck
import Pact.Types.Exp
import Pact.Types.PactValue
import Pact.Types.Pretty
import Pact.Types.Term
data RowDataValue
= RDLiteral Literal
| RDList (Vector RowDataValue)
| RDObject (ObjectMap RowDataValue)
| RDGuard (Guard RowDataValue)
| RDModRef ModRef
deriving (Eq,Show,Generic,Ord)
instance NFData RowDataValue
instance Arbitrary RowDataValue where
arbitrary = pactValueToRowData <$> arbitrary
instance ToJSON RowDataValue where
toJSON rdv = case rdv of
RDLiteral l -> toJSON l
RDList l -> toJSON l
RDObject o -> tag "o" o
RDGuard g -> tag "g" g
RDModRef (ModRef refName refSpec _) -> tag "m" $ object
[ "refName" .= refName
, "refSpec" .= refSpec
]
where
tag :: ToJSON t => Text -> t -> Value
tag t rv = object [ "$t" .= t, "$v" .= rv ]
instance FromJSON RowDataValue where
parseJSON v1 =
(RDLiteral <$> parseJSON v1) <|>
(RDList <$> parseJSON v1) <|>
parseTagged v1
where
parseTagged = withObject "tagged RowData" $ \o -> do
(tag :: Text) <- o .: "$t"
val <- o .: "$v"
case tag of
"o" -> RDObject <$> parseJSON val
"g" -> RDGuard <$> parseJSON val
"m" -> RDModRef <$> parseMR val
_ -> fail "tagged RowData"
parseMR = withObject "tagged ModRef" $ \o -> ModRef
<$> o .: "refName"
<*> o .: "refSpec"
<*> pure def
data RowDataVersion = RDV0 | RDV1
deriving (Eq,Show,Generic,Ord,Enum,Bounded)
instance NFData RowDataVersion
instance ToJSON RowDataVersion where
toJSON = toJSON . fromEnum
instance FromJSON RowDataVersion where
parseJSON = withScientific "RowDataVersion" $ \case
0 -> pure RDV0
1 -> pure RDV1
_ -> fail "RowDataVersion"
data RowData = RowData
{ _rdVersion :: RowDataVersion
, _rdData :: ObjectMap RowDataValue
}
deriving (Eq,Show,Generic,Ord)
instance NFData RowData
instance Pretty RowData where pretty (RowData _ m) = pretty m
pactValueToRowData :: PactValue -> RowDataValue
pactValueToRowData pv = case pv of
PLiteral l -> RDLiteral l
PList l -> RDList $ recur l
PObject o -> RDObject $ recur o
PGuard g -> RDGuard $ recur g
PModRef m -> RDModRef m
where
recur :: Functor f => f PactValue -> f RowDataValue
recur = fmap pactValueToRowData
rowDataToPactValue :: RowDataValue -> PactValue
rowDataToPactValue rdv = case rdv of
RDLiteral l -> PLiteral l
RDList l -> PList $ recur l
RDObject o -> PObject $ recur o
RDGuard g -> PGuard $ recur g
RDModRef m -> PModRef m
where
recur :: Functor f => f RowDataValue -> f PactValue
recur = fmap rowDataToPactValue
instance Pretty RowDataValue where
pretty = pretty . rowDataToPactValue
instance ToJSON RowData where
toJSON (RowData RDV0 m) = toJSON $ fmap rowDataToPactValue m
toJSON (RowData v m) = object
[ "$v" .= v, "$d" .= m ]
data OldPactValue
= OldPLiteral Literal
| OldPList (Vector OldPactValue)
| OldPObject (ObjectMap OldPactValue)
| OldPGuard (Guard OldPactValue)
| OldPModRef ModRef
-- Needed for parsing guard
instance ToJSON OldPactValue where
toJSON = \case
OldPLiteral l -> toJSON l
OldPObject o -> toJSON o
OldPList v -> toJSON v
OldPGuard x -> toJSON x
OldPModRef (ModRef refName refSpec refInfo) -> object $
[ "refName" .= refName
, "refSpec" .= refSpec
] ++
[ "refInfo" .= refInfo | refInfo /= def ]
instance FromJSON OldPactValue where
parseJSON v =
(OldPLiteral <$> parseJSON v) <|>
(OldPList <$> parseJSON v) <|>
(OldPGuard <$> parseJSON v) <|>
(OldPObject <$> parseJSON v) <|>
(OldPModRef <$> (parseNoInfo v <|> parseJSON v))
where
parseNoInfo = withObject "ModRef" $ \o -> ModRef
<$> o .: "refName"
<*> o .: "refSpec"
<*> (fromMaybe def <$> o .:? "refInfo")
instance FromJSON RowData where
parseJSON v =
parseVersioned v <|>
-- note: Parsing into `OldPactValue` here defaults to the code used in
-- the old FromJSON instance for PactValue, prior to the fix of moving
-- the `PModRef` parsing before PObject
RowData RDV0 . fmap oldPactValueToRowData <$> parseJSON v
where
oldPactValueToRowData = \case
OldPLiteral l -> RDLiteral l
OldPList l -> RDList $ recur l
OldPObject o -> RDObject $ recur o
OldPGuard g -> RDGuard $ recur g
OldPModRef m -> RDModRef m
recur :: Functor f => f OldPactValue -> f RowDataValue
recur = fmap oldPactValueToRowData
parseVersioned = withObject "RowData" $ \o -> RowData
<$> o .: "$v"
<*> o .: "$d"
| kadena-io/pact | src/Pact/Types/RowData.hs | bsd-3-clause | 5,376 | 0 | 16 | 1,327 | 1,600 | 806 | 794 | -1 | -1 |
z = (x, y)
where x = [ 1, 2, 3 ]
y = [ 1, 2, 3 ]
| itchyny/vim-haskell-indent | test/list/list.in.hs | mit | 49 | 2 | 5 | 19 | 49 | 26 | 23 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE PatternGuards #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-} -- QuasiQuoter
module Yesod.Routes.Parse
( parseRoutes
, parseRoutesFile
, parseRoutesNoCheck
, parseRoutesFileNoCheck
, parseType
, parseTypeTree
, TypeTree (..)
, dropBracket
, nameToType
, isTvar
) where
import Language.Haskell.TH.Syntax
import Data.Char (isUpper, isLower, isSpace)
import Language.Haskell.TH.Quote
import qualified System.IO as SIO
import Yesod.Routes.TH
import Yesod.Routes.Overlap (findOverlapNames)
import Data.List (foldl', isPrefixOf)
import Data.Maybe (mapMaybe)
import qualified Data.Set as Set
-- | A quasi-quoter to parse a string into a list of 'Resource's. Checks for
-- overlapping routes, failing if present; use 'parseRoutesNoCheck' to skip the
-- checking. See documentation site for details on syntax.
parseRoutes :: QuasiQuoter
parseRoutes = QuasiQuoter { quoteExp = x }
where
x s = do
let res = resourcesFromString s
case findOverlapNames res of
[] -> lift res
z -> error $ unlines $ "Overlapping routes: " : map show z
-- | Same as 'parseRoutes', but uses an external file instead of quasiquotation.
--
-- The recommended file extension is @.yesodroutes@.
parseRoutesFile :: FilePath -> Q Exp
parseRoutesFile = parseRoutesFileWith parseRoutes
-- | Same as 'parseRoutesNoCheck', but uses an external file instead of quasiquotation.
--
-- The recommended file extension is @.yesodroutes@.
parseRoutesFileNoCheck :: FilePath -> Q Exp
parseRoutesFileNoCheck = parseRoutesFileWith parseRoutesNoCheck
parseRoutesFileWith :: QuasiQuoter -> FilePath -> Q Exp
parseRoutesFileWith qq fp = do
qAddDependentFile fp
s <- qRunIO $ readUtf8File fp
quoteExp qq s
readUtf8File :: FilePath -> IO String
readUtf8File fp = do
h <- SIO.openFile fp SIO.ReadMode
SIO.hSetEncoding h SIO.utf8_bom
SIO.hGetContents h
-- | Same as 'parseRoutes', but performs no overlap checking.
parseRoutesNoCheck :: QuasiQuoter
parseRoutesNoCheck = QuasiQuoter
{ quoteExp = lift . resourcesFromString
}
-- | Converts a multi-line string to a set of resources. See documentation for
-- the format of this string. This is a partial function which calls 'error' on
-- invalid input.
resourcesFromString :: String -> [ResourceTree String]
resourcesFromString =
fst . parse 0 . filter (not . all (== ' ')) . foldr lineContinuations [] . lines . filter (/= '\r')
where
parse _ [] = ([], [])
parse indent (thisLine:otherLines)
| length spaces < indent = ([], thisLine : otherLines)
| otherwise = (this others, remainder)
where
parseAttr ('!':x) = Just x
parseAttr _ = Nothing
stripColonLast =
go id
where
go _ [] = Nothing
go front [x]
| null x = Nothing
| last x == ':' = Just $ front [init x]
| otherwise = Nothing
go front (x:xs) = go (front . (x:)) xs
spaces = takeWhile (== ' ') thisLine
(others, remainder) = parse indent otherLines'
(this, otherLines') =
case takeWhile (not . isPrefixOf "--") $ splitSpaces thisLine of
(pattern:rest0)
| Just (constr:rest) <- stripColonLast rest0
, Just attrs <- mapM parseAttr rest ->
let (children, otherLines'') = parse (length spaces + 1) otherLines
children' = addAttrs attrs children
(pieces, Nothing, check) = piecesFromStringCheck pattern
in ((ResourceParent constr check pieces children' :), otherLines'')
(pattern:constr:rest) ->
let (pieces, mmulti, check) = piecesFromStringCheck pattern
(attrs, rest') = takeAttrs rest
disp = dispatchFromString rest' mmulti
in ((ResourceLeaf (Resource constr pieces disp attrs check):), otherLines)
[] -> (id, otherLines)
_ -> error $ "Invalid resource line: " ++ thisLine
-- | Splits a string by spaces, as long as the spaces are not enclosed by curly brackets (not recursive).
splitSpaces :: String -> [String]
splitSpaces "" = []
splitSpaces str =
let (rest, piece) = parse $ dropWhile isSpace str in
piece:(splitSpaces rest)
where
parse :: String -> ( String, String)
parse ('{':s) = fmap ('{':) $ parseBracket s
parse (c:s) | isSpace c = (s, [])
parse (c:s) = fmap (c:) $ parse s
parse "" = ("", "")
parseBracket :: String -> ( String, String)
parseBracket ('{':_) = error $ "Invalid resource line (nested curly bracket): " ++ str
parseBracket ('}':s) = fmap ('}':) $ parse s
parseBracket (c:s) = fmap (c:) $ parseBracket s
parseBracket "" = error $ "Invalid resource line (unclosed curly bracket): " ++ str
piecesFromStringCheck :: String -> ([Piece String], Maybe String, Bool)
piecesFromStringCheck s0 =
(pieces, mmulti, check)
where
(s1, check1) = stripBang s0
(pieces', mmulti') = piecesFromString $ drop1Slash s1
pieces = map snd pieces'
mmulti = fmap snd mmulti'
check = check1 && all fst pieces' && maybe True fst mmulti'
stripBang ('!':rest) = (rest, False)
stripBang x = (x, True)
addAttrs :: [String] -> [ResourceTree String] -> [ResourceTree String]
addAttrs attrs =
map goTree
where
goTree (ResourceLeaf res) = ResourceLeaf (goRes res)
goTree (ResourceParent w x y z) = ResourceParent w x y (map goTree z)
goRes res =
res { resourceAttrs = noDupes ++ resourceAttrs res }
where
usedKeys = Set.fromList $ map fst $ mapMaybe toPair $ resourceAttrs res
used attr =
case toPair attr of
Nothing -> False
Just (key, _) -> key `Set.member` usedKeys
noDupes = filter (not . used) attrs
toPair s =
case break (== '=') s of
(x, '=':y) -> Just (x, y)
_ -> Nothing
-- | Take attributes out of the list and put them in the first slot in the
-- result tuple.
takeAttrs :: [String] -> ([String], [String])
takeAttrs =
go id id
where
go x y [] = (x [], y [])
go x y (('!':attr):rest) = go (x . (attr:)) y rest
go x y (z:rest) = go x (y . (z:)) rest
dispatchFromString :: [String] -> Maybe String -> Dispatch String
dispatchFromString rest mmulti
| null rest = Methods mmulti []
| all (all isUpper) rest = Methods mmulti rest
dispatchFromString [subTyp, subFun] Nothing =
Subsite subTyp subFun
dispatchFromString [_, _] Just{} =
error "Subsites cannot have a multipiece"
dispatchFromString rest _ = error $ "Invalid list of methods: " ++ show rest
drop1Slash :: String -> String
drop1Slash ('/':x) = x
drop1Slash x = x
piecesFromString :: String -> ([(CheckOverlap, Piece String)], Maybe (CheckOverlap, String))
piecesFromString "" = ([], Nothing)
piecesFromString x =
case (this, rest) of
(Left typ, ([], Nothing)) -> ([], Just typ)
(Left _, _) -> error "Multipiece must be last piece"
(Right piece, (pieces, mtyp)) -> (piece:pieces, mtyp)
where
(y, z) = break (== '/') x
this = pieceFromString y
rest = piecesFromString $ drop 1 z
parseType :: String -> Type
parseType orig =
maybe (error $ "Invalid type: " ++ show orig) ttToType $ parseTypeTree orig
parseTypeTree :: String -> Maybe TypeTree
parseTypeTree orig =
toTypeTree pieces
where
pieces = filter (not . null) $ splitOn (\c -> c == '-' || c == ' ') $ addDashes orig
addDashes [] = []
addDashes (x:xs) =
front $ addDashes xs
where
front rest
| x `elem` "()[]" = '-' : x : '-' : rest
| otherwise = x : rest
splitOn c s =
case y' of
_:y -> x : splitOn c y
[] -> [x]
where
(x, y') = break c s
data TypeTree = TTTerm String
| TTApp TypeTree TypeTree
| TTList TypeTree
deriving (Show, Eq)
toTypeTree :: [String] -> Maybe TypeTree
toTypeTree orig = do
(x, []) <- gos orig
return x
where
go [] = Nothing
go ("(":xs) = do
(x, rest) <- gos xs
case rest of
")":rest' -> Just (x, rest')
_ -> Nothing
go ("[":xs) = do
(x, rest) <- gos xs
case rest of
"]":rest' -> Just (TTList x, rest')
_ -> Nothing
go (x:xs) = Just (TTTerm x, xs)
gos xs1 = do
(t, xs2) <- go xs1
(ts, xs3) <- gos' id xs2
Just (foldl' TTApp t ts, xs3)
gos' front [] = Just (front [], [])
gos' front (x:xs)
| x `elem` words ") ]" = Just (front [], x:xs)
| otherwise = do
(t, xs') <- go $ x:xs
gos' (front . (t:)) xs'
ttToType :: TypeTree -> Type
ttToType (TTTerm s) = nameToType s
ttToType (TTApp x y) = ttToType x `AppT` ttToType y
ttToType (TTList t) = ListT `AppT` ttToType t
nameToType :: String -> Type
nameToType t = if isTvar t
then VarT $ mkName t
else ConT $ mkName t
isTvar :: String -> Bool
isTvar (h:_) = isLower h
isTvar _ = False
pieceFromString :: String -> Either (CheckOverlap, String) (CheckOverlap, Piece String)
pieceFromString ('#':'!':x) = Right $ (False, Dynamic $ dropBracket x)
pieceFromString ('!':'#':x) = Right $ (False, Dynamic $ dropBracket x) -- https://github.com/yesodweb/yesod/issues/652
pieceFromString ('#':x) = Right $ (True, Dynamic $ dropBracket x)
pieceFromString ('*':'!':x) = Left (False, x)
pieceFromString ('+':'!':x) = Left (False, x)
pieceFromString ('!':'*':x) = Left (False, x)
pieceFromString ('!':'+':x) = Left (False, x)
pieceFromString ('*':x) = Left (True, x)
pieceFromString ('+':x) = Left (True, x)
pieceFromString ('!':x) = Right $ (False, Static x)
pieceFromString x = Right $ (True, Static x)
dropBracket :: String -> String
dropBracket str@('{':x) = case break (== '}') x of
(s, "}") -> s
_ -> error $ "Unclosed bracket ('{'): " ++ str
dropBracket x = x
-- | If this line ends with a backslash, concatenate it together with the next line.
--
-- @since 1.6.8
lineContinuations :: String -> [String] -> [String]
lineContinuations this [] = [this]
lineContinuations this below@(next:rest) = case unsnoc this of
Just (this', '\\') -> (this'++next):rest
_ -> this:below
where unsnoc s = if null s then Nothing else Just (init s, last s)
| geraldus/yesod | yesod-core/src/Yesod/Routes/Parse.hs | mit | 10,561 | 0 | 20 | 2,900 | 3,671 | 1,922 | 1,749 | 234 | 8 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE Rank2Types #-}
module YesodCoreTest.Cache
( cacheTest
, Widget
, resourcesC
) where
import Test.Hspec
import Network.Wai
import Network.Wai.Test
import Yesod.Core
import UnliftIO.IORef
import Data.Typeable (Typeable)
import qualified Data.ByteString.Lazy.Char8 as L8
data C = C
newtype V1 = V1 Int
newtype V2 = V2 Int
mkYesod "C" [parseRoutes|
/ RootR GET
/key KeyR GET
/nested NestedR GET
/nested-key NestedKeyR GET
|]
instance Yesod C where
errorHandler e = liftIO (print e) >> defaultErrorHandler e
getRootR :: Handler RepPlain
getRootR = do
ref <- newIORef 0
V1 v1a <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1)
V1 v1b <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1)
V2 v2a <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1)
V2 v2b <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1)
cacheBySet "3" (V2 3)
V2 v3a <- cacheByGet "3" >>= \x ->
case x of
Just y -> return y
Nothing -> error "must be Just"
V2 v3b <- cachedBy "3" $ (pure $ V2 4)
return $ RepPlain $ toContent $ show [v1a, v1b, v2a, v2b, v3a, v3b]
getKeyR :: Handler RepPlain
getKeyR = do
ref <- newIORef 0
V1 v1a <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1)
V1 v1b <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1)
V2 v2a <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1)
V2 v2b <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1)
V2 v3a <- cachedBy "2" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1)
V2 v3b <- cachedBy "2" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1)
cacheBySet "4" (V2 4)
V2 v4a <- cacheByGet "4" >>= \x ->
case x of
Just y -> return y
Nothing -> error "must be Just"
V2 v4b <- cachedBy "4" $ (pure $ V2 5)
return $ RepPlain $ toContent $ show [v1a, v1b, v2a, v2b, v3a, v3b, v4a, v4b]
getNestedR :: Handler RepPlain
getNestedR = getNested cached
getNestedKeyR :: Handler RepPlain
getNestedKeyR = getNested $ cachedBy "3"
-- | Issue #1266
getNested :: (forall a. Typeable a => (Handler a -> Handler a)) -> Handler RepPlain
getNested cacheMethod = do
ref <- newIORef 0
let getV2 = atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1)
V1 _ <- cacheMethod $ do
V2 val <- cacheMethod $ getV2
return $ V1 val
V2 v2 <- cacheMethod $ getV2
return $ RepPlain $ toContent $ show v2
cacheTest :: Spec
cacheTest =
describe "Test.Cache" $ do
it "cached" $ runner $ do
res <- request defaultRequest
assertStatus 200 res
assertBody (L8.pack $ show [1, 1, 2, 2, 3, 3 :: Int]) res
it "cachedBy" $ runner $ do
res <- request defaultRequest { pathInfo = ["key"] }
assertStatus 200 res
assertBody (L8.pack $ show [1, 1, 2, 2, 3, 3, 4, 4 :: Int]) res
it "nested cached" $ runner $ do
res <- request defaultRequest { pathInfo = ["nested"] }
assertStatus 200 res
assertBody (L8.pack $ show (1 :: Int)) res
it "nested cachedBy" $ runner $ do
res <- request defaultRequest { pathInfo = ["nested-key"] }
assertStatus 200 res
assertBody (L8.pack $ show (1 :: Int)) res
runner :: Session () -> IO ()
runner f = toWaiApp C >>= runSession f
| geraldus/yesod | yesod-core/test/YesodCoreTest/Cache.hs | mit | 3,494 | 0 | 15 | 923 | 1,451 | 723 | 728 | 85 | 2 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts, GADTs, ScopedTypeVariables #-}
{-|
Description: The main graph module. __Start here__.
This module is reponsible for parsing the SVG files exported from Inkscape.
It also currently acts as a main driver for the whole graph pipeline:
1. Parsing the raw SVG files
2. Inserting them into the database (see "Svg.Database")
3. Retrieving the database values and generating a new SVG file
(See "Svg.Builder" and "Svg.Generator")
The final svg files are output in @public\/res\/graphs\/gen@ and are sent
directly to the client when viewing the @/graph@ page.
-}
module Svg.Parser
(parsePrebuiltSvgs) where
import Data.Maybe (mapMaybe, fromMaybe, fromJust, isNothing)
import Data.List.Split (splitOn)
import Data.List (find)
import qualified Data.Map as M (empty)
import Data.String.Utils (replace)
import Text.XML.HaXml hiding (find, qname, x, attr)
import Text.XML.HaXml.Util (tagTextContent)
import Text.XML.HaXml.Namespaces (printableName)
import System.Directory
import Database.Tables
import Database.DataType
import Svg.Database (insertGraph, insertElements, deleteGraphs)
import Svg.Generator
import Database.Persist.Sqlite hiding (replace)
import Config (graphPath)
import Text.Read (readMaybe, readEither)
parsePrebuiltSvgs :: IO ()
parsePrebuiltSvgs = do
deleteGraphs
performParse "Computer Science" "csc2015.svg"
performParse "Statistics" "sta2015.svg"
performParse "Biochemistry" "bch2015.svg"
performParse "Cell & Systems Biology" "csb2015.svg"
performParse "Estonian" "est2015.svg"
performParse "Finnish" "fin2015.svg"
performParse "Italian" "ita2015.svg"
performParse "Linguistics" "lin2015.svg"
performParse "Rotman" "rotman2015.svg"
performParse "Economics" "eco2015.svg"
performParse "Spanish" "spa2015.svg"
performParse "Portuguese" "prt2015.svg"
performParse "Slavic" "sla2015.svg"
performParse "East Asian Studies" "eas2015.svg"
performParse "English" "eng2015.svg"
performParse "History and Philosophy of Science" "hps2015.svg"
performParse "History" "his2015.svg"
performParse "Geography" "ggr2015.svg"
performParse "Aboriginal" "abs2015.svg"
performParse :: String -- ^ The title of the graph.
-> String -- ^ The filename of the file that will be parsed.
-> IO ()
performParse graphName inputFilename = do
graphFile <- readFile (graphPath ++ inputFilename)
let (graphWidth, graphHeight) = parseSize graphFile
key <- insertGraph graphName graphWidth graphHeight
let parsedGraph = parseGraph key graphFile
PersistInt64 keyVal = toPersistValue key
print "Graph Parsed"
insertElements parsedGraph
print "Graph Inserted"
let genGraphPath = graphPath ++ "gen/"
createDirectoryIfMissing True genGraphPath
buildSVG key M.empty (genGraphPath ++ show keyVal ++ ".svg") False
print "Success"
-- * Parsing functions
-- | Parses an SVG file.
--
-- This and the following functions traverse the raw SVG tree and return
-- three lists, each containing values corresponding to different graph elements
-- (edges, nodes, and text).
parseGraph :: GraphId -- ^ The unique identifier of the graph.
-> String -- ^ The file contents of the graph that will be parsed.
-> ([Path],[Shape],[Text])
parseGraph key graphFile =
let Document _ _ root _ = xmlParse "output.error" graphFile
svgElems = tag "svg" $ CElem root undefined
svgRoot = head svgElems
(paths, shapes, texts) = parseNode key svgRoot
shapes' = removeRedundant shapes
in
if null svgElems
then
error "No svg element detected"
else
(paths, filter small shapes', texts)
where
-- Raw SVG seems to have a rectangle the size of the whole image
small shape = shapeWidth shape < 300
removeRedundant shapes =
filter (not . \s -> (elem (shapePos s) (map shapePos shapes)) &&
(null (shapeFill s) || shapeFill s == "#000000") &&
elem (shapeType_ s) [Node, Hybrid]) shapes
-- | Parse the height and width dimensions from the SVG element, respectively,
-- and return them as a tuple.
parseSize :: String -- ^ The file contents of the graph that will be parsed.
-> (Double, Double)
parseSize graphFile =
let Document _ _ root _ = xmlParse "output.error" graphFile
svgElems = tag "svg" $ CElem root undefined
svgRoot = head svgElems
attrs = contentAttrs svgRoot
width = readAttr "width" attrs
height = readAttr "height" attrs
in
if null svgElems
then
error "No svg element detected"
else
(width, height)
-- | The main parsing function. Parses an SVG element,
-- and then recurses on its children.
parseNode :: GraphId -- ^ The Path's corresponding graph identifier.
-> Content i
-> ([Path],[Shape],[Text])
parseNode key content =
if getName content == "defs"
then ([],[],[])
else let attrs = contentAttrs content
trans = parseTransform $ lookupAttr "transform" attrs
styles' = styles (contentAttrs content)
fill = styleVal "fill" styles'
-- TODO: These 'tag "_"' conditions are mutually exclusive (I think).
rects = map (parseRect key . contentAttrs) (tag "rect" content)
texts = concatMap (parseText key styles' []) (tag "text" content)
paths = mapMaybe (parsePath key . contentAttrs) (tag "path" content)
ellipses = map (parseEllipse key . contentAttrs) (tag "ellipse" content)
concatThree (a1, b1, c1) (a2, b2, c2) =
(a1 ++ a2, b1 ++ b2, c1 ++ c2)
(newPaths, newShapes, newTexts) =
foldl concatThree (paths, rects ++ ellipses, texts)
(map (parseNode key) (path [children] content))
in
(map (updatePath fill trans) newPaths,
map (updateShape fill trans) newShapes,
map (updateText trans) newTexts)
-- | Create a rectangle from a list of attributes.
parseRect :: GraphId -- ^ The Rect's corresponding graph identifier.
-> [Attribute]
-> Shape
parseRect key attrs =
Shape key
""
(readAttr "x" attrs,
readAttr "y" attrs)
(readAttr "width" attrs)
(readAttr "height" attrs)
(styleVal "fill" (styles attrs))
""
[]
9
Node
-- | Create an ellipse from a list of attributes.
parseEllipse :: GraphId -- ^ The Ellipse's corresponding graph identifier.
-> [Attribute]
-> Shape
parseEllipse key attrs =
Shape key
""
(readAttr "cx" attrs,
readAttr "cy" attrs)
(readAttr "rx" attrs * 2)
(readAttr "ry" attrs * 2)
""
""
[]
20
BoolNode
-- | Create a path from a list of attributes.
parsePath :: GraphId -- ^ The Path's corresponding graph identifier.
-> [Attribute]
-> Maybe Path
parsePath key attrs =
if last (lookupAttr "d" attrs) == 'z' && not isRegion
then Nothing
else Just (Path key
""
d
""
""
isRegion
""
"")
where
d = parsePathD $ lookupAttr "d" attrs
fillAttr = styleVal "fill" (styles attrs)
isRegion = not $
null fillAttr || fillAttr == "none"
-- | Create text values from content.
-- It is necessary to pass in the content because we need to search
-- for nested tspan elements.
parseText :: GraphId -- ^ The Text's corresponding graph identifier.
-> [(String, String)]
-> [Attribute] -- ^ Ancestor tspan attributes
-> Content i
-> [Text]
parseText key style parentAttrs content =
if null (childrenBy (tag "tspan") content)
then
[Text key
(lookupAttr "id" (contentAttrs content ++ parentAttrs))
(readAttr "x" (contentAttrs content ++ parentAttrs),
readAttr "y" (contentAttrs content ++ parentAttrs))
(replace "&" "&" (replace ">" ">" $ tagTextContent content))
align
fill]
else
concatMap (parseText key (styles $ contentAttrs content)
(contentAttrs content ++ parentAttrs))
(childrenBy (tag "tspan") content)
where
newStyle = style ++ styles (contentAttrs content)
alignAttr = styleVal "text-anchor" newStyle
align = if null alignAttr
then "begin"
else alignAttr
fill = styleVal "fill" newStyle
-- * Helpers for manipulating attributes
-- | Gets the tag name of a Content Element.
getName :: Content i -> String
getName (CElem (Elem a _ _) _) = printableName a
getName _ = ""
contentAttrs :: Content i -> [Attribute]
contentAttrs (CElem (Elem _ attrs _) _) = attrs
contentAttrs _ = []
-- | Gets an Attribute's name.
attrName :: Attribute -> String
attrName (qname, _) = printableName qname
-- | Looks up the (string) value of the attribute with the corresponding name.
-- Returns the empty string if the attribute isn't found.
lookupAttr :: String -> [Attribute] -> String
lookupAttr nameStr attrs =
maybe "" (show . snd) $ find (\x -> attrName x == nameStr) attrs
-- | Looks up an attribute value and convert to another type.
readAttr :: Read a => String -- ^ The attribute's name.
-> [Attribute] -- ^ The element that contains the attribute.
-> a
readAttr attr attrs =
case readMaybe $ lookupAttr attr attrs of
Just x -> x
Nothing -> error $ "reading " ++ attr ++ " from " ++ show attrs
-- | Return a list of styles from the style attribute of an element.
-- Every style has the form (name, value).
styles :: [Attribute] -> [(String, String)]
styles attrs =
let styleStr = lookupAttr "style" attrs
in map toStyle $ splitOn ";" styleStr
where
toStyle split =
case splitOn ":" split of
[n,v] -> (n,v)
_ -> ("","")
-- | Gets a style attribute from a style string.
styleVal :: String -> [(String, String)] -> String
styleVal nameStr styleMap = fromMaybe "" $ lookup nameStr styleMap
-- | Parses a transform String into a tuple of Float.
parseTransform :: String -> Point
parseTransform "" = (0,0)
parseTransform transform =
let parsedTransform = splitOn "," $ drop 10 transform
xPos = readMaybe $ parsedTransform !! 0
yPos = readMaybe $ init $ parsedTransform !! 1
in
if isNothing xPos || isNothing yPos
then
error transform
else
(fromJust xPos, fromJust yPos)
-- | Parses a path's `d` attribute.
parsePathD :: String -- ^ The 'd' attribute of an SVG path.
-> [Point]
parsePathD d
| head d == 'm' = relCoords
| otherwise = absCoords
where
lengthMoreThanOne x = length x > 1
coordList = filter lengthMoreThanOne (map (splitOn ",") $ splitOn " " d)
-- Converts a relative coordinate structure into an absolute one.
relCoords = tail $ foldl (\x z -> x ++ [addTuples (convertToPoint z)
(last x)])
[(0,0)]
coordList
-- Converts a relative coordinate structure into an absolute one.
absCoords = map convertToPoint coordList
convertToPoint z =
let
x = readMaybe (head z)
y = readMaybe (last z)
in
case (x, y) of
(Just m, Just n) -> (m, n)
_ -> error $ show z
-- * Other helpers
-- | These functions are used to update the parsed values
-- with styles (transform and fill) inherited from their parents.
--
-- Eventually, it would be nice if we removed these functions and
-- simply passed everything down when making the recursive calls.
updatePath :: String -- ^ The fill that may be added to the Path.
-> Point -- ^ Transform that will be added to the Shape's
-- current transform value.
-> Path
-> Path
updatePath fill transform p =
p { pathPoints = map (addTuples transform) (pathPoints p),
pathFill = if null (pathFill p) then fill else pathFill p
}
updateShape :: String -- ^ The fill that may be added to the Shape.
-> Point -- ^ Transform that will be added to the Shape's
-- current transform value.
-> Shape
-> Shape
updateShape fill transform r =
r { shapePos = addTuples transform (shapePos r),
shapeFill = if null (shapeFill r) || shapeFill r == "none"
then fill
else shapeFill r,
shapeType_ = if fill == "#888888" then Hybrid
else case shapeType_ r of
Hybrid -> Hybrid
BoolNode -> BoolNode
Node -> Node
}
updateText :: Point -- ^ Transform that will be added to the input Shape's
-- current transform value.
-> Text
-> Text
updateText transform t =
t { textPos = addTuples transform (textPos t) }
-- | Adds two tuples together.
addTuples :: Point -> Point -> Point
addTuples (a,b) (c,d) = (a + c, b + d)
| alexbaluta/courseography | app/Svg/Parser.hs | gpl-3.0 | 13,673 | 0 | 18 | 4,149 | 3,053 | 1,589 | 1,464 | 263 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EC2.DeleteNetworkInterface
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified network interface. You must detach the network
-- interface before you can delete it.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkInterface.html AWS API Reference> for DeleteNetworkInterface.
module Network.AWS.EC2.DeleteNetworkInterface
(
-- * Creating a Request
deleteNetworkInterface
, DeleteNetworkInterface
-- * Request Lenses
, dninDryRun
, dninNetworkInterfaceId
-- * Destructuring the Response
, deleteNetworkInterfaceResponse
, DeleteNetworkInterfaceResponse
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'deleteNetworkInterface' smart constructor.
data DeleteNetworkInterface = DeleteNetworkInterface'
{ _dninDryRun :: !(Maybe Bool)
, _dninNetworkInterfaceId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteNetworkInterface' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dninDryRun'
--
-- * 'dninNetworkInterfaceId'
deleteNetworkInterface
:: Text -- ^ 'dninNetworkInterfaceId'
-> DeleteNetworkInterface
deleteNetworkInterface pNetworkInterfaceId_ =
DeleteNetworkInterface'
{ _dninDryRun = Nothing
, _dninNetworkInterfaceId = pNetworkInterfaceId_
}
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
dninDryRun :: Lens' DeleteNetworkInterface (Maybe Bool)
dninDryRun = lens _dninDryRun (\ s a -> s{_dninDryRun = a});
-- | The ID of the network interface.
dninNetworkInterfaceId :: Lens' DeleteNetworkInterface Text
dninNetworkInterfaceId = lens _dninNetworkInterfaceId (\ s a -> s{_dninNetworkInterfaceId = a});
instance AWSRequest DeleteNetworkInterface where
type Rs DeleteNetworkInterface =
DeleteNetworkInterfaceResponse
request = postQuery eC2
response
= receiveNull DeleteNetworkInterfaceResponse'
instance ToHeaders DeleteNetworkInterface where
toHeaders = const mempty
instance ToPath DeleteNetworkInterface where
toPath = const "/"
instance ToQuery DeleteNetworkInterface where
toQuery DeleteNetworkInterface'{..}
= mconcat
["Action" =:
("DeleteNetworkInterface" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"DryRun" =: _dninDryRun,
"NetworkInterfaceId" =: _dninNetworkInterfaceId]
-- | /See:/ 'deleteNetworkInterfaceResponse' smart constructor.
data DeleteNetworkInterfaceResponse =
DeleteNetworkInterfaceResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteNetworkInterfaceResponse' with the minimum fields required to make a request.
--
deleteNetworkInterfaceResponse
:: DeleteNetworkInterfaceResponse
deleteNetworkInterfaceResponse = DeleteNetworkInterfaceResponse'
| fmapfmapfmap/amazonka | amazonka-ec2/gen/Network/AWS/EC2/DeleteNetworkInterface.hs | mpl-2.0 | 3,987 | 0 | 11 | 760 | 447 | 271 | 176 | 64 | 1 |
----------------------------------------------------------------------------
-- |
-- Module : MainModule
-- Copyright : (c) Sergey Vinokurov 2018
-- License : BSD3-style (see LICENSE)
-- Maintainer : serg.foo@gmail.com
----------------------------------------------------------------------------
module MainModule where
import Dependency
| sergv/tags-server | test-data/0014module_imports_same_name_multiple_occurrences/MainModule.hs | bsd-3-clause | 356 | 0 | 3 | 48 | 14 | 12 | 2 | 2 | 0 |
{-# LANGUAGE MagicHash, UnboxedTuples #-}
-- |
-- Module : Data.Primitive.Addr
-- Copyright : (c) Roman Leshchinskiy 2009-2012
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Portability : non-portable
--
-- Primitive operations on machine addresses
--
module Data.Primitive.Addr (
-- * Types
Addr(..),
-- * Address arithmetic
nullAddr, plusAddr, minusAddr, remAddr,
-- * Element access
indexOffAddr, readOffAddr, writeOffAddr,
-- * Block operations
copyAddr, moveAddr, setAddr
) where
import Control.Monad.Primitive
import Data.Primitive.Types
import GHC.Base ( Int(..) )
import GHC.Prim
import GHC.Ptr
import Foreign.Marshal.Utils
-- | The null address
nullAddr :: Addr
nullAddr = Addr nullAddr#
infixl 6 `plusAddr`, `minusAddr`
infixl 7 `remAddr`
-- | Offset an address by the given number of bytes
plusAddr :: Addr -> Int -> Addr
plusAddr (Addr a#) (I# i#) = Addr (plusAddr# a# i#)
-- | Distance in bytes between two addresses. The result is only valid if the
-- difference fits in an 'Int'.
minusAddr :: Addr -> Addr -> Int
minusAddr (Addr a#) (Addr b#) = I# (minusAddr# a# b#)
-- | The remainder of the address and the integer.
remAddr :: Addr -> Int -> Int
remAddr (Addr a#) (I# i#) = I# (remAddr# a# i#)
-- | Read a value from a memory position given by an address and an offset.
-- The memory block the address refers to must be immutable. The offset is in
-- elements of type @a@ rather than in bytes.
indexOffAddr :: Prim a => Addr -> Int -> a
{-# INLINE indexOffAddr #-}
indexOffAddr (Addr addr#) (I# i#) = indexOffAddr# addr# i#
-- | Read a value from a memory position given by an address and an offset.
-- The offset is in elements of type @a@ rather than in bytes.
readOffAddr :: (Prim a, PrimMonad m) => Addr -> Int -> m a
{-# INLINE readOffAddr #-}
readOffAddr (Addr addr#) (I# i#) = primitive (readOffAddr# addr# i#)
-- | Write a value to a memory position given by an address and an offset.
-- The offset is in elements of type @a@ rather than in bytes.
writeOffAddr :: (Prim a, PrimMonad m) => Addr -> Int -> a -> m ()
{-# INLINE writeOffAddr #-}
writeOffAddr (Addr addr#) (I# i#) x = primitive_ (writeOffAddr# addr# i# x)
-- | Copy the given number of bytes from the second 'Addr' to the first. The
-- areas may not overlap.
copyAddr :: PrimMonad m => Addr -- ^ destination address
-> Addr -- ^ source address
-> Int -- ^ number of bytes
-> m ()
{-# INLINE copyAddr #-}
copyAddr (Addr dst#) (Addr src#) n
= unsafePrimToPrim $ copyBytes (Ptr dst#) (Ptr src#) n
-- | Copy the given number of bytes from the second 'Addr' to the first. The
-- areas may overlap.
moveAddr :: PrimMonad m => Addr -- ^ destination address
-> Addr -- ^ source address
-> Int -- ^ number of bytes
-> m ()
{-# INLINE moveAddr #-}
moveAddr (Addr dst#) (Addr src#) n
= unsafePrimToPrim $ moveBytes (Ptr dst#) (Ptr src#) n
-- | Fill a memory block of with the given value. The length is in
-- elements of type @a@ rather than in bytes.
setAddr :: (Prim a, PrimMonad m) => Addr -> Int -> a -> m ()
{-# INLINE setAddr #-}
setAddr (Addr addr#) (I# n#) x = primitive_ (setOffAddr# addr# 0# n# x)
| rleshchinskiy/primitive | Data/Primitive/Addr.hs | bsd-3-clause | 3,370 | 0 | 10 | 813 | 716 | 397 | 319 | 48 | 1 |
{-|
Module : Idris.REPL.Parser
Description : Parser for the REPL commands.
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.REPL.Parser (
parseCmd
, help
, allHelp
, setOptions
) where
import Idris.AbsSyntax
import Idris.Colours
import Idris.Core.TT
import Idris.Help
import qualified Idris.Parser as P
import Idris.REPL.Commands
import Control.Applicative
import Control.Monad.State.Strict
import qualified Data.ByteString.UTF8 as UTF8
import Data.Char (isSpace, toLower)
import Data.List
import Data.List.Split (splitOn)
import Debug.Trace
import System.Console.ANSI (Color(..))
import System.FilePath ((</>))
import Text.Parser.Char (anyChar, oneOf)
import Text.Parser.Combinators
import Text.Trifecta (Result, parseString)
import Text.Trifecta.Delta
parseCmd :: IState -> String -> String -> Result (Either String Command)
parseCmd i inputname = P.runparser pCmd i inputname . trim
where trim = f . f
where f = reverse . dropWhile isSpace
type CommandTable = [ ( [String], CmdArg, String
, String -> P.IdrisParser (Either String Command) ) ]
setOptions :: [(String, Opt)]
setOptions = [("errorcontext", ErrContext),
("showimplicits", ShowImpl),
("originalerrors", ShowOrigErr),
("autosolve", AutoSolve),
("nobanner", NoBanner),
("warnreach", WarnReach),
("evaltypes", EvalTypes),
("desugarnats", DesugarNats)]
help :: [([String], CmdArg, String)]
help = (["<expr>"], NoArg, "Evaluate an expression") :
[ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ]
allHelp :: [([String], CmdArg, String)]
allHelp = [ (map (':' :) names, args, text)
| (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ]
parserCommandsForHelp :: CommandTable
parserCommandsForHelp =
[ exprArgCmd ["t", "type"] Check "Check the type of an expression"
, exprArgCmd ["core"] Core "View the core language representation of a term"
, nameArgCmd ["miss", "missing"] Missing "Show missing clauses"
, (["doc"], NameArg, "Show internal documentation", cmd_doc)
, (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"
, genArg "namespace" (many anyChar) MakeDoc)
, (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"
, cmd_apropos)
, (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg
, " Search for values by type", cmd_search)
, nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name"
, nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name"
, namespaceArgCmd ["browse"] Browse "List the contents of some namespace"
, nameArgCmd ["total"] TotCheck "Check the totality of a name"
, noArgCmd ["r", "reload"] Reload "Reload current file"
, noArgCmd ["w", "watch"] Watch "Watch the current file for changes"
, (["l", "load"], FileArg, "Load a new file"
, strArg (\f -> Load f Nothing))
, (["cd"], FileArg, "Change working directory"
, strArg ChangeDirectory)
, (["module"], ModuleArg, "Import an extra module", moduleArg ModImport) -- NOTE: dragons
, noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL"
, noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables or holes)"
, (["p", "prove"], MetaVarArg, "Prove a metavariable"
, nameArg (Prove False))
, (["elab"], MetaVarArg, "Build a metavariable using the elaboration shell"
, nameArg (Prove True))
, (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof)
, (["rmproof"], NameArg, "Remove proof from proof stack"
, nameArg RmProof)
, (["showproof"], NameArg, "Show proof"
, nameArg ShowProof)
, noArgCmd ["proofs"] Proofs "Show available proofs"
, exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
, (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
, (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
, (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
, (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
, noArgCmd ["?", "h", "help"] Help "Display this help text"
, optArgCmd ["set"] SetOpt $ "Set an option (" ++ optionsList ++ ")"
, optArgCmd ["unset"] UnsetOpt "Unset an option"
, (["color", "colour"], ColourArg
, "Turn REPL colours on or off; set a specific colour"
, cmd_colour)
, (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)
, (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth)
, noArgCmd ["q", "quit"] Quit "Exit the Idris system"
, noArgCmd ["warranty"] Warranty "Displays warranty information"
, (["let"], ManyArgs DeclArg
, "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"
, cmd_let)
, (["unlet", "undefine"], ManyArgs NameArg
, "Remove the listed repl definitions, or all repl definitions if no names given"
, cmd_unlet)
, nameArgCmd ["printdef"] PrintDef "Show the definition of a function"
, (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
, "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
, cmd_pprint)
]
where optionsList = intercalate ", " $ map fst setOptions
parserCommands =
[ noArgCmd ["u", "universes"] Universes "Display universe constraints"
, noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers"
, nameArgCmd ["d", "def"] Defn "Display a name's internal definitions"
, nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name"
, nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name"
, exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression"
, exprArgCmd ["spec"] Spec "?"
, exprArgCmd ["whnf"] WHNF "(Debugging) Show weak head normal form of an expression"
, exprArgCmd ["inline"] TestInline "?"
, proofArgCmd ["cs", "casesplit"] CaseSplitAt
":cs <line> <name> splits the pattern variable on the line"
, proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom
":apc <line> <name> adds a pattern-matching proof clause to name on line"
, proofArgCmd ["ac", "addclause"] AddClauseFrom
":ac <line> <name> adds a clause for the definition of the name on the line"
, proofArgCmd ["am", "addmissing"] AddMissing
":am <line> <name> adds all missing pattern matches for the name on the line"
, proofArgCmd ["mw", "makewith"] MakeWith
":mw <line> <name> adds a with clause for the definition of the name on the line"
, proofArgCmd ["mc", "makecase"] MakeCase
":mc <line> <name> adds a case block for the definition of the metavariable on the line"
, proofArgCmd ["ml", "makelemma"] MakeLemma "?"
, (["log"], NumberArg, "Set logging verbosity level", cmd_log)
, ( ["logcats"]
, ManyArgs NameArg
, "Set logging categories"
, cmd_cats)
, (["lto", "loadto"], SeqArgs NumberArg FileArg
, "Load file up to line number", cmd_loadto)
, (["ps", "proofsearch"], NoArg
, ":ps <line> <name> <names> does proof search for name on line, with names as hints"
, cmd_proofsearch)
, (["ref", "refine"], NoArg
, ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable"
, cmd_refine)
, (["debugunify"], SeqArgs ExprArg ExprArg
, "(Debugging) Try to unify two expressions", const $ do
l <- P.simpleExpr defaultSyntax
r <- P.simpleExpr defaultSyntax
eof
return (Right (DebugUnify l r))
)
]
noArgCmd names command doc =
(names, NoArg, doc, noArgs command)
nameArgCmd names command doc =
(names, NameArg, doc, fnNameArg command)
namespaceArgCmd names command doc =
(names, NamespaceArg, doc, namespaceArg command)
exprArgCmd names command doc =
(names, ExprArg, doc, exprArg command)
metavarArgCmd names command doc =
(names, MetaVarArg, doc, fnNameArg command)
optArgCmd names command doc =
(names, OptionArg, doc, optArg command)
proofArgCmd names command doc =
(names, NoArg, doc, proofArg command)
pCmd :: P.IdrisParser (Either String Command)
pCmd = choice [ do c <- cmd names; parser c
| (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]
<|> unrecognized
<|> nop
<|> eval
where nop = do eof; return (Right NOP)
unrecognized = do
P.lchar ':'
cmd <- many anyChar
let cmd' = takeWhile (/=' ') cmd
return (Left $ "Unrecognized command: " ++ cmd')
cmd :: [String] -> P.IdrisParser String
cmd xs = try $ do
P.lchar ':'
docmd sorted_xs
where docmd [] = fail "Could not parse command"
docmd (x:xs) = try (P.reserved x >> return x) <|> docmd xs
sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs
noArgs :: Command -> String -> P.IdrisParser (Either String Command)
noArgs cmd name = do
let emptyArgs = do
eof
return (Right cmd)
let failure = return (Left $ ":" ++ name ++ " takes no arguments")
emptyArgs <|> failure
eval :: P.IdrisParser (Either String Command)
eval = do
t <- P.fullExpr defaultSyntax
return $ Right (Eval t)
exprArg :: (PTerm -> Command) -> String -> P.IdrisParser (Either String Command)
exprArg cmd name = do
let noArg = do
eof
return $ Left ("Usage is :" ++ name ++ " <expression>")
let justOperator = do
(op, fc) <- P.operatorFC
eof
return $ Right $ cmd (PRef fc [] (sUN op))
let properArg = do
t <- P.fullExpr defaultSyntax
return $ Right (cmd t)
try noArg <|> try justOperator <|> properArg
genArg :: String -> P.IdrisParser a -> (a -> Command)
-> String -> P.IdrisParser (Either String Command)
genArg argName argParser cmd name = do
let emptyArgs = do eof; failure
oneArg = do arg <- argParser
eof
return (Right (cmd arg))
try emptyArgs <|> oneArg <|> failure
where
failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">")
nameArg, fnNameArg :: (Name -> Command) -> String -> P.IdrisParser (Either String Command)
nameArg = genArg "name" $ fst <$> P.name
fnNameArg = genArg "functionname" $ fst <$> P.fnName
strArg :: (String -> Command) -> String -> P.IdrisParser (Either String Command)
strArg = genArg "string" (many anyChar)
moduleArg :: (FilePath -> Command) -> String -> P.IdrisParser (Either String Command)
moduleArg = genArg "module" (fmap (toPath . fst) P.identifier)
where
toPath n = foldl1' (</>) $ splitOn "." n
namespaceArg :: ([String] -> Command) -> String -> P.IdrisParser (Either String Command)
namespaceArg = genArg "namespace" (fmap (toNS . fst) P.identifier)
where
toNS = splitOn "."
optArg :: (Opt -> Command) -> String -> P.IdrisParser (Either String Command)
optArg cmd name = do
let emptyArgs = do
eof
return $ Left ("Usage is :" ++ name ++ " <option>")
let oneArg = do
o <- pOption
P.whiteSpace
eof
return (Right (cmd o))
let failure = return $ Left "Unrecognized setting"
try emptyArgs <|> oneArg <|> failure
where
pOption :: P.IdrisParser Opt
pOption = foldl (<|>) empty $ map (\(a, b) -> do discard (P.symbol a); return b) setOptions
proofArg :: (Bool -> Int -> Name -> Command) -> String -> P.IdrisParser (Either String Command)
proofArg cmd name = do
upd <- option False $ do
P.lchar '!'
return True
l <- fst <$> P.natural
n <- fst <$> P.name;
return (Right (cmd upd (fromInteger l) n))
cmd_doc :: String -> P.IdrisParser (Either String Command)
cmd_doc name = do
let constant = do
c <- fmap fst P.constant
eof
return $ Right (DocStr (Right c) FullDocs)
let pType = do
P.reserved "Type"
eof
return $ Right (DocStr (Left $ P.mkName ("Type", "")) FullDocs)
let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
try constant <|> pType <|> fnName
cmd_consolewidth :: String -> P.IdrisParser (Either String Command)
cmd_consolewidth name = do
w <- pConsoleWidth
return (Right (SetConsoleWidth w))
where
pConsoleWidth :: P.IdrisParser ConsoleWidth
pConsoleWidth = do discard (P.symbol "auto"); return AutomaticWidth
<|> do discard (P.symbol "infinite"); return InfinitelyWide
<|> do n <- fmap (fromInteger . fst) P.natural
return (ColsWide n)
cmd_printdepth :: String -> P.IdrisParser (Either String Command)
cmd_printdepth _ = do d <- optional (fmap (fromInteger . fst) P.natural)
return (Right $ SetPrinterDepth d)
cmd_execute :: String -> P.IdrisParser (Either String Command)
cmd_execute name = do
tm <- option maintm (P.fullExpr defaultSyntax)
return (Right (Execute tm))
where
maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"])
cmd_dynamic :: String -> P.IdrisParser (Either String Command)
cmd_dynamic name = do
let optArg = do l <- many anyChar
if (l /= "")
then return $ Right (DynamicLink l)
else return $ Right ListDynamic
let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
try optArg <|> failure
cmd_pprint :: String -> P.IdrisParser (Either String Command)
cmd_pprint name = do
fmt <- ppFormat
P.whiteSpace
n <- fmap (fromInteger . fst) P.natural
P.whiteSpace
t <- P.fullExpr defaultSyntax
return (Right (PPrint fmt n t))
where
ppFormat :: P.IdrisParser OutputFmt
ppFormat = (discard (P.symbol "html") >> return HTMLOutput)
<|> (discard (P.symbol "latex") >> return LaTeXOutput)
cmd_compile :: String -> P.IdrisParser (Either String Command)
cmd_compile name = do
let defaultCodegen = Via IBCFormat "c"
let codegenOption :: P.IdrisParser Codegen
codegenOption = do
let bytecodeCodegen = discard (P.symbol "bytecode") *> return Bytecode
viaCodegen = do x <- fst <$> P.identifier
return (Via IBCFormat (map toLower x))
bytecodeCodegen <|> viaCodegen
let hasOneArg = do
i <- get
f <- fst <$> P.identifier
eof
return $ Right (Compile defaultCodegen f)
let hasTwoArgs = do
i <- get
codegen <- codegenOption
f <- fst <$> P.identifier
eof
return $ Right (Compile codegen f)
let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
try hasTwoArgs <|> try hasOneArg <|> failure
cmd_addproof :: String -> P.IdrisParser (Either String Command)
cmd_addproof name = do
n <- option Nothing $ do
x <- fst <$> P.name
return (Just x)
eof
return (Right (AddProof n))
cmd_log :: String -> P.IdrisParser (Either String Command)
cmd_log name = do
i <- fmap (fromIntegral . fst) P.natural
eof
return (Right (LogLvl i))
cmd_cats :: String -> P.IdrisParser (Either String Command)
cmd_cats name = do
cs <- sepBy pLogCats (P.whiteSpace)
eof
return $ Right $ LogCategory (concat cs)
where
badCat = do
c <- fst <$> P.identifier
fail $ "Category: " ++ c ++ " is not recognised."
pLogCats :: P.IdrisParser [LogCat]
pLogCats = try (P.symbol (strLogCat IParse) >> return parserCats)
<|> try (P.symbol (strLogCat IElab) >> return elabCats)
<|> try (P.symbol (strLogCat ICodeGen) >> return codegenCats)
<|> try (P.symbol (strLogCat ICoverage) >> return [ICoverage])
<|> try (P.symbol (strLogCat IIBC) >> return [IIBC])
<|> try (P.symbol (strLogCat IErasure) >> return [IErasure])
<|> badCat
cmd_let :: String -> P.IdrisParser (Either String Command)
cmd_let name = do
defn <- concat <$> many (P.decl defaultSyntax)
return (Right (NewDefn defn))
cmd_unlet :: String -> P.IdrisParser (Either String Command)
cmd_unlet name = (Right . Undefine) `fmap` many (fst <$> P.name)
cmd_loadto :: String -> P.IdrisParser (Either String Command)
cmd_loadto name = do
toline <- fmap (fromInteger . fst) P.natural
f <- many anyChar;
return (Right (Load f (Just toline)))
cmd_colour :: String -> P.IdrisParser (Either String Command)
cmd_colour name = fmap Right pSetColourCmd
where
colours :: [(String, Maybe Color)]
colours = [ ("black", Just Black)
, ("red", Just Red)
, ("green", Just Green)
, ("yellow", Just Yellow)
, ("blue", Just Blue)
, ("magenta", Just Magenta)
, ("cyan", Just Cyan)
, ("white", Just White)
, ("default", Nothing)
]
pSetColourCmd :: P.IdrisParser Command
pSetColourCmd = (do c <- pColourType
let defaultColour = IdrisColour Nothing True False False False
opts <- sepBy pColourMod (P.whiteSpace)
let colour = foldr ($) defaultColour $ reverse opts
return $ SetColour c colour)
<|> try (P.symbol "on" >> return ColourOn)
<|> try (P.symbol "off" >> return ColourOff)
pColour :: P.IdrisParser (Maybe Color)
pColour = doColour colours
where doColour [] = fail "Unknown colour"
doColour ((s, c):cs) = (try (P.symbol s) >> return c) <|> doColour cs
pColourMod :: P.IdrisParser (IdrisColour -> IdrisColour)
pColourMod = try (P.symbol "vivid" >> return doVivid)
<|> try (P.symbol "dull" >> return doDull)
<|> try (P.symbol "underline" >> return doUnderline)
<|> try (P.symbol "nounderline" >> return doNoUnderline)
<|> try (P.symbol "bold" >> return doBold)
<|> try (P.symbol "nobold" >> return doNoBold)
<|> try (P.symbol "italic" >> return doItalic)
<|> try (P.symbol "noitalic" >> return doNoItalic)
<|> try (pColour >>= return . doSetColour)
where doVivid i = i { vivid = True }
doDull i = i { vivid = False }
doUnderline i = i { underline = True }
doNoUnderline i = i { underline = False }
doBold i = i { bold = True }
doNoBold i = i { bold = False }
doItalic i = i { italic = True }
doNoItalic i = i { italic = False }
doSetColour c i = i { colour = c }
-- | Generate the colour type names using the default Show instance.
colourTypes :: [(String, ColourType)]
colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
enumFromTo minBound maxBound
pColourType :: P.IdrisParser ColourType
pColourType = doColourType colourTypes
where doColourType [] = fail $ "Unknown colour category. Options: " ++
(concat . intersperse ", " . map fst) colourTypes
doColourType ((s,ct):cts) = (try (P.symbol s) >> return ct) <|> doColourType cts
idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
cmd_apropos :: String -> P.IdrisParser (Either String Command)
cmd_apropos = packageBasedCmd (some idChar) Apropos
packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command)
-> String -> P.IdrisParser (Either String Command)
packageBasedCmd valParser cmd name =
try (do P.lchar '('
pkgs <- sepBy (some idChar) (P.lchar ',')
P.lchar ')'
val <- valParser
return (Right (cmd pkgs val)))
<|> do val <- valParser
return (Right (cmd [] val))
cmd_search :: String -> P.IdrisParser (Either String Command)
cmd_search = packageBasedCmd
(P.fullExpr (defaultSyntax { implicitAllowed = True })) Search
cmd_proofsearch :: String -> P.IdrisParser (Either String Command)
cmd_proofsearch name = do
upd <- option False (do P.lchar '!'; return True)
l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
hints <- many (fst <$> P.fnName)
return (Right (DoProofSearch upd True l n hints))
cmd_refine :: String -> P.IdrisParser (Either String Command)
cmd_refine name = do
upd <- option False (do P.lchar '!'; return True)
l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
hint <- fst <$> P.fnName
return (Right (DoProofSearch upd False l n [hint]))
| ben-schulz/Idris-dev | src/Idris/REPL/Parser.hs | bsd-3-clause | 21,206 | 0 | 21 | 5,562 | 6,694 | 3,459 | 3,235 | 435 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.X11.Xlib
-- Copyright : (c) Alastair Reid, 1999-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- A collection of FFI declarations for interfacing with Xlib.
--
-- The library aims to provide a direct translation of the X
-- binding into Haskell so the most important documentation you
-- should read is /The Xlib Programming Manual/, available online at
-- <http://tronche.com/gui/x/xlib/>. Let me say that again because
-- it is very important. Get hold of this documentation and read it:
-- it tells you almost everything you need to know to use this library.
--
-----------------------------------------------------------------------------
module Graphics.X11.Xlib
( -- * Conventions
-- $conventions
-- * Types
module Graphics.X11.Types,
-- module Graphics.X11.Xlib.Types,
Display(..), Screen, Visual, GC, SetWindowAttributes, VisualInfo(..),
Point(..), Rectangle(..), Arc(..), Segment(..), Color(..),
Pixel, Position, Dimension, Angle, ScreenNumber, Buffer,
-- * X11 library functions
module Graphics.X11.Xlib.Event,
module Graphics.X11.Xlib.Display,
module Graphics.X11.Xlib.Screen,
module Graphics.X11.Xlib.Window,
module Graphics.X11.Xlib.Context,
module Graphics.X11.Xlib.Color,
module Graphics.X11.Xlib.Cursor,
module Graphics.X11.Xlib.Font,
module Graphics.X11.Xlib.Atom,
module Graphics.X11.Xlib.Region,
module Graphics.X11.Xlib.Image,
module Graphics.X11.Xlib.Misc,
) where
import Graphics.X11.Types
import Graphics.X11.Xlib.Types
import Graphics.X11.Xlib.Event
import Graphics.X11.Xlib.Display
import Graphics.X11.Xlib.Screen
import Graphics.X11.Xlib.Window
import Graphics.X11.Xlib.Context
import Graphics.X11.Xlib.Color
import Graphics.X11.Xlib.Cursor
import Graphics.X11.Xlib.Font
import Graphics.X11.Xlib.Atom
import Graphics.X11.Xlib.Region
import Graphics.X11.Xlib.Image
import Graphics.X11.Xlib.Misc
{- $conventions
In translating the library, we had to change names to conform with
Haskell's lexical syntax: function names and names of constants must start
with a lowercase letter; type names must start with an uppercase letter.
The case of the remaining letters is unchanged.
In addition, we chose to take advantage of Haskell's module system to
allow us to drop common prefixes (@X@, @XA_@, etc.) attached to X11
identifiers.
We named enumeration types so that function types would be easier
to understand. For example, we added 'Status', 'WindowClass', etc.
Note that the types are synonyms for 'Int' so no extra typesafety was
obtained.
We consistently raise exceptions when a function returns an error code.
In practice, this only affects the following functions because most Xlib
functions do not return error codes: 'allocColor', 'allocNamedColor',
'fetchBuffer', 'fetchBytes', 'fontFromGC', 'getGeometry', 'getIconName',
'iconifyWindow', 'loadQueryFont', 'lookupColor', 'openDisplay',
'parseColor', 'queryBestCursor', 'queryBestSize', 'queryBestStipple',
'queryBestTile', 'rotateBuffers', 'selectInput', 'storeBuffer',
'storeBytes', 'withdrawWindow'.
-}
----------------------------------------------------------------
-- End
----------------------------------------------------------------
| VIETCONG/X11 | Graphics/X11/Xlib.hs | bsd-3-clause | 3,542 | 12 | 5 | 567 | 330 | 243 | 87 | 32 | 0 |
-- |
-- The Reader monad transformer.
--
-- This is useful to keep a non-modifiable value
-- in a context
{-# LANGUAGE ConstraintKinds #-}
module Foundation.Monad.Reader
( -- * MonadReader
MonadReader(..)
, -- * ReaderT
ReaderT
, runReaderT
) where
import Basement.Compat.Base (($), (.), const)
import Foundation.Monad.Base
import Foundation.Monad.Exception
class Monad m => MonadReader m where
type ReaderContext m
ask :: m (ReaderContext m)
-- | Reader Transformer
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
instance Functor m => Functor (ReaderT r m) where
fmap f m = ReaderT $ fmap f . runReaderT m
{-# INLINE fmap #-}
instance Applicative m => Applicative (ReaderT r m) where
pure a = ReaderT $ const (pure a)
{-# INLINE pure #-}
fab <*> fa = ReaderT $ \r -> runReaderT fab r <*> runReaderT fa r
{-# INLINE (<*>) #-}
instance Monad m => Monad (ReaderT r m) where
return a = ReaderT $ const (return a)
{-# INLINE return #-}
ma >>= mab = ReaderT $ \r -> runReaderT ma r >>= \a -> runReaderT (mab a) r
{-# INLINE (>>=) #-}
instance (Monad m, MonadFix m) => MonadFix (ReaderT s m) where
mfix f = ReaderT $ \r -> mfix $ \a -> runReaderT (f a) r
{-# INLINE mfix #-}
instance MonadTrans (ReaderT r) where
lift f = ReaderT $ const f
{-# INLINE lift #-}
instance MonadIO m => MonadIO (ReaderT r m) where
liftIO f = lift (liftIO f)
{-# INLINE liftIO #-}
instance MonadFailure m => MonadFailure (ReaderT r m) where
type Failure (ReaderT r m) = Failure m
mFail e = ReaderT $ \_ -> mFail e
instance MonadThrow m => MonadThrow (ReaderT r m) where
throw e = ReaderT $ \_ -> throw e
instance MonadCatch m => MonadCatch (ReaderT r m) where
catch (ReaderT m) c = ReaderT $ \r -> m r `catch` (\e -> runReaderT (c e) r)
instance MonadBracket m => MonadBracket (ReaderT r m) where
generalBracket acq cleanup cleanupExcept innerAction = do
c <- ask
lift $ generalBracket (runReaderT acq c)
(\a b -> runReaderT (cleanup a b) c)
(\a exn -> runReaderT (cleanupExcept a exn) c)
(\a -> runReaderT (innerAction a) c)
instance Monad m => MonadReader (ReaderT r m) where
type ReaderContext (ReaderT r m) = r
ask = ReaderT return
| vincenthz/hs-foundation | foundation/Foundation/Monad/Reader.hs | bsd-3-clause | 2,372 | 0 | 14 | 646 | 843 | 438 | 405 | -1 | -1 |
module Sortier.Netz.Example where
-- $Id$
import Sortier.Netz.Type
bubble :: Int -> Netz
bubble n = mkNetz $ do
hi <- [ 2 .. n ]
lo <- reverse [ 1 .. pred hi ]
return ( lo, succ lo )
bad_example :: Int -> Netz
bad_example n = mkNetz $ do
hi <- [ 2 .. n ]
lo <- reverse [ 1 , 3 .. pred hi ]
return ( lo, succ lo )
| florianpilz/autotool | src/Sortier/Netz/Example.hs | gpl-2.0 | 344 | 0 | 11 | 106 | 153 | 80 | 73 | 12 | 1 |
module Stack.Options.ScriptParser where
import Data.Monoid ((<>))
import Options.Applicative
import Options.Applicative.Builder.Extra
data ScriptOpts = ScriptOpts
{ soPackages :: ![String]
, soFile :: !FilePath
, soArgs :: ![String]
, soCompile :: !ScriptExecute
}
deriving Show
data ScriptExecute
= SEInterpret
| SECompile
| SEOptimize
deriving Show
scriptOptsParser :: Parser ScriptOpts
scriptOptsParser = ScriptOpts
<$> many (strOption (long "package" <> help "Additional packages that must be installed"))
<*> strArgument (metavar "FILE" <> completer (fileExtCompleter [".hs", ".lhs"]))
<*> many (strArgument (metavar "-- ARGS (e.g. stack ghc -- X.hs -o x)"))
<*> (flag' SECompile
( long "compile"
<> help "Compile the script without optimization and run the executable"
) <|>
flag' SEOptimize
( long "optimize"
<> help "Compile the script with optimization and run the executable"
) <|>
pure SEInterpret)
| mrkkrp/stack | src/Stack/Options/ScriptParser.hs | bsd-3-clause | 1,068 | 0 | 14 | 282 | 237 | 127 | 110 | 37 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bits
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- This module defines bitwise operations for signed and unsigned
-- integers. Instances of the class 'Bits' for the 'Int' and
-- 'Integer' types are available from this module, and instances for
-- explicitly sized integral types are available from the
-- "Data.Int" and "Data.Word" modules.
--
-----------------------------------------------------------------------------
module Data.Bits (
Bits(
(.&.), (.|.), xor,
complement,
shift,
rotate,
zeroBits,
bit,
setBit,
clearBit,
complementBit,
testBit,
bitSizeMaybe,
bitSize,
isSigned,
shiftL, shiftR,
unsafeShiftL, unsafeShiftR,
rotateL, rotateR,
popCount
),
FiniteBits(
finiteBitSize,
countLeadingZeros,
countTrailingZeros
),
bitDefault,
testBitDefault,
popCountDefault,
toIntegralSized
) where
-- Defines the @Bits@ class containing bit-based operations.
-- See library document for details on the semantics of the
-- individual operations.
#include "MachDeps.h"
import Data.Maybe
import GHC.Enum
import GHC.Num
import GHC.Base
import GHC.Real
#if defined(MIN_VERSION_integer_gmp)
import GHC.Integer.GMP.Internals (bitInteger, popCountInteger)
#endif
infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR`
infixl 7 .&.
infixl 6 `xor`
infixl 5 .|.
{-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8
-- | The 'Bits' class defines bitwise operations over integral types.
--
-- * Bits are numbered from 0 with bit 0 being the least
-- significant bit.
class Eq a => Bits a where
{-# MINIMAL (.&.), (.|.), xor, complement,
(shift | (shiftL, shiftR)),
(rotate | (rotateL, rotateR)),
bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-}
-- | Bitwise \"and\"
(.&.) :: a -> a -> a
-- | Bitwise \"or\"
(.|.) :: a -> a -> a
-- | Bitwise \"xor\"
xor :: a -> a -> a
{-| Reverse all the bits in the argument -}
complement :: a -> a
{-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this unified 'shift' or 'shiftL' and
'shiftR', depending on which is more convenient for the type in
question. -}
shift :: a -> Int -> a
x `shift` i | i<0 = x `shiftR` (-i)
| i>0 = x `shiftL` i
| otherwise = x
{-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'.
An instance can define either this unified 'rotate' or 'rotateL' and
'rotateR', depending on which is more convenient for the type in
question. -}
rotate :: a -> Int -> a
x `rotate` i | i<0 = x `rotateR` (-i)
| i>0 = x `rotateL` i
| otherwise = x
{-
-- Rotation can be implemented in terms of two shifts, but care is
-- needed for negative values. This suggested implementation assumes
-- 2's-complement arithmetic. It is commented out because it would
-- require an extra context (Ord a) on the signature of 'rotate'.
x `rotate` i | i<0 && isSigned x && x<0
= let left = i+bitSize x in
((x `shift` i) .&. complement ((-1) `shift` left))
.|. (x `shift` left)
| i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x))
| i==0 = x
| i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x))
-}
-- | 'zeroBits' is the value with all bits unset.
--
-- The following laws ought to hold (for all valid bit indices @/n/@):
--
-- * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@
-- * @'setBit' 'zeroBits' /n/ == 'bit' /n/@
-- * @'testBit' 'zeroBits' /n/ == False@
-- * @'popCount' 'zeroBits' == 0@
--
-- This method uses @'clearBit' ('bit' 0) 0@ as its default
-- implementation (which ought to be equivalent to 'zeroBits' for
-- types which possess a 0th bit).
--
-- @since 4.7.0.0
zeroBits :: a
zeroBits = clearBit (bit 0) 0
-- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear.
--
-- Can be implemented using `bitDefault' if @a@ is also an
-- instance of 'Num'.
--
-- See also 'zeroBits'.
bit :: Int -> a
-- | @x \`setBit\` i@ is the same as @x .|. bit i@
setBit :: a -> Int -> a
-- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@
clearBit :: a -> Int -> a
-- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@
complementBit :: a -> Int -> a
-- | Return 'True' if the @n@th bit of the argument is 1
--
-- Can be implemented using `testBitDefault' if @a@ is also an
-- instance of 'Num'.
testBit :: a -> Int -> Bool
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. Returns Nothing
for types that do not have a fixed bitsize, like 'Integer'.
@since 4.7.0.0
-}
bitSizeMaybe :: a -> Maybe Int
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. The function 'bitSize' is
undefined for types that do not have a fixed bitsize, like 'Integer'.
-}
bitSize :: a -> Int
{-| Return 'True' if the argument is a signed type. The actual
value of the argument is ignored -}
isSigned :: a -> Bool
{-# INLINE setBit #-}
{-# INLINE clearBit #-}
{-# INLINE complementBit #-}
x `setBit` i = x .|. bit i
x `clearBit` i = x .&. complement (bit i)
x `complementBit` i = x `xor` bit i
{-| Shift the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'shiftR' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftL :: a -> Int -> a
{-# INLINE shiftL #-}
x `shiftL` i = x `shift` i
{-| Shift the argument left by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Defaults to 'shiftL' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftL :: a -> Int -> a
{-# INLINE unsafeShiftL #-}
x `unsafeShiftL` i = x `shiftL` i
{-| Shift the first argument right by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this and 'shiftL' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftR :: a -> Int -> a
{-# INLINE shiftR #-}
x `shiftR` i = x `shift` (-i)
{-| Shift the first argument right by the specified number of bits, which
must be non-negative and smaller than the number of bits in the type.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
Defaults to 'shiftR' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftR :: a -> Int -> a
{-# INLINE unsafeShiftR #-}
x `unsafeShiftR` i = x `shiftR` i
{-| Rotate the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateR' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateL :: a -> Int -> a
{-# INLINE rotateL #-}
x `rotateL` i = x `rotate` i
{-| Rotate the argument right by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateL' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateR :: a -> Int -> a
{-# INLINE rotateR #-}
x `rotateR` i = x `rotate` (-i)
{-| Return the number of set bits in the argument. This number is
known as the population count or the Hamming weight.
Can be implemented using `popCountDefault' if @a@ is also an
instance of 'Num'.
@since 4.5.0.0 -}
popCount :: a -> Int
-- |The 'FiniteBits' class denotes types with a finite, fixed number of bits.
--
-- @since 4.7.0.0
class Bits b => FiniteBits b where
-- | Return the number of bits in the type of the argument.
-- The actual value of the argument is ignored. Moreover, 'finiteBitSize'
-- is total, in contrast to the deprecated 'bitSize' function it replaces.
--
-- @
-- 'finiteBitSize' = 'bitSize'
-- 'bitSizeMaybe' = 'Just' . 'finiteBitSize'
-- @
--
-- @since 4.7.0.0
finiteBitSize :: b -> Int
-- | Count number of zero bits preceding the most significant set bit.
--
-- @
-- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- @
--
-- 'countLeadingZeros' can be used to compute log base 2 via
--
-- @
-- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countLeadingZeros :: b -> Int
countLeadingZeros x = (w-1) - go (w-1)
where
go i | i < 0 = i -- no bit set
| testBit x i = i
| otherwise = go (i-1)
w = finiteBitSize x
-- | Count number of zero bits following the least significant set bit.
--
-- @
-- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- 'countTrailingZeros' . 'negate' = 'countTrailingZeros'
-- @
--
-- The related
-- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation>
-- can be expressed in terms of 'countTrailingZeros' as follows
--
-- @
-- findFirstSet x = 1 + 'countTrailingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countTrailingZeros :: b -> Int
countTrailingZeros x = go 0
where
go i | i >= w = i
| testBit x i = i
| otherwise = go (i+1)
w = finiteBitSize x
-- The defaults below are written with lambdas so that e.g.
-- bit = bitDefault
-- is fully applied, so inlining will happen
-- | Default implementation for 'bit'.
--
-- Note that: @bitDefault i = 1 `shiftL` i@
--
-- @since 4.6.0.0
bitDefault :: (Bits a, Num a) => Int -> a
bitDefault = \i -> 1 `shiftL` i
{-# INLINE bitDefault #-}
-- | Default implementation for 'testBit'.
--
-- Note that: @testBitDefault x i = (x .&. bit i) /= 0@
--
-- @since 4.6.0.0
testBitDefault :: (Bits a, Num a) => a -> Int -> Bool
testBitDefault = \x i -> (x .&. bit i) /= 0
{-# INLINE testBitDefault #-}
-- | Default implementation for 'popCount'.
--
-- This implementation is intentionally naive. Instances are expected to provide
-- an optimized implementation for their size.
--
-- @since 4.6.0.0
popCountDefault :: (Bits a, Num a) => a -> Int
popCountDefault = go 0
where
go !c 0 = c
go c w = go (c+1) (w .&. (w - 1)) -- clear the least significant
{-# INLINABLE popCountDefault #-}
-- | Interpret 'Bool' as 1-bit bit-field
--
-- @since 4.7.0.0
instance Bits Bool where
(.&.) = (&&)
(.|.) = (||)
xor = (/=)
complement = not
shift x 0 = x
shift _ _ = False
rotate x _ = x
bit 0 = True
bit _ = False
testBit x 0 = x
testBit _ _ = False
bitSizeMaybe _ = Just 1
bitSize _ = 1
isSigned _ = False
popCount False = 0
popCount True = 1
-- | @since 4.7.0.0
instance FiniteBits Bool where
finiteBitSize _ = 1
countTrailingZeros x = if x then 0 else 1
countLeadingZeros x = if x then 0 else 1
-- | @since 2.01
instance Bits Int where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
zeroBits = 0
bit = bitDefault
testBit = testBitDefault
(I# x#) .&. (I# y#) = I# (x# `andI#` y#)
(I# x#) .|. (I# y#) = I# (x# `orI#` y#)
(I# x#) `xor` (I# y#) = I# (x# `xorI#` y#)
complement (I# x#) = I# (notI# x#)
(I# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I# (x# `iShiftL#` i#)
| otherwise = I# (x# `iShiftRA#` negateInt# i#)
(I# x#) `shiftL` (I# i#) = I# (x# `iShiftL#` i#)
(I# x#) `unsafeShiftL` (I# i#) = I# (x# `uncheckedIShiftL#` i#)
(I# x#) `shiftR` (I# i#) = I# (x# `iShiftRA#` i#)
(I# x#) `unsafeShiftR` (I# i#) = I# (x# `uncheckedIShiftRA#` i#)
{-# INLINE rotate #-} -- See Note [Constant folding for rotate]
(I# x#) `rotate` (I# i#) =
I# ((x# `uncheckedIShiftL#` i'#) `orI#` (x# `uncheckedIShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
popCount (I# x#) = I# (word2Int# (popCnt# (int2Word# x#)))
isSigned _ = True
-- | @since 4.6.0.0
instance FiniteBits Int where
finiteBitSize _ = WORD_SIZE_IN_BITS
countLeadingZeros (I# x#) = I# (word2Int# (clz# (int2Word# x#)))
countTrailingZeros (I# x#) = I# (word2Int# (ctz# (int2Word# x#)))
-- | @since 2.01
instance Bits Word where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W# x#) .&. (W# y#) = W# (x# `and#` y#)
(W# x#) .|. (W# y#) = W# (x# `or#` y#)
(W# x#) `xor` (W# y#) = W# (x# `xor#` y#)
complement (W# x#) = W# (x# `xor#` mb#)
where !(W# mb#) = maxBound
(W# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W# (x# `shiftL#` i#)
| otherwise = W# (x# `shiftRL#` negateInt# i#)
(W# x#) `shiftL` (I# i#) = W# (x# `shiftL#` i#)
(W# x#) `unsafeShiftL` (I# i#) = W# (x# `uncheckedShiftL#` i#)
(W# x#) `shiftR` (I# i#) = W# (x# `shiftRL#` i#)
(W# x#) `unsafeShiftR` (I# i#) = W# (x# `uncheckedShiftRL#` i#)
(W# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W# x#
| otherwise = W# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W# x#) = I# (word2Int# (popCnt# x#))
bit = bitDefault
testBit = testBitDefault
-- | @since 4.6.0.0
instance FiniteBits Word where
finiteBitSize _ = WORD_SIZE_IN_BITS
countLeadingZeros (W# x#) = I# (word2Int# (clz# x#))
countTrailingZeros (W# x#) = I# (word2Int# (ctz# x#))
-- | @since 2.01
instance Bits Integer where
(.&.) = andInteger
(.|.) = orInteger
xor = xorInteger
complement = complementInteger
shift x i@(I# i#) | i >= 0 = shiftLInteger x i#
| otherwise = shiftRInteger x (negateInt# i#)
testBit x (I# i) = testBitInteger x i
zeroBits = 0
#if defined(MIN_VERSION_integer_gmp)
bit (I# i#) = bitInteger i#
popCount x = I# (popCountInteger x)
#else
bit = bitDefault
popCount = popCountDefault
#endif
rotate x i = shift x i -- since an Integer never wraps around
bitSizeMaybe _ = Nothing
bitSize _ = errorWithoutStackTrace "Data.Bits.bitSize(Integer)"
isSigned _ = True
-----------------------------------------------------------------------------
-- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using
-- the size of the types as measured by 'Bits' methods.
--
-- A simpler version of this function is:
--
-- > toIntegral :: (Integral a, Integral b) => a -> Maybe b
-- > toIntegral x
-- > | toInteger x == y = Just (fromInteger y)
-- > | otherwise = Nothing
-- > where
-- > y = toInteger x
--
-- This version requires going through 'Integer', which can be inefficient.
-- However, @toIntegralSized@ is optimized to allow GHC to statically determine
-- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and
-- avoid going through 'Integer' for many types. (The implementation uses
-- 'fromIntegral', which is itself optimized with rules for @base@ types but may
-- go through 'Integer' for some type pairs.)
--
-- @since 4.8.0.0
toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b
toIntegralSized x -- See Note [toIntegralSized optimization]
| maybe True (<= x) yMinBound
, maybe True (x <=) yMaxBound = Just y
| otherwise = Nothing
where
y = fromIntegral x
xWidth = bitSizeMaybe x
yWidth = bitSizeMaybe y
yMinBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y) = Just 0
| isSigned x, isSigned y
, Just yW <- yWidth = Just (negate $ bit (yW-1)) -- Assumes sub-type
| otherwise = Nothing
yMaxBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y)
, Just xW <- xWidth, Just yW <- yWidth
, xW <= yW+1 = Nothing -- Max bound beyond a's domain
| Just yW <- yWidth = if isSigned y
then Just (bit (yW-1)-1)
else Just (bit yW-1)
| otherwise = Nothing
{-# INLINABLE toIntegralSized #-}
-- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured
-- by 'bitSizeMaybe' and 'isSigned'.
isBitSubType :: (Bits a, Bits b) => a -> b -> Bool
isBitSubType x y
-- Reflexive
| xWidth == yWidth, xSigned == ySigned = True
-- Every integer is a subset of 'Integer'
| ySigned, Nothing == yWidth = True
| not xSigned, not ySigned, Nothing == yWidth = True
-- Sub-type relations between fixed-with types
| xSigned == ySigned, Just xW <- xWidth, Just yW <- yWidth = xW <= yW
| not xSigned, ySigned, Just xW <- xWidth, Just yW <- yWidth = xW < yW
| otherwise = False
where
xWidth = bitSizeMaybe x
xSigned = isSigned x
yWidth = bitSizeMaybe y
ySigned = isSigned y
{-# INLINE isBitSubType #-}
{- Note [Constant folding for rotate]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The INLINE on the Int instance of rotate enables it to be constant
folded. For example:
sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sO7 :: Int#) (ww1_sOb :: Int#) ->
case ww1_sOb of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1);
10000000 -> ww_sO7
whereas before it was left as a call to $wrotate.
All other Bits instances seem to inline well enough on their
own to enable constant folding; for example 'shift':
sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sOb :: Int#) (ww1_sOf :: Int#) ->
case ww1_sOf of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1);
10000000 -> ww_sOb
}
-}
-- Note [toIntegralSized optimization]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The code in 'toIntegralSized' relies on GHC optimizing away statically
-- decidable branches.
--
-- If both integral types are statically known, GHC will be able optimize the
-- code significantly (for @-O1@ and better).
--
-- For instance (as of GHC 7.8.1) the following definitions:
--
-- > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32
-- >
-- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16
--
-- are translated into the following (simplified) /GHC Core/ language:
--
-- > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) })
-- >
-- > i16_to_w16 = \x -> case eta of _
-- > { I16# b1 -> case tagToEnum# (<=# 0 b1) of _
-- > { False -> Nothing
-- > ; True -> Just (W16# (narrow16Word# (int2Word# b1)))
-- > }
-- > }
| shlevy/ghc | libraries/base/Data/Bits.hs | bsd-3-clause | 21,692 | 0 | 14 | 6,332 | 3,648 | 2,034 | 1,614 | 254 | 2 |
--
-- Copyright (c) 2011 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Tools.Misc (
split
, strip
, chomp
, spawnShell
, spawnShell'
, safeSpawnShell
, differenceList
, getCurrentRunLevel
, fileSha1Sum
, replace
, endsWith
, uuidGen
) where
import qualified Data.Text as T
import Data.String
import Control.Applicative
import System.Process
import System.IO
import System.Exit
import List ( isPrefixOf )
import Tools.File
-- chop line ending characters off
chomp :: String -> String
chomp s = case reverse s of
('\n' : '\r' : xs) -> reverse xs
('\n' : xs) -> reverse xs
_ -> s
-- Split a list over an element
split :: (Eq a) => a -> [a] -> [[a]]
split sep xs =
let (y,ys) = span (/= sep) xs in
case ys of
[] -> [y]
zs -> y : split sep (tail zs)
-- Strip a string from whitespace
strip :: String -> String
strip = T.unpack . T.strip . T.pack
-- Execute shell command and wait for its output, return empty string in case of exit failure
spawnShell :: String -> IO String
spawnShell cmd =
spawnShell' cmd >>= f where f Nothing = return ""
f (Just s) = return s
-- Execute shell command and wait for its output, return Nothing on failure exit code
spawnShell' :: String -> IO (Maybe String)
spawnShell' cmd =
runInteractiveCommand cmd >>= \ (_, stdout, _, h) ->
do contents <- hGetContents stdout
-- force evaluation of contents
exitCode <- length contents `seq` waitForProcess h
case exitCode of
ExitSuccess -> return $ Just contents
_ -> return Nothing
-- Execute shell command and wait for its output, cause exception on failure exit code
safeSpawnShell :: String -> IO String
safeSpawnShell cmd =
spawnShell' cmd >>= f where
f Nothing = error $ message
f (Just s) = return s
message = "shell command: " ++ cmd ++ " FAILED."
differenceList :: (Eq a) => [a] -> [a] -> [a]
differenceList xs ys = [x | x <- xs, not (x `elem` ys)]
getCurrentRunLevel :: IO Int
getCurrentRunLevel = do
Just runlevelStr <- spawnShell' "runlevel"
let [prevStr, currentStr] = words runlevelStr
return $ read currentStr
fileSha1Sum :: FilePath -> IO Integer
fileSha1Sum path = do
Just (sumStr:_) <- fmap (reverse . words) <$> (spawnShell' $ "openssl dgst -sha1 \"" ++ path ++ "\"")
return $ read ("0x" ++ sumStr)
replace :: String -> String -> String -> String
replace pat repl txt =
T.unpack $ T.replace (T.pack pat) (T.pack repl) (T.pack txt)
endsWith :: (Eq a) => [a] -> [a] -> Bool
endsWith suffix s = (reverse suffix) `isPrefixOf` (reverse s)
uuidGen :: IsString a => IO a
uuidGen =
readFile "/proc/sys/kernel/random/uuid" >>= return . fromString . strip
where strip = T.unpack . T.strip . T.pack
| jean-edouard/manager | disksync/Tools/Misc.hs | gpl-2.0 | 3,722 | 0 | 13 | 1,034 | 934 | 497 | 437 | 72 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.