code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Test.Zodiac.Core.Gen where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.Text.Encoding as T
import Data.Time.Calendar (Day(..))
import Data.Time.Clock (UTCTime(..), addUTCTime, secondsToDiffTime)
import P
import System.Random (Random)
import Test.QuickCheck
import Zodiac.Core.Data
-- Generate bytes uniformly.
genUBytes :: (ByteString -> a) -> Int -> Gen a
genUBytes f n =
fmap (f . BS.pack) . vectorOf n $ choose (0, 255)
genNPlus :: (Integral a, Arbitrary a, Bounded a, Random a) => Gen a
genNPlus = choose (1, maxBound)
genTimeWithin :: RequestTimestamp -> RequestExpiry -> Gen UTCTime
genTimeWithin (RequestTimestamp rt) (RequestExpiry re) = do
secs <- choose (0, re - 1)
pure $ addUTCTime (fromIntegral secs) rt
genTimeBefore :: RequestTimestamp -> Gen UTCTime
genTimeBefore (RequestTimestamp rt) = do
secs <- choose (1, 1000) :: Gen Int
pure $ addUTCTime (fromIntegral (- secs)) rt
genTimeExpired :: RequestTimestamp -> RequestExpiry -> Gen UTCTime
genTimeExpired (RequestTimestamp rt) (RequestExpiry re) = do
secs <- choose (re, maxBound)
pure $ addUTCTime (fromIntegral secs) rt
genInvalidExpiry :: Gen ByteString
genInvalidExpiry =
fmap (T.encodeUtf8 . renderIntegral) $ oneof [tooSmall, tooBig]
where
tooSmall = choose (- maxBound, 0)
tooBig = choose (maxRequestExpiry, maxBound)
-- | Negative in a calendrical sense (i.e., before 0001-01-01).
genNegativeTimestamp :: Gen ByteString
genNegativeTimestamp = do
days <- ModifiedJulianDay <$> choose (- (2 ^ (256 :: Integer)), - 678575)
secPart <- choose (0, 86401)
pure . renderRequestTimestamp . RequestTimestamp $
UTCTime days (secondsToDiffTime secPart)
| ambiata/zodiac | zodiac-core/test/Test/Zodiac/Core/Gen.hs | bsd-3-clause | 1,862 | 0 | 14 | 358 | 594 | 319 | 275 | 40 | 1 |
{-# LANGUAGE TupleSections #-}
module Haskell99Pointfree.P31
(
) where
import Control.Lens
import Control.Applicative (liftA2, liftA3, (<*>))
import Data.Bool.HT
import Control.Monad (join)
--the obvious and simple method (testing if any number until from 2 to sqrt(n) does divide the input without rest)
p31_1 :: Int -> Bool
p31_1 = liftA3 if' (< 3) (== 2) $ not . view _2 . until condition nextStep . join ((2,False,,) . ceiling .sqrt. fromIntegral)
where
nextStep = (over _1 (+1) .) . flip (set _2) <*> (== 0) . liftA2 mod (^._4) (^._1)
condition = liftA2 (||) (view _2) ( (>) . view _1 <*> view _3)
--using dropWhile
p31_2 :: Int -> Bool
p31_2 = liftA3 if' (< 4) (1 <) $ ( (/= 0) . ) . ( . head) . mod <*> flip dropWhile [2 ..] . liftA2 (liftA2 (&&)) ( (>=) . ceiling . sqrt . fromIntegral) (( (/=0) . ) . mod )
{-
--sieve of turner (simple, unperfomant)
p31_3 :: Int -> Bool
p31_3 = dropWhile
where
primes = sieve [2..]
-}
--sieve of erastotenes
| SvenWille/Haskell99Pointfree | src/Haskell99Pointfree/P31.hs | bsd-3-clause | 993 | 1 | 12 | 219 | 349 | 203 | 146 | 13 | 1 |
{-#LANGUAGE FlexibleContexts, OverloadedStrings #-}
import Text.Regex.TDFA
import Data.Array
import Control.Monad
import Control.Monad.Identity
import Text.Parsec
--import Text.Parsec.Char
import Data.String
default(String)
type Replacement a = a -> MatchArray -> a
--data Replacement a = Subgroup { idx :: Int }
-- | Part { prt :: String }
-- deriving (Show)
constR :: (IsString a, Extract a, Stream s m Char) => String -> ParsecT s u m (Replacement a)
constR s = return $ \ _ _ -> (fromString s)
--constR s = return $ Part s
subgroupR :: (IsString a, Extract a, Stream s m Char) => Int -> ParsecT s u m (Replacement a)
subgroupR i= return $ \s m -> extract (m ! i) s
--subgroupR i = return $ Subgroup i
part :: (IsString a, Extract a, Stream s m Char) => ParsecT s u m (Replacement a)
part = many1 (noneOf "$") >>= constR
mgroup :: (IsString a, Extract a, Stream s m Char) => ParsecT s u m (Replacement a)
mgroup = try (char '$' >> fmap read (many1 digit) >>= subgroupR)
dollar :: (IsString a, Extract a, Stream s m Char) => ParsecT s u m (Replacement a)
dollar = char '$' >> char '$' >> constR "$"
replacement :: (IsString a, Extract a, Stream s m Char) => ParsecT s u m [Replacement a]
replacement = many (part <|> mgroup <|> dollar)
--replace :: (IsString a, Monoid a, Extract a, Stream s Identity Char) => a ->
replace :: (IsString a, Monoid a, Extract a, RegexOptions r c e, RegexLike r a, RegexMaker r c e sr, Stream s Identity Char) => a -> sr -> s -> a
replace a sr s = doreplace a (matchAll (makeRegex sr) a) s
doreplace :: (IsString a, Monoid a, Extract a, Stream s Identity Char) => a -> [MatchArray] -> s -> a
doreplace a ms s = prc ms
where prc [] = a
prc ms' = mconcat $ repl $ finl $ extr $ foldl twist ([],0) ms'
twist (as,sm) m = ((sm,(offs m)-sm):as,(offs m)+(len m))
offs m = fst (m ! 0)
len m = snd (m ! 0)
extr (is,l) = (map (flip extract $ a) is, l)
finl (ex,l) = (after l a):ex
repl [] = []
repl (p:ps)= case (runParser replacement () "Replacement String" s) of
Right rs -> (snd $ foldl (dorep rs) (reverse ms,[]) ps) ++ [p]
Left err -> []
dorep rs (m:ms',ss) p = (ms',p:(mconcat $ map (\f -> f a m) rs):ss)
excise :: (Monoid s, Extract s) => s -> [MatchArray] -> s
excise s ms = prc ms
where prc [] = s
prc ms' = mconcat $ reverse $ finl $ extr $ foldl twist ([],0) ms'
twist (as,sm) m = ((sm,(offs m)-sm):as,(offs m)+(len m))
offs m = fst (m ! 0)
len m = snd (m ! 0)
extr (is,l) = (map (flip extract $ s) is, l)
finl (ex,l) = (after l s):ex
mat :: String -> String -> [MatchArray]
mat r s = matchAll (mak r) s
str::String
str = "ich schau dann mal was ich machen kann, schau du nur das du nicht wegschaust"
k :: [MatchArray]
k= mat "schau" str
mts :: IO ()
mts = do
forM_ (map (\a -> a ! 0) k) (\a -> do
putStrLn $ show a)
return ()
twist :: ([(Int,Int)],Int) -> MatchArray -> ([(Int,Int)],Int)
twist (t,s) m = ( (a-s,s) : t, a + b )
where a= fst (m ! 0)
b= snd (m ! 0)
finl :: Int -> ([(Int,Int)],Int) -> [(Int,Int)]
finl l (t, s)= reverse $ (l-s,s):t
mak :: RegexMaker Regex CompOption ExecOption String => String -> Regex
mak = makeRegex
takeOut :: String -> String -> [String]
takeOut r s = trf mts
where mts :: [MatchArray]
mts = match (mak r) s
trf [] = [s]
trf a = map (\(t,d)-> take t (drop d s)) $ finl (length s) $ foldl twist ([],0) a
--r :: (RegexLike Regex String, RegexMaker Regex CompOption ExecOption String) => Regex
r :: Regex
r = makeRegex ("[[:space:]]+" :: String)
str2 :: String
str2 = " es hallo aaa=aaa koennen halllo >100< oder feg=feg >2000< leute hallllllo sein, nok=bok oder halo nur >1< hallo "
m1 :: [MatchArray]
m1 = match r str2
| mkelc/bkv2epub | Reg.hs | bsd-3-clause | 3,917 | 0 | 15 | 1,045 | 1,818 | 965 | 853 | 77 | 4 |
module NoiselessChannel
( stepChannel
, Channel
, initChannel
) where
import Control.Monad.State.Strict
import Interface( ForwMsg
, ForwSignal(..)
)
data Channel = Channel deriving Show
initChannel :: Channel
initChannel = Channel
stepChannel :: [ForwMsg] -> State Channel ForwSignal
stepChannel signals = return $ ForwSignal signals 0.0
| ownclo/alohas | src/NoiselessChannel.hs | bsd-3-clause | 391 | 0 | 6 | 98 | 91 | 54 | 37 | 12 | 1 |
-----------------------------------------------------------------------------
--
-- Code generation for foreign calls.
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module GHC.StgToCmm.Foreign (
cgForeignCall,
emitPrimCall, emitCCall,
emitForeignCall,
emitSaveThreadState,
saveThreadState,
emitLoadThreadState,
loadThreadState,
emitOpenNursery,
emitCloseNursery,
) where
import GhcPrelude hiding( succ, (<*>) )
import GHC.Stg.Syntax
import GHC.StgToCmm.Prof (storeCurCCS, ccsType)
import GHC.StgToCmm.Env
import GHC.StgToCmm.Monad
import GHC.StgToCmm.Utils
import GHC.StgToCmm.Closure
import GHC.StgToCmm.Layout
import GHC.Cmm.BlockId (newBlockId)
import GHC.Cmm
import GHC.Cmm.Utils
import GHC.Cmm.Graph
import Type
import GHC.Types.RepType
import GHC.Cmm.CLabel
import GHC.Runtime.Layout
import ForeignCall
import DynFlags
import Maybes
import Outputable
import UniqSupply
import BasicTypes
import TyCoRep
import TysPrim
import Util (zipEqual)
import Control.Monad
-----------------------------------------------------------------------------
-- Code generation for Foreign Calls
-----------------------------------------------------------------------------
-- | Emit code for a foreign call, and return the results to the sequel.
-- Precondition: the length of the arguments list is the same as the
-- arity of the foreign function.
cgForeignCall :: ForeignCall -- the op
-> Type -- type of foreign function
-> [StgArg] -- x,y arguments
-> Type -- result type
-> FCode ReturnKind
cgForeignCall (CCall (CCallSpec target cconv safety)) typ stg_args res_ty
= do { dflags <- getDynFlags
; let -- in the stdcall calling convention, the symbol needs @size appended
-- to it, where size is the total number of bytes of arguments. We
-- attach this info to the CLabel here, and the CLabel pretty printer
-- will generate the suffix when the label is printed.
call_size args
| StdCallConv <- cconv = Just (sum (map arg_size args))
| otherwise = Nothing
-- ToDo: this might not be correct for 64-bit API
arg_size (arg, _) = max (widthInBytes $ typeWidth $ cmmExprType dflags arg)
(wORD_SIZE dflags)
; cmm_args <- getFCallArgs stg_args typ
; (res_regs, res_hints) <- newUnboxedTupleRegs res_ty
; let ((call_args, arg_hints), cmm_target)
= case target of
StaticTarget _ _ _ False ->
panic "cgForeignCall: unexpected FFI value import"
StaticTarget _ lbl mPkgId True
-> let labelSource
= case mPkgId of
Nothing -> ForeignLabelInThisPackage
Just pkgId -> ForeignLabelInPackage pkgId
size = call_size cmm_args
in ( unzip cmm_args
, CmmLit (CmmLabel
(mkForeignLabel lbl size labelSource IsFunction)))
DynamicTarget -> case cmm_args of
(fn,_):rest -> (unzip rest, fn)
[] -> panic "cgForeignCall []"
fc = ForeignConvention cconv arg_hints res_hints CmmMayReturn
call_target = ForeignTarget cmm_target fc
-- we want to emit code for the call, and then emitReturn.
-- However, if the sequel is AssignTo, we shortcut a little
-- and generate a foreign call that assigns the results
-- directly. Otherwise we end up generating a bunch of
-- useless "r = r" assignments, which are not merely annoying:
-- they prevent the common block elimination from working correctly
-- in the case of a safe foreign call.
-- See Note [safe foreign call convention]
--
; sequel <- getSequel
; case sequel of
AssignTo assign_to_these _ ->
emitForeignCall safety assign_to_these call_target call_args
_something_else ->
do { _ <- emitForeignCall safety res_regs call_target call_args
; emitReturn (map (CmmReg . CmmLocal) res_regs)
}
}
{- Note [safe foreign call convention]
The simple thing to do for a safe foreign call would be the same as an
unsafe one: just
emitForeignCall ...
emitReturn ...
but consider what happens in this case
case foo x y z of
(# s, r #) -> ...
The sequel is AssignTo [r]. The call to newUnboxedTupleRegs picks [r]
as the result reg, and we generate
r = foo(x,y,z) returns to L1 -- emitForeignCall
L1:
r = r -- emitReturn
goto L2
L2:
...
Now L1 is a proc point (by definition, it is the continuation of the
safe foreign call). If L2 does a heap check, then L2 will also be a
proc point.
Furthermore, the stack layout algorithm has to arrange to save r
somewhere between the call and the jump to L1, which is annoying: we
would have to treat r differently from the other live variables, which
have to be saved *before* the call.
So we adopt a special convention for safe foreign calls: the results
are copied out according to the NativeReturn convention by the call,
and the continuation of the call should copyIn the results. (The
copyOut code is actually inserted when the safe foreign call is
lowered later). The result regs attached to the safe foreign call are
only used temporarily to hold the results before they are copied out.
We will now generate this:
r = foo(x,y,z) returns to L1
L1:
r = R1 -- copyIn, inserted by mkSafeCall
goto L2
L2:
... r ...
And when the safe foreign call is lowered later (see Note [lower safe
foreign calls]) we get this:
suspendThread()
r = foo(x,y,z)
resumeThread()
R1 = r -- copyOut, inserted by lowerSafeForeignCall
jump L1
L1:
r = R1 -- copyIn, inserted by mkSafeCall
goto L2
L2:
... r ...
Now consider what happens if L2 does a heap check: the Adams
optimisation kicks in and commons up L1 with the heap-check
continuation, resulting in just one proc point instead of two. Yay!
-}
emitCCall :: [(CmmFormal,ForeignHint)]
-> CmmExpr
-> [(CmmActual,ForeignHint)]
-> FCode ()
emitCCall hinted_results fn hinted_args
= void $ emitForeignCall PlayRisky results target args
where
(args, arg_hints) = unzip hinted_args
(results, result_hints) = unzip hinted_results
target = ForeignTarget fn fc
fc = ForeignConvention CCallConv arg_hints result_hints CmmMayReturn
emitPrimCall :: [CmmFormal] -> CallishMachOp -> [CmmActual] -> FCode ()
emitPrimCall res op args
= void $ emitForeignCall PlayRisky res (PrimTarget op) args
-- alternative entry point, used by GHC.Cmm.Parser
emitForeignCall
:: Safety
-> [CmmFormal] -- where to put the results
-> ForeignTarget -- the op
-> [CmmActual] -- arguments
-> FCode ReturnKind
emitForeignCall safety results target args
| not (playSafe safety) = do
dflags <- getDynFlags
let (caller_save, caller_load) = callerSaveVolatileRegs dflags
emit caller_save
target' <- load_target_into_temp target
args' <- mapM maybe_assign_temp args
emit $ mkUnsafeCall target' results args'
emit caller_load
return AssignedDirectly
| otherwise = do
dflags <- getDynFlags
updfr_off <- getUpdFrameOff
target' <- load_target_into_temp target
args' <- mapM maybe_assign_temp args
k <- newBlockId
let (off, _, copyout) = copyInOflow dflags NativeReturn (Young k) results []
-- see Note [safe foreign call convention]
tscope <- getTickScope
emit $
( mkStore (CmmStackSlot (Young k) (widthInBytes (wordWidth dflags)))
(CmmLit (CmmBlock k))
<*> mkLast (CmmForeignCall { tgt = target'
, res = results
, args = args'
, succ = k
, ret_args = off
, ret_off = updfr_off
, intrbl = playInterruptible safety })
<*> mkLabel k tscope
<*> copyout
)
return (ReturnedTo k off)
load_target_into_temp :: ForeignTarget -> FCode ForeignTarget
load_target_into_temp (ForeignTarget expr conv) = do
tmp <- maybe_assign_temp expr
return (ForeignTarget tmp conv)
load_target_into_temp other_target@(PrimTarget _) =
return other_target
-- What we want to do here is create a new temporary for the foreign
-- call argument if it is not safe to use the expression directly,
-- because the expression mentions caller-saves GlobalRegs (see
-- Note [Register Parameter Passing]).
--
-- However, we can't pattern-match on the expression here, because
-- this is used in a loop by GHC.Cmm.Parser, and testing the expression
-- results in a black hole. So we always create a temporary, and rely
-- on GHC.Cmm.Sink to clean it up later. (Yuck, ToDo). The generated code
-- ends up being the same, at least for the RTS .cmm code.
--
maybe_assign_temp :: CmmExpr -> FCode CmmExpr
maybe_assign_temp e = do
dflags <- getDynFlags
reg <- newTemp (cmmExprType dflags e)
emitAssign (CmmLocal reg) e
return (CmmReg (CmmLocal reg))
-- -----------------------------------------------------------------------------
-- Save/restore the thread state in the TSO
-- This stuff can't be done in suspendThread/resumeThread, because it
-- refers to global registers which aren't available in the C world.
emitSaveThreadState :: FCode ()
emitSaveThreadState = do
dflags <- getDynFlags
code <- saveThreadState dflags
emit code
-- | Produce code to save the current thread state to @CurrentTSO@
saveThreadState :: MonadUnique m => DynFlags -> m CmmAGraph
saveThreadState dflags = do
tso <- newTemp (gcWord dflags)
close_nursery <- closeNursery dflags tso
pure $ catAGraphs [
-- tso = CurrentTSO;
mkAssign (CmmLocal tso) currentTSOExpr,
-- tso->stackobj->sp = Sp;
mkStore (cmmOffset dflags
(CmmLoad (cmmOffset dflags
(CmmReg (CmmLocal tso))
(tso_stackobj dflags))
(bWord dflags))
(stack_SP dflags))
spExpr,
close_nursery,
-- and save the current cost centre stack in the TSO when profiling:
if gopt Opt_SccProfilingOn dflags then
mkStore (cmmOffset dflags (CmmReg (CmmLocal tso)) (tso_CCCS dflags)) cccsExpr
else mkNop
]
emitCloseNursery :: FCode ()
emitCloseNursery = do
dflags <- getDynFlags
tso <- newTemp (bWord dflags)
code <- closeNursery dflags tso
emit $ mkAssign (CmmLocal tso) currentTSOExpr <*> code
{- |
@closeNursery dflags tso@ produces code to close the nursery.
A local register holding the value of @CurrentTSO@ is expected for
efficiency.
Closing the nursery corresponds to the following code:
@
tso = CurrentTSO;
cn = CurrentNuresry;
// Update the allocation limit for the current thread. We don't
// check to see whether it has overflowed at this point, that check is
// made when we run out of space in the current heap block (stg_gc_noregs)
// and in the scheduler when context switching (schedulePostRunThread).
tso->alloc_limit -= Hp + WDS(1) - cn->start;
// Set cn->free to the next unoccupied word in the block
cn->free = Hp + WDS(1);
@
-}
closeNursery :: MonadUnique m => DynFlags -> LocalReg -> m CmmAGraph
closeNursery df tso = do
let tsoreg = CmmLocal tso
cnreg <- CmmLocal <$> newTemp (bWord df)
pure $ catAGraphs [
mkAssign cnreg currentNurseryExpr,
-- CurrentNursery->free = Hp+1;
mkStore (nursery_bdescr_free df cnreg) (cmmOffsetW df hpExpr 1),
let alloc =
CmmMachOp (mo_wordSub df)
[ cmmOffsetW df hpExpr 1
, CmmLoad (nursery_bdescr_start df cnreg) (bWord df)
]
alloc_limit = cmmOffset df (CmmReg tsoreg) (tso_alloc_limit df)
in
-- tso->alloc_limit += alloc
mkStore alloc_limit (CmmMachOp (MO_Sub W64)
[ CmmLoad alloc_limit b64
, CmmMachOp (mo_WordTo64 df) [alloc] ])
]
emitLoadThreadState :: FCode ()
emitLoadThreadState = do
dflags <- getDynFlags
code <- loadThreadState dflags
emit code
-- | Produce code to load the current thread state from @CurrentTSO@
loadThreadState :: MonadUnique m => DynFlags -> m CmmAGraph
loadThreadState dflags = do
tso <- newTemp (gcWord dflags)
stack <- newTemp (gcWord dflags)
open_nursery <- openNursery dflags tso
pure $ catAGraphs [
-- tso = CurrentTSO;
mkAssign (CmmLocal tso) currentTSOExpr,
-- stack = tso->stackobj;
mkAssign (CmmLocal stack) (CmmLoad (cmmOffset dflags (CmmReg (CmmLocal tso)) (tso_stackobj dflags)) (bWord dflags)),
-- Sp = stack->sp;
mkAssign spReg (CmmLoad (cmmOffset dflags (CmmReg (CmmLocal stack)) (stack_SP dflags)) (bWord dflags)),
-- SpLim = stack->stack + RESERVED_STACK_WORDS;
mkAssign spLimReg (cmmOffsetW dflags (cmmOffset dflags (CmmReg (CmmLocal stack)) (stack_STACK dflags))
(rESERVED_STACK_WORDS dflags)),
-- HpAlloc = 0;
-- HpAlloc is assumed to be set to non-zero only by a failed
-- a heap check, see HeapStackCheck.cmm:GC_GENERIC
mkAssign hpAllocReg (zeroExpr dflags),
open_nursery,
-- and load the current cost centre stack from the TSO when profiling:
if gopt Opt_SccProfilingOn dflags
then storeCurCCS
(CmmLoad (cmmOffset dflags (CmmReg (CmmLocal tso))
(tso_CCCS dflags)) (ccsType dflags))
else mkNop
]
emitOpenNursery :: FCode ()
emitOpenNursery = do
dflags <- getDynFlags
tso <- newTemp (bWord dflags)
code <- openNursery dflags tso
emit $ mkAssign (CmmLocal tso) currentTSOExpr <*> code
{- |
@openNursery dflags tso@ produces code to open the nursery. A local register
holding the value of @CurrentTSO@ is expected for efficiency.
Opening the nursery corresponds to the following code:
@
tso = CurrentTSO;
cn = CurrentNursery;
bdfree = CurrentNursery->free;
bdstart = CurrentNursery->start;
// We *add* the currently occupied portion of the nursery block to
// the allocation limit, because we will subtract it again in
// closeNursery.
tso->alloc_limit += bdfree - bdstart;
// Set Hp to the last occupied word of the heap block. Why not the
// next unocupied word? Doing it this way means that we get to use
// an offset of zero more often, which might lead to slightly smaller
// code on some architectures.
Hp = bdfree - WDS(1);
// Set HpLim to the end of the current nursery block (note that this block
// might be a block group, consisting of several adjacent blocks.
HpLim = bdstart + CurrentNursery->blocks*BLOCK_SIZE_W - 1;
@
-}
openNursery :: MonadUnique m => DynFlags -> LocalReg -> m CmmAGraph
openNursery df tso = do
let tsoreg = CmmLocal tso
cnreg <- CmmLocal <$> newTemp (bWord df)
bdfreereg <- CmmLocal <$> newTemp (bWord df)
bdstartreg <- CmmLocal <$> newTemp (bWord df)
-- These assignments are carefully ordered to reduce register
-- pressure and generate not completely awful code on x86. To see
-- what code we generate, look at the assembly for
-- stg_returnToStackTop in rts/StgStartup.cmm.
pure $ catAGraphs [
mkAssign cnreg currentNurseryExpr,
mkAssign bdfreereg (CmmLoad (nursery_bdescr_free df cnreg) (bWord df)),
-- Hp = CurrentNursery->free - 1;
mkAssign hpReg (cmmOffsetW df (CmmReg bdfreereg) (-1)),
mkAssign bdstartreg (CmmLoad (nursery_bdescr_start df cnreg) (bWord df)),
-- HpLim = CurrentNursery->start +
-- CurrentNursery->blocks*BLOCK_SIZE_W - 1;
mkAssign hpLimReg
(cmmOffsetExpr df
(CmmReg bdstartreg)
(cmmOffset df
(CmmMachOp (mo_wordMul df) [
CmmMachOp (MO_SS_Conv W32 (wordWidth df))
[CmmLoad (nursery_bdescr_blocks df cnreg) b32],
mkIntExpr df (bLOCK_SIZE df)
])
(-1)
)
),
-- alloc = bd->free - bd->start
let alloc =
CmmMachOp (mo_wordSub df) [CmmReg bdfreereg, CmmReg bdstartreg]
alloc_limit = cmmOffset df (CmmReg tsoreg) (tso_alloc_limit df)
in
-- tso->alloc_limit += alloc
mkStore alloc_limit (CmmMachOp (MO_Add W64)
[ CmmLoad alloc_limit b64
, CmmMachOp (mo_WordTo64 df) [alloc] ])
]
nursery_bdescr_free, nursery_bdescr_start, nursery_bdescr_blocks
:: DynFlags -> CmmReg -> CmmExpr
nursery_bdescr_free dflags cn =
cmmOffset dflags (CmmReg cn) (oFFSET_bdescr_free dflags)
nursery_bdescr_start dflags cn =
cmmOffset dflags (CmmReg cn) (oFFSET_bdescr_start dflags)
nursery_bdescr_blocks dflags cn =
cmmOffset dflags (CmmReg cn) (oFFSET_bdescr_blocks dflags)
tso_stackobj, tso_CCCS, tso_alloc_limit, stack_STACK, stack_SP :: DynFlags -> ByteOff
tso_stackobj dflags = closureField dflags (oFFSET_StgTSO_stackobj dflags)
tso_alloc_limit dflags = closureField dflags (oFFSET_StgTSO_alloc_limit dflags)
tso_CCCS dflags = closureField dflags (oFFSET_StgTSO_cccs dflags)
stack_STACK dflags = closureField dflags (oFFSET_StgStack_stack dflags)
stack_SP dflags = closureField dflags (oFFSET_StgStack_sp dflags)
closureField :: DynFlags -> ByteOff -> ByteOff
closureField dflags off = off + fixedHdrSize dflags
-- Note [Unlifted boxed arguments to foreign calls]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- For certain types passed to foreign calls, we adjust the actual
-- value passed to the call. For ByteArray#, Array#, SmallArray#,
-- and ArrayArray#, we pass the address of the array's payload, not
-- the address of the heap object. For example, consider
-- foreign import "c_foo" foo :: ByteArray# -> Int# -> IO ()
-- At a Haskell call like `foo x y`, we'll generate a C call that
-- is more like
-- c_foo( x+8, y )
-- where the "+8" takes the heap pointer (x :: ByteArray#) and moves
-- it past the header words of the ByteArray object to point directly
-- to the data inside the ByteArray#. (The exact offset depends
-- on the target architecture and on profiling) By contrast, (y :: Int#)
-- requires no such adjustment.
--
-- This adjustment is performed by 'add_shim'. The size of the
-- adjustment depends on the type of heap object. But
-- how can we determine that type? There are two available options.
-- We could use the types of the actual values that the foreign call
-- has been applied to, or we could use the types present in the
-- foreign function's type. Prior to GHC 8.10, we used the former
-- strategy since it's a little more simple. However, in issue #16650
-- and more compellingly in the comments of
-- https://gitlab.haskell.org/ghc/ghc/merge_requests/939, it was
-- demonstrated that this leads to bad behavior in the presence
-- of unsafeCoerce#. Returning to the above example, suppose the
-- Haskell call looked like
-- foo (unsafeCoerce# p)
-- where the types of expressions comprising the arguments are
-- p :: (Any :: TYPE 'UnliftedRep)
-- i :: Int#
-- so that the unsafe-coerce is between Any and ByteArray#.
-- These two types have the same kind (they are both represented by
-- a heap pointer) so no GC errors will occur if we do this unsafe coerce.
-- By the time this gets to the code generator the cast has been
-- discarded so we have
-- foo p y
-- But we *must* adjust the pointer to p by a ByteArray# shim,
-- *not* by an Any shim (the Any shim involves no offset at all).
--
-- To avoid this bad behavior, we adopt the second strategy: use
-- the types present in the foreign function's type.
-- In collectStgFArgTypes, we convert the foreign function's
-- type to a list of StgFArgType. Then, in add_shim, we interpret
-- these as numeric offsets.
getFCallArgs ::
[StgArg]
-> Type -- the type of the foreign function
-> FCode [(CmmExpr, ForeignHint)]
-- (a) Drop void args
-- (b) Add foreign-call shim code
-- It's (b) that makes this differ from getNonVoidArgAmodes
-- Precondition: args and typs have the same length
-- See Note [Unlifted boxed arguments to foreign calls]
getFCallArgs args typ
= do { mb_cmms <- mapM get (zipEqual "getFCallArgs" args (collectStgFArgTypes typ))
; return (catMaybes mb_cmms) }
where
get (arg,typ)
| null arg_reps
= return Nothing
| otherwise
= do { cmm <- getArgAmode (NonVoid arg)
; dflags <- getDynFlags
; return (Just (add_shim dflags typ cmm, hint)) }
where
arg_ty = stgArgType arg
arg_reps = typePrimRep arg_ty
hint = typeForeignHint arg_ty
-- The minimum amount of information needed to determine
-- the offset to apply to an argument to a foreign call.
-- See Note [Unlifted boxed arguments to foreign calls]
data StgFArgType
= StgPlainType
| StgArrayType
| StgSmallArrayType
| StgByteArrayType
-- See Note [Unlifted boxed arguments to foreign calls]
add_shim :: DynFlags -> StgFArgType -> CmmExpr -> CmmExpr
add_shim dflags ty expr = case ty of
StgPlainType -> expr
StgArrayType -> cmmOffsetB dflags expr (arrPtrsHdrSize dflags)
StgSmallArrayType -> cmmOffsetB dflags expr (smallArrPtrsHdrSize dflags)
StgByteArrayType -> cmmOffsetB dflags expr (arrWordsHdrSize dflags)
-- From a function, extract information needed to determine
-- the offset of each argument when used as a C FFI argument.
-- See Note [Unlifted boxed arguments to foreign calls]
collectStgFArgTypes :: Type -> [StgFArgType]
collectStgFArgTypes = go []
where
-- Skip foralls
go bs (ForAllTy _ res) = go bs res
go bs (AppTy{}) = reverse bs
go bs (TyConApp{}) = reverse bs
go bs (LitTy{}) = reverse bs
go bs (TyVarTy{}) = reverse bs
go _ (CastTy{}) = panic "myCollectTypeArgs: CastTy"
go _ (CoercionTy{}) = panic "myCollectTypeArgs: CoercionTy"
go bs (FunTy {ft_arg = arg, ft_res=res}) =
go (typeToStgFArgType arg:bs) res
-- Choose the offset based on the type. For anything other
-- than an unlifted boxed type, there is no offset.
-- See Note [Unlifted boxed arguments to foreign calls]
typeToStgFArgType :: Type -> StgFArgType
typeToStgFArgType typ
| tycon == arrayPrimTyCon = StgArrayType
| tycon == mutableArrayPrimTyCon = StgArrayType
| tycon == arrayArrayPrimTyCon = StgArrayType
| tycon == mutableArrayArrayPrimTyCon = StgArrayType
| tycon == smallArrayPrimTyCon = StgSmallArrayType
| tycon == smallMutableArrayPrimTyCon = StgSmallArrayType
| tycon == byteArrayPrimTyCon = StgByteArrayType
| tycon == mutableByteArrayPrimTyCon = StgByteArrayType
| otherwise = StgPlainType
where
-- Should be a tycon app, since this is a foreign call. We look
-- through newtypes so the offset does not change if a user replaces
-- a type in a foreign function signature with a representationally
-- equivalent newtype.
tycon = tyConAppTyCon (unwrapType typ)
| sdiehl/ghc | compiler/GHC/StgToCmm/Foreign.hs | bsd-3-clause | 23,648 | 0 | 22 | 6,046 | 3,818 | 1,978 | 1,840 | 303 | 8 |
{-# LANGUAGE OverloadedStrings #-}
module Lichen.Plagiarism.Main where
import System.Directory
import System.FilePath
import Data.Aeson
import Data.Semigroup ((<>))
--import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as BS
import Control.Monad.Reader
--import Control.Monad.Except
import Options.Applicative
import Lichen.Util
import Lichen.Error
import Lichen.Config
import Lichen.Languages
import Lichen.Plagiarism.Config
import Lichen.Plagiarism.Concatenate
import Lichen.Plagiarism.Highlight
import Lichen.Plagiarism.Report
import Lichen.Plagiarism.Walk
parseOptions :: Config -> Parser Config
parseOptions dc = Config
<$> strOption (long "config-file" <> short 'c' <> metavar "PATH" <> showDefault <> value (configFile dc) <> help "Configuration file")
<*> strOption (long "output-dir" <> short 'o' <> metavar "DIR" <> showDefault <> value (outputDir dc) <> help "Directory to store generated output")
<*> strOption (long "concat-dir" <> short 'c' <> metavar "DIR" <> showDefault <> value (concatDir dc) <> help "Subdirectory of output directory storing concatenated student code")
<*> strOption (long "highlight-dir" <> short 'i' <> metavar "DIR" <> showDefault <> value (highlightDir dc) <> help "Subdirectory of output directory storing syntax-highlighted student code")
<*> strOption (long "report-dir" <> short 'r' <> metavar "DIR" <> showDefault <> value (reportDir dc) <> help "Subdirectory of output directory storing the HTML report")
<*> (languageChoice (language dc) <$> (optional . strOption $ long "language" <> short 'l' <> metavar "LANG" <> help "Language of student code"))
<*> option auto (long "top-matches" <> short 't' <> metavar "N" <> showDefault <> value (topMatches dc) <> help "Number of top matches to report")
<*> option auto (long "semester" <> metavar "SEMESTER" <> value (semester dc) <> help "Semester within Submitty system")
<*> option auto (long "course" <> metavar "COURSE" <> value (course dc) <> help "Course within Submitty system")
<*> option auto (long "assignment" <> metavar "ASSIGNMENT" <> value (assignment dc) <> help "Assignment within Submitty system")
realMain :: Config -> IO ()
realMain ic = do
iopts <- liftIO . execParser $ opts ic
mcsrc <- readSafe BS.readFile Nothing $ configFile iopts
options <- case mcsrc of Just csrc -> do
c <- case eitherDecode csrc of Left e -> (printError . JSONDecodingError $ T.pack e) >> pure ic
Right t -> pure t
liftIO . execParser $ opts c
Nothing -> pure iopts
flip runConfigured options $ do
config <- ask
--p <- case sourceDir config of Just d -> return d; Nothing -> throwError $ InvocationError "No directory specified"
dir <- liftIO $ canonicalizePath undefined
--let concatenate = if allVersions config then concatenateAll else concatenateActive
let concatenate = concatenateActive
progress "Concatenating submissions" $ concatenate dir
progress "Highlighting concatenated files" $ highlight dir
prints <- progress "Fingerprinting submissions" $ fingerprintDir (language config) (outputDir config </> concatDir config ++ dir)
progress "Generating plagiarism reports" $ report dir prints
where opts c = info (helper <*> parseOptions c)
(fullDesc <> progDesc "Run plagiarism detection" <> header "plagiarism - plagiarism detection")
| Submitty/AnalysisTools | src/Lichen/Plagiarism/Main.hs | bsd-3-clause | 3,785 | 0 | 22 | 965 | 955 | 457 | 498 | 50 | 3 |
{-# LANGUAGE DataKinds, ExtendedDefaultRules, OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes, RecordWildCards, TemplateHaskell #-}
module Main where
import Language.Haskell.TH.Expand
import Control.Monad (forM_)
import Control.Monad (when)
import Control.Monad.Trans (liftIO)
import Data.Monoid ((<>))
import Data.Proxy (Proxy (..))
import Data.String (fromString)
import qualified Data.Text as T
import Language.Haskell.Exts (Decl (..), ImportDecl (..))
import Language.Haskell.Exts (Module (..), ModuleName (..))
import Language.Haskell.Exts (ParseResult (ParseOk), parseFile)
import Language.Haskell.Exts (ParseMode (..), prettyPrint)
import Language.Haskell.Exts (KnownExtension (PackageImports))
import Language.Haskell.Exts (defaultParseMode)
import Language.Haskell.Exts (fromParseResult,
parseModuleWithMode)
import Language.Haskell.Exts (Extension (EnableExtension))
import Language.Haskell.Exts.QQ (hs)
import Language.Haskell.Exts.SrcLoc (noLoc)
import Options.Declarative (Arg, Cmd, Def, Flag, get)
import qualified Options.Declarative as Opt
import Shelly (canonic, cp, fromText, ls, pwd)
import Shelly (run_, shelly, silently, test_e)
import Shelly (toTextIgnore, withTmpDir)
import Shelly (cd, echo, echo_err, mv, readfile,
writefile, (</>))
import Shelly (rm)
import System.FilePath (takeBaseName, takeDirectory,
takeFileName)
import System.Random (randomIO)
default (String)
main :: IO ()
main = Opt.run_ doMain
mkWrite out = [hs|Language.Haskell.TH.runIO . System.IO.writeFile $(liftHSE out)|]
finalize out m = [hs|
do let write = $(mkWrite out)
orig = $(liftHSE m)
mdic <- Language.Haskell.TH.Traced.tracing_ Language.Haskell.TH.Syntax.getQ
case mdic of
Nothing -> write $ Language.Haskell.Exts.prettyPrint orig
Just dic -> do
write $ Language.Haskell.Exts.prettyPrint $
Language.Haskell.TH.Expand.expandTH dic orig
|]
doMain :: Flag "g" '["ghc"] "PATH" "pass to ghc" (Def "ghc" FilePath)
-> Flag "a" '["with-args"] "STR" "argument(s) to pass to ghc" (Def "" String)
-> Flag "o" '[] "STR" "argument(s) to pass to ghc" (Maybe String)
-> Arg "TARGET" FilePath
-> Cmd "Expanding Template Haskell using GHC command" ()
doMain ghcCmd opts moutc target = liftIO $ do
let ghc = get ghcCmd
args = get opts
moup = get moutc
ParseOk m <- parseFile $ get target
shelly $ silently $ do
cwd <- pwd
origPath <- takeDirectory . T.unpack . toTextIgnore <$> canonic (fromString $ get target)
withTmpDir $ \dir -> do
cd dir
nonce <- liftIO randomIO
let Module loc n@(ModuleName mn) ps mws mes is ds = traceTHSplices m
is' = map (\n -> ImportDecl noLoc (ModuleName n) True False False Nothing Nothing Nothing)
["Language.Haskell.Exts", "GHC.Base", "GHC.Types", "Language.Haskell.TH"
,"Language.Haskell.Exts.Annotated.Syntax", "System.IO"]
tbmname = "M" ++ show (abs nonce + 1 :: Int)
tmpout = dir </> (tbmname ++ ".hs" :: String)
addFin = [hs|do
Language.Haskell.TH.Syntax.addModFinalizer $(finalize (T.unpack $ toTextIgnore tmpout) m)
return []|]
modified = Module loc n ps mws mes (is' ++ is)
(SpliceDecl noLoc addFin : ds)
fname = takeFileName $ get target
dest = dir </> fname
searchPath = "-i" <> toTextIgnore dir <> ":" <> toTextIgnore cwd
writefile dest $ T.pack $ prettyPrint modified
run_ (fromText $ T.pack ghc) (map T.pack (words args)
++ [searchPath, "-dynamic", "-c", toTextIgnore dest])
run_ (fromText $ T.pack ghc) (map T.pack (words args)
++ [searchPath, "-dynamic", "-ddump-minimal-imports", "-c", toTextIgnore tmpout])
let imps = dir </> (mn ++ ".imports")
imps_ok <- test_e imps
when imps_ok $ do
il <- readfile imps
let ParseOk (Module _ _ _ _ _ idecls _) = parseModuleWithMode
defaultParseMode { extensions = [EnableExtension PackageImports] } $ T.unpack il
ParseOk (Module i p c f d _ u) <- liftIO $ parseFile $ T.unpack $ toTextIgnore tmpout
writefile tmpout $ T.pack $ prettyPrint $ Module i p c f d idecls u
chs <- ls dir
forM_ (filter (\a -> a `notElem` [dest, tmpout, imps] && takeBaseName (T.unpack $ toTextIgnore a) == tbmname) chs) $ \f -> cp f (fromString origPath)
case moup of
Nothing -> echo =<< readfile tmpout
Just fp -> mv tmpout (fromText $ T.pack fp)
return ()
| konn/expandth | app/expandth-ghc.hs | bsd-3-clause | 5,325 | 0 | 26 | 1,793 | 1,379 | 746 | 633 | 85 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Control.Monad.Free as Free
import qualified Control.Monad.State as State
import Control.Monad.State (StateT)
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Proxy (Proxy(..))
import Network.Wai (Application)
import Servant (enter, (:~>)(Nat), serve, Handler)
import Application (server, Routes)
import Poll.Algebra
import Poll.Models
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
main :: IO ()
main = hspec spec
testApp :: PollStoreState -> Application
testApp store =
serve (Proxy :: Proxy Routes)
$ server (toHandler store)
spec :: Spec
spec = with (return $ testApp $ emptyStore "127.0.0.1") $
describe "GET /" $
it "responds with 200" $
get "/" `shouldRespondWith` 200
toHandler :: PollStoreState -> IpAddr -> StateT PollStoreState Handler :~> Handler
toHandler store ip = Nat (toHandler' store ip)
where
toHandler' :: forall a. PollStoreState -> IpAddr -> PollStore Handler a -> Handler a
toHandler' state ip th = State.evalStateT th state
----------------------------------------------------------------------
type PollStore m a = StateT PollStoreState m a
data PollStoreState =
PollStoreState
{ polls :: Map PollId PollData
, ip :: IpAddr
}
emptyStore :: IpAddr -> PollStoreState
emptyStore = PollStoreState Map.empty
instance Monad m => InterpretRepository (StateT PollStoreState m) where
interpret = Free.iterM iterRep
where
iterRep (GetIp cont) = do
ipAdr <- State.gets ip
cont ipAdr
iterRep (RecentPolls cnt contWith) = do
polls <- take cnt . reverse <$> State.gets (map toHeader . Map.elems . polls)
contWith polls
iterRep (LoadPoll pollId contWith) = do
found <- State.gets (Map.lookup pollId . polls)
contWith found
iterRep (Poll.Algebra.CreatePoll ip quest cs contWith) = do
nextPId <- nextPollId
nextCId <- nextChoiceId
let
choices = Map.fromList $ zipWith
(\cT cId -> (cId, PollChoice nextPId cId cT Set.empty))
cs
[nextCId..]
added = PollData nextPId quest ip choices
State.modify (\s -> s { polls = Map.insert nextPId added (polls s) })
contWith nextPId
iterRep (RegisterVote ip pollId choiceId cont) = do
choice <- getChoice pollId choiceId
cont
toHeader :: PollData -> PollHeader
toHeader (PollData pId quest creator _) = PollHeader pId quest creator
getChoice :: Monad m => PollId -> ChoiceId -> PollStore m (Maybe PollChoice)
getChoice pollId choiceId = do
poll <- State.gets (Map.lookup pollId . polls)
return $ poll >>= (Map.lookup choiceId . pdChoices)
nextPollId :: Monad m => PollStore m PollId
nextPollId = do
count <- State.gets (Map.size . polls)
return . fromIntegral $ count + 1
nextChoiceId :: Monad m => PollStore m ChoiceId
nextChoiceId = do
pMap <- State.gets polls
return . fromIntegral
$ Map.foldl' (\sum p -> sum + Map.size (pdChoices p)) 0 pMap
| CarstenKoenig/YouVote | test/Spec.hs | bsd-3-clause | 3,315 | 0 | 19 | 749 | 1,054 | 548 | 506 | 84 | 1 |
{-# OPTIONS -Wall #-}
module Game.HYahtzee.Engine.Transition where
data Transition l a = TransNorm l (a -> a) (Choice l a)
| TransFinal l (a -> a)
data Choice l a = Choice (a -> Bool) (Transition l a) (Transition l a)
executeTransition :: (Monad m) => a -> Transition t a -> (t -> a -> m a) -> m a
executeTransition state (TransNorm name f choice) io =
do newState <- (io name . f) state
executeChoice newState choice io
executeTransition state (TransFinal name f) io =
(io name . f) state
executeChoice :: (Monad m) => a -> Choice t a -> (t -> a -> m a) -> m a
executeChoice state (Choice test t1 t2) io =
if test state
then executeTransition state t1 io
else executeTransition state t2 io
{- Example -}
{-
mytran :: Transition String Integer
mytran = TransNorm "mytran"
(\x -> x - 1)
(Choice (> 1) mytran (TransFinal "" id))
iothingy_ :: String -> Integer -> IO Integer
iothingy_ "mytran" i = print i >> return i
iothingy_ _ i = return i
main :: IO ()
main = executeTransition 6 mytran iothingy_ >> return ()
-} | DamienCassou/HYahtzee | Game/HYahtzee/Engine/Transition.hs | bsd-3-clause | 1,098 | 0 | 12 | 280 | 321 | 166 | 155 | 16 | 2 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Wiki page controller.
module HL.C.Wiki where
import HL.C
import HL.M.Wiki
import HL.V.Wiki
import Prelude hiding (readFile)
-- | Wiki home (no page specified).
getWikiHomeR :: C Html
getWikiHomeR =
redirect (WikiR "HaskellWiki:Community")
-- | Wiki controller.
getWikiR :: Text -> C Html
getWikiR name =
do url <- getUrlRender
result <- io (getWikiPage name)
senza (wikiV url result)
| yogsototh/hl | src/HL/C/Wiki.hs | bsd-3-clause | 511 | 0 | 10 | 92 | 118 | 65 | 53 | 16 | 1 |
{-# LANGUAGE ViewPatterns #-}
module GeoService(getAllCities,autocomplete,autocompleteWithLimit) where
import Control.Monad.Trans.Either
import Servant.Client
import System.Environment
import Servant
import Data.Text (Text)
import GeoService.Model.City
import Api
getAllCities :: IO (Either String [GeoService.Model.City.City])
getAllCities = do
url <- getEnv "GEO_ENDPOINT"
let Right base = parseBaseUrl url
a <- runEitherT (getAllCites' base)
return a
autocomplete :: Text -> IO (Either String [GeoService.Model.City.City])
autocomplete work = do
url <- getEnv "GEO_ENDPOINT"
let Right base = parseBaseUrl url
a <- runEitherT (cityAutocomplete' work Nothing base)
return a
autocompleteWithLimit :: Text -> Int -> IO (Either String [GeoService.Model.City.City])
autocompleteWithLimit work limit = do
url <- getEnv "GEO_ENDPOINT"
let Right base = parseBaseUrl url
a <- runEitherT (cityAutocomplete' work (Just limit) base)
return a
( searchCountry' :<|> serachCountryShort :<|> getAllCites' :<|> cityAutocomplete' :<|> addCity :<|> refresh) = client api | Romer4ig/geodb | src/GeoService.hs | bsd-3-clause | 1,164 | 2 | 12 | 239 | 351 | 174 | 177 | 28 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Minecraft.Format.TileEntity
-- Copyright : (c) Tamar Christina 2012
-- License : BSD3
--
-- Maintainer : tamar@zhox.com
-- Stability : experimental
-- Portability : portable
--
-- Datatype description of the Schematic format.
-- Read more at of the format at
-- http://www.minecraftwiki.net/wiki/Schematic_File_Format
-- These .schematic files are a gzipped NBT format
--
-----------------------------------------------------------------------------
module Minecraft.Format.TileEntity where
type TileEntities = [TileEntity]
-- | Known TileEntity ids: Furnace, Sign, MobSpawner, Chest, Music, Trap,
-- RecordPlayer, Piston, Cauldron, EnchantTable, and End portal
data TileEntity
= TileEntity
deriving (Eq, Show) | Mistuke/CraftGen | Minecraft/Format/TileEntity.hs | bsd-3-clause | 835 | 0 | 6 | 122 | 52 | 39 | 13 | 5 | 0 |
{-------------------------------------------------------------------------------
MorphGrammar.Hofm.Transf
Higher-order functions morphology: transformations and condition functions
v1.0
Jan Snajder <jan.snajder@fer.hr>
(c) 2008 TakeLab
University of Zagreb
Faculty of Electrical Engineering and Computing
-------------------------------------------------------------------------------}
module MorphGrammar.Hofm.Transf (
Transf (..),
InvTransf (..),
OptTransf (..),
AnalyzableTransf (..),
sfx,
pfx,
dsfx,
dpfx,
difx,
asfx,
apfx,
aifx,
try,
opt,
Cond (..),
FCond,
ends,
starts,
nends) where
import Data.Maybe
import Data.List
import Data.Char
import Control.Monad
import Data.Ord (comparing)
--------------------------------------------------------------------------------
-- String transformation class
--------------------------------------------------------------------------------
class Transf t where
($$) :: (MonadPlus m) => t -> String -> m String
(&) :: t -> t -> t
rsfx :: String -> String -> t
rpfx :: String -> String -> t
rifx :: String -> String -> t
nul :: t
fail :: t -- mislim da ovo ne treba eksplicitno. ili?
-- mora vrijediti: forall s. fails $$ s == mzero
class (Transf t) => InvTransf t where -- invertible transf
inv :: t -> t
class (Transf t) => OptTransf t where
(.||.) :: t -> t -> t -- "orelse": do right ONLY IF left fails
(.|.) :: t -> t -> t -- "or": do both transformations
class (Transf t, Eq t) => AnalyzableTransf t where
functional :: t -> Bool
injective :: t -> Bool
consistent :: t -> Bool
consistent t = t /= MorphGrammar.Hofm.Transf.fail
infixr 9 &
infixr 6 $$
--------------------------------------------------------------------------------
-- Wrappers for common string transformations
--------------------------------------------------------------------------------
sfx :: (Transf t) => String -> t
sfx s = rsfx "" s
pfx :: (Transf t) => String -> t
pfx s = rpfx "" s
-- NB: 'ifx' operation is not well-defined and thus omitted
dsfx :: (Transf t) => String -> t
dsfx s = rsfx s ""
dpfx :: (Transf t) => String -> t
dpfx p = rpfx p ""
difx :: (Transf t) => String -> t
difx i = rifx i ""
-- generic afix alternation
afx :: (OptTransf t) => (String -> String -> t) -> [(String,String)] -> t
afx r [] = MorphGrammar.Hofm.Transf.fail
afx r as = foldl1 (.|.) $ map (uncurry r) as
asfx :: (OptTransf t) => [(String,String)] -> t
asfx = afx rsfx
apfx :: (OptTransf t) => [(String,String)] -> t
apfx = afx rpfx
aifx :: (OptTransf t) => [(String,String)] -> t
aifx = afx rifx
try :: (OptTransf t) => t -> t -- transform if applicable (do if you can)
try = (.||. nul)
opt :: (OptTransf t) => t -> t -- optional transform
opt = (.|. nul)
{-- Examples:
> sfx "i" & alt sibil & inv(sfx "a") $$ "slika" :: Maybe String
Just "slici"
> inv(sfx "i" & alt sibil & inv(sfx "a")) $$ "slici" :: [String]
["slika"]
--}
--------------------------------------------------------------------------------
-- Condition testing
--------------------------------------------------------------------------------
class Cond c where
test :: c -> String -> Bool
land :: c -> c -> c
lor :: c -> c -> c
neg :: c -> c
always :: c
never :: c
c1 `land` c2 = neg (neg c1 `lor` neg c2)
c1 `lor` c2 = neg (neg c1 `land` neg c2)
never = neg $ always
data FCond = FCond (String -> Bool)
instance Cond FCond where
test (FCond c) = c
land (FCond c1) (FCond c2) = FCond $ \s -> c1 s && c2 s
lor (FCond c1) (FCond c2) = FCond $ \s -> c1 s || c2 s
neg (FCond c) = FCond $ not . c
always = FCond $ const True
instance Show FCond where
show c = "<fcond>"
--------------------------------------------------------------------------------
-- Common condition functions
--------------------------------------------------------------------------------
nends :: [String] -> FCond
nends = neg . ends
ends :: [String] -> FCond
ends ss = FCond $ \s -> any (`isSuffixOf` s) ss
starts :: [String] -> FCond
starts ss = FCond $ \s -> any (`isPrefixOf` s) ss
| jsnajder/hofm | src/MorphGrammar/Hofm/Transf.hs | bsd-3-clause | 4,123 | 0 | 10 | 823 | 1,202 | 674 | 528 | 93 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
This module defines interface types and binders
-}
{-# LANGUAGE CPP, FlexibleInstances #-}
-- FlexibleInstances for Binary (DefMethSpec IfaceType)
module IfaceType (
IfExtName, IfLclName,
IfaceType(..), IfacePredType, IfaceKind, IfaceCoercion(..),
IfaceUnivCoProv(..),
IfaceTyCon(..), IfaceTyConInfo(..),
IfaceTyLit(..), IfaceTcArgs(..),
IfaceContext, IfaceBndr(..), IfaceOneShot(..), IfaceLamBndr,
IfaceTvBndr, IfaceIdBndr, IfaceTyConBinder(..),
IfaceForAllBndr(..), VisibilityFlag(..),
ifConstraintKind, ifTyConBinderTyVar, ifTyConBinderName,
-- Equality testing
IfRnEnv2, emptyIfRnEnv2, eqIfaceType, eqIfaceTypes,
eqIfaceTcArgs, eqIfaceTvBndrs, isIfaceLiftedTypeKind,
-- Conversion from Type -> IfaceType
toIfaceType, toIfaceTypes, toIfaceKind, toIfaceTyVar,
toIfaceContext, toIfaceBndr, toIfaceIdBndr,
toIfaceTyCon, toIfaceTyCon_name,
toIfaceTcArgs, toIfaceTvBndrs,
zipIfaceBinders, toDegenerateBinders,
binderToIfaceForAllBndr,
-- Conversion from IfaceTcArgs -> IfaceType
tcArgsIfaceTypes,
-- Conversion from Coercion -> IfaceCoercion
toIfaceCoercion,
-- Printing
pprIfaceType, pprParendIfaceType,
pprIfaceContext, pprIfaceContextArr,
pprIfaceIdBndr, pprIfaceLamBndr, pprIfaceTvBndr, pprIfaceTyConBinders,
pprIfaceBndrs, pprIfaceTcArgs, pprParendIfaceTcArgs,
pprIfaceForAllPart, pprIfaceForAll, pprIfaceSigmaType,
pprIfaceCoercion, pprParendIfaceCoercion,
splitIfaceSigmaTy, pprIfaceTypeApp, pprUserIfaceForAll,
suppressIfaceInvisibles,
stripIfaceInvisVars,
stripInvisArgs,
substIfaceType, substIfaceTyVar, substIfaceTcArgs, mkIfaceTySubst,
eqIfaceTvBndr
) where
#include "HsVersions.h"
import Coercion
import DataCon ( isTupleDataCon )
import TcType
import DynFlags
import TyCoRep -- needs to convert core types to iface types
import TyCon hiding ( pprPromotionQuote )
import CoAxiom
import Id
import Var
-- import RnEnv( FastStringEnv, mkFsEnv, lookupFsEnv )
import TysWiredIn
import TysPrim
import PrelNames
import Name
import BasicTypes
import Binary
import Outputable
import FastString
import UniqSet
import VarEnv
import UniqFM
import Util
{-
************************************************************************
* *
Local (nested) binders
* *
************************************************************************
-}
type IfLclName = FastString -- A local name in iface syntax
type IfExtName = Name -- An External or WiredIn Name can appear in IfaceSyn
-- (However Internal or System Names never should)
data IfaceBndr -- Local (non-top-level) binders
= IfaceIdBndr {-# UNPACK #-} !IfaceIdBndr
| IfaceTvBndr {-# UNPACK #-} !IfaceTvBndr
type IfaceIdBndr = (IfLclName, IfaceType)
type IfaceTvBndr = (IfLclName, IfaceKind)
data IfaceOneShot -- See Note [Preserve OneShotInfo] in CoreTicy
= IfaceNoOneShot -- and Note [The oneShot function] in MkId
| IfaceOneShot
type IfaceLamBndr
= (IfaceBndr, IfaceOneShot)
{-
%************************************************************************
%* *
IfaceType
%* *
%************************************************************************
-}
-------------------------------
type IfaceKind = IfaceType
data IfaceType -- A kind of universal type, used for types and kinds
= IfaceTyVar IfLclName -- Type/coercion variable only, not tycon
| IfaceLitTy IfaceTyLit
| IfaceAppTy IfaceType IfaceType
| IfaceFunTy IfaceType IfaceType
| IfaceDFunTy IfaceType IfaceType
| IfaceForAllTy IfaceForAllBndr IfaceType
| IfaceTyConApp IfaceTyCon IfaceTcArgs -- Not necessarily saturated
-- Includes newtypes, synonyms, tuples
| IfaceCastTy IfaceType IfaceCoercion
| IfaceCoercionTy IfaceCoercion
| IfaceTupleTy -- Saturated tuples (unsaturated ones use IfaceTyConApp)
TupleSort IfaceTyConInfo -- A bit like IfaceTyCon
IfaceTcArgs -- arity = length args
-- For promoted data cons, the kind args are omitted
type IfacePredType = IfaceType
type IfaceContext = [IfacePredType]
data IfaceTyLit
= IfaceNumTyLit Integer
| IfaceStrTyLit FastString
deriving (Eq)
data IfaceForAllBndr
= IfaceTv IfaceTvBndr VisibilityFlag
data IfaceTyConBinder
= IfaceAnon IfLclName IfaceType -- like Anon, but it includes a name from
-- which to produce a tyConTyVar
| IfaceNamed IfaceForAllBndr
-- See Note [Suppressing invisible arguments]
-- We use a new list type (rather than [(IfaceType,Bool)], because
-- it'll be more compact and faster to parse in interface
-- files. Rather than two bytes and two decisions (nil/cons, and
-- type/kind) there'll just be one.
data IfaceTcArgs
= ITC_Nil
| ITC_Vis IfaceType IfaceTcArgs
| ITC_Invis IfaceKind IfaceTcArgs
-- Encodes type constructors, kind constructors,
-- coercion constructors, the lot.
-- We have to tag them in order to pretty print them
-- properly.
data IfaceTyCon = IfaceTyCon { ifaceTyConName :: IfExtName
, ifaceTyConInfo :: IfaceTyConInfo }
deriving (Eq)
data IfaceTyConInfo -- Used to guide pretty-printing
-- and to disambiguate D from 'D (they share a name)
= NoIfaceTyConInfo
| IfacePromotedDataCon
deriving (Eq)
data IfaceCoercion
= IfaceReflCo Role IfaceType
| IfaceFunCo Role IfaceCoercion IfaceCoercion
| IfaceTyConAppCo Role IfaceTyCon [IfaceCoercion]
| IfaceAppCo IfaceCoercion IfaceCoercion
| IfaceForAllCo IfaceTvBndr IfaceCoercion IfaceCoercion
| IfaceCoVarCo IfLclName
| IfaceAxiomInstCo IfExtName BranchIndex [IfaceCoercion]
| IfaceUnivCo IfaceUnivCoProv Role IfaceType IfaceType
| IfaceSymCo IfaceCoercion
| IfaceTransCo IfaceCoercion IfaceCoercion
| IfaceNthCo Int IfaceCoercion
| IfaceLRCo LeftOrRight IfaceCoercion
| IfaceInstCo IfaceCoercion IfaceCoercion
| IfaceCoherenceCo IfaceCoercion IfaceCoercion
| IfaceKindCo IfaceCoercion
| IfaceSubCo IfaceCoercion
| IfaceAxiomRuleCo IfLclName [IfaceCoercion]
data IfaceUnivCoProv
= IfaceUnsafeCoerceProv
| IfacePhantomProv IfaceCoercion
| IfaceProofIrrelProv IfaceCoercion
| IfacePluginProv String
-- this constant is needed for dealing with pretty-printing classes
ifConstraintKind :: IfaceKind
ifConstraintKind = IfaceTyConApp (IfaceTyCon { ifaceTyConName = getName constraintKindTyCon
, ifaceTyConInfo = NoIfaceTyConInfo })
ITC_Nil
{-
%************************************************************************
%* *
Functions over IFaceTypes
* *
************************************************************************
-}
eqIfaceTvBndr :: IfaceTvBndr -> IfaceTvBndr -> Bool
eqIfaceTvBndr (occ1, _) (occ2, _) = occ1 == occ2
isIfaceLiftedTypeKind :: IfaceKind -> Bool
isIfaceLiftedTypeKind (IfaceTyConApp tc ITC_Nil)
= isLiftedTypeKindTyConName (ifaceTyConName tc)
isIfaceLiftedTypeKind (IfaceTyConApp tc
(ITC_Vis (IfaceTyConApp ptr_rep_lifted ITC_Nil) ITC_Nil))
= ifaceTyConName tc == tYPETyConName
&& ifaceTyConName ptr_rep_lifted `hasKey` ptrRepLiftedDataConKey
isIfaceLiftedTypeKind _ = False
splitIfaceSigmaTy :: IfaceType -> ([IfaceForAllBndr], [IfacePredType], IfaceType)
-- Mainly for printing purposes
splitIfaceSigmaTy ty
= (bndrs, theta, tau)
where
(bndrs, rho) = split_foralls ty
(theta, tau) = split_rho rho
split_foralls (IfaceForAllTy bndr ty)
= case split_foralls ty of { (bndrs, rho) -> (bndr:bndrs, rho) }
split_foralls rho = ([], rho)
split_rho (IfaceDFunTy ty1 ty2)
= case split_rho ty2 of { (ps, tau) -> (ty1:ps, tau) }
split_rho tau = ([], tau)
suppressIfaceInvisibles :: DynFlags -> [IfaceTyConBinder] -> [a] -> [a]
suppressIfaceInvisibles dflags tys xs
| gopt Opt_PrintExplicitKinds dflags = xs
| otherwise = suppress tys xs
where
suppress _ [] = []
suppress [] a = a
suppress (k:ks) a@(_:xs)
| isIfaceInvisBndr k = suppress ks xs
| otherwise = a
stripIfaceInvisVars :: DynFlags -> [IfaceTyConBinder] -> [IfaceTyConBinder]
stripIfaceInvisVars dflags tyvars
| gopt Opt_PrintExplicitKinds dflags = tyvars
| otherwise = filterOut isIfaceInvisBndr tyvars
isIfaceInvisBndr :: IfaceTyConBinder -> Bool
isIfaceInvisBndr (IfaceNamed (IfaceTv _ Invisible)) = True
isIfaceInvisBndr (IfaceNamed (IfaceTv _ Specified)) = True
isIfaceInvisBndr _ = False
-- | Extract a IfaceTvBndr from a IfaceTyConBinder
ifTyConBinderTyVar :: IfaceTyConBinder -> IfaceTvBndr
ifTyConBinderTyVar (IfaceAnon name ki) = (name, ki)
ifTyConBinderTyVar (IfaceNamed (IfaceTv tv _)) = tv
-- | Extract the variable name from a IfaceTyConBinder
ifTyConBinderName :: IfaceTyConBinder -> IfLclName
ifTyConBinderName (IfaceAnon name _) = name
ifTyConBinderName (IfaceNamed (IfaceTv (name, _) _)) = name
ifTyVarsOfType :: IfaceType -> UniqSet IfLclName
ifTyVarsOfType ty
= case ty of
IfaceTyVar v -> unitUniqSet v
IfaceAppTy fun arg
-> ifTyVarsOfType fun `unionUniqSets` ifTyVarsOfType arg
IfaceFunTy arg res
-> ifTyVarsOfType arg `unionUniqSets` ifTyVarsOfType res
IfaceDFunTy arg res
-> ifTyVarsOfType arg `unionUniqSets` ifTyVarsOfType res
IfaceForAllTy bndr ty
-> let (free, bound) = ifTyVarsOfForAllBndr bndr in
delListFromUniqSet (ifTyVarsOfType ty) bound `unionUniqSets` free
IfaceTyConApp _ args -> ifTyVarsOfArgs args
IfaceLitTy _ -> emptyUniqSet
IfaceCastTy ty co
-> ifTyVarsOfType ty `unionUniqSets` ifTyVarsOfCoercion co
IfaceCoercionTy co -> ifTyVarsOfCoercion co
IfaceTupleTy _ _ args -> ifTyVarsOfArgs args
ifTyVarsOfForAllBndr :: IfaceForAllBndr
-> ( UniqSet IfLclName -- names used free in the binder
, [IfLclName] ) -- names bound by this binder
ifTyVarsOfForAllBndr (IfaceTv (name, kind) _) = (ifTyVarsOfType kind, [name])
ifTyVarsOfArgs :: IfaceTcArgs -> UniqSet IfLclName
ifTyVarsOfArgs args = argv emptyUniqSet args
where
argv vs (ITC_Vis t ts) = argv (vs `unionUniqSets` (ifTyVarsOfType t)) ts
argv vs (ITC_Invis k ks) = argv (vs `unionUniqSets` (ifTyVarsOfType k)) ks
argv vs ITC_Nil = vs
ifTyVarsOfCoercion :: IfaceCoercion -> UniqSet IfLclName
ifTyVarsOfCoercion = go
where
go (IfaceReflCo _ ty) = ifTyVarsOfType ty
go (IfaceFunCo _ c1 c2) = go c1 `unionUniqSets` go c2
go (IfaceTyConAppCo _ _ cos) = ifTyVarsOfCoercions cos
go (IfaceAppCo c1 c2) = go c1 `unionUniqSets` go c2
go (IfaceForAllCo (bound, _) kind_co co)
= go co `delOneFromUniqSet` bound `unionUniqSets` go kind_co
go (IfaceCoVarCo cv) = unitUniqSet cv
go (IfaceAxiomInstCo _ _ cos) = ifTyVarsOfCoercions cos
go (IfaceUnivCo p _ ty1 ty2) = go_prov p `unionUniqSets`
ifTyVarsOfType ty1 `unionUniqSets`
ifTyVarsOfType ty2
go (IfaceSymCo co) = go co
go (IfaceTransCo c1 c2) = go c1 `unionUniqSets` go c2
go (IfaceNthCo _ co) = go co
go (IfaceLRCo _ co) = go co
go (IfaceInstCo c1 c2) = go c1 `unionUniqSets` go c2
go (IfaceCoherenceCo c1 c2) = go c1 `unionUniqSets` go c2
go (IfaceKindCo co) = go co
go (IfaceSubCo co) = go co
go (IfaceAxiomRuleCo rule cos)
= unionManyUniqSets
[ unitUniqSet rule
, ifTyVarsOfCoercions cos ]
go_prov IfaceUnsafeCoerceProv = emptyUniqSet
go_prov (IfacePhantomProv co) = go co
go_prov (IfaceProofIrrelProv co) = go co
go_prov (IfacePluginProv _) = emptyUniqSet
ifTyVarsOfCoercions :: [IfaceCoercion] -> UniqSet IfLclName
ifTyVarsOfCoercions = foldr (unionUniqSets . ifTyVarsOfCoercion) emptyUniqSet
{-
Substitutions on IfaceType. This is only used during pretty-printing to construct
the result type of a GADT, and does not deal with binders (eg IfaceForAll), so
it doesn't need fancy capture stuff.
-}
type IfaceTySubst = FastStringEnv IfaceType
mkIfaceTySubst :: [IfaceTvBndr] -> [IfaceType] -> IfaceTySubst
mkIfaceTySubst tvs tys = mkFsEnv $ zipWithEqual "mkIfaceTySubst" (\(fs,_) ty -> (fs,ty)) tvs tys
substIfaceType :: IfaceTySubst -> IfaceType -> IfaceType
substIfaceType env ty
= go ty
where
go (IfaceTyVar tv) = substIfaceTyVar env tv
go (IfaceAppTy t1 t2) = IfaceAppTy (go t1) (go t2)
go (IfaceFunTy t1 t2) = IfaceFunTy (go t1) (go t2)
go (IfaceDFunTy t1 t2) = IfaceDFunTy (go t1) (go t2)
go ty@(IfaceLitTy {}) = ty
go (IfaceTyConApp tc tys) = IfaceTyConApp tc (substIfaceTcArgs env tys)
go (IfaceTupleTy s i tys) = IfaceTupleTy s i (substIfaceTcArgs env tys)
go (IfaceForAllTy {}) = pprPanic "substIfaceType" (ppr ty)
go (IfaceCastTy ty co) = IfaceCastTy (go ty) (go_co co)
go (IfaceCoercionTy co) = IfaceCoercionTy (go_co co)
go_co (IfaceReflCo r ty) = IfaceReflCo r (go ty)
go_co (IfaceFunCo r c1 c2) = IfaceFunCo r (go_co c1) (go_co c2)
go_co (IfaceTyConAppCo r tc cos) = IfaceTyConAppCo r tc (go_cos cos)
go_co (IfaceAppCo c1 c2) = IfaceAppCo (go_co c1) (go_co c2)
go_co (IfaceForAllCo {}) = pprPanic "substIfaceCoercion" (ppr ty)
go_co (IfaceCoVarCo cv) = IfaceCoVarCo cv
go_co (IfaceAxiomInstCo a i cos) = IfaceAxiomInstCo a i (go_cos cos)
go_co (IfaceUnivCo prov r t1 t2) = IfaceUnivCo (go_prov prov) r (go t1) (go t2)
go_co (IfaceSymCo co) = IfaceSymCo (go_co co)
go_co (IfaceTransCo co1 co2) = IfaceTransCo (go_co co1) (go_co co2)
go_co (IfaceNthCo n co) = IfaceNthCo n (go_co co)
go_co (IfaceLRCo lr co) = IfaceLRCo lr (go_co co)
go_co (IfaceInstCo c1 c2) = IfaceInstCo (go_co c1) (go_co c2)
go_co (IfaceCoherenceCo c1 c2) = IfaceCoherenceCo (go_co c1) (go_co c2)
go_co (IfaceKindCo co) = IfaceKindCo (go_co co)
go_co (IfaceSubCo co) = IfaceSubCo (go_co co)
go_co (IfaceAxiomRuleCo n cos) = IfaceAxiomRuleCo n (go_cos cos)
go_cos = map go_co
go_prov IfaceUnsafeCoerceProv = IfaceUnsafeCoerceProv
go_prov (IfacePhantomProv co) = IfacePhantomProv (go_co co)
go_prov (IfaceProofIrrelProv co) = IfaceProofIrrelProv (go_co co)
go_prov (IfacePluginProv str) = IfacePluginProv str
substIfaceTcArgs :: IfaceTySubst -> IfaceTcArgs -> IfaceTcArgs
substIfaceTcArgs env args
= go args
where
go ITC_Nil = ITC_Nil
go (ITC_Vis ty tys) = ITC_Vis (substIfaceType env ty) (go tys)
go (ITC_Invis ty tys) = ITC_Invis (substIfaceType env ty) (go tys)
substIfaceTyVar :: IfaceTySubst -> IfLclName -> IfaceType
substIfaceTyVar env tv
| Just ty <- lookupFsEnv env tv = ty
| otherwise = IfaceTyVar tv
{-
************************************************************************
* *
Equality over IfaceTypes
* *
************************************************************************
Note [No kind check in ifaces]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We check iface types for equality only when checking the consistency
between two user-written signatures. In these cases, there is no possibility
for a kind mismatch. So we omit the kind check (which would be impossible to
write, anyway.)
-}
-- Like an RnEnv2, but mapping from FastString to deBruijn index
-- DeBruijn; see eqTypeX
type BoundVar = Int
data IfRnEnv2
= IRV2 { ifenvL :: UniqFM BoundVar -- from FastString
, ifenvR :: UniqFM BoundVar
, ifenv_next :: BoundVar
}
emptyIfRnEnv2 :: IfRnEnv2
emptyIfRnEnv2 = IRV2 { ifenvL = emptyUFM
, ifenvR = emptyUFM
, ifenv_next = 0 }
rnIfOccL :: IfRnEnv2 -> IfLclName -> Maybe BoundVar
rnIfOccL env = lookupUFM (ifenvL env)
rnIfOccR :: IfRnEnv2 -> IfLclName -> Maybe BoundVar
rnIfOccR env = lookupUFM (ifenvR env)
extendIfRnEnv2 :: IfRnEnv2 -> IfLclName -> IfLclName -> IfRnEnv2
extendIfRnEnv2 IRV2 { ifenvL = lenv
, ifenvR = renv
, ifenv_next = n } tv1 tv2
= IRV2 { ifenvL = addToUFM lenv tv1 n
, ifenvR = addToUFM renv tv2 n
, ifenv_next = n + 1
}
-- See Note [No kind check in ifaces]
eqIfaceType :: IfRnEnv2 -> IfaceType -> IfaceType -> Bool
eqIfaceType env (IfaceTyVar tv1) (IfaceTyVar tv2) =
case (rnIfOccL env tv1, rnIfOccR env tv2) of
(Just v1, Just v2) -> v1 == v2
(Nothing, Nothing) -> tv1 == tv2
_ -> False
eqIfaceType _ (IfaceLitTy l1) (IfaceLitTy l2) = l1 == l2
eqIfaceType env (IfaceAppTy t11 t12) (IfaceAppTy t21 t22)
= eqIfaceType env t11 t21 && eqIfaceType env t12 t22
eqIfaceType env (IfaceFunTy t11 t12) (IfaceFunTy t21 t22)
= eqIfaceType env t11 t21 && eqIfaceType env t12 t22
eqIfaceType env (IfaceDFunTy t11 t12) (IfaceDFunTy t21 t22)
= eqIfaceType env t11 t21 && eqIfaceType env t12 t22
eqIfaceType env (IfaceForAllTy bndr1 t1) (IfaceForAllTy bndr2 t2)
= eqIfaceForAllBndr env bndr1 bndr2 (\env' -> eqIfaceType env' t1 t2)
eqIfaceType env (IfaceTyConApp tc1 tys1) (IfaceTyConApp tc2 tys2)
= tc1 == tc2 && eqIfaceTcArgs env tys1 tys2
eqIfaceType env (IfaceTupleTy s1 tc1 tys1) (IfaceTupleTy s2 tc2 tys2)
= s1 == s2 && tc1 == tc2 && eqIfaceTcArgs env tys1 tys2
eqIfaceType env (IfaceCastTy t1 _) (IfaceCastTy t2 _)
= eqIfaceType env t1 t2
eqIfaceType _ (IfaceCoercionTy {}) (IfaceCoercionTy {})
= True
eqIfaceType _ _ _ = False
eqIfaceTypes :: IfRnEnv2 -> [IfaceType] -> [IfaceType] -> Bool
eqIfaceTypes env tys1 tys2 = and (zipWith (eqIfaceType env) tys1 tys2)
eqIfaceForAllBndr :: IfRnEnv2 -> IfaceForAllBndr -> IfaceForAllBndr
-> (IfRnEnv2 -> Bool) -- continuation
-> Bool
eqIfaceForAllBndr env (IfaceTv (tv1, k1) vis1) (IfaceTv (tv2, k2) vis2) k
= eqIfaceType env k1 k2 && vis1 == vis2 &&
k (extendIfRnEnv2 env tv1 tv2)
eqIfaceTcArgs :: IfRnEnv2 -> IfaceTcArgs -> IfaceTcArgs -> Bool
eqIfaceTcArgs _ ITC_Nil ITC_Nil = True
eqIfaceTcArgs env (ITC_Vis ty1 tys1) (ITC_Vis ty2 tys2)
= eqIfaceType env ty1 ty2 && eqIfaceTcArgs env tys1 tys2
eqIfaceTcArgs env (ITC_Invis ty1 tys1) (ITC_Invis ty2 tys2)
= eqIfaceType env ty1 ty2 && eqIfaceTcArgs env tys1 tys2
eqIfaceTcArgs _ _ _ = False
-- | Similar to 'eqTyVarBndrs', checks that tyvar lists
-- are the same length and have matching kinds; if so, extend the
-- 'IfRnEnv2'. Returns 'Nothing' if they don't match.
eqIfaceTvBndrs :: IfRnEnv2 -> [IfaceTvBndr] -> [IfaceTvBndr] -> Maybe IfRnEnv2
eqIfaceTvBndrs env [] [] = Just env
eqIfaceTvBndrs env ((tv1, k1):tvs1) ((tv2, k2):tvs2)
| eqIfaceType env k1 k2
= eqIfaceTvBndrs (extendIfRnEnv2 env tv1 tv2) tvs1 tvs2
eqIfaceTvBndrs _ _ _ = Nothing
{-
************************************************************************
* *
Functions over IFaceTcArgs
* *
************************************************************************
-}
stripInvisArgs :: DynFlags -> IfaceTcArgs -> IfaceTcArgs
stripInvisArgs dflags tys
| gopt Opt_PrintExplicitKinds dflags = tys
| otherwise = suppress_invis tys
where
suppress_invis c
= case c of
ITC_Invis _ ts -> suppress_invis ts
_ -> c
toIfaceTcArgs :: TyCon -> [Type] -> IfaceTcArgs
-- See Note [Suppressing invisible arguments]
toIfaceTcArgs tc ty_args
= go (mkEmptyTCvSubst in_scope) (tyConKind tc) ty_args
where
in_scope = mkInScopeSet (tyCoVarsOfTypes ty_args)
go _ _ [] = ITC_Nil
go env ty ts
| Just ty' <- coreView ty
= go env ty' ts
go env (ForAllTy bndr res) (t:ts)
| isVisibleBinder bndr = ITC_Vis t' ts'
| otherwise = ITC_Invis t' ts'
where
t' = toIfaceType t
ts' = go (extendTvSubstBinder env bndr t) res ts
go env (TyVarTy tv) ts
| Just ki <- lookupTyVar env tv = go env ki ts
go env kind (t:ts) = WARN( True, ppr tc $$ ppr (tyConKind tc) $$ ppr ty_args )
ITC_Vis (toIfaceType t) (go env kind ts) -- Ill-kinded
tcArgsIfaceTypes :: IfaceTcArgs -> [IfaceType]
tcArgsIfaceTypes ITC_Nil = []
tcArgsIfaceTypes (ITC_Invis t ts) = t : tcArgsIfaceTypes ts
tcArgsIfaceTypes (ITC_Vis t ts) = t : tcArgsIfaceTypes ts
{-
Note [Suppressing invisible arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We use the IfaceTcArgs to specify which of the arguments to a type
constructor should be visible.
This in turn used to control suppression when printing types,
under the control of -fprint-explicit-kinds.
See also Type.filterOutInvisibleTypes.
For example, given
T :: forall k. (k->*) -> k -> * -- Ordinary kind polymorphism
'Just :: forall k. k -> 'Maybe k -- Promoted
we want
T * Tree Int prints as T Tree Int
'Just * prints as Just *
************************************************************************
* *
Pretty-printing
* *
************************************************************************
-}
pprIfaceInfixApp :: (TyPrec -> a -> SDoc) -> TyPrec -> SDoc -> a -> a -> SDoc
pprIfaceInfixApp pp p pp_tc ty1 ty2
= maybeParen p FunPrec $
sep [pp FunPrec ty1, pprInfixVar True pp_tc <+> pp FunPrec ty2]
pprIfacePrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc
pprIfacePrefixApp p pp_fun pp_tys
| null pp_tys = pp_fun
| otherwise = maybeParen p TyConPrec $
hang pp_fun 2 (sep pp_tys)
-- ----------------------------- Printing binders ------------------------------------
instance Outputable IfaceBndr where
ppr (IfaceIdBndr bndr) = pprIfaceIdBndr bndr
ppr (IfaceTvBndr bndr) = char '@' <+> pprIfaceTvBndr bndr
pprIfaceBndrs :: [IfaceBndr] -> SDoc
pprIfaceBndrs bs = sep (map ppr bs)
pprIfaceLamBndr :: IfaceLamBndr -> SDoc
pprIfaceLamBndr (b, IfaceNoOneShot) = ppr b
pprIfaceLamBndr (b, IfaceOneShot) = ppr b <> text "[OneShot]"
pprIfaceIdBndr :: (IfLclName, IfaceType) -> SDoc
pprIfaceIdBndr (name, ty) = parens (ppr name <+> dcolon <+> ppr ty)
pprIfaceTvBndr :: IfaceTvBndr -> SDoc
pprIfaceTvBndr (tv, ki)
| isIfaceLiftedTypeKind ki = ppr tv
| otherwise = parens (ppr tv <+> dcolon <+> ppr ki)
pprIfaceTyConBinders :: [IfaceTyConBinder] -> SDoc
pprIfaceTyConBinders = sep . map go
where
go (IfaceAnon name ki) = pprIfaceTvBndr (name, ki)
go (IfaceNamed (IfaceTv tv _)) = pprIfaceTvBndr tv
instance Binary IfaceBndr where
put_ bh (IfaceIdBndr aa) = do
putByte bh 0
put_ bh aa
put_ bh (IfaceTvBndr ab) = do
putByte bh 1
put_ bh ab
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
return (IfaceIdBndr aa)
_ -> do ab <- get bh
return (IfaceTvBndr ab)
instance Binary IfaceOneShot where
put_ bh IfaceNoOneShot = do
putByte bh 0
put_ bh IfaceOneShot = do
putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> do return IfaceNoOneShot
_ -> do return IfaceOneShot
-- ----------------------------- Printing IfaceType ------------------------------------
---------------------------------
instance Outputable IfaceType where
ppr ty = pprIfaceType ty
pprIfaceType, pprParendIfaceType ::IfaceType -> SDoc
pprIfaceType = ppr_ty TopPrec
pprParendIfaceType = ppr_ty TyConPrec
ppr_ty :: TyPrec -> IfaceType -> SDoc
ppr_ty _ (IfaceTyVar tyvar) = ppr tyvar
ppr_ty ctxt_prec (IfaceTyConApp tc tys) = sdocWithDynFlags (pprTyTcApp ctxt_prec tc tys)
ppr_ty _ (IfaceTupleTy s i tys) = pprTuple s i tys
ppr_ty _ (IfaceLitTy n) = ppr_tylit n
-- Function types
ppr_ty ctxt_prec (IfaceFunTy ty1 ty2)
= -- We don't want to lose synonyms, so we mustn't use splitFunTys here.
maybeParen ctxt_prec FunPrec $
sep [ppr_ty FunPrec ty1, sep (ppr_fun_tail ty2)]
where
ppr_fun_tail (IfaceFunTy ty1 ty2)
= (arrow <+> ppr_ty FunPrec ty1) : ppr_fun_tail ty2
ppr_fun_tail other_ty
= [arrow <+> pprIfaceType other_ty]
ppr_ty ctxt_prec (IfaceAppTy ty1 ty2)
= maybeParen ctxt_prec TyConPrec $
ppr_ty FunPrec ty1 <+> pprParendIfaceType ty2
ppr_ty ctxt_prec (IfaceCastTy ty co)
= maybeParen ctxt_prec FunPrec $
sep [ppr_ty FunPrec ty, text "`cast`", ppr_co FunPrec co]
ppr_ty ctxt_prec (IfaceCoercionTy co)
= ppr_co ctxt_prec co
ppr_ty ctxt_prec ty
= maybeParen ctxt_prec FunPrec (ppr_iface_sigma_type True ty)
instance Outputable IfaceTcArgs where
ppr tca = pprIfaceTcArgs tca
pprIfaceTcArgs, pprParendIfaceTcArgs :: IfaceTcArgs -> SDoc
pprIfaceTcArgs = ppr_tc_args TopPrec
pprParendIfaceTcArgs = ppr_tc_args TyConPrec
ppr_tc_args :: TyPrec -> IfaceTcArgs -> SDoc
ppr_tc_args ctx_prec args
= let pprTys t ts = ppr_ty ctx_prec t <+> ppr_tc_args ctx_prec ts
in case args of
ITC_Nil -> empty
ITC_Vis t ts -> pprTys t ts
ITC_Invis t ts -> pprTys t ts
-------------------
ppr_iface_sigma_type :: Bool -> IfaceType -> SDoc
ppr_iface_sigma_type show_foralls_unconditionally ty
= ppr_iface_forall_part show_foralls_unconditionally tvs theta (ppr tau)
where
(tvs, theta, tau) = splitIfaceSigmaTy ty
-------------------
pprIfaceForAllPart :: [IfaceForAllBndr] -> [IfaceType] -> SDoc -> SDoc
pprIfaceForAllPart tvs ctxt sdoc = ppr_iface_forall_part False tvs ctxt sdoc
pprIfaceForAllCoPart :: [(IfLclName, IfaceCoercion)] -> SDoc -> SDoc
pprIfaceForAllCoPart tvs sdoc = sep [ pprIfaceForAllCo tvs
, sdoc ]
ppr_iface_forall_part :: Outputable a
=> Bool -> [IfaceForAllBndr] -> [a] -> SDoc -> SDoc
ppr_iface_forall_part show_foralls_unconditionally tvs ctxt sdoc
= sep [ if show_foralls_unconditionally
then pprIfaceForAll tvs
else pprUserIfaceForAll tvs
, pprIfaceContextArr ctxt
, sdoc]
-- | Render the "forall ... ." or "forall ... ->" bit of a type.
pprIfaceForAll :: [IfaceForAllBndr] -> SDoc
pprIfaceForAll [] = empty
pprIfaceForAll bndrs@(IfaceTv _ vis : _)
= add_separator (text "forall" <+> doc) <+> pprIfaceForAll bndrs'
where
(bndrs', doc) = ppr_itv_bndrs bndrs vis
add_separator stuff = case vis of
Visible -> stuff <+> arrow
_inv -> stuff <> dot
-- | Render the ... in @(forall ... .)@ or @(forall ... ->)@.
-- Returns both the list of not-yet-rendered binders and the doc.
-- No anonymous binders here!
ppr_itv_bndrs :: [IfaceForAllBndr]
-> VisibilityFlag -- ^ visibility of the first binder in the list
-> ([IfaceForAllBndr], SDoc)
ppr_itv_bndrs all_bndrs@(bndr@(IfaceTv _ vis) : bndrs) vis1
| vis `sameVis` vis1 = let (bndrs', doc) = ppr_itv_bndrs bndrs vis1 in
(bndrs', pprIfaceForAllBndr bndr <+> doc)
| otherwise = (all_bndrs, empty)
ppr_itv_bndrs [] _ = ([], empty)
pprIfaceForAllCo :: [(IfLclName, IfaceCoercion)] -> SDoc
pprIfaceForAllCo [] = empty
pprIfaceForAllCo tvs = text "forall" <+> pprIfaceForAllCoBndrs tvs <> dot
pprIfaceForAllCoBndrs :: [(IfLclName, IfaceCoercion)] -> SDoc
pprIfaceForAllCoBndrs bndrs = hsep $ map pprIfaceForAllCoBndr bndrs
pprIfaceForAllBndr :: IfaceForAllBndr -> SDoc
pprIfaceForAllBndr (IfaceTv tv Invisible) = sdocWithDynFlags $ \dflags ->
if gopt Opt_PrintExplicitForalls dflags
then braces $ pprIfaceTvBndr tv
else pprIfaceTvBndr tv
pprIfaceForAllBndr (IfaceTv tv _) = pprIfaceTvBndr tv
pprIfaceForAllCoBndr :: (IfLclName, IfaceCoercion) -> SDoc
pprIfaceForAllCoBndr (tv, kind_co)
= parens (ppr tv <+> dcolon <+> pprIfaceCoercion kind_co)
pprIfaceSigmaType :: IfaceType -> SDoc
pprIfaceSigmaType ty = ppr_iface_sigma_type False ty
pprUserIfaceForAll :: [IfaceForAllBndr] -> SDoc
pprUserIfaceForAll tvs
= sdocWithDynFlags $ \dflags ->
ppWhen (any tv_has_kind_var tvs || gopt Opt_PrintExplicitForalls dflags) $
pprIfaceForAll tvs
where
tv_has_kind_var bndr
= not (isEmptyUniqSet (fst (ifTyVarsOfForAllBndr bndr)))
-------------------
-- See equivalent function in TyCoRep.hs
pprIfaceTyList :: TyPrec -> IfaceType -> IfaceType -> SDoc
-- Given a type-level list (t1 ': t2), see if we can print
-- it in list notation [t1, ...].
-- Precondition: Opt_PrintExplicitKinds is off
pprIfaceTyList ctxt_prec ty1 ty2
= case gather ty2 of
(arg_tys, Nothing)
-> char '\'' <> brackets (fsep (punctuate comma
(map (ppr_ty TopPrec) (ty1:arg_tys))))
(arg_tys, Just tl)
-> maybeParen ctxt_prec FunPrec $ hang (ppr_ty FunPrec ty1)
2 (fsep [ colon <+> ppr_ty FunPrec ty | ty <- arg_tys ++ [tl]])
where
gather :: IfaceType -> ([IfaceType], Maybe IfaceType)
-- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn]
-- = (tys, Just tl) means ty is of form t1:t2:...tn:tl
gather (IfaceTyConApp tc tys)
| tcname == consDataConName
, (ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil))) <- tys
, (args, tl) <- gather ty2
= (ty1:args, tl)
| tcname == nilDataConName
= ([], Nothing)
where tcname = ifaceTyConName tc
gather ty = ([], Just ty)
pprIfaceTypeApp :: IfaceTyCon -> IfaceTcArgs -> SDoc
pprIfaceTypeApp tc args = sdocWithDynFlags (pprTyTcApp TopPrec tc args)
pprTyTcApp :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> DynFlags -> SDoc
pprTyTcApp ctxt_prec tc tys dflags
| ifaceTyConName tc `hasKey` ipClassKey
, ITC_Vis (IfaceLitTy (IfaceStrTyLit n)) (ITC_Vis ty ITC_Nil) <- tys
= char '?' <> ftext n <> text "::" <> ppr_ty TopPrec ty
| ifaceTyConName tc == consDataConName
, not (gopt Opt_PrintExplicitKinds dflags)
, ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil)) <- tys
= pprIfaceTyList ctxt_prec ty1 ty2
| ifaceTyConName tc == tYPETyConName
, ITC_Vis (IfaceTyConApp ptr_rep ITC_Nil) ITC_Nil <- tys
, ifaceTyConName ptr_rep `hasKey` ptrRepLiftedDataConKey
= char '*'
| ifaceTyConName tc == tYPETyConName
, ITC_Vis (IfaceTyConApp ptr_rep ITC_Nil) ITC_Nil <- tys
, ifaceTyConName ptr_rep `hasKey` ptrRepUnliftedDataConKey
= char '#'
| otherwise
= ppr_iface_tc_app ppr_ty ctxt_prec tc tys_wo_kinds
where
tys_wo_kinds = tcArgsIfaceTypes $ stripInvisArgs dflags tys
pprIfaceCoTcApp :: TyPrec -> IfaceTyCon -> [IfaceCoercion] -> SDoc
pprIfaceCoTcApp ctxt_prec tc tys = ppr_iface_tc_app ppr_co ctxt_prec tc tys
ppr_iface_tc_app :: (TyPrec -> a -> SDoc) -> TyPrec -> IfaceTyCon -> [a] -> SDoc
ppr_iface_tc_app pp _ tc [ty]
| n == listTyConName = pprPromotionQuote tc <> brackets (pp TopPrec ty)
| n == parrTyConName = pprPromotionQuote tc <> paBrackets (pp TopPrec ty)
where
n = ifaceTyConName tc
ppr_iface_tc_app pp ctxt_prec tc tys
| not (isSymOcc (nameOccName tc_name))
= pprIfacePrefixApp ctxt_prec (ppr tc) (map (pp TyConPrec) tys)
| [ty1,ty2] <- tys -- Infix, two arguments;
-- we know nothing of precedence though
= pprIfaceInfixApp pp ctxt_prec (ppr tc) ty1 ty2
| tc_name == starKindTyConName || tc_name == unliftedTypeKindTyConName
|| tc_name == unicodeStarKindTyConName
= ppr tc -- Do not wrap *, # in parens
| otherwise
= pprIfacePrefixApp ctxt_prec (parens (ppr tc)) (map (pp TyConPrec) tys)
where
tc_name = ifaceTyConName tc
pprTuple :: TupleSort -> IfaceTyConInfo -> IfaceTcArgs -> SDoc
pprTuple sort info args
= -- drop the RuntimeRep vars.
-- See Note [Unboxed tuple RuntimeRep vars] in TyCon
let tys = tcArgsIfaceTypes args
args' = case sort of
UnboxedTuple -> drop (length tys `div` 2) tys
_ -> tys
in
pprPromotionQuoteI info <>
tupleParens sort (pprWithCommas pprIfaceType args')
ppr_tylit :: IfaceTyLit -> SDoc
ppr_tylit (IfaceNumTyLit n) = integer n
ppr_tylit (IfaceStrTyLit n) = text (show n)
pprIfaceCoercion, pprParendIfaceCoercion :: IfaceCoercion -> SDoc
pprIfaceCoercion = ppr_co TopPrec
pprParendIfaceCoercion = ppr_co TyConPrec
ppr_co :: TyPrec -> IfaceCoercion -> SDoc
ppr_co _ (IfaceReflCo r ty) = angleBrackets (ppr ty) <> ppr_role r
ppr_co ctxt_prec (IfaceFunCo r co1 co2)
= maybeParen ctxt_prec FunPrec $
sep (ppr_co FunPrec co1 : ppr_fun_tail co2)
where
ppr_fun_tail (IfaceFunCo r co1 co2)
= (arrow <> ppr_role r <+> ppr_co FunPrec co1) : ppr_fun_tail co2
ppr_fun_tail other_co
= [arrow <> ppr_role r <+> pprIfaceCoercion other_co]
ppr_co _ (IfaceTyConAppCo r tc cos)
= parens (pprIfaceCoTcApp TopPrec tc cos) <> ppr_role r
ppr_co ctxt_prec (IfaceAppCo co1 co2)
= maybeParen ctxt_prec TyConPrec $
ppr_co FunPrec co1 <+> pprParendIfaceCoercion co2
ppr_co ctxt_prec co@(IfaceForAllCo {})
= maybeParen ctxt_prec FunPrec (pprIfaceForAllCoPart tvs (pprIfaceCoercion inner_co))
where
(tvs, inner_co) = split_co co
split_co (IfaceForAllCo (name, _) kind_co co')
= let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'')
split_co co' = ([], co')
ppr_co _ (IfaceCoVarCo covar) = ppr covar
ppr_co ctxt_prec (IfaceUnivCo IfaceUnsafeCoerceProv r ty1 ty2)
= maybeParen ctxt_prec TyConPrec $
text "UnsafeCo" <+> ppr r <+>
pprParendIfaceType ty1 <+> pprParendIfaceType ty2
ppr_co _ (IfaceUnivCo _ _ ty1 ty2)
= angleBrackets ( ppr ty1 <> comma <+> ppr ty2 )
ppr_co ctxt_prec (IfaceInstCo co ty)
= maybeParen ctxt_prec TyConPrec $
text "Inst" <+> pprParendIfaceCoercion co
<+> pprParendIfaceCoercion ty
ppr_co ctxt_prec (IfaceAxiomRuleCo tc cos)
= maybeParen ctxt_prec TyConPrec $ ppr tc <+> parens (interpp'SP cos)
ppr_co ctxt_prec (IfaceAxiomInstCo n i cos)
= ppr_special_co ctxt_prec (ppr n <> brackets (ppr i)) cos
ppr_co ctxt_prec (IfaceSymCo co)
= ppr_special_co ctxt_prec (text "Sym") [co]
ppr_co ctxt_prec (IfaceTransCo co1 co2)
= ppr_special_co ctxt_prec (text "Trans") [co1,co2]
ppr_co ctxt_prec (IfaceNthCo d co)
= ppr_special_co ctxt_prec (text "Nth:" <> int d) [co]
ppr_co ctxt_prec (IfaceLRCo lr co)
= ppr_special_co ctxt_prec (ppr lr) [co]
ppr_co ctxt_prec (IfaceSubCo co)
= ppr_special_co ctxt_prec (text "Sub") [co]
ppr_co ctxt_prec (IfaceCoherenceCo co1 co2)
= ppr_special_co ctxt_prec (text "Coh") [co1,co2]
ppr_co ctxt_prec (IfaceKindCo co)
= ppr_special_co ctxt_prec (text "Kind") [co]
ppr_special_co :: TyPrec -> SDoc -> [IfaceCoercion] -> SDoc
ppr_special_co ctxt_prec doc cos
= maybeParen ctxt_prec TyConPrec
(sep [doc, nest 4 (sep (map pprParendIfaceCoercion cos))])
ppr_role :: Role -> SDoc
ppr_role r = underscore <> pp_role
where pp_role = case r of
Nominal -> char 'N'
Representational -> char 'R'
Phantom -> char 'P'
-------------------
instance Outputable IfaceTyCon where
ppr tc = pprPromotionQuote tc <> ppr (ifaceTyConName tc)
pprPromotionQuote :: IfaceTyCon -> SDoc
pprPromotionQuote tc = pprPromotionQuoteI (ifaceTyConInfo tc)
pprPromotionQuoteI :: IfaceTyConInfo -> SDoc
pprPromotionQuoteI NoIfaceTyConInfo = empty
pprPromotionQuoteI IfacePromotedDataCon = char '\''
instance Outputable IfaceCoercion where
ppr = pprIfaceCoercion
instance Binary IfaceTyCon where
put_ bh (IfaceTyCon n i) = put_ bh n >> put_ bh i
get bh = do n <- get bh
i <- get bh
return (IfaceTyCon n i)
instance Binary IfaceTyConInfo where
put_ bh NoIfaceTyConInfo = putByte bh 0
put_ bh IfacePromotedDataCon = putByte bh 1
get bh =
do i <- getByte bh
case i of
0 -> return NoIfaceTyConInfo
_ -> return IfacePromotedDataCon
instance Outputable IfaceTyLit where
ppr = ppr_tylit
instance Binary IfaceTyLit where
put_ bh (IfaceNumTyLit n) = putByte bh 1 >> put_ bh n
put_ bh (IfaceStrTyLit n) = putByte bh 2 >> put_ bh n
get bh =
do tag <- getByte bh
case tag of
1 -> do { n <- get bh
; return (IfaceNumTyLit n) }
2 -> do { n <- get bh
; return (IfaceStrTyLit n) }
_ -> panic ("get IfaceTyLit " ++ show tag)
instance Binary IfaceForAllBndr where
put_ bh (IfaceTv tv vis) = do
put_ bh tv
put_ bh vis
get bh = do
tv <- get bh
vis <- get bh
return (IfaceTv tv vis)
instance Binary IfaceTyConBinder where
put_ bh (IfaceAnon n ty) = putByte bh 0 >> put_ bh n >> put_ bh ty
put_ bh (IfaceNamed b) = putByte bh 1 >> put_ bh b
get bh =
do c <- getByte bh
case c of
0 -> do
n <- get bh
ty <- get bh
return $! IfaceAnon n ty
_ -> do
b <- get bh
return $! IfaceNamed b
instance Binary IfaceTcArgs where
put_ bh tk =
case tk of
ITC_Vis t ts -> putByte bh 0 >> put_ bh t >> put_ bh ts
ITC_Invis t ts -> putByte bh 1 >> put_ bh t >> put_ bh ts
ITC_Nil -> putByte bh 2
get bh =
do c <- getByte bh
case c of
0 -> do
t <- get bh
ts <- get bh
return $! ITC_Vis t ts
1 -> do
t <- get bh
ts <- get bh
return $! ITC_Invis t ts
2 -> return ITC_Nil
_ -> panic ("get IfaceTcArgs " ++ show c)
-------------------
pprIfaceContextArr :: Outputable a => [a] -> SDoc
-- Prints "(C a, D b) =>", including the arrow
pprIfaceContextArr [] = empty
pprIfaceContextArr preds = pprIfaceContext preds <+> darrow
pprIfaceContext :: Outputable a => [a] -> SDoc
pprIfaceContext [] = parens empty
pprIfaceContext [pred] = ppr pred -- No parens
pprIfaceContext preds = parens (fsep (punctuate comma (map ppr preds)))
instance Binary IfaceType where
put_ bh (IfaceForAllTy aa ab) = do
putByte bh 0
put_ bh aa
put_ bh ab
put_ bh (IfaceTyVar ad) = do
putByte bh 1
put_ bh ad
put_ bh (IfaceAppTy ae af) = do
putByte bh 2
put_ bh ae
put_ bh af
put_ bh (IfaceFunTy ag ah) = do
putByte bh 3
put_ bh ag
put_ bh ah
put_ bh (IfaceDFunTy ag ah) = do
putByte bh 4
put_ bh ag
put_ bh ah
put_ bh (IfaceTyConApp tc tys)
= do { putByte bh 5; put_ bh tc; put_ bh tys }
put_ bh (IfaceCastTy a b)
= do { putByte bh 6; put_ bh a; put_ bh b }
put_ bh (IfaceCoercionTy a)
= do { putByte bh 7; put_ bh a }
put_ bh (IfaceTupleTy s i tys)
= do { putByte bh 8; put_ bh s; put_ bh i; put_ bh tys }
put_ bh (IfaceLitTy n)
= do { putByte bh 9; put_ bh n }
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
ab <- get bh
return (IfaceForAllTy aa ab)
1 -> do ad <- get bh
return (IfaceTyVar ad)
2 -> do ae <- get bh
af <- get bh
return (IfaceAppTy ae af)
3 -> do ag <- get bh
ah <- get bh
return (IfaceFunTy ag ah)
4 -> do ag <- get bh
ah <- get bh
return (IfaceDFunTy ag ah)
5 -> do { tc <- get bh; tys <- get bh
; return (IfaceTyConApp tc tys) }
6 -> do { a <- get bh; b <- get bh
; return (IfaceCastTy a b) }
7 -> do { a <- get bh
; return (IfaceCoercionTy a) }
8 -> do { s <- get bh; i <- get bh; tys <- get bh
; return (IfaceTupleTy s i tys) }
_ -> do n <- get bh
return (IfaceLitTy n)
instance Binary IfaceCoercion where
put_ bh (IfaceReflCo a b) = do
putByte bh 1
put_ bh a
put_ bh b
put_ bh (IfaceFunCo a b c) = do
putByte bh 2
put_ bh a
put_ bh b
put_ bh c
put_ bh (IfaceTyConAppCo a b c) = do
putByte bh 3
put_ bh a
put_ bh b
put_ bh c
put_ bh (IfaceAppCo a b) = do
putByte bh 4
put_ bh a
put_ bh b
put_ bh (IfaceForAllCo a b c) = do
putByte bh 5
put_ bh a
put_ bh b
put_ bh c
put_ bh (IfaceCoVarCo a) = do
putByte bh 6
put_ bh a
put_ bh (IfaceAxiomInstCo a b c) = do
putByte bh 7
put_ bh a
put_ bh b
put_ bh c
put_ bh (IfaceUnivCo a b c d) = do
putByte bh 8
put_ bh a
put_ bh b
put_ bh c
put_ bh d
put_ bh (IfaceSymCo a) = do
putByte bh 9
put_ bh a
put_ bh (IfaceTransCo a b) = do
putByte bh 10
put_ bh a
put_ bh b
put_ bh (IfaceNthCo a b) = do
putByte bh 11
put_ bh a
put_ bh b
put_ bh (IfaceLRCo a b) = do
putByte bh 12
put_ bh a
put_ bh b
put_ bh (IfaceInstCo a b) = do
putByte bh 13
put_ bh a
put_ bh b
put_ bh (IfaceCoherenceCo a b) = do
putByte bh 14
put_ bh a
put_ bh b
put_ bh (IfaceKindCo a) = do
putByte bh 15
put_ bh a
put_ bh (IfaceSubCo a) = do
putByte bh 16
put_ bh a
put_ bh (IfaceAxiomRuleCo a b) = do
putByte bh 17
put_ bh a
put_ bh b
get bh = do
tag <- getByte bh
case tag of
1 -> do a <- get bh
b <- get bh
return $ IfaceReflCo a b
2 -> do a <- get bh
b <- get bh
c <- get bh
return $ IfaceFunCo a b c
3 -> do a <- get bh
b <- get bh
c <- get bh
return $ IfaceTyConAppCo a b c
4 -> do a <- get bh
b <- get bh
return $ IfaceAppCo a b
5 -> do a <- get bh
b <- get bh
c <- get bh
return $ IfaceForAllCo a b c
6 -> do a <- get bh
return $ IfaceCoVarCo a
7 -> do a <- get bh
b <- get bh
c <- get bh
return $ IfaceAxiomInstCo a b c
8 -> do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return $ IfaceUnivCo a b c d
9 -> do a <- get bh
return $ IfaceSymCo a
10-> do a <- get bh
b <- get bh
return $ IfaceTransCo a b
11-> do a <- get bh
b <- get bh
return $ IfaceNthCo a b
12-> do a <- get bh
b <- get bh
return $ IfaceLRCo a b
13-> do a <- get bh
b <- get bh
return $ IfaceInstCo a b
14-> do a <- get bh
b <- get bh
return $ IfaceCoherenceCo a b
15-> do a <- get bh
return $ IfaceKindCo a
16-> do a <- get bh
return $ IfaceSubCo a
17-> do a <- get bh
b <- get bh
return $ IfaceAxiomRuleCo a b
_ -> panic ("get IfaceCoercion " ++ show tag)
instance Binary IfaceUnivCoProv where
put_ bh IfaceUnsafeCoerceProv = putByte bh 1
put_ bh (IfacePhantomProv a) = do
putByte bh 2
put_ bh a
put_ bh (IfaceProofIrrelProv a) = do
putByte bh 3
put_ bh a
put_ bh (IfacePluginProv a) = do
putByte bh 4
put_ bh a
get bh = do
tag <- getByte bh
case tag of
1 -> return $ IfaceUnsafeCoerceProv
2 -> do a <- get bh
return $ IfacePhantomProv a
3 -> do a <- get bh
return $ IfaceProofIrrelProv a
4 -> do a <- get bh
return $ IfacePluginProv a
_ -> panic ("get IfaceUnivCoProv " ++ show tag)
instance Binary (DefMethSpec IfaceType) where
put_ bh VanillaDM = putByte bh 0
put_ bh (GenericDM t) = putByte bh 1 >> put_ bh t
get bh = do
h <- getByte bh
case h of
0 -> return VanillaDM
_ -> do { t <- get bh; return (GenericDM t) }
{-
************************************************************************
* *
Conversion from Type to IfaceType
* *
************************************************************************
-}
----------------
toIfaceTvBndr :: TyVar -> (IfLclName, IfaceKind)
toIfaceTvBndr tyvar = ( occNameFS (getOccName tyvar)
, toIfaceKind (tyVarKind tyvar)
)
toIfaceIdBndr :: Id -> (IfLclName, IfaceType)
toIfaceIdBndr id = (occNameFS (getOccName id), toIfaceType (idType id))
toIfaceTvBndrs :: [TyVar] -> [IfaceTvBndr]
toIfaceTvBndrs = map toIfaceTvBndr
toIfaceBndr :: Var -> IfaceBndr
toIfaceBndr var
| isId var = IfaceIdBndr (toIfaceIdBndr var)
| otherwise = IfaceTvBndr (toIfaceTvBndr var)
toIfaceKind :: Type -> IfaceType
toIfaceKind = toIfaceType
---------------------
toIfaceType :: Type -> IfaceType
-- Synonyms are retained in the interface type
toIfaceType (TyVarTy tv) = IfaceTyVar (toIfaceTyVar tv)
toIfaceType (AppTy t1 t2) = IfaceAppTy (toIfaceType t1) (toIfaceType t2)
toIfaceType (LitTy n) = IfaceLitTy (toIfaceTyLit n)
toIfaceType (ForAllTy (Named tv vis) t)
= IfaceForAllTy (varToIfaceForAllBndr tv vis) (toIfaceType t)
toIfaceType (ForAllTy (Anon t1) t2)
| isPredTy t1 = IfaceDFunTy (toIfaceType t1) (toIfaceType t2)
| otherwise = IfaceFunTy (toIfaceType t1) (toIfaceType t2)
toIfaceType (CastTy ty co) = IfaceCastTy (toIfaceType ty) (toIfaceCoercion co)
toIfaceType (CoercionTy co) = IfaceCoercionTy (toIfaceCoercion co)
toIfaceType (TyConApp tc tys) -- Look for the two sorts of saturated tuple
| Just sort <- tyConTuple_maybe tc
, n_tys == arity
= IfaceTupleTy sort NoIfaceTyConInfo (toIfaceTcArgs tc tys)
| Just dc <- isPromotedDataCon_maybe tc
, isTupleDataCon dc
, n_tys == 2*arity
= IfaceTupleTy BoxedTuple IfacePromotedDataCon (toIfaceTcArgs tc (drop arity tys))
| otherwise
= IfaceTyConApp (toIfaceTyCon tc) (toIfaceTcArgs tc tys)
where
arity = tyConArity tc
n_tys = length tys
toIfaceTyVar :: TyVar -> FastString
toIfaceTyVar = occNameFS . getOccName
toIfaceCoVar :: CoVar -> FastString
toIfaceCoVar = occNameFS . getOccName
varToIfaceForAllBndr :: TyVar -> VisibilityFlag -> IfaceForAllBndr
varToIfaceForAllBndr v vis
= IfaceTv (toIfaceTvBndr v) vis
binderToIfaceForAllBndr :: TyBinder -> IfaceForAllBndr
binderToIfaceForAllBndr (Named v vis) = IfaceTv (toIfaceTvBndr v) vis
binderToIfaceForAllBndr binder
= pprPanic "binderToIfaceForAllBndr" (ppr binder)
----------------
toIfaceTyCon :: TyCon -> IfaceTyCon
toIfaceTyCon tc
= IfaceTyCon tc_name info
where
tc_name = tyConName tc
info | isPromotedDataCon tc = IfacePromotedDataCon
| otherwise = NoIfaceTyConInfo
toIfaceTyCon_name :: Name -> IfaceTyCon
toIfaceTyCon_name n = IfaceTyCon n NoIfaceTyConInfo
-- Used for the "rough-match" tycon stuff,
-- where pretty-printing is not an issue
toIfaceTyLit :: TyLit -> IfaceTyLit
toIfaceTyLit (NumTyLit x) = IfaceNumTyLit x
toIfaceTyLit (StrTyLit x) = IfaceStrTyLit x
----------------
toIfaceTypes :: [Type] -> [IfaceType]
toIfaceTypes ts = map toIfaceType ts
----------------
toIfaceContext :: ThetaType -> IfaceContext
toIfaceContext = toIfaceTypes
----------------
toIfaceCoercion :: Coercion -> IfaceCoercion
toIfaceCoercion (Refl r ty) = IfaceReflCo r (toIfaceType ty)
toIfaceCoercion (TyConAppCo r tc cos)
| tc `hasKey` funTyConKey
, [arg,res] <- cos = IfaceFunCo r (toIfaceCoercion arg) (toIfaceCoercion res)
| otherwise = IfaceTyConAppCo r (toIfaceTyCon tc)
(map toIfaceCoercion cos)
toIfaceCoercion (AppCo co1 co2) = IfaceAppCo (toIfaceCoercion co1)
(toIfaceCoercion co2)
toIfaceCoercion (ForAllCo tv k co) = IfaceForAllCo (toIfaceTvBndr tv)
(toIfaceCoercion k)
(toIfaceCoercion co)
toIfaceCoercion (CoVarCo cv) = IfaceCoVarCo (toIfaceCoVar cv)
toIfaceCoercion (AxiomInstCo con ind cos)
= IfaceAxiomInstCo (coAxiomName con) ind
(map toIfaceCoercion cos)
toIfaceCoercion (UnivCo p r t1 t2) = IfaceUnivCo (toIfaceUnivCoProv p) r
(toIfaceType t1)
(toIfaceType t2)
toIfaceCoercion (SymCo co) = IfaceSymCo (toIfaceCoercion co)
toIfaceCoercion (TransCo co1 co2) = IfaceTransCo (toIfaceCoercion co1)
(toIfaceCoercion co2)
toIfaceCoercion (NthCo d co) = IfaceNthCo d (toIfaceCoercion co)
toIfaceCoercion (LRCo lr co) = IfaceLRCo lr (toIfaceCoercion co)
toIfaceCoercion (InstCo co arg) = IfaceInstCo (toIfaceCoercion co)
(toIfaceCoercion arg)
toIfaceCoercion (CoherenceCo c1 c2) = IfaceCoherenceCo (toIfaceCoercion c1)
(toIfaceCoercion c2)
toIfaceCoercion (KindCo c) = IfaceKindCo (toIfaceCoercion c)
toIfaceCoercion (SubCo co) = IfaceSubCo (toIfaceCoercion co)
toIfaceCoercion (AxiomRuleCo co cs) = IfaceAxiomRuleCo (coaxrName co)
(map toIfaceCoercion cs)
toIfaceUnivCoProv :: UnivCoProvenance -> IfaceUnivCoProv
toIfaceUnivCoProv UnsafeCoerceProv = IfaceUnsafeCoerceProv
toIfaceUnivCoProv (PhantomProv co) = IfacePhantomProv (toIfaceCoercion co)
toIfaceUnivCoProv (ProofIrrelProv co) = IfaceProofIrrelProv (toIfaceCoercion co)
toIfaceUnivCoProv (PluginProv str) = IfacePluginProv str
toIfaceUnivCoProv (HoleProv h) = pprPanic "toIfaceUnivCoProv hit a hole" (ppr h)
----------------------
-- | Zip together tidied tyConTyVars with tyConBinders to make IfaceTyConBinders
zipIfaceBinders :: [TyVar] -> [TyBinder] -> [IfaceTyConBinder]
zipIfaceBinders = zipWith go
where
go tv (Anon _) = let (name, ki) = toIfaceTvBndr tv in
IfaceAnon name ki
go tv (Named _ vis) = IfaceNamed (IfaceTv (toIfaceTvBndr tv) vis)
-- | Make IfaceTyConBinders without tyConTyVars. Used for pretty-printing only
toDegenerateBinders :: [TyBinder] -> [IfaceTyConBinder]
toDegenerateBinders = zipWith go [1..]
where
go :: Int -> TyBinder -> IfaceTyConBinder
go n (Anon ty) = IfaceAnon (mkFastString ("t" ++ show n)) (toIfaceType ty)
go _ (Named tv vis) = IfaceNamed (IfaceTv (toIfaceTvBndr tv) vis)
| GaloisInc/halvm-ghc | compiler/iface/IfaceType.hs | bsd-3-clause | 53,130 | 0 | 17 | 15,692 | 15,042 | 7,430 | 7,612 | 1,061 | 29 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.TextureEnvCrossbar
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All tokens from the ARB_texture_env_crossbar extension, see
-- <http://www.opengl.org/registry/specs/ARB/texture_env_crossbar.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.TextureEnvCrossbar (
-- * Tokens
gl_TEXTURE0,
gl_TEXTURE1,
gl_TEXTURE10,
gl_TEXTURE11,
gl_TEXTURE12,
gl_TEXTURE13,
gl_TEXTURE14,
gl_TEXTURE15,
gl_TEXTURE16,
gl_TEXTURE17,
gl_TEXTURE18,
gl_TEXTURE19,
gl_TEXTURE2,
gl_TEXTURE20,
gl_TEXTURE21,
gl_TEXTURE22,
gl_TEXTURE23,
gl_TEXTURE24,
gl_TEXTURE25,
gl_TEXTURE26,
gl_TEXTURE27,
gl_TEXTURE28,
gl_TEXTURE29,
gl_TEXTURE3,
gl_TEXTURE30,
gl_TEXTURE31,
gl_TEXTURE4,
gl_TEXTURE5,
gl_TEXTURE6,
gl_TEXTURE7,
gl_TEXTURE8,
gl_TEXTURE9
) where
import Graphics.Rendering.OpenGL.Raw.Core32
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/TextureEnvCrossbar.hs | bsd-3-clause | 1,210 | 0 | 4 | 209 | 131 | 94 | 37 | 34 | 0 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE DataKinds #-}
module Data.Net.Recurrent where
import Control.Applicative
import Data.Net
import Data.Net.FullyConnected
import Data.Vector.Fixed
import Data.Vector.Fixed.Size
import Control.Monad.State
import Prelude hiding (sum)
lstm' :: (Num a) => Net (Vector (N 2)) a (Vector (N 4) a -> State a a)
lstm' = (\summer [x, g1, g2, g3] ->
let p1 = x * g1
in do
p2 <- (g2*) <$> get
put (summer [p1, p2])
(g3*) <$> get)
<$> sumNeuron
unfoldM :: (Functor m, Monad m) => (a -> m a) -> Int -> a -> m [a]
unfoldM f = go
where go 0 _ = return []
go n x = do
x' <- f x
(x:) <$> go (n-1) x'
unfoldForever :: (Functor m, Monad m) => (a -> m a) -> a -> m [a]
unfoldForever f = go
where go x = do
x' <- f x
(x:) <$> go x'
unrollState :: (a -> State s a) -> a -> State s [(a, s)]
unrollState f = go
where go x = do
t <- (,) <$> f x <*> get
(t:) <$> go (fst t)
unrollStateN :: (a -> State s a) -> Int -> a -> State s [(a, s)]
unrollStateN f = go
where go 0 _ = return []
go n x = do
t <- (,) <$> f x <*> get
(t:) <$> go (n-1) (fst t)
| Apsod/fixed | Data/Net/Recurrent.hs | bsd-3-clause | 1,282 | 0 | 15 | 424 | 628 | 330 | 298 | 41 | 2 |
{-|
Module : Control.Flag
Description : Defines flags and option descriptions.
Copyright : (c) Andrew Michaud, 2015
License : BSD3
Maintainer : andrewjmichaud@gmail.com
Stability : experimental
This module describes the flags permitted for the Sudoku application. The flags exist as a data
type, and descriptions and long and short option flags are provided as well.
-}
module Sudoku.Control.Flag (
-- * Classes
Flag(..)
-- * Option Descriptions
, options
) where
import System.Console.GetOpt
-- | Datatype for command-line flags.
data Flag = Graphical -- ^ Enable graphical mode - --graphical, -g
| Help -- ^ Show help - --help, -h
| Version -- ^ Show version information - version, -V
| File String -- ^ Provide a file to load from - --file, -f
deriving (Eq, Ord, Show)
-- | Describe all allowed command-line options.
options :: [OptDescr Flag]
options = [ Option "g" ["graphical"] (NoArg Graphical)
"Start the graphical interface."
, Option "f" ["file"] (ReqArg File "File")
"Provide a file to load a Sudoku board from."
, Option "V" ["version"] (NoArg Version)
"Print out version information."
, Option "h" ["help"] (NoArg Help)
"Print this help message."
]
| andrewmichaud/JustSudoku | src/Sudoku/Control/Flag.hs | bsd-3-clause | 1,343 | 0 | 8 | 369 | 169 | 99 | 70 | 18 | 1 |
{-# LANGUAGE CPP, RecursiveDo #-}
module Text.Earley.Mixfix where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Data.Either
import Data.Foldable(asum, foldrM)
import Text.Earley
data Associativity
= LeftAssoc
| NonAssoc
| RightAssoc
deriving (Eq, Show)
-- | An identifier with identifier parts ('Just's), and holes ('Nothing's)
-- representing the positions of its arguments.
--
-- Example (commonly written "if_then_else_"):
-- @['Just' "if", 'Nothing', 'Just' "then", 'Nothing', 'Just' "else", 'Nothing'] :: 'Holey' 'String'@
type Holey a = [Maybe a]
-- | Create a grammar for parsing mixfix expressions.
mixfixExpression
:: [[(Holey (Prod r e t ident), Associativity)]]
-- ^ A table of holey identifier parsers, with associativity information.
-- The identifiers should be in groups of precedence levels listed from
-- binding the least to the most tightly.
--
-- The associativity is taken into account when an identifier starts or
-- ends with a hole, or both. Internal holes (e.g. after "if" in
-- "if_then_else_") start from the beginning of the table.
-> Prod r e t expr
-- ^ An atom, i.e. what is parsed at the lowest level. This will
-- commonly be a (non-mixfix) identifier or a parenthesised expression.
-> (Holey ident -> [expr] -> expr)
-- ^ How to combine the successful application of a holey identifier to its
-- arguments into an expression.
-> Grammar r e (Prod r e t expr)
mixfixExpression table atom app = mdo
expr <- foldrM ($) atom $ map (level expr) table
return expr
where
app' xs = app (either (const Nothing) Just <$> xs) $ lefts xs
level expr idents next = mdo
same <- rule $ asum $ next : map (mixfixIdent same) idents
return same
where
cons p q = (:) <$> p <*> q
mixfixIdent same (ps, a) = app' <$> go ps
where
go ps' = case ps' of
[] -> pure []
[Just p] -> pure . Right <$> p
Nothing:rest -> cons (Left <$> if a == RightAssoc then next
else same)
$ go rest
[Just p, Nothing] -> cons (Right <$> p)
$ pure . Left <$> if a == LeftAssoc then next else same
Just p:Nothing:rest -> cons (Right <$> p)
$ cons (Left <$> expr)
$ go rest
Just p:rest@(Just _:_) -> cons (Right <$> p) $ go rest
| Axure/Earley | Text/Earley/Mixfix.hs | bsd-3-clause | 2,463 | 0 | 19 | 701 | 585 | 309 | 276 | 38 | 8 |
{-# LANGUAGE GADTs,FlexibleInstances,UndecidableInstances #-}
module Data.Interface.Sequence where
import Data.Monoid
import Data.Foldable
import Data.Traversable
import Control.Applicative hiding (empty)
import Prelude hiding (foldr,foldl)
class Sequence s where
empty :: s a
singleton :: a -> s a
(.><) :: s a -> s a -> s a
viewl :: s a -> ViewL s a
viewr :: s a -> ViewR s a
(.|>) :: s a -> a -> s a
(.<|) :: a -> s a -> s a
l .|> r = l .>< singleton r
l .<| r = singleton l .>< r
l .>< r = case viewl l of
EmptyL -> r
h :< t -> h .<| (t .>< r)
viewl q = case viewr q of
EmptyR -> EmptyL
p :> l -> case viewl p of
EmptyL -> l :< empty
h :< t -> h :< (t .|> l)
viewr q = case viewl q of
EmptyL -> EmptyR
h :< t -> case viewr t of
EmptyR -> empty :> h
p :> l -> (h .<| p) :> l
data ViewL s a where
EmptyL :: ViewL s a
(:<) :: a -> s a -> ViewL s a
data ViewR s a where
EmptyR :: ViewR s a
(:>) :: s a -> a -> ViewR s a
| feuerbach/freemonad-benchmark | Data/Interface/Sequence.hs | mit | 1,065 | 0 | 15 | 364 | 472 | 244 | 228 | 36 | 0 |
{-# LANGUAGE MultiParamTypeClasses, UndecidableInstances, FlexibleInstances
, TypeSynonymInstances #-}
{- |
Module : ./Modifications/ModalEmbedding.hs
Copyright : (c) Mihai Codescu, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Mihai.Codescu@dfki.de
Stability : experimental
Portability : non-portable (Logic)
institution modification
-}
{-
CASL -------------------------id------------------> CASL
CASL ---CASL2Modal----> ModalCASL --Modal2CASL----> CASL
-}
module Modifications.ModalEmbedding where
import Logic.Modification
import Logic.Logic
import Logic.Comorphism
import Comorphisms.CASL2Modal
import Comorphisms.Modal2CASL
import CASL.Logic_CASL
import CASL.Sign
import CASL.Morphism
import CASL.AS_Basic_CASL
import CASL.Sublogic as SL
import Common.ProofTree
data MODAL_EMBEDDING = MODAL_EMBEDDING deriving Show
instance Language MODAL_EMBEDDING
instance Modification MODAL_EMBEDDING (InclComorphism CASL CASL_Sublogics)
(CompComorphism CASL2Modal Modal2CASL)
CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree
CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree
CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree
CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree
where
sourceComorphism MODAL_EMBEDDING = mkIdComorphism CASL (top_sublogic CASL)
targetComorphism MODAL_EMBEDDING = CompComorphism CASL2Modal Modal2CASL
tauSigma MODAL_EMBEDDING sigma = do
(sigma1, _ ) <- wrapMapTheory CASL2Modal (sigma, [])
(sigma2, _ ) <- wrapMapTheory Modal2CASL (sigma1, [])
return (embedMorphism () sigma sigma2)
| spechub/Hets | Modifications/ModalEmbedding.hs | gpl-2.0 | 2,027 | 0 | 11 | 409 | 311 | 165 | 146 | 44 | 0 |
-- C -> Haskell Compiler: Lexer for C Header Files
--
-- Author : Manuel M T Chakravarty, Duncan Coutts
-- Created: 12 Febuary 2007
--
-- Copyright (c) [1999..2004] Manuel M T Chakravarty
-- Copyright (c) 2005-2007 Duncan Coutts
--
-- This file 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 file 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.
--
--- DESCRIPTION ---------------------------------------------------------------
--
-- Monad for the C lexer and parser
--
--- DOCU ----------------------------------------------------------------------
--
-- language: Haskell 98
--
-- This monad has to be usable with Alex and Happy. Some things in it are
-- dictated by that, eg having to be able to remember the last token.
--
-- The monad also provides a unique name supply (via the Names module)
--
-- For parsing C we have to maintain a set of identifiers that we know to be
-- typedef'ed type identifiers. We also must deal correctly with scope so we
-- keep a list of sets of identifiers so we can save the outer scope when we
-- enter an inner scope.
--
--- TODO ----------------------------------------------------------------------
--
--
module CParserMonad (
P,
execParser,
failP,
getNewName, -- :: P Name
addTypedef, -- :: Ident -> P ()
shadowTypedef, -- :: Ident -> P ()
isTypeIdent, -- :: Ident -> P Bool
enterScope, -- :: P ()
leaveScope, -- :: P ()
setPos, -- :: Position -> P ()
getPos, -- :: P Position
getInput, -- :: P String
setInput, -- :: String -> P ()
getLastToken, -- :: P CToken
setLastToken, -- :: CToken -> P ()
) where
import Position (Position(..), Pos(posOf))
import Errors (interr)
import UNames (Name)
import Idents (Ident, lexemeToIdent, identToLexeme)
import Control.Applicative (Applicative(..))
import Control.Monad (liftM, ap)
import Data.Set (Set)
import qualified Data.Set as Set (fromList, insert, member, delete)
import CTokens (CToken)
data ParseResult a
= POk !PState a
| PFailed [String] Position -- The error message and position
data PState = PState {
curPos :: !Position, -- position at current input location
curInput :: !String, -- the current input
prevToken :: CToken, -- the previous token
namesupply :: ![Name], -- the name unique supply
tyidents :: !(Set Ident), -- the set of typedef'ed identifiers
scopes :: ![Set Ident] -- the tyident sets for outer scopes
}
newtype P a = P { unP :: PState -> ParseResult a }
instance Functor P where
fmap = liftM
instance Applicative P where
pure = return
(<*>) = ap
instance Monad P where
return = returnP
(>>=) = thenP
fail m = getPos >>= \pos -> failP pos [m]
execParser :: P a -> String -> Position -> [Ident] -> [Name]
-> Either a ([String], Position)
execParser (P parser) input pos builtins names =
case parser initialState of
POk _ result -> Left result
PFailed message pos -> Right (message, pos)
where initialState = PState {
curPos = pos,
curInput = input,
prevToken = interr "CLexer.execParser: Touched undefined token!",
namesupply = names,
tyidents = Set.fromList builtins,
scopes = []
}
{-# INLINE returnP #-}
returnP :: a -> P a
returnP a = P $ \s -> POk s a
{-# INLINE thenP #-}
thenP :: P a -> (a -> P b) -> P b
(P m) `thenP` k = P $ \s ->
case m s of
POk s' a -> (unP (k a)) s'
PFailed err pos -> PFailed err pos
failP :: Position -> [String] -> P a
failP pos msg = P $ \_ -> PFailed msg pos
getNewName :: P Name
getNewName = P $ \s@PState{namesupply=(n:ns)} -> POk s{namesupply=ns} n
setPos :: Position -> P ()
setPos pos = P $ \s -> POk s{curPos=pos} ()
getPos :: P Position
getPos = P $ \s@PState{curPos=pos} -> POk s pos
addTypedef :: Ident -> P ()
addTypedef ident = (P $ \s@PState{tyidents=tyidents} ->
POk s{tyidents = ident `Set.insert` tyidents} ())
shadowTypedef :: Ident -> P ()
shadowTypedef ident = (P $ \s@PState{tyidents=tyidents} ->
-- optimisation: mostly the ident will not be in
-- the tyident set so do a member lookup to avoid
-- churn induced by calling delete
POk s{tyidents = if ident `Set.member` tyidents
then ident `Set.delete` tyidents
else tyidents } ())
isTypeIdent :: Ident -> P Bool
isTypeIdent ident = P $ \s@PState{tyidents=tyidents} ->
POk s $! Set.member ident tyidents
enterScope :: P ()
enterScope = P $ \s@PState{tyidents=tyidents,scopes=ss} ->
POk s{scopes=tyidents:ss} ()
leaveScope :: P ()
leaveScope = P $ \s@PState{scopes=ss} ->
case ss of
[] -> interr "leaveScope: already in global scope"
(tyidents:ss') -> POk s{tyidents=tyidents, scopes=ss'} ()
getInput :: P String
getInput = P $ \s@PState{curInput=i} -> POk s i
setInput :: String -> P ()
setInput i = P $ \s -> POk s{curInput=i} ()
getLastToken :: P CToken
getLastToken = P $ \s@PState{prevToken=tok} -> POk s tok
setLastToken :: CToken -> P ()
setLastToken tok = P $ \s -> POk s{prevToken=tok} ()
| mimi1vx/gtk2hs | tools/c2hs/c/CParserMonad.hs | gpl-3.0 | 5,913 | 0 | 14 | 1,706 | 1,431 | 818 | 613 | 114 | 2 |
module Workshop.RandomnessSpec(spec) where
import Workshop.Randomness
import Test.Hspec
spec :: Spec
spec = do
-- Not really big
describe "'Big data' support" $ do
-- sum of all age fields in the list
it "computes total age" $ do
total [personOfAge 10] `shouldBe` 10
--total [personOfAge x | x <- [0..20]] `shouldBe` 210
total (map personOfAge [0..20]) `shouldBe` 210
-- average age
it "computes average age" $ do
average (map personOfAge [0..20]) `shouldBe` 10
-- partition into young and old
it "partitions people" $ do
let (old, young) = ages (map personOfAge [40..60])
length old `shouldBe` 10
length young `shouldBe` 11
-- the random Person generator
describe "Random generator" $ do
-- the ages are 0..100, over enough records, the average should be ~50
it "generates good distribution of ages" $ do
ps <- people
average ps `shouldSatisfy` (< 2) . abs . (50 -)
where
personOfAge = Person "a" "b" | eigengo/scala-launchpad | haskell/test/Workshop/RandomnessSpec.hs | apache-2.0 | 1,060 | 0 | 19 | 308 | 269 | 138 | 131 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.QSemN
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (concurrency)
--
-- Quantity semaphores in which each thread may wait for an arbitrary
-- \"amount\".
--
-----------------------------------------------------------------------------
module Control.Concurrent.QSemN
( -- * General Quantity Semaphores
QSemN, -- abstract
newQSemN, -- :: Int -> IO QSemN
waitQSemN, -- :: QSemN -> Int -> IO ()
signalQSemN -- :: QSemN -> Int -> IO ()
) where
import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar
, tryPutMVar, isEmptyMVar)
import Control.Exception
import Control.Monad (when)
import Data.IORef (IORef, newIORef, atomicModifyIORef)
import System.IO.Unsafe (unsafePerformIO)
-- | 'QSemN' is a quantity semaphore in which the resource is acquired
-- and released in units of one. It provides guaranteed FIFO ordering
-- for satisfying blocked `waitQSemN` calls.
--
-- The pattern
--
-- > bracket_ (waitQSemN n) (signalQSemN n) (...)
--
-- is safe; it never loses any of the resource.
--
data QSemN = QSemN !(IORef (Int, [(Int, MVar ())], [(Int, MVar ())]))
-- The semaphore state (i, xs, ys):
--
-- i is the current resource value
--
-- (xs,ys) is the queue of blocked threads, where the queue is
-- given by xs ++ reverse ys. We can enqueue new blocked threads
-- by consing onto ys, and dequeue by removing from the head of xs.
--
-- A blocked thread is represented by an empty (MVar ()). To unblock
-- the thread, we put () into the MVar.
--
-- A thread can dequeue itself by also putting () into the MVar, which
-- it must do if it receives an exception while blocked in waitQSemN.
-- This means that when unblocking a thread in signalQSemN we must
-- first check whether the MVar is already full.
-- |Build a new 'QSemN' with a supplied initial quantity.
-- The initial quantity must be at least 0.
newQSemN :: Int -> IO QSemN
newQSemN initial
| initial < 0 = fail "newQSemN: Initial quantity must be non-negative"
| otherwise = do
sem <- newIORef (initial, [], [])
return (QSemN sem)
-- An unboxed version of Maybe (MVar a)
data MaybeMV a = JustMV !(MVar a) | NothingMV
-- |Wait for the specified quantity to become available
waitQSemN :: QSemN -> Int -> IO ()
-- We need to mask here. Once we've enqueued our MVar, we need
-- to be sure to wait for it. Otherwise, we could lose our
-- allocated resource.
waitQSemN qs@(QSemN m) sz = mask_ $ do
-- unsafePerformIO and not unsafeDupablePerformIO. We must
-- be sure to wait on the same MVar that gets enqueued.
mmvar <- atomicModifyIORef m $ \ (i,b1,b2) -> unsafePerformIO $ do
let z = i-sz
if z < 0
then do
b <- newEmptyMVar
return ((i, b1, (sz,b):b2), JustMV b)
else return ((z, b1, b2), NothingMV)
-- Note: this case match actually allocates the MVar if necessary.
case mmvar of
NothingMV -> return ()
JustMV b -> wait b
where
wait :: MVar () -> IO ()
wait b = do
takeMVar b `onException` do
already_filled <- not <$> tryPutMVar b ()
when already_filled $ signalQSemN qs sz
-- |Signal that a given quantity is now available from the 'QSemN'.
signalQSemN :: QSemN -> Int -> IO ()
-- We don't need to mask here because we should *already* be masked
-- here (e.g., by bracket). Indeed, if we're not already masked,
-- it's too late to do so.
--
-- What if the unsafePerformIO thunk is forced in another thread,
-- and receives an asynchronous exception? That shouldn't be a
-- problem: when we force it ourselves, presumably masked, we
-- will resume its execution.
signalQSemN (QSemN m) sz0 = do
-- unsafePerformIO and not unsafeDupablePerformIO. We must not
-- wake up more threads than we're supposed to.
unit <- atomicModifyIORef m $ \(i,a1,a2) ->
unsafePerformIO (loop (sz0 + i) a1 a2)
-- Forcing this will actually wake the necessary threads.
evaluate unit
where
loop 0 bs b2 = return ((0, bs, b2), ())
loop sz [] [] = return ((sz, [], []), ())
loop sz [] b2 = loop sz (reverse b2) []
loop sz ((j,b):bs) b2
| j > sz = do
r <- isEmptyMVar b
if r then return ((sz, (j,b):bs, b2), ())
else loop sz bs b2
| otherwise = do
r <- tryPutMVar b ()
if r then loop (sz-j) bs b2
else loop sz bs b2
| sdiehl/ghc | libraries/base/Control/Concurrent/QSemN.hs | bsd-3-clause | 4,800 | 0 | 21 | 1,138 | 908 | 507 | 401 | 61 | 6 |
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding (break)
import Control.Category ((>>>))
import qualified Data.Text as T
import Data.Char
import Data.List hiding (lines, unlines, break)
import Data.Maybe
import qualified Data.Map as Map
import Data.Ord
import Data.Tuple
import HSL.Json
import HSL.Stdlib
import HSL.IO
import HSL.Types
%s
p = %s
main = runLineProcessor p
| libscott/hawk | src/Main.hs | bsd-3-clause | 498 | 2 | 5 | 169 | 116 | 72 | 44 | -1 | -1 |
module Main (
main
) where
import qualified Data.Set as Set
import Development.Abba
import System.Environment
import Text.Printf
main = do
let
cxxFlags = ["-std=c++0x"]
rules = Set.fromList
[ Rule ["all"] ["foo"] Nothing
, Rule ["clean"] [] $ Just $ \_ _ -> do
clean "foo"
clean "foo.o"
clean "main.o"
, Rule ["foo"] ["main.o", "foo.o"] $ Just
$ buildCxxExecutable cxxFlags
, Rule ["foo.o"] ["foo.cxx"] $ Just
$ buildCxxObject cxxFlags
, Rule ["main.o"] ["main.cxx"] $ Just
$ buildCxxObject cxxFlags
]
dependencyGraph
= constructDependencyGraph rules
initialTargets <- getArgs
buildTargets rules dependencyGraph initialTargets
where
buildCxxExecutable cxxFlags targets dependencies
= shell "g++"
$ [ "-o", targets !! 0
]
++ cxxFlags
++ dependencies
buildCxxObject cxxFlags targets dependencies
= shell "g++"
$ [ "-c"
, "-o", targets !! 0
]
++ cxxFlags
++ dependencies
| mgeorgehansen/Abba | tests/make-simple/Buildscript.hs | bsd-3-clause | 1,246 | 0 | 16 | 506 | 303 | 158 | 145 | 36 | 1 |
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Stack.CCS
-- Copyright : (c) The University of Glasgow 2011
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Access to GHC's call-stack simulation
--
-- @since 4.5.0.0
-----------------------------------------------------------------------------
{-# LANGUAGE UnboxedTuples, MagicHash, NoImplicitPrelude #-}
module GHC.Stack.CCS (
-- * Call stacks
currentCallStack,
whoCreated,
-- * Internals
CostCentreStack,
CostCentre,
getCurrentCCS,
getCCSOf,
clearCCS,
ccsCC,
ccsParent,
ccLabel,
ccModule,
ccSrcSpan,
ccsToStrings,
renderStack
) where
import Foreign
import Foreign.C
import GHC.Base
import GHC.Ptr
import GHC.Foreign as GHC
import GHC.IO.Encoding
import GHC.List ( concatMap, reverse )
-- | A cost-centre stack from GHC's cost-center profiler.
data CostCentreStack
-- | A cost-centre from GHC's cost-center profiler.
data CostCentre
-- | Returns the current 'CostCentreStack' (value is @nullPtr@ if the current
-- program was not compiled with profiling support). Takes a dummy argument
-- which can be used to avoid the call to @getCurrentCCS@ being floated out by
-- the simplifier, which would result in an uninformative stack ("CAF").
getCurrentCCS :: dummy -> IO (Ptr CostCentreStack)
getCurrentCCS _dummy = errorWithoutStackTrace "getCurrentCCS not handled!"
-- IO $ \s ->
-- case getCurrentCCS## dummy s of
-- (## s', addr ##) -> (## s', Ptr addr ##)
-- | Get the 'CostCentreStack' associated with the given value.
getCCSOf :: a -> IO (Ptr CostCentreStack)
getCCSOf obj = errorWithoutStackTrace "getCCSOf not handled!"
-- IO $ \s ->
-- case getCCSOf## obj s of
-- (## s', addr ##) -> (## s', Ptr addr ##)
-- | Run a computation with an empty cost-center stack. For example, this is
-- used by the interpreter to run an interpreted computation without the call
-- stack showing that it was invoked from GHC.
clearCCS :: IO a -> IO a
clearCCS (IO m) = errorWithoutStackTrace "clearCCS not handled!"
-- IO $ \s -> clearCCS## m s
-- | Get the 'CostCentre' at the head of a 'CostCentreStack'.
ccsCC :: Ptr CostCentreStack -> IO (Ptr CostCentre)
ccsCC p = errorWithoutStackTrace "ccsCC not handled!"
-- (# peek CostCentreStack, cc) p
-- | Get the tail of a 'CostCentreStack'.
ccsParent :: Ptr CostCentreStack -> IO (Ptr CostCentreStack)
ccsParent p = errorWithoutStackTrace "ccsParent not handled!"
-- (# peek CostCentreStack, prevStack) p
-- | Get the label of a 'CostCentre'.
ccLabel :: Ptr CostCentre -> IO CString
ccLabel p = errorWithoutStackTrace "ccLabel not handled!"
-- (# peek CostCentre, label) p
-- | Get the module of a 'CostCentre'.
ccModule :: Ptr CostCentre -> IO CString
ccModule p = errorWithoutStackTrace "ccModule not handled!"
-- (# peek CostCentre, module) p
-- | Get the source span of a 'CostCentre'.
ccSrcSpan :: Ptr CostCentre -> IO CString
ccSrcSpan p = errorWithoutStackTrace "ccSrcSpan not handled!"
-- (# peek CostCentre, srcloc) p
-- | Returns a @[String]@ representing the current call stack. This
-- can be useful for debugging.
--
-- The implementation uses the call-stack simulation maintained by the
-- profiler, so it only works if the program was compiled with @-prof@
-- and contains suitable SCC annotations (e.g. by using @-fprof-auto@).
-- Otherwise, the list returned is likely to be empty or
-- uninformative.
--
-- @since 4.5.0.0
currentCallStack :: IO [String]
currentCallStack = ccsToStrings =<< getCurrentCCS ()
-- | Format a 'CostCentreStack' as a list of lines.
ccsToStrings :: Ptr CostCentreStack -> IO [String]
ccsToStrings ccs0 = go ccs0 []
where
go ccs acc
| ccs == nullPtr = return acc
| otherwise = do
cc <- ccsCC ccs
lbl <- GHC.peekCString utf8 =<< ccLabel cc
mdl <- GHC.peekCString utf8 =<< ccModule cc
loc <- GHC.peekCString utf8 =<< ccSrcSpan cc
parent <- ccsParent ccs
if (mdl == "MAIN" && lbl == "MAIN")
then return acc
else go parent ((mdl ++ '.':lbl ++ ' ':'(':loc ++ ")") : acc)
-- | Get the stack trace attached to an object.
--
-- @since 4.5.0.0
whoCreated :: a -> IO [String]
whoCreated obj = do
ccs <- getCCSOf obj
ccsToStrings ccs
renderStack :: [String] -> String
renderStack strs =
"CallStack (from -prof):" ++ concatMap ("\n "++) (reverse strs)
| rahulmutt/ghcvm | libraries/base/GHC/Stack/CCS.hs | bsd-3-clause | 4,589 | 0 | 20 | 910 | 707 | 384 | 323 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, TypeFamilies, PolyKinds, TypeApplications, TypeFamilyDependencies #-}
module ClosedFam2 where
import Language.Haskell.TH
$( return [ ClosedTypeFamilyD
(TypeFamilyHead
(mkName "Equals")
[ KindedTV (mkName "a") (VarT (mkName "k"))
, KindedTV (mkName "b") (VarT (mkName "k")) ]
( TyVarSig (KindedTV (mkName "r") (VarT (mkName "k"))))
Nothing)
[ TySynEqn Nothing
(AppT (AppT (ConT (mkName "Equals")) (VarT (mkName "a")))
(VarT (mkName "a")))
(ConT (mkName "Int"))
, TySynEqn Nothing
(AppT (AppT (ConT (mkName "Equals")) (VarT (mkName "a")))
(VarT (mkName "b")))
(ConT (mkName "Bool")) ] ])
a :: Equals b b
a = (5 :: Int)
b :: Equals Int Bool
b = False
$( return [ ClosedTypeFamilyD
(TypeFamilyHead
(mkName "Foo")
[ KindedTV (mkName "a") (VarT (mkName "k"))]
(KindSig StarT ) Nothing )
[ TySynEqn Nothing
(AppT (AppKindT (ConT (mkName "Foo")) StarT)
(VarT (mkName "a")))
(ConT (mkName "Int"))
, TySynEqn Nothing
(AppT (AppKindT (ConT (mkName "Foo")) (AppT (AppT ArrowT StarT) (StarT)))
(VarT (mkName "a")))
(ConT (mkName "Bool")) ] ])
c :: Foo Int
c = 5
d :: Foo Bool
d = 6
e :: Foo Maybe
e = False
| sdiehl/ghc | testsuite/tests/th/ClosedFam2TH.hs | bsd-3-clause | 1,685 | 0 | 19 | 735 | 565 | 287 | 278 | 41 | 1 |
import System.Console.CmdTheLine
import Control.Applicative
import System.Directory ( copyFile
, doesDirectoryExist
)
import System.FilePath ( takeFileName
, pathSeparator
, hasTrailingPathSeparator
)
import System.IO
import System.Exit ( exitFailure )
sep = [pathSeparator]
cp :: Bool -> [String] -> String -> IO ()
cp dry sources dest =
chooseTactic =<< doesDirectoryExist dest
where
chooseTactic isDir
| singleFile = singleCopy $ head sources
| not isDir = notDirErr
| otherwise = mapM_ copyToDir sources
where
singleCopy = if isDir then copyToDir else copyToFile
singleFile = length sources == 1
notDirErr = do
hPutStrLn stderr "cp: DEST is not a directory and SOURCES is of length >1."
exitFailure
copyToDir filePath = if dry
then putStrLn $ concat [ "cp: copying ", filePath, " to ", dest' ]
else copyFile filePath dest'
where
dest' = withTrailingSep ++ takeFileName filePath
withTrailingSep =
if hasTrailingPathSeparator dest then dest else dest ++ sep
copyToFile filePath = if dry
then putStrLn $ concat [ "cp: copying ", filePath, " to ", dest ]
else copyFile filePath dest
-- An example of using the 'rev' and 'Left' variants of 'pos', as well as
-- validating file paths.
cpTerm = cp <$> dry <*> filesExist sources <*> validPath dest
where
dry = value $ flag (optInfo [ "dry", "d" ])
{ optName = "DRY"
, optDoc = "Perform a dry run. Print what would be copied, but do not "
++ "copy it."
}
sources = nonEmpty $ revPosLeft 0 [] posInfo
{ posName = "SOURCES"
, posDoc = "Source file(s) to copy."
}
dest = required $ revPos 0 Nothing posInfo
{ posName = "DEST"
, posDoc = "Destination of the copy. Must be a directory if there "
++ "is more than one $(i,SOURCE)."
}
termInfo = defTI
{ termName = "cp"
, version = "v1.0"
, termDoc = "Copy files from SOURCES to DEST."
, man = [ S "BUGS"
, P "Email bug reports to <portManTwo@example.com>"
]
}
main = run ( cpTerm, termInfo )
| glutamate/cmdtheline | doc/examples/cp.hs | mit | 2,279 | 0 | 12 | 724 | 506 | 275 | 231 | 50 | 5 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudSearch.DescribeAnalysisSchemes
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Gets the analysis schemes configured for a domain. An analysis scheme defines
-- language-specific text processing options for a 'text' field. Can be limited to
-- specific analysis schemes by name. By default, shows all analysis schemes and
-- includes any pending changes to the configuration. Set the 'Deployed' option to 'true' to show the active configuration and exclude pending changes. For more
-- information, see Configuring Analysis Schemes in the /Amazon CloudSearchDeveloper Guide/.
--
-- <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_DescribeAnalysisSchemes.html>
module Network.AWS.CloudSearch.DescribeAnalysisSchemes
(
-- * Request
DescribeAnalysisSchemes
-- ** Request constructor
, describeAnalysisSchemes
-- ** Request lenses
, das1AnalysisSchemeNames
, das1Deployed
, das1DomainName
-- * Response
, DescribeAnalysisSchemesResponse
-- ** Response constructor
, describeAnalysisSchemesResponse
-- ** Response lenses
, dasrAnalysisSchemes
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.CloudSearch.Types
import qualified GHC.Exts
data DescribeAnalysisSchemes = DescribeAnalysisSchemes
{ _das1AnalysisSchemeNames :: List "member" Text
, _das1Deployed :: Maybe Bool
, _das1DomainName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeAnalysisSchemes' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'das1AnalysisSchemeNames' @::@ ['Text']
--
-- * 'das1Deployed' @::@ 'Maybe' 'Bool'
--
-- * 'das1DomainName' @::@ 'Text'
--
describeAnalysisSchemes :: Text -- ^ 'das1DomainName'
-> DescribeAnalysisSchemes
describeAnalysisSchemes p1 = DescribeAnalysisSchemes
{ _das1DomainName = p1
, _das1AnalysisSchemeNames = mempty
, _das1Deployed = Nothing
}
-- | The analysis schemes you want to describe.
das1AnalysisSchemeNames :: Lens' DescribeAnalysisSchemes [Text]
das1AnalysisSchemeNames =
lens _das1AnalysisSchemeNames (\s a -> s { _das1AnalysisSchemeNames = a })
. _List
-- | Whether to display the deployed configuration ('true') or include any pending
-- changes ('false'). Defaults to 'false'.
das1Deployed :: Lens' DescribeAnalysisSchemes (Maybe Bool)
das1Deployed = lens _das1Deployed (\s a -> s { _das1Deployed = a })
-- | The name of the domain you want to describe.
das1DomainName :: Lens' DescribeAnalysisSchemes Text
das1DomainName = lens _das1DomainName (\s a -> s { _das1DomainName = a })
newtype DescribeAnalysisSchemesResponse = DescribeAnalysisSchemesResponse
{ _dasrAnalysisSchemes :: List "member" AnalysisSchemeStatus
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeAnalysisSchemesResponse where
type Item DescribeAnalysisSchemesResponse = AnalysisSchemeStatus
fromList = DescribeAnalysisSchemesResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _dasrAnalysisSchemes
-- | 'DescribeAnalysisSchemesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dasrAnalysisSchemes' @::@ ['AnalysisSchemeStatus']
--
describeAnalysisSchemesResponse :: DescribeAnalysisSchemesResponse
describeAnalysisSchemesResponse = DescribeAnalysisSchemesResponse
{ _dasrAnalysisSchemes = mempty
}
-- | The analysis scheme descriptions.
dasrAnalysisSchemes :: Lens' DescribeAnalysisSchemesResponse [AnalysisSchemeStatus]
dasrAnalysisSchemes =
lens _dasrAnalysisSchemes (\s a -> s { _dasrAnalysisSchemes = a })
. _List
instance ToPath DescribeAnalysisSchemes where
toPath = const "/"
instance ToQuery DescribeAnalysisSchemes where
toQuery DescribeAnalysisSchemes{..} = mconcat
[ "AnalysisSchemeNames" =? _das1AnalysisSchemeNames
, "Deployed" =? _das1Deployed
, "DomainName" =? _das1DomainName
]
instance ToHeaders DescribeAnalysisSchemes
instance AWSRequest DescribeAnalysisSchemes where
type Sv DescribeAnalysisSchemes = CloudSearch
type Rs DescribeAnalysisSchemes = DescribeAnalysisSchemesResponse
request = post "DescribeAnalysisSchemes"
response = xmlResponse
instance FromXML DescribeAnalysisSchemesResponse where
parseXML = withElement "DescribeAnalysisSchemesResult" $ \x -> DescribeAnalysisSchemesResponse
<$> x .@? "AnalysisSchemes" .!@ mempty
| romanb/amazonka | amazonka-cloudsearch/gen/Network/AWS/CloudSearch/DescribeAnalysisSchemes.hs | mpl-2.0 | 5,504 | 0 | 10 | 1,082 | 627 | 378 | 249 | 73 | 1 |
module Reddit.Types.Empty ( nothing ) where
import Control.Monad (liftM)
import Data.Aeson
import Data.Aeson.Types
import Data.Monoid
import Prelude
import qualified Data.HashMap.Strict as Hash
-- | More specific @void@ for forcing a @Empty@ @FromJSON@ instance
nothing :: Monad m => m Empty -> m ()
nothing = liftM $ const ()
data Empty = Empty
deriving (Show, Read, Eq)
instance FromJSON Empty where
parseJSON (Object o) =
if Hash.null o
then return Empty
else do
errs <- (o .: "json") >>= (.: "errors") :: Parser [Value]
if null errs
then return Empty
else mempty
parseJSON _ = mempty
| FranklinChen/reddit | src/Reddit/Types/Empty.hs | bsd-2-clause | 650 | 0 | 12 | 158 | 205 | 112 | 93 | 21 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.PrettyPrint
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Re-export of "Text.PrettyPrint.HughesPJ" to provide a default
-- pretty-printing library. Marked experimental at the moment; the
-- default library might change at a later date.
--
-----------------------------------------------------------------------------
module Text.PrettyPrint (
module Text.PrettyPrint.HughesPJ
) where
import Prelude
import Text.PrettyPrint.HughesPJ
| alekar/hugs | packages/base/Text/PrettyPrint.hs | bsd-3-clause | 727 | 2 | 5 | 106 | 41 | 32 | 9 | 4 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2013
--
-----------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
module SPARC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import SPARC.Base
import SPARC.CodeGen.Sanity
import SPARC.CodeGen.Amode
import SPARC.CodeGen.CondCode
import SPARC.CodeGen.Gen64
import SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.Ppr ()
import SPARC.Instr
import SPARC.Imm
import SPARC.AddrMode
import SPARC.Regs
import SPARC.Stack
import Instruction
import Format
import NCGMonad
-- Our intermediate code:
import BlockId
import Cmm
import CmmUtils
import CmmSwitch
import Hoopl
import PIC
import Reg
import CLabel
import CPrim
-- The rest:
import BasicTypes
import DynFlags
import FastString
import OrdList
import Outputable
import Platform
import Unique
import Control.Monad ( mapAndUnzipM )
-- | Top level code generation
cmmTopCodeGen :: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph)
= do let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
let tops = proc : concat statics
return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
-- | Do code generation on a single block of CMM code.
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
basicBlockCodeGen :: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
let
(top,other_blocks,statics)
= foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
-- do intra-block sanity checking
blocksChecked
= map (checkBlock block)
$ BasicBlock id top : other_blocks
return (blocksChecked, statics)
-- | Convert some Cmm statements to SPARC instructions.
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode format reg src
| isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode format reg src
where ty = cmmRegType dflags reg
format = cmmTypeFormat ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode format addr src
| isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode format addr src
where ty = cmmExprType dflags src
format = cmmTypeFormat ty
CmmUnsafeForeignCall target result_regs args
-> genCCall target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false _ -> do
b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg } -> genJump arg
_
-> panic "stmtToInstrs: statement should have been cps'd away"
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_IntCode pk addr src = do
(srcReg, code) <- getSomeReg src
Amode dstAddr addr_code <- getAmode addr
return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
r <- getRegister src
let dst = getRegisterReg (targetPlatform dflags) reg
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` OR False g0 (RIReg freg) dst
-- Floating point assignment to memory
assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_FltCode pk addr src = do
dflags <- getDynFlags
Amode dst__2 code1 <- getAmode addr
(src__2, code2) <- getSomeReg src
tmp1 <- getNewRegNat pk
let
pk__2 = cmmExprType dflags src
code__2 = code1 `appOL` code2 `appOL`
if formatToWidth pk == typeWidth pk__2
then unitOL (ST pk src__2 dst__2)
else toOL [ FxTOy (cmmTypeFormat pk__2) pk src__2 tmp1
, ST pk tmp1 dst__2]
return code__2
-- Floating point assignment to a register/temporary
assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_FltCode pk dstCmmReg srcCmmExpr = do
dflags <- getDynFlags
let platform = targetPlatform dflags
srcRegister <- getRegister srcCmmExpr
let dstReg = getRegisterReg platform dstCmmReg
return $ case srcRegister of
Any _ code -> code dstReg
Fixed _ srcFixedReg srcCode -> srcCode `snocOL` FMOV pk srcFixedReg dstReg
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (toOL [CALL (Left target) 0 True, NOP])
where
target = ImmCLbl lbl
genJump tree
= do
(target, code) <- getSomeReg tree
return (code `snocOL` JMP (AddrRegReg target g0) `snocOL` NOP)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
SPARC: First, we have to ensure that the condition codes are set
according to the supplied comparison operation. We generate slightly
different code for floating point comparisons, because a floating
point operation cannot directly precede a @BF@. We assume the worst
and fill that slot with a @NOP@.
SPARC: Do not fill the delay slots here; you will confuse the register
allocator.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump bid bool = do
CondCode is_float cond code <- getCondCode bool
return (
code `appOL`
toOL (
if is_float
then [NOP, BF cond False bid, NOP]
else [BI cond False bid, NOP]
)
)
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| gopt Opt_PIC dflags
= error "MachCodeGen: sparc genSwitch PIC not finished\n"
| otherwise
= do (e_reg, e_code) <- getSomeReg (cmmOffset dflags expr offset)
base_reg <- getNewRegNat II32
offset_reg <- getNewRegNat II32
dst <- getNewRegNat II32
label <- getNewLabelNat
return $ e_code `appOL`
toOL
[ -- load base of jump table
SETHI (HI (ImmCLbl label)) base_reg
, OR False base_reg (RIImm $ LO $ ImmCLbl label) base_reg
-- the addrs in the table are 32 bits wide..
, SLL e_reg (RIImm $ ImmInt 2) offset_reg
-- load and jump to the destination
, LD II32 (AddrRegReg base_reg offset_reg) dst
, JMP_TBL (AddrRegImm dst (ImmInt 0)) ids label
, NOP ]
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids label) =
let jumpTable = map (jumpTableEntry dflags) ids
in Just (CmmData ReadOnlyData (Statics label jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- Generating C calls
{-
Now the biggest nightmare---calls. Most of the nastiness is buried in
@get_arg@, which moves the arguments to the correct registers/stack
locations. Apart from that, the code is easy.
The SPARC calling convention is an absolute
nightmare. The first 6x32 bits of arguments are mapped into
%o0 through %o5, and the remaining arguments are dumped to the
stack, beginning at [%sp+92]. (Note that %o6 == %sp.)
If we have to put args on the stack, move %o6==%sp down by
the number of words to go on the stack, to ensure there's enough space.
According to Fraser and Hanson's lcc book, page 478, fig 17.2,
16 words above the stack pointer is a word for the address of
a structure return value. I use this as a temporary location
for moving values from float to int regs. Certainly it isn't
safe to put anything in the 16 words starting at %sp, since
this area can get trashed at any time due to window overflows
caused by signal handlers.
A final complication (if the above isn't enough) is that
we can't blithely calculate the arguments one by one into
%o0 .. %o5. Consider the following nested calls:
fff a (fff b c)
Naive code moves a into %o0, and (fff b c) into %o1. Unfortunately
the inner call will itself use %o0, which trashes the value put there
in preparation for the outer call. Upshot: we need to calculate the
args into temporary regs, and move those to arg regs or onto the
stack only immediately prior to the call proper. Sigh.
-}
genCCall
:: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
-- On SPARC under TSO (Total Store Ordering), writes earlier in the instruction stream
-- are guaranteed to take place before writes afterwards (unlike on PowerPC).
-- Ref: Section 8.4 of the SPARC V9 Architecture manual.
--
-- In the SPARC case we don't need a barrier.
--
genCCall (PrimTarget MO_WriteBarrier) _ _
= return $ nilOL
genCCall (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall target dest_regs args
= do -- work out the arguments, and assign them to integer regs
argcode_and_vregs <- mapM arg_to_int_vregs args
let (argcodes, vregss) = unzip argcode_and_vregs
let vregs = concat vregss
let n_argRegs = length allArgRegs
let n_argRegs_used = min (length vregs) n_argRegs
-- deal with static vs dynamic call targets
callinsns <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ ->
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
ForeignTarget expr _
-> do (dyn_c, [dyn_r]) <- arg_to_int_vregs expr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
PrimTarget mop
-> do res <- outOfLineMachOp mop
lblOrMopExpr <- case res of
Left lbl -> do
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
Right mopExpr -> do
(dyn_c, [dyn_r]) <- arg_to_int_vregs mopExpr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
return lblOrMopExpr
let argcode = concatOL argcodes
let (move_sp_down, move_sp_up)
= let diff = length vregs - n_argRegs
nn = if odd diff then diff + 1 else diff -- keep 8-byte alignment
in if nn <= 0
then (nilOL, nilOL)
else (unitOL (moveSp (-1*nn)), unitOL (moveSp (1*nn)))
let transfer_code
= toOL (move_final vregs allArgRegs extraStackArgsHere)
dflags <- getDynFlags
return
$ argcode `appOL`
move_sp_down `appOL`
transfer_code `appOL`
callinsns `appOL`
unitOL NOP `appOL`
move_sp_up `appOL`
assign_code (targetPlatform dflags) dest_regs
-- | Generate code to calculate an argument, and move it into one
-- or two integer vregs.
arg_to_int_vregs :: CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs arg = do dflags <- getDynFlags
arg_to_int_vregs' dflags arg
arg_to_int_vregs' :: DynFlags -> CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs' dflags arg
-- If the expr produces a 64 bit int, then we can just use iselExpr64
| isWord64 (cmmExprType dflags arg)
= do (ChildCode64 code r_lo) <- iselExpr64 arg
let r_hi = getHiVRegFromLo r_lo
return (code, [r_hi, r_lo])
| otherwise
= do (src, code) <- getSomeReg arg
let pk = cmmExprType dflags arg
case cmmTypeFormat pk of
-- Load a 64 bit float return value into two integer regs.
FF64 -> do
v1 <- getNewRegNat II32
v2 <- getNewRegNat II32
let code2 =
code `snocOL`
FMOV FF64 src f0 `snocOL`
ST FF32 f0 (spRel 16) `snocOL`
LD II32 (spRel 16) v1 `snocOL`
ST FF32 f1 (spRel 16) `snocOL`
LD II32 (spRel 16) v2
return (code2, [v1,v2])
-- Load a 32 bit float return value into an integer reg
FF32 -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
ST FF32 src (spRel 16) `snocOL`
LD II32 (spRel 16) v1
return (code2, [v1])
-- Move an integer return value into its destination reg.
_ -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
OR False g0 (RIReg src) v1
return (code2, [v1])
-- | Move args from the integer vregs into which they have been
-- marshalled, into %o0 .. %o5, and the rest onto the stack.
--
move_final :: [Reg] -> [Reg] -> Int -> [Instr]
-- all args done
move_final [] _ _
= []
-- out of aregs; move to stack
move_final (v:vs) [] offset
= ST II32 v (spRel offset)
: move_final vs [] (offset+1)
-- move into an arg (%o[0..5]) reg
move_final (v:vs) (a:az) offset
= OR False g0 (RIReg v) a
: move_final vs az offset
-- | Assign results returned from the call into their
-- destination regs.
--
assign_code :: Platform -> [LocalReg] -> OrdList Instr
assign_code _ [] = nilOL
assign_code platform [dest]
= let rep = localRegType dest
width = typeWidth rep
r_dest = getRegisterReg platform (CmmLocal dest)
result
| isFloatType rep
, W32 <- width
= unitOL $ FMOV FF32 (regSingle $ fReg 0) r_dest
| isFloatType rep
, W64 <- width
= unitOL $ FMOV FF64 (regSingle $ fReg 0) r_dest
| not $ isFloatType rep
, W32 <- width
= unitOL $ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest
| not $ isFloatType rep
, W64 <- width
, r_dest_hi <- getHiVRegFromLo r_dest
= toOL [ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest_hi
, mkRegRegMoveInstr platform (regSingle $ oReg 1) r_dest]
| otherwise
= panic "SPARC.CodeGen.GenCCall: no match"
in result
assign_code _ _
= panic "SPARC.CodeGen.GenCCall: no match"
-- | Generate a call to implement an out-of-line floating point operation
outOfLineMachOp
:: CallishMachOp
-> NatM (Either CLabel CmmExpr)
outOfLineMachOp mop
= do let functionName
= outOfLineMachOp_table mop
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference
$ mkForeignLabel functionName Nothing ForeignLabelInExternalPackage IsFunction
let mopLabelOrExpr
= case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return mopLabelOrExpr
-- | Decide what C function to use to implement a CallishMachOp
--
outOfLineMachOp_table
:: CallishMachOp
-> FastString
outOfLineMachOp_table mop
= case mop of
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Pwr -> fsLit "powf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Pwr -> fsLit "pow"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_UF_Conv w -> fsLit $ word2FloatLabel w
MO_Memcpy _ -> fsLit "memcpy"
MO_Memset _ -> fsLit "memset"
MO_Memmove _ -> fsLit "memmove"
MO_BSwap w -> fsLit $ bSwapLabel w
MO_PopCnt w -> fsLit $ popCntLabel w
MO_Clz w -> fsLit $ clzLabel w
MO_Ctz w -> fsLit $ ctzLabel w
MO_AtomicRMW w amop -> fsLit $ atomicRMWLabel w amop
MO_Cmpxchg w -> fsLit $ cmpxchgLabel w
MO_AtomicRead w -> fsLit $ atomicReadLabel w
MO_AtomicWrite w -> fsLit $ atomicWriteLabel w
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _) -> unsupported
where unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
| ml9951/ghc | compiler/nativeGen/SPARC/CodeGen.hs | bsd-3-clause | 22,492 | 0 | 29 | 7,323 | 4,622 | 2,295 | 2,327 | 385 | 48 |
{-
Copyright (C) 2013-2014 John MacFarlane <jgm@berkeley.edu>
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 : Text.Pandoc.Process
Copyright : Copyright (C) 2013-2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
ByteString variant of 'readProcessWithExitCode'.
-}
module Text.Pandoc.Process (pipeProcess)
where
import System.Process
import System.Exit (ExitCode (..))
import Control.Exception
import System.IO (hClose, hFlush)
import Control.Concurrent (putMVar, takeMVar, newEmptyMVar, forkIO)
import Control.Monad (unless)
import qualified Data.ByteString.Lazy as BL
{- |
Version of 'System.Process.readProcessWithExitCode' that uses lazy bytestrings
instead of strings and allows setting environment variables.
@readProcessWithExitCode@ creates an external process, reads its
standard output and standard error strictly, waits until the process
terminates, and then returns the 'ExitCode' of the process,
the standard output, and the standard error.
If an asynchronous exception is thrown to the thread executing
@readProcessWithExitCode@, the forked process will be terminated and
@readProcessWithExitCode@ will wait (block) until the process has been
terminated.
-}
pipeProcess
:: Maybe [(String, String)] -- ^ environment variables
-> FilePath -- ^ Filename of the executable (see 'proc' for details)
-> [String] -- ^ any arguments
-> BL.ByteString -- ^ standard input
-> IO (ExitCode,BL.ByteString,BL.ByteString) -- ^ exitcode, stdout, stderr
pipeProcess mbenv cmd args input =
mask $ \restore -> do
(Just inh, Just outh, Just errh, pid) <- createProcess (proc cmd args)
{ env = mbenv,
std_in = CreatePipe,
std_out = CreatePipe,
std_err = CreatePipe }
flip onException
(do hClose inh; hClose outh; hClose errh;
terminateProcess pid; waitForProcess pid) $ restore $ do
-- fork off a thread to start consuming stdout
out <- BL.hGetContents outh
waitOut <- forkWait $ evaluate $ BL.length out
-- fork off a thread to start consuming stderr
err <- BL.hGetContents errh
waitErr <- forkWait $ evaluate $ BL.length err
-- now write and flush any input
let writeInput = do
unless (BL.null input) $ do
BL.hPutStr inh input
hFlush inh
hClose inh
writeInput
-- wait on the output
waitOut
waitErr
hClose outh
hClose errh
-- wait on the process
ex <- waitForProcess pid
return (ex, out, err)
forkWait :: IO a -> IO (IO a)
forkWait a = do
res <- newEmptyMVar
_ <- mask $ \restore -> forkIO $ try (restore a) >>= putMVar res
return (takeMVar res >>= either (\ex -> throwIO (ex :: SomeException)) return)
| peter-fogg/pardoc | src/Text/Pandoc/Process.hs | gpl-2.0 | 3,802 | 0 | 21 | 1,061 | 564 | 290 | 274 | 45 | 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="pl-PL">
<title>Port Scan | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Zawartość</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Szukaj</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Ulubione</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/zest/src/main/javahelp/org/zaproxy/zap/extension/zest/resources/help_pl_PL/helpset_pl_PL.hs | apache-2.0 | 974 | 80 | 66 | 160 | 420 | 212 | 208 | -1 | -1 |
module WhileM where
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--short-names" @-}
import RIO
{-@
whileM :: forall < p :: World -> Prop
, qc :: World -> Bool -> World -> Prop
, qe :: World -> () -> World -> Prop
, q :: World -> () -> World -> Prop>.
{x::(), s1::World<p>, b::{v:Bool | Prop v}, s2::World<qc s1 b> |- World<qe s2 x> <: World<p>}
{b::{v:Bool | Prop v}, x2::(), s1::World<p>, s3::World |- World<q s3 x2> <: World<q s1 x2> }
{b::{v:Bool | not (Prop v)}, x2::(), s1::World<p> |- World<qc s1 b> <: World<q s1 x2> }
RIO <p, qc> Bool
-> RIO <{\v -> true}, qe> ()
-> RIO <p, q> ()
@-}
whileM :: RIO Bool -> RIO () -> RIO ()
whileM (RIO cond) (RIO e)
= undefined -- moved to todo because it breaks travis, but why? | ssaavedra/liquidhaskell | benchmarks/icfp15/pos/WhileM.hs | bsd-3-clause | 830 | 0 | 8 | 251 | 59 | 32 | 27 | 5 | 1 |
module RegAlloc.Linear.Stats (
binSpillReasons,
countRegRegMovesNat,
pprStats
)
where
import RegAlloc.Linear.Base
import RegAlloc.Liveness
import Instruction
import UniqFM
import Outputable
import Data.List
import State
-- | Build a map of how many times each reg was alloced, clobbered, loaded etc.
binSpillReasons
:: [SpillReason] -> UniqFM [Int]
binSpillReasons reasons
= addListToUFM_C
(zipWith (+))
emptyUFM
(map (\reason -> case reason of
SpillAlloc r -> (r, [1, 0, 0, 0, 0])
SpillClobber r -> (r, [0, 1, 0, 0, 0])
SpillLoad r -> (r, [0, 0, 1, 0, 0])
SpillJoinRR r -> (r, [0, 0, 0, 1, 0])
SpillJoinRM r -> (r, [0, 0, 0, 0, 1])) reasons)
-- | Count reg-reg moves remaining in this code.
countRegRegMovesNat
:: Instruction instr
=> NatCmmDecl statics instr -> Int
countRegRegMovesNat cmm
= execState (mapGenBlockTopM countBlock cmm) 0
where
countBlock b@(BasicBlock _ instrs)
= do mapM_ countInstr instrs
return b
countInstr instr
| Just _ <- takeRegRegMoveInstr instr
= do modify (+ 1)
return instr
| otherwise
= return instr
-- | Pretty print some RegAllocStats
pprStats
:: Instruction instr
=> [NatCmmDecl statics instr] -> [RegAllocStats] -> SDoc
pprStats code statss
= let -- sum up all the instrs inserted by the spiller
spills = foldl' (plusUFM_C (zipWith (+)))
emptyUFM
$ map ra_spillInstrs statss
spillTotals = foldl' (zipWith (+))
[0, 0, 0, 0, 0]
$ nonDetEltsUFM spills
-- See Note [Unique Determinism and code generation]
-- count how many reg-reg-moves remain in the code
moves = sum $ map countRegRegMovesNat code
pprSpill (reg, spills)
= parens $ (hcat $ punctuate (text ", ") (doubleQuotes (ppr reg) : map ppr spills))
in ( text "-- spills-added-total"
$$ text "-- (allocs, clobbers, loads, joinRR, joinRM, reg_reg_moves_remaining)"
$$ (parens $ (hcat $ punctuate (text ", ") (map ppr spillTotals ++ [ppr moves])))
$$ text ""
$$ text "-- spills-added"
$$ text "-- (reg_name, allocs, clobbers, loads, joinRR, joinRM)"
$$ (pprUFMWithKeys spills (vcat . map pprSpill))
$$ text "")
| olsner/ghc | compiler/nativeGen/RegAlloc/Linear/Stats.hs | bsd-3-clause | 2,711 | 0 | 22 | 1,031 | 693 | 369 | 324 | 59 | 5 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Network.Wai.Handler.SCGI
( run
, runSendfile
) where
import Network.Wai
import Network.Wai.Handler.CGI (runGeneric, requestBodyFunc)
import Foreign.Ptr
import Foreign.Marshal.Alloc
import Foreign.C
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Unsafe as S
import qualified Data.ByteString.Char8 as S8
import Data.IORef
import Data.ByteString.Lazy.Internal (defaultChunkSize)
run :: Application -> IO ()
run app = runOne Nothing app >> run app
runSendfile :: ByteString -> Application -> IO ()
runSendfile sf app = runOne (Just sf) app >> runSendfile sf app
runOne :: Maybe ByteString -> Application -> IO ()
runOne sf app = do
socket <- c'accept 0 nullPtr nullPtr
headersBS <- readNetstring socket
let headers@((_, conLenS):_) = parseHeaders $ S.split 0 headersBS
let conLen = case reads conLenS of
(i, _):_ -> i
[] -> 0
conLenI <- newIORef conLen
runGeneric headers (requestBodyFunc $ input socket conLenI)
(write socket) sf app
drain socket conLenI
_ <- c'close socket
return ()
write :: CInt -> S.ByteString -> IO ()
write socket bs = S.unsafeUseAsCStringLen bs $ \(s, l) -> do
_ <- c'write socket s (fromIntegral l)
return ()
input :: CInt -> IORef Int -> Int -> IO (Maybe S.ByteString)
input socket ilen rlen = do
len <- readIORef ilen
case len of
0 -> return Nothing
_ -> do
bs <- readByteString socket
$ minimum [defaultChunkSize, len, rlen]
writeIORef ilen $ len - S.length bs
return $ Just bs
drain :: CInt -> IORef Int -> IO () -- FIXME do it in chunks
drain socket ilen = do
len <- readIORef ilen
_ <- readByteString socket len
return ()
parseHeaders :: [S.ByteString] -> [(String, String)]
parseHeaders (x:y:z) = (S8.unpack x, S8.unpack y) : parseHeaders z
parseHeaders _ = []
readNetstring :: CInt -> IO S.ByteString
readNetstring socket = do
len <- readLen 0
bs <- readByteString socket len
_ <- readByteString socket 1 -- the comma
return bs
where
readLen l = do
bs <- readByteString socket 1
let [c] = S8.unpack bs
if c == ':'
then return l
else readLen $ l * 10 + (fromEnum c - fromEnum '0')
readByteString :: CInt -> Int -> IO S.ByteString
readByteString socket len = do
buf <- mallocBytes len
_ <- c'read socket buf $ fromIntegral len
S.unsafePackCStringFinalizer (castPtr buf) len $ free buf
foreign import ccall unsafe "accept"
c'accept :: CInt -> Ptr a -> Ptr a -> IO CInt
foreign import ccall unsafe "close"
c'close :: CInt -> IO CInt
foreign import ccall unsafe "write"
c'write :: CInt -> Ptr CChar -> CInt -> IO CInt
foreign import ccall unsafe "read"
c'read :: CInt -> Ptr CChar -> CInt -> IO CInt
| jberryman/wai | wai-extra/Network/Wai/Handler/SCGI.hs | mit | 2,944 | 0 | 15 | 749 | 1,079 | 533 | 546 | 80 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Lexer where
import Data.Char
import Data.Monoid
import Data.Text (Text, pack, unpack)
data Token
= TokenInt Int
| TokenDouble Double
| TokenTrue
| TokenFalse
| TokenString Text
| TokenVar Text
| TokenDot
| TokenColon
| TokenSemiColon
| TokenComma
| TokenPO
| TokenPC
| TokenSBO
| TokenSBC
| TokenBO
| TokenBC
| TokenArrow
| TokenTInt
| TokenTDouble
| TokenTBool
| TokenTString
| TokenIf
| TokenElse
| TokenCase
| TokenEqual
| TokenEquals
| TokenIn
| TokenSource
| TokenAO
| TokenAC
| TokenPlus
| TokenTimes
| TokenMinus
| TokenDivide
deriving Show
renderToken :: Token -> String
renderToken (TokenInt n) = show n
renderToken (TokenDouble d) = show d
renderToken TokenTrue = "true"
renderToken TokenFalse = "false"
renderToken (TokenString s) = "\"" <> unpack s <> "\""
renderToken (TokenVar v) = unpack v
renderToken TokenDot = "."
renderToken TokenColon = ":"
renderToken TokenSemiColon = ";"
renderToken TokenComma = ","
renderToken TokenPO = "("
renderToken TokenPC = ")"
renderToken TokenSBO = "["
renderToken TokenSBC = "]"
renderToken TokenBO = "{"
renderToken TokenBC = "}"
renderToken TokenArrow = "->"
renderToken TokenTInt = "int"
renderToken TokenTDouble = "double"
renderToken TokenTBool = "bool"
renderToken TokenTString = "string"
renderToken TokenIf = "if"
renderToken TokenElse = "else"
renderToken TokenCase = "case"
renderToken TokenEqual = "="
renderToken TokenEquals = "=="
renderToken TokenIn = "in"
renderToken TokenSource = "source"
renderToken TokenAO = "<"
renderToken TokenAC = ">"
renderToken TokenPlus = "+"
renderToken TokenTimes = "*"
renderToken TokenMinus = "-"
renderToken TokenDivide = "/"
lexer :: String -> [Token]
lexer [] = []
lexer (c:cs)
| isSpace c = lexer cs
| isAlpha c || c == '_' = lexVar (c:cs)
| isDigit c = lexNum (c:cs)
lexer ('.':cs) = TokenDot : lexer cs
lexer (',':cs) = TokenComma : lexer cs
lexer ('=':'=':cs) = TokenEquals : lexer cs
lexer ('=':cs) = TokenEqual : lexer cs
lexer ('-':'>':cs) = TokenArrow : lexer cs
lexer (':':cs) = TokenColon : lexer cs
lexer (';':cs) = TokenSemiColon : lexer cs
lexer ('(':cs) = TokenPO : lexer cs
lexer (')':cs) = TokenPC : lexer cs
lexer ('[':cs) = TokenSBO : lexer cs
lexer (']':cs) = TokenSBC : lexer cs
lexer ('{':cs) = TokenBO : lexer cs
lexer ('}':cs) = TokenBC : lexer cs
lexer ('<':cs) = TokenAO : lexer cs
lexer ('>':cs) = TokenAC : lexer cs
lexer ('+':cs) = TokenPlus : lexer cs
lexer ('*':cs) = TokenTimes : lexer cs
lexer ('-':cs) = TokenMinus : lexer cs
lexer ('/':cs) = TokenDivide : lexer cs
lexer ('"':cs) = let (s, rest) = span (/= '"') cs in
TokenString (pack s) : lexer (tail rest)
lexVar :: String -> [Token]
lexVar cs =
case span (\c -> isAlpha c || isDigit c || c == '_' || c == '-' || c == '\'' ) cs of
("true",rest) -> TokenTrue : lexer rest
("false",rest) -> TokenFalse : lexer rest
("if",rest) -> TokenIf : lexer rest
("else",rest) -> TokenElse : lexer rest
("case",rest) -> TokenCase : lexer rest
("in",rest) -> TokenIn : lexer rest
("source",rest) -> TokenSource : lexer rest
("int",rest) -> TokenTInt : lexer rest
("double",rest) -> TokenTDouble : lexer rest
("bool",rest) -> TokenTBool : lexer rest
("string",rest) -> TokenTString : lexer rest
(var,rest) -> TokenVar (pack var) : lexer rest
lexNum :: String -> [Token]
lexNum cs =
case rest of
('.':xs) ->
let (afterdec, rest') = span isDigit xs
in TokenDouble (read (num <> "." <> afterdec)) : lexer rest'
_ -> TokenInt (read num) : lexer rest
where (num,rest) = span isDigit cs
| dbp/thistle | src/Lexer.hs | isc | 3,873 | 0 | 16 | 960 | 1,502 | 775 | 727 | 126 | 12 |
--002 代入->束縛
a = 1
b = 2
c = a + b
main = do
print c
| mino2357/Hello_Haskell | src/haskell003.hs | mit | 67 | 0 | 7 | 24 | 32 | 17 | 15 | 5 | 1 |
{-# OPTIONS_GHC -Wall #-}
module Foreign where
import Data.Coerce
import GHCJS.Foreign.Callback
import GHCJS.Foreign.Callback.Internal
import GHCJS.Types
foreign import javascript safe "$1($2);"
invokeCallback :: Callback (JSVal -> IO ()) -> JSVal -> IO ()
foreign import javascript safe "$1($2, $3);"
invokeCallback2 :: Callback (JSVal -> JSVal -> IO ()) -> JSVal -> JSVal -> IO ()
foreign import javascript unsafe "exports[$1] = $2;"
setExport :: JSString -> Callback a -> IO ()
mkAsync2 :: (JSVal -> IO JSVal) -> JSVal -> JSVal -> IO()
mkAsync2 f a1 = coerce $ (f a1 >>=) . invokeCallback
mkAsync3 :: (JSVal -> JSVal -> IO JSVal) -> JSVal -> JSVal -> JSVal -> IO()
mkAsync3 f a1 a2 = coerce $ (f a1 a2 >>=) . invokeCallback
| atom-haskell/atom-haskell-utils | hs/src/Foreign.hs | mit | 738 | 15 | 10 | 133 | 275 | 144 | 131 | 16 | 1 |
module Main where
import Protolude
import qualified Walnut as W
import Data.Conduit (($$), ($=))
main :: IO ()
main
= do
-- | Create a ZMQ Message source, the mvar produced here will continuously
-- produce 'Message' data until the end of time.
(mvarR, mvarS) <- W.zmqSockets
-- | Run our Conduit.
W.zmqReceive mvarR
$= W.printer
$$ W.zmqForward mvarS
| Reisen/Walnut | bin/walnut/src/Main.hs | mit | 433 | 0 | 10 | 140 | 86 | 51 | 35 | 11 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.XPathResult
(js_iterateNext, iterateNext, js_snapshotItem, snapshotItem,
pattern ANY_TYPE, pattern NUMBER_TYPE, pattern STRING_TYPE,
pattern BOOLEAN_TYPE, pattern UNORDERED_NODE_ITERATOR_TYPE,
pattern ORDERED_NODE_ITERATOR_TYPE,
pattern UNORDERED_NODE_SNAPSHOT_TYPE,
pattern ORDERED_NODE_SNAPSHOT_TYPE,
pattern ANY_UNORDERED_NODE_TYPE, pattern FIRST_ORDERED_NODE_TYPE,
js_getResultType, getResultType, js_getNumberValue, getNumberValue,
js_getStringValue, getStringValue, js_getBooleanValue,
getBooleanValue, js_getSingleNodeValue, getSingleNodeValue,
js_getInvalidIteratorState, getInvalidIteratorState,
js_getSnapshotLength, getSnapshotLength, XPathResult,
castToXPathResult, gTypeXPathResult)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"iterateNext\"]()"
js_iterateNext :: JSRef XPathResult -> IO (JSRef Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.iterateNext Mozilla XPathResult.iterateNext documentation>
iterateNext :: (MonadIO m) => XPathResult -> m (Maybe Node)
iterateNext self
= liftIO ((js_iterateNext (unXPathResult self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"snapshotItem\"]($2)"
js_snapshotItem :: JSRef XPathResult -> Word -> IO (JSRef Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.snapshotItem Mozilla XPathResult.snapshotItem documentation>
snapshotItem ::
(MonadIO m) => XPathResult -> Word -> m (Maybe Node)
snapshotItem self index
= liftIO
((js_snapshotItem (unXPathResult self) index) >>= fromJSRef)
pattern ANY_TYPE = 0
pattern NUMBER_TYPE = 1
pattern STRING_TYPE = 2
pattern BOOLEAN_TYPE = 3
pattern UNORDERED_NODE_ITERATOR_TYPE = 4
pattern ORDERED_NODE_ITERATOR_TYPE = 5
pattern UNORDERED_NODE_SNAPSHOT_TYPE = 6
pattern ORDERED_NODE_SNAPSHOT_TYPE = 7
pattern ANY_UNORDERED_NODE_TYPE = 8
pattern FIRST_ORDERED_NODE_TYPE = 9
foreign import javascript unsafe "$1[\"resultType\"]"
js_getResultType :: JSRef XPathResult -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.resultType Mozilla XPathResult.resultType documentation>
getResultType :: (MonadIO m) => XPathResult -> m Word
getResultType self = liftIO (js_getResultType (unXPathResult self))
foreign import javascript unsafe "$1[\"numberValue\"]"
js_getNumberValue :: JSRef XPathResult -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.numberValue Mozilla XPathResult.numberValue documentation>
getNumberValue :: (MonadIO m) => XPathResult -> m Double
getNumberValue self
= liftIO (js_getNumberValue (unXPathResult self))
foreign import javascript unsafe "$1[\"stringValue\"]"
js_getStringValue :: JSRef XPathResult -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.stringValue Mozilla XPathResult.stringValue documentation>
getStringValue ::
(MonadIO m, FromJSString result) => XPathResult -> m result
getStringValue self
= liftIO
(fromJSString <$> (js_getStringValue (unXPathResult self)))
foreign import javascript unsafe "($1[\"booleanValue\"] ? 1 : 0)"
js_getBooleanValue :: JSRef XPathResult -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.booleanValue Mozilla XPathResult.booleanValue documentation>
getBooleanValue :: (MonadIO m) => XPathResult -> m Bool
getBooleanValue self
= liftIO (js_getBooleanValue (unXPathResult self))
foreign import javascript unsafe "$1[\"singleNodeValue\"]"
js_getSingleNodeValue :: JSRef XPathResult -> IO (JSRef Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.singleNodeValue Mozilla XPathResult.singleNodeValue documentation>
getSingleNodeValue :: (MonadIO m) => XPathResult -> m (Maybe Node)
getSingleNodeValue self
= liftIO
((js_getSingleNodeValue (unXPathResult self)) >>= fromJSRef)
foreign import javascript unsafe
"($1[\"invalidIteratorState\"] ? 1 : 0)" js_getInvalidIteratorState
:: JSRef XPathResult -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.invalidIteratorState Mozilla XPathResult.invalidIteratorState documentation>
getInvalidIteratorState :: (MonadIO m) => XPathResult -> m Bool
getInvalidIteratorState self
= liftIO (js_getInvalidIteratorState (unXPathResult self))
foreign import javascript unsafe "$1[\"snapshotLength\"]"
js_getSnapshotLength :: JSRef XPathResult -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XPathResult.snapshotLength Mozilla XPathResult.snapshotLength documentation>
getSnapshotLength :: (MonadIO m) => XPathResult -> m Word
getSnapshotLength self
= liftIO (js_getSnapshotLength (unXPathResult self)) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/XPathResult.hs | mit | 5,662 | 56 | 11 | 782 | 1,170 | 653 | 517 | 89 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.TextTrackCue
(js_newTextTrackCue, newTextTrackCue, js_getTrack, getTrack,
js_setId, setId, js_getId, getId, js_setStartTime, setStartTime,
js_getStartTime, getStartTime, js_setEndTime, setEndTime,
js_getEndTime, getEndTime, js_setPauseOnExit, setPauseOnExit,
js_getPauseOnExit, getPauseOnExit, enter, exit, TextTrackCue,
castToTextTrackCue, gTypeTextTrackCue, IsTextTrackCue,
toTextTrackCue)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe
"new window[\"TextTrackCue\"]($1,\n$2, $3)" js_newTextTrackCue ::
Double -> Double -> JSString -> IO (JSRef TextTrackCue)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue Mozilla TextTrackCue documentation>
newTextTrackCue ::
(MonadIO m, ToJSString text) =>
Double -> Double -> text -> m TextTrackCue
newTextTrackCue startTime endTime text
= liftIO
(js_newTextTrackCue startTime endTime (toJSString text) >>=
fromJSRefUnchecked)
foreign import javascript unsafe "$1[\"track\"]" js_getTrack ::
JSRef TextTrackCue -> IO (JSRef TextTrack)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.track Mozilla TextTrackCue.track documentation>
getTrack ::
(MonadIO m, IsTextTrackCue self) => self -> m (Maybe TextTrack)
getTrack self
= liftIO
((js_getTrack (unTextTrackCue (toTextTrackCue self))) >>=
fromJSRef)
foreign import javascript unsafe "$1[\"id\"] = $2;" js_setId ::
JSRef TextTrackCue -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.id Mozilla TextTrackCue.id documentation>
setId ::
(MonadIO m, IsTextTrackCue self, ToJSString val) =>
self -> val -> m ()
setId self val
= liftIO
(js_setId (unTextTrackCue (toTextTrackCue self)) (toJSString val))
foreign import javascript unsafe "$1[\"id\"]" js_getId ::
JSRef TextTrackCue -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.id Mozilla TextTrackCue.id documentation>
getId ::
(MonadIO m, IsTextTrackCue self, FromJSString result) =>
self -> m result
getId self
= liftIO
(fromJSString <$>
(js_getId (unTextTrackCue (toTextTrackCue self))))
foreign import javascript unsafe "$1[\"startTime\"] = $2;"
js_setStartTime :: JSRef TextTrackCue -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.startTime Mozilla TextTrackCue.startTime documentation>
setStartTime ::
(MonadIO m, IsTextTrackCue self) => self -> Double -> m ()
setStartTime self val
= liftIO
(js_setStartTime (unTextTrackCue (toTextTrackCue self)) val)
foreign import javascript unsafe "$1[\"startTime\"]"
js_getStartTime :: JSRef TextTrackCue -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.startTime Mozilla TextTrackCue.startTime documentation>
getStartTime ::
(MonadIO m, IsTextTrackCue self) => self -> m Double
getStartTime self
= liftIO (js_getStartTime (unTextTrackCue (toTextTrackCue self)))
foreign import javascript unsafe "$1[\"endTime\"] = $2;"
js_setEndTime :: JSRef TextTrackCue -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.endTime Mozilla TextTrackCue.endTime documentation>
setEndTime ::
(MonadIO m, IsTextTrackCue self) => self -> Double -> m ()
setEndTime self val
= liftIO (js_setEndTime (unTextTrackCue (toTextTrackCue self)) val)
foreign import javascript unsafe "$1[\"endTime\"]" js_getEndTime ::
JSRef TextTrackCue -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.endTime Mozilla TextTrackCue.endTime documentation>
getEndTime :: (MonadIO m, IsTextTrackCue self) => self -> m Double
getEndTime self
= liftIO (js_getEndTime (unTextTrackCue (toTextTrackCue self)))
foreign import javascript unsafe "$1[\"pauseOnExit\"] = $2;"
js_setPauseOnExit :: JSRef TextTrackCue -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.pauseOnExit Mozilla TextTrackCue.pauseOnExit documentation>
setPauseOnExit ::
(MonadIO m, IsTextTrackCue self) => self -> Bool -> m ()
setPauseOnExit self val
= liftIO
(js_setPauseOnExit (unTextTrackCue (toTextTrackCue self)) val)
foreign import javascript unsafe "($1[\"pauseOnExit\"] ? 1 : 0)"
js_getPauseOnExit :: JSRef TextTrackCue -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.pauseOnExit Mozilla TextTrackCue.pauseOnExit documentation>
getPauseOnExit ::
(MonadIO m, IsTextTrackCue self) => self -> m Bool
getPauseOnExit self
= liftIO (js_getPauseOnExit (unTextTrackCue (toTextTrackCue self)))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.onenter Mozilla TextTrackCue.onenter documentation>
enter ::
(IsTextTrackCue self, IsEventTarget self) => EventName self Event
enter = unsafeEventName (toJSString "enter")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackCue.onexit Mozilla TextTrackCue.onexit documentation>
exit ::
(IsTextTrackCue self, IsEventTarget self) => EventName self Event
exit = unsafeEventName (toJSString "exit") | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/TextTrackCue.hs | mit | 6,144 | 72 | 13 | 1,004 | 1,379 | 757 | 622 | 101 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Capnp.GenHelpers.New.Rpc
( module Capnp.New.Rpc.Server
, module Capnp.Repr.Methods
, parseCap
, encodeCap
) where
import Capnp.Message (Mutability(..))
import qualified Capnp.Message as M
import Capnp.New.Rpc.Server
import qualified Capnp.Repr as R
import Capnp.Repr.Methods
import qualified Capnp.Untyped as U
parseCap :: (R.IsCap a, U.ReadCtx m 'Const) => R.Raw a 'Const -> m (Client a)
parseCap (R.Raw cap) = Client <$> U.getClient cap
encodeCap :: (R.IsCap a, U.RWCtx m s) => M.Message ('Mut s) -> Client a -> m (R.Raw a ('Mut s))
encodeCap msg (Client c) = R.Raw <$> U.appendCap msg c
| zenhack/haskell-capnp | lib/Capnp/GenHelpers/New/Rpc.hs | mit | 783 | 0 | 13 | 196 | 260 | 147 | 113 | 18 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Librato.Jobs where
import Librato.Internal
import Librato.Types
import Network.URI.Template
getJob :: JobId a -> Librato (Maybe (JobStatus a))
getJob = get "jobs/{id}"
| iand675/librato | src/Librato/Jobs.hs | mit | 238 | 0 | 10 | 31 | 59 | 33 | 26 | 8 | 1 |
module TigerSemant
(
transprog
)
where
import TigerSemTr
import TigerSemantTypes
import qualified TigerLexer as TLex
import qualified TigerAbsyn as TAbs
import qualified TigerSymbol as TSym
import qualified TigerTemp as TTmp
import qualified TigerTranslate as TTra
import qualified Data.Map as Map
import qualified TigerParser as TPar
import Control.Monad.State
import Control.Monad.Except
import Data.IORef.MonadIO
import Data.List
import Data.Maybe
type GexpTy = (TTra.Gexp, Ty)
-- Functions used to report error
cyclicTypeError :: TLex.AlexPosn -> [String] -> SemantError
cyclicTypeError pos types = SE pos $ TypeLoop types
notCallableError :: TLex.AlexPosn -> String -> SemantError
notCallableError pos str = SE pos $ NotCallable str
typeMisMatchError :: TLex.AlexPosn -> String -> String -> SemantError
typeMisMatchError pos str1 str2 = SE pos $ TypeMismatch str1 str2
argumentNameError :: TLex.AlexPosn -> String -> String -> SemantError
argumentNameError pos str1 str2 = SE pos $ ArgumentName str1 str2
undefinedBinop :: TLex.AlexPosn -> String -> String -> SemantError
undefinedBinop pos str1 str2 = SE pos $ UndefinedBinop str1 str2
undefinedError :: TLex.AlexPosn -> String -> SemantError
undefinedError pos str = SE pos $ Undefined str
argumentCountError :: TLex.AlexPosn -> Int -> Int -> SemantError
argumentCountError pos c1 c2 = SE pos $ ArgumentCount c1 c2
breakOutOfLoop :: TLex.AlexPosn -> SemantError
breakOutOfLoop pos = SE pos $ BreakOutsideOfLoop
duplicateDefinition :: TLex.AlexPosn -> String -> SemantError
duplicateDefinition pos str = SE pos $ DuplicateDefinition str
notVariable :: TLex.AlexPosn -> String -> SemantError
notVariable pos str = SE pos $ NotVariable str
enterLoop :: SemTr ()
enterLoop = do l <- getLoopLevel
putLoopLevel $ l+1
exitLoop :: SemTr ()
exitLoop = do l <- getLoopLevel
putLoopLevel $ l-1
actualTy' :: TLex.AlexPosn -> Ty -> [Ty] -> SemTr Ty
actualTy' pos a@(Name (_, iorefmaybety)) searched =
do if a `elem` searched
then throwError $ cyclicTypeError pos $ map show searched
else do maybety <- liftIO $ readIORef iorefmaybety
case maybety of
(Just ty) -> actualTy' pos ty (a:searched)
Nothing -> error "Compiler error: fatal error in cyclic type detection."
actualTy' pos a searched = do if a `elem` searched
then throwError $ cyclicTypeError pos $ map show searched
else return a
actualTy :: TLex.AlexPosn -> Ty -> SemTr Ty
actualTy pos ty = actualTy' pos ty []
isPointer :: Ty -> SemTr Bool
isPointer String = return False
isPointer INT = return False
isPointer Unit = return False
isPointer t@(Name _) = do
aty <- actualTy (TLex.AlexPn 0 0 0) t
isPointer aty
isPointer Nil = return False
isPointer (Array _) = return True
isPointer (Record _) = return True
withBinding :: Venv -> Tenv -> SemTr a -> SemTr a
withBinding v t checker =
do ov <- getVenv
ot <- getTenv
putVenv v
putTenv t
a <- checker
putVenv ov
putTenv ot
return a
findFirstDiffInLists :: Eq a => [a] -> [a] -> Maybe Int
findFirstDiffInLists la lb | la == lb = Nothing
| length la /= length lb = error "Compiler error: list a and list b must be the"
" same length in findFirstDiffInLists."
| otherwise = let equalities = zipWith (==) la lb
in (False) `elemIndex` equalities
zipWithM5 :: (Monad m) => (a -> b -> c -> d -> e -> m g) -> [a] -> [b] -> [c] -> [d] -> [e] -> m [g]
zipWithM5 f (a:args1) (b:args2) (c:args3) (d:args4) (e:args5)= do
g <- f a b c d e
gs <- zipWithM5 f args1 args2 args3 args4 args5
return $ g:gs
zipWithM5 _ [] [] [] [] [] = return []
zipWithM5 _ _ _ _ _ _ = error $ "zipWithM5: Args 1..5 must have the same length."
nestedZip :: [[a]] -> [[b]] -> [[(a, b)]]
nestedZip as bs = zipWith zip as bs
insertList :: (Ord k) => Map.Map k v -> [k] -> [v] -> Map.Map k v
insertList m keys values = foldr (uncurry Map.insert) m (zip keys values)
sym2ty :: TSym.Symbol -> TLex.AlexPosn -> SemTr Ty
sym2ty sym pos = do
t <- getTenv
case Map.lookup sym t of
Nothing -> throwError $ undefinedError pos $ name sym
Just ty -> return ty
addtypetobinding :: TSym.Symbol -> Ty -> SemTr ()
addtypetobinding sym ty = do
t <- getTenv
let t' = Map.insert sym ty t
putTenv t'
addfunctiontobinding :: TSym.Symbol -> TTra.Level -> TTmp.Label -> [(Ty, Access)] -> Ty -> SemTr ()
addfunctiontobinding sym lvl lab params result = do
v <- getVenv
let fentry = FunEntry lvl lab params result
let v' = Map.insert sym fentry v
putVenv v'
transdec :: TTra.Level -> Maybe TTmp.Label -> TAbs.Dec -> SemTr (Venv, Tenv, [TTra.Gexp])
transdec lvl lab dec =
let g (TAbs.FunctionDec fdecs) = let fnamesyms = map TAbs.fundecName fdecs
fparams = map TAbs.fundecParams fdecs
ffieldnamess = fmap (map TAbs.tfieldName) fparams
ffieldtypess = fmap (map TAbs.tfieldTyp) fparams
ffieldposess = fmap (map TAbs.tfieldPos) fparams
fbodyexps = map TAbs.fundecBody fdecs
ftypes = map TAbs.fundecResult fdecs
in do fparamtyss <- mapM (mapM (uncurry sym2ty)) (nestedZip ffieldtypess ffieldposess)
(flevels, formalsWithOffsetss) <- fmap unzip $ mapM (TTra.newLevel lvl) fparamtyss
fresulttys <- mapM ftype2ty ftypes
flabs <- mapM (\_ -> newLabel) fdecs
let fentries = zipWith4 FunEntry flevels flabs formalsWithOffsetss fresulttys
v <- getVenv
t <- getTenv
let v' = insertList v fnamesyms fentries
_ <- withBinding v' t $ zipWithM5 (checkbody lab) flevels flabs fresulttys
(zip3 ffieldnamess fparamtyss $ fmap (map snd) formalsWithOffsetss)
fbodyexps
return (v', t, [])
where ftype2ty (Just (s, pos)) = sym2ty s pos
ftype2ty Nothing = return Unit
checkbody newlab newlvl funlab decty (paramsyms, paramtys, paramaccesses) bodyexp =
do let varentries = zipWith3 VarEntry paramaccesses paramtys $ take (length paramsyms) $ repeat False
v <- getVenv
t <- getTenv
let v' = insertList v paramsyms varentries
(gexp, bodyty) <- withBinding v' t $ transexp newlvl newlab bodyexp
let bodyposition = TPar.extractPosition bodyexp
bodyty' <- actualTy bodyposition bodyty
decty' <- actualTy bodyposition decty
if bodyty' == decty'
then do retvalIsptr <- isPointer bodyty'
TTra.createProcFrag funlab newlvl gexp retvalIsptr
else throwError $ typeMisMatchError (TPar.extractPosition bodyexp) (show bodyty) (show decty)
g (TAbs.VarDec {TAbs.varDecVar=vardec, TAbs.varDecTyp=typandpos, TAbs.varDecInit=initexp, TAbs.varDecPos=pos}) =
do (initgexp, initty) <- transexp lvl lab initexp
let varnamesym = TAbs.vardecName vardec
isinitptr <- isPointer initty
varaccess <- liftIO $ TTra.allocInFrame isinitptr lvl
var <- TTra.simpleVar varaccess lvl isinitptr
assigngexp <- TTra.assign var initgexp
case typandpos of
Just (typsym, typpos) -> do typty <- sym2ty typsym typpos
initty' <- actualTy (TPar.extractPosition initexp) initty
typty' <- actualTy typpos typty
if initty' == typty'
then do let varentry = VarEntry varaccess initty' False
v <- getVenv
t <- getTenv
let v' = Map.insert varnamesym varentry v
return (v', t, [assigngexp])
else throwError $ typeMisMatchError pos (show initty) (show typty)
Nothing -> do v <- getVenv
t <- getTenv
let varentry = VarEntry varaccess initty False
let v' = Map.insert varnamesym varentry v
return (v', t, [assigngexp])
g (TAbs.TypeDec decs) =
do v <- getVenv
t <- getTenv
let names = map TAbs.typedecName decs
let poses = map TAbs.typedecPos decs
mapM_ (uncurry (checkname t)) (zip poses names)
refNothings <- mapM (\_ -> liftIO $ newIORef Nothing) decs
let nametypes = zipWith (curry Name) names refNothings
let t' = insertList t names nametypes
let absyntys = map TAbs.typedecTy decs
tys <- mapM (withBinding v t' . transty) absyntys
mapM_ (\(ref, ty) -> liftIO $ writeIORef ref $ Just ty) (zip refNothings tys)
return (v, t', [])
where checkname t pos sym = do case Map.lookup sym t of
Nothing -> return ()
Just _ -> throwError $ duplicateDefinition pos $ name sym
in g dec
transexp :: TTra.Level -> Maybe TTmp.Label -> TAbs.Exp -> SemTr GexpTy
transexp lvl lab absexp =
let g (TAbs.VarExp v) = transvar lvl lab v
g (TAbs.NilExp _) = return (TTra.nilGexp, Nil)
g (TAbs.IntExp (v, _)) = do gexp <- TTra.intExp v
return (gexp, INT)
g (TAbs.StringExp (v, _)) = do gexp <- TTra.stringExp v
return (gexp, String)
g (TAbs.SeqExp []) = error "Compiler error: fatal error in sequence"
" expression type checking"
g (TAbs.SeqExp (epos:[])) = g $ fst epos
g (TAbs.SeqExp (epos:eposes)) = do (ge, _) <- g $ fst epos
(ge', ty) <- g $ TAbs.SeqExp eposes
ge'' <- TTra.constructEseq ge ge'
return (ge'', ty)
g (TAbs.AppExp {TAbs.appFunc=funcsym, TAbs.appArgs=funcargs, TAbs.appPos=pos}) =
do v <- getVenv
case Map.lookup funcsym v of
Just (FunEntry {funLevel=funlvl
,funLabel=funlab
,funFormals=funformals
,funResult=funresult}) ->
do (ges, tys) <- liftM unzip $ mapM g funcargs
let argposes = map TPar.extractPosition funcargs
argtys <- mapM (uncurry actualTy) (zip argposes tys)
formaltys <- mapM (actualTy pos) (map fst funformals)
case findFirstDiffInLists argtys formaltys of
Nothing -> do isresultptr <- isPointer funresult
gexp <- TTra.callFunction funlab lvl funlvl ges isresultptr
return (gexp, funresult)
Just idx -> throwError $ typeMisMatchError (TPar.extractPosition $ funcargs !! idx) (show $ argtys !! idx) (show $ formaltys !! idx)
Just _ -> throwError $ notCallableError pos $ name funcsym
Nothing -> throwError $ undefinedError pos $ name funcsym
g (TAbs.OpExp {TAbs.opLeft=lexp, TAbs.opOper=op, TAbs.opRight=rexp, TAbs.opPos=pos}) =
do (lgexp, lty) <- g lexp
(rgexp, rty) <- g rexp
lty' <- actualTy (TPar.extractPosition lexp) lty
rty' <- actualTy (TPar.extractPosition rexp) rty
if (lty' == rty')
then case lty of
INT -> do { gexp <- op2fun op lgexp rgexp; return (gexp, INT) }
String -> do { gexp <- op2funstr op lgexp rgexp; return (gexp, INT) }
Nil -> throwError $ undefinedBinop pos (show Nil) (show rty)
Unit -> throwError $ undefinedBinop pos (show Unit) (show rty)
_ -> case op of
TAbs.EqOp -> do { gexp <- op2fun op lgexp rgexp; return (gexp, INT) }
TAbs.NeqOp -> do { gexp <- op2fun op lgexp rgexp; return (gexp, INT) }
_ -> throwError $ undefinedBinop pos (show lty) (show rty)
else throwError $ typeMisMatchError pos (show lty) (show rty)
where op2fun TAbs.EqOp = TTra.eqCmp
op2fun TAbs.NeqOp = TTra.notEqCmp
op2fun TAbs.LtOp = TTra.lessThan
op2fun TAbs.LeOp = TTra.lessThanOrEq
op2fun TAbs.GtOp = flip TTra.lessThan
op2fun TAbs.GeOp = flip TTra.lessThanOrEq
op2fun o = TTra.arithmetic o
op2funstr TAbs.EqOp = TTra.eqStr
op2funstr TAbs.NeqOp = TTra.notEqStr
op2funstr TAbs.LtOp = TTra.strLessThan
op2funstr TAbs.LeOp = TTra.strLessThanOrEq
op2funstr TAbs.GtOp = flip TTra.strLessThan
op2funstr TAbs.GeOp = flip TTra.strLessThanOrEq
op2funstr _ = error "Compiler error: impossible operator on string."
g (TAbs.RecordExp {TAbs.recordFields=efields, TAbs.recordTyp=typsym, TAbs.recordPos=pos}) =
let checkrecord ty = do let typefields = fst ty
let (fieldnames, fieldtys) = unzip typefields
let (efieldnames, eexps, eposes) = unzip3 efields
if length efieldnames == length fieldnames
then case findFirstDiffInLists efieldnames fieldnames of
Nothing -> do (gexps, exptys) <- liftM unzip $ mapM g eexps
exptys' <- mapM (uncurry actualTy) (zip eposes exptys)
fieldtys' <- mapM (actualTy pos) fieldtys
case findFirstDiffInLists exptys' fieldtys' of
Nothing -> do isptrs <- mapM isPointer fieldtys'
finalgexp <- TTra.createRecord $ zip gexps isptrs
return (finalgexp, Record ty)
Just idx -> throwError $ typeMisMatchError
(TPar.extractPosition $ eexps !! idx)
(show $ exptys !! idx)
(show $ fieldtys !! idx)
Just idx -> throwError $ argumentNameError (TPar.extractPosition $ eexps !! idx)
(name $ efieldnames !! idx)
(name $ fieldnames !! idx)
else throwError $ argumentCountError pos (length efieldnames) (length fieldnames)
in do t <- getTenv
case Map.lookup typsym t of
Nothing -> throwError $ undefinedError pos $ name typsym
Just (Record ty) -> checkrecord ty
Just typ@(Name _) -> do aty <- actualTy pos typ
case aty of
Record ty -> checkrecord ty
_ -> throwError $ typeMisMatchError pos ("Record") (name typsym)
Just _ -> throwError $ typeMisMatchError pos ("Record") (name typsym)
g (TAbs.AssignExp {TAbs.assignVar=var, TAbs.assignExp=aexp, TAbs.assignPos=pos}) =
do (vgexp, vty) <- transvar lvl lab var
(agexp, aty) <- g aexp
vty' <- actualTy pos vty
aty' <- actualTy (TPar.extractPosition aexp) aty
if vty' == aty'
then do gexp <- TTra.assign vgexp agexp
return (gexp, Unit)
else throwError $ typeMisMatchError pos (show vty) (show aty)
g (TAbs.IfExp {TAbs.ifTest=testexp, TAbs.ifThen=thenexp, TAbs.ifElse=elseexp, TAbs.ifPos=pos}) =
do (testgexp, testty) <- g testexp
(thengexp, thenty) <- g thenexp
thenty' <- actualTy (TPar.extractPosition thenexp) thenty
if testty == INT
then case elseexp of
Just elseexp' -> do (elsegexp, elsety) <- g elseexp'
elsety' <- actualTy (TPar.extractPosition elseexp') elsety
if (thenty' == elsety')
then do isptr <- isPointer thenty'
gexp <- TTra.ifThenElse testgexp thengexp elsegexp isptr
return (gexp, elsety)
else throwError $ typeMisMatchError pos (show thenty) (show elsety)
Nothing -> if (thenty' == Unit)
then do gexp <- TTra.ifThen testgexp thengexp
return (gexp, Unit)
else throwError $ typeMisMatchError pos (show Unit) (show thenty)
else throwError $ typeMisMatchError pos (show INT) (show testty)
g (TAbs.WhileExp {TAbs.whileTest=testexp, TAbs.whileBody=bodyexp, TAbs.whilePos=pos}) =
do (testgexp, testty) <- g testexp
if (testty == INT)
then do donelab <- newLabel
enterLoop
(bodygexp, bodyty) <- transexp lvl (Just donelab) bodyexp
exitLoop
bodyty' <- actualTy (TPar.extractPosition bodyexp) bodyty
if (bodyty' == Unit)
then do gexp <- TTra.whileLoop testgexp bodygexp donelab
return (gexp, Unit)
else throwError $ typeMisMatchError pos (show Unit) (show bodyty)
else throwError $ typeMisMatchError pos (show INT) (show testty)
g (TAbs.ForExp {TAbs.forVar=vardec, TAbs.forLo=lowexp, TAbs.forHi=highexp, TAbs.forBody=bodyexp, TAbs.forPos=pos}) =
do let itername = TAbs.vardecName vardec
(lowgexp, lowty) <- g lowexp
(highgexp, highty) <- g highexp
if (lowty == highty)
then if (lowty == INT)
then do v <- getVenv
t <- getTenv
iteraccess <- liftIO $ TTra.allocInFrame False lvl
let v' = Map.insert itername (VarEntry iteraccess INT True) v
itergexp<- TTra.simpleVar iteraccess lvl False
donelab <- newLabel
enterLoop
(bodygexp, bodyty) <- withBinding v' t (transexp lvl (Just donelab) bodyexp)
exitLoop
bodyty' <- actualTy (TPar.extractPosition bodyexp) bodyty
if bodyty' == Unit
then do gexp <- TTra.forLoop lowgexp highgexp bodygexp donelab itergexp
return (gexp, Unit)
else throwError $ typeMisMatchError pos (show Unit) (show bodyty)
else throwError $ typeMisMatchError pos (show INT) (show lowty)
else throwError $ typeMisMatchError pos (show lowty) (show highty)
g (TAbs.BreakExp pos) =
do l <- getLoopLevel
if (l > 0)
then case lab of
Just lab' -> do gexp <- TTra.break lab'
return (gexp, Unit)
Nothing -> throwError $ breakOutOfLoop pos
else throwError $ breakOutOfLoop pos
g (TAbs.LetExp {TAbs.letDecs=decs, TAbs.letBody=bodyexp}) =
let transdecs (d:[]) = transdec lvl lab d
transdecs (d:ds) = do (v, t, ges) <- transdec lvl lab d
(v', t', gess) <- withBinding v t $ transdecs ds
return (v', t', ges++gess)
transdecs [] = do v <- getVenv
t <- getTenv
return (v, t, [])
in do (v', t', ges) <- transdecs decs
(bodygexp, bodyty) <- withBinding v' t' $ g bodyexp
gexp <- TTra.letExpression ges bodygexp
return (gexp, bodyty)
g (TAbs.ArrayExp {TAbs.arrayTyp=typsym, TAbs.arraySize=sizexp, TAbs.arrayInit=initexp, TAbs.arrayPos=pos}) =
let checkarray typ ty = do (sizegexp, sizety) <- g sizexp
if (sizety == INT)
then do (initgexp, initty) <- g initexp
initty' <- actualTy (TPar.extractPosition initexp) initty
ty' <- actualTy pos ty
if (initty' == ty')
then do gexp <- TTra.createArray sizegexp initgexp
return (gexp, typ)
else throwError $ typeMisMatchError pos (show ty) (show initty)
else throwError $ typeMisMatchError pos (show INT) (show sizety)
in do t <- getTenv
case Map.lookup typsym t of
Just typ@(Array (ty, _)) -> checkarray typ ty
Just typ@(Name _) -> do aty <- actualTy pos typ
case aty of
Array (ty, _) -> checkarray aty ty
_ -> throwError $ typeMisMatchError pos ("Array") (show typsym)
Just typ -> throwError $ typeMisMatchError pos ("Array") (show typ)
Nothing -> throwError $ undefinedError pos (name typsym)
in g absexp
transvar :: TTra.Level -> Maybe TTmp.Label -> TAbs.Var -> SemTr GexpTy
transvar lvl _ (TAbs.SimpleVar(s, pos)) = do v <- getVenv
case Map.lookup s v of
Nothing -> throwError $ undefinedError pos $ name s
Just (VarEntry acc ty _) -> do isptr <- isPointer ty
gexp <- TTra.simpleVar acc lvl isptr
return (gexp, ty)
Just _ -> throwError $ notVariable pos $ name s
transvar lvl lab (TAbs.FieldVar(v, s, pos)) = do (vgexp, vty) <- transvar lvl lab v
vty' <- actualTy (TPar.extractPosition v) vty
case vty' of
Record(symtypairs, _) ->
case findIndex (\(sym, _) -> sym == s) symtypairs of
Nothing -> throwError $ undefinedError pos $ name s
Just idx -> do let ty = snd $ symtypairs !! idx
isptr <- isPointer ty
gexp <- TTra.field vgexp idx isptr
return (gexp, ty)
_ -> throwError $ typeMisMatchError pos ("Record") (show vty')
transvar lvl lab (TAbs.SubscriptVar(v, idxexp, pos)) = do (vgexp, vty) <- transvar lvl lab v
(idxgexp, idxty) <- transexp lvl lab idxexp
idxty' <- actualTy pos idxty
if idxty' == INT
then do vty' <- actualTy (TPar.extractPosition v) vty
case vty' of
Array (innerty, _) -> do
isptr <- isPointer innerty
gexp <- TTra.subscript vgexp idxgexp isptr
return (gexp, innerty)
_ -> throwError $ typeMisMatchError pos ("Array") (show vty)
else throwError $ typeMisMatchError pos (show INT) (show idxty)
transty :: TAbs.Ty -> SemTr Ty
transty (TAbs.NameTy(sym, pos)) =
do t <- getTenv
case Map.lookup sym t of
Nothing -> throwError $ undefinedError pos $ name sym
Just ty -> return ty
transty (TAbs.ArrayTy(sym, pos)) =
do t <- getTenv
case Map.lookup sym t of
Nothing -> throwError $ undefinedError pos $ name sym
Just ty -> do u <- genUniq
return $ Array(ty, u)
transty (TAbs.RecordTy tfields) =
do t <- getTenv
let names = map TAbs.tfieldName tfields
let types = map TAbs.tfieldTyp tfields
let poses = map TAbs.tfieldPos tfields
case findIndex (not . (flip exists t)) types of
Nothing -> do let tys = map (fromJust . (flip Map.lookup t)) types
u <- genUniq
return $ Record (zip names tys, u)
Just idx -> throwError $ undefinedError (poses !! idx) (name $ names !! idx)
where exists typ t = typ `Map.member` t
transprog :: TAbs.Program -> SemTr [Frag]
transprog absyn = let builtintypes = [("string", String), ("int", INT)]
builtinfuncnames = ["chr", "concat", "exit", "flush", "getch"
,"not", "ord", "print", "size", "substring"]
builtinfunctys = [String, String, Unit, Unit,
String, INT, INT, Unit,
INT, String]
builtinparamtys = [[INT], [String, String]
,[INT], [], [], [INT], [String]
,[String], [String]
,[String, INT, INT]]
in
do builtintypsym <- mapM symbol $ map fst builtintypes
mapM_ (uncurry addtypetobinding) (zip builtintypsym $ map snd builtintypes)
builtinfuncsyms <- mapM symbol builtinfuncnames
builtinfunclabs <- mapM namedLabel builtinfuncnames
let builtinfunclvls = take (length builtinfuncsyms) $ repeat TTra.outerMost
let paramtyswithdummyaccess = liftM (map (\ty -> (ty, (TTra.outerMost, 0)))) builtinparamtys
_ <- zipWithM5 addfunctiontobinding builtinfuncsyms builtinfunclvls builtinfunclabs paramtyswithdummyaccess builtinfunctys
case absyn of
TAbs.Pexp e -> do (mainlvl,_) <- TTra.newLevel TTra.outerMost []
(gexp, _) <- transexp mainlvl Nothing e
TTra.createMainFrag mainlvl gexp
frags <- TTra.getResult
return frags
TAbs.Pdecs (ds) -> do (mainlvl,_) <- TTra.newLevel TTra.outerMost []
transprog' mainlvl ds
frags <- TTra.getResult
return frags
where transprog' mainlvl (d:decs) = do (v, t, _) <- transdec mainlvl Nothing d
withBinding v t $ transprog' mainlvl decs
return ()
transprog' _ _ = return ()
| hengchu/tiger-haskell | src/tigersemant.hs | mit | 29,811 | 0 | 29 | 13,196 | 8,486 | 4,180 | 4,306 | 469 | 66 |
module Sgd.Svm.Train where
import qualified Sgd.Svm.Read as R
import Sgd.Num.Vector
import Sgd.Svm.LossFun
type Sample = R.Sample Int
type Model = (FullVector, Double, Double) -- model parameter (w, wDivsor, wBias)
type PredLoss = (Double, Double, Double) -- prediction error on the Model (los, cost, num.error)
{-- TODO: remove
fTest :: [Sample] -> [Sample]
fTest x = x
--}
f x = t
where
t = x + 10
train :: Loss -- loss and dloss function
-> [Sample] -- list of samples
-> Double -- regularizer
-> Int -- epochs
-> Model
train l x lambda epochs = foldl (go) wParam0 [1..epochs]
where
go wParam _ = trainMany (dloss l) x lambda wParam eta
-- daz-li: memory performance tuning,
dim = R.dimSample x
-- dim = 2000
wParam0 = initParam dim
-- daz-li: memory performance tuning,
n = min 1000 . length $ x
-- n = 1000
fTrain = trainMany (dloss l) (take n x) lambda wParam0
fTest = testMany (loss l) (take n x) lambda
eta0 = determineEta0 (fTest . fTrain) (2, 1, 2)
eta = map (\t -> eta0 / (1 + lambda * eta0 * t)) [0..]
initParam :: Int -> Model
initParam dimVar = (rep (dimVar + 1) 0, 1, 0)
determineEta0 :: ([Double] -> PredLoss) -- fTest . fTrain params: given [eta] return PredLoss
-> (Double, Double, Double) -- (factor, lowEta, highEta)
-> Double -- eta
determineEta0 f e@(factor, loEta, hiEta)
| loCost < hiCost = slideEta f e hiCost
| loCost > hiCost = climbEta f e loCost
where
(_, loCost, _) = f $ repeat loEta
(_, hiCost, _) = f $ repeat hiEta
slideEta :: ([Double] -> PredLoss) -- fTest . fTrain params: given [eta] return PredLoss
-> (Double, Double, Double) -- (factor, lowEta, highEta)
-> Double -- highCost
-> Double -- eta
slideEta f (factor, loEta, hiEta) hiCost
| loCost < hiCost = slideEta f (factor, loEta/factor, loEta) loCost
| otherwise = loEta
where
(_, loCost, _) = f $ repeat loEta
climbEta :: ([Double] -> PredLoss) -- fTest . fTrain params: given [eta] return PredLoss
-> (Double, Double, Double) -- (factor, lowEta, highEta)
-> Double -- lowCost
-> Double -- eta
climbEta f (factor, loEta, hiEta) loCost
| loCost > hiCost = climbEta f (factor, hiEta, hiEta*2) hiCost
| otherwise = loEta
where
(_, hiCost, _) = f $ repeat hiEta
trainMany :: (Double -> Double -> Double) -- dloss function
-> [Sample] -- list of samples
-> Double -- regularizer
-> Model -- current model parameter
-> [Double] -- sgd gain eta for each iteration (or sample)
-> Model
trainMany dloss x lambda wParam0 eta = foldl go wParam0 $ zip x eta
where
go wParam (xt, etat) = trainOne dloss xt lambda wParam etat
trainOne :: (Double -> Double -> Double) -- dloss function
-> (SparseVector, Double) -- single input and response (x, y)
-> Double -- regularizer
-> Model -- current model parameter
-> Double -- sgd gain eta
-> Model
trainOne dloss (x, y) lambda (w, wDiv, wBias) eta = (w'', wDiv'', wBias')
where
s = (dotFS w x) / wDiv + wBias
d = dloss s y
wDiv' = wDiv / (1 - eta * lambda)
(w', wDiv'') = renorm w wDiv'
-- TODO should use accumulate function of Vector!
w'' = addFS w' . mul x $ eta * d * wDiv''
wBias' = wBias + d * eta * 0.01;
testMany :: (Double -> Double -> Double) -- loss function
-> [Sample] -- list of samples
-> Double -- regularizer
-> Model -- model parameter
-> PredLoss
testMany loss x lambda wParam = (los, cost, nerr)
where
los = ploss / fromIntegral (length x)
nerr = (fromIntegral pnerr) / fromIntegral (length x)
cost = los + 0.5 * lambda * (wnorm wParam)
(ploss, pnerr) = (\(t1, t2, _) -> (sum t1, sum t2)) . unzip3 . map go $ x
where
go x = testOne loss x lambda wParam
testOne :: (Double -> Double -> Double) -- loss function
-> (SparseVector, Double) -- single input and response (x, y)
-> Double -- regularizer
-> Model -- model parameter
-> (Double, Int, Double)
testOne loss (x, y) lambda (w, wDiv, wBias) = (ploss, pnerr, s)
where
s = (dotFS w x) / wDiv + wBias
ploss = loss s y
pnerr = if s * y <= 0 then 1 else 0
renorm :: FullVector -> Double -> (FullVector, Double)
renorm w wDiv
| wDiv == 1.0 || wDiv <= 1e5 = (w, wDiv)
| otherwise = (scale w $ 1 / wDiv, 1.0)
wnorm (w, wDiv, wBias) = (dot w w ) / wDiv / wDiv
| daz-li/svm_sgd_haskell | src/Sgd/Svm/Train.hs | mit | 5,257 | 0 | 14 | 1,982 | 1,529 | 847 | 682 | 95 | 2 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-|
Copyright : (c) Microsoft
License : MIT
Maintainer : adamsap@microsoft.com
Stability : alpha
Portability : portable
-}
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module Language.Bond.Syntax.Util
( -- * Type classification
-- | Functions that test if a type belongs to a particular category. These
-- functions will resolve type aliases and return answer based on the type
-- the alias resolves to.
isScalar
, isString
, isContainer
, isList
, isAssociative
, isNullable
, isStruct
, isMetaName
-- * Folds
, foldMapFields
, foldMapStructFields
, foldMapType
-- * Helper functions
, resolveAlias
) where
import Data.Maybe
import Data.List
import qualified Data.Foldable as F
import Data.Monoid
import Prelude
import Language.Bond.Util
import Language.Bond.Syntax.Types
-- | Returns 'True' if the type represents a scalar.
isScalar :: Type -> Bool
isScalar BT_Int8 = True
isScalar BT_Int16 = True
isScalar BT_Int32 = True
isScalar BT_Int64 = True
isScalar BT_UInt8 = True
isScalar BT_UInt16 = True
isScalar BT_UInt32 = True
isScalar BT_UInt64 = True
isScalar BT_Float = True
isScalar BT_Double = True
isScalar BT_Bool = True
isScalar (BT_TypeParam (TypeParam _ (Just Value))) = True
isScalar (BT_UserDefined Enum {..} _) = True
isScalar (BT_UserDefined a@Alias {} args) = isScalar $ resolveAlias a args
isScalar _ = False
-- | Returns 'True' if the type represents a meta-name type.
isMetaName :: Type -> Bool
isMetaName BT_MetaName = True
isMetaName BT_MetaFullName = True
isMetaName (BT_UserDefined a@Alias {} args) = isMetaName $ resolveAlias a args
isMetaName _ = False
-- | Returns 'True' if the type represents a string.
isString :: Type -> Bool
isString BT_String = True
isString BT_WString = True
isString (BT_UserDefined a@Alias {} args) = isString $ resolveAlias a args
isString _ = False
-- | Returns 'True' if the type represents a list or a vector.
isList :: Type -> Bool
isList (BT_List _) = True
isList (BT_Vector _) = True
isList (BT_UserDefined a@Alias {} args) = isList $ resolveAlias a args
isList _ = False
-- | Returns 'True' if the type represents a map or a set.
isAssociative :: Type -> Bool
isAssociative (BT_Set _) = True
isAssociative (BT_Map _ _) = True
isAssociative (BT_UserDefined a@Alias {} args) = isAssociative $ resolveAlias a args
isAssociative _ = False
-- | Returns 'True' if the type represents a container.
isContainer :: Type -> Bool
isContainer f = isList f || isAssociative f
-- | Returns 'True' if the type represents a struct.
isStruct :: Type -> Bool
isStruct (BT_UserDefined Struct {} _) = True
isStruct (BT_UserDefined Forward {} _) = True
isStruct (BT_UserDefined a@Alias {} args) = isStruct $ resolveAlias a args
isStruct _ = False
-- | Returns 'True' if the type represents a nullable type.
isNullable :: Type -> Bool
isNullable (BT_Nullable _) = True
isNullable (BT_UserDefined a@Alias {} args) = isNullable $ resolveAlias a args
isNullable _ = False
mapType :: (Type -> Type) -> Type -> Type
mapType f (BT_UserDefined decl args) = BT_UserDefined decl $ map f args
mapType f (BT_Map key value) = BT_Map (f key) (f value)
mapType f (BT_List element) = BT_List $ f element
mapType f (BT_Vector element) = BT_Vector $ f element
mapType f (BT_Set element) = BT_Set $ f element
mapType f (BT_Nullable element) = BT_Nullable $ f element
mapType f (BT_Bonded struct) = BT_Bonded $ f struct
mapType f x = f x
-- | Maps all fields, including fields of the base, to a monoid, and combines
-- the results.
foldMapFields :: (Monoid m) => (Field -> m) -> Type -> m
foldMapFields f t = case t of
(BT_UserDefined Struct {..} _) -> optional (foldMapFields f) structBase <> F.foldMap f structFields
(BT_UserDefined a@Alias {..} args) -> foldMapFields f $ resolveAlias a args
_ -> mempty
-- | Like 'foldMapFields' but takes a 'Declaration' as an argument instead of 'Type'.
foldMapStructFields :: Monoid m => (Field -> m) -> Declaration -> m
foldMapStructFields f s = foldMapFields f $ BT_UserDefined s []
-- | Maps all parts of a 'Type' to a monoid and combines the results.
--
-- E.g. for a type:
--
-- @list\<nullable\<int32>>@
--
-- the result is:
--
-- @ f (BT_List (BT_Nullable BT_Int32)) <> f (BT_Nullable BT_Int32) <> f BT_Int32@
foldMapType :: (Monoid m) => (Type -> m) -> Type -> m
foldMapType f t@(BT_UserDefined _decl args) = f t <> F.foldMap (foldMapType f) args
foldMapType f t@(BT_Map key value) = f t <> foldMapType f key <> foldMapType f value
foldMapType f t@(BT_List element) = f t <> foldMapType f element
foldMapType f t@(BT_Vector element) = f t <> foldMapType f element
foldMapType f t@(BT_Set element) = f t <> foldMapType f element
foldMapType f t@(BT_Nullable element) = f t <> foldMapType f element
foldMapType f t@(BT_Bonded struct) = f t <> foldMapType f struct
foldMapType f x = f x
-- | Resolves a type alias declaration with given type arguments. Note that the
-- function resolves one level of aliasing and thus may return a type alias.
resolveAlias :: Declaration -> [Type] -> Type
resolveAlias Alias {..} args = mapType resolveParam $ resolveParam aliasType
where
resolveParam (BT_TypeParam param) = snd.fromJust $ find ((param ==).fst) paramsArgs
resolveParam x = x
paramsArgs = zip declParams args
resolveAlias _ _ = error "resolveAlias: impossible happened."
| upsoft/bond | compiler/src/Language/Bond/Syntax/Util.hs | mit | 5,536 | 0 | 12 | 1,036 | 1,548 | 801 | 747 | 100 | 3 |
module Median ( median
) where
import Data.List
median :: (Fractional a, Ord a) => [a] -> Maybe a
median xs | null xs = Nothing
| odd len = Just $ sorted !! mid
| even len = Just meanMedian
| otherwise = Nothing
where len = length sorted
mid = len `div` 2
meanMedian = (sorted !! (mid - 1) + sorted !! mid) / 2
sorted = sort xs
| blitzcode/rust-exp | hs-src/Median.hs | mit | 425 | 0 | 13 | 169 | 165 | 84 | 81 | 11 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Language.Sexp.Token where
import Data.Text (Text)
import Data.Text.Lazy (pack, fromStrict)
import Data.Scientific
import Text.PrettyPrint.Leijen.Text
data Token
= TokLParen -- (
| TokRParen -- )
| TokLBracket -- [
| TokRBracket -- ]
| TokQuote -- e.g. '(foo bar)
| TokHash -- e.g. #(foo bar)
| TokSymbol { getSymbol :: !Text } -- foo, bar
| TokKeyword { getKeyword :: !Text } -- :foo, :bar
| TokInt { getInt :: !Integer } -- 42, -1, +100500
| TokReal { getReal :: !Scientific } -- 42.0, -1.0, 3.14, -1e10
| TokStr { getString :: !Text } -- "foo", "", "hello world"
| TokBool { getBool :: !Bool } -- #f, #t
| TokUnknown { getUnknown :: !Char } -- for unknown lexemes
deriving (Show, Eq)
data LocatedBy p a = L !p !a
deriving (Show, Eq, Functor)
{-# INLINE mapPosition #-}
mapPosition :: (p -> p') -> LocatedBy p a -> LocatedBy p' a
mapPosition f (L p a) = L (f p) a
extract :: LocatedBy p a -> a
extract (L _ a) = a
(@@) :: (a -> (p -> b)) -> LocatedBy p a -> b
(@@) f (L p a) = f a p
instance Pretty Token where
pretty TokLParen = "left paren '('"
pretty TokRParen = "right paren ')'"
pretty TokLBracket = "left bracket '['"
pretty TokRBracket = "right bracket '['"
pretty TokQuote = "quote \"'\""
pretty TokHash = "hash '#'"
pretty (TokSymbol s) = "symbol" <+> dquote <> text (fromStrict s) <> dquote
pretty (TokKeyword k) = "keyword" <+> dquote <> text (fromStrict k) <> dquote
pretty (TokInt n) = "integer" <+> integer n
pretty (TokReal n) = "real number" <+> text (pack (show n))
pretty (TokStr s) = "string" <+> text (pack (show s))
pretty (TokBool b) = "boolean" <+> if b then "#t" else "#f"
pretty (TokUnknown u) = "unknown lexeme" <+> text (pack (show u))
| ricardopenyamari/ir2haskell | clir-parser-haskell-master/lib/sexp-grammar/src/Language/Sexp/Token.hs | gpl-2.0 | 2,006 | 0 | 11 | 561 | 627 | 340 | 287 | 64 | 1 |
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses #-}
module Lambda.Backward_Join where
import Lambda.Type
import Lambda.Tree ( peng )
import qualified Lambda.Backward_Join.Instance as I
import qualified Lambda.Backward_Join.Solution as S
import Lambda.Step
import Lambda.Alpha
import Challenger.Partial
import Inter.Types
import Autolib.ToDoc
import Autolib.Size
import Autolib.Reporter
import Data.Typeable
data Lambda_Backward_Join = Lambda_Backward_Join
deriving ( Read, Show, Typeable )
instance OrderScore Lambda_Backward_Join where
scoringOrder _ = Increasing
instance Measure Lambda_Backward_Join I.Type S.Type where
measure p inst sol = fromIntegral $ size $ S.start sol
instance Partial Lambda_Backward_Join I.Type S.Type where
report p inst = do
inform $ vcat
[ text "gesucht ist ein Term t"
, text "mit t ->^*" <+> toDoc ( I.left_goal inst )
, text "und t ->^*" <+> toDoc ( I.right_goal inst )
]
inform $ vcat
[ text "Sie sollen jeweils auch die Ableitungen angeben."
, text "Dabei wird jeder Schritt durch eine Nummer"
, text "aus einer Liste von möglichen Schritten bezeichnet."
]
initial p inst = S.example
total p inst sol = do
verify_derivation "linke"
( S.start sol ) ( S.left_steps sol ) ( I.left_goal inst )
verify_derivation "rechte"
( S.start sol ) ( S.right_steps sol ) ( I.right_goal inst )
verify_derivation tag start steps goal = do
inform $ fsep [ text "prüfe", text tag, text "Ableitung" ]
final <- nested 4 $ derive start steps
assert ( Lambda.Alpha.convertible final goal )
$ vcat [ text "ist alpha-konvertierbar zu", nest 4 $ toDoc goal ]
make_fixed :: Make
make_fixed = direct Lambda_Backward_Join I.example
| Erdwolf/autotool-bonn | src/Lambda/Backward_Join.hs | gpl-2.0 | 1,852 | 4 | 15 | 448 | 490 | 249 | 241 | 43 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
module Algebraic.Multiset where
import qualified Algebraic.Set.Multi as M
import qualified Autolib.TES.Binu as B
import Algebraic2.Class
import Algebraic2.Instance as AI
import Condition
import Autolib.ToDoc
import Autolib.Choose
import Autolib.Reader
import Autolib.Size
import Autolib.Reporter
import Autolib.FiniteMap
import Data.Typeable
data Algebraic_Multiset = Algebraic_Multiset
deriving ( Read, Show, Typeable )
derives [makeReader][''Algebraic_Multiset]
data Restriction = None deriving Typeable
derives [makeReader,makeToDoc][''Restriction]
instance Condition Restriction (M.Multiset a)
instance Algebraic Algebraic_Multiset () ( M.Multiset M.Identifier ) where
-- evaluate :: tag -> Exp a -> Reporter a
evaluate tag bel exp = do
v <- tfoldB bel inter exp
inform $ vcat [ text "Der Wert Ihres Terms ist"
, nest 4 $ toDoc v
]
return v
-- equivalent :: tag -> a -> a -> Reporter Bool
equivalent tag a b = do
inform $ text "stimmen die Werte überein?"
let d = M.symmetric_difference a b
ok = M.null d
when ( not ok ) $ reject $ vcat
[ text "Nein, die symmetrische Differenzmenge ist"
, nest 4 $ toDoc d
]
return ok
-- some_formula :: tag -> Algebraic.Instance.Type a -> Exp a
some_formula tag i = read "A + (B & C)"
roll_value tag i =
M.roll (map (M.Identifier . return) ['p' .. 'u' ]) 5
default_context tag = ()
-- default_instance :: tag -> Algebraic.Instance.Type a
default_instance tag = AI.Make
{ target = read "{p:2,q:3}"
, context = ()
, description = Nothing
, operators = default_operators tag
, predefined = listToFM
[ (read "A", read "{p:1, q:2}" )
, (read "B", read "{q:1, r:3}" )
, (read "C", read "{p:2, s:4}" )
]
, max_size = 12
}
default_operators tag = bops
| marcellussiegburg/autotool | collection/src/Algebraic/Multiset.hs | gpl-2.0 | 2,086 | 25 | 11 | 546 | 497 | 277 | 220 | 52 | 0 |
module QuickPlot (
module QuickPlot.IPC.QQ
, runQuickPlot
, runQuickPlotWith
, Plottable (..)
, plot
, clear
, toJSON
) where
import QuickPlot.IPC.Server
import QuickPlot.IPC.QQ
import QuickPlot.IPC.Protocol
import Data.Aeson
-- | Port the QuickPlot server is supposed to use
type Port = Int
-- | Directory path of the QuickPlot client files
type UserDirectory = FilePath
-- TODO: Load scripts from custom directory into the real index.html
-- | Start a QuickPlot server
-- Run this function only once in a ghci session (even after reload)
runQuickPlotWith :: UserDirectory -- ^ Path to directory with user scripts (doesn't work)
-> Port -- ^ Port of the QuickPlot server
-> IO ()
runQuickPlotWith = runServer
-- | Start a QuickPlot server at "http://localhost:8000"
-- Run this function only once in a ghci session (even after reload)
runQuickPlot :: IO ()
runQuickPlot = runQuickPlotWith "" 8000
-- | Remove all plots in the browser
-- If the browser is not connected by now the behaviour is undefined
clear :: IO ()
clear = sendMessage (QPMessage QuickPlot Clear Null)
-- | Show data visualizations in the browser
-- If the browser is not connected to QuickPlot a warning will be printed to stdout
plot :: (Plottable p)
=> p -- ^ JSON that can be visualized
-> IO ()
plot content = sendMessage (QPMessage (whichLibrary content) NewPlot (plottableToJSON content))
-- All the instances of the class are plottable and should be encoded in a JSON structure
-- that the library can process
class Plottable a where
-- | Convert to Aeson's Value
plottableToJSON :: a -> Value
-- | Which library should be used to visualize the data
whichLibrary :: a -> Library
| tepf/QuickPlot | src/QuickPlot.hs | gpl-3.0 | 1,782 | 0 | 9 | 404 | 242 | 143 | 99 | 29 | 1 |
instance Eq Point where
(Pt x y) == (Pt x' y') = x == x' && y == y' | hmemcpy/milewski-ctfp-pdf | src/content/1.7/code/haskell/snippet12.hs | gpl-3.0 | 71 | 0 | 8 | 22 | 48 | 23 | 25 | 2 | 0 |
module Main where
import System.Random
import System.Environment (getArgs, getProgName)
import Utils
import HACDetRNG
import HACAgent as Agent
import qualified HACFrontend as Front
import qualified HACSimulation as Sim
import qualified HACSimulationImpl as SimImpl
-----------------------------------------------------------------------------------------------------------------------
-- IO-Driven Simulation
-----------------------------------------------------------------------------------------------------------------------
main :: IO ()
main = do
let dt = 0.025
let wt = Border -- Infinite | Border | Wraping
let agentCount = 500
let heroDist = 0.25
let rngSeed = 42
let rng = mkStdGen rngSeed
let (agents, rng') = Agent.createRandAgentStates rng agentCount heroDist
let simIn = Sim.SimIn { Sim.simInInitAgents = agents, Sim.simInWorldType = wt }
Front.initialize
SimImpl.simulationIO simIn (render dt wt)
Front.shutdown
-----------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
-- Step-Driven Simulation
-----------------------------------------------------------------------------------------------------------------------
{-
main :: IO ()
main = do
let dt = 0.01
let wt = Border -- Infinite | Border | Wraping
let agentCount = 1000
let heroDist = 0.25
let rngSeed = 42
let rng = mkStdGen rngSeed
let (agents, rng') = Agent.createRandAgentStates rng agentCount heroDist
let simIn = Sim.SimIn { Sim.simInInitAgents = agents, Sim.simInWorldType = wt }
let steps = 1000
Front.initialize
-- NOTE: this won't lead to "long numbercrunching" when stepCount is high because of haskells lazyness. Just an
-- unevaluated array will be returned and then when rendering the steps the required list-element will be
-- calculated by the simulation.
let outs = SimImpl.simulationStep simIn dt steps
freezeRender wt (last outs)
Front.shutdown
-}
-----------------------------------------------------------------------------------------------------------------------
render :: Double -> Agent.WorldType -> Sim.SimOut -> IO (Bool, Double)
render dt wt simOut = do
let aos = Sim.simOutAgents simOut
winOpen <- Front.renderFrame aos wt
return (winOpen, dt)
-- NOTE: used to freeze a given output: render it until the window is closed
freezeRender :: Agent.WorldType -> Sim.SimOut -> IO (Bool, Double)
freezeRender wt simOut = do
(cont, _) <- render 0.0 wt simOut
if cont then
freezeRender wt simOut
else
return (False, 0.0)
renderOutputs :: [Sim.SimOut] -> Agent.WorldType -> IO (Bool, Double)
renderOutputs (s:xs) wt
| null xs = return (True, 0.0)
| otherwise = do
(cont, dt) <- render 0.0 wt s
if cont then
renderOutputs xs wt
else
return (True, 0.0)
-----------------------------------------------------------------------------------------------------------------------
-- Testing Rendering --
-----------------------------------------------------------------------------------------------------------------------
{-
main :: IO ()
main = do
let dt = 0.5
let as = createTestAgents
let aos' = createTestAgentOuts
Front.initialize
let wt = Border
let simIn = Sim.SimIn { Sim.simInInitAgents = as, Sim.simInWorldType = wt }
let outs = SimImpl.simulationStep simIn dt 1
freezeRender wt (head outs)
Front.shutdown
-}
createTestAgents :: [Agent.AgentState]
createTestAgents = [a1, a2, a3]
where
a1 = Agent.AgentState { agentId = 0,
agentPos = (0.5, 0.25),
enemy = 2,
friend = 1,
hero = True }
a2 = Agent.AgentState { agentId = 1,
agentPos = (0.75, 0.75),
enemy = 2,
friend = 0,
hero = True }
a3 = Agent.AgentState { agentId = 2,
agentPos = (0.25, 0.75),
enemy = 1,
friend = 0,
hero = False }
createTestAgentOuts :: [Agent.AgentOut]
createTestAgentOuts = [ao1, ao2, ao3]
where
ao1 = Agent.AgentOut{ agentOutState = Agent.AgentState { agentId = 0,
agentPos = (0.25, 0.5),
enemy = 1,
friend = 2,
hero = True},
agentOutDir = (-1.0, 0.0) }
ao2 = Agent.AgentOut{ agentOutState = Agent.AgentState { agentId = 1,
agentPos = (0.2, 0.2),
enemy = 0,
friend = 2,
hero = True},
agentOutDir = (1.0, 0.0) }
ao3 = Agent.AgentOut{ agentOutState = Agent.AgentState { agentId = 2,
agentPos = (0.3, 0.3),
enemy = 0,
friend = 1,
hero = True},
agentOutDir = (1.0, 0.0) }
| thalerjonathan/phd | coding/prototyping/haskell/HerosAndCowards/src/Main.hs | gpl-3.0 | 5,727 | 0 | 11 | 1,975 | 891 | 516 | 375 | 78 | 2 |
{-
Python5 — a hypothetic language
Copyright (C) 2015 - Yuriy Syrovetskiy
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 3 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, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE NamedFieldPuns #-}
import Data.List ( delete, isSuffixOf )
import Python5.Builtin
import System.Directory ( getDirectoryContents, setCurrentDirectory )
import System.Environment ( getEnvironment )
import System.FilePath ( (</>) )
import System.Process ( CreateProcess(env), proc, readCreateProcess )
import Test.Tasty ( defaultMain, testGroup )
import Test.Tasty.HUnit ( (@?=), testCase )
examplesDir :: String
examplesDir = "examples"
testInput :: String
testInput = "TEST INPUT"
expectedOutput :: Dict String String
expectedOutput = dict
[ "calc.hs" := "0.5\n8\n5.666666666666667\n5\n"
, "control.hs" := "The product is: 384\n"
, "data.hs" := unlines [ "[BANANA, APPLE, LIME]"
, "[(0, Banana), (1, Apple), (2, Lime)]" ]
, "dict.hs" := "3\n"
, "functions.hs" := "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 \n"
, "io.hs" := "Hello, I'm Python5!\nWhat is your name?\nHi, TEST INPUT.\n"
, "types.hs" := "ValueError ()\n"
]
main :: IO ()
main = do
setCurrentDirectory ".." -- to the project dir
files <- getDirectoryContents examplesDir
let hsFiles = filter (".hs" `isSuffixOf`) files
let examples = delete "Test.hs" hsFiles
defaultMain $
testGroup "examples"
[ testCase ex $ do
result <- python5 (examplesDir </> ex) testInput
Just result @?= get(ex) expectedOutput
| ex <- examples ]
python5 :: String -> String -> IO String
python5 scriptFile stdinContent = do
curEnv <- getEnvironment
let cmd = "bin" </> "python5"
args = [scriptFile]
env = Just $ curEnv ++ [("PYTHON5_LOCALTEST", "1")]
processInfo = (proc cmd args){env}
readCreateProcess processInfo stdinContent
| cblp/python5 | python5/tests/Examples.hs | gpl-3.0 | 2,545 | 1 | 16 | 620 | 439 | 237 | 202 | 43 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Blogger.Pages.Revert
-- Copyright : (c) 2015-2016 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)
--
-- Reverts a published or scheduled page to draft state.
--
-- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API v3 Reference> for @blogger.pages.revert@.
module Network.Google.Resource.Blogger.Pages.Revert
(
-- * REST Resource
PagesRevertResource
-- * Creating a Request
, pagesRevert
, PagesRevert
-- * Request Lenses
, pagXgafv
, pagUploadProtocol
, pagAccessToken
, pagUploadType
, pagBlogId
, pagPageId
, pagCallback
) where
import Network.Google.Blogger.Types
import Network.Google.Prelude
-- | A resource alias for @blogger.pages.revert@ method which the
-- 'PagesRevert' request conforms to.
type PagesRevertResource =
"v3" :>
"blogs" :>
Capture "blogId" Text :>
"pages" :>
Capture "pageId" Text :>
"revert" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] Page
-- | Reverts a published or scheduled page to draft state.
--
-- /See:/ 'pagesRevert' smart constructor.
data PagesRevert =
PagesRevert'
{ _pagXgafv :: !(Maybe Xgafv)
, _pagUploadProtocol :: !(Maybe Text)
, _pagAccessToken :: !(Maybe Text)
, _pagUploadType :: !(Maybe Text)
, _pagBlogId :: !Text
, _pagPageId :: !Text
, _pagCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PagesRevert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pagXgafv'
--
-- * 'pagUploadProtocol'
--
-- * 'pagAccessToken'
--
-- * 'pagUploadType'
--
-- * 'pagBlogId'
--
-- * 'pagPageId'
--
-- * 'pagCallback'
pagesRevert
:: Text -- ^ 'pagBlogId'
-> Text -- ^ 'pagPageId'
-> PagesRevert
pagesRevert pPagBlogId_ pPagPageId_ =
PagesRevert'
{ _pagXgafv = Nothing
, _pagUploadProtocol = Nothing
, _pagAccessToken = Nothing
, _pagUploadType = Nothing
, _pagBlogId = pPagBlogId_
, _pagPageId = pPagPageId_
, _pagCallback = Nothing
}
-- | V1 error format.
pagXgafv :: Lens' PagesRevert (Maybe Xgafv)
pagXgafv = lens _pagXgafv (\ s a -> s{_pagXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pagUploadProtocol :: Lens' PagesRevert (Maybe Text)
pagUploadProtocol
= lens _pagUploadProtocol
(\ s a -> s{_pagUploadProtocol = a})
-- | OAuth access token.
pagAccessToken :: Lens' PagesRevert (Maybe Text)
pagAccessToken
= lens _pagAccessToken
(\ s a -> s{_pagAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pagUploadType :: Lens' PagesRevert (Maybe Text)
pagUploadType
= lens _pagUploadType
(\ s a -> s{_pagUploadType = a})
pagBlogId :: Lens' PagesRevert Text
pagBlogId
= lens _pagBlogId (\ s a -> s{_pagBlogId = a})
pagPageId :: Lens' PagesRevert Text
pagPageId
= lens _pagPageId (\ s a -> s{_pagPageId = a})
-- | JSONP
pagCallback :: Lens' PagesRevert (Maybe Text)
pagCallback
= lens _pagCallback (\ s a -> s{_pagCallback = a})
instance GoogleRequest PagesRevert where
type Rs PagesRevert = Page
type Scopes PagesRevert =
'["https://www.googleapis.com/auth/blogger"]
requestClient PagesRevert'{..}
= go _pagBlogId _pagPageId _pagXgafv
_pagUploadProtocol
_pagAccessToken
_pagUploadType
_pagCallback
(Just AltJSON)
bloggerService
where go
= buildClient (Proxy :: Proxy PagesRevertResource)
mempty
| brendanhay/gogol | gogol-blogger/gen/Network/Google/Resource/Blogger/Pages/Revert.hs | mpl-2.0 | 4,647 | 0 | 19 | 1,178 | 779 | 452 | 327 | 114 | 1 |
import Primes
import System.Environment
import System.Random
main = do x <- getArgs
seed <- newStdGen
print $ isPrime seed $ rInteger $ head x
rInteger :: String -> Integer
rInteger = read | pernas/Primes | isprime.hs | unlicense | 211 | 1 | 10 | 54 | 71 | 34 | 37 | 8 | 1 |
{-# OPTIONS_GHC -Wall -Werror #-}
module ChapterExercises_7 where
import Control.Applicative
import Text.Trifecta
import Data.Word
import Numeric
import Data.Bits
import Test.Hspec
import Test.HUnit
import ParseTestCaseHelpers
import qualified ChapterExercises_6 as IPv4
data IPAddress6 = IPAddress6 Word64 Word64
deriving (Eq, Ord)
-- Show IPAddress6 in expanded form
instance Show IPAddress6 where
show (IPAddress6 w1 w2) =
let sg :: Word64 -> Int -> String
sg w i = showHex (shiftR w (16*i)
.&. (toEnum . fromEnum) (maxBound :: Word16)) ""
in sg w1 3 ++ ":" ++ sg w1 2 ++ ":" ++ sg w1 1 ++ ":" ++ sg w1 0
++ ":" ++ sg w2 3 ++ ":" ++ sg w2 2 ++ ":" ++ sg w2 1 ++ ":"
++ sg w2 0
ipv6toInteger :: IPAddress6 -> Integer
ipv6toInteger (IPAddress6 w1 w2) =
((65536 ^ (4::Integer)) * (toInteger w1))
+ ((65536 ^ (0::Integer)) * (toInteger w2))
parseIPAddress6 :: Parser IPAddress6
parseIPAddress6 = parseIPv6Sections >>= return . calcIPAddress6
calcIPAddress6 :: [IPv6Section] -> IPAddress6
calcIPAddress6 s =
let sExp = expandIPv6Sections s
calculateGroups :: [IPv6Section] -> (Word64, Integer)
calculateGroups secs =
foldr (\(Group i) (w, p) -> (w + ( (toEnum $ fromEnum i)
* (65536 ^ p)),p+1)) (0,0) secs
(firstWord64, _) = calculateGroups (take 4 sExp)
(secondWord64, _) = calculateGroups (drop 4 sExp)
in IPAddress6 firstWord64 secondWord64
-- Assumes only one 'Collapse' exists
expandIPv6Sections :: [IPv6Section] -> [IPv6Section]
expandIPv6Sections sections =
let maxSize = 8
s = length sections
zg = replicate (maxSize + 1 - s) $ Group 0
in foldr (\sec ac -> if sec == Collapse
then zg ++ ac
else (sec:ac)) [] sections
data IPv6Section = Group Word16 | Collapse
deriving (Eq, Show)
parseIPv6Sections :: Parser [IPv6Section]
parseIPv6Sections = do
-- Parse a list of Groups and Collapses as is.
start <- ( (do IPv6Group x <- parseIPv6Group
pure $ Group x)
<* char ':'
<|> (string "::" >> pure Collapse)
) <?> "Start of IPv6"
middle <- many $ try (
(do IPv6Group x <- parseIPv6Group
pure $ Group x)
<* char ':'
<|> (char ':' >> pure Collapse)
) <?> "Middle of IPv6"
end <- ( (do IPv6Group x <- parseIPv6Group
pure $ Group x)
<|> (char ':' >> pure Collapse)
) <?> "End of IPv6"
let sl = [start] ++ middle ++ [end]
-- If more than one Collapse exists then we have a problem
if (foldr (\s acc -> if (s == Collapse)
then acc+1
else acc) (0::Int) sl) > 1
then unexpected "Too many collapsed sections"
else return ()
if length sl > 16
then unexpected "Too many sections"
else return ()
return sl
newtype IPv6Group = IPv6Group Word16
deriving (Eq, Ord, Show)
parseIPv6Group :: Parser IPv6Group
parseIPv6Group = do
-- Take dangerous shortcuts to get parsed hex value.
s <- some hexDigit :: Parser String
if length s > 4
then unexpected $ "Group of (" ++ (show $ length s)
++ ") size is too large"
else return ()
let ((g,_):_) = readHex s :: [(Integer, String)]
return $ IPv6Group $ toEnum $ fromInteger g
-- Run a series of simple parsing tests
-- with fixed inputs and fixed expected results
parserTests :: IO ()
parserTests = do
putStrLn "\nTesting IPv6 parser:"
parseFailCase parseIPv6Group ""
parseFailCase parseIPv6Group ":"
parseSuccessCase parseIPv6Group "0000" $ IPv6Group 0
parseSuccessCase parseIPv6Group "000a" $ IPv6Group 10
parseSuccessCase parseIPv6Group "00fa" $ IPv6Group 250
parseSuccessCase parseIPv6Group "10fa" $ IPv6Group 4346
parseFailCase parseIPv6Group "11111"
parseSuccessCase parseIPv6Sections "0000:001" $ [Group 0, Group 1]
parseSuccessCase parseIPv6Sections "0000:1:001" $
[Group 0, Group 1, Group 1]
parseSuccessCase parseIPv6Sections "0000:1::001" $
[Group 0, Group 1, Collapse, Group 1]
parseSuccessCase parseIPv6Sections "0000:1::001" $
[Group 0, Group 1, Collapse, Group 1]
parseFailCase parseIPv6Sections "1:1::1::11"
-- Tests other non parsing functions
testIPv6Helpers :: IO ()
testIPv6Helpers = hspec $ -- do
describe "IPv6" $ do
it "Expanding collapsed IPv6Section (middle)" $
let d = [Group 1, Collapse, Group 1]
in expandIPv6Sections d
@?=
[ Group 1, Group 0, Group 0, Group 0
, Group 0, Group 0, Group 0, Group 1
]
it "Expanding collapsed IPv6Section (start)" $
let d = [Collapse, Group 100, Group 1]
in expandIPv6Sections d
@?=
[ Group 0, Group 0, Group 0, Group 0
, Group 0, Group 0, Group 100, Group 1
]
it "Expanding collapsed IPv6Section (end)" $
let d = [Group 1002, Group 1, Collapse]
in expandIPv6Sections d
@?=
[ Group 1002, Group 1, Group 0, Group 0
, Group 0, Group 0, Group 0, Group 0
]
it "calculate '::1' IPv6 value" $
let d = [Collapse, Group 1]
in calcIPAddress6 d `shouldBe` IPAddress6 0 1
it "calculate '::2' IPv6 value" $
let d = [Collapse, Group 2]
in calcIPAddress6 d `shouldBe` IPAddress6 0 2
it "calculate '::0' IPv6 value" $
let d = [Collapse, Group 0]
in calcIPAddress6 d `shouldBe` IPAddress6 0 0
it "calculate '0:ffff:cc78:f:0:ffff:ac10:fe01' IPv6 value" $
let d = [ Group 0, Group 65535, Group 52344, Group 15
, Group 0, Group 65535, Group 44048, Group 65025 ]
in calcIPAddress6 d `shouldBe`
IPAddress6 281474112159759 281473568538113
it "'0:0:0:0:0:ffff:ac10:fe01' IPv6 to decimal" $ do
let (Success p) =
parseString parseIPAddress6 mempty "0:0:0:0:0:ffff:ac10:fe01"
ipv6toInteger p `shouldBe` 281473568538113
it "'0:0:0:0:0:ffff:cc78:f' IPv6 to decimal" $ do
let (Success p) =
parseString parseIPAddress6 mempty "0:0:0:0:0:ffff:cc78:f"
ipv6toInteger p `shouldBe` 281474112159759
it "'FE80:0000:0000:0000:0202:B3FF:FE1E:8329' IPv6 to decimal" $ do
let (Success p) =
parseString parseIPAddress6 mempty
"FE80:0000:0000:0000:0202:B3FF:FE1E:8329"
ipv6toInteger p `shouldBe` 338288524927261089654163772891438416681
it "'2001:DB8::8:800:200C:417A' IPv6 to decimal" $ do
let (Success p) =
parseString parseIPAddress6 mempty "2001:DB8::8:800:200C:417A"
ipv6toInteger p `shouldBe` 42540766411282592856906245548098208122
it "'FE80::0202:B3FF:FE1E:8329' IPv6 to decimal" $ do
let (Success p) =
parseString parseIPAddress6 mempty "FE80::0202:B3FF:FE1E:8329"
ipv6toInteger p `shouldBe` 338288524927261089654163772891438416681
it "'::4' IPv6 to decimal" $ do
let (Success p) = parseString parseIPAddress6 mempty "::4"
ipv6toInteger p `shouldBe` 4
toIPAddress6 :: IPv4.IPAddress -> IPAddress6
toIPAddress6 (IPv4.IPAddress w) =
let ffff :: Word64
ffff = (toEnum . fromEnum) (maxBound :: Word16)
in IPAddress6 0 ((shiftL ffff 32) + ((toEnum . fromEnum) w))
| dmp1ce/Haskell-Programming-Exercises | Chapter 24/src/ChapterExercises_7.hs | unlicense | 7,394 | 0 | 22 | 2,066 | 2,270 | 1,122 | 1,148 | 167 | 4 |
import Data.Char
data Operator = Plus | Minus | Times | Div
deriving (Show, Eq)
data Token = TokOp Operator
| TokAssign
| TokLParen
| TokRParen
| TokIdent String
| TokNum Double
| TokEnd
deriving (Show, Eq)
operator :: Char -> Operator
operator c | c == '+' = Plus
| c == '-' = Minus
| c == '*' = Times
| c == '/' = Div
tokenize :: String -> [Token]
tokenize [] = []
tokenize (c : cs)
| elem c "+-*/" = TokOp (operator c) : tokenize cs
| c == '=' = TokAssign : tokenize cs
| c == '(' = TokLParen : tokenize cs
| c == ')' = TokRParen : tokenize cs
| isDigit c = number c cs
| isAlpha c = identifier c cs
| isSpace c = tokenize cs
| otherwise = error $ "Cannot tokenize " ++ [c]
identifier :: Char -> String -> [Token]
identifier c cs = let (name, cs') = span isAlphaNum cs in
TokIdent (c:name) : tokenize cs'
number :: Char -> String -> [Token]
number c cs =
let (digs, cs') = span isDigit cs in
TokNum (read (c : digs)) : tokenize cs'
---- parser ----
data Tree = SumNode Operator Tree Tree
| ProdNode Operator Tree Tree
| AssignNode String Tree
| UnaryNode Operator Tree
| NumNode Double
| VarNode String
deriving Show
lookAhead :: [Token] -> Token
lookAhead [] = TokEnd
lookAhead (t:ts) = t
accept :: [Token] -> [Token]
accept [] = error "Nothing to accept"
accept (t:ts) = ts
expression :: [Token] -> (Tree, [Token])
expression toks =
let (termTree, toks') = term toks
in
case lookAhead toks' of
(TokOp op) | elem op [Plus, Minus] ->
let (exTree, toks'') = expression (accept toks')
in (SumNode op termTree exTree, toks'')
TokAssign ->
case termTree of
VarNode str ->
let (exTree, toks'') = expression (accept toks')
in (AssignNode str exTree, toks'')
_ -> error "Only variables can be assigned to"
_ -> (termTree, toks')
term :: [Token] -> (Tree, [Token])
term toks =
let (facTree, toks') = factor toks
in
case lookAhead toks' of
(TokOp op) | elem op [Times, Div] ->
let (termTree, toks'') = term (accept toks')
in (ProdNode op facTree termTree, toks'')
_ -> (facTree, toks')
factor :: [Token] -> (Tree, [Token])
factor toks =
case lookAhead toks of
(TokNum x) -> (NumNode x, accept toks)
(TokIdent str) -> (VarNode str, accept toks)
(TokOp op) | elem op [Plus, Minus] ->
let (facTree, toks') = factor (accept toks)
in (UnaryNode op facTree, toks')
TokLParen ->
let (expTree, toks') = expression (accept toks)
in
if lookAhead toks' /= TokRParen
then error "Missing right parenthesis"
else (expTree, accept toks')
_ -> error $ "Parse error on token: " ++ show toks
parse :: [Token] -> Tree
parse toks = let (tree, toks') = expression toks
in
if null toks'
then tree
else error $ "Leftover tokens: " ++ show toks'
main = (print . parse . tokenize) "x1 = -15 / (2 + x2)"
| egaburov/funstuff | Haskell/BartoszBofH/8_Parser/parser_gold.hs | apache-2.0 | 3,296 | 64 | 12 | 1,129 | 1,208 | 637 | 571 | 89 | 6 |
-- -*- coding: utf-8; -*-
module Text where
import Data.Char
import Data.List
import Model
import qualified Data.Map as Map
replaceChars :: Map.Map Char String -> String -> String
replaceChars rules =
let f :: Char -> String -> String
f c acc = case (Map.lookup c rules) of
Just s -> s ++ acc
Nothing -> c : acc
in foldr f ""
replaceString :: Map.Map String String -> String -> String
replaceString rules "" = ""
replaceString rules str =
case applyReplaceStringRules (Map.toList rules) str of
([],c:cs) -> c : replaceString rules cs
(v,s) -> v ++ replaceString rules s
applyReplaceStringRules [] str = ([],str)
applyReplaceStringRules ((k,v):rs) str | isPrefixOf k str = (v,drop (length k) str)
applyReplaceStringRules (_:rs) str = applyReplaceStringRules rs str
replaceCharPair :: Map.Map Char (String,String) -> String -> String
replaceCharPair _ "" = ""
replaceCharPair rules (c:acc) =
case (c, break (c ==) acc) of
(_,(wrappedtext,_:acc')) ->
case (Map.lookup c rules) of
Just (b,e) -> b ++ replaceCharPair rules wrappedtext ++ e ++ replaceCharPair rules acc'
Nothing -> c : replaceCharPair rules acc
_ -> c : replaceCharPair rules acc
onlyAscii = filter (\c -> ord c < 128)
onlyLowUnicode = filter (\c -> ord c < 9216)
newLineAsSpace :: String -> String
newLineAsSpace =
let f :: Char -> String -> String
f c acc =
case c of
'\n' -> ' ' : acc
_ -> c:acc
in foldr f ""
dashBetweenDigits :: String -> String
dashBetweenDigits "" = ""
dashBetweenDigits (a:'-':b:acc) | isDigit a && isDigit b = a : "{\\raise0.2ex\\hbox{-}}" ++ dashBetweenDigits (b:acc)
dashBetweenDigits (c:acc) = c:dashBetweenDigits acc
identifierChars = [ConnectorPunctuation,DecimalNumber,
LowercaseLetter,UppercaseLetter]
colored :: String -> String
colored =
let f :: Char -> String -> String
f c acc =
case (c, break (\x -> generalCategory x /= generalCategory (head acc) &&
not (generalCategory x `elem` identifierChars &&
generalCategory (head acc) `elem` identifierChars)) acc) of
('⒢',(w,acc')) -> "{\\color{green}" ++ w ++ "}" ++ acc'
('⒭',(w,acc')) -> "{\\color{red}" ++ w ++ "}" ++ acc'
('⒝',(w,acc')) -> "{\\color{blue}" ++ w ++ "}" ++ acc'
('⒞',(w,acc')) -> "{\\color{cyan}" ++ w ++ "}" ++ acc'
('⒨',(w,acc')) -> "{\\color{magenta}" ++ w ++ "}" ++ acc'
('⒩',(w,acc')) -> "{\\color{brown}" ++ w ++ "}" ++ acc'
_ -> c:acc
in foldr f ""
coloredPrefix :: String -> [String] -> String -> String
coloredPrefix color prefixes str =
case take 1 $ intersect (reverse.take 50.inits$str) prefixes of
[prefix] -> "{\\color{"++color++"}"++prefix++"}"++ drop (length prefix) str
_ -> str
addColor :: String -> [String] -> String -> String
addColor color words str =
let f c cs = coloredPrefix color words (c:cs)
in foldr f "" str
srcSize "1" _ = "Huge"
srcSize "2" _ = "huge"
srcSize "3" _ = "LARGE"
srcSize "4" _ = "Large"
srcSize "5" _ = "large"
srcSize "6" _ = "normalsize"
srcSize "7" _ = "small"
srcSize "8" _ = "footnotesize"
srcSize "9" _ = "scriptsize"
srcSize "10" _ = "tiny"
srcSize "auto" content = autoSrcSize (onlyAscii content)
srcSize _ content = autoSrcSize (onlyAscii content)
autoSrcSize content =
let lns = lines content
height = floor $ 1.1 * fromIntegral (length lns)
width = maximum $ map (length . filter (\c -> ord c < 256)) lns
in
if width <= 45 && height <= 15 then "Large"
else if width <= 55 && height <= 18 then "large"
else if width <= 65 && height <= 21 then "normalsize"
else if width <= 72 && height <= 23 then "small"
else if width <= 82 && height <= 27 then "footnotesize"
else if width <= 90 && height <= 33 then "scriptsize"
else "tiny"
divideLongLine n line =
case (splitAt n line) of
(x,"") -> x
(x,y) -> x ++ "\n" ++ divideLongLine n y
divideLongLines n = unlines . map (divideLongLine n) . lines
onlyPrefixed :: [String] -> String -> String
onlyPrefixed prefixes = unlines . filter (/="") . map (onlyPrefixedLine prefixes) . lines
onlyPrefixedLine :: [String] -> String -> String
onlyPrefixedLine (prefix:prefixes) line | isPrefixOf prefix line = drop (length prefix) line
onlyPrefixedLine (_:prefixes) line = onlyPrefixedLine prefixes line
onlyPrefixedLine [] line = ""
boldPrefixed :: [String] -> String -> String
boldPrefixed prefixes = unlines . map (boldPrefixedLine prefixes) . lines
boldPrefixedLine :: [String] -> String -> String
boldPrefixedLine (prefix:prefixes) line | isPrefixOf prefix line =
let prefixLength = length prefix
in take prefixLength line ++ "\\textbf{" ++ drop prefixLength line ++ "}"
boldPrefixedLine (_:prefixes) line = boldPrefixedLine prefixes line
boldPrefixedLine [] line = line
| grzegorzbalcerek/orgmode | Text.hs | bsd-2-clause | 4,983 | 0 | 21 | 1,190 | 1,941 | 999 | 942 | 112 | 7 |
{-# LANGUAGE CPP, UnboxedTuples, MagicHash, DeriveDataTypeable #-}
-- |
-- Module : Data.Primitive.Types
-- Copyright : (c) Roman Leshchinskiy 2009-2012
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Portability : non-portable
--
-- Basic types and classes for primitive array operations
--
module Data.Primitive.Types (
Prim(..),
Addr(..),
) where
import Control.Monad.Primitive
import Data.Primitive.MachDeps
import Data.Primitive.Internal.Operations
import GHC.Base (
Int(..), Char(..),
)
import GHC.Float (
Float(..), Double(..)
)
import GHC.Word (
Word(..), Word8(..), Word16(..), Word32(..), Word64(..)
)
import GHC.Int (
Int8(..), Int16(..), Int32(..), Int64(..)
)
import GHC.Ptr (
Ptr(..), FunPtr(..)
)
import GHC.Prim
#if __GLASGOW_HASKELL__ >= 706
hiding (setByteArray#)
#endif
import Data.Typeable ( Typeable )
import Data.Data ( Data(..) )
import Data.Primitive.Internal.Compat ( isTrue#, mkNoRepType )
-- | A machine address
data Addr = Addr Addr# deriving ( Typeable )
instance Eq Addr where
Addr a# == Addr b# = isTrue# (eqAddr# a# b#)
Addr a# /= Addr b# = isTrue# (neAddr# a# b#)
instance Ord Addr where
Addr a# > Addr b# = isTrue# (gtAddr# a# b#)
Addr a# >= Addr b# = isTrue# (geAddr# a# b#)
Addr a# < Addr b# = isTrue# (ltAddr# a# b#)
Addr a# <= Addr b# = isTrue# (leAddr# a# b#)
instance Data Addr where
toConstr _ = error "toConstr"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Data.Primitive.Types.Addr"
-- | Class of types supporting primitive array operations
class Prim a where
-- | Size of values of type @a@. The argument is not used.
sizeOf# :: a -> Int#
-- | Alignment of values of type @a@. The argument is not used.
alignment# :: a -> Int#
-- | Read a value from the array. The offset is in elements of type
-- @a@ rather than in bytes.
indexByteArray# :: ByteArray# -> Int# -> a
-- | Read a value from the mutable array. The offset is in elements of type
-- @a@ rather than in bytes.
readByteArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, a #)
-- | Write a value to the mutable array. The offset is in elements of type
-- @a@ rather than in bytes.
writeByteArray# :: MutableByteArray# s -> Int# -> a -> State# s -> State# s
-- | Fill a slice of the mutable array with a value. The offset and length
-- of the chunk are in elements of type @a@ rather than in bytes.
setByteArray# :: MutableByteArray# s -> Int# -> Int# -> a -> State# s -> State# s
-- | 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# :: Addr# -> Int# -> a
-- | 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# :: Addr# -> Int# -> State# s -> (# State# s, a #)
-- | 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# :: Addr# -> Int# -> a -> State# s -> State# s
-- | Fill a memory block given by an address, an offset and a length.
-- The offset and length are in elements of type @a@ rather than in bytes.
setOffAddr# :: Addr# -> Int# -> Int# -> a -> State# s -> State# s
#define derivePrim(ty, ctr, sz, align, idx_arr, rd_arr, wr_arr, set_arr, idx_addr, rd_addr, wr_addr, set_addr) \
instance Prim (ty) where { \
sizeOf# _ = unI# sz \
; alignment# _ = unI# align \
; indexByteArray# arr# i# = ctr (idx_arr arr# i#) \
; readByteArray# arr# i# s# = case rd_arr arr# i# s# of \
{ (# s1#, x# #) -> (# s1#, ctr x# #) } \
; writeByteArray# arr# i# (ctr x#) s# = wr_arr arr# i# x# s# \
; setByteArray# arr# i# n# (ctr x#) s# \
= let { i = fromIntegral (I# i#) \
; n = fromIntegral (I# n#) \
} in \
case unsafeCoerce# (internal (set_arr arr# i n x#)) s# of \
{ (# s1#, _ #) -> s1# } \
\
; indexOffAddr# addr# i# = ctr (idx_addr addr# i#) \
; readOffAddr# addr# i# s# = case rd_addr addr# i# s# of \
{ (# s1#, x# #) -> (# s1#, ctr x# #) } \
; writeOffAddr# addr# i# (ctr x#) s# = wr_addr addr# i# x# s# \
; setOffAddr# addr# i# n# (ctr x#) s# \
= let { i = fromIntegral (I# i#) \
; n = fromIntegral (I# n#) \
} in \
case unsafeCoerce# (internal (set_addr addr# i n x#)) s# of \
{ (# s1#, _ #) -> s1# } \
; {-# INLINE sizeOf# #-} \
; {-# INLINE alignment# #-} \
; {-# INLINE indexByteArray# #-} \
; {-# INLINE readByteArray# #-} \
; {-# INLINE writeByteArray# #-} \
; {-# INLINE setByteArray# #-} \
; {-# INLINE indexOffAddr# #-} \
; {-# INLINE readOffAddr# #-} \
; {-# INLINE writeOffAddr# #-} \
; {-# INLINE setOffAddr# #-} \
}
unI# :: Int -> Int#
unI# (I# n#) = n#
derivePrim(Word, W#, sIZEOF_WORD, aLIGNMENT_WORD,
indexWordArray#, readWordArray#, writeWordArray#, setWordArray#,
indexWordOffAddr#, readWordOffAddr#, writeWordOffAddr#, setWordOffAddr#)
derivePrim(Word8, W8#, sIZEOF_WORD8, aLIGNMENT_WORD8,
indexWord8Array#, readWord8Array#, writeWord8Array#, setWord8Array#,
indexWord8OffAddr#, readWord8OffAddr#, writeWord8OffAddr#, setWord8OffAddr#)
derivePrim(Word16, W16#, sIZEOF_WORD16, aLIGNMENT_WORD16,
indexWord16Array#, readWord16Array#, writeWord16Array#, setWord16Array#,
indexWord16OffAddr#, readWord16OffAddr#, writeWord16OffAddr#, setWord16OffAddr#)
derivePrim(Word32, W32#, sIZEOF_WORD32, aLIGNMENT_WORD32,
indexWord32Array#, readWord32Array#, writeWord32Array#, setWord32Array#,
indexWord32OffAddr#, readWord32OffAddr#, writeWord32OffAddr#, setWord32OffAddr#)
derivePrim(Word64, W64#, sIZEOF_WORD64, aLIGNMENT_WORD64,
indexWord64Array#, readWord64Array#, writeWord64Array#, setWord64Array#,
indexWord64OffAddr#, readWord64OffAddr#, writeWord64OffAddr#, setWord64OffAddr#)
derivePrim(Int, I#, sIZEOF_INT, aLIGNMENT_INT,
indexIntArray#, readIntArray#, writeIntArray#, setIntArray#,
indexIntOffAddr#, readIntOffAddr#, writeIntOffAddr#, setIntOffAddr#)
derivePrim(Int8, I8#, sIZEOF_INT8, aLIGNMENT_INT8,
indexInt8Array#, readInt8Array#, writeInt8Array#, setInt8Array#,
indexInt8OffAddr#, readInt8OffAddr#, writeInt8OffAddr#, setInt8OffAddr#)
derivePrim(Int16, I16#, sIZEOF_INT16, aLIGNMENT_INT16,
indexInt16Array#, readInt16Array#, writeInt16Array#, setInt16Array#,
indexInt16OffAddr#, readInt16OffAddr#, writeInt16OffAddr#, setInt16OffAddr#)
derivePrim(Int32, I32#, sIZEOF_INT32, aLIGNMENT_INT32,
indexInt32Array#, readInt32Array#, writeInt32Array#, setInt32Array#,
indexInt32OffAddr#, readInt32OffAddr#, writeInt32OffAddr#, setInt32OffAddr#)
derivePrim(Int64, I64#, sIZEOF_INT64, aLIGNMENT_INT64,
indexInt64Array#, readInt64Array#, writeInt64Array#, setInt64Array#,
indexInt64OffAddr#, readInt64OffAddr#, writeInt64OffAddr#, setInt64OffAddr#)
derivePrim(Float, F#, sIZEOF_FLOAT, aLIGNMENT_FLOAT,
indexFloatArray#, readFloatArray#, writeFloatArray#, setFloatArray#,
indexFloatOffAddr#, readFloatOffAddr#, writeFloatOffAddr#, setFloatOffAddr#)
derivePrim(Double, D#, sIZEOF_DOUBLE, aLIGNMENT_DOUBLE,
indexDoubleArray#, readDoubleArray#, writeDoubleArray#, setDoubleArray#,
indexDoubleOffAddr#, readDoubleOffAddr#, writeDoubleOffAddr#, setDoubleOffAddr#)
derivePrim(Char, C#, sIZEOF_CHAR, aLIGNMENT_CHAR,
indexWideCharArray#, readWideCharArray#, writeWideCharArray#, setWideCharArray#,
indexWideCharOffAddr#, readWideCharOffAddr#, writeWideCharOffAddr#, setWideCharOffAddr#)
derivePrim(Addr, Addr, sIZEOF_PTR, aLIGNMENT_PTR,
indexAddrArray#, readAddrArray#, writeAddrArray#, setAddrArray#,
indexAddrOffAddr#, readAddrOffAddr#, writeAddrOffAddr#, setAddrOffAddr#)
derivePrim(Ptr a, Ptr, sIZEOF_PTR, aLIGNMENT_PTR,
indexAddrArray#, readAddrArray#, writeAddrArray#, setAddrArray#,
indexAddrOffAddr#, readAddrOffAddr#, writeAddrOffAddr#, setAddrOffAddr#)
derivePrim(FunPtr a, FunPtr, sIZEOF_PTR, aLIGNMENT_PTR,
indexAddrArray#, readAddrArray#, writeAddrArray#, setAddrArray#,
indexAddrOffAddr#, readAddrOffAddr#, writeAddrOffAddr#, setAddrOffAddr#)
| dolio/primitive | Data/Primitive/Types.hs | bsd-3-clause | 9,394 | 0 | 12 | 2,609 | 1,447 | 847 | 600 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.DrawRangeElements
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/EXT/draw_range_elements.txt EXT_draw_range_elements> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.DrawRangeElements (
-- * Enums
gl_MAX_ELEMENTS_INDICES_EXT,
gl_MAX_ELEMENTS_VERTICES_EXT,
-- * Functions
glDrawRangeElementsEXT
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/EXT/DrawRangeElements.hs | bsd-3-clause | 800 | 0 | 4 | 91 | 52 | 42 | 10 | 6 | 0 |
module Arhelk.Russian.Lemma.Data.Adjective where
import Arhelk.Russian.Lemma.Data.Common
import Arhelk.Russian.Lemma.Data.Substantive
import Lens.Simple
import Data.Monoid
import TextShow
-- | Разряд прилагательного
data AdjectiveCategory =
QualitiveAdjective -- ^ Качественное
| ComparativeAdjective -- ^ Относительное
| PossessiveAdjective -- ^ Притяжательное
deriving (Eq, Ord, Enum, Show, Bounded)
instance TextShow AdjectiveCategory where
showb v = case v of
QualitiveAdjective -> "качеств."
ComparativeAdjective -> "сравн."
PossessiveAdjective -> "притяж."
-- | Степень сравнения
data AdjectiveDegree =
PositiveDegree -- ^ Положительная степерь
| ComparitiveDegree -- ^ Сравнительная степень
| SuperlativeDegree -- ^ Превосходная степень
deriving (Eq, Ord, Enum, Show, Bounded)
instance TextShow AdjectiveDegree where
showb v = case v of
PositiveDegree -> "полож. степень"
ComparitiveDegree -> "сравн. степень"
SuperlativeDegree -> "превосх. степень"
data AdjectiveProperties = AdjectiveProperties {
_adjGender :: Maybe GrammarGender
, _adjCase :: Maybe GrammarCase
, _adjQuantity :: Maybe GrammarQuantity
, _adjShort :: Maybe Bool
, _adjCategory :: Maybe AdjectiveCategory
} deriving (Eq, Show)
$(makeLenses ''AdjectiveProperties)
instance Monoid AdjectiveProperties where
mempty = AdjectiveProperties {
_adjGender = Nothing
, _adjCase = Nothing
, _adjQuantity = Nothing
, _adjShort = Nothing
, _adjCategory = Nothing
}
mappend a b = AdjectiveProperties {
_adjGender = getFirst $ First (_adjGender a) <> First (_adjGender b)
, _adjCase = getFirst $ First (_adjCase a) <> First (_adjCase b)
, _adjQuantity = getFirst $ First (_adjQuantity a) <> First (_adjQuantity b)
, _adjShort = getFirst $ First (_adjShort a) <> First (_adjShort b)
, _adjCategory = getFirst $ First (_adjCategory a) <> First (_adjCategory b)
}
instance TextShow AdjectiveProperties where
showb AdjectiveProperties{..} = unwordsB [
maybe "" showb _adjGender
, maybe "" showb _adjCase
, maybe "" showb _adjQuantity
, maybe "" showb _adjShort
, maybe "" showb _adjCategory
] | Teaspot-Studio/arhelk-russian | src/Arhelk/Russian/Lemma/Data/Adjective.hs | bsd-3-clause | 2,368 | 0 | 12 | 402 | 563 | 305 | 258 | -1 | -1 |
module CallByName.Suites where
import qualified CallByName.EvaluatorSuite as EvalTest
import qualified CallByName.ParserSuite as ParseTest
import Test.HUnit
tests = TestList [ EvalTest.tests, ParseTest.tests ]
| li-zhirui/EoplLangs | test/CallByName/Suites.hs | bsd-3-clause | 225 | 0 | 7 | 37 | 45 | 29 | 16 | 5 | 1 |
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses,
UndecidableInstances #-}
module Control.Monad.LLVMGen.Metadata(
MonadMetadata(..),
MetadataT,
Metadata,
runMetadataT,
runMetadata
) where
import Control.Applicative
import Control.Monad.Artifacts.Class
import Control.Monad.CommentBuffer
import Control.Monad.Comments
import Control.Monad.LLVMGen.Metadata.Class
import Control.Monad.Cont
import Control.Monad.Error
import Control.Monad.Genpos
import Control.Monad.Gensym
import Control.Monad.Keywords
import Control.Monad.Loader.Class
import Control.Monad.Messages
import Control.Monad.SourceFiles
import Control.Monad.SourceBuffer
import Control.Monad.State
import Control.Monad.Symbols
import Data.Word
import LLVM.General.AST hiding (Type)
data Context =
Context {
-- | Current Metadata ID
ctxMetadataID :: !Word,
-- | All metadata nodes.
ctxMetadataNodes :: ![(Word, [Maybe Operand])]
-- | Map from FileInfos to metadatas representing DWARF file objects.
}
newtype MetadataT m a =
MetadataT { unpackMetadataT :: StateT Context m a }
type Metadata = MetadataT IO
runMetadataT :: Monad m =>
MetadataT m a
-- ^ The @MetadataT@ monad transformer to execute.
-> m (a, [(Word, [Maybe Operand])])
runMetadataT c =
do
(out, Context { ctxMetadataNodes = nodes }) <-
runStateT (unpackMetadataT c) Context { ctxMetadataNodes = [],
ctxMetadataID = 0 }
return (out, nodes)
runMetadata :: Metadata a
-- ^ The @Metadata@ monad to execute.
-> IO (a, [(Word, [Maybe Operand])])
runMetadata = runMetadataT
getMetadataID' :: Monad m => StateT Context m Word
getMetadataID' =
do
ctx @ Context { ctxMetadataID = idx } <- get
put ctx { ctxMetadataID = idx + 1 }
return idx
addMetadataNode' :: Monad m => Word -> [Maybe Operand] -> StateT Context m ()
addMetadataNode' idx operands =
do
ctx @ Context { ctxMetadataNodes = nodes } <- get
put ctx { ctxMetadataNodes = (idx, operands) : nodes }
instance Monad m => Monad (MetadataT m) where
return = MetadataT . return
s >>= f = MetadataT $ unpackMetadataT s >>= unpackMetadataT . f
instance Monad m => Applicative (MetadataT m) where
pure = return
(<*>) = ap
instance (MonadPlus m, Alternative m) => Alternative (MetadataT m) where
empty = lift empty
s1 <|> s2 = MetadataT (unpackMetadataT s1 <|> unpackMetadataT s2)
instance Functor (MetadataT m) where
fmap = fmap
instance MonadIO m => MonadMetadata (MetadataT m) where
getMetadataID = MetadataT getMetadataID'
addMetadataNode idx = MetadataT . addMetadataNode' idx
instance MonadIO m => MonadIO (MetadataT m) where
liftIO = MetadataT . liftIO
instance MonadTrans MetadataT where
lift = MetadataT . lift
instance MonadArtifacts path m => MonadArtifacts path (MetadataT m) where
artifact path = lift . artifact path
artifactBytestring path = lift . artifactBytestring path
artifactLazyBytestring path = lift . artifactLazyBytestring path
instance MonadCommentBuffer m => MonadCommentBuffer (MetadataT m) where
startComment = lift startComment
appendComment = lift . appendComment
finishComment = lift finishComment
addComment = lift . addComment
saveCommentsAsPreceeding = lift . saveCommentsAsPreceeding
clearComments = lift clearComments
instance MonadComments m => MonadComments (MetadataT m) where
preceedingComments = lift . preceedingComments
instance MonadCont m => MonadCont (MetadataT m) where
callCC f =
MetadataT (callCC (\c -> unpackMetadataT (f (MetadataT . c))))
instance (Error e, MonadError e m) => MonadError e (MetadataT m) where
throwError = lift . throwError
m `catchError` h =
MetadataT (unpackMetadataT m `catchError` (unpackMetadataT . h))
instance MonadGenpos m => MonadGenpos (MetadataT m) where
point = lift . point
filename = lift . filename
instance MonadGensym m => MonadGensym (MetadataT m) where
symbol = lift . symbol
unique = lift . unique
instance MonadKeywords p t m => MonadKeywords p t (MetadataT m) where
mkKeyword p = lift . mkKeyword p
instance MonadMessages msg m => MonadMessages msg (MetadataT m) where
message = lift . message
instance MonadLoader path info m => MonadLoader path info (MetadataT m) where
load = lift . load
instance MonadPositions m => MonadPositions (MetadataT m) where
pointInfo = lift . pointInfo
fileInfo = lift . fileInfo
instance MonadSourceFiles m => MonadSourceFiles (MetadataT m) where
sourceFile = lift . sourceFile
instance MonadSourceBuffer m => MonadSourceBuffer (MetadataT m) where
linebreak = lift . linebreak
startFile fname = lift . startFile fname
finishFile = lift finishFile
instance MonadState s m => MonadState s (MetadataT m) where
get = lift get
put = lift . put
instance MonadSymbols m => MonadSymbols (MetadataT m) where
nullSym = lift nullSym
allNames = lift allNames
allSyms = lift allSyms
name = lift . name
instance MonadPlus m => MonadPlus (MetadataT m) where
mzero = lift mzero
mplus s1 s2 = MetadataT (mplus (unpackMetadataT s1)
(unpackMetadataT s2))
instance MonadFix m => MonadFix (MetadataT m) where
mfix f = MetadataT (mfix (unpackMetadataT . f))
| emc2/iridium | src/Control/Monad/LLVMGen/Metadata.hs | bsd-3-clause | 6,942 | 2 | 15 | 1,385 | 1,655 | 883 | 772 | 134 | 1 |
module Main where
import System.Environment (getArgs)
import Test.ReadmeTest
main :: IO ()
main = getArgs >>= mapM_ convertThenRun
| igrep/readme-test | app/Main.hs | bsd-3-clause | 154 | 0 | 6 | 41 | 41 | 23 | 18 | 5 | 1 |
module Sols.Prob2 (
solution
) where
import Common.Fibonacci (fibLessThan)
solution = print (sum [x | x <- (fibLessThan 4000000), x `mod` 2 == 0])
| authentik8/haskell-euler | src/Sols/Prob2.hs | bsd-3-clause | 155 | 0 | 12 | 32 | 66 | 37 | 29 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Stripe.Plan
( Plan(..)
, amount
, PlanInterval(..)
, PlanId(..)
, PlanTrialDays(..)
, createPlan
, getPlan
, getPlans
, delPlan
, delPlanById
{- Re-Export -}
, Amount(..)
, Count(..)
, Currency(..)
, Offset(..)
, StripeConfig(..)
, StripeT(StripeT)
, runStripeT
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (liftM, mzero)
import Control.Monad.Error (MonadIO)
import Data.Aeson (FromJSON (..), Value (..), (.:), (.:?))
import Data.Char (toLower)
import qualified Data.Text as T
import Network.HTTP.Types (StdMethod (..))
import Web.Stripe.Client (StripeConfig (..), StripeRequest (..),
StripeT (..), baseSReq, query, queryData,
query_, runStripeT)
import Web.Stripe.Utils (Amount (..), Count (..), Currency (..),
Offset (..), optionalArgs, showByteString,
textToByteString)
----------------
-- Data Types --
----------------
-- | Represents a plan in the Stripe system.
data Plan = Plan
{ planId :: PlanId
, planAmount :: Amount
, planInterval :: PlanInterval
, planName :: T.Text
, planCurrency :: Currency
, planTrialDays :: Maybe PlanTrialDays
} deriving Show
-- | Represents the billing cycle for a plan. If an interval identifier is not
-- known, 'UnknownPlan' is used to carry the original identifier supplied by
-- Stripe.
data PlanInterval = Monthly | Yearly | UnknownPlan T.Text deriving (Show, Eq)
-- | Represents the identifier for a given 'Plan' in the Stripe system.
newtype PlanId = PlanId { unPlanId :: T.Text } deriving (Show, Eq)
-- | Represents the length of the trial period. That is, the number of days
-- before the customer is billed.
newtype PlanTrialDays = PlanTrialDays { unPlanTrialDays :: Int } deriving (Show, Eq)
amount :: Plan -> Int
amount plan = unAmount $ planAmount plan
-- | Creates a 'Plan' in the Stripe system.
createPlan :: MonadIO m => Plan -> StripeT m ()
createPlan p = query_ (planRq []) { sMethod = POST, sData = fdata }
where
fdata = pdata ++ optionalArgs odata
pdata = [ ("id", textToByteString . unPlanId $ planId p)
, ("amount", showByteString $ amount p)
, ("interval", textToByteString . fromPlanInterval $ planInterval p)
, ("name", textToByteString $ planName p)
, ("currency", textToByteString . unCurrency $ planCurrency p)
]
odata = [ ( "trial_period_days"
, showByteString . unPlanTrialDays <$> planTrialDays p
)
]
-- | Retrieves a specific 'Plan' based on its 'PlanId'.
getPlan :: MonadIO m => PlanId -> StripeT m Plan
getPlan (PlanId pid) = liftM snd $ query (planRq [pid])
-- | Retrieves a list of all 'Plan's. The query can optionally be refined to
-- a specific:
--
-- * number of charges, via 'Count' and
-- * page of results, via 'Offset'.
getPlans :: MonadIO m => Maybe Count -> Maybe Offset -> StripeT m [Plan]
getPlans mc mo = liftM snd $ queryData (planRq []) { sQString = qs }
where
qs = optionalArgs [ ("count", show . unCount <$> mc)
, ("offset", show . unOffset <$> mo)
]
-- | Deletes a 'Plan' if it exists. If it does not, an 'InvalidRequestError'
-- will be thrown indicating this.
delPlan :: MonadIO m => Plan -> StripeT m Bool
delPlan = delPlanById . planId
-- | Deletes a 'Plan', identified by its 'PlanId', if it exists. If it does
-- not, an 'InvalidRequestError' will be thrown indicating this.
delPlanById :: MonadIO m => PlanId -> StripeT m Bool
delPlanById (PlanId pid) = liftM snd $ queryData (planRq [pid]) { sMethod = DELETE }
-- | Convenience function to create a 'StripeRequest' specific to plan-related
-- actions.
planRq :: [T.Text] -> StripeRequest
planRq pcs = baseSReq { sDestination = "plans":pcs }
------------------
-- JSON Parsing --
------------------
-- | Converts a 'PlanInterval' to a T.Text for input into the Stripe API. For
-- 'UnknownPlan's, the original interval code will be used.
fromPlanInterval :: PlanInterval -> T.Text
fromPlanInterval Monthly = "month"
fromPlanInterval Yearly = "year"
fromPlanInterval (UnknownPlan p) = p
-- | Convert a T.Text to a 'PlanInterval'. Used for parsing output from the
-- Stripe API.
toPlanInterval :: T.Text -> PlanInterval
toPlanInterval p = case T.map toLower p of
"month" -> Monthly
"year" -> Yearly
_ -> UnknownPlan p
-- | Attempts to parse JSON into a 'Plan'.
instance FromJSON Plan where
parseJSON (Object o) = Plan
<$> (PlanId <$> o .: "id")
<*> (Amount <$> o .: "amount")
<*> (toPlanInterval <$> o .: "interval")
<*> o .: "name"
<*> (Currency <$> o .: "currency")
<*> (fmap PlanTrialDays <$> o .:? "trial_period_days")
parseJSON _ = mzero
| michaelschade/hs-stripe | src/Web/Stripe/Plan.hs | bsd-3-clause | 5,313 | 0 | 15 | 1,573 | 1,176 | 687 | 489 | 88 | 3 |
{-# LANGUAGE OverloadedStrings,NoImplicitPrelude,TemplateHaskell, GeneralizedNewtypeDeriving, DeriveGeneric #-}
{-# LANGUAGE RecordWildCards #-}
module Data.Acid.CellSpec (main, spec) where
import Data.Acid.Cell.InternalSpec hiding (main,spec)
import Test.Hspec
import Data.Acid ( AcidState, Query, Update, EventResult
, makeAcidic,openLocalStateFrom, closeAcidState )
import CorePrelude
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
True `shouldBe` False
| plow-technologies/acid-cell | test/Data/Acid/CellSpec.hs | bsd-3-clause | 580 | 0 | 13 | 120 | 126 | 74 | 52 | 15 | 1 |
module Main where
import Types
import PongGame
import GUI
import Utils
initialGame :: Gene -> PongGame
initialGame g =
Game { ballLoc = (-10, 30)
, ballVel = (150, -300)
, p1 = UserPlayer False False (-25)
, p2 = GenePlayer D g (-40)
, result = NotFinished
}
movePaddle' :: PongGame -> PongGame
movePaddle' g = let a = mayMoveUserDown (mayMoveUserUp (p1 g))
b = moveGene (p2 g)
in g { p1 = a, p2 = b }
where
mayMoveUserUp :: UserPlayer -> UserPlayer
mayMoveUserUp p = if movingUp p && getPos p < upperBound
then setPos p (+3)
else p
mayMoveUserDown :: UserPlayer -> UserPlayer
mayMoveUserDown p = if movingDown p && getPos p > lowerBound
then setPos p (subtract 3)
else p
moveGene :: GenePlayer -> GenePlayer
moveGene p =
if move p == U
then if getPos p < upperBound then setPos p (+3) else p
else if getPos p > lowerBound then setPos p (subtract 3) else p
interpretGene' :: PongGame -> PongGame
interpretGene' game =
let (bx, by) = normalize (ballLoc game)
q = doubrant (ballVel game)
m = gene (p2 game) !! (q*(factor*factor) + bx*factor + by)
in game { p2 = (p2 game) { move = m } }
update' :: Float -> PongGame -> PongGame
update' seconds game =
case result game of
NotFinished -> (checkFinish . movePaddle' . interpretGene' . paddleBounce . wallBounce . moveBall seconds) game
_ -> game
main :: IO ()
main = do
(_, g) <- readGene
play window background fps (initialGame g) render handleKeys update'
| foollbar/Ponga | src/Play.hs | bsd-3-clause | 1,689 | 0 | 16 | 546 | 605 | 320 | 285 | 44 | 6 |
{-|
Module : Idris.CmdOptions
Description : A parser for the CmdOptions for the Idris executable.
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE Arrows #-}
module Idris.CmdOptions
(
module Idris.CmdOptions
, opt
, getClient, getPkg, getPkgCheck, getPkgClean, getPkgMkDoc
, getPkgREPL, getPkgTest, getPort, getIBCSubDir
) where
import Idris.AbsSyntax (getClient, getIBCSubDir, getPkg, getPkgCheck,
getPkgClean, getPkgMkDoc, getPkgREPL, getPkgTest,
getPort, opt)
import Idris.AbsSyntaxTree
import Idris.Info (getIdrisVersion)
-- import Idris.REPL
import IRTS.CodegenCommon
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Except (throwE)
import Control.Monad.Trans.Reader (ask)
import Data.Char
import Data.Maybe
import Options.Applicative
import Options.Applicative.Arrows
import Options.Applicative.Types (ReadM(..))
import Safe (lastMay)
import Text.ParserCombinators.ReadP hiding (many, option)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
runArgParser :: IO [Opt]
runArgParser = do opts <- execParser $ info parser
(fullDesc
<> headerDoc (Just idrisHeader)
<> progDescDoc (Just idrisProgDesc)
<> footerDoc (Just idrisFooter)
)
return $ preProcOpts opts
where
idrisHeader = PP.hsep [PP.text "Idris version", PP.text getIdrisVersion, PP.text ", (C) The Idris Community 2016"]
idrisProgDesc = PP.vsep [PP.empty,
PP.text "Idris is a general purpose pure functional programming language with dependent",
PP.text "types. Dependent types allow types to be predicated on values, meaning that",
PP.text "some aspects of a program's behaviour can be specified precisely in the type.",
PP.text "It is compiled, with eager evaluation. Its features are influenced by Haskell",
PP.text "and ML.",
PP.empty,
PP.vsep $ map (PP.indent 4 . PP.text) [
"+ Full dependent types with dependent pattern matching",
"+ Simple case expressions, where-clauses, with-rule",
"+ Pattern matching let- and lambda-bindings",
"+ Overloading via Interfaces (Type class-like), Monad comprehensions",
"+ do-notation, idiom brackets",
"+ Syntactic conveniences for lists, tuples, dependent pairs",
"+ Totality checking",
"+ Coinductive types",
"+ Indentation significant syntax, Extensible syntax",
"+ Tactic based theorem proving (influenced by Coq)",
"+ Cumulative universes",
"+ Simple Foreign Function Interface",
"+ Hugs style interactive environment"
]]
idrisFooter = PP.vsep [PP.text "It is important to note that Idris is first and foremost a research tool",
PP.text "and project. Thus the tooling provided and resulting programs created",
PP.text "should not necessarily be seen as production ready nor for industrial use.",
PP.empty,
PP.text "More details over Idris can be found online here:",
PP.empty,
PP.indent 4 (PP.text "http://www.idris-lang.org/")]
pureArgParser :: [String] -> [Opt]
pureArgParser args = case getParseResult $ execParserPure (prefs idm) (info parser idm) args of
Just opts -> preProcOpts opts
Nothing -> []
parser :: Parser [Opt]
parser = runA $ proc () -> do
flags <- asA parseFlags -< ()
files <- asA (many $ argument (fmap Filename str) (metavar "FILES")) -< ()
A parseVersion >>> A helper -< (flags ++ files)
parseFlags :: Parser [Opt]
parseFlags = many $
flag' NoBanner (long "nobanner" <> help "Suppress the banner")
<|> flag' Quiet (short 'q' <> long "quiet" <> help "Quiet verbosity")
-- IDE Mode Specific Flags
<|> flag' Idemode (long "ide-mode" <> help "Run the Idris REPL with machine-readable syntax")
<|> flag' IdemodeSocket (long "ide-mode-socket" <> help "Choose a socket for IDE mode to listen on")
<|> (Client <$> strOption (long "client"))
-- Logging Flags
<|> (OLogging <$> option auto (long "log" <> metavar "LEVEL" <> help "Debugging log level"))
<|> (OLogCats <$> option (str >>= parseLogCats)
(long "logging-categories"
<> metavar "CATS"
<> help "Colon separated logging categories. Use --listlogcats to see list."))
-- Turn off things
<|> flag' NoBasePkgs (long "nobasepkgs" <> help "Do not use the given base package")
<|> flag' NoPrelude (long "noprelude" <> help "Do not use the given prelude")
<|> flag' NoBuiltins (long "nobuiltins" <> help "Do not use the builtin functions")
<|> flag' NoREPL (long "check" <> help "Typecheck only, don't start the REPL")
<|> (Output <$> strOption (short 'o' <> long "output" <> metavar "FILE" <> help "Specify output file"))
-- <|> flag' TypeCase (long "typecase")
<|> flag' Interface (long "interface" <> help "Generate interface files from ExportLists")
<|> flag' TypeInType (long "typeintype" <> help "Turn off Universe checking")
<|> flag' DefaultTotal (long "total" <> help "Require functions to be total by default")
<|> flag' DefaultPartial (long "partial")
<|> flag' WarnPartial (long "warnpartial" <> help "Warn about undeclared partial functions")
<|> flag' WarnReach (long "warnreach" <> help "Warn about reachable but inaccessible arguments")
<|> flag' NoCoverage (long "nocoverage")
<|> flag' ErrContext (long "errorcontext")
-- Show things
<|> flag' ShowAll (long "info" <> help "Display information about installation.")
<|> flag' ShowLoggingCats (long "listlogcats" <> help "Display logging categories")
<|> flag' ShowLibs (long "link" <> help "Display link flags")
<|> flag' ShowPkgs (long "listlibs" <> help "Display installed libraries")
<|> flag' ShowLibDir (long "libdir" <> help "Display library directory")
<|> flag' ShowDocDir (long "docdir" <> help "Display idrisdoc install directory")
<|> flag' ShowIncs (long "include" <> help "Display the includes flags")
<|> flag' Verbose (short 'V' <> long "verbose" <> help "Loud verbosity")
<|> (IBCSubDir <$> strOption (long "ibcsubdir" <> metavar "FILE" <> help "Write IBC files into sub directory"))
<|> (ImportDir <$> strOption (short 'i' <> long "idrispath" <> help "Add directory to the list of import paths"))
<|> (SourceDir <$> strOption (long "sourcepath" <> help "Add directory to the list of source search paths"))
<|> flag' WarnOnly (long "warn")
<|> (Pkg <$> strOption (short 'p' <> long "package" <> help "Add package as a dependency"))
<|> (Port <$> option portReader (long "port" <> metavar "PORT" <> help "REPL TCP port - pass \"none\" to not bind any port"))
-- Package commands
<|> (PkgBuild <$> strOption (long "build" <> metavar "IPKG" <> help "Build package"))
<|> (PkgInstall <$> strOption (long "install" <> metavar "IPKG" <> help "Install package"))
<|> (PkgREPL <$> strOption (long "repl" <> metavar "IPKG" <> help "Launch REPL, only for executables"))
<|> (PkgClean <$> strOption (long "clean" <> metavar "IPKG" <> help "Clean package"))
<|> (PkgDocBuild <$> strOption (long "mkdoc" <> metavar "IPKG" <> help "Generate IdrisDoc for package"))
<|> (PkgDocInstall <$> strOption (long "installdoc" <> metavar "IPKG" <> help "Install IdrisDoc for package"))
<|> (PkgCheck <$> strOption (long "checkpkg" <> metavar "IPKG" <> help "Check package only"))
<|> (PkgTest <$> strOption (long "testpkg" <> metavar "IPKG" <> help "Run tests for package"))
-- Misc options
<|> (BCAsm <$> strOption (long "bytecode"))
<|> flag' (OutputTy Raw) (short 'S' <> long "codegenonly" <> help "Do no further compilation of code generator output")
<|> flag' (OutputTy Object) (short 'c' <> long "compileonly" <> help "Compile to object files rather than an executable")
<|> (DumpDefun <$> strOption (long "dumpdefuns"))
<|> (DumpCases <$> strOption (long "dumpcases"))
<|> (UseCodegen . parseCodegen) <$> strOption (long "codegen"
<> metavar "TARGET"
<> help "Select code generator: C, Javascript, Node and bytecode are bundled with Idris")
<|> ((UseCodegen . Via JSONFormat) <$> strOption (long "portable-codegen"
<> metavar "TARGET"
<> help "Pass the name of the code generator. This option is for codegens that take JSON formatted IR."))
<|> (CodegenArgs <$> strOption (long "cg-opt"
<> metavar "ARG"
<> help "Arguments to pass to code generator"))
<|> (EvalExpr <$> strOption (long "eval" <> short 'e' <> metavar "EXPR" <> help "Evaluate an expression without loading the REPL"))
<|> flag' (InterpretScript "Main.main") (long "execute" <> help "Execute as idris")
<|> (InterpretScript <$> strOption (long "exec" <> metavar "EXPR" <> help "Execute as idris"))
<|> ((Extension . getExt) <$> strOption (long "extension"
<> short 'X'
<> metavar "EXT"
<> help "Turn on language extension (TypeProviders or ErrorReflection)"))
-- Optimisation Levels
<|> flag' (OptLevel 3) (long "O3")
<|> flag' (OptLevel 2) (long "O2")
<|> flag' (OptLevel 1) (long "O1")
<|> flag' (OptLevel 0) (long "O0")
<|> flag' (AddOpt PETransform) (long "partial-eval")
<|> flag' (RemoveOpt PETransform) (long "no-partial-eval" <> help "Switch off partial evaluation, mainly for debugging purposes")
<|> (OptLevel <$> option auto (short 'O' <> long "level"))
<|> (TargetTriple <$> strOption (long "target" <> metavar "TRIPLE" <> help "If supported the codegen will target the named triple."))
<|> (TargetCPU <$> strOption (long "cpu" <> metavar "CPU" <> help "If supported the codegen will target the named CPU e.g. corei7 or cortex-m3"))
-- Colour Options
<|> flag' (ColourREPL True) (long "colour" <> long "color" <> help "Force coloured output")
<|> flag' (ColourREPL False) (long "nocolour" <> long "nocolor" <> help "Disable coloured output")
<|> (UseConsoleWidth <$> option (str >>= parseConsoleWidth) (long "consolewidth" <> metavar "WIDTH" <> help "Select console width: auto, infinite, nat"))
<|> flag' DumpHighlights (long "highlight" <> help "Emit source code highlighting")
<|> flag' NoElimDeprecationWarnings (long "no-elim-deprecation-warnings" <> help "Disable deprecation warnings for %elim")
<|> flag' NoOldTacticDeprecationWarnings (long "no-tactic-deprecation-warnings" <> help "Disable deprecation warnings for the old tactic sublanguage")
where
getExt :: String -> LanguageExt
getExt s = fromMaybe (error ("Unknown extension " ++ s)) (maybeRead s)
maybeRead :: String -> Maybe LanguageExt
maybeRead = fmap fst . listToMaybe . reads
portReader :: ReadM REPLPort
portReader =
((ListenPort . fromIntegral) <$> auto) <|>
(ReadM $ do opt <- ask
if map toLower opt == "none"
then return $ DontListen
else lift $ throwE $ ErrorMsg $
"got " <> opt <> " expected port number or \"none\"")
parseVersion :: Parser (a -> a)
parseVersion = infoOption getIdrisVersion (short 'v' <> long "version" <> help "Print version information")
preProcOpts :: [Opt] -> [Opt]
preProcOpts (NoBuiltins : xs) = NoBuiltins : NoPrelude : preProcOpts xs
preProcOpts (Output s : xs) = Output s : NoREPL : preProcOpts xs
preProcOpts (BCAsm s : xs) = BCAsm s : NoREPL : preProcOpts xs
preProcOpts (x:xs) = x : preProcOpts xs
preProcOpts [] = []
parseCodegen :: String -> Codegen
parseCodegen "bytecode" = Bytecode
parseCodegen cg = Via IBCFormat (map toLower cg)
parseLogCats :: Monad m => String -> m [LogCat]
parseLogCats s =
case lastMay (readP_to_S doParse s) of
Just (xs, _) -> return xs
_ -> fail "Incorrect categories specified"
where
doParse :: ReadP [LogCat]
doParse = do
cs <- sepBy1 parseLogCat (char ':')
eof
return (concat cs)
parseLogCat :: ReadP [LogCat]
parseLogCat = (string (strLogCat IParse) *> return parserCats)
<|> (string (strLogCat IElab) *> return elabCats)
<|> (string (strLogCat ICodeGen) *> return codegenCats)
<|> (string (strLogCat ICoverage) *> return [ICoverage])
<|> (string (strLogCat IIBC) *> return [IIBC])
<|> (string (strLogCat IErasure) *> return [IErasure])
<|> parseLogCatBad
parseLogCatBad :: ReadP [LogCat]
parseLogCatBad = do
s <- look
fail $ "Category: " ++ s ++ " is not recognised."
parseConsoleWidth :: Monad m => String -> m ConsoleWidth
parseConsoleWidth "auto" = return AutomaticWidth
parseConsoleWidth "infinite" = return InfinitelyWide
parseConsoleWidth s =
case lastMay (readP_to_S integerReader s) of
Just (r, _) -> return $ ColsWide r
_ -> fail $ "Cannot parse: " ++ s
integerReader :: ReadP Int
integerReader = do
digits <- many1 $ satisfy isDigit
return $ read digits
| ben-schulz/Idris-dev | src/Idris/CmdOptions.hs | bsd-3-clause | 14,629 | 1 | 78 | 4,503 | 3,495 | 1,722 | 1,773 | 208 | 2 |
module HLint(hlint) where
import Proof.QED
import Control.Monad.IO.Class
hlint = do
decl "data Nat = S Nat | Z"
decl "data Int = Neg Nat | Zero | Pos Nat"
skip $ prove "n x => take n (repeat x) = replicate n x" $ do
unfold "replicate"
skip $ prove "n x => head (drop n x) = x !! n" $ do
unfold "head"
unfold "error"
recurse
prove "f => (($) . f) = f" $ do
unfold "$"
unfold "."
unlet
twice $ rhs expand
prove "f z g x => foldr f z (map g x) = foldr (f . g) z x" $ do
unfold "."
recurse
unfold "map"
prove "(\\x -> cycle [x]) = repeat" $ do
rhs expand
recurse
unlet
twice $ unfold "++"
prove "f x => zipWith f (repeat x) = map (f x)" $ do
expand
rhs expand
recurse
unlet
unfold "repeat"
prove "x y => (if x then False else y) = not x && y" $ do
many unfold_
skip $ prove "map fromJust . filter isJust = catMaybes" $ do
unfold "map"
unfold "catMaybes"
unfold "concatMap"
unfold "concat"
many $ unfold "."
unlet
recurse
unfold "isJust"
unfold "fromJust"
bhs $ unfold "map"
unfold "++"
prove "mapMaybe id = catMaybes" $ do
unfold "mapMaybe"
unfold "."
unlet
rhs expand
divide
unfold "id"
recurse
rhs $ strict "[]"
prove "f x => map f (repeat x) = repeat (f x)" $ do
recurse
unfold "repeat"
unlet
prove "f x y => map (uncurry f) (zip x y) = zipWith f x y" $ do
unfold "zip"
recurse
unlet
unfold "uncurry"
unfold "zipWith"
unlet
unfold "fst"
unfold "snd"
prove "iterate id = repeat" $ do
expand
rhs expand
recurse
at 1 $ unfold "id"
prove "f x => catMaybes (map f x) = mapMaybe f x" $ do
unfold "mapMaybe"
unfold "."
skip $ prove "concatMap maybeToList = catMaybes" $ do
unfold "catMaybes"
liftIO $ print "here1"
expand
liftIO $ print "here2"
twice divide
unfold "maybeToList"
skip $ prove "f g x => concatMap f (map g x) = concatMap (f . g) x" $ do
twice $ unfold "concatMap"
twice $ unfold "concat"
skip $ prove "x => head (reverse x) = last x" $ do
unfold "head"
unfold "reverse"
recurse
unlet
bhs unfold_
unfold "foldl"
unlet
unfold "flip"
error "generalise" -- unsafeReplace "flip (:) [] a" "a"
recurse
unlet
unfold "flip"
error "generalise" -- unsafeReplace "flip (:) a b" "a"
| ndmitchell/qed | test/HLint.hs | bsd-3-clause | 2,794 | 0 | 11 | 1,128 | 657 | 250 | 407 | 100 | 1 |
----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) Daniel Molina Wegener 2012
-- License : BSD 3 (see the LICENSE file)
-- Author : Daniel Molina Wegener <dmw@coder.cl>
-- Homepage : http://coder.cl/products/logrev/
-- Repository : https://github.com/dmw/ApacheLogRev
--
-- An Apache Access Log Statistics extractor
--
-- This is the initial commit of this project, please write
-- me directly if you want to contribute.
-----------------------------------------------------------------------------
module Main (main) where
import qualified Data.Map as M
import qualified Data.String.Utils as S (join)
import Control.DeepSeq (deepseq)
import Data.GeoIP.GeoDB
import Data.IORef
import Data.List
import Data.LogRev.LogStats
import Data.LogRev.Parser
import Data.LogRev.Processing
import Data.Maybe (fromJust, isJust, isNothing)
import Graphics.LogRev.Charts
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO
import System.IO.Unsafe ()
import System.Posix.Temp ()
import Text.Printf
progVersion :: String
progVersion = "ApacheLogRev 0.0.1"
emptyLogRevStats :: LogRevStats
emptyLogRevStats = LogRevStats {
sTot = 0
, sSzTot = 0
, sSz = M.empty
, sMap = M.empty
, sPer = M.empty
}
actionMap :: LogRevStatsMap
actionMap = M.fromList [
(
"http_status"
, LogRevStatsAction
{
aHeader = "HTTP Status"
, aAction = statsHandlerStatus
, aOutput = emptyLogRevStats
, aPlot = plotPngBarChart
}
)
,
(
"connections"
, LogRevStatsAction
{
aHeader = "Connections From Countries"
, aAction = statsHandlerCountry
, aOutput = emptyLogRevStats
, aPlot = plotPngBarChart
}
)
]
startOptions :: LogRevOptions
startOptions = LogRevOptions {
optVerbose = False
, optVersion = False
, optHelp = False
, inpFile = "main.log"
, outFile = "report"
, lrsFile = "main.lrs"
, geoHdl = safeGeoDB
}
safeGeoDB :: Maybe GeoDB
safeGeoDB = let
geo = bringGeoCityDB
geoc = bringGeoCountryDB
in if isJust geo
then geo
else geoc
progOptions :: [OptDescr (LogRevOptions -> IO LogRevOptions)]
progOptions =
[ Option "i" ["input"]
(ReqArg (\ x o -> return o { inpFile = x }) "FILE")
"input file"
, Option "o" ["output"]
(ReqArg (\ x o -> return o { outFile = x }) "FILE")
"output file"
, Option "l" ["lrs"]
(ReqArg (\ x o -> return o { lrsFile = x }) "FILE")
"log reviser specification"
, Option "v" ["verbose"]
(NoArg (\ o -> return o { optVerbose = True }))
"verbose output"
, Option "V" ["version"]
(NoArg (\ _ -> hPutStrLn stderr progVersion
>> exitSuccess))
"displays program version"
, Option "h" ["help"]
(NoArg (\ _ -> do
prg <- getProgName
hPutStrLn stderr (usageInfo prg progOptions)
>> exitSuccess))
"displays this message"
]
logRevMakeStringStat :: LogRevStatsAction -> String
logRevMakeStringStat l = printf "%s:\n%s\n" (aHeader l)
$ S.join "\n"
$ fmap (\ x -> printf f
x (r M.! x) (s M.! x)
(logRevCntPer l x) (logRevSzPer l x)) m
where r = sMap o
s = sSz o
m = sort $ M.keys r
o = aOutput l
f = "%10.10s: %10.d %10.d %10.2f %10.2f"
applyAction :: LogRevOptions
-> LogRevStatsAction
-> LogLine
-> LogRevStatsAction
applyAction o a l = a { aOutput = aAction a o (aOutput a) l }
procLogMachine :: LogRevOptions
-> LogRevStatsMap
-> String
-> LogRevStatsMap
procLogMachine o m x = let
ln = parseLogLine x
in case ln of
Left e -> m
Right l -> let r = fmap (flip (applyAction o) l) m
in r
foldLogLines :: LogRevOptions
-> LogRevStatsMap
-> [String]
-> LogRevStatsMap
foldLogLines mo ms ~ml = foldLogLines' mo ms ml
where foldLogLines' _ s [] = s
foldLogLines' o s (x : ~xs) = let
sm = procLogMachine o s x
in o `seq` sm `seq` foldLogLines' o sm xs
procResults :: LogRevOptions
-> LogRevStatsMap
-> IO ()
procResults o xs = putStrLn report >> mapM_ mkpl mkeys
where report = S.join "\n" $ fmap mkrss mkeys
mkeys = M.keys xs
mkpl x = aPlot (xs M.! x) o (xs M.! x)
mkrss x = logRevMakeStringStat $ xs M.! x
handlerIOError :: IOError -> IO ()
handlerIOError e = putStrLn (printf "IOError: %s" $ show e)
>> exitFailure
defOpts :: LogRevOptions -> LogRevOptions
defOpts lo = fo `deepseq` fo
where optVerbose_ = lo `deepseq` optVerbose lo
optVersion_ = lo `deepseq` optVersion lo
optHelp_ = lo `deepseq` optHelp lo
inpFile_ = lo `deepseq` inpFile lo
outFile_ = lo `deepseq` outFile lo
lrsFile_ = lo `deepseq` lrsFile lo
geoHdl_ = lo `deepseq` geoHdl lo
fo = LogRevOptions {
optVerbose = optVerbose_
, optVersion = optVersion_
, optHelp = optHelp_
, inpFile = inpFile_
, outFile = outFile_
, lrsFile = lrsFile_
, geoHdl = geoHdl_
}
processArgs :: IO ()
processArgs = do
argv <- getArgs
let (act, nopt, errs) = getOpt RequireOrder progOptions argv
opts <- foldl (>>=) (return startOptions) act
putStrLn $ printf "Processing: %s\n" (inpFile opts)
inpData <- readFile (inpFile opts)
procResults opts $ foldLogLines opts actionMap $ lines inpData
main :: IO ()
main = processArgs `catch` handlerIOError
| dmw/ApacheLogRev | src/Main.hs | bsd-3-clause | 6,036 | 0 | 18 | 1,951 | 1,573 | 864 | 709 | 157 | 2 |
{-# LANGUAGE RankNTypes, FlexibleContexts,
NamedFieldPuns, RecordWildCards, PatternGuards #-}
module Distribution.Server.Features.Documentation (
DocumentationFeature(..),
DocumentationResource(..),
initDocumentationFeature
) where
import Distribution.Server.Framework
import Distribution.Server.Features.Documentation.State
import Distribution.Server.Features.Upload
import Distribution.Server.Features.Core
import Distribution.Server.Features.TarIndexCache
import Distribution.Server.Framework.BackupRestore
import qualified Distribution.Server.Framework.ResponseContentTypes as Resource
import Distribution.Server.Framework.BlobStorage (BlobId)
import qualified Distribution.Server.Framework.BlobStorage as BlobStorage
import qualified Distribution.Server.Util.ServeTarball as ServerTarball
import qualified Distribution.Server.Util.DocMeta as DocMeta
import Data.TarIndex (TarIndex)
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Check as Tar
import Distribution.Text
import Distribution.Package
import Distribution.Version (nullVersion)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map as Map
import Data.Function (fix)
import Data.Aeson (toJSON)
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import System.Directory (getModificationTime)
-- TODO:
-- 1. Write an HTML view for organizing uploads
-- 2. Have cabal generate a standard doc tarball, and serve that here
data DocumentationFeature = DocumentationFeature {
documentationFeatureInterface :: HackageFeature,
queryHasDocumentation :: forall m. MonadIO m => PackageIdentifier -> m Bool,
queryDocumentation :: forall m. MonadIO m => PackageIdentifier -> m (Maybe BlobId),
queryDocumentationIndex :: forall m. MonadIO m => m (Map.Map PackageId BlobId),
uploadDocumentation :: DynamicPath -> ServerPartE Response,
deleteDocumentation :: DynamicPath -> ServerPartE Response,
documentationResource :: DocumentationResource,
-- | Notification of documentation changes
documentationChangeHook :: Hook PackageId ()
}
instance IsHackageFeature DocumentationFeature where
getFeatureInterface = documentationFeatureInterface
data DocumentationResource = DocumentationResource {
packageDocsContent :: Resource,
packageDocsWhole :: Resource,
packageDocsStats :: Resource,
packageDocsContentUri :: PackageId -> String,
packageDocsWholeUri :: String -> PackageId -> String
}
initDocumentationFeature :: String
-> ServerEnv
-> IO (CoreResource
-> IO [PackageIdentifier]
-> UploadFeature
-> TarIndexCacheFeature
-> IO DocumentationFeature)
initDocumentationFeature name
env@ServerEnv{serverStateDir} = do
-- Canonical state
documentationState <- documentationStateComponent name serverStateDir
-- Hooks
documentationChangeHook <- newHook
return $ \core getPackages upload tarIndexCache -> do
let feature = documentationFeature name env
core getPackages upload tarIndexCache
documentationState
documentationChangeHook
return feature
documentationStateComponent :: String -> FilePath -> IO (StateComponent AcidState Documentation)
documentationStateComponent name stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> name) initialDocumentation
return StateComponent {
stateDesc = "Package documentation"
, stateHandle = st
, getState = query st GetDocumentation
, putState = update st . ReplaceDocumentation
, backupState = \_ -> dumpBackup
, restoreState = updateDocumentation (Documentation Map.empty)
, resetState = documentationStateComponent name
}
where
dumpBackup doc =
let exportFunc (pkgid, blob) = BackupBlob ([display pkgid, "documentation.tar"]) blob
in map exportFunc . Map.toList $ documentation doc
updateDocumentation :: Documentation -> RestoreBackup Documentation
updateDocumentation docs = RestoreBackup {
restoreEntry = \entry ->
case entry of
BackupBlob [str, "documentation.tar"] blobId | Just pkgId <- simpleParse str -> do
docs' <- importDocumentation pkgId blobId docs
return (updateDocumentation docs')
_ ->
return (updateDocumentation docs)
, restoreFinalize = return docs
}
importDocumentation :: PackageId -> BlobId -> Documentation -> Restore Documentation
importDocumentation pkgId blobId (Documentation docs) =
return (Documentation (Map.insert pkgId blobId docs))
documentationFeature :: String
-> ServerEnv
-> CoreResource
-> IO [PackageIdentifier]
-> UploadFeature
-> TarIndexCacheFeature
-> StateComponent AcidState Documentation
-> Hook PackageId ()
-> DocumentationFeature
documentationFeature name
ServerEnv{serverBlobStore = store, serverBaseURI}
CoreResource{
packageInPath
, guardValidPackageId
, corePackagePage
, corePackagesPage
, lookupPackageId
}
getPackages
UploadFeature{..}
TarIndexCacheFeature{cachedTarIndex}
documentationState
documentationChangeHook
= DocumentationFeature{..}
where
documentationFeatureInterface = (emptyHackageFeature name) {
featureDesc = "Maintain and display documentation"
, featureResources =
map ($ documentationResource) [
packageDocsContent
, packageDocsWhole
, packageDocsStats
]
, featureState = [abstractAcidStateComponent documentationState]
}
queryHasDocumentation :: MonadIO m => PackageIdentifier -> m Bool
queryHasDocumentation pkgid = queryState documentationState (HasDocumentation pkgid)
queryDocumentation :: MonadIO m => PackageIdentifier -> m (Maybe BlobId)
queryDocumentation pkgid = queryState documentationState (LookupDocumentation pkgid)
queryDocumentationIndex :: MonadIO m => m (Map.Map PackageId BlobId)
queryDocumentationIndex =
liftM documentation (queryState documentationState GetDocumentation)
documentationResource = fix $ \r -> DocumentationResource {
packageDocsContent = (extendResourcePath "/docs/.." corePackagePage) {
resourceDesc = [ (GET, "Browse documentation") ]
, resourceGet = [ ("", serveDocumentation) ]
}
, packageDocsWhole = (extendResourcePath "/docs.:format" corePackagePage) {
resourceDesc = [ (GET, "Download documentation")
, (PUT, "Upload documentation")
, (DELETE, "Delete documentation")
]
, resourceGet = [ ("tar", serveDocumentationTar) ]
, resourcePut = [ ("tar", uploadDocumentation) ]
, resourceDelete = [ ("", deleteDocumentation) ]
}
, packageDocsStats = (extendResourcePath "/docs.:format" corePackagesPage) {
resourceDesc = [ (GET, "Get information about which packages have documentation") ]
, resourceGet = [ ("json", serveDocumentationStats) ]
}
, packageDocsContentUri = \pkgid ->
renderResource (packageDocsContent r) [display pkgid]
, packageDocsWholeUri = \format pkgid ->
renderResource (packageDocsWhole r) [display pkgid, format]
}
serveDocumentationStats :: DynamicPath -> ServerPartE Response
serveDocumentationStats _dpath = do
pkgs <- mapParaM queryHasDocumentation =<< liftIO getPackages
return . toResponse . toJSON . map aux $ pkgs
where
aux :: (PackageIdentifier, Bool) -> (String, Bool)
aux (pkgId, hasDocs) = (display pkgId, hasDocs)
serveDocumentationTar :: DynamicPath -> ServerPartE Response
serveDocumentationTar dpath =
withDocumentation (packageDocsWhole documentationResource)
dpath $ \_ blobid _ -> do
age <- liftIO . getFileAge $ BlobStorage.filepath store blobid
let maxAge = documentationCacheTime age
cacheControl [Public, maxAge]
(BlobStorage.blobETag blobid)
file <- liftIO $ BlobStorage.fetch store blobid
return $ toResponse $ Resource.DocTarball file blobid
-- return: not-found error or tarball
serveDocumentation :: DynamicPath -> ServerPartE Response
serveDocumentation dpath = do
withDocumentation (packageDocsContent documentationResource)
dpath $ \pkgid blob index -> do
let tarball = BlobStorage.filepath store blob
etag = BlobStorage.blobETag blob
-- if given a directory, the default page is index.html
-- the root directory within the tarball is e.g. foo-1.0-docs/
age <- liftIO $ getFileAge tarball
let maxAge = documentationCacheTime age
ServerTarball.serveTarball (display pkgid ++ " documentation")
[{-no index-}] (display pkgid ++ "-docs")
tarball index [Public, maxAge] etag
-- The cache time for documentation starts at ten minutes and
-- increases exponentially for four days, when it cuts off at
-- a maximum of one day.
documentationCacheTime :: NominalDiffTime -> CacheControl
documentationCacheTime t
-- We check if it's been four days instead of just capping the time
-- with max because there's no point in doing the whole calculation
-- for old documentation if we're going to throw it away anyway.
| t > 3600*24*4 = maxAgeDays 1
| otherwise = maxAgeSeconds $ 60*10 + ceiling (exp (3.28697e-5 * fromInteger (ceiling t) :: Double))
uploadDocumentation :: DynamicPath -> ServerPartE Response
uploadDocumentation dpath = do
pkgid <- packageInPath dpath
guardValidPackageId pkgid
guardAuthorisedAsMaintainerOrTrustee (packageName pkgid)
-- The order of operations:
-- * Insert new documentation into blob store
-- * Generate the new index
-- * Drop the index for the old tar-file
-- * Link the new documentation to the package
fileContents <- expectUncompressedTarball
mres <- liftIO $ BlobStorage.addWith store fileContents
(\content -> return (checkDocTarball pkgid content))
case mres of
Left err -> errBadRequest "Invalid documentation tarball" [MText err]
Right ((), blobid) -> do
updateState documentationState $ InsertDocumentation pkgid blobid
runHook_ documentationChangeHook pkgid
noContent (toResponse ())
{-
To upload documentation using curl:
curl -u admin:admin \
-X PUT \
-H "Content-Type: application/x-tar" \
--data-binary @transformers-0.3.0.0-docs.tar \
http://localhost:8080/package/transformers-0.3.0.0/docs
or
curl -u admin:admin \
-X PUT \
-H "Content-Type: application/x-tar" \
-H "Content-Encoding: gzip" \
--data-binary @transformers-0.3.0.0-docs.tar.gz \
http://localhost:8080/package/transformers-0.3.0.0/docs
The tarfile is expected to have the structure
transformers-0.3.0.0-docs/index.html
..
-}
deleteDocumentation :: DynamicPath -> ServerPartE Response
deleteDocumentation dpath = do
pkgid <- packageInPath dpath
guardValidPackageId pkgid
guardAuthorisedAsMaintainerOrTrustee (packageName pkgid)
updateState documentationState $ RemoveDocumentation pkgid
runHook_ documentationChangeHook pkgid
noContent (toResponse ())
withDocumentation :: Resource -> DynamicPath
-> (PackageId -> BlobId -> TarIndex -> ServerPartE Response)
-> ServerPartE Response
withDocumentation self dpath func = do
pkgid <- packageInPath dpath
-- lookupPackageId returns the latest version if no version is specified.
pkginfo <- lookupPackageId pkgid
-- Set up the canonical URL to point to the unversioned path
let basedpath =
[ if var == "package"
then (var, unPackageName $ pkgName pkgid)
else e
| e@(var, _) <- dpath ]
basePkgPath = (renderResource' self basedpath)
canonicalLink = show serverBaseURI ++ basePkgPath
canonicalHeader = "<" ++ canonicalLink ++ ">; rel=\"canonical\""
-- Link: <http://canonical.link>; rel="canonical"
-- See https://support.google.com/webmasters/answer/139066?hl=en#6
setHeaderM "Link" canonicalHeader
case pkgVersion pkgid == nullVersion of
-- if no version is given we want to redirect to the latest version
True -> tempRedirect latestPkgPath (toResponse "")
where
latest = packageId pkginfo
dpath' = [ if var == "package"
then (var, display latest)
else e
| e@(var, _) <- dpath ]
latestPkgPath = (renderResource' self dpath')
False -> do
mdocs <- queryState documentationState $ LookupDocumentation pkgid
case mdocs of
Nothing ->
errNotFoundH "Not Found"
[ MText "There is no documentation for "
, MLink (display pkgid) ("/package/" ++ display pkgid)
, MText ". See "
, MLink canonicalLink canonicalLink
, MText " for the latest version."
]
where
-- Essentially errNotFound, but overloaded to specify a header.
-- (Needed since errNotFound throws away result of setHeaderM)
errNotFoundH title message = throwError
(ErrorResponse 404
[("Link", canonicalHeader)]
title message)
Just blob -> do
index <- liftIO $ cachedTarIndex blob
func pkgid blob index
-- Check the tar file is well formed and all files are within foo-1.0-docs/
checkDocTarball :: PackageId -> BSL.ByteString -> Either String ()
checkDocTarball pkgid =
checkEntries
. fmapErr (either id show) . Tar.checkTarbomb (display pkgid ++ "-docs")
. fmapErr (either id show) . Tar.checkSecurity
. fmapErr (either id show) . Tar.checkPortability
. fmapErr show . Tar.read
where
fmapErr f = Tar.foldEntries Tar.Next Tar.Done (Tar.Fail . f)
checkEntries = Tar.foldEntries checkEntry (Right ()) Left
checkEntry entry remainder
| Tar.entryPath entry == docMetaPath = checkDocMeta entry remainder
| otherwise = remainder
checkDocMeta entry remainder =
case Tar.entryContent entry of
Tar.NormalFile content size
| size <= maxDocMetaFileSize ->
case DocMeta.parseDocMeta content of
Just _ -> remainder
Nothing -> Left "meta.json is invalid"
| otherwise -> Left "meta.json too large"
_ -> Left "meta.json not a file"
maxDocMetaFileSize = 16 * 1024 -- 16KiB
docMetaPath = DocMeta.packageDocMetaTarPath pkgid
{------------------------------------------------------------------------------
Auxiliary
------------------------------------------------------------------------------}
mapParaM :: Monad m => (a -> m b) -> [a] -> m [(a, b)]
mapParaM f = mapM (\x -> (,) x `liftM` f x)
getFileAge :: FilePath -> IO NominalDiffTime
getFileAge file = diffUTCTime <$> getCurrentTime <*> getModificationTime file
| edsko/hackage-server | Distribution/Server/Features/Documentation.hs | bsd-3-clause | 16,286 | 0 | 23 | 4,661 | 3,153 | 1,655 | 1,498 | 266 | 6 |
module Opaleye.Operators (module Opaleye.Operators, (.==), case_) where
import Opaleye.Column (Column(Column), (.==), case_)
import Opaleye.QueryArr (QueryArr(QueryArr))
import qualified Opaleye.Internal.PrimQuery as PQ
import qualified Database.HaskellDB.PrimQuery as HPQ
restrict :: QueryArr (Column Bool) ()
restrict = QueryArr f where
f (Column predicate, primQ, t0) = ((), PQ.restrict predicate primQ, t0)
doubleOfInt :: Column Int -> Column Double
doubleOfInt (Column e) = (Column (HPQ.CastExpr "double precision" e))
| k0001/haskell-opaleye | Opaleye/Operators.hs | bsd-3-clause | 550 | 0 | 9 | 89 | 187 | 110 | 77 | 10 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Test.ZM.ADT.Word16.K295e24d62fac (Word16(..)) where
import qualified Prelude(Eq,Ord,Show)
import qualified GHC.Generics
import qualified Flat
import qualified Data.Model
import qualified Test.ZM.ADT.Word.Kf92e8339908a
newtype Word16 = Word16 Test.ZM.ADT.Word.Kf92e8339908a.Word
deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat)
instance Data.Model.Model Word16
| tittoassini/typed | test/Test/ZM/ADT/Word16/K295e24d62fac.hs | bsd-3-clause | 469 | 0 | 7 | 47 | 118 | 76 | 42 | 11 | 0 |
module Control.Concurrent.Delay
(
-- * Delay
Delay(Delay)
, usDelay
, msDelay
, sDelay
, mDelay
, hDelay
, (.+.)
) where
------------------------------------------------------------------------------
import Data.Int (Int64)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | DELAY
--
-- TODO:
-- * Add overflow checks.
-- | Type representing delay in microseconds.
newtype Delay = Delay Int64
-- | Sums two delays.
(.+.) :: Delay -> Delay -> Delay
(Delay x) .+. (Delay y) = Delay $ x + y
{-# INLINE (.+.) #-}
infixl 6 .+.
-- | Delay in microseconds.
usDelay :: Int64 -> Delay
usDelay = Delay
{-# INLINE usDelay #-}
-- | Delay in milliseconds.
msDelay :: Int64 -> Delay
msDelay = Delay . (1000 *)
{-# INLINE msDelay #-}
-- | Delay in seconds.
sDelay :: Int64 -> Delay
sDelay = Delay . (1000 * 1000 *)
{-# INLINE sDelay #-}
-- | Delay in minutes.
mDelay :: Int64 -> Delay
mDelay = Delay . (1000 * 1000 * 60 *)
{-# INLINE mDelay #-}
-- | Delay in hours.
hDelay :: Int64 -> Delay
hDelay = Delay . (1000 * 1000 * 60 * 24 *)
{-# INLINE hDelay #-}
| Palmik/suspend | src/Control/Concurrent/Delay.hs | bsd-3-clause | 1,176 | 0 | 9 | 212 | 252 | 156 | 96 | 32 | 1 |
module Graphics.UI.GLUT.Turtle.Console (
Console,
openConsole,
consolePrompt,
consoleOutput,
consoleKeyboard,
consoleCommand
) where
import Graphics.UI.GLUT.Turtle.GLUTools(
KeyState(..), Modifiers,
createWindow, printCommands, keyboardCallback, displayAction)
import Data.IORef(IORef, newIORef, readIORef, writeIORef)
import Data.IORef.Tools(atomicModifyIORef_)
import Control.Applicative((<$>))
import Control.Concurrent.STM(atomically)
import Control.Concurrent.STM.TChan(
TChan, newTChan, readTChan, writeTChan, isEmptyTChan)
--------------------------------------------------------------------------------
data Console = Console{
cPrompt :: IORef String,
cCommand :: IORef String,
cHistory :: IORef [String],
cUpdate :: IORef Int,
cResult :: TChan String
}
openConsole :: String -> Int -> Int -> IO Console
openConsole name w h = do
cwindow <- createWindow name w h
cprompt <- newIORef ""
ccommand <- newIORef ""
chistory <- newIORef []
cupdate <- newIORef 1
cresult <- atomically newTChan
let console = Console{
cPrompt = cprompt,
cCommand = ccommand,
cHistory = chistory,
cUpdate = cupdate,
cResult = cresult }
keyboardCallback $ consoleKeyboard console
displayAction cupdate $ do
prmpt <- readIORef cprompt
cmd <- readIORef ccommand
hst <- readIORef chistory
printCommands cwindow $ (prmpt ++ reverse cmd) : hst
return console
consolePrompt :: Console -> String -> IO ()
consolePrompt = writeIORef . cPrompt
consoleOutput :: Console -> String -> IO ()
consoleOutput console str = do
atomicModifyIORef_ (cUpdate console) succ
atomicModifyIORef_ (cHistory console) (str :)
consoleKeyboard :: Console -> Char -> KeyState -> Modifiers -> IO ()
consoleKeyboard console '\r' Down _ = do
atomicModifyIORef_ (cUpdate console) succ
prmpt <- readIORef $ cPrompt console
cmd <- readIORef $ cCommand console
atomicModifyIORef_ (cHistory console) $ ((prmpt ++ reverse cmd) :)
writeIORef (cCommand console) ""
atomically $ writeTChan (cResult console) $ reverse cmd
consoleKeyboard console '\b' Down _ = do
atomicModifyIORef_ (cUpdate console) succ
atomicModifyIORef_ (cCommand console) $ drop 1
consoleKeyboard console chr Down _ = do
atomicModifyIORef_ (cUpdate console) succ
atomicModifyIORef_ (cCommand console) (chr :)
consoleKeyboard _ _ _ _ = return ()
consoleCommand :: Console -> IO (Maybe String)
consoleCommand console = atomically $ do
emp <- isEmptyTChan $ cResult console
if emp then return Nothing else Just <$> readTChan (cResult console)
| YoshikuniJujo/gluturtle | src/Graphics/UI/GLUT/Turtle/Console.hs | bsd-3-clause | 2,519 | 38 | 14 | 388 | 872 | 443 | 429 | 68 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Abyme.Regiony.Universe.Generate where
import Data.List (delete, nub)
import qualified Data.Map.Strict as M
import Control.Monad (guard)
import Control.Lens hiding (elements)
import Linear
import Test.QuickCheck.Gen
import Test.QuickCheck.Arbitrary
import Abyme.Util
import Abyme.Polyomino
import Abyme.Regiony.Universe
import Abyme.Regiony.Addressing
import Abyme.Regiony.Chunk
monomino :: Shape
monomino = Shape (V2 0 0) (Polyomino [V2 0 0])
minimal :: Universe
minimal = Universe (M.fromList [(id1, region1), (id2, region2)])
where id1 = RegionId 1
id2 = RegionId 2
region1 = Region id1 id2 (V2 0 0) [monomino]
region2 = Region id2 id1 (V2 0 0) [monomino]
-- Assuming there isn't already a square there
growPiece :: Universe -> Piece -> V2 Integer -> Universe
growPiece u p n = fuseInhabitantRegions added (regionParent added (p ^. pieceRegion))
where added = u & atPiece p . shapePolyomino . polyominoSquares %~ (n:)
potentialNewSquares :: Universe -> Region -> [(Piece, V2 Integer)]
potentialNewSquares u r = do
p <- regionPieces r
l <- halo u p
guard (not $ isInhabited u l)
return $ (p, locationToPosition l - (p ^. pieceShape . shapePosition) - (r ^. regionPosition))
-- Assuming the square is uninhabited
growChild :: Universe -> Location -> Universe
growChild u l = fuseInhabitantRegions newUniverse locationRegion
where newId = newRegionId u
locationRegion = l ^. locationSquare . squarePiece . pieceRegion
newRegion = Region newId (locationRegion ^. regionId) (locationToPosition l) [monomino]
newUniverse = u & universeRegions . at newId ?~ newRegion
potentialNewChildren :: Universe -> Region -> [Location]
potentialNewChildren u r = filter (not . isInhabited u) $ constituentLocations u r
-- --------------------------------------------------------------------------------
-- -- Growing
randomRegion :: Universe -> Gen Region
randomRegion u = do
let allRegions = u ^.. universeRegions . traverse
elements allRegions
randomPiece :: Universe -> Gen Piece
randomPiece u = do
region <- randomRegion u
elements (regionPieces region)
randomSquare :: Universe -> Gen Square
randomSquare u = do
piece <- randomPiece u
elements (constituentSquares u piece)
randomLocation :: Universe -> Gen Location
randomLocation u = do
square <- randomSquare u
x <- elements [0 .. levelScale - 1]
y <- elements [0 .. levelScale - 1]
return (Location square (V2 x y))
growRandomPiece :: Universe -> Gen Universe
growRandomPiece u = do
r <- randomRegion u
let ss = potentialNewSquares u r
if null ss then
return u
else do
(piece, pos) <- elements ss
return $ growPiece u piece pos
growRandomChild :: Universe -> Gen Universe
growRandomChild u = do
r <- randomRegion u
let cs = potentialNewChildren u r
if null cs then
return u
else do
location <- elements cs
return $ growChild u location
growByOne :: Universe -> Gen Universe
growByOne u = oneof [growRandomPiece u, growRandomChild u]
-- --------------------------------------------------------------------------------
-- -- Shrinking
-- TODO: just check parentId
removableRegions :: Universe -> [Region]
removableRegions u = filter (uninhabited u) allRegions
where allRegions = u ^.. universeRegions . traverse
removeRegion :: Universe -> Region -> Universe
removeRegion u r = u & universeRegions . at (r ^. regionId) .~ Nothing
pieceRemovableSquares :: Universe -> Piece -> [Square]
pieceRemovableSquares _u (Piece _ (Shape _ (Polyomino [_a]))) = [] -- We can't leave an empty shape
pieceRemovableSquares u p = filter (uninhabited u) nonRegionBridges
where nonInternalBridges = fmap (Square p) $ polyRemovableSquares (p ^. pieceShape ^. shapePolyomino)
nonRegionBridges = filter (\s -> regionIsConnected $ regionRemoveSquare (p ^. pieceRegion) s) nonInternalBridges
allRemovableSquares :: Universe -> [Square]
allRemovableSquares u = do
let allRegions = u ^.. universeRegions . traverse
region <- allRegions
pieces <- regionPieces region
pieceRemovableSquares u pieces
regionRemoveSquare :: Region -> Square -> Region
regionRemoveSquare r s = r & singular (regionShapes
. traverse
. filtered (== (s ^. squarePiece . pieceShape)))
. shapePolyomino
. polyominoSquares
%~ delete (s ^. squareCoordinates)
removeSquare :: Universe -> Square -> Universe
removeSquare u s = u & atPiece (s ^. squarePiece) . shapePolyomino . polyominoSquares %~ delete (s ^. squareCoordinates)
-- --------------------------------------------------------------------------------
-- -- Arbitrary
instance Arbitrary (V2 Integer) where
arbitrary = sized $ \n -> do
let m = ceiling $ sqrt $ (fromIntegral n :: Double)
x <- choose (-m, m)
y <- choose (-m, m)
return $ V2 x y
-- This is dumb and slow
instance Arbitrary Polyomino where
arbitrary = attempt `suchThat` polyIsConnected
where attempt = do
squares <- listOf arbitrary
return (Polyomino $ nub squares)
shrink (Polyomino ss) = filter polyIsConnected $ fmap Polyomino $ shrink ss
instance Arbitrary Shape where
arbitrary = Shape <$> arbitrary <*> arbitrary
instance Arbitrary Universe where
arbitrary = sized $ \n -> do
if n == 0 then
return minimal
else do
u <- resize (n - 1) arbitrary
growByOne u
shrink u = fmap (removeSquare u) (allRemovableSquares u)
++ fmap (removeRegion u) (removableRegions u)
| mvr/abyme | haskell-model/src/Abyme/Regiony/Universe/Generate.hs | bsd-3-clause | 5,713 | 0 | 16 | 1,211 | 1,786 | 907 | 879 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
-------------------------------------------------------------------
-- |
-- Module : Irreverent.Bitucket.Core.Data.Pipelines.EnvironmentVariable
-- Copyright : (C) 2017 - 2018 Irreverent Pixel Feats
-- License : BSD-style (see the file /LICENSE.md)
-- Maintainer : Dom De Re
--
-------------------------------------------------------------------
module Irreverent.Bitbucket.Core.Data.Pipelines.EnvironmentVariable (
-- * Types
PipelinesEnvironmentVariable(..)
, PipelinesEnvironmentVariableValue(..)
) where
import Irreverent.Bitbucket.Core.Data.Common (
Uuid(..)
)
import qualified Ultra.Data.Text as T
import Preamble
data PipelinesEnvironmentVariableValue =
SecuredPipelinesVariableValue
| UnsecuredPipelinesVariableValue !T.Text
deriving (Show, Eq)
data PipelinesEnvironmentVariable = PipelinesEnvironmentVariable {
pevValue :: !PipelinesEnvironmentVariableValue
, pevKey :: !T.Text
, pevUuid :: !Uuid
} deriving (Show, Eq)
| irreverent-pixel-feats/bitbucket | bitbucket-core/src/Irreverent/Bitbucket/Core/Data/Pipelines/EnvironmentVariable.hs | bsd-3-clause | 1,032 | 0 | 10 | 159 | 134 | 88 | 46 | 25 | 0 |
---------------------------------------------------------------------------------
-- |
-- Module : Data.SBV
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- (The sbv library is hosted at <http://github.com/LeventErkok/sbv>.
-- Comments, bug reports, and patches are always welcome.)
--
-- SBV: SMT Based Verification
--
-- Express properties about Haskell programs and automatically prove
-- them using SMT solvers.
--
-- >>> prove $ \x -> x `shiftL` 2 .== 4 * (x :: SWord8)
-- Q.E.D.
--
-- >>> prove $ \x -> x `shiftL` 2 .== 2 * (x :: SWord8)
-- Falsifiable. Counter-example:
-- s0 = 32 :: Word8
--
-- The function 'prove' has the following type:
--
-- @
-- 'prove' :: 'Provable' a => a -> 'IO' 'ThmResult'
-- @
--
-- The class 'Provable' comes with instances for n-ary predicates, for arbitrary n.
-- The predicates are just regular Haskell functions over symbolic signed and unsigned
-- bit-vectors. Functions for checking satisfiability ('sat' and 'allSat') are also
-- provided.
--
-- In particular, the sbv library introduces the types:
--
-- * 'SBool': Symbolic Booleans (bits).
--
-- * 'SWord8', 'SWord16', 'SWord32', 'SWord64': Symbolic Words (unsigned).
--
-- * 'SInt8', 'SInt16', 'SInt32', 'SInt64': Symbolic Ints (signed).
--
-- * 'SInteger': Unbounded signed integers.
--
-- * 'SReal': Algebraic-real numbers
--
-- * 'SFloat': IEEE-754 single-precision floating point values
--
-- * 'SDouble': IEEE-754 double-precision floating point values
--
-- * 'SArray', 'SFunArray': Flat arrays of symbolic values.
--
-- * Symbolic polynomials over GF(2^n), polynomial arithmetic, and CRCs.
--
-- * Uninterpreted constants and functions over symbolic values, with user
-- defined SMT-Lib axioms.
--
-- * Uninterpreted sorts, and proofs over such sorts, potentially with axioms.
--
-- The user can construct ordinary Haskell programs using these types, which behave
-- very similar to their concrete counterparts. In particular these types belong to the
-- standard classes 'Num', 'Bits', custom versions of 'Eq' ('EqSymbolic')
-- and 'Ord' ('OrdSymbolic'), along with several other custom classes for simplifying
-- programming with symbolic values. The framework takes full advantage of Haskell's type
-- inference to avoid many common mistakes.
--
-- Furthermore, predicates (i.e., functions that return 'SBool') built out of
-- these types can also be:
--
-- * proven correct via an external SMT solver (the 'prove' function)
--
-- * checked for satisfiability (the 'sat', 'allSat' functions)
--
-- * used in synthesis (the `sat` function with existentials)
--
-- * quick-checked
--
-- If a predicate is not valid, 'prove' will return a counterexample: An
-- assignment to inputs such that the predicate fails. The 'sat' function will
-- return a satisfying assignment, if there is one. The 'allSat' function returns
-- all satisfying assignments, lazily.
--
-- The sbv library uses third-party SMT solvers via the standard SMT-Lib interface:
-- <http://smtlib.cs.uiowa.edu/>
--
-- The SBV library is designed to work with any SMT-Lib compliant SMT-solver.
-- Currently, we support the following SMT-Solvers out-of-the box:
--
-- * ABC from University of Berkeley: <http://www.eecs.berkeley.edu/~alanmi/abc/>
--
-- * CVC4 from New York University and University of Iowa: <http://cvc4.cs.nyu.edu/>
--
-- * Boolector from Johannes Kepler University: <http://fmv.jku.at/boolector/>
--
-- * MathSAT from Fondazione Bruno Kessler and DISI-University of Trento: <http://mathsat.fbk.eu/>
--
-- * Yices from SRI: <http://yices.csl.sri.com/>
--
-- * Z3 from Microsoft: <http://z3.codeplex.com/>
--
-- SBV also allows calling these solvers in parallel, either getting results from multiple solvers
-- or returning the fastest one. (See 'proveWithAll', 'proveWithAny', etc.)
--
-- Support for other compliant solvers can be added relatively easily, please
-- get in touch if there is a solver you'd like to see included.
---------------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
#if __GLASGOW_HASKELL__ < 710
{-# LANGUAGE OverlappingInstances #-}
#endif
module Data.SBV (
-- * Programming with symbolic values
-- $progIntro
-- ** Symbolic types
-- *** Symbolic bit
SBool
-- *** Unsigned symbolic bit-vectors
, SWord8, SWord16, SWord32, SWord64
-- *** Signed symbolic bit-vectors
, SInt8, SInt16, SInt32, SInt64
-- *** Signed unbounded integers
-- $unboundedLimitations
, SInteger
-- *** IEEE-floating point numbers
-- $floatingPoints
, SFloat, SDouble, RoundingFloat(..), RoundingMode(..), SRoundingMode, nan, infinity, sNaN, sInfinity, fusedMA
-- **** Rounding modes
, sRoundNearestTiesToEven, sRoundNearestTiesToAway, sRoundTowardPositive, sRoundTowardNegative, sRoundTowardZero
-- **** FP classifiers
, isNormalFP, isSubnormalFP, isZeroFP, isInfiniteFP, isNaNFP, isNegativeFP, isPositiveFP, isNegativeZeroFP, isPositiveZeroFP, isPointFP
-- **** Conversion to and from Word32, Word64
, sWord32ToSFloat, sWord64ToSDouble, sFloatToSWord32, sDoubleToSWord64
-- **** Blasting floats to sign, exponent, mantissa bits
, blastSFloat, blastSDouble
-- *** Signed algebraic reals
-- $algReals
, SReal, AlgReal, sIntegerToSReal, fpToSReal, sRealToSFloat, sRealToSDouble
-- ** Creating a symbolic variable
-- $createSym
, sBool, sWord8, sWord16, sWord32, sWord64, sInt8, sInt16, sInt32, sInt64, sInteger, sReal, sFloat, sDouble
-- ** Creating a list of symbolic variables
-- $createSyms
, sBools, sWord8s, sWord16s, sWord32s, sWord64s, sInt8s, sInt16s, sInt32s, sInt64s, sIntegers, sReals, sFloats, sDoubles
-- *** Abstract SBV type
, SBV
-- *** Arrays of symbolic values
, SymArray(..), SArray, SFunArray, mkSFunArray
-- *** Full binary trees
, STree, readSTree, writeSTree, mkSTree
-- ** Operations on symbolic values
-- *** Word level
, sbvTestBit, sbvPopCount, sbvShiftLeft, sbvShiftRight, sbvRotateLeft, sbvRotateRight, sbvSignedShiftArithRight, setBitTo, oneIf, lsb, msb
-- *** Predicates
, allEqual, allDifferent, inRange, sElem
-- *** Addition and Multiplication with high-bits
, fullAdder, fullMultiplier
-- *** Exponentiation
, (.^)
-- *** Blasting/Unblasting
, blastBE, blastLE, FromBits(..)
-- *** Splitting, joining, and extending
, Splittable(..)
-- *** Sign-casting
, SignCast(..)
-- ** Polynomial arithmetic and CRCs
, Polynomial(..), crcBV, crc
-- ** Conditionals: Mergeable values
, Mergeable(..), ite, iteLazy, sBranch
-- ** Conditional symbolic simulation
, sAssert, sAssertCont
-- ** Symbolic equality
, EqSymbolic(..)
-- ** Symbolic ordering
, OrdSymbolic(..)
-- ** Symbolic integral numbers
, SIntegral
-- ** Division
, SDivisible(..)
-- ** The Boolean class
, Boolean(..)
-- *** Generalizations of boolean operations
, bAnd, bOr, bAny, bAll
-- ** Pretty-printing and reading numbers in Hex & Binary
, PrettyNum(..), readBin
-- * Uninterpreted sorts, constants, and functions
-- $uninterpreted
, Uninterpreted(..), addAxiom
-- * Enumerations
-- $enumerations
-- * Properties, proofs, and satisfiability
-- $proveIntro
-- ** Predicates
, Predicate, Provable(..), Equality(..)
-- ** Proving properties
, prove, proveWith, isTheorem, isTheoremWith
-- ** Checking satisfiability
, sat, satWith, isSatisfiable, isSatisfiableWith
-- ** Finding all satisfying assignments
, allSat, allSatWith
-- ** Satisfying a sequence of boolean conditions
, solve
-- ** Adding constraints
-- $constrainIntro
, constrain, pConstrain
-- ** Checking constraint vacuity
, isVacuous, isVacuousWith
-- * Checking safety
-- $safeIntro
, safe, safeWith, SExecutable(..)
-- * Proving properties using multiple solvers
-- $multiIntro
, proveWithAll, proveWithAny, satWithAll, satWithAny, allSatWithAll, allSatWithAny
-- * Optimization
-- $optimizeIntro
, minimize, maximize, optimize
, minimizeWith, maximizeWith, optimizeWith
-- * Computing expected values
, expectedValue, expectedValueWith
-- * Model extraction
-- $modelExtraction
-- ** Inspecting proof results
-- $resultTypes
, ThmResult(..), SatResult(..), AllSatResult(..), SMTResult(..), SafeResult(..)
-- ** Programmable model extraction
-- $programmableExtraction
, SatModel(..), Modelable(..), displayModels, extractModels
, getModelDictionaries, getModelValues, getModelUninterpretedValues
-- * SMT Interface: Configurations and solvers
, SMTConfig(..), SMTLibLogic(..), Logic(..), OptimizeOpts(..), Solver(..), SMTSolver(..), boolector, cvc4, yices, z3, mathSAT, abc, defaultSolverConfig, sbvCurrentSolver, defaultSMTCfg, sbvCheckSolverInstallation, sbvAvailableSolvers
-- * Symbolic computations
, Symbolic, output, SymWord(..)
-- * Getting SMT-Lib output (for offline analysis)
, compileToSMTLib, generateSMTBenchmarks
-- * Test case generation
, genTest, getTestValues, TestVectors, TestStyle(..), renderTest, CW(..), HasKind(..), Kind(..), cwToBool
-- * Code generation from symbolic programs
-- $cCodeGeneration
, SBVCodeGen
-- ** Setting code-generation options
, cgPerformRTCs, cgSetDriverValues, cgGenerateDriver, cgGenerateMakefile
-- ** Designating inputs
, cgInput, cgInputArr
-- ** Designating outputs
, cgOutput, cgOutputArr
-- ** Designating return values
, cgReturn, cgReturnArr
-- ** Code generation with uninterpreted functions
, cgAddPrototype, cgAddDecl, cgAddLDFlags
-- ** Code generation with 'SInteger' and 'SReal' types
-- $unboundedCGen
, cgIntegerSize, cgSRealType, CgSRealType(..)
-- ** Compilation to C
, compileToC, compileToCLib
-- * Module exports
-- $moduleExportIntro
, module Data.Bits
, module Data.Word
, module Data.Int
, module Data.Ratio
) where
import Control.Monad (filterM)
import Control.Concurrent.Async (async, waitAny, waitAnyCancel)
import System.IO.Unsafe (unsafeInterleaveIO) -- only used safely!
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.Data
import Data.SBV.BitVectors.Model
import Data.SBV.BitVectors.PrettyNum
import Data.SBV.BitVectors.Rounding
import Data.SBV.BitVectors.SignCast
import Data.SBV.BitVectors.Splittable
import Data.SBV.BitVectors.STree
import Data.SBV.Compilers.C
import Data.SBV.Compilers.CodeGen
import Data.SBV.Provers.Prover
import Data.SBV.Tools.GenTest
import Data.SBV.Tools.ExpectedValue
import Data.SBV.Tools.Optimize
import Data.SBV.Tools.Polynomial
import Data.SBV.Utils.Boolean
import Data.Bits
import Data.Int
import Data.Ratio
import Data.Word
-- | The currently active solver, obtained by importing "Data.SBV".
-- To have other solvers /current/, import one of the bridge
-- modules "Data.SBV.Bridge.CVC4", "Data.SBV.Bridge.Yices", or
-- "Data.SBV.Bridge.Z3" directly.
sbvCurrentSolver :: SMTConfig
sbvCurrentSolver = z3
-- | Is the floating-point number a normal value. (i.e., not denormalized.)
isNormalFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isNormalFP = liftFPPredicate "fp.isNormal" isNormalized
where isNormalized x = not (isDenormalized x || isInfinite x || isNaN x)
-- | Is the floating-point number a subnormal value. (Also known as denormal.)
isSubnormalFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isSubnormalFP = liftFPPredicate "fp.isSubnormal" isDenormalized
-- | Is the floating-point number 0? (Note that both +0 and -0 will satisfy this predicate.)
isZeroFP :: (Floating a, SymWord a) => SBV a -> SBool
isZeroFP = liftFPPredicate "fp.isZero" (== 0)
-- | Is the floating-point number infinity? (Note that both +oo and -oo will satisfy this predicate.)
isInfiniteFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isInfiniteFP = liftFPPredicate "fp.isInfinite" isInfinite
-- | Is the floating-point number a NaN value?
isNaNFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isNaNFP = liftFPPredicate "fp.isNaN" isNaN
-- | Is the floating-point number negative? Note that -0 satisfies this predicate but +0 does not.
isNegativeFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isNegativeFP = liftFPPredicate "fp.isNegative" (\x -> x < 0 || isNegativeZero x)
-- | Is the floating-point number positive? Note that +0 satisfies this predicate but -0 does not.
isPositiveFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isPositiveFP = liftFPPredicate "fp.isPositive" (\x -> x >= 0 && not (isNegativeZero x))
-- | Is the floating point number -0?
isNegativeZeroFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isNegativeZeroFP x = isZeroFP x &&& isNegativeFP x
-- | Is the floating point number +0?
isPositiveZeroFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isPositiveZeroFP x = isZeroFP x &&& isPositiveFP x
-- | Is the floating-point number a regular floating point, i.e., not NaN, nor +oo, nor -oo. Normals or denormals are allowed.
isPointFP :: (RealFloat a, SymWord a) => SBV a -> SBool
isPointFP x = bnot (isNaNFP x ||| isInfiniteFP x)
-- | Form the symbolic conjunction of a given list of boolean conditions. Useful in expressing
-- problems with constraints, like the following:
--
-- @
-- do [x, y, z] <- sIntegers [\"x\", \"y\", \"z\"]
-- solve [x .> 5, y + z .< x]
-- @
solve :: [SBool] -> Symbolic SBool
solve = return . bAnd
-- | Check whether the given solver is installed and is ready to go. This call does a
-- simple call to the solver to ensure all is well.
sbvCheckSolverInstallation :: SMTConfig -> IO Bool
sbvCheckSolverInstallation cfg = do ThmResult r <- proveWith cfg $ \x -> (x+x) .== ((x*2) :: SWord8)
case r of
Unsatisfiable _ -> return True
_ -> return False
-- | The default configs corresponding to supported SMT solvers
defaultSolverConfig :: Solver -> SMTConfig
defaultSolverConfig Z3 = z3
defaultSolverConfig Yices = yices
defaultSolverConfig Boolector = boolector
defaultSolverConfig CVC4 = cvc4
defaultSolverConfig MathSAT = mathSAT
defaultSolverConfig ABC = abc
-- | Return the known available solver configs, installed on your machine.
sbvAvailableSolvers :: IO [SMTConfig]
sbvAvailableSolvers = filterM sbvCheckSolverInstallation (map defaultSolverConfig [minBound .. maxBound])
sbvWithAny :: Provable a => [SMTConfig] -> (SMTConfig -> a -> IO b) -> a -> IO (Solver, b)
sbvWithAny [] _ _ = error "SBV.withAny: No solvers given!"
sbvWithAny solvers what a = snd `fmap` (mapM try solvers >>= waitAnyCancel)
where try s = async $ what s a >>= \r -> return (name (solver s), r)
sbvWithAll :: Provable a => [SMTConfig] -> (SMTConfig -> a -> IO b) -> a -> IO [(Solver, b)]
sbvWithAll solvers what a = mapM try solvers >>= (unsafeInterleaveIO . go)
where try s = async $ what s a >>= \r -> return (name (solver s), r)
go [] = return []
go as = do (d, r) <- waitAny as
rs <- unsafeInterleaveIO $ go (filter (/= d) as)
return (r : rs)
-- | Prove a property with multiple solvers, running them in separate threads. The
-- results will be returned in the order produced.
proveWithAll :: Provable a => [SMTConfig] -> a -> IO [(Solver, ThmResult)]
proveWithAll = (`sbvWithAll` proveWith)
-- | Prove a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
proveWithAny :: Provable a => [SMTConfig] -> a -> IO (Solver, ThmResult)
proveWithAny = (`sbvWithAny` proveWith)
-- | Find a satisfying assignment to a property with multiple solvers, running them in separate threads. The
-- results will be returned in the order produced.
satWithAll :: Provable a => [SMTConfig] -> a -> IO [(Solver, SatResult)]
satWithAll = (`sbvWithAll` satWith)
-- | Find a satisfying assignment to a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
satWithAny :: Provable a => [SMTConfig] -> a -> IO (Solver, SatResult)
satWithAny = (`sbvWithAny` satWith)
-- | Find all satisfying assignments to a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
allSatWithAll :: Provable a => [SMTConfig] -> a -> IO [(Solver, AllSatResult)]
allSatWithAll = (`sbvWithAll` allSatWith)
-- | Find all satisfying assignments to a property with multiple solvers, running them in separate threads. Only
-- the result of the first one to finish will be returned, remaining threads will be killed.
allSatWithAny :: Provable a => [SMTConfig] -> a -> IO (Solver, AllSatResult)
allSatWithAny = (`sbvWithAny` allSatWith)
-- | Equality as a proof method. Allows for
-- very concise construction of equivalence proofs, which is very typical in
-- bit-precise proofs.
infix 4 ===
class Equality a where
(===) :: a -> a -> IO ThmResult
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, EqSymbolic z) => Equality (SBV a -> z) where
k === l = prove $ \a -> k a .== l a
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, EqSymbolic z) => Equality (SBV a -> SBV b -> z) where
k === l = prove $ \a b -> k a b .== l a b
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, EqSymbolic z) => Equality ((SBV a, SBV b) -> z) where
k === l = prove $ \a b -> k (a, b) .== l (a, b)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> z) where
k === l = prove $ \a b c -> k a b c .== l a b c
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c) -> z) where
k === l = prove $ \a b c -> k (a, b, c) .== l (a, b, c)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> z) where
k === l = prove $ \a b c d -> k a b c d .== l a b c d
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d) -> z) where
k === l = prove $ \a b c d -> k (a, b, c, d) .== l (a, b, c, d)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> SBV e -> z) where
k === l = prove $ \a b c d e -> k a b c d e .== l a b c d e
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d, SBV e) -> z) where
k === l = prove $ \a b c d e -> k (a, b, c, d, e) .== l (a, b, c, d, e)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> SBV e -> SBV f -> z) where
k === l = prove $ \a b c d e f -> k a b c d e f .== l a b c d e f
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d, SBV e, SBV f) -> z) where
k === l = prove $ \a b c d e f -> k (a, b, c, d, e, f) .== l (a, b, c, d, e, f)
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, SymWord g, EqSymbolic z) => Equality (SBV a -> SBV b -> SBV c -> SBV d -> SBV e -> SBV f -> SBV g -> z) where
k === l = prove $ \a b c d e f g -> k a b c d e f g .== l a b c d e f g
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(SymWord a, SymWord b, SymWord c, SymWord d, SymWord e, SymWord f, SymWord g, EqSymbolic z) => Equality ((SBV a, SBV b, SBV c, SBV d, SBV e, SBV f, SBV g) -> z) where
k === l = prove $ \a b c d e f g -> k (a, b, c, d, e, f, g) .== l (a, b, c, d, e, f, g)
-- Haddock section documentation
{- $progIntro
The SBV library is really two things:
* A framework for writing symbolic programs in Haskell, i.e., programs operating on
symbolic values along with the usual concrete counterparts.
* A framework for proving properties of such programs using SMT solvers.
The programming goal of SBV is to provide a /seamless/ experience, i.e., let people program
in the usual Haskell style without distractions of symbolic coding. While Haskell helps
in some aspects (the 'Num' and 'Bits' classes simplify coding), it makes life harder
in others. For instance, @if-then-else@ only takes 'Bool' as a test in Haskell, and
comparisons ('>' etc.) only return 'Bool's. Clearly we would like these values to be
symbolic (i.e., 'SBool'), thus stopping us from using some native Haskell constructs.
When symbolic versions of operators are needed, they are typically obtained by prepending a dot,
for instance '==' becomes '.=='. Care has been taken to make the transition painless. In
particular, any Haskell program you build out of symbolic components is fully concretely
executable within Haskell, without the need for any custom interpreters. (They are truly
Haskell programs, not AST's built out of pieces of syntax.) This provides for an integrated
feel of the system, one of the original design goals for SBV.
-}
{- $proveIntro
The SBV library provides a "push-button" verification system via automated SMT solving. The
design goal is to let SMT solvers be used without any knowledge of how SMT solvers work
or how different logics operate. The details are hidden behind the SBV framework, providing
Haskell programmers with a clean API that is unencumbered by the details of individual solvers.
To that end, we use the SMT-Lib standard (<http://smtlib.cs.uiowa.edu/>)
to communicate with arbitrary SMT solvers.
-}
{- $multiIntro
On a multi-core machine, it might be desirable to try a given property using multiple SMT solvers,
using parallel threads. Even with machines with single-cores, threading can be helpful if you
want to try out multiple-solvers but do not know which one would work the best
for the problem at hand ahead of time.
The functions in this section allow proving/satisfiability-checking with multiple
backends at the same time. Each function comes in two variants, one that
returns the results from all solvers, the other that returns the fastest one.
The @All@ variants, (i.e., 'proveWithAll', 'satWithAll', 'allSatWithAll') run all solvers and
return all the results. SBV internally makes sure that the result is lazily generated; so,
the order of solvers given does not matter. In other words, the order of results will follow
the order of the solvers as they finish, not as given by the user. These variants are useful when you
want to make sure multiple-solvers agree (or disagree!) on a given problem.
The @Any@ variants, (i.e., 'proveWithAny', 'satWithAny', 'allSatWithAny') will run all the solvers
in parallel, and return the results of the first one finishing. The other threads will then be killed. These variants
are useful when you do not care if the solvers produce the same result, but rather want to get the
solution as quickly as possible, taking advantage of modern many-core machines.
Note that the function 'sbvAvailableSolvers' will return all the installed solvers, which can be
used as the first argument to all these functions, if you simply want to try all available solvers on a machine.
-}
{- $safeIntro
The 'sAssert' and 'sAssertCont' functions allow users to introduce invariants through-out their code to make sure
certain properties hold at all times. This is another mechanism to provide further documentation/contract info
into SBV code. The functions 'safe' and 'safeWith' can then be used to statically discharge these proof assumptions.
If a violation is found, SBV will print a model showing which inputs lead to the invariant being violated.
Here's a simple example. Let's assume we have a function that does subtraction, and requires it's
first argument to be larger than the second:
>>> let sub x y = sAssert "sub: x >= y must hold!" (x .>= y) (x - y)
Clearly, this function is not safe, as there's nothing that ensures us to pass a larger second argument.
If we try to prove a theorem regarding sub, we'll get an exception:
>>> prove $ \x y -> sub x y .>= (0 :: SInt16)
*** Exception: Assertion failure: "sub: x >= y must hold!"
s0 = -32768 :: Int16
s1 = -32767 :: Int16
Of course, we can use, 'safe' to statically see if such a violation is possible before we attempt a proof:
>>> safe (sub :: SInt8 -> SInt8 -> SInt8)
Assertion failure: "sub: x >= y must hold!"
s0 = -128 :: Int8
s1 = -127 :: Int8
What happens if we make sure to arrange for this invariant? Consider this version:
>>> let safeSub x y = ite (x .>= y) (sub x y) (sub y x)
Clearly, 'safeSub' must be safe. And indeed, SBV can prove that:
>>> safe (safeSub :: SInt8 -> SInt8 -> SInt8)
No safety violations detected.
Note how we used 'sub' and 'safeSub' polymorphically. We only need to monomorphise our types when a proof
attempt is done, as we did in the 'safe' calls.
-}
{- $optimizeIntro
Symbolic optimization. A call of the form:
@minimize Quantified cost n valid@
returns @Just xs@, such that:
* @xs@ has precisely @n@ elements
* @valid xs@ holds
* @cost xs@ is minimal. That is, for all sequences @ys@ that satisfy the first two criteria above, @cost xs .<= cost ys@ holds.
If there is no such sequence, then 'minimize' will return 'Nothing'.
The function 'maximize' is similar, except the comparator is '.>='. So the value returned has the largest cost (or value, in that case).
The function 'optimize' allows the user to give a custom comparison function.
The 'OptimizeOpts' argument controls how the optimization is done. If 'Quantified' is used, then the SBV optimization engine satisfies the following predicate:
@exists xs. forall ys. valid xs && (valid ys ``implies`` (cost xs ``cmp`` cost ys))@
Note that this may cause efficiency problems as it involves alternating quantifiers.
If 'OptimizeOpts' is set to 'Iterative' 'True', then SBV will programmatically
search for an optimal solution, by repeatedly calling the solver appropriately. (The boolean argument controls whether progress reports are given. Use
'False' for quiet operation.) Note that the quantified and iterative versions are two different optimization approaches and may not necessarily yield the same
results. In particular, the quantified version can find solutions where there is no global optimum value, while the iterative version would simply loop forever
in such cases. On the other hand, the iterative version might be more suitable if the quantified version of the problem is too hard to deal with by the SMT solver.
-}
{- $modelExtraction
The default 'Show' instances for prover calls provide all the counter-example information in a
human-readable form and should be sufficient for most casual uses of sbv. However, tools built
on top of sbv will inevitably need to look into the constructed models more deeply, programmatically
extracting their results and performing actions based on them. The API provided in this section
aims at simplifying this task.
-}
{- $resultTypes
'ThmResult', 'SatResult', and 'AllSatResult' are simple newtype wrappers over 'SMTResult'. Their
main purpose is so that we can provide custom 'Show' instances to print results accordingly.
-}
{- $programmableExtraction
While default 'Show' instances are sufficient for most use cases, it is sometimes desirable (especially
for library construction) that the SMT-models are reinterpreted in terms of domain types. Programmable
extraction allows getting arbitrarily typed models out of SMT models.
-}
{- $cCodeGeneration
The SBV library can generate straight-line executable code in C. (While other target languages are
certainly possible, currently only C is supported.) The generated code will perform no run-time memory-allocations,
(no calls to @malloc@), so its memory usage can be predicted ahead of time. Also, the functions will execute precisely the
same instructions in all calls, so they have predictable timing properties as well. The generated code
has no loops or jumps, and is typically quite fast. While the generated code can be large due to complete unrolling,
these characteristics make them suitable for use in hard real-time systems, as well as in traditional computing.
-}
{- $unboundedCGen
The types 'SInteger' and 'SReal' are unbounded quantities that have no direct counterparts in the C language. Therefore,
it is not possible to generate standard C code for SBV programs using these types, unless custom libraries are available. To
overcome this, SBV allows the user to explicitly set what the corresponding types should be for these two cases, using
the functions below. Note that while these mappings will produce valid C code, the resulting code will be subject to
overflow/underflows for 'SInteger', and rounding for 'SReal', so there is an implicit loss of precision.
If the user does /not/ specify these mappings, then SBV will
refuse to compile programs that involve these types.
-}
{- $moduleExportIntro
The SBV library exports the following modules wholesale, as user programs will have to import these
modules to make any sensible use of the SBV functionality.
-}
{- $createSym
These functions simplify declaring symbolic variables of various types. Strictly speaking, they are just synonyms
for 'free' (specialized at the given type), but they might be easier to use.
-}
{- $createSyms
These functions simplify declaring a sequence symbolic variables of various types. Strictly speaking, they are just synonyms
for 'mapM' 'free' (specialized at the given type), but they might be easier to use.
-}
{- $unboundedLimitations
The SBV library supports unbounded signed integers with the type 'SInteger', which are not subject to
overflow/underflow as it is the case with the bounded types, such as 'SWord8', 'SInt16', etc. However,
some bit-vector based operations are /not/ supported for the 'SInteger' type while in the verification mode. That
is, you can use these operations on 'SInteger' values during normal programming/simulation.
but the SMT translation will not support these operations since there corresponding operations are not supported in SMT-Lib.
Note that this should rarely be a problem in practice, as these operations are mostly meaningful on fixed-size
bit-vectors. The operations that are restricted to bounded word/int sizes are:
* Rotations and shifts: 'rotateL', 'rotateR', 'shiftL', 'shiftR'
* Bitwise logical ops: '.&.', '.|.', 'xor', 'complement'
* Extraction and concatenation: 'split', '#', and 'extend' (see the 'Splittable' class)
Usual arithmetic ('+', '-', '*', 'sQuotRem', 'sQuot', 'sRem', 'sDivMod', 'sDiv', 'sMod') and logical operations ('.<', '.<=', '.>', '.>=', '.==', './=') operations are
supported for 'SInteger' fully, both in programming and verification modes.
-}
{- $algReals
Algebraic reals are roots of single-variable polynomials with rational coefficients. (See
<http://en.wikipedia.org/wiki/Algebraic_number>.) Note that algebraic reals are infinite
precision numbers, but they do not cover all /real/ numbers. (In particular, they cannot
represent transcendentals.) Some irrational numbers are algebraic (such as @sqrt 2@), while
others are not (such as pi and e).
SBV can deal with real numbers just fine, since the theory of reals is decidable. (See
<http://smtlib.cs.uiowa.edu/theories/Reals.smt2>.) In addition, by leveraging backend
solver capabilities, SBV can also represent and solve non-linear equations involving real-variables.
(For instance, the Z3 SMT solver, supports polynomial constraints on reals starting with v4.0.)
-}
{- $floatingPoints
Floating point numbers are defined by the IEEE-754 standard; and correspond to Haskell's
'Float' and 'Double' types. For SMT support with floating-point numbers, see the paper
by Rummer and Wahl: <http://www.philipp.ruemmer.org/publications/smt-fpa.pdf>.
-}
{- $constrainIntro
A constraint is a means for restricting the input domain of a formula. Here's a simple
example:
@
do x <- 'exists' \"x\"
y <- 'exists' \"y\"
'constrain' $ x .> y
'constrain' $ x + y .>= 12
'constrain' $ y .>= 3
...
@
The first constraint requires @x@ to be larger than @y@. The scond one says that
sum of @x@ and @y@ must be at least @12@, and the final one says that @y@ to be at least @3@.
Constraints provide an easy way to assert additional properties on the input domain, right at the point of
the introduction of variables.
Note that the proper reading of a constraint
depends on the context:
* In a 'sat' (or 'allSat') call: The constraint added is asserted
conjunctively. That is, the resulting satisfying model (if any) will
always satisfy all the constraints given.
* In a 'prove' call: In this case, the constraint acts as an implication.
The property is proved under the assumption that the constraint
holds. In other words, the constraint says that we only care about
the input space that satisfies the constraint.
* In a 'quickCheck' call: The constraint acts as a filter for 'quickCheck';
if the constraint does not hold, then the input value is considered to be irrelevant
and is skipped. Note that this is similar to 'prove', but is stronger: We do not
accept a test case to be valid just because the constraints fail on them, although
semantically the implication does hold. We simply skip that test case as a /bad/
test vector.
* In a 'genTest' call: Similar to 'quickCheck' and 'prove': If a constraint
does not hold, the input value is ignored and is not included in the test
set.
A good use case (in fact the motivating use case) for 'constrain' is attaching a
constraint to a 'forall' or 'exists' variable at the time of its creation.
Also, the conjunctive semantics for 'sat' and the implicative
semantics for 'prove' simplify programming by choosing the correct interpretation
automatically. However, one should be aware of the semantic difference. For instance, in
the presence of constraints, formulas that are /provable/ are not necessarily
/satisfiable/. To wit, consider:
@
do x <- 'exists' \"x\"
'constrain' $ x .< x
return $ x .< (x :: 'SWord8')
@
This predicate is unsatisfiable since no element of 'SWord8' is less than itself. But
it's (vacuously) true, since it excludes the entire domain of values, thus making the proof
trivial. Hence, this predicate is provable, but is not satisfiable. To make sure the given
constraints are not vacuous, the functions 'isVacuous' (and 'isVacuousWith') can be used.
Also note that this semantics imply that test case generation ('genTest') and quick-check
can take arbitrarily long in the presence of constraints, if the random input values generated
rarely satisfy the constraints. (As an extreme case, consider @'constrain' 'false'@.)
A probabilistic constraint (see 'pConstrain') attaches a probability threshold for the
constraint to be considered. For instance:
@
'pConstrain' 0.8 c
@
will make sure that the condition @c@ is satisfied 80% of the time (and correspondingly, falsified 20%
of the time), in expectation. This variant is useful for 'genTest' and 'quickCheck' functions, where we
want to filter the test cases according to some probability distribution, to make sure that the test-vectors
are drawn from interesting subsets of the input space. For instance, if we were to generate 100 test cases
with the above constraint, we'd expect about 80 of them to satisfy the condition @c@, while about 20 of them
will fail it.
The following properties hold:
@
'constrain' = 'pConstrain' 1
'pConstrain' t c = 'pConstrain' (1-t) (not c)
@
Note that while 'constrain' can be used freely, 'pConstrain' is only allowed in the contexts of
'genTest' or 'quickCheck'. Calls to 'pConstrain' in a prove/sat call will be rejected as SBV does not
deal with probabilistic constraints when it comes to satisfiability and proofs.
Also, both 'constrain' and 'pConstrain' calls during code-generation will also be rejected, for similar reasons.
-}
{- $uninterpreted
Users can introduce new uninterpreted sorts simply by defining a data-type in Haskell and registering it as such. The
following example demonstrates:
@
data B = B () deriving (Eq, Ord, Data, Typeable, Read, Show)
instance SymWord B
instance HasKind B
instance SatModel B -- required only if 'getModel' etc. is used.
@
(Note that you'll also need to use the language pragma @DeriveDataTypeable@, and import @Data.Generics@ for the above to work.)
Once GHC implements derivable user classes (<http://hackage.haskell.org/trac/ghc/ticket/5462>), we will be able to simplify this to:
@
data B = B () deriving (Eq, Ord, Data, Typeable, Read, Show, SymWord, HasKind)
@
This is all it takes to introduce 'B' as an uninterpreted sort in SBV, which makes the type @SBV B@ automagically become available as the type
of symbolic values that ranges over 'B' values. Note that the @()@ argument is important to distinguish it from enumerations.
Uninterpreted functions over both uninterpreted and regular sorts can be declared using the facilities introduced by
the 'Uninterpreted' class.
-}
{- $enumerations
If the uninterpreted sort definition takes the form of an enumeration (i.e., a simple data type with all nullary constructors), then SBV will actually
translate that as just such a data-type to SMT-Lib, and will use the constructors as the inhabitants of the said sort. A simple example is:
@
data X = A | B | C deriving (Eq, Ord, Data, Typeable, Read, Show)
instance SymWord X
instance HasKind X
instance SatModel X
@
Now, the user can define
@
type SX = SBV X
@
and treat @SX@ as a regular symbolic type ranging over the values @A@, @B@, and @C@. Such values can be compared for equality, and with the usual
other comparison operators, such as @.==@, @./=@, @.>@, @.>=@, @<@, and @<=@.
Note that in this latter case the type is no longer uninterpreted, but is properly represented as a simple enumeration of the said elements. A simple
query would look like:
@
allSat $ \x -> x .== (x :: SX)
@
which would list all three elements of this domain as satisfying solutions.
@
Solution #1:
s0 = A :: X
Solution #2:
s0 = B :: X
Solution #3:
s0 = C :: X
Found 3 different solutions.
@
Note that the result is properly typed as @X@ elements; these are not mere strings. So, in a 'getModel' scenario, the user can recover actual
elements of the domain and program further with those values as usual.
-}
{-# ANN module ("HLint: ignore Use import/export shortcut" :: String) #-}
| Copilot-Language/sbv-for-copilot | Data/SBV.hs | bsd-3-clause | 39,408 | 0 | 14 | 7,294 | 4,356 | 2,555 | 1,801 | 196 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.DepthClamp
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/depth_clamp.txt ARB_depth_clamp> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.DepthClamp (
-- * Enums
gl_DEPTH_CLAMP
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/DepthClamp.hs | bsd-3-clause | 635 | 0 | 4 | 78 | 37 | 31 | 6 | 3 | 0 |
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-}
module Data.Csv.Util
( (<$!>)
, blankLine
, liftM2'
, endOfLine
, doubleQuote
, newline
, cr
, toStrict
) where
import Control.Applicative ((<|>))
import Data.Word (Word8)
import Data.Attoparsec.ByteString.Char8 (string)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.ByteString as B
import qualified Data.Vector as V
import Data.Attoparsec.ByteString (Parser)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((*>))
#endif
#if MIN_VERSION_bytestring(0,10,0)
import Data.ByteString.Lazy (toStrict)
#else
import qualified Data.ByteString.Lazy as L
toStrict :: L.ByteString -> B.ByteString
toStrict = B.concat . L.toChunks
#endif
-- | A strict version of 'Data.Functor.<$>' for monads.
(<$!>) :: Monad m => (a -> b) -> m a -> m b
f <$!> m = do
a <- m
return $! f a
{-# INLINE (<$!>) #-}
infixl 4 <$!>
-- | Is this an empty record (i.e. a blank line)?
blankLine :: V.Vector B.ByteString -> Bool
blankLine v = V.length v == 1 && (B.null (V.head v))
-- | A version of 'liftM2' that is strict in the result of its first
-- action.
liftM2' :: (Monad m) => (a -> b -> c) -> m a -> m b -> m c
liftM2' f a b = do
!x <- a
y <- b
return (f x y)
{-# INLINE liftM2' #-}
-- | Match either a single newline character @\'\\n\'@, or a carriage
-- return followed by a newline character @\"\\r\\n\"@, or a single
-- carriage return @\'\\r\'@.
endOfLine :: Parser ()
endOfLine = (A.word8 newline *> return ()) <|> (string "\r\n" *> return ()) <|> (A.word8 cr *> return ())
{-# INLINE endOfLine #-}
doubleQuote, newline, cr :: Word8
doubleQuote = 34
newline = 10
cr = 13
| hvr/cassava | src/Data/Csv/Util.hs | bsd-3-clause | 1,703 | 0 | 10 | 343 | 448 | 254 | 194 | 42 | 1 |
module Settings.Monad.Global (
module Settings.Monad.Global,
module Settings.Monad.Exception,
module Settings.Monad.Reader,
module Settings.Monad.State,
module Settings.Monad.Writer,
module Settings.Exception.GeneralException,
Async
) where
import Control.Concurrent.Async
import Control.Monad.Trans.Except
import Control.Monad.Trans.RWS.Strict
import Settings.Exception.GeneralException
import Settings.Monad.Exception
import Settings.Monad.Reader
import Settings.Monad.State
import Settings.Monad.Writer
type Global = ExceptT SomeException (RWST EnvR EnvW EnvS IO)
type Excepted a = Either SomeException a
type ExDisplayed a = Either String a
runGlobal :: Global a -> IO (Excepted a)
runGlobal g = do
(envR, envS) <- setup
(\(a,_,_) -> a) <$> runRWST (runExceptT g) envR envS
runGlobalAsync :: Global a -> IO (EnvS, Async (Excepted a))
runGlobalAsync g = do
(envR, envS) <- setup
asynced <- async $ (\(a,_,_) -> a) <$> runRWST (runExceptT g) envR envS
return (envS, asynced)
setup :: IO (EnvR, EnvS)
setup = do
maybeEnvR <- tryGetEnvR
envR <- maybe (error "Config read fault!") return maybeEnvR
envS <- getEnvS
return (envR, envS)
| Evan-Zhao/FastCanvas | src/Settings/Monad/Global.hs | bsd-3-clause | 1,283 | 0 | 12 | 293 | 404 | 228 | 176 | 34 | 1 |
{-# LANGUAGE Rank2Types, MultiParamTypeClasses, FlexibleContexts,
TypeFamilies, ScopedTypeVariables, BangPatterns #-}
-- |
-- Module : Data.Vector.Generic
-- Copyright : (c) Roman Leshchinskiy 2008-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable
--
-- Generic interface to pure vectors.
--
module Data.Vector.Generic (
-- * Immutable vectors
Vector(..), Mutable,
-- * Accessors
-- ** Length information
length, null,
-- ** Indexing
(!), (!?), head, last,
unsafeIndex, unsafeHead, unsafeLast,
-- ** Monadic indexing
indexM, headM, lastM,
unsafeIndexM, unsafeHeadM, unsafeLastM,
-- ** Extracting subvectors (slicing)
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- * Construction
-- ** Initialisation
empty, singleton, replicate, generate, iterateN,
-- ** Monadic initialisation
replicateM, generateM, create,
-- ** Unfolding
unfoldr, unfoldrN,
constructN, constructrN,
-- ** Enumeration
enumFromN, enumFromStepN, enumFromTo, enumFromThenTo,
-- ** Concatenation
cons, snoc, (++), concat,
-- ** Restricting memory usage
force,
-- * Modifying vectors
-- ** Bulk updates
(//), update, update_,
unsafeUpd, unsafeUpdate, unsafeUpdate_,
-- ** Accumulations
accum, accumulate, accumulate_,
unsafeAccum, unsafeAccumulate, unsafeAccumulate_,
-- ** Permutations
reverse, backpermute, unsafeBackpermute,
-- ** Safe destructive updates
modify,
-- * Elementwise operations
-- ** Indexing
indexed,
-- ** Mapping
map, imap, concatMap,
-- ** Monadic mapping
mapM, mapM_, forM, forM_,
-- ** Zipping
zipWith, zipWith3, zipWith4, zipWith5, zipWith6,
izipWith, izipWith3, izipWith4, izipWith5, izipWith6,
zip, zip3, zip4, zip5, zip6,
-- ** Monadic zipping
zipWithM, zipWithM_,
-- ** Unzipping
unzip, unzip3, unzip4, unzip5, unzip6,
-- * Working with predicates
-- ** Filtering
filter, ifilter, filterM,
takeWhile, dropWhile,
-- ** Partitioning
partition, unstablePartition, span, break,
-- ** Searching
elem, notElem, find, findIndex, findIndices, elemIndex, elemIndices,
-- * Folding
foldl, foldl1, foldl', foldl1', foldr, foldr1, foldr', foldr1',
ifoldl, ifoldl', ifoldr, ifoldr',
-- ** Specialised folds
all, any, and, or,
sum, product,
maximum, maximumBy, minimum, minimumBy,
minIndex, minIndexBy, maxIndex, maxIndexBy,
-- ** Monadic folds
foldM, foldM', fold1M, fold1M',
foldM_, foldM'_, fold1M_, fold1M'_,
-- ** Monadic sequencing
sequence, sequence_,
-- * Prefix sums (scans)
prescanl, prescanl',
postscanl, postscanl',
scanl, scanl', scanl1, scanl1',
prescanr, prescanr',
postscanr, postscanr',
scanr, scanr', scanr1, scanr1',
-- * Conversions
-- ** Lists
toList, fromList, fromListN,
-- ** Different vector types
convert,
-- ** Mutable vectors
freeze, thaw, copy, unsafeFreeze, unsafeThaw, unsafeCopy,
-- * Fusion support
-- ** Conversion to/from Streams
stream, unstream, streamR, unstreamR,
-- ** Recycling support
new, clone,
-- * Utilities
-- ** Comparisons
eq, cmp,
-- ** Show and Read
showsPrec, readPrec,
-- ** @Data@ and @Typeable@
gfoldl, dataCast, mkType
) where
import Data.Vector.Generic.Base
import Data.Vector.Generic.Mutable ( MVector )
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Generic.New as New
import Data.Vector.Generic.New ( New )
import qualified Data.Vector.Fusion.Stream as Stream
import Data.Vector.Fusion.Stream ( Stream, MStream, Step(..), inplace, liftStream )
import qualified Data.Vector.Fusion.Stream.Monadic as MStream
import Data.Vector.Fusion.Stream.Size
import Data.Vector.Fusion.Util
import Control.Monad.ST ( ST, runST )
import Control.Monad.Primitive
import qualified Control.Monad as Monad
import qualified Data.List as List
import Prelude hiding ( length, null,
replicate, (++), concat,
head, last,
init, tail, take, drop, splitAt, reverse,
map, concat, concatMap,
zipWith, zipWith3, zip, zip3, unzip, unzip3,
filter, takeWhile, dropWhile, span, break,
elem, notElem,
foldl, foldl1, foldr, foldr1,
all, any, and, or, sum, product, maximum, minimum,
scanl, scanl1, scanr, scanr1,
enumFromTo, enumFromThenTo,
mapM, mapM_, sequence, sequence_,
showsPrec )
import qualified Text.Read as Read
#if __GLASGOW_HASKELL__ >= 707
import Data.Typeable ( Typeable, gcast1 )
#else
import Data.Typeable ( Typeable1, gcast1 )
#endif
#include "vector.h"
import Data.Data ( Data, DataType )
#if MIN_VERSION_base(4,2,0)
import Data.Data ( mkNoRepType )
#else
import Data.Data ( mkNorepType )
mkNoRepType :: String -> DataType
mkNoRepType = mkNorepType
#endif
-- Length information
-- ------------------
-- | /O(1)/ Yield the length of the vector.
length :: Vector v a => v a -> Int
{-# INLINE_STREAM length #-}
length v = basicLength v
{-# RULES
"length/unstream [Vector]" forall s.
length (new (New.unstream s)) = Stream.length s
#-}
-- | /O(1)/ Test whether a vector if empty
null :: Vector v a => v a -> Bool
{-# INLINE_STREAM null #-}
null v = basicLength v == 0
{-# RULES
"null/unstream [Vector]" forall s.
null (new (New.unstream s)) = Stream.null s
#-}
-- Indexing
-- --------
infixl 9 !
-- | O(1) Indexing
(!) :: Vector v a => v a -> Int -> a
{-# INLINE_STREAM (!) #-}
(!) v i = BOUNDS_CHECK(checkIndex) "(!)" i (length v)
$ unId (basicUnsafeIndexM v i)
infixl 9 !?
-- | O(1) Safe indexing
(!?) :: Vector v a => v a -> Int -> Maybe a
{-# INLINE_STREAM (!?) #-}
v !? i | i < 0 || i >= length v = Nothing
| otherwise = Just $ unsafeIndex v i
-- | /O(1)/ First element
head :: Vector v a => v a -> a
{-# INLINE_STREAM head #-}
head v = v ! 0
-- | /O(1)/ Last element
last :: Vector v a => v a -> a
{-# INLINE_STREAM last #-}
last v = v ! (length v - 1)
-- | /O(1)/ Unsafe indexing without bounds checking
unsafeIndex :: Vector v a => v a -> Int -> a
{-# INLINE_STREAM unsafeIndex #-}
unsafeIndex v i = UNSAFE_CHECK(checkIndex) "unsafeIndex" i (length v)
$ unId (basicUnsafeIndexM v i)
-- | /O(1)/ First element without checking if the vector is empty
unsafeHead :: Vector v a => v a -> a
{-# INLINE_STREAM unsafeHead #-}
unsafeHead v = unsafeIndex v 0
-- | /O(1)/ Last element without checking if the vector is empty
unsafeLast :: Vector v a => v a -> a
{-# INLINE_STREAM unsafeLast #-}
unsafeLast v = unsafeIndex v (length v - 1)
{-# RULES
"(!)/unstream [Vector]" forall i s.
new (New.unstream s) ! i = s Stream.!! i
"(!?)/unstream [Vector]" forall i s.
new (New.unstream s) !? i = s Stream.!? i
"head/unstream [Vector]" forall s.
head (new (New.unstream s)) = Stream.head s
"last/unstream [Vector]" forall s.
last (new (New.unstream s)) = Stream.last s
"unsafeIndex/unstream [Vector]" forall i s.
unsafeIndex (new (New.unstream s)) i = s Stream.!! i
"unsafeHead/unstream [Vector]" forall s.
unsafeHead (new (New.unstream s)) = Stream.head s
"unsafeLast/unstream [Vector]" forall s.
unsafeLast (new (New.unstream s)) = Stream.last s
#-}
-- Monadic indexing
-- ----------------
-- | /O(1)/ Indexing in a monad.
--
-- The monad allows operations to be strict in the vector when necessary.
-- Suppose vector copying is implemented like this:
--
-- > copy mv v = ... write mv i (v ! i) ...
--
-- For lazy vectors, @v ! i@ would not be evaluated which means that @mv@
-- would unnecessarily retain a reference to @v@ in each element written.
--
-- With 'indexM', copying can be implemented like this instead:
--
-- > copy mv v = ... do
-- > x <- indexM v i
-- > write mv i x
--
-- Here, no references to @v@ are retained because indexing (but /not/ the
-- elements) is evaluated eagerly.
--
indexM :: (Vector v a, Monad m) => v a -> Int -> m a
{-# INLINE_STREAM indexM #-}
indexM v i = BOUNDS_CHECK(checkIndex) "indexM" i (length v)
$ basicUnsafeIndexM v i
-- | /O(1)/ First element of a vector in a monad. See 'indexM' for an
-- explanation of why this is useful.
headM :: (Vector v a, Monad m) => v a -> m a
{-# INLINE_STREAM headM #-}
headM v = indexM v 0
-- | /O(1)/ Last element of a vector in a monad. See 'indexM' for an
-- explanation of why this is useful.
lastM :: (Vector v a, Monad m) => v a -> m a
{-# INLINE_STREAM lastM #-}
lastM v = indexM v (length v - 1)
-- | /O(1)/ Indexing in a monad without bounds checks. See 'indexM' for an
-- explanation of why this is useful.
unsafeIndexM :: (Vector v a, Monad m) => v a -> Int -> m a
{-# INLINE_STREAM unsafeIndexM #-}
unsafeIndexM v i = UNSAFE_CHECK(checkIndex) "unsafeIndexM" i (length v)
$ basicUnsafeIndexM v i
-- | /O(1)/ First element in a monad without checking for empty vectors.
-- See 'indexM' for an explanation of why this is useful.
unsafeHeadM :: (Vector v a, Monad m) => v a -> m a
{-# INLINE_STREAM unsafeHeadM #-}
unsafeHeadM v = unsafeIndexM v 0
-- | /O(1)/ Last element in a monad without checking for empty vectors.
-- See 'indexM' for an explanation of why this is useful.
unsafeLastM :: (Vector v a, Monad m) => v a -> m a
{-# INLINE_STREAM unsafeLastM #-}
unsafeLastM v = unsafeIndexM v (length v - 1)
{-# RULES
"indexM/unstream [Vector]" forall s i.
indexM (new (New.unstream s)) i = liftStream s MStream.!! i
"headM/unstream [Vector]" forall s.
headM (new (New.unstream s)) = MStream.head (liftStream s)
"lastM/unstream [Vector]" forall s.
lastM (new (New.unstream s)) = MStream.last (liftStream s)
"unsafeIndexM/unstream [Vector]" forall s i.
unsafeIndexM (new (New.unstream s)) i = liftStream s MStream.!! i
"unsafeHeadM/unstream [Vector]" forall s.
unsafeHeadM (new (New.unstream s)) = MStream.head (liftStream s)
"unsafeLastM/unstream [Vector]" forall s.
unsafeLastM (new (New.unstream s)) = MStream.last (liftStream s)
#-}
-- Extracting subvectors (slicing)
-- -------------------------------
-- | /O(1)/ Yield a slice of the vector without copying it. The vector must
-- contain at least @i+n@ elements.
slice :: Vector v a => Int -- ^ @i@ starting index
-> Int -- ^ @n@ length
-> v a
-> v a
{-# INLINE_STREAM slice #-}
slice i n v = BOUNDS_CHECK(checkSlice) "slice" i n (length v)
$ basicUnsafeSlice i n v
-- | /O(1)/ Yield all but the last element without copying. The vector may not
-- be empty.
init :: Vector v a => v a -> v a
{-# INLINE_STREAM init #-}
init v = slice 0 (length v - 1) v
-- | /O(1)/ Yield all but the first element without copying. The vector may not
-- be empty.
tail :: Vector v a => v a -> v a
{-# INLINE_STREAM tail #-}
tail v = slice 1 (length v - 1) v
-- | /O(1)/ Yield the first @n@ elements without copying. The vector may
-- contain less than @n@ elements in which case it is returned unchanged.
take :: Vector v a => Int -> v a -> v a
{-# INLINE_STREAM take #-}
take n v = unsafeSlice 0 (delay_inline min n' (length v)) v
where n' = max n 0
-- | /O(1)/ Yield all but the first @n@ elements without copying. The vector may
-- contain less than @n@ elements in which case an empty vector is returned.
drop :: Vector v a => Int -> v a -> v a
{-# INLINE_STREAM drop #-}
drop n v = unsafeSlice (delay_inline min n' len)
(delay_inline max 0 (len - n')) v
where n' = max n 0
len = length v
-- | /O(1)/ Yield the first @n@ elements paired with the remainder without copying.
--
-- Note that @'splitAt' n v@ is equivalent to @('take' n v, 'drop' n v)@
-- but slightly more efficient.
{-# INLINE_STREAM splitAt #-}
splitAt :: Vector v a => Int -> v a -> (v a, v a)
splitAt n v = ( unsafeSlice 0 m v
, unsafeSlice m (delay_inline max 0 (len - n')) v
)
where
m = delay_inline min n' len
n' = max n 0
len = length v
-- | /O(1)/ Yield a slice of the vector without copying. The vector must
-- contain at least @i+n@ elements but this is not checked.
unsafeSlice :: Vector v a => Int -- ^ @i@ starting index
-> Int -- ^ @n@ length
-> v a
-> v a
{-# INLINE_STREAM unsafeSlice #-}
unsafeSlice i n v = UNSAFE_CHECK(checkSlice) "unsafeSlice" i n (length v)
$ basicUnsafeSlice i n v
-- | /O(1)/ Yield all but the last element without copying. The vector may not
-- be empty but this is not checked.
unsafeInit :: Vector v a => v a -> v a
{-# INLINE_STREAM unsafeInit #-}
unsafeInit v = unsafeSlice 0 (length v - 1) v
-- | /O(1)/ Yield all but the first element without copying. The vector may not
-- be empty but this is not checked.
unsafeTail :: Vector v a => v a -> v a
{-# INLINE_STREAM unsafeTail #-}
unsafeTail v = unsafeSlice 1 (length v - 1) v
-- | /O(1)/ Yield the first @n@ elements without copying. The vector must
-- contain at least @n@ elements but this is not checked.
unsafeTake :: Vector v a => Int -> v a -> v a
{-# INLINE unsafeTake #-}
unsafeTake n v = unsafeSlice 0 n v
-- | /O(1)/ Yield all but the first @n@ elements without copying. The vector
-- must contain at least @n@ elements but this is not checked.
unsafeDrop :: Vector v a => Int -> v a -> v a
{-# INLINE unsafeDrop #-}
unsafeDrop n v = unsafeSlice n (length v - n) v
{-# RULES
"slice/new [Vector]" forall i n p.
slice i n (new p) = new (New.slice i n p)
"init/new [Vector]" forall p.
init (new p) = new (New.init p)
"tail/new [Vector]" forall p.
tail (new p) = new (New.tail p)
"take/new [Vector]" forall n p.
take n (new p) = new (New.take n p)
"drop/new [Vector]" forall n p.
drop n (new p) = new (New.drop n p)
"unsafeSlice/new [Vector]" forall i n p.
unsafeSlice i n (new p) = new (New.unsafeSlice i n p)
"unsafeInit/new [Vector]" forall p.
unsafeInit (new p) = new (New.unsafeInit p)
"unsafeTail/new [Vector]" forall p.
unsafeTail (new p) = new (New.unsafeTail p)
#-}
-- Initialisation
-- --------------
-- | /O(1)/ Empty vector
empty :: Vector v a => v a
{-# INLINE empty #-}
empty = unstream Stream.empty
-- | /O(1)/ Vector with exactly one element
singleton :: forall v a. Vector v a => a -> v a
{-# INLINE singleton #-}
singleton x = elemseq (undefined :: v a) x
$ unstream (Stream.singleton x)
-- | /O(n)/ Vector of the given length with the same value in each position
replicate :: forall v a. Vector v a => Int -> a -> v a
{-# INLINE replicate #-}
replicate n x = elemseq (undefined :: v a) x
$ unstream
$ Stream.replicate n x
-- | /O(n)/ Construct a vector of the given length by applying the function to
-- each index
generate :: Vector v a => Int -> (Int -> a) -> v a
{-# INLINE generate #-}
generate n f = unstream (Stream.generate n f)
-- | /O(n)/ Apply function n times to value. Zeroth element is original value.
iterateN :: Vector v a => Int -> (a -> a) -> a -> v a
{-# INLINE iterateN #-}
iterateN n f x = unstream (Stream.iterateN n f x)
-- Unfolding
-- ---------
-- | /O(n)/ Construct a vector by repeatedly applying the generator function
-- to a seed. The generator function yields 'Just' the next element and the
-- new seed or 'Nothing' if there are no more elements.
--
-- > unfoldr (\n -> if n == 0 then Nothing else Just (n,n-1)) 10
-- > = <10,9,8,7,6,5,4,3,2,1>
unfoldr :: Vector v a => (b -> Maybe (a, b)) -> b -> v a
{-# INLINE unfoldr #-}
unfoldr f = unstream . Stream.unfoldr f
-- | /O(n)/ Construct a vector with at most @n@ by repeatedly applying the
-- generator function to the a seed. The generator function yields 'Just' the
-- next element and the new seed or 'Nothing' if there are no more elements.
--
-- > unfoldrN 3 (\n -> Just (n,n-1)) 10 = <10,9,8>
unfoldrN :: Vector v a => Int -> (b -> Maybe (a, b)) -> b -> v a
{-# INLINE unfoldrN #-}
unfoldrN n f = unstream . Stream.unfoldrN n f
-- | /O(n)/ Construct a vector with @n@ elements by repeatedly applying the
-- generator function to the already constructed part of the vector.
--
-- > constructN 3 f = let a = f <> ; b = f <a> ; c = f <a,b> in f <a,b,c>
--
constructN :: forall v a. Vector v a => Int -> (v a -> a) -> v a
{-# INLINE constructN #-}
-- NOTE: We *CANNOT* wrap this in New and then fuse because the elements
-- might contain references to the immutable vector!
constructN !n f = runST (
do
v <- M.new n
v' <- unsafeFreeze v
fill v' 0
)
where
fill :: forall s. v a -> Int -> ST s (v a)
fill !v i | i < n = let x = f (unsafeTake i v)
in
elemseq v x $
do
v' <- unsafeThaw v
M.unsafeWrite v' i x
v'' <- unsafeFreeze v'
fill v'' (i+1)
fill v i = return v
-- | /O(n)/ Construct a vector with @n@ elements from right to left by
-- repeatedly applying the generator function to the already constructed part
-- of the vector.
--
-- > constructrN 3 f = let a = f <> ; b = f<a> ; c = f <b,a> in f <c,b,a>
--
constructrN :: forall v a. Vector v a => Int -> (v a -> a) -> v a
{-# INLINE constructrN #-}
-- NOTE: We *CANNOT* wrap this in New and then fuse because the elements
-- might contain references to the immutable vector!
constructrN !n f = runST (
do
v <- n `seq` M.new n
v' <- unsafeFreeze v
fill v' 0
)
where
fill :: forall s. v a -> Int -> ST s (v a)
fill !v i | i < n = let x = f (unsafeSlice (n-i) i v)
in
elemseq v x $
do
v' <- unsafeThaw v
M.unsafeWrite v' (n-i-1) x
v'' <- unsafeFreeze v'
fill v'' (i+1)
fill v i = return v
-- Enumeration
-- -----------
-- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+1@
-- etc. This operation is usually more efficient than 'enumFromTo'.
--
-- > enumFromN 5 3 = <5,6,7>
enumFromN :: (Vector v a, Num a) => a -> Int -> v a
{-# INLINE enumFromN #-}
enumFromN x n = enumFromStepN x 1 n
-- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+y@,
-- @x+y+y@ etc. This operations is usually more efficient than 'enumFromThenTo'.
--
-- > enumFromStepN 1 0.1 5 = <1,1.1,1.2,1.3,1.4>
enumFromStepN :: forall v a. (Vector v a, Num a) => a -> a -> Int -> v a
{-# INLINE enumFromStepN #-}
enumFromStepN x y n = elemseq (undefined :: v a) x
$ elemseq (undefined :: v a) y
$ unstream
$ Stream.enumFromStepN x y n
-- | /O(n)/ Enumerate values from @x@ to @y@.
--
-- /WARNING:/ This operation can be very inefficient. If at all possible, use
-- 'enumFromN' instead.
enumFromTo :: (Vector v a, Enum a) => a -> a -> v a
{-# INLINE enumFromTo #-}
enumFromTo x y = unstream (Stream.enumFromTo x y)
-- | /O(n)/ Enumerate values from @x@ to @y@ with a specific step @z@.
--
-- /WARNING:/ This operation can be very inefficient. If at all possible, use
-- 'enumFromStepN' instead.
enumFromThenTo :: (Vector v a, Enum a) => a -> a -> a -> v a
{-# INLINE enumFromThenTo #-}
enumFromThenTo x y z = unstream (Stream.enumFromThenTo x y z)
-- Concatenation
-- -------------
-- | /O(n)/ Prepend an element
cons :: forall v a. Vector v a => a -> v a -> v a
{-# INLINE cons #-}
cons x v = elemseq (undefined :: v a) x
$ unstream
$ Stream.cons x
$ stream v
-- | /O(n)/ Append an element
snoc :: forall v a. Vector v a => v a -> a -> v a
{-# INLINE snoc #-}
snoc v x = elemseq (undefined :: v a) x
$ unstream
$ Stream.snoc (stream v) x
infixr 5 ++
-- | /O(m+n)/ Concatenate two vectors
(++) :: Vector v a => v a -> v a -> v a
{-# INLINE (++) #-}
v ++ w = unstream (stream v Stream.++ stream w)
-- | /O(n)/ Concatenate all vectors in the list
concat :: Vector v a => [v a] -> v a
{-# INLINE concat #-}
concat vs = unstream (Stream.flatten mk step (Exact n) (Stream.fromList vs))
where
n = List.foldl' (\k v -> k + length v) 0 vs
{-# INLINE_INNER step #-}
step (v,i,k)
| i < k = case unsafeIndexM v i of
Box x -> Stream.Yield x (v,i+1,k)
| otherwise = Stream.Done
{-# INLINE mk #-}
mk v = let k = length v
in
k `seq` (v,0,k)
-- Monadic initialisation
-- ----------------------
-- | /O(n)/ Execute the monadic action the given number of times and store the
-- results in a vector.
replicateM :: (Monad m, Vector v a) => Int -> m a -> m (v a)
{-# INLINE replicateM #-}
replicateM n m = unstreamM (MStream.replicateM n m)
-- | /O(n)/ Construct a vector of the given length by applying the monadic
-- action to each index
generateM :: (Monad m, Vector v a) => Int -> (Int -> m a) -> m (v a)
{-# INLINE generateM #-}
generateM n f = unstreamM (MStream.generateM n f)
-- | Execute the monadic action and freeze the resulting vector.
--
-- @
-- create (do { v \<- 'M.new' 2; 'M.write' v 0 \'a\'; 'M.write' v 1 \'b\'; return v }) = \<'a','b'\>
-- @
create :: Vector v a => (forall s. ST s (Mutable v s a)) -> v a
{-# INLINE create #-}
create p = new (New.create p)
-- Restricting memory usage
-- ------------------------
-- | /O(n)/ Yield the argument but force it not to retain any extra memory,
-- possibly by copying it.
--
-- This is especially useful when dealing with slices. For example:
--
-- > force (slice 0 2 <huge vector>)
--
-- Here, the slice retains a reference to the huge vector. Forcing it creates
-- a copy of just the elements that belong to the slice and allows the huge
-- vector to be garbage collected.
force :: Vector v a => v a -> v a
-- FIXME: we probably ought to inline this later as the rules still might fire
-- otherwise
{-# INLINE_STREAM force #-}
force v = new (clone v)
-- Bulk updates
-- ------------
-- | /O(m+n)/ For each pair @(i,a)@ from the list, replace the vector
-- element at position @i@ by @a@.
--
-- > <5,9,2,7> // [(2,1),(0,3),(2,8)] = <3,9,8,7>
--
(//) :: Vector v a => v a -- ^ initial vector (of length @m@)
-> [(Int, a)] -- ^ list of index/value pairs (of length @n@)
-> v a
{-# INLINE (//) #-}
v // us = update_stream v (Stream.fromList us)
-- | /O(m+n)/ For each pair @(i,a)@ from the vector of index/value pairs,
-- replace the vector element at position @i@ by @a@.
--
-- > update <5,9,2,7> <(2,1),(0,3),(2,8)> = <3,9,8,7>
--
update :: (Vector v a, Vector v (Int, a))
=> v a -- ^ initial vector (of length @m@)
-> v (Int, a) -- ^ vector of index/value pairs (of length @n@)
-> v a
{-# INLINE update #-}
update v w = update_stream v (stream w)
-- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the
-- corresponding value @a@ from the value vector, replace the element of the
-- initial vector at position @i@ by @a@.
--
-- > update_ <5,9,2,7> <2,0,2> <1,3,8> = <3,9,8,7>
--
-- This function is useful for instances of 'Vector' that cannot store pairs.
-- Otherwise, 'update' is probably more convenient.
--
-- @
-- update_ xs is ys = 'update' xs ('zip' is ys)
-- @
update_ :: (Vector v a, Vector v Int)
=> v a -- ^ initial vector (of length @m@)
-> v Int -- ^ index vector (of length @n1@)
-> v a -- ^ value vector (of length @n2@)
-> v a
{-# INLINE update_ #-}
update_ v is w = update_stream v (Stream.zipWith (,) (stream is) (stream w))
update_stream :: Vector v a => v a -> Stream (Int,a) -> v a
{-# INLINE update_stream #-}
update_stream = modifyWithStream M.update
-- | Same as ('//') but without bounds checking.
unsafeUpd :: Vector v a => v a -> [(Int, a)] -> v a
{-# INLINE unsafeUpd #-}
unsafeUpd v us = unsafeUpdate_stream v (Stream.fromList us)
-- | Same as 'update' but without bounds checking.
unsafeUpdate :: (Vector v a, Vector v (Int, a)) => v a -> v (Int, a) -> v a
{-# INLINE unsafeUpdate #-}
unsafeUpdate v w = unsafeUpdate_stream v (stream w)
-- | Same as 'update_' but without bounds checking.
unsafeUpdate_ :: (Vector v a, Vector v Int) => v a -> v Int -> v a -> v a
{-# INLINE unsafeUpdate_ #-}
unsafeUpdate_ v is w
= unsafeUpdate_stream v (Stream.zipWith (,) (stream is) (stream w))
unsafeUpdate_stream :: Vector v a => v a -> Stream (Int,a) -> v a
{-# INLINE unsafeUpdate_stream #-}
unsafeUpdate_stream = modifyWithStream M.unsafeUpdate
-- Accumulations
-- -------------
-- | /O(m+n)/ For each pair @(i,b)@ from the list, replace the vector element
-- @a@ at position @i@ by @f a b@.
--
-- > accum (+) <5,9,2> [(2,4),(1,6),(0,3),(1,7)] = <5+3, 9+6+7, 2+4>
accum :: Vector v a
=> (a -> b -> a) -- ^ accumulating function @f@
-> v a -- ^ initial vector (of length @m@)
-> [(Int,b)] -- ^ list of index/value pairs (of length @n@)
-> v a
{-# INLINE accum #-}
accum f v us = accum_stream f v (Stream.fromList us)
-- | /O(m+n)/ For each pair @(i,b)@ from the vector of pairs, replace the vector
-- element @a@ at position @i@ by @f a b@.
--
-- > accumulate (+) <5,9,2> <(2,4),(1,6),(0,3),(1,7)> = <5+3, 9+6+7, 2+4>
accumulate :: (Vector v a, Vector v (Int, b))
=> (a -> b -> a) -- ^ accumulating function @f@
-> v a -- ^ initial vector (of length @m@)
-> v (Int,b) -- ^ vector of index/value pairs (of length @n@)
-> v a
{-# INLINE accumulate #-}
accumulate f v us = accum_stream f v (stream us)
-- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the
-- corresponding value @b@ from the the value vector,
-- replace the element of the initial vector at
-- position @i@ by @f a b@.
--
-- > accumulate_ (+) <5,9,2> <2,1,0,1> <4,6,3,7> = <5+3, 9+6+7, 2+4>
--
-- This function is useful for instances of 'Vector' that cannot store pairs.
-- Otherwise, 'accumulate' is probably more convenient:
--
-- @
-- accumulate_ f as is bs = 'accumulate' f as ('zip' is bs)
-- @
accumulate_ :: (Vector v a, Vector v Int, Vector v b)
=> (a -> b -> a) -- ^ accumulating function @f@
-> v a -- ^ initial vector (of length @m@)
-> v Int -- ^ index vector (of length @n1@)
-> v b -- ^ value vector (of length @n2@)
-> v a
{-# INLINE accumulate_ #-}
accumulate_ f v is xs = accum_stream f v (Stream.zipWith (,) (stream is)
(stream xs))
accum_stream :: Vector v a => (a -> b -> a) -> v a -> Stream (Int,b) -> v a
{-# INLINE accum_stream #-}
accum_stream f = modifyWithStream (M.accum f)
-- | Same as 'accum' but without bounds checking.
unsafeAccum :: Vector v a => (a -> b -> a) -> v a -> [(Int,b)] -> v a
{-# INLINE unsafeAccum #-}
unsafeAccum f v us = unsafeAccum_stream f v (Stream.fromList us)
-- | Same as 'accumulate' but without bounds checking.
unsafeAccumulate :: (Vector v a, Vector v (Int, b))
=> (a -> b -> a) -> v a -> v (Int,b) -> v a
{-# INLINE unsafeAccumulate #-}
unsafeAccumulate f v us = unsafeAccum_stream f v (stream us)
-- | Same as 'accumulate_' but without bounds checking.
unsafeAccumulate_ :: (Vector v a, Vector v Int, Vector v b)
=> (a -> b -> a) -> v a -> v Int -> v b -> v a
{-# INLINE unsafeAccumulate_ #-}
unsafeAccumulate_ f v is xs
= unsafeAccum_stream f v (Stream.zipWith (,) (stream is) (stream xs))
unsafeAccum_stream
:: Vector v a => (a -> b -> a) -> v a -> Stream (Int,b) -> v a
{-# INLINE unsafeAccum_stream #-}
unsafeAccum_stream f = modifyWithStream (M.unsafeAccum f)
-- Permutations
-- ------------
-- | /O(n)/ Reverse a vector
reverse :: (Vector v a) => v a -> v a
{-# INLINE reverse #-}
-- FIXME: make this fuse better, add support for recycling
reverse = unstream . streamR
-- | /O(n)/ Yield the vector obtained by replacing each element @i@ of the
-- index vector by @xs'!'i@. This is equivalent to @'map' (xs'!') is@ but is
-- often much more efficient.
--
-- > backpermute <a,b,c,d> <0,3,2,3,1,0> = <a,d,c,d,b,a>
backpermute :: (Vector v a, Vector v Int)
=> v a -- ^ @xs@ value vector
-> v Int -- ^ @is@ index vector (of length @n@)
-> v a
{-# INLINE backpermute #-}
-- This somewhat non-intuitive definition ensures that the resulting vector
-- does not retain references to the original one even if it is lazy in its
-- elements. This would not be the case if we simply used map (v!)
backpermute v is = seq v
$ seq n
$ unstream
$ Stream.unbox
$ Stream.map index
$ stream is
where
n = length v
{-# INLINE index #-}
-- NOTE: we do it this way to avoid triggering LiberateCase on n in
-- polymorphic code
index i = BOUNDS_CHECK(checkIndex) "backpermute" i n
$ basicUnsafeIndexM v i
-- | Same as 'backpermute' but without bounds checking.
unsafeBackpermute :: (Vector v a, Vector v Int) => v a -> v Int -> v a
{-# INLINE unsafeBackpermute #-}
unsafeBackpermute v is = seq v
$ seq n
$ unstream
$ Stream.unbox
$ Stream.map index
$ stream is
where
n = length v
{-# INLINE index #-}
-- NOTE: we do it this way to avoid triggering LiberateCase on n in
-- polymorphic code
index i = UNSAFE_CHECK(checkIndex) "unsafeBackpermute" i n
$ basicUnsafeIndexM v i
-- Safe destructive updates
-- ------------------------
-- | Apply a destructive operation to a vector. The operation will be
-- performed in place if it is safe to do so and will modify a copy of the
-- vector otherwise.
--
-- @
-- modify (\\v -> 'M.write' v 0 \'x\') ('replicate' 3 \'a\') = \<\'x\',\'a\',\'a\'\>
-- @
modify :: Vector v a => (forall s. Mutable v s a -> ST s ()) -> v a -> v a
{-# INLINE modify #-}
modify p = new . New.modify p . clone
-- We have to make sure that this is strict in the stream but we can't seq on
-- it while fusion is happening. Hence this ugliness.
modifyWithStream :: Vector v a
=> (forall s. Mutable v s a -> Stream b -> ST s ())
-> v a -> Stream b -> v a
{-# INLINE modifyWithStream #-}
modifyWithStream p v s = new (New.modifyWithStream p (clone v) s)
-- Indexing
-- --------
-- | /O(n)/ Pair each element in a vector with its index
indexed :: (Vector v a, Vector v (Int,a)) => v a -> v (Int,a)
{-# INLINE indexed #-}
indexed = unstream . Stream.indexed . stream
-- Mapping
-- -------
-- | /O(n)/ Map a function over a vector
map :: (Vector v a, Vector v b) => (a -> b) -> v a -> v b
{-# INLINE map #-}
map f = unstream . inplace (MStream.map f) . stream
-- | /O(n)/ Apply a function to every element of a vector and its index
imap :: (Vector v a, Vector v b) => (Int -> a -> b) -> v a -> v b
{-# INLINE imap #-}
imap f = unstream . inplace (MStream.map (uncurry f) . MStream.indexed)
. stream
-- | Map a function over a vector and concatenate the results.
concatMap :: (Vector v a, Vector v b) => (a -> v b) -> v a -> v b
{-# INLINE concatMap #-}
-- NOTE: We can't fuse concatMap anyway so don't pretend we do.
-- This seems to be slightly slower
-- concatMap f = concat . Stream.toList . Stream.map f . stream
-- Slowest
-- concatMap f = unstream . Stream.concatMap (stream . f) . stream
-- Seems to be fastest
concatMap f = unstream
. Stream.flatten mk step Unknown
. stream
where
{-# INLINE_INNER step #-}
step (v,i,k)
| i < k = case unsafeIndexM v i of
Box x -> Stream.Yield x (v,i+1,k)
| otherwise = Stream.Done
{-# INLINE mk #-}
mk x = let v = f x
k = length v
in
k `seq` (v,0,k)
-- Monadic mapping
-- ---------------
-- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a
-- vector of results
mapM :: (Monad m, Vector v a, Vector v b) => (a -> m b) -> v a -> m (v b)
{-# INLINE mapM #-}
mapM f = unstreamM . Stream.mapM f . stream
-- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the
-- results
mapM_ :: (Monad m, Vector v a) => (a -> m b) -> v a -> m ()
{-# INLINE mapM_ #-}
mapM_ f = Stream.mapM_ f . stream
-- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a
-- vector of results. Equvalent to @flip 'mapM'@.
forM :: (Monad m, Vector v a, Vector v b) => v a -> (a -> m b) -> m (v b)
{-# INLINE forM #-}
forM as f = mapM f as
-- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the
-- results. Equivalent to @flip 'mapM_'@.
forM_ :: (Monad m, Vector v a) => v a -> (a -> m b) -> m ()
{-# INLINE forM_ #-}
forM_ as f = mapM_ f as
-- Zipping
-- -------
-- | /O(min(m,n))/ Zip two vectors with the given function.
zipWith :: (Vector v a, Vector v b, Vector v c)
=> (a -> b -> c) -> v a -> v b -> v c
{-# INLINE zipWith #-}
zipWith f xs ys = unstream (Stream.zipWith f (stream xs) (stream ys))
-- | Zip three vectors with the given function.
zipWith3 :: (Vector v a, Vector v b, Vector v c, Vector v d)
=> (a -> b -> c -> d) -> v a -> v b -> v c -> v d
{-# INLINE zipWith3 #-}
zipWith3 f as bs cs = unstream (Stream.zipWith3 f (stream as)
(stream bs)
(stream cs))
zipWith4 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e)
=> (a -> b -> c -> d -> e) -> v a -> v b -> v c -> v d -> v e
{-# INLINE zipWith4 #-}
zipWith4 f as bs cs ds
= unstream (Stream.zipWith4 f (stream as)
(stream bs)
(stream cs)
(stream ds))
zipWith5 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v f)
=> (a -> b -> c -> d -> e -> f) -> v a -> v b -> v c -> v d -> v e
-> v f
{-# INLINE zipWith5 #-}
zipWith5 f as bs cs ds es
= unstream (Stream.zipWith5 f (stream as)
(stream bs)
(stream cs)
(stream ds)
(stream es))
zipWith6 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v f, Vector v g)
=> (a -> b -> c -> d -> e -> f -> g)
-> v a -> v b -> v c -> v d -> v e -> v f -> v g
{-# INLINE zipWith6 #-}
zipWith6 f as bs cs ds es fs
= unstream (Stream.zipWith6 f (stream as)
(stream bs)
(stream cs)
(stream ds)
(stream es)
(stream fs))
-- | /O(min(m,n))/ Zip two vectors with a function that also takes the
-- elements' indices.
izipWith :: (Vector v a, Vector v b, Vector v c)
=> (Int -> a -> b -> c) -> v a -> v b -> v c
{-# INLINE izipWith #-}
izipWith f xs ys = unstream
(Stream.zipWith (uncurry f) (Stream.indexed (stream xs))
(stream ys))
izipWith3 :: (Vector v a, Vector v b, Vector v c, Vector v d)
=> (Int -> a -> b -> c -> d) -> v a -> v b -> v c -> v d
{-# INLINE izipWith3 #-}
izipWith3 f as bs cs
= unstream (Stream.zipWith3 (uncurry f) (Stream.indexed (stream as))
(stream bs)
(stream cs))
izipWith4 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e)
=> (Int -> a -> b -> c -> d -> e) -> v a -> v b -> v c -> v d -> v e
{-# INLINE izipWith4 #-}
izipWith4 f as bs cs ds
= unstream (Stream.zipWith4 (uncurry f) (Stream.indexed (stream as))
(stream bs)
(stream cs)
(stream ds))
izipWith5 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v f)
=> (Int -> a -> b -> c -> d -> e -> f) -> v a -> v b -> v c -> v d
-> v e -> v f
{-# INLINE izipWith5 #-}
izipWith5 f as bs cs ds es
= unstream (Stream.zipWith5 (uncurry f) (Stream.indexed (stream as))
(stream bs)
(stream cs)
(stream ds)
(stream es))
izipWith6 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v f, Vector v g)
=> (Int -> a -> b -> c -> d -> e -> f -> g)
-> v a -> v b -> v c -> v d -> v e -> v f -> v g
{-# INLINE izipWith6 #-}
izipWith6 f as bs cs ds es fs
= unstream (Stream.zipWith6 (uncurry f) (Stream.indexed (stream as))
(stream bs)
(stream cs)
(stream ds)
(stream es)
(stream fs))
-- | /O(min(m,n))/ Zip two vectors
zip :: (Vector v a, Vector v b, Vector v (a,b)) => v a -> v b -> v (a, b)
{-# INLINE zip #-}
zip = zipWith (,)
zip3 :: (Vector v a, Vector v b, Vector v c, Vector v (a, b, c))
=> v a -> v b -> v c -> v (a, b, c)
{-# INLINE zip3 #-}
zip3 = zipWith3 (,,)
zip4 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v (a, b, c, d))
=> v a -> v b -> v c -> v d -> v (a, b, c, d)
{-# INLINE zip4 #-}
zip4 = zipWith4 (,,,)
zip5 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v (a, b, c, d, e))
=> v a -> v b -> v c -> v d -> v e -> v (a, b, c, d, e)
{-# INLINE zip5 #-}
zip5 = zipWith5 (,,,,)
zip6 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v f, Vector v (a, b, c, d, e, f))
=> v a -> v b -> v c -> v d -> v e -> v f -> v (a, b, c, d, e, f)
{-# INLINE zip6 #-}
zip6 = zipWith6 (,,,,,)
-- Monadic zipping
-- ---------------
-- | /O(min(m,n))/ Zip the two vectors with the monadic action and yield a
-- vector of results
zipWithM :: (Monad m, Vector v a, Vector v b, Vector v c)
=> (a -> b -> m c) -> v a -> v b -> m (v c)
-- FIXME: specialise for ST and IO?
{-# INLINE zipWithM #-}
zipWithM f as bs = unstreamM $ Stream.zipWithM f (stream as) (stream bs)
-- | /O(min(m,n))/ Zip the two vectors with the monadic action and ignore the
-- results
zipWithM_ :: (Monad m, Vector v a, Vector v b)
=> (a -> b -> m c) -> v a -> v b -> m ()
{-# INLINE zipWithM_ #-}
zipWithM_ f as bs = Stream.zipWithM_ f (stream as) (stream bs)
-- Unzipping
-- ---------
-- | /O(min(m,n))/ Unzip a vector of pairs.
unzip :: (Vector v a, Vector v b, Vector v (a,b)) => v (a, b) -> (v a, v b)
{-# INLINE unzip #-}
unzip xs = (map fst xs, map snd xs)
unzip3 :: (Vector v a, Vector v b, Vector v c, Vector v (a, b, c))
=> v (a, b, c) -> (v a, v b, v c)
{-# INLINE unzip3 #-}
unzip3 xs = (map (\(a, b, c) -> a) xs,
map (\(a, b, c) -> b) xs,
map (\(a, b, c) -> c) xs)
unzip4 :: (Vector v a, Vector v b, Vector v c, Vector v d,
Vector v (a, b, c, d))
=> v (a, b, c, d) -> (v a, v b, v c, v d)
{-# INLINE unzip4 #-}
unzip4 xs = (map (\(a, b, c, d) -> a) xs,
map (\(a, b, c, d) -> b) xs,
map (\(a, b, c, d) -> c) xs,
map (\(a, b, c, d) -> d) xs)
unzip5 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v (a, b, c, d, e))
=> v (a, b, c, d, e) -> (v a, v b, v c, v d, v e)
{-# INLINE unzip5 #-}
unzip5 xs = (map (\(a, b, c, d, e) -> a) xs,
map (\(a, b, c, d, e) -> b) xs,
map (\(a, b, c, d, e) -> c) xs,
map (\(a, b, c, d, e) -> d) xs,
map (\(a, b, c, d, e) -> e) xs)
unzip6 :: (Vector v a, Vector v b, Vector v c, Vector v d, Vector v e,
Vector v f, Vector v (a, b, c, d, e, f))
=> v (a, b, c, d, e, f) -> (v a, v b, v c, v d, v e, v f)
{-# INLINE unzip6 #-}
unzip6 xs = (map (\(a, b, c, d, e, f) -> a) xs,
map (\(a, b, c, d, e, f) -> b) xs,
map (\(a, b, c, d, e, f) -> c) xs,
map (\(a, b, c, d, e, f) -> d) xs,
map (\(a, b, c, d, e, f) -> e) xs,
map (\(a, b, c, d, e, f) -> f) xs)
-- Filtering
-- ---------
-- | /O(n)/ Drop elements that do not satisfy the predicate
filter :: Vector v a => (a -> Bool) -> v a -> v a
{-# INLINE filter #-}
filter f = unstream . inplace (MStream.filter f) . stream
-- | /O(n)/ Drop elements that do not satisfy the predicate which is applied to
-- values and their indices
ifilter :: Vector v a => (Int -> a -> Bool) -> v a -> v a
{-# INLINE ifilter #-}
ifilter f = unstream
. inplace (MStream.map snd . MStream.filter (uncurry f)
. MStream.indexed)
. stream
-- | /O(n)/ Drop elements that do not satisfy the monadic predicate
filterM :: (Monad m, Vector v a) => (a -> m Bool) -> v a -> m (v a)
{-# INLINE filterM #-}
filterM f = unstreamM . Stream.filterM f . stream
-- | /O(n)/ Yield the longest prefix of elements satisfying the predicate
-- without copying.
takeWhile :: Vector v a => (a -> Bool) -> v a -> v a
{-# INLINE takeWhile #-}
takeWhile f = unstream . Stream.takeWhile f . stream
-- | /O(n)/ Drop the longest prefix of elements that satisfy the predicate
-- without copying.
dropWhile :: Vector v a => (a -> Bool) -> v a -> v a
{-# INLINE dropWhile #-}
dropWhile f = unstream . Stream.dropWhile f . stream
-- Parititioning
-- -------------
-- | /O(n)/ Split the vector in two parts, the first one containing those
-- elements that satisfy the predicate and the second one those that don't. The
-- relative order of the elements is preserved at the cost of a sometimes
-- reduced performance compared to 'unstablePartition'.
partition :: Vector v a => (a -> Bool) -> v a -> (v a, v a)
{-# INLINE partition #-}
partition f = partition_stream f . stream
-- FIXME: Make this inplace-fusible (look at how stable_partition is
-- implemented in C++)
partition_stream :: Vector v a => (a -> Bool) -> Stream a -> (v a, v a)
{-# INLINE_STREAM partition_stream #-}
partition_stream f s = s `seq` runST (
do
(mv1,mv2) <- M.partitionStream f s
v1 <- unsafeFreeze mv1
v2 <- unsafeFreeze mv2
return (v1,v2))
-- | /O(n)/ Split the vector in two parts, the first one containing those
-- elements that satisfy the predicate and the second one those that don't.
-- The order of the elements is not preserved but the operation is often
-- faster than 'partition'.
unstablePartition :: Vector v a => (a -> Bool) -> v a -> (v a, v a)
{-# INLINE unstablePartition #-}
unstablePartition f = unstablePartition_stream f . stream
unstablePartition_stream
:: Vector v a => (a -> Bool) -> Stream a -> (v a, v a)
{-# INLINE_STREAM unstablePartition_stream #-}
unstablePartition_stream f s = s `seq` runST (
do
(mv1,mv2) <- M.unstablePartitionStream f s
v1 <- unsafeFreeze mv1
v2 <- unsafeFreeze mv2
return (v1,v2))
unstablePartition_new :: Vector v a => (a -> Bool) -> New v a -> (v a, v a)
{-# INLINE_STREAM unstablePartition_new #-}
unstablePartition_new f (New.New p) = runST (
do
mv <- p
i <- M.unstablePartition f mv
v <- unsafeFreeze mv
return (unsafeTake i v, unsafeDrop i v))
{-# RULES
"unstablePartition" forall f p.
unstablePartition_stream f (stream (new p))
= unstablePartition_new f p
#-}
-- FIXME: make span and break fusible
-- | /O(n)/ Split the vector into the longest prefix of elements that satisfy
-- the predicate and the rest without copying.
span :: Vector v a => (a -> Bool) -> v a -> (v a, v a)
{-# INLINE span #-}
span f = break (not . f)
-- | /O(n)/ Split the vector into the longest prefix of elements that do not
-- satisfy the predicate and the rest without copying.
break :: Vector v a => (a -> Bool) -> v a -> (v a, v a)
{-# INLINE break #-}
break f xs = case findIndex f xs of
Just i -> (unsafeSlice 0 i xs, unsafeSlice i (length xs - i) xs)
Nothing -> (xs, empty)
-- Searching
-- ---------
infix 4 `elem`
-- | /O(n)/ Check if the vector contains an element
elem :: (Vector v a, Eq a) => a -> v a -> Bool
{-# INLINE elem #-}
elem x = Stream.elem x . stream
infix 4 `notElem`
-- | /O(n)/ Check if the vector does not contain an element (inverse of 'elem')
notElem :: (Vector v a, Eq a) => a -> v a -> Bool
{-# INLINE notElem #-}
notElem x = Stream.notElem x . stream
-- | /O(n)/ Yield 'Just' the first element matching the predicate or 'Nothing'
-- if no such element exists.
find :: Vector v a => (a -> Bool) -> v a -> Maybe a
{-# INLINE find #-}
find f = Stream.find f . stream
-- | /O(n)/ Yield 'Just' the index of the first element matching the predicate
-- or 'Nothing' if no such element exists.
findIndex :: Vector v a => (a -> Bool) -> v a -> Maybe Int
{-# INLINE findIndex #-}
findIndex f = Stream.findIndex f . stream
-- | /O(n)/ Yield the indices of elements satisfying the predicate in ascending
-- order.
findIndices :: (Vector v a, Vector v Int) => (a -> Bool) -> v a -> v Int
{-# INLINE findIndices #-}
findIndices f = unstream
. inplace (MStream.map fst . MStream.filter (f . snd)
. MStream.indexed)
. stream
-- | /O(n)/ Yield 'Just' the index of the first occurence of the given element or
-- 'Nothing' if the vector does not contain the element. This is a specialised
-- version of 'findIndex'.
elemIndex :: (Vector v a, Eq a) => a -> v a -> Maybe Int
{-# INLINE elemIndex #-}
elemIndex x = findIndex (x==)
-- | /O(n)/ Yield the indices of all occurences of the given element in
-- ascending order. This is a specialised version of 'findIndices'.
elemIndices :: (Vector v a, Vector v Int, Eq a) => a -> v a -> v Int
{-# INLINE elemIndices #-}
elemIndices x = findIndices (x==)
-- Folding
-- -------
-- | /O(n)/ Left fold
foldl :: Vector v b => (a -> b -> a) -> a -> v b -> a
{-# INLINE foldl #-}
foldl f z = Stream.foldl f z . stream
-- | /O(n)/ Left fold on non-empty vectors
foldl1 :: Vector v a => (a -> a -> a) -> v a -> a
{-# INLINE foldl1 #-}
foldl1 f = Stream.foldl1 f . stream
-- | /O(n)/ Left fold with strict accumulator
foldl' :: Vector v b => (a -> b -> a) -> a -> v b -> a
{-# INLINE foldl' #-}
foldl' f z = Stream.foldl' f z . stream
-- | /O(n)/ Left fold on non-empty vectors with strict accumulator
foldl1' :: Vector v a => (a -> a -> a) -> v a -> a
{-# INLINE foldl1' #-}
foldl1' f = Stream.foldl1' f . stream
-- | /O(n)/ Right fold
foldr :: Vector v a => (a -> b -> b) -> b -> v a -> b
{-# INLINE foldr #-}
foldr f z = Stream.foldr f z . stream
-- | /O(n)/ Right fold on non-empty vectors
foldr1 :: Vector v a => (a -> a -> a) -> v a -> a
{-# INLINE foldr1 #-}
foldr1 f = Stream.foldr1 f . stream
-- | /O(n)/ Right fold with a strict accumulator
foldr' :: Vector v a => (a -> b -> b) -> b -> v a -> b
{-# INLINE foldr' #-}
foldr' f z = Stream.foldl' (flip f) z . streamR
-- | /O(n)/ Right fold on non-empty vectors with strict accumulator
foldr1' :: Vector v a => (a -> a -> a) -> v a -> a
{-# INLINE foldr1' #-}
foldr1' f = Stream.foldl1' (flip f) . streamR
-- | /O(n)/ Left fold (function applied to each element and its index)
ifoldl :: Vector v b => (a -> Int -> b -> a) -> a -> v b -> a
{-# INLINE ifoldl #-}
ifoldl f z = Stream.foldl (uncurry . f) z . Stream.indexed . stream
-- | /O(n)/ Left fold with strict accumulator (function applied to each element
-- and its index)
ifoldl' :: Vector v b => (a -> Int -> b -> a) -> a -> v b -> a
{-# INLINE ifoldl' #-}
ifoldl' f z = Stream.foldl' (uncurry . f) z . Stream.indexed . stream
-- | /O(n)/ Right fold (function applied to each element and its index)
ifoldr :: Vector v a => (Int -> a -> b -> b) -> b -> v a -> b
{-# INLINE ifoldr #-}
ifoldr f z = Stream.foldr (uncurry f) z . Stream.indexed . stream
-- | /O(n)/ Right fold with strict accumulator (function applied to each
-- element and its index)
ifoldr' :: Vector v a => (Int -> a -> b -> b) -> b -> v a -> b
{-# INLINE ifoldr' #-}
ifoldr' f z xs = Stream.foldl' (flip (uncurry f)) z
$ Stream.indexedR (length xs) $ streamR xs
-- Specialised folds
-- -----------------
-- | /O(n)/ Check if all elements satisfy the predicate.
all :: Vector v a => (a -> Bool) -> v a -> Bool
{-# INLINE all #-}
all f = Stream.and . Stream.map f . stream
-- | /O(n)/ Check if any element satisfies the predicate.
any :: Vector v a => (a -> Bool) -> v a -> Bool
{-# INLINE any #-}
any f = Stream.or . Stream.map f . stream
-- | /O(n)/ Check if all elements are 'True'
and :: Vector v Bool => v Bool -> Bool
{-# INLINE and #-}
and = Stream.and . stream
-- | /O(n)/ Check if any element is 'True'
or :: Vector v Bool => v Bool -> Bool
{-# INLINE or #-}
or = Stream.or . stream
-- | /O(n)/ Compute the sum of the elements
sum :: (Vector v a, Num a) => v a -> a
{-# INLINE sum #-}
sum = Stream.foldl' (+) 0 . stream
-- | /O(n)/ Compute the produce of the elements
product :: (Vector v a, Num a) => v a -> a
{-# INLINE product #-}
product = Stream.foldl' (*) 1 . stream
-- | /O(n)/ Yield the maximum element of the vector. The vector may not be
-- empty.
maximum :: (Vector v a, Ord a) => v a -> a
{-# INLINE maximum #-}
maximum = Stream.foldl1' max . stream
-- | /O(n)/ Yield the maximum element of the vector according to the given
-- comparison function. The vector may not be empty.
maximumBy :: Vector v a => (a -> a -> Ordering) -> v a -> a
{-# INLINE maximumBy #-}
maximumBy cmp = Stream.foldl1' maxBy . stream
where
{-# INLINE maxBy #-}
maxBy x y = case cmp x y of
LT -> y
_ -> x
-- | /O(n)/ Yield the minimum element of the vector. The vector may not be
-- empty.
minimum :: (Vector v a, Ord a) => v a -> a
{-# INLINE minimum #-}
minimum = Stream.foldl1' min . stream
-- | /O(n)/ Yield the minimum element of the vector according to the given
-- comparison function. The vector may not be empty.
minimumBy :: Vector v a => (a -> a -> Ordering) -> v a -> a
{-# INLINE minimumBy #-}
minimumBy cmp = Stream.foldl1' minBy . stream
where
{-# INLINE minBy #-}
minBy x y = case cmp x y of
GT -> y
_ -> x
-- | /O(n)/ Yield the index of the maximum element of the vector. The vector
-- may not be empty.
maxIndex :: (Vector v a, Ord a) => v a -> Int
{-# INLINE maxIndex #-}
maxIndex = maxIndexBy compare
-- | /O(n)/ Yield the index of the maximum element of the vector according to
-- the given comparison function. The vector may not be empty.
maxIndexBy :: Vector v a => (a -> a -> Ordering) -> v a -> Int
{-# INLINE maxIndexBy #-}
maxIndexBy cmp = fst . Stream.foldl1' imax . Stream.indexed . stream
where
imax (i,x) (j,y) = i `seq` j `seq`
case cmp x y of
LT -> (j,y)
_ -> (i,x)
-- | /O(n)/ Yield the index of the minimum element of the vector. The vector
-- may not be empty.
minIndex :: (Vector v a, Ord a) => v a -> Int
{-# INLINE minIndex #-}
minIndex = minIndexBy compare
-- | /O(n)/ Yield the index of the minimum element of the vector according to
-- the given comparison function. The vector may not be empty.
minIndexBy :: Vector v a => (a -> a -> Ordering) -> v a -> Int
{-# INLINE minIndexBy #-}
minIndexBy cmp = fst . Stream.foldl1' imin . Stream.indexed . stream
where
imin (i,x) (j,y) = i `seq` j `seq`
case cmp x y of
GT -> (j,y)
_ -> (i,x)
-- Monadic folds
-- -------------
-- | /O(n)/ Monadic fold
foldM :: (Monad m, Vector v b) => (a -> b -> m a) -> a -> v b -> m a
{-# INLINE foldM #-}
foldM m z = Stream.foldM m z . stream
-- | /O(n)/ Monadic fold over non-empty vectors
fold1M :: (Monad m, Vector v a) => (a -> a -> m a) -> v a -> m a
{-# INLINE fold1M #-}
fold1M m = Stream.fold1M m . stream
-- | /O(n)/ Monadic fold with strict accumulator
foldM' :: (Monad m, Vector v b) => (a -> b -> m a) -> a -> v b -> m a
{-# INLINE foldM' #-}
foldM' m z = Stream.foldM' m z . stream
-- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator
fold1M' :: (Monad m, Vector v a) => (a -> a -> m a) -> v a -> m a
{-# INLINE fold1M' #-}
fold1M' m = Stream.fold1M' m . stream
discard :: Monad m => m a -> m ()
{-# INLINE discard #-}
discard m = m >> return ()
-- | /O(n)/ Monadic fold that discards the result
foldM_ :: (Monad m, Vector v b) => (a -> b -> m a) -> a -> v b -> m ()
{-# INLINE foldM_ #-}
foldM_ m z = discard . Stream.foldM m z . stream
-- | /O(n)/ Monadic fold over non-empty vectors that discards the result
fold1M_ :: (Monad m, Vector v a) => (a -> a -> m a) -> v a -> m ()
{-# INLINE fold1M_ #-}
fold1M_ m = discard . Stream.fold1M m . stream
-- | /O(n)/ Monadic fold with strict accumulator that discards the result
foldM'_ :: (Monad m, Vector v b) => (a -> b -> m a) -> a -> v b -> m ()
{-# INLINE foldM'_ #-}
foldM'_ m z = discard . Stream.foldM' m z . stream
-- | /O(n)/ Monad fold over non-empty vectors with strict accumulator
-- that discards the result
fold1M'_ :: (Monad m, Vector v a) => (a -> a -> m a) -> v a -> m ()
{-# INLINE fold1M'_ #-}
fold1M'_ m = discard . Stream.fold1M' m . stream
-- Monadic sequencing
-- ------------------
-- | Evaluate each action and collect the results
sequence :: (Monad m, Vector v a, Vector v (m a)) => v (m a) -> m (v a)
{-# INLINE sequence #-}
sequence = mapM id
-- | Evaluate each action and discard the results
sequence_ :: (Monad m, Vector v (m a)) => v (m a) -> m ()
{-# INLINE sequence_ #-}
sequence_ = mapM_ id
-- Prefix sums (scans)
-- -------------------
-- | /O(n)/ Prescan
--
-- @
-- prescanl f z = 'init' . 'scanl' f z
-- @
--
-- Example: @prescanl (+) 0 \<1,2,3,4\> = \<0,1,3,6\>@
--
prescanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
{-# INLINE prescanl #-}
prescanl f z = unstream . inplace (MStream.prescanl f z) . stream
-- | /O(n)/ Prescan with strict accumulator
prescanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
{-# INLINE prescanl' #-}
prescanl' f z = unstream . inplace (MStream.prescanl' f z) . stream
-- | /O(n)/ Scan
--
-- @
-- postscanl f z = 'tail' . 'scanl' f z
-- @
--
-- Example: @postscanl (+) 0 \<1,2,3,4\> = \<1,3,6,10\>@
--
postscanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
{-# INLINE postscanl #-}
postscanl f z = unstream . inplace (MStream.postscanl f z) . stream
-- | /O(n)/ Scan with strict accumulator
postscanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
{-# INLINE postscanl' #-}
postscanl' f z = unstream . inplace (MStream.postscanl' f z) . stream
-- | /O(n)/ Haskell-style scan
--
-- > scanl f z <x1,...,xn> = <y1,...,y(n+1)>
-- > where y1 = z
-- > yi = f y(i-1) x(i-1)
--
-- Example: @scanl (+) 0 \<1,2,3,4\> = \<0,1,3,6,10\>@
--
scanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
{-# INLINE scanl #-}
scanl f z = unstream . Stream.scanl f z . stream
-- | /O(n)/ Haskell-style scan with strict accumulator
scanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
{-# INLINE scanl' #-}
scanl' f z = unstream . Stream.scanl' f z . stream
-- | /O(n)/ Scan over a non-empty vector
--
-- > scanl f <x1,...,xn> = <y1,...,yn>
-- > where y1 = x1
-- > yi = f y(i-1) xi
--
scanl1 :: Vector v a => (a -> a -> a) -> v a -> v a
{-# INLINE scanl1 #-}
scanl1 f = unstream . inplace (MStream.scanl1 f) . stream
-- | /O(n)/ Scan over a non-empty vector with a strict accumulator
scanl1' :: Vector v a => (a -> a -> a) -> v a -> v a
{-# INLINE scanl1' #-}
scanl1' f = unstream . inplace (MStream.scanl1' f) . stream
-- | /O(n)/ Right-to-left prescan
--
-- @
-- prescanr f z = 'reverse' . 'prescanl' (flip f) z . 'reverse'
-- @
--
prescanr :: (Vector v a, Vector v b) => (a -> b -> b) -> b -> v a -> v b
{-# INLINE prescanr #-}
prescanr f z = unstreamR . inplace (MStream.prescanl (flip f) z) . streamR
-- | /O(n)/ Right-to-left prescan with strict accumulator
prescanr' :: (Vector v a, Vector v b) => (a -> b -> b) -> b -> v a -> v b
{-# INLINE prescanr' #-}
prescanr' f z = unstreamR . inplace (MStream.prescanl' (flip f) z) . streamR
-- | /O(n)/ Right-to-left scan
postscanr :: (Vector v a, Vector v b) => (a -> b -> b) -> b -> v a -> v b
{-# INLINE postscanr #-}
postscanr f z = unstreamR . inplace (MStream.postscanl (flip f) z) . streamR
-- | /O(n)/ Right-to-left scan with strict accumulator
postscanr' :: (Vector v a, Vector v b) => (a -> b -> b) -> b -> v a -> v b
{-# INLINE postscanr' #-}
postscanr' f z = unstreamR . inplace (MStream.postscanl' (flip f) z) . streamR
-- | /O(n)/ Right-to-left Haskell-style scan
scanr :: (Vector v a, Vector v b) => (a -> b -> b) -> b -> v a -> v b
{-# INLINE scanr #-}
scanr f z = unstreamR . Stream.scanl (flip f) z . streamR
-- | /O(n)/ Right-to-left Haskell-style scan with strict accumulator
scanr' :: (Vector v a, Vector v b) => (a -> b -> b) -> b -> v a -> v b
{-# INLINE scanr' #-}
scanr' f z = unstreamR . Stream.scanl' (flip f) z . streamR
-- | /O(n)/ Right-to-left scan over a non-empty vector
scanr1 :: Vector v a => (a -> a -> a) -> v a -> v a
{-# INLINE scanr1 #-}
scanr1 f = unstreamR . inplace (MStream.scanl1 (flip f)) . streamR
-- | /O(n)/ Right-to-left scan over a non-empty vector with a strict
-- accumulator
scanr1' :: Vector v a => (a -> a -> a) -> v a -> v a
{-# INLINE scanr1' #-}
scanr1' f = unstreamR . inplace (MStream.scanl1' (flip f)) . streamR
-- Conversions - Lists
-- ------------------------
-- | /O(n)/ Convert a vector to a list
toList :: Vector v a => v a -> [a]
{-# INLINE toList #-}
toList = Stream.toList . stream
-- | /O(n)/ Convert a list to a vector
fromList :: Vector v a => [a] -> v a
{-# INLINE fromList #-}
fromList = unstream . Stream.fromList
-- | /O(n)/ Convert the first @n@ elements of a list to a vector
--
-- @
-- fromListN n xs = 'fromList' ('take' n xs)
-- @
fromListN :: Vector v a => Int -> [a] -> v a
{-# INLINE fromListN #-}
fromListN n = unstream . Stream.fromListN n
-- Conversions - Immutable vectors
-- -------------------------------
-- | /O(n)/ Convert different vector types
convert :: (Vector v a, Vector w a) => v a -> w a
{-# INLINE convert #-}
convert = unstream . stream
-- Conversions - Mutable vectors
-- -----------------------------
-- | /O(1)/ Unsafe convert a mutable vector to an immutable one without
-- copying. The mutable vector may not be used after this operation.
unsafeFreeze
:: (PrimMonad m, Vector v a) => Mutable v (PrimState m) a -> m (v a)
{-# INLINE unsafeFreeze #-}
unsafeFreeze = basicUnsafeFreeze
-- | /O(n)/ Yield an immutable copy of the mutable vector.
freeze :: (PrimMonad m, Vector v a) => Mutable v (PrimState m) a -> m (v a)
{-# INLINE freeze #-}
freeze mv = unsafeFreeze =<< M.clone mv
-- | /O(1)/ Unsafely convert an immutable vector to a mutable one without
-- copying. The immutable vector may not be used after this operation.
unsafeThaw :: (PrimMonad m, Vector v a) => v a -> m (Mutable v (PrimState m) a)
{-# INLINE_STREAM unsafeThaw #-}
unsafeThaw = basicUnsafeThaw
-- | /O(n)/ Yield a mutable copy of the immutable vector.
thaw :: (PrimMonad m, Vector v a) => v a -> m (Mutable v (PrimState m) a)
{-# INLINE_STREAM thaw #-}
thaw v = do
mv <- M.unsafeNew (length v)
unsafeCopy mv v
return mv
{-# RULES
"unsafeThaw/new [Vector]" forall p.
unsafeThaw (new p) = New.runPrim p
"thaw/new [Vector]" forall p.
thaw (new p) = New.runPrim p
#-}
{-
-- | /O(n)/ Yield a mutable vector containing copies of each vector in the
-- list.
thawMany :: (PrimMonad m, Vector v a) => [v a] -> m (Mutable v (PrimState m) a)
{-# INLINE_STREAM thawMany #-}
-- FIXME: add rule for (stream (new (New.create (thawMany vs))))
-- NOTE: We don't try to consume the list lazily as this wouldn't significantly
-- change the space requirements anyway.
thawMany vs = do
mv <- M.new n
thaw_loop mv vs
return mv
where
n = List.foldl' (\k v -> k + length v) 0 vs
thaw_loop mv [] = mv `seq` return ()
thaw_loop mv (v:vs)
= do
let n = length v
unsafeCopy (M.unsafeTake n mv) v
thaw_loop (M.unsafeDrop n mv) vs
-}
-- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must
-- have the same length.
copy
:: (PrimMonad m, Vector v a) => Mutable v (PrimState m) a -> v a -> m ()
{-# INLINE copy #-}
copy dst src = BOUNDS_CHECK(check) "copy" "length mismatch"
(M.length dst == length src)
$ unsafeCopy dst src
-- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must
-- have the same length. This is not checked.
unsafeCopy
:: (PrimMonad m, Vector v a) => Mutable v (PrimState m) a -> v a -> m ()
{-# INLINE unsafeCopy #-}
unsafeCopy dst src = UNSAFE_CHECK(check) "unsafeCopy" "length mismatch"
(M.length dst == length src)
$ (dst `seq` src `seq` basicUnsafeCopy dst src)
-- Conversions to/from Streams
-- ---------------------------
-- | /O(1)/ Convert a vector to a 'Stream'
stream :: Vector v a => v a -> Stream a
{-# INLINE_STREAM stream #-}
stream v = v `seq` n `seq` (Stream.unfoldr get 0 `Stream.sized` Exact n)
where
n = length v
-- NOTE: the False case comes first in Core so making it the recursive one
-- makes the code easier to read
{-# INLINE get #-}
get i | i >= n = Nothing
| otherwise = case basicUnsafeIndexM v i of Box x -> Just (x, i+1)
-- | /O(n)/ Construct a vector from a 'Stream'
unstream :: Vector v a => Stream a -> v a
{-# INLINE unstream #-}
unstream s = new (New.unstream s)
{-# RULES
"stream/unstream [Vector]" forall s.
stream (new (New.unstream s)) = s
"New.unstream/stream [Vector]" forall v.
New.unstream (stream v) = clone v
"clone/new [Vector]" forall p.
clone (new p) = p
"inplace [Vector]"
forall (f :: forall m. Monad m => MStream m a -> MStream m a) m.
New.unstream (inplace f (stream (new m))) = New.transform f m
"uninplace [Vector]"
forall (f :: forall m. Monad m => MStream m a -> MStream m a) m.
stream (new (New.transform f m)) = inplace f (stream (new m))
#-}
-- | /O(1)/ Convert a vector to a 'Stream', proceeding from right to left
streamR :: Vector v a => v a -> Stream a
{-# INLINE_STREAM streamR #-}
streamR v = v `seq` n `seq` (Stream.unfoldr get n `Stream.sized` Exact n)
where
n = length v
{-# INLINE get #-}
get 0 = Nothing
get i = let i' = i-1
in
case basicUnsafeIndexM v i' of Box x -> Just (x, i')
-- | /O(n)/ Construct a vector from a 'Stream', proceeding from right to left
unstreamR :: Vector v a => Stream a -> v a
{-# INLINE unstreamR #-}
unstreamR s = new (New.unstreamR s)
{-# RULES
"streamR/unstreamR [Vector]" forall s.
streamR (new (New.unstreamR s)) = s
"New.unstreamR/streamR/new [Vector]" forall p.
New.unstreamR (streamR (new p)) = p
"New.unstream/streamR/new [Vector]" forall p.
New.unstream (streamR (new p)) = New.modify M.reverse p
"New.unstreamR/stream/new [Vector]" forall p.
New.unstreamR (stream (new p)) = New.modify M.reverse p
"inplace right [Vector]"
forall (f :: forall m. Monad m => MStream m a -> MStream m a) m.
New.unstreamR (inplace f (streamR (new m))) = New.transformR f m
"uninplace right [Vector]"
forall (f :: forall m. Monad m => MStream m a -> MStream m a) m.
streamR (new (New.transformR f m)) = inplace f (streamR (new m))
#-}
unstreamM :: (Monad m, Vector v a) => MStream m a -> m (v a)
{-# INLINE_STREAM unstreamM #-}
unstreamM s = do
xs <- MStream.toList s
return $ unstream $ Stream.unsafeFromList (MStream.size s) xs
unstreamPrimM :: (PrimMonad m, Vector v a) => MStream m a -> m (v a)
{-# INLINE_STREAM unstreamPrimM #-}
unstreamPrimM s = M.munstream s >>= unsafeFreeze
-- FIXME: the next two functions are only necessary for the specialisations
unstreamPrimM_IO :: Vector v a => MStream IO a -> IO (v a)
{-# INLINE unstreamPrimM_IO #-}
unstreamPrimM_IO = unstreamPrimM
unstreamPrimM_ST :: Vector v a => MStream (ST s) a -> ST s (v a)
{-# INLINE unstreamPrimM_ST #-}
unstreamPrimM_ST = unstreamPrimM
{-# RULES
"unstreamM[IO]" unstreamM = unstreamPrimM_IO
"unstreamM[ST]" unstreamM = unstreamPrimM_ST
#-}
-- Recycling support
-- -----------------
-- | Construct a vector from a monadic initialiser.
new :: Vector v a => New v a -> v a
{-# INLINE_STREAM new #-}
new m = m `seq` runST (unsafeFreeze =<< New.run m)
-- | Convert a vector to an initialiser which, when run, produces a copy of
-- the vector.
clone :: Vector v a => v a -> New v a
{-# INLINE_STREAM clone #-}
clone v = v `seq` New.create (
do
mv <- M.new (length v)
unsafeCopy mv v
return mv)
-- Comparisons
-- -----------
-- | /O(n)/ Check if two vectors are equal. All 'Vector' instances are also
-- instances of 'Eq' and it is usually more appropriate to use those. This
-- function is primarily intended for implementing 'Eq' instances for new
-- vector types.
eq :: (Vector v a, Eq a) => v a -> v a -> Bool
{-# INLINE eq #-}
xs `eq` ys = stream xs == stream ys
-- | /O(n)/ Compare two vectors lexicographically. All 'Vector' instances are
-- also instances of 'Ord' and it is usually more appropriate to use those. This
-- function is primarily intended for implementing 'Ord' instances for new
-- vector types.
cmp :: (Vector v a, Ord a) => v a -> v a -> Ordering
{-# INLINE cmp #-}
cmp xs ys = compare (stream xs) (stream ys)
-- Show
-- ----
-- | Generic definition of 'Prelude.showsPrec'
showsPrec :: (Vector v a, Show a) => Int -> v a -> ShowS
{-# INLINE showsPrec #-}
showsPrec p v = showParen (p > 10) $ showString "fromList " . shows (toList v)
-- | Generic definition of 'Text.Read.readPrec'
readPrec :: (Vector v a, Read a) => Read.ReadPrec (v a)
{-# INLINE readPrec #-}
readPrec = Read.parens $ Read.prec 10 $ do
Read.Ident "fromList" <- Read.lexP
xs <- Read.readPrec
return (fromList xs)
-- Data and Typeable
-- -----------------
-- | Generic definion of 'Data.Data.gfoldl' that views a 'Vector' as a
-- list.
gfoldl :: (Vector v a, Data a)
=> (forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g)
-> v a
-> c (v a)
{-# INLINE gfoldl #-}
gfoldl f z v = z fromList `f` toList v
mkType :: String -> DataType
{-# INLINE mkType #-}
mkType = mkNoRepType
#if __GLASGOW_HASKELL__ >= 707
dataCast :: (Vector v a, Data a, Typeable v, Typeable t)
#else
dataCast :: (Vector v a, Data a, Typeable1 v, Typeable1 t)
#endif
=> (forall d. Data d => c (t d)) -> Maybe (c (v a))
{-# INLINE dataCast #-}
dataCast f = gcast1 f
| moonKimura/vector-0.10.9.1 | Data/Vector/Generic.hs | bsd-3-clause | 67,629 | 0 | 16 | 18,117 | 18,114 | 9,624 | 8,490 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{- |
Module : ./DFOL/Logic_DFOL.hs
Description : Instances of classes defined in Logic.hs for first-order logic
with dependent types (DFOL)
Copyright : (c) Kristina Sojakova, DFKI Bremen 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : k.sojakova@jacobs-university.de
Stability : experimental
Portability : portable
Ref: Florian Rabe: First-Order Logic with Dependent Types.
IJCAR 2006, pages 377-391.
-}
module DFOL.Logic_DFOL where
import Common.Result
import Data.Monoid
import qualified Data.Map as Map
import qualified Data.Set as Set
import Control.Monad (unless)
import DFOL.AS_DFOL
import DFOL.Sign
import DFOL.Morphism
import DFOL.Parse_AS_DFOL
import DFOL.ATC_DFOL ()
import DFOL.Analysis_DFOL
import DFOL.Symbol
import DFOL.Colimit
import Logic.Logic
-- lid for first-order logic with dependent types
data DFOL = DFOL deriving Show
instance Language DFOL where
description DFOL = "First-Order Logic with Dependent Types\n" ++
"developed by F. Rabe"
-- instance of Category for DFOL
instance Category Sign Morphism where
ide = idMorph
dom = source
cod = target
isInclusion = Map.null . symMap . canForm
composeMorphisms = compMorph
legal_mor m = unless (isValidMorph m) $ fail "illegal DFOL morphism"
instance Monoid BASIC_SPEC where
mempty = Basic_spec []
mappend (Basic_spec l1) (Basic_spec l2) = Basic_spec $ l1 ++ l2
-- syntax for DFOL
instance Syntax DFOL BASIC_SPEC Symbol SYMB_ITEMS SYMB_MAP_ITEMS where
parse_basic_spec DFOL = Just basicSpec
parse_symb_items DFOL = Just symbItems
parse_symb_map_items DFOL = Just symbMapItems
-- sentences for DFOL
instance Sentences DFOL FORMULA Sign Morphism Symbol where
map_sen DFOL m = wrapInResult . applyMorph m
sym_of DFOL = singletonList . Set.map Symbol . getSymbols
symmap_of DFOL = toSymMap . symMap
sym_name DFOL = toId
-- static analysis for DFOL
instance StaticAnalysis DFOL
BASIC_SPEC
FORMULA
SYMB_ITEMS
SYMB_MAP_ITEMS
Sign
Morphism
Symbol
Symbol
where
basic_analysis DFOL = Just basicAnalysis
stat_symb_map_items DFOL _ _ = symbMapAnalysis
stat_symb_items DFOL _ = symbAnalysis
symbol_to_raw DFOL = id
id_to_raw DFOL = fromId
matches DFOL s1 s2 = s1 == s2
empty_signature DFOL = emptySig
is_subsig DFOL sig1 sig2 = isValidMorph $ Morphism sig1 sig2 Map.empty
signature_union DFOL = sigUnion
intersection DFOL = sigIntersection
subsig_inclusion DFOL = inclusionMorph
morphism_union DFOL = morphUnion
induced_from_morphism DFOL = inducedFromMorphism
induced_from_to_morphism DFOL = inducedFromToMorphism
signature_colimit DFOL = sigColimit
generated_sign DFOL = coGenSig False
cogenerated_sign DFOL = coGenSig True
final_union DFOL = sigUnion -- in DFOL every signature union is final
-- instance of logic for DFOL
instance Logic DFOL
()
BASIC_SPEC
FORMULA
SYMB_ITEMS
SYMB_MAP_ITEMS
Sign
Morphism
Symbol
Symbol
()
-- creates a Result
wrapInResult :: a -> Result a
wrapInResult x = Result [] $ Just x
| spechub/Hets | DFOL/Logic_DFOL.hs | gpl-2.0 | 3,165 | 0 | 9 | 655 | 641 | 334 | 307 | 79 | 1 |
module HyLoRes.Core.SMP.Subsumer ( Channels(..), runSubsumer )
where
import Prelude hiding ( log )
import Control.Concurrent
import Control.Monad.State
import Control.Monad.Reader
import Control.Concurrent.Chan
import HyLoRes.Logger ( LoggerT, runLoggerT, LoggerCfg(..),
log, LoggerEvent(..) )
import HyLoRes.Subsumption.STMSubsumptionTrie ( STMSubsumptionTrie )
import qualified HyLoRes.Subsumption.STMSubsumptionTrie as ST
import HyLoRes.Core.SMP.Base ( ChSubsumerToDispatcher, ChDispatcherToSubsumer,
MsgDispatcherToSubsumer(..) )
import HyLoRes.Clause.FullClause ( FullClause )
import HyLoRes.Formula ( At, Nom, Opaque )
import Control.Concurrent.STM
type ChChildToSubsumer = Chan SubsumptionResult
data SubsumptionResult = SUBSUMED
| CLAUSE (FullClause (At Nom Opaque))
data Channels = CH{fromDispatcher :: ChDispatcherToSubsumer,
toDispatcher :: ChSubsumerToDispatcher}
data SData = SD{ checked :: [FullClause (At Nom Opaque)] }
type Subsumer = ReaderT Channels (
LoggerT (
StateT (TVar STMSubsumptionTrie) (
StateT SData
IO)))
emptySD :: SData
emptySD = SD{checked = []}
runSubsumer :: Channels -> LoggerCfg -> TVar STMSubsumptionTrie -> IO ()
runSubsumer chs lc tr = (`evalStateT` emptySD)
. (`evalStateT` tr)
. (`runLoggerT` ("[S]: ", lc))
. (`runReaderT` chs) $ subsumerLoop
runSubsumerChild :: ChChildToSubsumer
-> TVar STMSubsumptionTrie
-> FullClause (At Nom Opaque)
-> IO ()
runSubsumerChild fs tr cl = do result <- atomically (do subsumes cl tr)
writeChan fs result
subsumes :: FullClause (At Nom Opaque) -> TVar STMSubsumptionTrie-> STM (SubsumptionResult)
subsumes cl tr = do subsumed <- ST.subsumes tr cl
if subsumed
then return $ SUBSUMED
else do ST.add cl tr
return $ CLAUSE cl
subsumerLoop :: Subsumer ()
subsumerLoop =
do chans <- channels
m <- liftIO $ readChan (fromDispatcher chans)
case m of
STOP -> return ()
D2S_CLAUSES cls ->
do let toCheck = length cls
log L_Comm $ concat ["Clauses from Dispatcher: ", show toCheck]
tr <- trie
-- let notSubsumed = mapM checkLocalSubsumption cls tr
--
fc <- liftIO $ newChan
forM_ cls $ \cl ->
liftIO $ (forkIO $ runSubsumerChild fc tr cl)
forM_ cls $ \_ -> do
msg <- liftIO $ readChan fc
case msg of
CLAUSE cl' -> addToChecked cl'
_ -> return ()
--
sd' <- sdata
let subsumed = toCheck - (length $ checked sd')
liftIO $ writeChan (toDispatcher chans) (checked sd')
log L_Comm $ concat ["Checked : ", show (checked sd')]
log L_Comm $ concat ["Subsumed : ", show subsumed]
lift . lift . lift $ put sd'{checked=[]}
subsumerLoop
addToChecked :: FullClause (At Nom Opaque) -> Subsumer ()
addToChecked cl = do sd <- sdata
lift . lift . lift $ put sd{checked = cl : (checked sd)}
channels :: Subsumer Channels
channels = ask
trie :: Subsumer (TVar STMSubsumptionTrie)
trie = lift . lift $ get
sdata :: Subsumer SData
sdata = lift . lift . lift $ get
| nevrenato/HyLoRes_Source | src/HyLoRes/Core/SMP/Subsumer.hs | gpl-2.0 | 3,614 | 0 | 20 | 1,229 | 1,045 | 547 | 498 | 79 | 3 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Server where
import System.IO
import Network.HaskellNet.IMAP
import Data.ByteString.Char8
import Control.Monad
import Network.HaskellNet.IMAP.SSL
import Codec.MIME.Parse
import Control.Applicative
import Codec.MIME.Type
import Network.HaskellNet.IMAP.Connection
import Codec.Crypto.RSA
class LockState a
data LOpen = Open
data LClosed = Closed
instance LockState LOpen
instance LockState LClosed
class (LockState a, LockState b) => Locks a b where
type LMerge a b :: *
instance Locks LOpen LOpen where
type LMerge LOpen LOpen = LOpen
instance Locks LOpen LClosed where
type LMerge LOpen LClosed = LClosed
instance Locks LClosed LOpen where
type LMerge LClosed LOpen = LClosed
instance Locks LClosed LClosed where
type LMerge LClosed LClosed = LClosed
class Server server where
type Key server :: *
type Query server :: *
lookup :: SHandle h => server LOpen -> Query server -> [h]
open :: (LockState l') => Key server -> server LClosed -> IO (server l')
close :: (LockState l') => server l' -> IO (server LClosed)
pin :: String -> server LOpen -> IO s
glance :: server LOpen -> IO [String]
class SHandle h where
transfer :: Server s => h -> s LOpen -> IO h
uid :: h -> Int
name :: h -> String
split :: h -> IO (h, h)
author :: h -> String
size :: h -> IO Int
shGetBody :: h -> IO String
shGetContents :: h -> IO String
shPutStr :: String -> h -> IO ()
properties :: h -> IO [(String, a)]
set :: a -> b -> h -> IO h
--data Source s q k => Only s q k = Only s
--data Pool q k = forall s. Source s q k => Pool [Only s q k]
class DList a
data (Server s, LockState l) => DOnly s l
data (DList a) => DMerge x a
instance DList (DOnly s l)
instance DList (DMerge x a)
data Pool k q a o where
Only :: LockState l => s l -> Pool (Key s) (Query s) (DOnly s l) l
Merge :: (LockState l, LockState o, DList a) => s l -> Pool (Key s) (Query s) a o -> Pool (Key s) (Query s) (DMerge (DOnly s l) a) (LMerge l o)
instance Server (Pool k q a) where
type Key (Pool k q a) = k
type Query (Pool k q a) = q
close (Only s) = Only <$> Server.close s
close (Merge s p) = Merge <$> Server.close s <*> Server.close p
{--
class Server s => Tryopen s l where
type Willopen s :: *
tryopen :: LockState l => Key server -> server l -> IO (server l')
instance Tryopen s LOpen where
type Willopen s :: LOpen
tryopen --}
--instance Source (Pool q k) q k where
-- sempty = return $ Pool []
-- open (Pool sources) key = undefined
{--instance Source s q k => Source (Only s q k) q k where
sempty = undefined
open (Only source) key = open' source key
where
open' :: Source s q k => s -> k -> IO (Only s q k)
open' source' key' = Only <$> open source' key'--}
data Gmail l = LockState l => Gmail l
data Disk l = LockState l => Disk l
data UserPass = UserPass String String
instance Server Gmail where
type Key Gmail = UserPass
type Query Gmail = Gmail LOpen
instance Server Disk where
type Key Disk = UserPass
type Query Disk = Gmail LOpen
| trehansiddharth/mlsciencebowl | hs/server-lock.hs | gpl-3.0 | 3,312 | 77 | 14 | 771 | 1,053 | 566 | 487 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Test.AWS.Data.Base64
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Test.AWS.Data.Base64 (tests) where
import Data.Monoid
import Data.String
import Network.AWS.Prelude
import Network.HTTP.Types
import Test.AWS.Util
import Test.Tasty
tests :: TestTree
tests = testGroup "base64"
[ testGroup "text"
[ testFromText "deserialise" encoded decoded
, testToText "serialise" encoded decoded
]
, testGroup "query"
[ testToQuery "serialise" ("x=" <> urlEncode True encoded) decoded
]
, testGroup "xml"
[ testFromXML "deserialise" encoded decoded
, testToXML "serialise" encoded decoded
]
, testGroup "json"
[ testFromJSON "deserialise" (str encoded) decoded
, testToJSON "serialise" (str encoded) decoded
]
]
encoded :: IsString a => a
encoded = "U2VkIHV0IHBlcnNwaWNpYXRpcyB1bmRlIG9tbmlzIGlzdGUgbmF0dXMgZXJyb3Igc2l0IHZvbHVwdGF0ZW0="
decoded :: Base64
decoded = Base64 "Sed ut perspiciatis unde omnis iste natus error sit voluptatem"
| fmapfmapfmap/amazonka | core/test/Test/AWS/Data/Base64.hs | mpl-2.0 | 1,355 | 0 | 12 | 350 | 226 | 126 | 100 | 25 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- 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)
--
module Main (main) where
import Test.Tasty
import Test.AWS.SNS
import Test.AWS.SNS.Internal
main :: IO ()
main = defaultMain $ testGroup "SNS"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
| fmapfmapfmap/amazonka | amazonka-sns/test/Main.hs | mpl-2.0 | 522 | 0 | 8 | 103 | 76 | 47 | 29 | 9 | 1 |
{-|
Module : Idris.Package.Parser
Description : `iPKG` file parser and package description information.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE CPP, ConstraintKinds #-}
#if !(MIN_VERSION_base(4,8,0))
{-# LANGUAGE OverlappingInstances #-}
#endif
module Idris.Package.Parser where
import Text.Trifecta hiding (span, charLiteral, natural, symbol, char, string, whiteSpace)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import Idris.Core.TT
import Idris.REPL
import Idris.AbsSyntaxTree
import Idris.Parser.Helpers hiding (stringLiteral)
import Idris.CmdOptions
import Idris.Package.Common
import Control.Monad.State.Strict
import Control.Applicative
import System.FilePath (takeFileName, isValid)
import Data.Maybe (isNothing, fromJust)
import Data.List (union)
import Util.System
type PParser = StateT PkgDesc IdrisInnerParser
instance HasLastTokenSpan PParser where
getLastTokenSpan = return Nothing
#if MIN_VERSION_base(4,9,0)
instance {-# OVERLAPPING #-} DeltaParsing PParser where
line = lift line
{-# INLINE line #-}
position = lift position
{-# INLINE position #-}
slicedWith f (StateT m) = StateT $ \s -> slicedWith (\(a,s') b -> (f a b, s')) $ m s
{-# INLINE slicedWith #-}
rend = lift rend
{-# INLINE rend #-}
restOfLine = lift restOfLine
{-# INLINE restOfLine #-}
#endif
#if MIN_VERSION_base(4,8,0)
instance {-# OVERLAPPING #-} TokenParsing PParser where
#else
instance TokenParsing PParser where
#endif
someSpace = many (simpleWhiteSpace <|> singleLineComment <|> multiLineComment) *> pure ()
parseDesc :: FilePath -> IO PkgDesc
parseDesc fp = do
p <- readFile fp
case runparser pPkg defaultPkg fp p of
Failure (ErrInfo err _) -> fail (show $ PP.plain err)
Success x -> return x
pPkg :: PParser PkgDesc
pPkg = do
reserved "package"
p <- filename
st <- get
put (st { pkgname = p })
some pClause
st <- get
eof
return st
-- | Parses a filename.
-- |
-- | Treated for now as an identifier or a double-quoted string.
filename :: (MonadicParsing m, HasLastTokenSpan m) => m String
filename = (do
filename <- token $
-- Treat a double-quoted string as a filename to support spaces.
-- This also moves away from tying filenames to identifiers, so
-- it will also accept hyphens
-- (https://github.com/idris-lang/Idris-dev/issues/2721)
stringLiteral
<|>
-- Through at least version 0.9.19.1, IPKG executable values were
-- possibly namespaced identifiers, like foo.bar.baz.
show <$> fst <$> iName []
case filenameErrorMessage filename of
Just errorMessage -> fail errorMessage
Nothing -> return filename)
<?> "filename"
where
-- TODO: Report failing span better! We could lookAhead,
-- or do something with DeltaParsing?
filenameErrorMessage :: FilePath -> Maybe String
filenameErrorMessage path = either Just (const Nothing) $ do
checkEmpty path
checkValid path
checkNoDirectoryComponent path
where
checkThat ok message =
if ok then Right () else Left message
checkEmpty path =
checkThat (path /= "") "filename must not be empty"
checkValid path =
checkThat (System.FilePath.isValid path)
"filename must contain only valid characters"
checkNoDirectoryComponent path =
checkThat (path == takeFileName path)
"filename must contain no directory component"
pClause :: PParser ()
pClause = do reserved "executable"; lchar '=';
exec <- filename
st <- get
put (st { execout = Just exec })
<|> do reserved "main"; lchar '=';
main <- fst <$> iName []
st <- get
put (st { idris_main = Just main })
<|> do reserved "sourcedir"; lchar '=';
src <- fst <$> identifier
st <- get
put (st { sourcedir = src })
<|> do reserved "opts"; lchar '=';
opts <- stringLiteral
st <- get
let args = pureArgParser (words opts)
put (st { idris_opts = args ++ idris_opts st })
<|> do reserved "pkgs"; lchar '=';
ps <- sepBy1 (fst <$> identifier) (lchar ',')
st <- get
let pkgs = pureArgParser $ concatMap (\x -> ["-p", x]) ps
put (st { pkgdeps = ps `union` (pkgdeps st)
, idris_opts = pkgs ++ idris_opts st})
<|> do reserved "modules"; lchar '=';
ms <- sepBy1 (fst <$> iName []) (lchar ',')
st <- get
put (st { modules = modules st ++ ms })
<|> do reserved "libs"; lchar '=';
ls <- sepBy1 (fst <$> identifier) (lchar ',')
st <- get
put (st { libdeps = libdeps st ++ ls })
<|> do reserved "objs"; lchar '=';
ls <- sepBy1 (fst <$> identifier) (lchar ',')
st <- get
put (st { objs = objs st ++ ls })
<|> do reserved "makefile"; lchar '=';
mk <- fst <$> iName []
st <- get
put (st { makefile = Just (show mk) })
<|> do reserved "tests"; lchar '=';
ts <- sepBy1 (fst <$> iName []) (lchar ',')
st <- get
put st { idris_tests = idris_tests st ++ ts }
<|> do reserved "version"
lchar '='
vStr <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgversion = Just vStr}
<|> do reserved "readme"
lchar '='
rme <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put (st { pkgreadme = Just rme })
<|> do reserved "license"
lchar '='
lStr <- many (satisfy (not . isEol))
eol
st <- get
put st {pkglicense = Just lStr}
<|> do reserved "homepage"
lchar '='
www <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkghomepage = Just www}
<|> do reserved "sourceloc"
lchar '='
srcpage <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgsourceloc = Just srcpage}
<|> do reserved "bugtracker"
lchar '='
src <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgbugtracker = Just src}
<|> do reserved "brief"
lchar '='
brief <- stringLiteral
st <- get
someSpace
put st {pkgbrief = Just brief}
<|> do reserved "author"; lchar '=';
author <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgauthor = Just author}
<|> do reserved "maintainer"; lchar '=';
maintainer <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgmaintainer = Just maintainer}
| ozgurakgun/Idris-dev | src/Idris/Package/Parser.hs | bsd-3-clause | 7,419 | 0 | 29 | 2,631 | 2,086 | 1,010 | 1,076 | 166 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
-- |Miscellaneous utilities for dealing with OpenGL errors.
module Graphics.GLUtil.GLError (printError, printErrorMsg, throwError,
GLError, throwErrorMsg) where
import Control.Exception (Exception, throwIO)
import Control.Monad (when)
import Data.List (intercalate)
import Data.Typeable (Typeable)
import Graphics.Rendering.OpenGL
import System.IO (hPutStrLn, stderr)
-- |Check OpenGL error flags and print them on 'stderr'.
printError :: IO ()
printError = get errors >>= mapM_ (hPutStrLn stderr . ("GL: "++) . show)
-- |Check OpenGL error flags and print them on 'stderr' with the given
-- message as a prefix. If there are no errors, nothing is printed.
printErrorMsg :: String -> IO ()
printErrorMsg msg = do errs <- get errors
when (not (null errs))
(putStrLn msg >> mapM_ printErr errs)
where printErr = hPutStrLn stderr . (" GL: "++) . show
-- |An exception type for OpenGL errors.
data GLError = GLError String deriving (Typeable)
instance Exception GLError where
instance Show GLError where
show (GLError msg) = "GLError " ++ msg
-- |Prefix each of a list of messages with "GL: ".
printGLErrors :: Show a => [a] -> String
printGLErrors = intercalate "\n GL: " . ("" :) . map show
-- |Throw an exception if there is an OpenGL error.
throwError :: IO ()
throwError = do errs <- get errors
when (not (null errs))
(throwIO . GLError . tail $ printGLErrors errs)
-- |Throw an exception if there is an OpenGL error. The exception's
-- error message is prefixed with the supplied 'String'.
throwErrorMsg :: String -> IO ()
throwErrorMsg msg = do errs <- get errors
when (not (null errs))
(throwIO $ GLError (msg++printGLErrors errs))
| coghex/abridgefaraway | src/GLUtil/GLError.hs | bsd-3-clause | 1,856 | 0 | 13 | 449 | 455 | 241 | 214 | 30 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.Mail
-- Copyright : (c) Spencer Janssen
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Spencer Janssen <sjanssen@cse.unl.edu>
-- Stability : unstable
-- Portability : unportable
--
-- A plugin for checking mail.
--
-----------------------------------------------------------------------------
module Plugins.Mail where
import Plugins
import Plugins.Utils (expandHome, changeLoop)
import Control.Monad
import Control.Concurrent.STM
import System.Directory
import System.FilePath
import System.INotify
import Data.List (isPrefixOf)
import Data.Set (Set)
import qualified Data.Set as S
-- | A list of mail box names and paths to maildirs.
data Mail = Mail [(String, FilePath)] String
deriving (Read, Show)
instance Exec Mail where
alias (Mail _ a) = a
start (Mail ms _) cb = do
vs <- mapM (const $ newTVarIO S.empty) ms
let ts = map fst ms
rs = map ((</> "new") . snd) ms
ev = [Move, MoveIn, MoveOut, Create, Delete]
ds <- mapM expandHome rs
i <- initINotify
zipWithM_ (\d v -> addWatch i ev d (handle v)) ds vs
forM_ (zip ds vs) $ \(d, v) -> do
s <- fmap (S.fromList . filter (not . isPrefixOf "."))
$ getDirectoryContents d
atomically $ modifyTVar v (S.union s)
changeLoop (mapM (fmap S.size . readTVar) vs) $ \ns ->
cb . unwords $ [m ++ ":" ++ show n
| (m, n) <- zip ts ns
, n /= 0 ]
handle :: TVar (Set String) -> Event -> IO ()
handle v e = atomically $ modifyTVar v $ case e of
Created {} -> create
MovedIn {} -> create
Deleted {} -> delete
MovedOut {} -> delete
_ -> id
where
delete = S.delete (filePath e)
create = S.insert (filePath e)
| tsiliakis/xmobar | src/Plugins/Mail.hs | bsd-3-clause | 1,949 | 0 | 20 | 568 | 600 | 317 | 283 | 40 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Types
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
--
-- This module is the host of the most prevalent types throughout Yi.
-- It is unfortunately a necessary evil to avoid use of bootfiles.
--
-- You're encouraged to import from more idiomatic modules which will
-- re-export these where appropriate.
module Yi.Types where
import Control.Concurrent (MVar, modifyMVar, modifyMVar_, readMVar)
import Control.Monad.Base (MonadBase, liftBase)
import Control.Monad.Reader (MonadReader, ReaderT, ask, asks, runReaderT)
import Control.Monad.RWS.Strict (MonadWriter, RWS, ap, liftM3, void)
import Control.Monad.State (MonadState (..), State, forever, runState)
import Data.Binary (Binary)
import qualified Data.Binary as B (get, put)
import Data.Default (Default, def)
import qualified Data.DelayList as DelayList (DelayList)
import qualified Data.DynamicState as ConfigState (DynamicState)
import qualified Data.DynamicState.Serializable as DynamicState (DynamicState)
import Data.Function (on)
import Data.List.NonEmpty (NonEmpty)
import Data.List.PointedList (PointedList)
import qualified Data.Map as M (Map)
import qualified Data.Text as T (Text)
import qualified Data.Text.Encoding as E (decodeUtf8, encodeUtf8)
import Data.Time (UTCTime (..))
import Data.Typeable (Typeable)
import Data.Word (Word8)
import Yi.Buffer.Basic (BufferRef, WindowRef)
import Yi.Buffer.Implementation
import Yi.Buffer.Undo (URList)
import Yi.Config.Misc (ScrollStyle)
import Yi.Event (Event)
import qualified Yi.Interact as I (I, P (End))
import Yi.KillRing (Killring)
import Yi.Layout (AnyLayoutManager)
import Yi.Monad (getsAndModify)
import Yi.Process (SubprocessId, SubprocessInfo)
import qualified Yi.Rope as R (ConverterName, YiString)
import Yi.Style (StyleName)
import Yi.Style.Library (Theme)
import Yi.Syntax (ExtHL, Stroke)
import Yi.Tab (Tab)
import Yi.UI.Common (UI)
import Yi.Window (Window)
-- Yi.Keymap
-- TODO: refactor this!
data Action = forall a. Show a => YiA (YiM a)
| forall a. Show a => EditorA (EditorM a)
| forall a. Show a => BufferA (BufferM a)
deriving Typeable
emptyAction :: Action
emptyAction = BufferA (return ())
class (Default a, Binary a, Typeable a) => YiVariable a
class (Default a, Typeable a) => YiConfigVariable a
instance Eq Action where
_ == _ = False
instance Show Action where
show (YiA _) = "@Y"
show (EditorA _) = "@E"
show (BufferA _) = "@B"
type Interact ev a = I.I ev Action a
type KeymapM a = Interact Event a
type Keymap = KeymapM ()
type KeymapEndo = Keymap -> Keymap
type KeymapProcess = I.P Event Action
data IsRefreshNeeded = MustRefresh | NoNeedToRefresh
deriving (Show, Eq)
data Yi = Yi { yiUi :: UI Editor
, yiInput :: [Event] -> IO () -- ^ input stream
, yiOutput :: IsRefreshNeeded -> [Action] -> IO () -- ^ output stream
, yiConfig :: Config
-- TODO: this leads to anti-patterns and seems like one itself
-- too coarse for actual concurrency, otherwise pointless
-- And MVars can be empty so this causes soundness problems
-- Also makes code a bit opaque
, yiVar :: MVar YiVar -- ^ The only mutable state in the program
}
deriving Typeable
data YiVar = YiVar { yiEditor :: !Editor
, yiSubprocessIdSupply :: !SubprocessId
, yiSubprocesses :: !(M.Map SubprocessId SubprocessInfo)
}
-- | The type of user-bindable functions
-- TODO: doc how these are actually user-bindable
-- are they?
newtype YiM a = YiM {runYiM :: ReaderT Yi IO a}
deriving (Monad, Applicative, MonadReader Yi, MonadBase IO, Typeable, Functor)
instance MonadState Editor YiM where
get = yiEditor <$> (liftBase . readMVar =<< yiVar <$> ask)
put v = liftBase . flip modifyMVar_ (\x -> return $ x {yiEditor = v}) =<< yiVar <$> ask
instance MonadEditor YiM where
askCfg = yiConfig <$> ask
withEditor f = do
r <- asks yiVar
cfg <- asks yiConfig
liftBase $ unsafeWithEditor cfg r f
unsafeWithEditor :: Config -> MVar YiVar -> EditorM a -> IO a
unsafeWithEditor cfg r f = modifyMVar r $ \var -> do
let e = yiEditor var
let (e',a) = runEditor cfg f e
-- Make sure that the result of runEditor is evaluated before
-- replacing the editor state. Otherwise, we might replace e
-- with an exception-producing thunk, which makes it impossible
-- to look at or update the editor state.
-- Maybe this could also be fixed by -fno-state-hack flag?
-- TODO: can we simplify this?
e' `seq` a `seq` return (var {yiEditor = e'}, a)
data KeymapSet = KeymapSet
{ topKeymap :: Keymap -- ^ Content of the top-level loop.
, insertKeymap :: Keymap -- ^ For insertion-only modes
}
extractTopKeymap :: KeymapSet -> Keymap
extractTopKeymap kms = forever (topKeymap kms)
-- Note the use of "forever": this has quite subtle implications, as it means that
-- failures in one iteration can yield to jump to the next iteration seamlessly.
-- eg. in emacs keybinding, failures in incremental search, like <left>, will "exit"
-- incremental search and immediately move to the left.
-- Yi.Buffer.Misc
-- | The BufferM monad writes the updates performed.
newtype BufferM a = BufferM { fromBufferM :: RWS Window [Update] FBuffer a }
deriving (Monad, Functor, MonadWriter [Update], MonadState FBuffer, MonadReader Window, Typeable)
-- | Currently duplicates some of Vim's indent settings. Allowing a
-- buffer to specify settings that are more dynamic, perhaps via
-- closures, could be useful.
data IndentSettings = IndentSettings
{ expandTabs :: Bool -- ^ Insert spaces instead of tabs as possible
, tabSize :: Int -- ^ Size of a Tab
, shiftWidth :: Int -- ^ Indent by so many columns
} deriving (Eq, Show, Typeable)
instance Applicative BufferM where
pure = return
(<*>) = ap
data FBuffer = forall syntax.
FBuffer { bmode :: !(Mode syntax)
, rawbuf :: !(BufferImpl syntax)
, attributes :: !Yi.Types.Attributes
}
deriving Typeable
instance Eq FBuffer where
(==) = (==) `on` bkey__ . attributes
type WinMarks = MarkSet Mark
data MarkSet a = MarkSet { fromMark, insMark, selMark :: !a }
deriving (Traversable, Foldable, Functor)
instance Binary a => Binary (MarkSet a) where
put (MarkSet f i s) = B.put f >> B.put i >> B.put s
get = liftM3 MarkSet B.get B.get B.get
data Attributes
= Attributes
{ ident :: !BufferId
, bkey__ :: !BufferRef -- ^ immutable unique key
, undos :: !URList -- ^ undo/redo list
, bufferDynamic :: !DynamicState.DynamicState -- ^ dynamic components
, preferCol :: !(Maybe Int)
-- ^ prefered column to arrive at when we do a lineDown / lineUp
, preferVisCol :: !(Maybe Int)
-- ^ prefered column to arrive at visually (ie, respecting wrap)
, stickyEol :: !Bool
-- ^ stick to the end of line (used by vim bindings mostly)
, pendingUpdates :: ![UIUpdate]
-- ^ updates that haven't been synched in the UI yet
, selectionStyle :: !SelectionStyle
, keymapProcess :: !KeymapProcess
, winMarks :: !(M.Map WindowRef WinMarks)
, lastActiveWindow :: !Window
, lastSyncTime :: !UTCTime
-- ^ time of the last synchronization with disk
, readOnly :: !Bool -- ^ read-only flag
, inserting :: !Bool -- ^ the keymap is ready for insertion into this buffer
, directoryContent :: !Bool -- ^ does buffer contain directory contents
, pointFollowsWindow :: !(WindowRef -> Bool)
, updateTransactionInFlight :: !Bool
, updateTransactionAccum :: ![Update]
, fontsizeVariation :: !Int
, encodingConverterName :: Maybe R.ConverterName
-- ^ How many points (frontend-specific) to change
-- the font by in this buffer
} deriving Typeable
instance Binary Yi.Types.Attributes where
put (Yi.Types.Attributes n b u bd pc pv se pu selectionStyle_
_proc wm law lst ro ins _dc _pfw isTransacPresent transacAccum fv cn) = do
let putTime (UTCTime x y) = B.put (fromEnum x) >> B.put (fromEnum y)
B.put n >> B.put b >> B.put u >> B.put bd
B.put pc >> B.put pv >> B.put se >> B.put pu >> B.put selectionStyle_ >> B.put wm
B.put law >> putTime lst >> B.put ro >> B.put ins >> B.put _dc
B.put isTransacPresent >> B.put transacAccum >> B.put fv >> B.put cn
get = Yi.Types.Attributes <$> B.get <*> B.get <*> B.get <*> B.get <*>
B.get <*> B.get <*> B.get <*> B.get <*> B.get <*> pure I.End <*> B.get <*> B.get
<*> getTime <*> B.get <*> B.get <*> B.get
<*> pure (const False) <*> B.get <*> B.get <*> B.get <*> B.get
where
getTime = UTCTime <$> (toEnum <$> B.get) <*> (toEnum <$> B.get)
data BufferId = MemBuffer T.Text
| FileBuffer FilePath
deriving (Show, Eq, Ord)
instance Binary BufferId where
get = B.get >>= \case
(0 :: Word8) -> MemBuffer . E.decodeUtf8 <$> B.get
1 -> FileBuffer <$> B.get
x -> fail $ "Binary failed on BufferId, tag: " ++ show x
put (MemBuffer t) = B.put (0 :: Word8) >> B.put (E.encodeUtf8 t)
put (FileBuffer t) = B.put (1 :: Word8) >> B.put t
data SelectionStyle = SelectionStyle
{ highlightSelection :: !Bool
, rectangleSelection :: !Bool
} deriving Typeable
instance Binary SelectionStyle where
put (SelectionStyle h r) = B.put h >> B.put r
get = SelectionStyle <$> B.get <*> B.get
data AnyMode = forall syntax. AnyMode (Mode syntax)
deriving Typeable
-- | A Mode customizes the Yi interface for editing a particular data
-- format. It specifies when the mode should be used and controls
-- file-specific syntax highlighting and command input, among other
-- things.
data Mode syntax = Mode
{ modeName :: T.Text
-- ^ so this can be serialized, debugged.
, modeApplies :: FilePath -> R.YiString -> Bool
-- ^ What type of files does this mode apply to?
, modeHL :: ExtHL syntax
-- ^ Syntax highlighter
, modePrettify :: syntax -> BufferM ()
-- ^ Prettify current \"paragraph\"
, modeKeymap :: KeymapSet -> KeymapSet
-- ^ Buffer-local keymap modification
, modeIndent :: syntax -> IndentBehaviour -> BufferM ()
-- ^ emacs-style auto-indent line
, modeAdjustBlock :: syntax -> Int -> BufferM ()
-- ^ adjust the indentation after modification
, modeFollow :: syntax -> Action
-- ^ Follow a \"link\" in the file. (eg. go to location of error message)
, modeIndentSettings :: IndentSettings
, modeToggleCommentSelection :: Maybe (BufferM ())
, modeGetStrokes :: syntax -> Point -> Point -> Point -> [Stroke]
-- ^ Strokes that should be applied when displaying a syntax element
-- should this be an Action instead?
, modeOnLoad :: BufferM ()
-- ^ An action that is to be executed when this mode is set
, modeModeLine :: [T.Text] -> BufferM T.Text
-- ^ buffer-local modeline formatting method
, modeGotoDeclaration :: BufferM ()
-- ^ go to the point where the variable is declared
}
-- | Used to specify the behaviour of the automatic indent command.
data IndentBehaviour =
IncreaseCycle -- ^ Increase the indentation to the next higher indentation
-- hint. If we are currently at the highest level of
-- indentation then cycle back to the lowest.
| DecreaseCycle -- ^ Decrease the indentation to the next smaller indentation
-- hint. If we are currently at the smallest level then
-- cycle back to the largest
| IncreaseOnly -- ^ Increase the indentation to the next higher hint
-- if no such hint exists do nothing.
| DecreaseOnly -- ^ Decrease the indentation to the next smaller indentation
-- hint, if no such hint exists do nothing.
deriving (Eq, Show)
-- Yi.Editor
type Status = ([T.Text], StyleName)
type Statuses = DelayList.DelayList Status
-- | The Editor state
data Editor = Editor
{ bufferStack :: !(NonEmpty BufferRef)
-- ^ Stack of all the buffers.
-- Invariant: first buffer is the current one.
, buffers :: !(M.Map BufferRef FBuffer)
, refSupply :: !Int -- ^ Supply for buffer, window and tab ids.
, tabs_ :: !(PointedList Tab)
-- ^ current tab contains the visible windows pointed list.
, dynamic :: !DynamicState.DynamicState -- ^ dynamic components
, statusLines :: !Statuses
, maxStatusHeight :: !Int
, killring :: !Killring
, currentRegex :: !(Maybe SearchExp)
-- ^ currently highlighted regex (also most recent regex for use
-- in vim bindings)
, searchDirection :: !Direction
, pendingEvents :: ![Event]
-- ^ Processed events that didn't yield any action yet.
, onCloseActions :: !(M.Map BufferRef (EditorM ()))
-- ^ Actions to be run when the buffer is closed; should be scrapped.
} deriving Typeable
newtype EditorM a = EditorM {fromEditorM :: ReaderT Config (State Editor) a}
deriving (Monad, Applicative, MonadState Editor,
MonadReader Config, Functor, Typeable)
instance MonadEditor EditorM where
askCfg = ask
withEditor = id
class (Monad m, MonadState Editor m) => MonadEditor m where
askCfg :: m Config
withEditor :: EditorM a -> m a
withEditor f = do
cfg <- askCfg
getsAndModify (runEditor cfg f)
withEditor_ :: EditorM a -> m ()
withEditor_ = withEditor . void
runEditor :: Config -> EditorM a -> Editor -> (Editor, a)
runEditor cfg f e = let (a, e') = runState (runReaderT (fromEditorM f) cfg) e
in (e',a)
-- Yi.Config
data UIConfig = UIConfig {
configFontName :: Maybe String, -- ^ Font name, for the UI that support it.
configFontSize :: Maybe Int, -- ^ Font size, for the UI that support it.
configScrollStyle :: Maybe ScrollStyle,
-- ^ Style of scroll
configScrollWheelAmount :: Int, -- ^ Amount to move the buffer when using the scroll wheel
configLeftSideScrollBar :: Bool, -- ^ Should the scrollbar be shown on the left side?
configAutoHideScrollBar :: Bool, -- ^ Hide scrollbar automatically if text fits on one page.
configAutoHideTabBar :: Bool, -- ^ Hide the tabbar automatically if only one tab is present
configLineWrap :: Bool, -- ^ Wrap lines at the edge of the window if too long to display.
configCursorStyle :: CursorStyle,
configWindowFill :: Char,
-- ^ The char with which to fill empty window space. Usually '~' for vi-like
-- editors, ' ' for everything else.
configTheme :: Theme -- ^ UI colours
}
type UIBoot = Config -> ([Event] -> IO ())
-> ([Action] -> IO ()) -> Editor -> IO (UI Editor)
-- | When should we use a "fat" cursor (i.e. 2 pixels wide, rather than 1)? Fat
-- cursors have only been implemented for the Pango frontend.
data CursorStyle = AlwaysFat
| NeverFat
| FatWhenFocused
| FatWhenFocusedAndInserting
-- | Configuration record. All Yi hooks can be set here.
data Config = Config {startFrontEnd :: UIBoot,
-- ^ UI to use.
configUI :: UIConfig,
-- ^ UI-specific configuration.
startActions :: [Action],
-- ^ Actions to run when the editor is started.
initialActions :: [Action],
-- ^ Actions to run after startup (after startActions) or reload.
defaultKm :: KeymapSet,
-- ^ Default keymap to use.
configInputPreprocess :: I.P Event Event,
modeTable :: [AnyMode],
-- ^ List modes by order of preference.
debugMode :: Bool,
-- ^ Produce a .yi.dbg file with a lot of debug information.
configRegionStyle :: RegionStyle,
-- ^ Set to 'Exclusive' for an emacs-like behaviour.
configKillringAccumulate :: Bool,
-- ^ Set to 'True' for an emacs-like behaviour, where
-- all deleted text is accumulated in a killring.
configCheckExternalChangesObsessively :: Bool,
bufferUpdateHandler :: [[Update] -> BufferM ()],
layoutManagers :: [AnyLayoutManager],
-- ^ List of layout managers for 'cycleLayoutManagersNext'
configVars :: ConfigState.DynamicState
-- ^ Custom configuration, containing the 'YiConfigVariable's. Configure with 'configVariableA'.
}
-- Yi.Buffer.Normal
-- Region styles are relative to the buffer contents.
-- They likely should be considered a TextUnit.
data RegionStyle = LineWise
| Inclusive
| Exclusive
| Block
deriving (Eq, Typeable, Show)
instance Binary RegionStyle where
put LineWise = B.put (0 :: Word8)
put Inclusive = B.put (1 :: Word8)
put Exclusive = B.put (2 :: Word8)
put Block = B.put (3 :: Word8)
get = B.get >>= \case
(0 :: Word8) -> return LineWise
1 -> return Inclusive
2 -> return Exclusive
3 -> return Block
n -> fail $ "Binary RegionStyle fail with " ++ show n
-- TODO: put in the buffer state proper.
instance Default RegionStyle where
def = Inclusive
instance YiVariable RegionStyle
| siddhanathan/yi | yi-core/src/Yi/Types.hs | gpl-2.0 | 19,122 | 0 | 27 | 5,668 | 3,841 | 2,172 | 1,669 | -1 | -1 |
{-# OPTIONS_GHC -fplugin=System.Hardware.Haskino.ShallowDeepPlugin #-}
-------------------------------------------------------------------------------
-- |
-- Module : System.Hardware.Haskino.SamplePrograms.Rewrite.TransMultiTest1.hs
-- Copyright : (c) University of Kansas
-- License : BSD3
-- Stability : experimental
--
-- MultiModule test example used for rewrite written in shallow version.
-------------------------------------------------------------------------------
module System.Hardware.Haskino.SamplePrograms.Rewrite.TransMultiTest1 (myRead1, myRead2, myRead3, myWrite) where
import System.Hardware.Haskino
import Control.Monad
import Data.Word
import Data.Boolean
myRead1 :: Word8 -> Arduino Bool
myRead1 p = do
delayMillis 100
a <- digitalRead (p+1)
return (not a)
myRead2 :: Word8 -> Arduino Bool
myRead2 p = do
delayMillis 100
digitalRead (p+1)
myRead3 :: Word8 -> Arduino Bool
myRead3 p = do
delayMillis 100
return True
myWrite :: Word8 -> Bool -> Arduino ()
myWrite p b = do
delayMillis 100
digitalWrite (p+1) (not b)
extraFunc :: Word32 -> Arduino ()
extraFunc a = delayMillis (a * 100)
| ku-fpg/kansas-amber | tests/TransTests/TransMultiTest1.hs | bsd-3-clause | 1,168 | 0 | 10 | 194 | 268 | 139 | 129 | 25 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Core.ShellParser(parseCommand, parseTactic) where
import Core.TT
import Core.Elaborate
import Core.CoreParser
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Language
import qualified Text.ParserCombinators.Parsec.Token as PTok
import Debug.Trace
type TokenParser a = PTok.TokenParser a
lexer :: TokenParser ()
lexer = PTok.makeTokenParser haskellDef
whiteSpace= PTok.whiteSpace lexer
lexeme = PTok.lexeme lexer
symbol = PTok.symbol lexer
natural = PTok.natural lexer
parens = PTok.parens lexer
semi = PTok.semi lexer
comma = PTok.comma lexer
identifier= PTok.identifier lexer
reserved = PTok.reserved lexer
operator = PTok.operator lexer
reservedOp= PTok.reservedOp lexer
lchar = lexeme.char
parseCommand = parse pCommand "(input)"
parseTactic = parse (pTactic >>= return . Tac) "(input)"
pCommand :: Parser Command
pCommand = do reserved "theorem"; n <- iName []; lchar ':'; ty <- pTerm
return (Theorem n ty)
<|> do reserved "eval"; tm <- pTerm
return (Eval tm)
<|> do reserved "print"; n <- iName []; return (Print n)
<|> do reserved "quit";
return Quit
pTactic :: Parser (Elab ())
pTactic = do reserved "attack"; return attack
<|> do reserved "claim"; n <- iName []; lchar ':'; ty <- pTerm
return (claim n ty)
<|> do reserved "regret"; return regret
<|> do reserved "exact"; tm <- pTerm; return (exact tm)
<|> do reserved "fill"; tm <- pTerm; return (fill tm)
<|> do reserved "apply"; tm <- pTerm; args <- many pArgType;
return (discard (apply tm (map (\x -> (x,0)) args)))
<|> do reserved "solve"; return solve
<|> do reserved "compute"; return compute
<|> do reserved "intro"; n <- iName []; return (intro (Just n))
<|> do reserved "forall"; n <- iName []; lchar ':'; ty <- pTerm
return (forall n ty)
<|> do reserved "arg"; n <- iName []; t <- iName []; return (arg n t)
<|> do reserved "patvar"; n <- iName []; return (patvar n)
-- <|> do reserved "patarg"; n <- iName []; t <- iName []; return (patarg n t)
<|> do reserved "eval"; t <- pTerm; return (eval_in t)
<|> do reserved "check"; t <- pTerm; return (check_in t)
<|> do reserved "focus"; n <- iName []; return (focus n)
<|> do reserved "state"; return proofstate
<|> do reserved "undo"; return undo
<|> do reserved "qed"; return (discard qed)
pArgType :: Parser Bool
pArgType = do lchar '_'; return True -- implicit (machine fills in)
<|> do lchar '?'; return False -- user fills in
| byorgey/Idris-dev | src/Core/ShellParser.hs | bsd-3-clause | 2,775 | 0 | 29 | 680 | 1,042 | 495 | 547 | 60 | 1 |
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------
module InteractiveEvalTypes (
#ifdef GHCI
RunResult(..), Status(..), Resume(..), History(..),
#endif
) where
#ifdef GHCI
import Id
import BasicTypes
import Name
import RdrName
import TypeRep
import ByteCodeInstr
import SrcLoc
import Exception
import Control.Concurrent
data RunResult
= RunOk [Name] -- ^ names bound by this evaluation
| RunException SomeException -- ^ statement raised an exception
| RunBreak ThreadId [Name] (Maybe BreakInfo)
data Status
= Break Bool HValue BreakInfo ThreadId
-- ^ the computation hit a breakpoint (Bool <=> was an exception)
| Complete (Either SomeException [HValue])
-- ^ the computation completed with either an exception or a value
data Resume
= Resume {
resumeStmt :: String, -- the original statement
resumeThreadId :: ThreadId, -- thread running the computation
resumeBreakMVar :: MVar (),
resumeStatMVar :: MVar Status,
resumeBindings :: ([TyThing], GlobalRdrEnv),
resumeFinalIds :: [Id], -- [Id] to bind on completion
resumeApStack :: HValue, -- The object from which we can get
-- value of the free variables.
resumeBreakInfo :: Maybe BreakInfo,
-- the breakpoint we stopped at
-- (Nothing <=> exception)
resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
-- to fetch the ModDetails & ModBreaks
-- to get this.
resumeHistory :: [History],
resumeHistoryIx :: Int -- 0 <==> at the top of the history
}
data History
= History {
historyApStack :: HValue,
historyBreakInfo :: BreakInfo,
historyEnclosingDecls :: [String] -- declarations enclosing the breakpoint
}
#endif
| ekmett/ghc | compiler/main/InteractiveEvalTypes.hs | bsd-3-clause | 2,218 | 0 | 10 | 690 | 288 | 190 | 98 | 1 | 0 |
----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.DecorationAddons
-- Copyright : (c) Jan Vornberger 2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : jan.vornberger@informatik.uni-oldenburg.de
-- Stability : unstable
-- Portability : not portable
--
-- Various stuff that can be added to the decoration. Most of it
-- is intended to be used by other modules. See
-- "XMonad.Layout.ButtonDecoration" for a module that makes use of this.
--
-----------------------------------------------------------------------------
module XMonad.Layout.DecorationAddons (
titleBarButtonHandler
,defaultThemeWithButtons
,handleScreenCrossing
) where
import XMonad
import qualified XMonad.StackSet as W
import XMonad.Layout.Decoration
import XMonad.Actions.WindowMenu
import XMonad.Layout.Minimize
import XMonad.Layout.Maximize
import XMonad.Hooks.ManageDocks
import XMonad.Util.Font
import XMonad.Util.PositionStore
import Control.Applicative((<$>))
import Data.Maybe
import qualified Data.Set as S
minimizeButtonOffset :: Int
minimizeButtonOffset = 48
maximizeButtonOffset :: Int
maximizeButtonOffset = 25
closeButtonOffset :: Int
closeButtonOffset = 10
buttonSize :: Int
buttonSize = 10
-- | A function intended to be plugged into the 'decorationCatchClicksHook' of a decoration.
-- It will intercept clicks on the buttons of the decoration and invoke the associated action.
-- To actually see the buttons, you will need to use a theme that includes them.
-- See 'defaultThemeWithButtons' below.
titleBarButtonHandler :: Window -> Int -> Int -> X Bool
titleBarButtonHandler mainw distFromLeft distFromRight = do
let action = if (fi distFromLeft <= 3 * buttonSize)
then focus mainw >> windowMenu >> return True
else if (fi distFromRight >= closeButtonOffset &&
fi distFromRight <= closeButtonOffset + buttonSize)
then focus mainw >> kill >> return True
else if (fi distFromRight >= maximizeButtonOffset &&
fi distFromRight <= maximizeButtonOffset + (2 * buttonSize))
then focus mainw >> sendMessage (maximizeRestore mainw) >> return True
else if (fi distFromRight >= minimizeButtonOffset &&
fi distFromRight <= minimizeButtonOffset + buttonSize)
then focus mainw >> minimizeWindow mainw >> return True
else return False
action
-- | Intended to be used together with 'titleBarButtonHandler'. See above.
defaultThemeWithButtons :: Theme
defaultThemeWithButtons = def {
windowTitleAddons = [ (" (M)", AlignLeft)
, ("_" , AlignRightOffset minimizeButtonOffset)
, ("[]" , AlignRightOffset maximizeButtonOffset)
, ("X" , AlignRightOffset closeButtonOffset)
]
}
-- | A function intended to be plugged into the 'decorationAfterDraggingHook' of a decoration.
-- It will check if the window has been dragged onto another screen and shift it there.
-- The PositionStore is also updated accordingly, as this is designed to be used together
-- with "XMonad.Layout.PositionStoreFloat".
handleScreenCrossing :: Window -> Window -> X Bool
handleScreenCrossing w decoWin = withDisplay $ \d -> do
root <- asks theRoot
(_, _, _, px, py, _, _, _) <- io $ queryPointer d root
ws <- gets windowset
sc <- fromMaybe (W.current ws) <$> pointScreen (fi px) (fi py)
maybeWksp <- screenWorkspace $ W.screen sc
let targetWksp = maybeWksp >>= \wksp ->
W.findTag w ws >>= \currentWksp ->
if (currentWksp /= wksp)
then Just wksp
else Nothing
case targetWksp of
Just wksp -> do
-- find out window under cursor on target workspace
-- apparently we have to switch to the workspace first
-- to make this work, which unforunately introduces some flicker
windows $ \ws' -> W.view wksp ws'
(_, _, selWin, _, _, _, _, _) <- io $ queryPointer d root
-- adjust PositionStore
let oldScreenRect = screenRect . W.screenDetail $ W.current ws
newScreenRect = screenRect . W.screenDetail $ sc
{-- somewhat ugly hack to get proper ScreenRect,
creates unwanted inter-dependencies
TODO: get ScreenRects in a proper way --}
oldScreenRect' <- fmap ($ oldScreenRect) (calcGap $ S.fromList [minBound .. maxBound])
newScreenRect' <- fmap ($ newScreenRect) (calcGap $ S.fromList [minBound .. maxBound])
wa <- io $ getWindowAttributes d decoWin
modifyPosStore (\ps ->
posStoreMove ps w (fi $ wa_x wa) (fi $ wa_y wa)
oldScreenRect' newScreenRect')
-- set focus correctly so the window will be inserted
-- at the correct position on the target workspace
-- and then shift the window
windows $ \ws' -> W.shiftWin wksp w . W.focusWindow selWin $ ws'
-- return True to signal that screen crossing has taken place
return True
Nothing -> return False
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Layout/DecorationAddons.hs | bsd-2-clause | 5,966 | 0 | 20 | 2,074 | 969 | 524 | 445 | 72 | 5 |
-- | A common problem is the desire to have an action run at a scheduled
-- interval, but only if it is needed. For example, instead of having
-- every web request result in a new @getCurrentTime@ call, we'd like to
-- have a single worker thread run every second, updating an @IORef@.
-- However, if the request frequency is less than once per second, this is
-- a pessimization, and worse, kills idle GC.
--
-- This library allows you to define actions which will either be
-- performed by a dedicated thread or, in times of low volume, will be
-- executed by the calling thread.
module Control.AutoUpdate (
-- * Type
UpdateSettings
, defaultUpdateSettings
-- * Accessors
, updateFreq
, updateSpawnThreshold
, updateAction
-- * Creation
, mkAutoUpdate
) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar,
takeMVar, tryPutMVar)
import Control.Exception (SomeException, catch, throw, mask_, try)
import Control.Monad (void)
import Data.IORef (newIORef, readIORef, writeIORef)
-- | Default value for creating an @UpdateSettings@.
--
-- Since 0.1.0
defaultUpdateSettings :: UpdateSettings ()
defaultUpdateSettings = UpdateSettings
{ updateFreq = 1000000
, updateSpawnThreshold = 3
, updateAction = return ()
}
-- | Settings to control how values are updated.
--
-- This should be constructed using @defaultUpdateSettings@ and record
-- update syntax, e.g.:
--
-- @
-- let set = defaultUpdateSettings { updateAction = getCurrentTime }
-- @
--
-- Since 0.1.0
data UpdateSettings a = UpdateSettings
{ updateFreq :: Int
-- ^ Microseconds between update calls. Same considerations as
-- @threadDelay@ apply.
--
-- Default: 1 second (1000000)
--
-- Since 0.1.0
, updateSpawnThreshold :: Int
-- ^ NOTE: This value no longer has any effect, since worker threads are
-- dedicated instead of spawned on demand.
--
-- Previously, this determined: How many times the data must be requested
-- before we decide to spawn a dedicated thread.
--
-- Default: 3
--
-- Since 0.1.0
, updateAction :: IO a
-- ^ Action to be performed to get the current value.
--
-- Default: does nothing.
--
-- Since 0.1.0
}
-- | Generate an action which will either read from an automatically
-- updated value, or run the update action in the current thread.
--
-- Since 0.1.0
mkAutoUpdate :: UpdateSettings a -> IO (IO a)
mkAutoUpdate us = do
-- A baton to tell the worker thread to generate a new value.
needsRunning <- newEmptyMVar
-- The initial response variable. Response variables allow the requesting
-- thread to block until a value is generated by the worker thread.
responseVar0 <- newEmptyMVar
-- The current value, if available. We start off with a Left value
-- indicating no value is available, and the above-created responseVar0 to
-- give a variable to block on.
currRef <- newIORef $ Left responseVar0
-- This is used to set a value in the currRef variable when the worker
-- thread exits. In reality, that value should never be used, since the
-- worker thread exiting only occurs if an async exception is thrown, which
-- should only occur if there are no references to needsRunning left.
-- However, this handler will make error messages much clearer if there's a
-- bug in the implementation.
let fillRefOnExit f = do
eres <- try f
case eres of
Left e -> writeIORef currRef $ error $
"Control.AutoUpdate.mkAutoUpdate: worker thread exited with exception: "
++ show (e :: SomeException)
Right () -> writeIORef currRef $ error $
"Control.AutoUpdate.mkAutoUpdate: worker thread exited normally, "
++ "which should be impossible due to usage of infinite loop"
-- fork the worker thread immediately. Note that we mask async exceptions,
-- but *not* in an uninterruptible manner. This will allow a
-- BlockedIndefinitelyOnMVar exception to still be thrown, which will take
-- down this thread when all references to the returned function are
-- garbage collected, and therefore there is no thread that can fill the
-- needsRunning MVar.
--
-- Note that since we throw away the ThreadId of this new thread and never
-- calls myThreadId, normal async exceptions can never be thrown to it,
-- only RTS exceptions.
mask_ $ void $ forkIO $ fillRefOnExit $ do
-- This infinite loop makes up out worker thread. It takes an a
-- responseVar value where the next value should be putMVar'ed to for
-- the benefit of any requesters currently blocked on it.
let loop responseVar = do
-- block until a value is actually needed
takeMVar needsRunning
-- new value requested, so run the updateAction
a <- catchSome $ updateAction us
-- we got a new value, update currRef and lastValue
writeIORef currRef $ Right a
putMVar responseVar a
-- delay until we're needed again
threadDelay $ updateFreq us
-- delay's over. create a new response variable and set currRef
-- to use it, so that the next requester will block on that
-- variable. Then loop again with the updated response
-- variable.
responseVar' <- newEmptyMVar
writeIORef currRef $ Left responseVar'
loop responseVar'
-- Kick off the loop, with the initial responseVar0 variable.
loop responseVar0
return $ do
mval <- readIORef currRef
case mval of
Left responseVar -> do
-- no current value, force the worker thread to run...
void $ tryPutMVar needsRunning ()
-- and block for the result from the worker
readMVar responseVar
-- we have a current value, use it
Right val -> return val
-- | Turn a runtime exception into an impure exception, so that all @IO@
-- actions will complete successfully. This simply defers the exception until
-- the value is forced.
catchSome :: IO a -> IO a
catchSome act = Control.Exception.catch act $ \e -> return $ throw (e :: SomeException)
| jberryman/wai | auto-update/Control/AutoUpdate.hs | mit | 6,650 | 0 | 18 | 1,937 | 646 | 367 | 279 | 56 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.