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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- http://www.codewars.com/kata/558ee8415872565824000007
module Codewars.Kata.Divisible where
isDivisible :: Integral n => n -> [n] -> Bool
isDivisible n xs = n `mod` foldl lcm 1 xs == 0 | Bodigrim/katas | src/haskell/7-Is-n-divisible-by-.hs | bsd-2-clause | 187 | 0 | 8 | 27 | 58 | 32 | 26 | 3 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Blaze.ByteString.Builder.ZoomCache
-- Copyright : Conrad Parker
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Conrad Parker <conrad@metadecks.org>
-- Stability : unstable
-- Portability : unknown
--
-- Blaze-builder utility functions for writing ZoomCache files.
----------------------------------------------------------------------
module Blaze.ByteString.Builder.ZoomCache (
-- * Creating builders for ZoomCache types
fromSampleOffset
-- * Creating builders from numeric types used by ZoomCache
, fromFloat
, fromDouble
, fromIntegral32be
, fromIntegerVLC
, fromRational64
) where
import Blaze.ByteString.Builder
import Data.Bits
import Data.Monoid
import Data.Ratio
import Data.Word
import Unsafe.Coerce (unsafeCoerce)
import Data.ZoomCache.Common
----------------------------------------------------------------------
-- Creating builders for ZoomCache types.
-- | Serialize a 'TimeStamp' in 64bit big endian format.
fromSampleOffset :: SampleOffset -> Builder
fromSampleOffset = fromInt64be . fromIntegral . unSO
{-# INLINE fromSampleOffset #-}
----------------------------------------------------------------------
-- Creating builders from numeric types used by ZoomCache.
-- | Serialize a 'Float' in big-endian IEEE 754-2008 binary32 format
-- (IEEE 754-1985 single format).
fromFloat :: Float -> Builder
fromFloat = fromWord32be . toWord32
where
toWord32 :: Float -> Word32
toWord32 = unsafeCoerce
{-# INLINE fromFloat #-}
-- | Serialize a 'Double' in big-endian IEEE 754-2008 binary64 format
-- (IEEE 754-1985 double format).
fromDouble :: Double -> Builder
fromDouble = fromWord64be . toWord64
where
toWord64 :: Double -> Word64
toWord64 = unsafeCoerce
{-# INLINE fromDouble #-}
-- | Serialize an 'Integral' in 32bit big endian format.
fromIntegral32be :: forall a . (Integral a) => a -> Builder
fromIntegral32be = fromInt32be . fromIntegral
{-# SPECIALIZE INLINE fromIntegral32be :: Int -> Builder #-}
{-# SPECIALIZE INLINE fromIntegral32be :: Integer -> Builder #-}
-- | Serialize an 'Integer' in variable-length-coding format
-- For details of the variable-length coding format, see
-- "Data.ZoomCache.Numeric.Int".
fromIntegerVLC :: Integer -> Builder
fromIntegerVLC x0 = enc x1 `mappend` buildVLC xHi
where
x1 = (xLo `shiftL` 1) .|. sign0
sign0 | x0 < 0 = 1
| otherwise = 0
(xHi, xLo) = bCont 6 (abs x0)
-- Split a bitstring of length len into a tuple of
-- the top (len-n) bits and (the lower n bits with the
-- extension bit set if any of the top (len-n) bits are
-- non-zero). We assume n < 8.
bCont :: (Num a, Bits a) => Int -> a -> (a, a)
bCont n v
| hi == 0 = (hi, lo)
| otherwise = (hi, lo .|. (2^n))
where
-- Split a bitstring of length len into a tuple of
-- the top (len-n) bits and the lower n bits.
(hi, lo) = (v `shiftR` n, v .&. (2^n -1))
-- Build a variable-length-coded sequence of bytes corresponding
-- to the contents of x, 7 bits at a time.
buildVLC x
| x == 0 = mempty
| otherwise = enc lo `mappend` buildVLC hi
where
(hi, lo) = bCont 7 x
enc :: Integer -> Builder
enc = fromWord8 . fromIntegral
-- | Serialize a 'Rational' as a sequence of two 64bit big endian format
-- integers.
fromRational64 :: Rational -> Builder
fromRational64 r = mconcat
[ fromInt64be . fromIntegral . numerator $ r
, fromInt64be . fromIntegral . denominator $ r
]
{-# INLINE fromRational64 #-}
| kfish/zoom-cache | Blaze/ByteString/Builder/ZoomCache.hs | bsd-2-clause | 3,882 | 0 | 13 | 919 | 587 | 343 | 244 | 56 | 1 |
import Control.Applicative
import System.Random
import System.Environment
import HW.FloatAdder.Test
main :: IO ()
main = do args <- getArgs
let len = read $ head args
cases <- generateCases len <$> getStdGen
mapM_ (putStrLn . \(x,y,z) -> show x ++ " " ++ show y ++ " " ++ show z) cases
| grafi-tt/Maizul | fpu-misc/original/fadd-grafi/TestData.hs | bsd-2-clause | 319 | 0 | 15 | 84 | 128 | 64 | 64 | 9 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module Handsontable.JQuery (
newHandsonTable
) where
import Handsontable (marshalCfg, HandsonOptions)
import Handsontable.JQuery.Internal
import JavaScript.JQuery
--------------------------------------------------------------------------------
newHandsonTable :: HandsonOptions -> JQuery -> IO Handsontable
newHandsonTable cfg jq = hst_newHandsontable jq =<< marshalCfg cfg
| adinapoli/ghcjs-handsontable | src-ghcjs/Handsontable/JQuery.hs | bsd-3-clause | 481 | 0 | 7 | 50 | 73 | 42 | 31 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Draw.PostListOverlay where
import Prelude ()
import Prelude.MH
import Brick
import Brick.Widgets.Border
import Brick.Widgets.Center
import Control.Monad.Trans.Reader ( withReaderT )
import qualified Data.Text as T
import Lens.Micro.Platform ( (^?), (%~), to )
import Network.Mattermost.Lenses
import Network.Mattermost.Types
import Draw.Main
import Draw.Messages
import Draw.Util
import Themes
import Types
hLimitWithPadding :: Int -> Widget n -> Widget n
hLimitWithPadding pad contents = Widget
{ hSize = Fixed
, vSize = (vSize contents)
, render =
withReaderT (& availWidthL %~ (\ n -> n - (2 * pad))) $ render $ cropToContext contents
}
drawPostListOverlay :: PostListContents -> ChatState -> [Widget Name]
drawPostListOverlay contents st =
(joinBorders $ drawPostsBox contents st) : (forceAttr "invalid" <$> drawMain st)
-- | Draw a PostListOverlay as a floating overlay on top of whatever
-- is rendered beneath it
drawPostsBox :: PostListContents -> ChatState -> Widget Name
drawPostsBox contents st =
centerLayer $ hLimitWithPadding 10 $ borderWithLabel contentHeader $
padRight (Pad 1) messageListContents
where -- The 'window title' of the overlay
hs = getHighlightSet st
contentHeader = withAttr channelListHeaderAttr $ txt $ case contents of
PostListFlagged -> "Flagged posts"
PostListSearch terms searching -> "Search results" <> if searching
then ": " <> terms
else " (" <> (T.pack . show . length) messages <> "): " <> terms
messages = insertDateMarkers
(filterMessages knownChannel $ st^.csPostListOverlay.postListPosts)
(getDateFormat st)
(st^.timeZone)
knownChannel msg =
case msg^.mChannelId of
Just cId | Nothing <- st^?csChannels.channelByIdL(cId) -> False
_ -> True
-- The overall contents, with a sensible default even if there
-- are no messages
messageListContents
| null messages =
padTopBottom 1 $
hCenter $
withDefAttr clientEmphAttr $
str $ case contents of
PostListFlagged -> "You have no flagged messages."
PostListSearch _ searching ->
if searching
then "Searching ..."
else "No search results found"
| otherwise = vBox renderedMessageList
-- The render-message function we're using
renderMessageForOverlay msg =
let renderedMsg = renderSingleMessage st hs Nothing msg
in case msg^.mOriginalPost of
-- We should factor out some of the channel name logic at
-- some point, but we can do that later
Just post
| Just chan <- st^?csChannels.channelByIdL(post^.postChannelIdL) ->
case chan^.ccInfo.cdType of
Direct
| Just u <- userByDMChannelName (chan^.ccInfo.cdName)
(myUserId st)
st ->
(forceAttr channelNameAttr (txt (userSigil <> u^.uiName)) <=>
(str " " <+> renderedMsg))
_ -> (forceAttr channelNameAttr (txt (chan^.ccInfo.to mkChannelName)) <=>
(str " " <+> renderedMsg))
_ | CP _ <- msg^.mType -> str "[BUG: unknown channel]"
| otherwise -> renderedMsg
-- The full message list, rendered with the current selection
renderedMessageList =
let (s, (before, after)) = splitMessages (MessagePostId <$> st^.csPostListOverlay.postListSelected) messages
in case s of
Nothing -> map renderMessageForOverlay (reverse (toList messages))
Just curMsg ->
[unsafeRenderMessageSelection (curMsg, (after, before)) renderMessageForOverlay]
| aisamanra/matterhorn | src/Draw/PostListOverlay.hs | bsd-3-clause | 4,200 | 0 | 24 | 1,446 | 935 | 486 | 449 | -1 | -1 |
-- |
-- Module: Database.Migrate
-- Copyright: (c) 2012 Mark Hibberd
-- License: BSD3
-- Maintainer: Mark Hibberd <mark@hibberd.id.au>
-- Portability: portable
--
-- A library to assist with managing database versioning
-- and migration.
--
-- /Note/: This library is under heavy development, currently
-- the PostgreSQL implementation is functional, but
-- expected to change. It is intended that a type safe
-- migration api, command line tools and MySql support be added
-- before this library will be considered stable.
--
module Database.Migrate (module X) where
import Database.Migrate.Data as X
import Database.Migrate.Kernel as X
import Database.Migrate.Loader as X
import Database.Migrate.Main as X
import Database.Migrate.PostgreSQL as X
| markhibberd/database-migrate | src/Database/Migrate.hs | bsd-3-clause | 766 | 0 | 4 | 126 | 68 | 54 | 14 | 6 | 0 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE MultiWayIf #-}
module Hans.Tcp.RecvWindow (
-- * Receive Window
Window(),
emptyWindow,
recvSegment,
rcvWnd,
rcvNxt, setRcvNxt,
rcvRight,
moveRcvRight,
-- ** Sequence Numbers
sequenceNumberValid,
) where
import Hans.Lens
import Hans.Tcp.Packet
import qualified Data.ByteString as S
import Data.Word (Word16)
-- Segments --------------------------------------------------------------------
data Segment = Segment { segStart :: !TcpSeqNum
-- ^ The first byte occupied by this segment
, segEnd :: !TcpSeqNum
-- ^ The last byte occupied by this segment
, segHdr :: !TcpHeader
, segBody :: !S.ByteString
} deriving (Show)
mkSegment :: TcpHeader -> S.ByteString -> Segment
mkSegment segHdr segBody =
Segment { segStart = tcpSeqNum segHdr
, segEnd = tcpSegLastSeqNum segHdr (S.length segBody)
, .. }
-- | The next segment number, directly after this one.
segNext :: Segment -> TcpSeqNum
segNext Segment { .. } = segEnd + 1
-- | Drop data off of the front of this segment.
trimSeg :: Int -> Segment -> Maybe Segment
trimSeg len seg@Segment { .. }
| len' <= 0 =
Just seg
| len' >= S.length segBody =
Nothing
| otherwise =
Just $! Segment { segStart = segStart + fromIntegral len'
, segHdr = segHdr { tcpSeqNum = tcpSeqNum segHdr
+ fromIntegral len }
, segBody = S.drop len segBody
, .. }
where
flag l | view l segHdr = 1
| otherwise = 0
-- adjust the length to account for syn/fin
len' = len - flag tcpSyn - flag tcpFin
-- | Resolve overlap between two segments. It's assumed that the two segments do
-- actually overlap.
resolveOverlap :: Segment -> Segment -> [Segment]
resolveOverlap a b =
case trimSeg (fromTcpSeqNum (segEnd x - segStart y)) x of
Just x' -> [x',y]
Nothing -> error "resolveOverlap: invariant violated"
where
(x,y) | segStart a < segStart b = (a,b) -- a overlaps b
| otherwise = (b,a) -- b overlaps a
-- Receive Window --------------------------------------------------------------
-- | The receive window.
--
-- INVARIANTS:
--
-- 1. All segments in rwSegments are within the window defined by rwRcvNxt and
-- rwRcvWnd
-- 2. The segments in rwSegments should not overlap
--
data Window = Window { wSegments :: ![Segment]
-- ^ Out of order segments.
, wRcvNxt :: !TcpSeqNum
-- ^ Left-edge of the receive window
, wRcvRight :: !TcpSeqNum
-- ^ Right-edge of the receive window
, wMax :: !TcpSeqNum
-- ^ Maximum size of the receive window
} deriving (Show)
emptyWindow :: TcpSeqNum -> Int -> Window
emptyWindow wRcvNxt maxWin =
Window { wSegments = []
, wRcvRight = wRcvNxt + wMax
, .. }
where
wMax = fromIntegral maxWin
-- | The value of RCV.WND.
rcvWnd :: Lens' Window Word16
rcvWnd f Window { .. } =
fmap (\ wnd -> Window { wRcvRight = wRcvNxt + fromIntegral wnd, .. })
(f (fromTcpSeqNum (wRcvRight - wRcvNxt)))
-- | The left edge of the receive window.
rcvNxt :: Getting r Window TcpSeqNum
rcvNxt = to wRcvNxt
-- | The right edge of the receive window, RCV.NXT + RCV.WND.
rcvRight :: Getting r Window TcpSeqNum
rcvRight = to wRcvRight
-- | Only sets RCV.NXT when the segment queue is empty. Returns 'True' when the
-- value has been successfully changed.
setRcvNxt :: TcpSeqNum -> Window -> (Window,Bool)
setRcvNxt nxt win
| null (wSegments win) = (win { wRcvNxt = nxt, wRcvRight = nxt + wMax win }, True)
| otherwise = (win, False)
-- | Check an incoming segment, and queue it in the receive window. When the
-- segment received was valid 'Just' is returned, including segments in the
-- receive window were unblocked by it.
--
-- NOTE: when Just[] is returned, this should be a signal to issue a duplicate
-- ACK, as we've receive something out of sequence (fast retransmit).
recvSegment :: TcpHeader -> S.ByteString -> Window
-> (Window, Maybe [(TcpHeader,S.ByteString)])
recvSegment hdr body win
-- add the trimmed frame to the receive queue
| Just seg <- sequenceNumberValid (wRcvNxt win) (wRcvRight win) hdr body =
let (win', segs) = addSegment seg win
in (win', Just [ (segHdr,segBody) | Segment { .. } <- segs ])
-- drop the invalid frame
| otherwise =
(win, Nothing)
-- | Increase the right edge of the window by n, clamping at the maximum window
-- size.
moveRcvRight :: Int -> Window -> (Window, ())
moveRcvRight n = \ win ->
let rcvRight' = view rcvRight win + min (max 0 (fromIntegral n)) (wMax win)
in (win { wRcvRight = rcvRight' }, ())
{-# INLINE moveRcvRight #-}
-- | Add a validated segment to the receive window, and return
addSegment :: Segment -> Window -> (Window, [Segment])
addSegment seg win
-- The new segment falls right at the beginning of the receive window. Move
-- RCV.NXT and put the segment into the receive buffer. Don't modify
-- RCV.WND until the segment has been removed from the receive buffer.
| segStart seg == wRcvNxt win =
advanceLeft seg win
-- As addSegment should only be called with the results of
-- sequenceNumberValid, the only remaining case to consider is that the
-- segment falls somewhere else within the window.
| otherwise =
(insertOutOfOrder seg win, [])
-- | Use this segment to advance the window, which may unblock zero or more out
-- of order segments. The list returned is always non-empty, as it includes the
-- segment that's given.
advanceLeft :: Segment -> Window -> (Window, [Segment])
advanceLeft seg win
-- there were no other segments that might be unblocked by this one
| null (wSegments win) =
( win { wRcvNxt = segNext seg }, [seg])
-- see if this segment unblocks any others
| otherwise =
let win' = insertOutOfOrder seg win -- to resolve overlap
(nxt,valid,rest) = splitContiguous (wSegments win')
in (win' { wSegments = rest, wRcvNxt = nxt }, valid)
-- | Insert a new segment into the receive window. NOTE: we don't need to worry
-- about trimming the segment to fit the window, as that's already been done by
-- sequenceNumberValid.
insertOutOfOrder :: Segment -> Window -> Window
insertOutOfOrder seg Window { .. } = Window { wSegments = segs', .. }
where
segs' = loop seg wSegments
loop new segs@(x:xs)
-- new segment ends before x starts
| segEnd new < segStart x = new : segs
-- new segment starts after x
| segStart new > segEnd x =
x : loop new segs
-- segments overlap
| otherwise = resolveOverlap new x ++ xs
loop new [] = [new]
-- | Split out contiguous segments, and out of order segments. NOTE: this
-- assumes that the segment list given does not contain any overlapping
-- segments, and is ordered.
--
-- NOTE: this should never be called with an empty list.
splitContiguous :: [Segment] -> (TcpSeqNum,[Segment],[Segment])
splitContiguous (seg:segs) = loop [seg] (segNext seg) segs
where
loop acc from (x:xs) | segStart x == from = loop (x:acc) (segNext seg) xs
loop acc from xs = (from, reverse acc, xs)
splitContiguous [] = error "splitContiguous: empty list"
-- Window Checks ---------------------------------------------------------------
-- | This is the check described on page 68 of RFC793, which checks that data
-- falls within the expected receive window. When the check is successful, the
-- segment returned is one that has been trimmed to fit in the window (if
-- necessary).
--
-- When this produces a segment, the segment has these properties:
--
-- 1. The sequence number is within the window
-- 2. The segment body falls within the window
-- 3. The segment has been copied from the original bytestring
--
-- The reason for point 3 is that when frames are allocated by devices, they are
-- likely allocated to the full MTU, and not resized. Copying here frees up some
-- memory.
sequenceNumberValid :: TcpSeqNum -- ^ RCV.NXT
-> TcpSeqNum -- ^ RCV.NXT + RCV.WND
-> TcpHeader
-> S.ByteString
-> Maybe Segment
sequenceNumberValid nxt wnd hdr@TcpHeader { .. } payload
| payloadLen == 0 =
if nullWindow
-- test 1
then if tcpSeqNum == nxt then Just (mkSegment hdr S.empty) else Nothing
-- test 2
else if seqNumInWindow then Just (mkSegment hdr S.empty) else Nothing
| otherwise =
if nullWindow
-- test 3
then Nothing
-- test 4
else if | seqNumInWindow -> Just (mkSegment hdr seg')
| dataEndInWindow -> Just (mkSegment hdr' seg')
| otherwise -> Nothing
where
nullWindow = nxt == wnd
payloadLen = tcpSegLen hdr (fromIntegral (S.length payload))
segEnd = tcpSeqNum + fromIntegral (payloadLen - 1)
-- adjusted header for when the payload spans RCV.NXT
hdr' = hdr { tcpSeqNum = nxt }
-- XXX: this doesn't account for syn/fin at the moment
-- trim the payload to fit in the window
seg' = S.copy $ S.drop (fromTcpSeqNum (nxt - tcpSeqNum))
$ S.take (fromTcpSeqNum (segEnd - wnd)) payload
seqNumInWindow = nxt <= tcpSeqNum && tcpSeqNum < wnd
dataEndInWindow = nxt <= segEnd && segEnd < wnd
| cartazio/HaNS | src/Hans/Tcp/RecvWindow.hs | bsd-3-clause | 9,742 | 7 | 19 | 2,657 | 1,996 | 1,084 | 912 | 157 | 7 |
{-# LANGUAGE TupleSections #-}
module Rho.SessionState where
import Control.Concurrent
import Control.Monad
import Data.IORef
import Data.List (sortOn)
import qualified Data.Map as M
import Data.Maybe (fromJust)
import qualified Data.Set as S
import Data.Word
import Network.Socket (PortNumber, SockAddr)
import Safe (headMay)
import Rho.InfoHash
import Rho.PeerComms.PeerConnState
import Rho.PeerComms.PeerId
import Rho.PieceMgr
import qualified Rho.PieceStats as PS
import Rho.Tracker
import Rho.Utils
type PeerConnRef = (PeerId, IORef PeerConn)
type PeerConnRef' = (PeerConn, IORef PeerConn)
readPeerConnRef :: PeerConnRef -> IO PeerConnRef'
readPeerConnRef (_, ref) = (, ref) <$> readIORef ref
peerConn :: PeerConnRef -> IO PeerConn
peerConn = readIORef . snd
data Session = Session
{ sessPeerId :: PeerId
-- ^ our peer id
, sessInfoHash :: InfoHash
-- ^ info hash of the torrent we're downloading/seeding
, sessTrackers :: MVar [Tracker]
-- ^ trackers we use to request peers
, sessPeers :: MVar (M.Map PeerId (IORef PeerConn))
-- ^ connected peers
, sessPieceMgr :: MVar (Maybe PieceMgr)
-- ^ piece manager for torrent data
, sessPieceStats :: MVar PS.PieceStats
-- TODO: Should this be an MVar?
-- TODO: We should remove pieces that we completed from PieceStats.
-- TODO: We should remove disconnected peers from PieceStats.
, sessMIPieceMgr :: MVar PieceMgr
-- ^ piece manager for info dictionary
, sessRequestedPieces :: MVar (S.Set PieceIdx)
-- ^ set of pieces we've requested
, sessPort :: PortNumber
-- ^ port number of the socket that we use for incoming handshakes
, sessOnMIComplete :: MVar (IO ())
-- ^ callback to call when metainfo download completed
, sessOnTorrentComplete :: MVar (IO ())
-- ^ callback to call when torrent download completed
, sessDownloaded :: IORef Word64
, sessUploaded :: IORef Word64
, sessCurrentOptUnchoke :: IORef (Maybe PeerConnRef)
-- ^ Lucky peer chosen for optimistic unchoke. We rotate this in every 30
-- seconds. When we unchoked the current peer can be seen in pcLastUnchoke
-- field of PeerConn.
}
initSession
:: PeerId -> InfoHash -> PortNumber
-> [Tracker] -> Maybe PieceMgr -> Maybe PieceMgr -> IO Session
initSession peerId infoHash port trackers pieces miPieces = do
ts <- newMVar trackers
peers <- newMVar M.empty
pmgr <- newMVar pieces
miPMgr <- maybe newEmptyMVar newMVar miPieces
pstats <- newMVar PS.initPieceStats
reqs <- newMVar S.empty
miCb <- newMVar (return ())
tCb <- newMVar (return ())
dr <- newIORef 0
ur <- newIORef 0
opt <- newIORef Nothing
return $ Session peerId infoHash ts peers pmgr pstats miPMgr reqs port miCb tCb dr ur opt
type SessStats = (Word64, Word64, Word64)
stats :: Session -> IO (Word64, Word64, Word64)
stats Session{sessDownloaded=d, sessUploaded=u, sessPieceMgr=pm} = do
d' <- readIORef d
u' <- readIORef u
pm' <- readMVar pm
let l = case pm' of
Nothing -> 0
Just PieceMgr{pmTotalSize=ts} -> ts - d'
return (d', l, u')
--------------------------------------------------------------------------------
-- | Check whether we've an active connection with the given socket address.
checkActiveConnection :: Session -> SockAddr -> IO (Maybe PeerConn)
checkActiveConnection sess addr = do
peers <- mapM readIORef =<< M.elems <$> readMVar (sessPeers sess)
return $ headMay $ filter ((addr ==) . pcSockAddr) peers
readPeers :: Session -> IO [PeerConnRef']
readPeers = mapM readPeerConnRef . M.toList <=< readMVar . sessPeers
peerConnRefFromId :: Session -> PeerId -> IO (Maybe PeerConnRef)
peerConnRefFromId Session{sessPeers=peers} pId = ((pId,) <.> M.lookup pId) <$> readMVar peers
currentOptUnchoke :: Session -> IO (Maybe PeerConnRef)
currentOptUnchoke = readIORef . sessCurrentOptUnchoke
setCurrentOptUnchoke :: Session -> Maybe PeerConnRef -> IO ()
setCurrentOptUnchoke = writeIORef . sessCurrentOptUnchoke
addPiece :: Session -> PeerId -> PieceIdx -> IO ()
addPiece Session{sessPieceStats=statsMV} pid pIdx =
modifyMVar_ statsMV $ return . PS.addPiece pid pIdx
addPieces :: Session -> PeerId -> [PieceIdx] -> IO ()
addPieces Session{sessPieceStats=statsMV} pid pIdx =
modifyMVar_ statsMV $ return . PS.addPieces pid pIdx
piecesToReq :: Session -> IO [(PieceIdx, S.Set PeerId)]
piecesToReq sess = do
stats <- readMVar (sessPieceStats sess)
alreadyRequested <- readMVar (sessRequestedPieces sess)
return $ filter (not . (flip S.member alreadyRequested) . fst) (PS.takeMins stats 10)
markPieceComplete :: Session -> PieceIdx -> IO ()
markPieceComplete Session{sessPieceStats=ps} pIdx =
modifyMVar_ ps $ return . PS.removePiece pIdx
pieceReqForPeer :: Session -> PeerConn -> IO (Maybe PieceIdx)
pieceReqForPeer sess pc = do
missings <- (S.fromList <.> missingPieces) =<< (fromJust <$> readMVar (sessPieceMgr sess))
peerPcs <- peerPieces pc
reqs <- readMVar (sessRequestedPieces sess)
pStats <- readMVar (sessPieceStats sess)
let
canRequest = S.toList ((missings `S.intersection` peerPcs) `S.difference` reqs)
pris = zip canRequest (map (flip PS.piecePriority pStats) canRequest)
prisSorted = sortOn snd [ (pIdx, pri) | (pIdx, Just pri) <- pris ]
return $ fst <$> headMay prisSorted
| osa1/rho-torrent | src/Rho/SessionState.hs | bsd-3-clause | 5,766 | 0 | 16 | 1,433 | 1,552 | 807 | 745 | -1 | -1 |
{-# LANGUAGE CPP, TypeOperators #-}
-----------------------------------------------------------------------------
-- |
-- Module : Xmobar.Config
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability : unstable
-- Portability : unportable
--
-- The configuration module of Xmobar, a text based status bar
--
-----------------------------------------------------------------------------
module Config
( -- * Configuration
-- $config
Config (..)
, XPosition (..), Align (..), Border(..)
, defaultConfig
, runnableTypes
) where
import Commands
import {-# SOURCE #-} Runnable
import Plugins.Monitors
import Plugins.Date
import Plugins.PipeReader
import Plugins.BufferedPipeReader
import Plugins.CommandReader
import Plugins.StdinReader
import Plugins.XMonadLog
import Plugins.EWMH
import Plugins.Kbd
#ifdef INOTIFY
import Plugins.Mail
import Plugins.MBox
#endif
#ifdef DATEZONE
import Plugins.DateZone
#endif
-- $config
-- Configuration data type and default configuration
-- | The configuration data type
data Config =
Config { font :: String -- ^ Font
, bgColor :: String -- ^ Backgroud color
, fgColor :: String -- ^ Default font color
, position :: XPosition -- ^ Top Bottom or Static
, dock :: Bool -- act as a normal dockapp (don't override_redirect)
, border :: Border -- ^ NoBorder TopB BottomB or FullB
, borderColor :: String -- ^ Border color
, hideOnStart :: Bool -- ^ Hide (Unmap) the window on
-- initialization
, lowerOnStart :: Bool -- ^ Lower to the bottom of the
-- window stack on initialization
, persistent :: Bool -- ^ Whether automatic hiding should
-- be enabled or disabled
, commands :: [Runnable] -- ^ For setting the command, the command arguments
-- and refresh rate for the programs to run (optional)
, sepChar :: String -- ^ The character to be used for indicating
-- commands in the output template (default '%')
, alignSep :: String -- ^ Separators for left, center and right text alignment
, template :: String -- ^ The output template
} deriving (Read)
data XPosition = Top
| TopW Align Int
| TopSize Align Int Int
| Bottom
| BottomW Align Int
| BottomSize Align Int Int
| Static {xpos, ypos, width, height :: Int}
| OnScreen Int XPosition
deriving ( Read, Eq )
data Align = L | R | C deriving ( Read, Eq )
data Border = NoBorder
| TopB
| BottomB
| FullB
| TopBM Int
| BottomBM Int
| FullBM Int
deriving ( Read, Eq )
-- | The default configuration values
defaultConfig :: Config
defaultConfig =
Config { font = "-misc-fixed-*-*-*-*-10-*-*-*-*-*-*-*"
, bgColor = "#000000"
, fgColor = "#BFBFBF"
, position = Top
, dock = False
, border = NoBorder
, borderColor = "#BFBFBF"
, hideOnStart = False
, lowerOnStart = True
, persistent = False
, commands = [ Run $ Date "%a %b %_d %Y * %H:%M:%S" "theDate" 10
, Run StdinReader]
, sepChar = "%"
, alignSep = "}{"
, template = "%StdinReader% }{ <fc=#00FF00>%uname%</fc> * <fc=#FF0000>%theDate%</fc>"
}
-- | An alias for tuple types that is more convenient for long lists.
type a :*: b = (a, b)
infixr :*:
-- | This is the list of types that can be hidden inside
-- 'Runnable.Runnable', the existential type that stores all commands
-- to be executed by Xmobar. It is used by 'Runnable.readRunnable' in
-- the 'Runnable.Runnable' Read instance. To install a plugin just add
-- the plugin's type to the list of types (separated by ':*:') appearing in
-- this function's type signature.
runnableTypes :: Command :*: Monitors :*: Date :*: PipeReader :*: BufferedPipeReader :*: CommandReader :*: StdinReader :*: XMonadLog :*: EWMH :*: Kbd :*:
#ifdef INOTIFY
Mail :*: MBox :*:
#endif
#ifdef DATEZONE
DateZone :*:
#endif
()
runnableTypes = undefined
| raboof/xmobar | src/Config.hs | bsd-3-clause | 4,741 | 0 | 18 | 1,647 | 605 | 394 | 211 | 74 | 1 |
module System.Console.OptMatch.Popular where
import Control.Applicative
import Control.Monad
import System.Console.OptMatch
import System.Console.OptMatch.Basic
popular :: (Functor m, Monad m) => a -> (a -> OptMatchT m a) -> OptMatchT m a
popular a m = do
r <- m a <|> fixAndRetry
popular r m <|> return r where
fixAndRetry = do
optional expandShortOptions
m a
expandShortOptions :: (Functor m, Monad m) => OptMatchT m ()
expandShortOptions = do
unexpect $ prefix "--"
prefix "-"
str <- shift
forM (reverse str) $ \c -> unshift ['-', c]
return ()
keyword :: Monad m => String -> OptMatchT m String
keyword = just
argument :: Monad m => OptMatchT m String
argument = unexpect (prefix "-") >> shift
| pasberth/optmatch | System/Console/OptMatch/Popular.hs | bsd-3-clause | 732 | 0 | 10 | 150 | 288 | 143 | 145 | 23 | 1 |
module Blog.BackEnd.ModelChangeListener where
import Blog.Model.Entry ( Model )
class ModelChangeListener c where
handle_model_change :: c -> Model -> IO ()
| prb/perpubplat | src/Blog/BackEnd/ModelChangeListener.hs | bsd-3-clause | 165 | 0 | 10 | 28 | 45 | 25 | 20 | 4 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
module Application (program, Handles (..))
where
import Common
import Lib
import Data.Either
import Data.Typeable
import Data.Maybe
import Control.Monad
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Workers
import Dump
import Restore
data ProxySMs s = ProxySMs
data ProxyE e = ProxyE
toDump :: [SMs] -> [E] -> String -> Dump
toDump sms es x = case reads x of
[] -> error "structure messed up"
[((cs,rs),_)] -> let
cs' = [(readAnE e, map readAnSMs sms, i) | (e,sms,i) <- cs]
rs' = [(readAnSMs s, map (Left . readAnE) es) | (s,es) <- rs]
in (cs',rs')
where readAnE e = case readKs e readE es of
Nothing -> error $ "no event type for " ++ show e
Just e -> e
readAnSMs sm = case readKs sm readSMs sms of
Nothing -> error $ "no state type for " ++ show sm
Just sm -> sm
readSMs x (SMs q) = SMs <$> reada x q
readE x (E q) = E <$> reada x q
toString :: Dump -> String
toString (cs,rs) = show (cs',rs') where
cs' = do (e,sms,i) <- cs
return (unE e, map unSMs sms, i)
rs' = do (s,ejs) <- rs
return (unSMs s,map unE . lefts $ ejs)
unSMs (SMs s) = show s
unE (E e) = show e
-- | what we need to control the system
data Handles = Handles
(Either E J -> IO ()) -- ^ accept an event
(IO (Either E J)) -- ^ wait for an event
(FilePath -> IO ()) -- ^ dump the michelle to a file
(FilePath -> IO ()) -- ^ boot michelle from file
(IO ()) -- ^ turn off michelle
-- | the main IO function which fires and kill the actors
program :: [SMs] -- ^ state types
-> [E] -- ^ event types
-> IO Handles -- ^ communication channels with the modules
program sms es = do
events <- atomically $ newTChan -- events common channel (dump channel)
control <- atomically $ newTChan -- borning machines channel
tree <- atomically $ newTVar Nothing
forkIO $ workersThread tree control
let boot file = do
d <- toDump sms es <$> readFile file
atomically $ newStore control events d >>= writeTVar tree . Just
dump file = do
t <- atomically $ readTVar tree
case t of
Nothing -> print "could not dump a service not started"
Just t -> do d <- atomically $ do
(t,d) <- newDump t
writeTVar tree (Just t)
return d
writeFile file (toString d)
return $ Handles
(atomically . writeTChan events)
(atomically $ readTChan events)
dump
boot
(atomically $ writeTVar tree Nothing)
| paolino/michelle | Application.hs | bsd-3-clause | 2,454 | 34 | 17 | 591 | 935 | 488 | 447 | 71 | 4 |
module Twitch (module M, module Twitch) where
import Twitch.Irc.Client as M
import Twitch.Irc.Parser as M
import Twitch.Irc.Constants as M
import Twitch.Irc.Types as M | Globidev/Twitch-hs | src/Twitch.hs | bsd-3-clause | 168 | 0 | 4 | 23 | 46 | 34 | 12 | 5 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Engine
( engine
) where
import Control.Monad (forever)
import Control.Monad.Reader (ask, liftIO)
import Control.Concurrent (threadDelay)
import Data.IORef (readIORef)
import Display
import Linear.V3
import Render
import Render.Engine
import Render.Mesh
import qualified SDL (getWindowSurface, showWindow)
engine :: Engine ()
engine = do
EngineState {..} <- ask
ms <- liftIO $ readIORef meshes
window <- liftIO initWindow
screen <- liftIO $ SDL.getWindowSurface window
liftIO $ SDL.showWindow window
forever $ do
clearWithCol (255, 0, 255, 100)
mapM_ transform ms
render
present window screen
liftIO $ threadDelay (floor $ 1000000.0 / 60.0)
| Lucsanszky/soft-engine | src/Engine.hs | bsd-3-clause | 755 | 0 | 14 | 167 | 232 | 121 | 111 | 26 | 1 |
{-# LANGUAGE DataKinds #-}
module ElmFormat.Parse where
import Elm.Utils ((|>))
import AST.V0_16
import AST.Module (Module)
import AST.Structure ( ASTNS )
import Data.Coapplicative
import qualified Data.Text as Text
import ElmVersion ( ElmVersion )
import qualified Parse.Literal
import qualified Parse.Parse as Parse
import qualified Reporting.Error.Syntax as Syntax
import qualified Reporting.Result as Result
import Reporting.Annotation (Located)
import qualified AST.Module as Module
import qualified Parse.Module
import Data.Text (Text)
parse :: ElmVersion -> Text -> Result.Result () Syntax.Error (Module [UppercaseIdentifier] (ASTNS Located [UppercaseIdentifier] 'TopLevelNK))
parse elmVersion input =
Text.unpack input
|> Parse.parseModule elmVersion
toMaybe :: Result.Result a b c -> Maybe c
toMaybe res =
case res of
Result.Result _ (Result.Ok c) ->
Just c
_ ->
Nothing
toEither :: Result.Result a b c -> Either [b] c
toEither res =
case res of
Result.Result _ (Result.Ok c) ->
Right c
Result.Result _ (Result.Err b) ->
Left $ map extract b
import' :: ElmVersion -> Text -> Either [Syntax.Error] Module.UserImport
import' elmVersion text =
toEither $ Parse.parse (Text.unpack text) (Parse.Module.import' elmVersion)
-- TODO: can this be removed?
parseLiteral :: Text -> Result.Result () Syntax.Error LiteralValue
parseLiteral input =
Parse.parse (Text.unpack input) Parse.Literal.literal
| avh4/elm-format | elm-format-lib/src/ElmFormat/Parse.hs | bsd-3-clause | 1,519 | 0 | 12 | 308 | 473 | 256 | 217 | 41 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : ProcessMining.Model.PetriNet.Graphviz
-- Copyright : Mauro Taraborelli 2015
-- License : BSD3
--
-- Maintainer : maurotaraborelli@gmail.com
-- Stability : experimental
-- Portability : unknown
--
-- Algorithm to convert a Petri Net to dot language.
module ProcessMining.Model.PetriNet.Graphviz
(
toDot
)
where
import Prelude hiding ((<$>))
import Data.Text ()
import qualified Data.Text.Lazy ()
import Text.PrettyPrint.Leijen.Text
import ProcessMining.Model.PetriNet
-- | Convert a 'PetriNet' to dot language.
--
-- >>> :set -XOverloadedStrings
-- >>> :module + ProcessMining.Log.SimpleLog ProcessMining.Discovery.Alpha
-- >>> let a = "a" :: Activity
-- >>> let b = "b" :: Activity
-- >>> let c = "c" :: Activity
-- >>> let d = "d" :: Activity
-- >>> let e = "e" :: Activity
-- >>> let abcd = addActivities [a,b,c,d] emptyTrace
-- >>> let acbd = addActivities [a,c,b,d] emptyTrace
-- >>> let aed = addActivities [a,e,d] emptyTrace
-- >>> let l1 = addTraces [aed,acbd,acbd,abcd,abcd,abcd] emptySimpleLog
-- >>> let pn1 = alpha l1
-- >>> toDot pn1
-- digraph PetriNet {
-- rankdir=LR;
-- subgraph place {
-- node [shape=circle,fixedsize=true,width=1.5];
-- "input";
-- "output";
-- "p({a},{b,e})";
-- "p({a},{c,e})";
-- "p({b,e},{d})";
-- "p({c,e},{d})";
-- }
-- subgraph toTransitions {
-- node [shape=rect,fixedsize=true,width=1.5];
-- "a";
-- "b";
-- "c";
-- "d";
-- "e";
-- }
-- "input" -> "a";
-- "p({a},{b,e})" -> "b";
-- "p({a},{b,e})" -> "e";
-- "p({a},{c,e})" -> "c";
-- "p({a},{c,e})" -> "e";
-- "p({b,e},{d})" -> "d";
-- "p({c,e},{d})" -> "d";
-- "a" -> "p({a},{b,e})";
-- "a" -> "p({a},{c,e})";
-- "b" -> "p({b,e},{d})";
-- "c" -> "p({c,e},{d})";
-- "d" -> "output";
-- "e" -> "p({b,e},{d})";
-- "e" -> "p({c,e},{d})";
-- }
toDot :: PetriNet -> Doc
toDot pn = text "digraph PetriNet" <+> lbrace
<> nest 4 (line
<> text "rankdir=LR;"
<$> text "subgraph place" <+> lbrace
<> nest 4 (line
<> text "node [shape=circle,fixedsize=true,width=1.5];"
<$> vsep (map ((\p -> p <> semi) . dquotes . pretty) ps))
<$> rbrace)
<> nest 4 (line
<> text "subgraph toTransitions" <+> lbrace
<> nest 4 (line
<> text "node [shape=rect,fixedsize=true,width=1.5];"
<$> vsep (map ((\t -> t <> semi) . dquotes . pretty) ts))
<$> rbrace)
<> nest 4 (line
<> vsep (map ((\f -> f <> semi) . prettyFlowRelationDot) frs))
<$> rbrace
where
ps = toPlaces pn
ts = toTransitions pn
frs = toFlowRelations pn
prettyFlowRelationDot :: FlowRelation -> Doc
prettyFlowRelationDot (PlaceTransition p t) = dquotes (pretty p) <+> text "->" <+>
dquotes (pretty t)
prettyFlowRelationDot (TransitionPlace t p) = dquotes (pretty t) <+> text "->" <+>
dquotes (pretty p)
| maurotrb/processmining | src/ProcessMining/Model/PetriNet/Graphviz.hs | bsd-3-clause | 3,435 | 0 | 24 | 1,134 | 490 | 284 | 206 | 36 | 1 |
-- |
-- This module implements a service for interfacing with the Interactive
-- Brokers API.
module API.IB
( module API.IB.Connection
, module API.IB.Data
, module API.IB.Enum
, module Currency
)
where
import API.IB.Connection
import API.IB.Data
import API.IB.Enum
import Currency
----------------------------------------------------------------------------- | RobinKrom/interactive-brokers | library/API/IB.hs | bsd-3-clause | 378 | 0 | 5 | 58 | 58 | 41 | 17 | 9 | 0 |
{-# LANGUAGE BangPatterns, OverloadedStrings, TupleSections #-}
module Main where
import Control.Arrow (second)
import Control.Monad.Trans (liftIO)
import Control.Monad.Random (evalRandIO)
import Data.Default.Class (def)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.IO as TIO
import Network.HTTP.Types (status400)
import Network.Wai.Middleware.RequestLogger
import System.Directory (getDirectoryContents)
import Lib
import Web.Scotty
main :: IO ()
main = do
logger <- mkRequestLogger def{outputFormat = Apache FromHeader}
lcs <- langCorpuses "./data"
withNgrams logger (map (second digrams) lcs)
where
withNgrams logger (!ts) = scotty 3111 $ do
middleware logger
get "/" indexFile
get "/text/:lang/:length" (generateText ts)
indexFile :: ActionM ()
indexFile = file "./static/index.html"
generateText :: [(String, Digrams)] -> ActionM ()
generateText ts = do
len <- (min 1000) `fmap` param "length"
lang <- param "lang"::ActionM String
case lookup lang ts of
Nothing -> do
text (mconcat ["Language ", TL.pack lang, " not supported"])
status status400
(Just ngrams) -> do
r <- liftIO $ evalRandIO (fromDigrams len ngrams)
text (connect r)
connect :: [T.Text] -> TL.Text
connect = TL.fromChunks . (:[]) . T.intercalate (T.pack " ")
langCorpuses :: FilePath -> IO [(String, Corpus)]
langCorpuses d = listContents d >>=
mapM (\l -> makeCorpus l (d</>l))
where
makeCorpus :: String -> FilePath -> IO (String, Corpus)
makeCorpus lang dir = listContents dir >>=
mapM (TIO.readFile . (dir</>)) >>=
return . (lang,) . clean . T.concat
listContents :: FilePath -> IO [FilePath]
listContents dir =
filter (not . flip elem [".", ".."]) `fmap` getDirectoryContents dir
(</>) :: FilePath -> FilePath -> FilePath
p </> r = p ++ "/" ++ r
| pzel/slowotok | app/Main.hs | bsd-3-clause | 1,939 | 0 | 17 | 418 | 687 | 362 | 325 | 50 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
module Configurator.Dsl
where
import Control.Applicative hiding (many, (<|>))
import Control.Monad
import Data.Monoid ((<>))
import Data.Text (Text, pack, unpack)
import Prelude hiding (max, min)
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Language
import qualified Text.ParserCombinators.Parsec.Token as Token
import Types.Dynamic
parseTrigger :: Text -> Either String Exp
parseTrigger raw = convE $ parse topLevel "parse triggers" (unpack raw)
convE :: Either ParseError Exp -> Either String Exp
convE (Left e) = Left (show e)
convE (Right g) = Right g
languageDef :: LanguageDef st
languageDef =
emptyDef { Token.commentStart = ""
, Token.commentEnd = ""
, Token.commentLine = ""
, Token.identStart = letter
, Token.identLetter = alphaNum <|> char '.'
, Token.reservedNames = [ "last"
, "avg"
, "min"
, "max"
, "nodata"
, "change"
, "prev"
]
, Token.reservedOpNames = [ "&&", "||", "not", "=", ">", "<" ]
}
lexer :: Token.TokenParser st
lexer = Token.makeTokenParser languageDef
triggerIdentifier :: Parser Counter
triggerIdentifier = try $ do
i <- optionMaybe $ (Token.identifier lexer) <* char ':' -- parses an identifier
allpart <- (many alphaNum) `sepBy` (char '.')
case allpart of
[a,b,c] -> return $ Counter (pack <$> i) (pack a) (pack b) (pack c)
_ -> fail "not counter"
reserved :: String -> Parser ()
reserved = Token.reserved lexer -- parses a reserved name
reservedOp :: String -> Parser ()
reservedOp = Token.reservedOp lexer -- parses an operator
parens :: Parser Exp -> Parser Exp
parens = Token.parens lexer -- parses surrounding parenthesis:
semi :: Parser String
semi = Token.semi lexer -- parses a semicolon
integer :: Parser Int
integer = fromIntegral <$> Token.integer lexer
whiteSpace :: Parser ()
whiteSpace = Token.whiteSpace lexer -- parses whitespace
stringLiteral :: Parser Text
stringLiteral = pack <$> Token.stringLiteral lexer
expr :: Parser Exp
expr = whiteSpace >> topLevel
topLevel :: Parser Exp
topLevel = buildExpressionParser bOperators bTerm
bOperators :: [[Operator Char () Exp]]
bOperators = [ [Prefix (try $ whiteSpace >> reservedOp "not" >> return Not) ]
, [Infix (try $ whiteSpace >> reservedOp "&&" >> return And) AssocLeft]
, [Infix (try $ whiteSpace >> reservedOp "||" >> return Or) AssocLeft]
]
bTerm :: Parser Exp
bTerm = parens topLevel <|>
middleLevel <|>
nodata <|>
change
middleLevel :: Parser Exp
middleLevel = do
a <- funs
f <- relation
b <- funs
return $ f a b
relation :: Parser (DynExp -> DynExp -> Exp)
relation = (try $ whiteSpace *> reservedOp "=" *> return Equal)
<|> (try $ whiteSpace *> reservedOp ">" *> return More)
<|> (try $ whiteSpace *> reservedOp "<" *> return Less)
funs :: Parser DynExp
funs = (fun "min" Min) <|> (fun "max" Max) <|> (fun "last" Last) <|> (fun "avg" Avg) <|> prev <|> envval <|> val
fun :: String -> (Counter -> Period Int -> DynExp) -> Parser DynExp
fun i f = f <$> (reserved i *> char '(' *> triggerIdentifier <* char ',') <*> periodP <* char ')'
prev :: Parser DynExp
prev = Prev <$> (reserved "prev" *> char '(' *> triggerIdentifier <* char ')')
envval :: Parser DynExp
envval = EnvVal <$> triggerIdentifier
change :: Parser Exp
change = Change <$> (reserved "change" *> char '(' *> triggerIdentifier <* char ')')
nodata :: Parser Exp
nodata = NoData <$> (reserved "nodata" *> char '(' *> triggerIdentifier <* char ',') <*> periodP <* char ')'
val :: Parser DynExp
val = Val <$> try (number <|> str)
str :: Parser Dyn
str = to <$> stringLiteral
number :: Parser Dyn
number = do
a <- try $ optionMaybe (many1 digit)
p <- try $ optionMaybe (char '.')
b <- try $ optionMaybe (many1 digit)
c <- try $ optionMaybe quant
case (a, p, b, c) of
(Nothing, Just _ , Just x , _ ) -> return (to (read $ "0." <> x :: Double))
(Just x , Nothing, _ , Just q ) -> return (to (un q * (read x :: Int)))
(Just x , Nothing, _ , Nothing ) -> return (to (read x :: Int))
(Just x , Just _ , Nothing, _ ) -> return (to (read x :: Double))
(Just x , Just _ , Just y , _ ) -> return (to (read $ x <> "." <> y :: Double ))
_ -> fail "bad number"
periodP :: Parser (Period Int)
periodP = spaces *> choice [try time, try (Count <$> integer)] <* spaces
time :: Parser (Period Int)
time = do
i <- integer
q <- quant
return $ (*i) <$> q
quant :: Parser (Period Int)
quant = try (string "mk") *> (pure $ MicroSec 1 )
<|> try (string "ms") *> (pure $ MicroSec 1000)
<|> try (char 's' ) *> (pure $ MicroSec 1000000)
<|> try (char 'm' ) *> (pure $ MicroSec ( 60 * 1000000))
<|> try (char 'h' ) *> (pure $ MicroSec ( 60 * 60 * 1000000))
<|> try (char 'D' ) *> (pure $ MicroSec ( 24 * 60 * 60 * 1000000))
<|> try (char 'W' ) *> (pure $ MicroSec ( 7 * 24 * 60 * 60 * 1000000))
<|> try (string "MB") *> (pure $ Byte ( 1024 * 1024))
<|> try (char 'M' ) *> (pure $ MicroSec ( 30 * 24 * 60 * 60 * 1000000))
<|> try (char 'Y' ) *> (pure $ MicroSec ( 365 * 24 * 60 * 60 * 1000000))
<|> try (char 'B' ) *> (pure $ Byte 1)
<|> try (string "KB") *> (pure $ Byte 1024)
<|> try (string "GB") *> (pure $ Byte ( 1024 * 1024 * 1024))
<|> try (string "TB") *> (pure $ Byte ( 1024 * 1024 * 1024 * 1024))
| chemist/fixmon | src/Configurator/Dsl.hs | bsd-3-clause | 6,134 | 0 | 34 | 1,862 | 2,266 | 1,167 | 1,099 | 131 | 6 |
module Main where
import qualified CLI
import qualified API.Main as API
import System.Environment
import System.IO (hPutStrLn, stderr)
main :: IO ()
main = getArgs >>= chooseMode
chooseMode :: [String] -> IO ()
chooseMode [] = hPutStrLn stderr "Invalid arguments. Use --cli or --api"
chooseMode ("--cli":_) = CLI.main
chooseMode ("--api":_) = API.main
chooseMode _ = hPutStrLn stderr "Invalid arguments."
| robmcl4/Glug | app/Main.hs | bsd-3-clause | 410 | 0 | 7 | 63 | 132 | 73 | 59 | 12 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Language.R.Evaluate
-- Copyright : (c) 2010 David M. Rosenberg
-- License : BSD3
--
-- Maintainer : David Rosenberg <rosenbergdm@uchicago.edu>
-- Stability : experimental
-- Portability : portable
-- Created : 05/28/10
--
-- Description :
-- DESCRIPTION HERE.
-----------------------------------------------------------------------------
module Language.R.Evaluate where
import Language.R.Internal
| rosenbergdm/language-r | src/Language/R/Evaluate.hs | bsd-3-clause | 518 | 0 | 4 | 76 | 27 | 23 | 4 | 2 | 0 |
{-|
CRUD functionality for 'TagRel's.
-}
module Database.OrgMode.Internal.Query.TagRel where
import Database.Esqueleto
import qualified Database.Persist as P
import Database.OrgMode.Internal.Import
import Database.OrgMode.Internal.Types
-------------------------------------------------------------------------------
-- * Creation
{-|
Creates a 'TagRel' in the database from given data. This represents ownership of
a 'Tag' for a 'Heading'. See more in "OrgMode.Database.Internal.Types" for
details on ownership.
-}
add :: (MonadIO m)
=> Key Heading -- ^ Heading that has the tag
-> Key Tag -- ^ Tag to use
-> ReaderT SqlBackend m (Key TagRel) -- ^ ID of created 'TagRel'
add owner tag = P.insert (TagRel owner tag)
-------------------------------------------------------------------------------
-- * Deletion
{-|
Deletes 'TagRel's by list of IDs
-}
deleteByIds :: (MonadIO m)
=> [Key TagRel]
-> ReaderT SqlBackend m ()
deleteByIds relIds =
delete $
from $ \(rel) -> do
where_ $ in_ (rel ^. TagRelId) (valList relIds)
return ()
{-|
Deletes all 'TagRel's by given list of 'Heading' IDs.
-}
deleteByHeadings :: (MonadIO m) => [Key Heading] -> ReaderT SqlBackend m ()
deleteByHeadings hedIds =
delete $
from $ \(rel) -> do
where_ $ in_ (rel ^. TagRelHeading) (valList hedIds)
return ()
| rzetterberg/orgmode-sql | lib/Database/OrgMode/Internal/Query/TagRel.hs | bsd-3-clause | 1,478 | 0 | 12 | 376 | 291 | 158 | 133 | 24 | 1 |
{-# LANGUAGE CPP #-}
module Happstack.Server.Internal.Socket
( acceptLite
, sockAddrToPeer
) where
import Data.List (intersperse)
import Data.Word (Word32)
import qualified Network.Socket as S
( Socket
, PortNumber()
, SockAddr(..)
, HostName
, accept
)
import Numeric (showHex)
type HostAddress = Word32
type HostAddress6 = (Word32, Word32, Word32, Word32)
-- | Converts a HostAddress to a String in dot-decimal notation
showHostAddress :: HostAddress -> String
showHostAddress num = concat [show q1, ".", show q2, ".", show q3, ".", show q4]
where (num',q1) = num `quotRem` 256
(num'',q2) = num' `quotRem` 256
(num''',q3) = num'' `quotRem` 256
(_,q4) = num''' `quotRem` 256
-- | Converts a IPv6 HostAddress6 to standard hex notation
showHostAddress6 :: HostAddress6 -> String
showHostAddress6 (a,b,c,d) =
(concat . intersperse ":" . map (flip showHex ""))
[p1,p2,p3,p4,p5,p6,p7,p8]
where (a',p2) = a `quotRem` 65536
(_,p1) = a' `quotRem` 65536
(b',p4) = b `quotRem` 65536
(_,p3) = b' `quotRem` 65536
(c',p6) = c `quotRem` 65536
(_,p5) = c' `quotRem` 65536
(d',p8) = d `quotRem` 65536
(_,p7) = d' `quotRem` 65536
-- | alternative implementation of accept to work around EAI_AGAIN errors
acceptLite :: S.Socket -> IO (S.Socket, S.HostName, S.PortNumber)
acceptLite sock = do
(sock', addr) <- S.accept sock
let (peer, port) = sockAddrToPeer addr
return (sock', peer, port)
sockAddrToPeer :: S.SockAddr -> (S.HostName, S.PortNumber)
sockAddrToPeer addr =
case addr of
(S.SockAddrInet p ha) -> (showHostAddress ha, p)
(S.SockAddrInet6 p _ ha _) -> (showHostAddress6 ha, p)
_ -> error "sockAddrToPeer: Unsupported socket type"
| Happstack/happstack-server | src/Happstack/Server/Internal/Socket.hs | bsd-3-clause | 1,806 | 0 | 10 | 425 | 643 | 374 | 269 | 44 | 3 |
{-# LANGUAGE CPP #-}
-- | Ways for the client to use player input via UI to produce server
-- requests, based on the client's view (visualized for the player)
-- of the game state.
module Game.LambdaHack.Client.UI
( -- * Client UI monad
MonadClientUI
-- * Assorted UI operations
, queryUI, pongUI
, displayRespUpdAtomicUI, displayRespSfxAtomicUI
-- * Startup
, srtFrontend, KeyKind, SessionUI
-- * Operations exposed for LoopClient
, ColorMode(..), displayMore, msgAdd
#ifdef EXPOSE_INTERNAL
-- * Internal operations
, humanCommand
#endif
) where
import Control.Exception.Assert.Sugar
import Control.Monad
import Data.Either.Compat
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import qualified Data.Map.Strict as M
import Data.Maybe
import Game.LambdaHack.Atomic
import qualified Game.LambdaHack.Client.Key as K
import Game.LambdaHack.Client.MonadClient
import Game.LambdaHack.Client.State
import Game.LambdaHack.Client.UI.Content.KeyKind
import Game.LambdaHack.Client.UI.DisplayAtomicClient
import Game.LambdaHack.Client.UI.HandleHumanClient
import Game.LambdaHack.Client.UI.HumanCmd
import Game.LambdaHack.Client.UI.KeyBindings
import Game.LambdaHack.Client.UI.MonadClientUI
import Game.LambdaHack.Client.UI.MsgClient
import Game.LambdaHack.Client.UI.StartupFrontendClient
import Game.LambdaHack.Client.UI.WidgetClient
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.MonadStateRead
import Game.LambdaHack.Common.Msg
import Game.LambdaHack.Common.Request
import Game.LambdaHack.Common.State
import Game.LambdaHack.Content.ModeKind
-- | Handle the move of a UI player.
queryUI :: MonadClientUI m => m RequestUI
queryUI = do
side <- getsClient sside
fact <- getsState $ (EM.! side) . sfactionD
let (leader, mtgt) = fromMaybe (assert `failure` fact) $ gleader fact
req <- humanCommand
leader2 <- getLeaderUI
mtgt2 <- getsClient $ fmap fst . EM.lookup leader2 . stargetD
if (leader2, mtgt2) /= (leader, mtgt)
then return $! ReqUILeader leader2 mtgt2 req
else return $! req
-- | Let the human player issue commands until any command takes time.
humanCommand :: forall m. MonadClientUI m => m RequestUI
humanCommand = do
-- For human UI we invalidate whole @sbfsD@ at the start of each
-- UI player input that start a player move, which is an overkill,
-- but doesn't slow screensavers, because they are UI,
-- but not human.
modifyClient $ \cli -> cli {sbfsD = EM.empty, slastLost = ES.empty}
let loop :: Either Bool (Maybe Bool, Overlay) -> m RequestUI
loop mover = do
(lastBlank, over) <- case mover of
Left b -> do
-- Display current state and keys if no slideshow or if interrupted.
keys <- if b then describeMainKeys else return ""
sli <- promptToSlideshow keys
return (Nothing, head . snd $! slideshow sli)
Right bLast ->
-- (Re-)display the last slide while waiting for the next key.
return bLast
(seqCurrent, seqPrevious, k) <- getsClient slastRecord
case k of
0 -> do
let slastRecord = ([], seqCurrent, 0)
modifyClient $ \cli -> cli {slastRecord}
_ -> do
let slastRecord = ([], seqCurrent ++ seqPrevious, k - 1)
modifyClient $ \cli -> cli {slastRecord}
lastPlay <- getsClient slastPlay
km <- getKeyOverlayCommand lastBlank over
-- Messages shown, so update history and reset current report.
when (null lastPlay) recordHistory
abortOrCmd <- do
-- Look up the key.
Binding{bcmdMap} <- askBinding
case M.lookup km{K.pointer=Nothing} bcmdMap of
Just (_, _, cmd) -> do
-- Query and clear the last command key.
modifyClient $ \cli -> cli
{swaitTimes = if swaitTimes cli > 0
then - swaitTimes cli
else 0}
escAI <- getsClient sescAI
case escAI of
EscAIStarted -> do
modifyClient $ \cli -> cli {sescAI = EscAIMenu}
cmdHumanSem cmd
EscAIMenu -> do
unless (km `elem` [K.escKM, K.returnKM]) $
modifyClient $ \cli -> cli {sescAI = EscAIExited}
cmdHumanSem cmd
_ -> do
modifyClient $ \cli -> cli {sescAI = EscAINothing}
stgtMode <- getsClient stgtMode
if km == K.escKM && isNothing stgtMode && isRight mover
then cmdHumanSem Clear
else cmdHumanSem cmd
Nothing -> let msgKey = "unknown command <" <> K.showKM km <> ">"
in failWith msgKey
-- The command was failed or successful and if the latter,
-- possibly took some time.
case abortOrCmd of
Right cmdS ->
-- Exit the loop and let other actors act. No next key needed
-- and no slides could have been generated.
return cmdS
Left slides -> do
-- If no time taken, rinse and repeat.
-- Analyse the obtained slides.
let (onBlank, sli) = slideshow slides
mLast <- case sli of
[] -> do
stgtMode <- getsClient stgtMode
return $ Left $ isJust stgtMode || km == K.escKM
[sLast] ->
-- Avoid displaying the single slide twice.
return $ Right (onBlank, sLast)
_ -> do
-- Show, one by one, all slides, awaiting confirmation
-- for all but the last one (which is displayed twice, BTW).
-- Note: the code that generates the slides is responsible
-- for inserting the @more@ prompt.
go <- getInitConfirms ColorFull [km] slides
return $! if go then Right (onBlank, last sli) else Left True
loop mLast
loop $ Left False
-- | Client signals to the server that it's still online, flushes frames
-- (if needed) and sends some extra info.
pongUI :: MonadClientUI m => m RequestUI
pongUI = do
escPressed <- tryTakeMVarSescMVar
side <- getsClient sside
fact <- getsState $ (EM.! side) . sfactionD
let pong ats = return $ ReqUIPong ats
underAI = isAIFact fact
if escPressed && underAI && fleaderMode (gplayer fact) /= LeaderNull then do
modifyClient $ \cli -> cli {sescAI = EscAIStarted}
-- Ask server to turn off AI for the faction's leader.
let atomicCmd = UpdAtomic $ UpdAutoFaction side False
pong [atomicCmd]
else do
-- Respond to the server normally, perhaps pinging the frontend, too.
when underAI syncFrames
pong []
| beni55/LambdaHack | Game/LambdaHack/Client/UI.hs | bsd-3-clause | 6,828 | 5 | 31 | 1,989 | 1,464 | 793 | 671 | -1 | -1 |
module System.Build.Data
(
module System.Build.Data.KeyPValue
, module System.Build.Data.SourceRelease
) where
import System.Build.Data.KeyPValue
import System.Build.Data.SourceRelease
| tonymorris/lastik | System/Build/Data.hs | bsd-3-clause | 190 | 0 | 5 | 19 | 39 | 28 | 11 | 6 | 0 |
{-# LANGUAGE PatternGuards #-}
module Idris.DataOpts where
-- Forcing, detagging and collapsing
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import Idris.Core.TT
import Control.Applicative
import Data.List
import Data.Maybe
import Debug.Trace
class Optimisable term where
applyOpts :: term -> Idris term
instance (Optimisable a, Optimisable b) => Optimisable (a, b) where
applyOpts (x, y) = (,) <$> applyOpts x <*> applyOpts y
instance (Optimisable a, Optimisable b) => Optimisable (vs, a, b) where
applyOpts (v, x, y) = (,,) v <$> applyOpts x <*> applyOpts y
instance Optimisable a => Optimisable [a] where
applyOpts = mapM applyOpts
instance Optimisable a => Optimisable (Either a (a, a)) where
applyOpts (Left t) = Left <$> applyOpts t
applyOpts (Right t) = Right <$> applyOpts t
-- Raw is for compile time optimisation (before type checking)
-- Term is for run time optimisation (after type checking, collapsing allowed)
-- Compile time: no collapsing
instance Optimisable Raw where
applyOpts t@(RApp f a)
| (Var n, args) <- raw_unapply t -- MAGIC HERE
= raw_apply (Var n) <$> mapM applyOpts args
| otherwise = RApp <$> applyOpts f <*> applyOpts a
applyOpts (RBind n b t) = RBind n <$> applyOpts b <*> applyOpts t
applyOpts (RForce t) = applyOpts t
applyOpts t = return t
-- Erase types (makes ibc smaller, and we don't need them)
instance Optimisable (Binder (TT Name)) where
applyOpts (Let t v) = Let <$> return Erased <*> applyOpts v
applyOpts b = return (b { binderTy = Erased })
instance Optimisable (Binder Raw) where
applyOpts b = do t' <- applyOpts (binderTy b)
return (b { binderTy = t' })
-- Run-time: do everything
prel = [txt "Nat", txt "Prelude"]
instance Optimisable (TT Name) where
applyOpts (P _ (NS (UN fn) mod) _)
| fn == txt "plus" && mod == prel
= return (P Ref (sUN "prim__addBigInt") Erased)
applyOpts (P _ (NS (UN fn) mod) _)
| fn == txt "mult" && mod == prel
= return (P Ref (sUN "prim__mulBigInt") Erased)
applyOpts (App (P _ (NS (UN fn) mod) _) x)
| fn == txt "fromIntegerNat" && mod == prel
= applyOpts x
applyOpts (P _ (NS (UN fn) mod) _)
| fn == txt "fromIntegerNat" && mod == prel
= return (App (P Ref (sNS (sUN "id") ["Basics","Prelude"]) Erased) Erased)
applyOpts (P _ (NS (UN fn) mod) _)
| fn == txt "toIntegerNat" && mod == prel
= return (App (P Ref (sNS (sUN "id") ["Basics","Prelude"]) Erased) Erased)
applyOpts c@(P (DCon t arity uniq) n _)
= return $ applyDataOptRT n t arity uniq []
applyOpts t@(App f a)
| (c@(P (DCon t arity uniq) n _), args) <- unApply t
= applyDataOptRT n t arity uniq <$> mapM applyOpts args
| otherwise = App <$> applyOpts f <*> applyOpts a
applyOpts (Bind n b t) = Bind n <$> applyOpts b <*> applyOpts t
applyOpts (Proj t i) = Proj <$> applyOpts t <*> pure i
applyOpts t = return t
-- Need to saturate arguments first to ensure that optimisation happens uniformly
applyDataOptRT :: Name -> Int -> Int -> Bool -> [Term] -> Term
applyDataOptRT n tag arity uniq args
| length args == arity = doOpts n args
| otherwise = let extra = satArgs (arity - length args)
tm = doOpts n (args ++ map (\n -> P Bound n Erased) extra)
in bind extra tm
where
satArgs n = map (\i -> sMN i "sat") [1..n]
bind [] tm = tm
bind (n:ns) tm = Bind n (Lam Erased) (pToV n (bind ns tm))
-- Nat special cases
-- TODO: Would be nice if this was configurable in idris source!
-- Issue #1597 https://github.com/idris-lang/Idris-dev/issues/1597
doOpts (NS (UN z) [nat, prelude]) []
| z == txt "Z" && nat == txt "Nat" && prelude == txt "Prelude"
= Constant (BI 0)
doOpts (NS (UN s) [nat, prelude]) [k]
| s == txt "S" && nat == txt "Nat" && prelude == txt "Prelude"
= App (App (P Ref (sUN "prim__addBigInt") Erased) k) (Constant (BI 1))
doOpts n args = mkApp (P (DCon tag arity uniq) n Erased) args
| andyarvanitis/Idris-dev | src/Idris/DataOpts.hs | bsd-3-clause | 4,137 | 1 | 16 | 1,083 | 1,684 | 832 | 852 | 76 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Turtle.Shell
import Turtle.Line
import Turtle.Prelude hiding (die)
import Data.Aeson
import Data.Text (unpack, pack, Text)
import System.Directory (getAppUserDataDirectory, getDirectoryContents)
import System.FilePath ((</>), dropExtension)
import qualified Data.ByteString.Lazy as BS
import Data.Monoid ((<>))
import Data.List
import Control.Applicative
import Control.Monad
import Data.String
import GHC.IO.Exception (ExitCode(..))
import System.Exit (die)
data Packages = Packages {
patched :: [Text],
vanilla :: [Text]
} deriving (Show, Eq, Ord)
instance FromJSON Packages where
parseJSON (Object v) = Packages <$> v.: "patched" <*> v.: "vanilla"
parseJSON _ = empty
parsePackagesFile :: FilePath -> IO (Maybe Packages)
parsePackagesFile fname = do
contents <- BS.readFile fname
let packages = decode contents
patched' <- patchedLibraries
return $ fmap (\p -> p { patched = patched' }) packages
packagesFilePath :: IO FilePath
packagesFilePath = (</> "patches" </> "packages.json") <$> getAppUserDataDirectory "etlas"
patchedLibraries :: IO [Text]
patchedLibraries = do
patchesDir <- fmap (</> "patches" </> "patches") $ getAppUserDataDirectory "etlas"
packages <- fmap ( nub
. map dropExtension
. filter (\p -> p `notElem` ["",".",".."]))
$ getDirectoryContents patchesDir
return $ map pack packages
buildPackage :: Text -> IO ()
buildPackage pkg = do
let outString = "Installing package " ++ unpack pkg ++ "..."
lenOutString = length outString
dashes = replicate lenOutString '-'
putStrLn dashes
putStrLn outString
putStrLn dashes
sh $ procExitOnError "etlas" ["install", pkg] empty
verifyJar :: IO ()
verifyJar = sh verifyScript
procExitOnError :: Text -> [Text] -> Shell Line -> Shell ()
procExitOnError prog args shellm = do
exitCode <- proc prog args shellm
case exitCode of
ExitFailure code -> liftIO $ die ("ExitCode " ++ show code)
ExitSuccess -> return ()
verifyScript :: Shell ()
verifyScript = do
echo "Building the Verify script..."
let verifyScriptPath = "utils" </> "class-verifier"
verifyScriptCmd = verifyScriptPath </> "Verify.java"
testVerifyPath = "tests" </> "verify"
outPath = testVerifyPath </> "build"
outJar = outPath </> "Out.jar"
mainSource = testVerifyPath </> "Main.hs"
procExitOnError "javac" [pack verifyScriptCmd] mempty
echo "Verify.class built successfully."
echo "Compiling a simple program..."
echo "=== Eta Compiler Output ==="
exists <- testdir (fromString outPath)
when (not exists) $ mkdir (fromString outPath)
procExitOnError "eta" ["-fforce-recomp", "-o", pack outJar, pack mainSource] mempty
echo "=== ==="
echo "Compiled succesfully."
echo "Verifying the bytecode of compiled program..."
echo "=== Verify Script Output ==="
procExitOnError "java" ["-cp", pack verifyScriptPath, "Verify", pack outJar] mempty
echo "=== ==="
echo "Bytecode looking good."
echo "Running the simple program..."
echo "=== Simple Program Output ==="
procExitOnError "java" ["-cp", pack outJar, "eta.main"] mempty
echo "=== ==="
echo "Done! Everything's looking good."
main :: IO ()
main = do
verifyJar
let vmUpdateCmd = "etlas update"
_ <- shell vmUpdateCmd ""
epmPkgs <- packagesFilePath
pkg <- parsePackagesFile epmPkgs
case pkg of
Nothing -> die "Problem parsing your packages.json file"
Just pkg' -> do
let packages = (patched pkg') <> (vanilla pkg')
mapM_ buildPackage packages
| AlexeyRaga/eta | tests/packages/Test.hs | bsd-3-clause | 3,681 | 0 | 17 | 776 | 1,072 | 533 | 539 | 97 | 2 |
module DayOfWeek where
data DayOfWeek =
Mon | Tue | Weds | Thu | Fri | Sat | Sun
deriving (Ord, Show, Eq)
check' :: Ord a => a -> a -> Bool
check' a a' = a == a' | brodyberg/Notes | ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/DayOfWeek.hs | mit | 168 | 0 | 7 | 46 | 78 | 44 | 34 | 6 | 1 |
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
{-# LANGUAGE LambdaCase #-}
module CoreS.ASTUnitypeUtils where
import CoreS.ASTUnitype
import qualified CoreS.AST as C
import Data.Maybe (maybeToList)
import Data.Set (fromList, union, intersection)
-- (`dependsOn y x` is `True` if `y` depends on `x`
--
-- if `dependsOn y x == False` then `y; x;` and `x; y;`
-- should be semantically identical
dependsOn :: AST -> AST -> Bool
dependsOn a1 a2 = (impure a1) || (impure a2) ||
(not $ null $ (fromList $ changesIds a1) `intersection` ((fromList $ changesIds a2) `union` (fromList $ changesIds a2))) ||
(not $ null $ (fromList $ usesIds a1) `intersection` (fromList $ changesIds a2))
usesIds :: AST -> [C.Ident]
usesIds = \case
LVName n -> C._nmIds n
LVArray a as -> um $ a:as
InitExpr a -> usesIds a
InitArr as -> um as
ELit a -> usesIds a
EVar a -> usesIds a
ECast _ a -> usesIds a
ECond a1 a2 a3 -> um [a1,a2,a3]
EAssign a1 a2 -> um [a1,a2]
EOAssign a1 _ a2 -> um [a1,a2]
ENum _ a1 a2 -> um [a1,a2]
ECmp _ a1 a2 -> um [a1,a2]
ELog _ a1 a2 -> um [a1,a2]
ENot a -> usesIds a
EStep _ a -> usesIds a
EBCompl a -> usesIds a
EPlus a -> usesIds a
EMinus a -> usesIds a
EMApp n as -> (C._nmIds n) ++ (um as) -- should the identifier parts of the name be in here?
EArrNew _ as _ -> um as
EArrNewI _ _ as -> um as
EInstNew n as -> (C._nmIds n) ++ (um as)
ESysOut a -> usesIds a
Block as -> um as
SExpr a -> usesIds a
SVars d -> concat $ map
(\a -> (C._vdiIdent $ C._vdVDI a):(concat $ maybeToList $ (usesIds . toUnitype) <$> (C._vdVInit a)))
(C._tvdVDecls d)
SReturn a -> usesIds a
SIf a1 a2 -> um [a1,a2]
SIfElse a1 a2 a3 -> um [a1,a2,a3]
SWhile a1 a2 -> um [a1,a2]
SDo a1 a2 -> um [a1,a2]
SForB ma1 ma2 mas a -> um $ a : maybeToList ma1 ++
maybeToList ma2 ++
(concat . maybeToList) mas
SForE _ id a1 a2 -> id : um [a1,a2]
SSwitch a as -> um $ a:as
SwitchBlock l as -> undefined -- switchLabels contains expressions, which may include names, maybe just find the expression and convert to unitype?
SwitchCase a -> usesIds a
FIVars d -> concat $ map
(\a -> (C._vdiIdent $ C._vdVDI a):(concat $ maybeToList $ (usesIds . toUnitype) <$> (C._vdVInit a)))
(C._tvdVDecls d)
FIExprs as -> um as
--(MethodDecl _ id fps as -> id : ((map (C._vdiIdent . C._fpVDI) fps) ++ um as)
--(CompilationUnit as1 as2) -> um $ as1 ++ as2
ClassTypeDecl a -> usesIds a
--(ClassDecl id a -> id : usesIds a
ClassBody as -> um as
MemberDecl a -> usesIds a
_ -> []
where um x = concat $ map usesIds x
changesIds :: AST -> [C.Ident]
changesIds = \case
LVName n -> C._nmIds n -- find everything that could acctually reach this, should those be replaced by usesId?
LVArray a as -> (usesIds a) ++ (cm $ as) -- should this be uses? also see above
InitExpr a -> changesIds a
InitArr as -> cm as
ECast _ a -> changesIds a
ECond a1 a2 a3 -> cm [a1,a2,a3]
EAssign a1 a2 -> cm [a1,a2] -- reaches LValue
EOAssign a1 _ a2 -> cm [a1,a2] -- reaches LValue
ENum _ a1 a2 -> cm [a1,a2]
ECmp _ a1 a2 -> cm [a1,a2]
ELog _ a1 a2 -> cm [a1,a2]
ENot a -> changesIds a
EStep _ a -> changesIds a
EBCompl a -> changesIds a
EPlus a -> changesIds a
EMinus a -> changesIds a
EMApp _ as -> cm as
EArrNew _ as _ -> cm as
EArrNewI _ _ as -> cm as
EInstNew n as -> (C._nmIds n) ++ (cm as)
ESysOut a -> changesIds a
Block as -> cm as
SExpr a -> changesIds a
SVars d -> concat $ map
(\a -> (C._vdiIdent $ C._vdVDI a):(concat $ maybeToList $ (changesIds . toUnitype) <$> (C._vdVInit a)))
(C._tvdVDecls d)
SReturn a -> changesIds a
SIf a1 a2 -> cm [a1,a2]
SIfElse a1 a2 a3 -> cm [a1,a2,a3]
SWhile a1 a2 -> cm [a1,a2]
SDo a1 a2 -> cm [a1,a2]
SForB ma1 ma2 mas a -> cm $ a : maybeToList ma1 ++
maybeToList ma2 ++
(concat . maybeToList) mas
SForE _ id a1 a2 -> id : cm [a1,a2]
SSwitch a as -> cm $ a:as
SwitchBlock l as -> undefined -- switchLabels contains expressions, which may include names, maybe just find the expression and convert to unitype?
SwitchCase a -> changesIds a
FIVars d -> concat $ map
(\a -> (C._vdiIdent $ C._vdVDI a):(concat $ maybeToList $ (changesIds . toUnitype) <$> (C._vdVInit a)))
(C._tvdVDecls d)
FIExprs as -> cm as
--(MethodDecl _ id fps as -> id : ((map (C._vdiIdent . C._fpVDI) fps) ++ cm as)
--(CompilationUnit as1 as2) -> cm $ as1 ++ as2
ClassTypeDecl a -> changesIds a
--(ClassDecl id a -> id : changesIds a
ClassBody as -> cm as
MemberDecl a -> changesIds a
_ -> []
where cm x = concat $ map changesIds x
nbrOfStatements :: AST -> Int
nbrOfStatements a = 1 + case a of
LVArray a as -> sm $ a:as
InitExpr a -> nbrOfStatements a
InitArr as -> sm as
ELit a -> nbrOfStatements a
EVar a -> nbrOfStatements a
ECast _ a -> nbrOfStatements a
ECond a b c -> sm [a, b, c]
EAssign a b -> sm [a, b]
EOAssign a _ b -> sm [a, b]
ENum _ a b -> sm [a, b]
ECmp _ a b -> sm [a, b]
ELog _ a b -> sm [a, b]
ENot a -> nbrOfStatements a
EStep _ a -> nbrOfStatements a
EBCompl a -> nbrOfStatements a
EPlus a -> nbrOfStatements a
EMinus a -> nbrOfStatements a
EMApp _ as -> sm as
EInstNew _ as -> sm as
EArrNew _ as _ -> sm as
EArrNewI _ _ as -> sm as
ESysOut a -> nbrOfStatements a
Block as -> sm as
SExpr a -> nbrOfStatements a
SReturn a -> nbrOfStatements a
SIf a b -> sm [a, b]
SIfElse a b c -> sm [a, b, c]
SWhile a b -> sm [a, b]
SDo a b -> sm [a, b]
SForB mas mbs mcs d -> sm $ d : maybeToList mas ++
maybeToList mbs ++
(concat . maybeToList) mcs
SForE _ _ a b -> sm [a, b]
SSwitch a bs -> sm $ a:bs
SwitchBlock _ as -> sm as
SwitchCase a -> nbrOfStatements a
FIExprs as -> sm as
MethodDecl _ _ _ as -> sm as
CompilationUnit is as -> sm $ is ++ as
ClassTypeDecl a -> nbrOfStatements a
ClassDecl _ a -> nbrOfStatements a
ClassBody as -> sm as
MemberDecl a -> nbrOfStatements a
_ -> 0
where sm x = sum $ map nbrOfStatements x
impure :: AST -> Bool
impure = \case
SContinue -> True
SBreak -> True
LVArray a as -> ai $ a:as
InitExpr a -> impure a
InitArr as -> ai as
ECast _ a -> impure a
ECond a1 a2 a3 -> ai [a1,a2,a3]
EAssign a1 a2 -> ai [a1,a2] -- reaches LValue
EOAssign a1 _ a2 -> ai [a1,a2] -- reaches LValue
ENum _ a1 a2 -> ai [a1,a2]
ECmp _ a1 a2 -> ai [a1,a2]
ELog _ a1 a2 -> ai [a1,a2]
ENot a -> impure a
EStep _ a -> impure a
EBCompl a -> impure a
EPlus a -> impure a
EMinus a -> impure a
EMApp _ as -> True
EArrNew _ as _ -> ai as
EArrNewI _ _ as -> ai as
EInstNew n as -> ai as
ESysOut a -> True
Block as -> ai as
SExpr a -> impure a
SVars d -> or $ concat $ map
(\a -> (maybeToList $ fmap (impure . toUnitype) (C._vdVInit a)))
(C._tvdVDecls d)
SReturn a -> impure a
SIf a1 a2 -> ai [a1,a2]
SIfElse a1 a2 a3 -> ai [a1,a2,a3]
SWhile a1 a2 -> ai [a1,a2]
SDo a1 a2 -> ai [a1,a2]
SForB ma1 ma2 mas a -> ai $ a : maybeToList ma1 ++
maybeToList ma2 ++
(concat . maybeToList) mas
SForE _ _ a1 a2 -> ai [a1,a2]
SSwitch a as -> ai $ a:as
SwitchBlock l as -> undefined -- switchLabels contains expressions, which may include names, maybe just find the expression and convert to unitype?
SwitchCase a -> impure a
FIVars d -> or $ concat $ map
(\a -> (maybeToList $ fmap (impure . toUnitype) (C._vdVInit a)))
(C._tvdVDecls d)
FIExprs as -> ai as
--(MethodDecl _ id fps as -> id : ((map (C._vdiIdent . C._fpVDI) fps) ++ cm as)
--(CompilationUnit as1 as2) -> cm $ as1 ++ as2
ClassTypeDecl a -> impure a
--(ClassDecl id a -> id : changesIds a
ClassBody as -> ai as
MemberDecl a -> impure a
_ -> False
where ai x = any impure x
| Centril/DATX02-17-26 | libsrc/CoreS/ASTUnitypeUtils.hs | gpl-2.0 | 10,697 | 0 | 17 | 4,320 | 3,473 | 1,670 | 1,803 | 207 | 42 |
{-# LANGUAGE DeriveDataTypeable #-}
module Arbre.Path
(
SourcePath(..),
Path(..)
)
where
import Data.Typeable
import Data.Data
import Data.Map as M
import Arbre.Expressions
data SourcePath = SourcePath String Path
data Path = Path [Literal]
-- resolve :: LiteralProgram -> Path ->
| blanu/arbre | Arbre/Path.hs | gpl-2.0 | 290 | 0 | 7 | 48 | 69 | 44 | 25 | 11 | 0 |
import Control.Monad (forM_)
import Data.List
import Test.HUnit
import qualified Portage.Dependency as P
import qualified Portage.Dependency.Normalize as PN
import qualified Portage.PackageId as P
import qualified Portage.Use as P
import qualified RunTests as RT
tests :: Test
tests = TestList [ TestLabel "normalize_in_use_and_top" test_normalize_in_use_and_top
]
pnm :: P.PackageName
pnm = P.mkPackageName "dev-haskell" "mtl"
pnp :: P.PackageName
pnp = P.mkPackageName "dev-haskell" "parsec"
pnq :: P.PackageName
pnq = P.mkPackageName "dev-haskell" "quickcheck"
def_attr :: P.DAttr
def_attr = P.DAttr P.AnySlot []
p_v :: [Int] -> P.Version
p_v v = P.Version { P.versionNumber = v
, P.versionChar = Nothing
, P.versionSuffix = []
, P.versionRevision = 0
}
d_all :: [P.Dependency] -> P.Dependency
d_all = P.DependAllOf
d_any :: [P.Dependency] -> P.Dependency
d_any = P.DependAnyOf
d_ge :: P.PackageName -> [Int] -> P.Dependency
d_ge pn v = P.DependAtom $ P.Atom pn
(P.DRange (P.NonstrictLB $ p_v v) P.InfinityB)
def_attr
d_p :: String -> P.Dependency
d_p pn = P.DependAtom $ P.Atom (P.mkPackageName "c" pn)
(P.DRange P.ZeroB P.InfinityB)
def_attr
d_use :: String -> P.Dependency -> P.Dependency
d_use u d = P.mkUseDependency (True, P.Use u) d
d_nuse :: String -> P.Dependency -> P.Dependency
d_nuse u d = P.mkUseDependency (False, P.Use u) d
test_normalize_in_use_and_top :: Test
test_normalize_in_use_and_top = TestCase $ do
let deps = [ ( d_all [ d_ge pnm [1,0]
, d_use "foo" (d_all [ d_ge pnm [1,0] -- duplicate
, d_ge pnp [2,1]
])
]
, [ ">=dev-haskell/mtl-1.0"
, "foo? ( >=dev-haskell/parsec-2.1 )"
]
)
, ( d_all [ d_ge pnm [1,0]
, d_use "foo" (d_any [ d_ge pnm [1,0] -- already satisfied
, d_ge pnp [2,1]
])
]
, [ ">=dev-haskell/mtl-1.0" ]
)
, ( d_any [ d_all [ d_ge pnm [1,0] -- common subdep
, d_ge pnq [1,2]
]
, d_all [ d_ge pnm [1,0]
, d_ge pnp [3,1]
]
]
, [ ">=dev-haskell/mtl-1.0"
, "|| ( >=dev-haskell/parsec-3.1"
, " >=dev-haskell/quickcheck-1.2 )"
]
)
, ( d_all [ d_use "foo" $ d_use "bar" $ d_ge pnm [1,0]
, d_use "bar" $ d_use "foo" $ d_ge pnm [1,0]
]
, [ "bar? ( foo? ( >=dev-haskell/mtl-1.0 ) )" ]
)
, ( d_all [ d_use "foo" $ d_ge pnm [1,0]
, d_use "foo" $ d_ge pnp [3,1]
]
, [ "foo? ( >=dev-haskell/mtl-1.0"
, " >=dev-haskell/parsec-3.1 )"
]
)
, ( d_all [ d_use "a" $ d_use "b" $ d_ge pnm [1,0]
, d_nuse "a" $ d_use "b" $ d_ge pnm [1,0]
]
, [ "b? ( >=dev-haskell/mtl-1.0 )"
]
)
-- 'test?' is special
, ( d_use "a" $ d_use "test" $ d_ge pnm [1,0]
, [ "test? ( a? ( >=dev-haskell/mtl-1.0 ) )"
]
)
, -- pop context for complementary depends, like
-- a? ( x y a ) !a? ( x y na )
-- leads to
-- x y a? ( a ) !a? ( na )
( d_all [ d_use "a" $ d_all $ map d_p [ "x", "y", "a" ]
, d_nuse "a" $ d_all $ map d_p [ "x", "y", "na" ]
]
, [ "c/x"
, "c/y"
, "a? ( c/a )"
, "!a? ( c/na )"
]
)
, -- push stricter context into less strict
( d_all [ d_ge pnm [2,0]
, d_use "a" $ d_ge pnm [1,0]
]
,
[ ">=dev-haskell/mtl-2.0" ]
)
, -- propagate use guarded depend into deeply nested one
( d_all [ d_use "a" $ d_all $ map d_p [ "x" ]
, d_use "test" $ d_use "a" $ d_all $ map d_p [ "x", "t" ]
]
, [ "test? ( a? ( c/t ) )"
, "a? ( c/x )"
]
)
, -- lift nested use context for complementary depends
-- a? ( b? ( y ) ) b? ( x )
( d_all [ d_use "a" $ d_use "b" $ d_all $ map d_p [ "x", "y" ]
, d_nuse "a" $ d_use "b" $ d_p "x"
]
, [ "a? ( b? ( c/y ) )"
, "b? ( c/x )"
]
)
, -- more advanced lift of complementary deps
-- a? ( b? ( x y ) )
-- !a? ( b? ( y z ) )
( d_all [ d_use "a" $ d_use "b" $ d_all $ map d_p [ "x", "y" ]
, d_nuse "a" $ d_use "b" $ d_all $ map d_p [ "y", "z" ]
]
, [ "a? ( b? ( c/x ) )"
, "!a? ( b? ( c/z ) )"
, "b? ( c/y )"
]
)
, -- completely expanded set of USEs
-- a? ( b? ( c? ( x y z ) )
-- a? ( b? ( !c? ( x y ) )
-- a? ( !b? ( c? ( x z ) )
-- a? ( !b? ( !c? ( x ) )
--
-- !a? ( b? ( c? ( y z ) )
-- !a? ( b? ( !c? ( y ) )
-- !a? ( !b? ( c? ( z ) )
-- !a? ( !b? ( !c? ( ) )
( d_all [ d_use "a" $ d_use "b" $ d_use "c" $ d_all $ map d_p [ "x", "y", "z" ]
, d_use "a" $ d_use "b" $ d_nuse "c" $ d_all $ map d_p [ "x", "y" ]
, d_use "a" $ d_nuse "b" $ d_use "c" $ d_all $ map d_p [ "x", "z" ]
, d_use "a" $ d_nuse "b" $ d_nuse "c" $ d_all $ map d_p [ "x" ]
, d_nuse "a" $ d_use "b" $ d_use "c" $ d_all $ map d_p [ "y", "z" ]
, d_nuse "a" $ d_use "b" $ d_nuse "c" $ d_all $ map d_p [ "y" ]
, d_nuse "a" $ d_nuse "b" $ d_use "c" $ d_all $ map d_p [ "z" ]
, d_nuse "a" $ d_nuse "b" $ d_nuse "c" $ d_all $ map d_p [ ]
]
, [ "a? ( c/x )"
, "b? ( c/y )"
, "c? ( c/z )"
]
)
, -- pop simple common subdepend
-- a? ( b? ( d ) )
-- !a? ( b? ( d ) )
( d_all [ d_use "a" $ d_use "b" $ d_p "d"
, d_nuse "a" $ d_use "b" $ d_p "d"
]
, [ "b? ( c/d )"
]
)
, -- pop '|| ( some thing )' depend
( let any_part = d_any $ map d_p ["a", "b"] in
d_all [ d_use "u" $ d_all [ any_part , d_p "z"]
, d_nuse "u" $ any_part
]
, [ "|| ( c/a"
, " c/b )"
, "u? ( c/z )"
]
)
, -- simplify slightly more complex counterguard
-- v? ( c/d )
-- u? ( !v? ( c/d ) )
-- to
-- v? ( c/d )
-- u? ( c/d )
( d_all [ d_use "v" $ d_p "d"
, d_use "u" $ d_nuse "v" $ d_p "d"
]
, [ "u? ( c/d )"
, "v? ( c/d )"
]
)
, -- ffi? ( c/d c/e )
-- !ffi ( !gmp ( c/d c/e ) )
-- gmp? ( c/d c/e )
-- to
-- ( c/d c/e )
( let de = d_all [ d_p "d" , d_p "e" ]
in d_all [ d_use "ffi" de
, d_nuse "ffi" $ d_nuse "gmp" $ de
, d_use "gmp" $ de
]
, [ "c/d"
, "c/e"
]
)
{- TODO: another popular case
, -- simplify even more complex counterguard
-- u? ( c/d )
-- !u? ( v? ( c/d ) )
-- to
-- u? ( c/d )
-- v? ( c/d )
( d_all [ d_use "u" $ d_p "d"
, d_nuse "u" $ d_use "v" $ d_p "d"
]
, [ "u? ( c/d )"
, "v? ( c/d )"
]
)
-}
]
forM_ deps $ \(d, expected) ->
let actual = P.dep2str 0 $ PN.normalize_depend d
in assertEqual ("expecting matching result for " ++ show d)
(intercalate "\n" expected)
actual
main :: IO ()
main = RT.run_tests tests
| gentoo-haskell/hackport | tests/normalize_deps.hs | gpl-3.0 | 10,035 | 4 | 21 | 5,586 | 2,056 | 1,108 | 948 | 128 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElastiCache.CreateCacheSubnetGroup
-- 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)
--
-- The /CreateCacheSubnetGroup/ action creates a new cache subnet group.
--
-- Use this parameter only when you are creating a cluster in an Amazon
-- Virtual Private Cloud (VPC).
--
-- /See:/ <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CreateCacheSubnetGroup.html AWS API Reference> for CreateCacheSubnetGroup.
module Network.AWS.ElastiCache.CreateCacheSubnetGroup
(
-- * Creating a Request
createCacheSubnetGroup
, CreateCacheSubnetGroup
-- * Request Lenses
, ccsgCacheSubnetGroupName
, ccsgCacheSubnetGroupDescription
, ccsgSubnetIds
-- * Destructuring the Response
, createCacheSubnetGroupResponse
, CreateCacheSubnetGroupResponse
-- * Response Lenses
, crsCacheSubnetGroup
, crsResponseStatus
) where
import Network.AWS.ElastiCache.Types
import Network.AWS.ElastiCache.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Represents the input of a /CreateCacheSubnetGroup/ action.
--
-- /See:/ 'createCacheSubnetGroup' smart constructor.
data CreateCacheSubnetGroup = CreateCacheSubnetGroup'
{ _ccsgCacheSubnetGroupName :: !Text
, _ccsgCacheSubnetGroupDescription :: !Text
, _ccsgSubnetIds :: ![Text]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateCacheSubnetGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccsgCacheSubnetGroupName'
--
-- * 'ccsgCacheSubnetGroupDescription'
--
-- * 'ccsgSubnetIds'
createCacheSubnetGroup
:: Text -- ^ 'ccsgCacheSubnetGroupName'
-> Text -- ^ 'ccsgCacheSubnetGroupDescription'
-> CreateCacheSubnetGroup
createCacheSubnetGroup pCacheSubnetGroupName_ pCacheSubnetGroupDescription_ =
CreateCacheSubnetGroup'
{ _ccsgCacheSubnetGroupName = pCacheSubnetGroupName_
, _ccsgCacheSubnetGroupDescription = pCacheSubnetGroupDescription_
, _ccsgSubnetIds = mempty
}
-- | A name for the cache subnet group. This value is stored as a lowercase
-- string.
--
-- Constraints: Must contain no more than 255 alphanumeric characters or
-- hyphens.
--
-- Example: 'mysubnetgroup'
ccsgCacheSubnetGroupName :: Lens' CreateCacheSubnetGroup Text
ccsgCacheSubnetGroupName = lens _ccsgCacheSubnetGroupName (\ s a -> s{_ccsgCacheSubnetGroupName = a});
-- | A description for the cache subnet group.
ccsgCacheSubnetGroupDescription :: Lens' CreateCacheSubnetGroup Text
ccsgCacheSubnetGroupDescription = lens _ccsgCacheSubnetGroupDescription (\ s a -> s{_ccsgCacheSubnetGroupDescription = a});
-- | A list of VPC subnet IDs for the cache subnet group.
ccsgSubnetIds :: Lens' CreateCacheSubnetGroup [Text]
ccsgSubnetIds = lens _ccsgSubnetIds (\ s a -> s{_ccsgSubnetIds = a}) . _Coerce;
instance AWSRequest CreateCacheSubnetGroup where
type Rs CreateCacheSubnetGroup =
CreateCacheSubnetGroupResponse
request = postQuery elastiCache
response
= receiveXMLWrapper "CreateCacheSubnetGroupResult"
(\ s h x ->
CreateCacheSubnetGroupResponse' <$>
(x .@? "CacheSubnetGroup") <*> (pure (fromEnum s)))
instance ToHeaders CreateCacheSubnetGroup where
toHeaders = const mempty
instance ToPath CreateCacheSubnetGroup where
toPath = const "/"
instance ToQuery CreateCacheSubnetGroup where
toQuery CreateCacheSubnetGroup'{..}
= mconcat
["Action" =:
("CreateCacheSubnetGroup" :: ByteString),
"Version" =: ("2015-02-02" :: ByteString),
"CacheSubnetGroupName" =: _ccsgCacheSubnetGroupName,
"CacheSubnetGroupDescription" =:
_ccsgCacheSubnetGroupDescription,
"SubnetIds" =:
toQueryList "SubnetIdentifier" _ccsgSubnetIds]
-- | /See:/ 'createCacheSubnetGroupResponse' smart constructor.
data CreateCacheSubnetGroupResponse = CreateCacheSubnetGroupResponse'
{ _crsCacheSubnetGroup :: !(Maybe CacheSubnetGroup)
, _crsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateCacheSubnetGroupResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'crsCacheSubnetGroup'
--
-- * 'crsResponseStatus'
createCacheSubnetGroupResponse
:: Int -- ^ 'crsResponseStatus'
-> CreateCacheSubnetGroupResponse
createCacheSubnetGroupResponse pResponseStatus_ =
CreateCacheSubnetGroupResponse'
{ _crsCacheSubnetGroup = Nothing
, _crsResponseStatus = pResponseStatus_
}
-- | Undocumented member.
crsCacheSubnetGroup :: Lens' CreateCacheSubnetGroupResponse (Maybe CacheSubnetGroup)
crsCacheSubnetGroup = lens _crsCacheSubnetGroup (\ s a -> s{_crsCacheSubnetGroup = a});
-- | The response status code.
crsResponseStatus :: Lens' CreateCacheSubnetGroupResponse Int
crsResponseStatus = lens _crsResponseStatus (\ s a -> s{_crsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-elasticache/gen/Network/AWS/ElastiCache/CreateCacheSubnetGroup.hs | mpl-2.0 | 5,815 | 0 | 13 | 1,112 | 712 | 429 | 283 | 93 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : Network.MPD.Applicative.PlaybackControl
Copyright : (c) Joachim Fasting 2012
License : MIT
Maintainer : joachifm@fastmail.fm
Stability : stable
Portability : unportable
Controlling playback.
-}
module Network.MPD.Applicative.PlaybackControl
( next
, pause
, toggle
, play
, playId
, previous
, seek
, seekId
, seekCur
, stop
) where
import Network.MPD.Applicative.Internal
import Network.MPD.Commands.Arg hiding (Command)
import Network.MPD.Commands.Types
-- | Play next song in the playlist.
next :: Command ()
next = Command emptyResponse ["next"]
-- | Pauses playback on True, resumes on False.
pause :: Bool -> Command ()
pause f = Command emptyResponse ["pause" <@> f]
-- | Toggles playback.
--
-- @since 0.10.0.0
toggle :: Command ()
toggle = Command emptyResponse ["pause"]
-- | Begin playback (optionally at a specific position).
play :: Maybe Position -> Command ()
play mbPos = Command emptyResponse c
where
c = return $ maybe "play" ("play" <@>) mbPos
-- | Begin playback at the specified song id.
playId :: Id -> Command ()
playId id' = Command emptyResponse ["playid" <@> id']
-- | Play previous song.
previous :: Command ()
previous = Command emptyResponse ["previous"]
-- | Seek to time in the song at the given position.
seek :: Position -> FractionalSeconds -> Command ()
seek pos time = Command emptyResponse ["seek" <@> pos <++> time]
-- | Seek to time in the song with the given id.
seekId :: Id -> FractionalSeconds -> Command ()
seekId id' time = Command emptyResponse ["seekid" <@> id' <++> time]
-- | Seek to time in the current song. Absolute time for True in
-- the frist argument, relative time for False.
--
-- @since 0.9.2.0
seekCur :: Bool -> FractionalSeconds -> Command ()
seekCur bool time
| bool = Command emptyResponse ["seekcur" <@> time]
| otherwise = Command emptyResponse ["seekcur" <@> (Sign time)]
-- | Stop playback.
stop :: Command ()
stop = Command emptyResponse ["stop"]
| bens/libmpd-haskell | src/Network/MPD/Applicative/PlaybackControl.hs | lgpl-2.1 | 2,090 | 0 | 10 | 442 | 457 | 250 | 207 | 38 | 1 |
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI, OverloadedStrings #-}
module Reflex.Dom.Xhr.Foreign (
XMLHttpRequest
, XMLHttpRequestResponseType
, module Reflex.Dom.Xhr.Foreign
) where
import Prelude hiding (error)
import Data.Text (Text)
import GHCJS.DOM.Types hiding (Text)
import GHCJS.DOM
import GHCJS.DOM.Enums
import GHCJS.DOM.XMLHttpRequest
import Data.Maybe (fromMaybe)
import GHCJS.DOM.EventTarget (dispatchEvent)
import GHCJS.DOM.EventM (EventM, on)
prepareWebView :: WebView -> IO ()
prepareWebView _ = return ()
xmlHttpRequestNew :: a -> IO XMLHttpRequest
xmlHttpRequestNew _ = newXMLHttpRequest -- XMLHttpRequest <$> ghcjs_dom_xml_http_request_new
xmlHttpRequestOpen ::
(ToJSString method, ToJSString url, ToJSString user, ToJSString password) =>
XMLHttpRequest -> method -> url -> Bool -> user -> password -> IO ()
xmlHttpRequestOpen = open
-- This used to be a non blocking call, but now it uses an interruptible ffi
xmlHttpRequestSend :: ToJSString payload => XMLHttpRequest -> Maybe payload -> IO ()
xmlHttpRequestSend self = maybe (send self) (sendString self)
xmlHttpRequestSetRequestHeader :: (ToJSString header, ToJSString value)
=> XMLHttpRequest -> header -> value -> IO ()
xmlHttpRequestSetRequestHeader = setRequestHeader
xmlHttpRequestAbort :: XMLHttpRequest -> IO ()
xmlHttpRequestAbort = abort
xmlHttpRequestGetAllResponseHeaders :: XMLHttpRequest -> IO Text
xmlHttpRequestGetAllResponseHeaders self = fromMaybe "" <$> getAllResponseHeaders self
xmlHttpRequestGetResponseHeader :: (ToJSString header)
=> XMLHttpRequest -> header -> IO Text
xmlHttpRequestGetResponseHeader self header = fromMaybe "" <$> getResponseHeader self header
xmlHttpRequestOverrideMimeType :: ToJSString override => XMLHttpRequest -> override -> IO ()
xmlHttpRequestOverrideMimeType = overrideMimeType
xmlHttpRequestDispatchEvent :: IsEvent evt => XMLHttpRequest -> Maybe evt -> IO Bool
xmlHttpRequestDispatchEvent = dispatchEvent
xmlHttpRequestOnabort :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
xmlHttpRequestOnabort = (`on` abortEvent)
xmlHttpRequestOnerror :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
xmlHttpRequestOnerror = (`on` error)
xmlHttpRequestOnload :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
xmlHttpRequestOnload = (`on` load)
xmlHttpRequestOnloadend :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> IO (IO ())
xmlHttpRequestOnloadend = (`on` loadEnd)
xmlHttpRequestOnloadstart :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> IO (IO ())
xmlHttpRequestOnloadstart = (`on` loadStart)
xmlHttpRequestOnprogress :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
xmlHttpRequestOnprogress = (`on` progress)
xmlHttpRequestOntimeout :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> IO (IO ())
xmlHttpRequestOntimeout = (`on` timeout)
xmlHttpRequestOnreadystatechange :: XMLHttpRequest -> EventM XMLHttpRequest Event () -> IO (IO ())
xmlHttpRequestOnreadystatechange = (`on` readyStateChange)
xmlHttpRequestSetTimeout :: XMLHttpRequest -> Word -> IO ()
xmlHttpRequestSetTimeout = setTimeout
xmlHttpRequestGetTimeout :: XMLHttpRequest -> IO Word
xmlHttpRequestGetTimeout = getTimeout
xmlHttpRequestGetReadyState :: XMLHttpRequest -> IO Word
xmlHttpRequestGetReadyState = getReadyState
xmlHttpRequestSetWithCredentials :: XMLHttpRequest -> Bool -> IO ()
xmlHttpRequestSetWithCredentials = setWithCredentials
xmlHttpRequestGetWithCredentials :: XMLHttpRequest -> IO Bool
xmlHttpRequestGetWithCredentials = getWithCredentials
xmlHttpRequestGetUpload :: XMLHttpRequest -> IO (Maybe XMLHttpRequestUpload)
xmlHttpRequestGetUpload = getUpload
xmlHttpRequestGetResponseText :: FromJSString result => XMLHttpRequest -> IO (Maybe result)
xmlHttpRequestGetResponseText = getResponseText
responseTextToText :: Maybe Text -> Maybe Text
responseTextToText = id
xmlHttpRequestGetResponseXML :: XMLHttpRequest -> IO (Maybe Document)
xmlHttpRequestGetResponseXML = getResponseXML
xmlHttpRequestSetResponseType :: XMLHttpRequest -> XMLHttpRequestResponseType -> IO ()
xmlHttpRequestSetResponseType = setResponseType
toResponseType :: a -> a
toResponseType = id
xmlHttpRequestGetResponseType :: XMLHttpRequest -> IO XMLHttpRequestResponseType
xmlHttpRequestGetResponseType = getResponseType
xmlHttpRequestGetStatus :: XMLHttpRequest -> IO Word
xmlHttpRequestGetStatus = getStatus
xmlHttpRequestGetStatusText :: FromJSString result => XMLHttpRequest -> IO result
xmlHttpRequestGetStatusText = getStatusText
xmlHttpRequestGetResponseURL :: FromJSString result => XMLHttpRequest -> IO result
xmlHttpRequestGetResponseURL = getResponseURL
| hamishmack/reflex-dom | src-ghcjs/Reflex/Dom/Xhr/Foreign.hs | bsd-3-clause | 4,888 | 0 | 13 | 651 | 1,139 | 608 | 531 | 84 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies, DataKinds, UndecidableInstances, PolyKinds #-}
module T6018th where
import Language.Haskell.TH
-- Test that injectivity works correct with TH. This test is not as exhaustive
-- as the original T6018 test.
-- type family F a b c = (result :: k) | result -> a b c
-- type instance F Int Char Bool = Bool
-- type instance F Char Bool Int = Int
-- type instance F Bool Int Char = Char
$( return
[ OpenTypeFamilyD
(mkName "F")
[ PlainTV (mkName "a"), PlainTV (mkName "b"), PlainTV (mkName "c") ]
(TyVarSig (KindedTV (mkName "result") (VarT (mkName "k"))))
(Just $ InjectivityAnn (mkName "result")
[(mkName "a"), (mkName "b"), (mkName "c") ])
, TySynInstD
(mkName "F")
(TySynEqn [ ConT (mkName "Int"), ConT (mkName "Char")
, ConT (mkName "Bool")]
( ConT (mkName "Bool")))
, TySynInstD
(mkName "F")
(TySynEqn [ ConT (mkName "Char"), ConT (mkName "Bool")
, ConT (mkName "Int")]
( ConT (mkName "Int")))
, TySynInstD
(mkName "F")
(TySynEqn [ ConT (mkName "Bool"), ConT (mkName "Int")
, ConT (mkName "Char")]
( ConT (mkName "Char")))
] )
-- this is injective - a type variables mentioned on LHS is not mentioned on RHS
-- but we don't claim injectivity in that argument.
--
-- type family J a (b :: k) = r | r -> a
---type instance J Int b = Char
$( return
[ OpenTypeFamilyD
(mkName "J")
[ PlainTV (mkName "a"), KindedTV (mkName "b") (VarT (mkName "k")) ]
(TyVarSig (PlainTV (mkName "r")))
(Just $ InjectivityAnn (mkName "r") [mkName "a"])
, TySynInstD
(mkName "J")
(TySynEqn [ ConT (mkName "Int"), VarT (mkName "b") ]
( ConT (mkName "Int")))
] )
-- Closed type families
-- type family IClosed (a :: *) (b :: *) (c :: *) = r | r -> a b where
-- IClosed Int Char Bool = Bool
-- IClosed Int Char Int = Bool
-- IClosed Bool Int Int = Int
$( return
[ ClosedTypeFamilyD
(mkName "I")
[ KindedTV (mkName "a") StarT, KindedTV (mkName "b") StarT
, KindedTV (mkName "c") StarT ]
(TyVarSig (PlainTV (mkName "r")))
(Just $ InjectivityAnn (mkName "r") [(mkName "a"), (mkName "b")])
[ TySynEqn [ ConT (mkName "Int"), ConT (mkName "Char")
, ConT (mkName "Bool")]
( ConT (mkName "Bool"))
, TySynEqn [ ConT (mkName "Int"), ConT (mkName "Char")
, ConT (mkName "Int")]
( ConT (mkName "Bool"))
, TySynEqn [ ConT (mkName "Bool"), ConT (mkName "Int")
, ConT (mkName "Int")]
( ConT (mkName "Int"))
]
] )
-- reification test
$( do { decl@([ClosedTypeFamilyD _ _ _ (Just inj) _]) <-
[d| type family Bak a = r | r -> a where
Bak Int = Char
Bak Char = Int
Bak a = a |]
; return decl
}
)
-- Check whether incorrect injectivity declarations are caught
-- type family I a b c = r | r -> a b
-- type instance I Int Char Bool = Bool
-- type instance I Int Int Int = Bool
-- type instance I Bool Int Int = Int
$( return
[ OpenTypeFamilyD
(mkName "H")
[ PlainTV (mkName "a"), PlainTV (mkName "b"), PlainTV (mkName "c") ]
(TyVarSig (PlainTV (mkName "r")))
(Just $ InjectivityAnn (mkName "r")
[(mkName "a"), (mkName "b") ])
, TySynInstD
(mkName "H")
(TySynEqn [ ConT (mkName "Int"), ConT (mkName "Char")
, ConT (mkName "Bool")]
( ConT (mkName "Bool")))
, TySynInstD
(mkName "H")
(TySynEqn [ ConT (mkName "Int"), ConT (mkName "Int")
, ConT (mkName "Int")]
( ConT (mkName "Bool")))
, TySynInstD
(mkName "H")
(TySynEqn [ ConT (mkName "Bool"), ConT (mkName "Int")
, ConT (mkName "Int")]
( ConT (mkName "Int")))
] )
| mpickering/ghc-exactprint | tests/examples/ghc8/T6018th.hs | bsd-3-clause | 4,142 | 0 | 17 | 1,410 | 1,226 | 629 | 597 | 80 | 0 |
{-# LANGUAGE RebindableSyntax #-}
{-# OPTIONS_GHC -fplugin Control.Supermonad.Plugin #-}
{-
******************************************************************************
* H M T C *
* *
* Module: MTStdEnv *
* Purpose: MiniTriangle Initial Environment *
* Authors: Henrik Nilsson *
* *
* Copyright (c) Henrik Nilsson, 2006 - 2015 *
* *
******************************************************************************
-}
-- | MiniTriangle initial environment
module MTStdEnv (
Env, -- Re-exported
mtStdEnv -- :: Env
) where
import Control.Supermonad.Prelude
-- HMTC module imports
import Name
import TAMCode (MTInt)
import Type
import Symbol (ExtSymVal (..))
import Env
-- | The MiniTriangle initial environment.
--
-- [Types:] Boolean, Character, Integer
--
-- [Constants:]
--
-- * false, true : Boolean
--
-- * minint, maxint : Integer
--
-- [Functions (binary (infix) and unary (prefix/postfix) operators):]
--
-- * (++_), (--_), (_++), (_--) : (Ref Integer) -> Integer
--
-- * (_+_), (_-_), (_*_), (_\/_), (_\^_) : (Integer, Integer) -> Integer
--
-- * (-_) : Integer -> Integer
--
-- * (_\<_), (_\<=_), (_==_), (_!=_), (_>=_), (_>_) :
-- (Integer, Integer) -> Boolean,
-- (Boolan, Boolean) -> Boolean
--
-- * (_&&_), (_||_) : (Boolean, Boolean) -> Boolean
--
-- * (!_) : Boolean -> Boolean
--
-- [Procedures:]
--
-- * getchr : (Snk Character) -> Void
--
-- * putchr : Character -> Void
--
-- * getint : (Snk Integer) -> Void
--
-- * putint : Integer -> Void
--
-- * skip : () -> Void
--
-- Note the naming convention for infix/prefix/postfix operators with
-- underscore indicating the argument position(s). Parser assumes this.
-- Note that labels have to agree with the code in "LibMT".
mtStdEnv :: Env
mtStdEnv =
mkTopLvlEnv
[("Boolean", Boolean),
("Character", Character),
("Integer", Integer)]
[("false", Boolean, ESVBool False),
("true", Boolean, ESVBool True),
("minint", Integer, ESVInt (minBound :: MTInt)),
("maxint", Integer, ESVInt (maxBound :: MTInt)),
("++_", Arr [Ref Integer] Integer, ESVLbl "preinc"),
("--_", Arr [Ref Integer] Integer, ESVLbl "predec"),
("_++", Arr [Ref Integer] Integer, ESVLbl "postinc"),
("_--", Arr [Ref Integer] Integer, ESVLbl "postdec"),
("_+_", Arr [Integer, Integer] Integer, ESVLbl "add"),
("_-_", Arr [Integer, Integer] Integer, ESVLbl "sub"),
("_*_", Arr [Integer, Integer] Integer, ESVLbl "mul"),
("_/_", Arr [Integer, Integer] Integer, ESVLbl "div"),
("_^_", Arr [Integer, Integer] Integer, ESVLbl "pow"),
("-_", Arr [Integer] Integer, ESVLbl "neg"),
-- The comparison operators are overloaded, but their impl. shared.
("_<_", Arr [Integer, Integer] Boolean, ESVLbl "lt"),
("_<=_", Arr [Integer, Integer] Boolean, ESVLbl "le"),
("_==_", Arr [Integer, Integer] Boolean, ESVLbl "eq"),
("_!=_", Arr [Integer, Integer] Boolean, ESVLbl "ne"),
("_>=_", Arr [Integer, Integer] Boolean, ESVLbl "ge"),
("_>_", Arr [Integer, Integer] Boolean, ESVLbl "gt"),
("_<_", Arr [Boolean, Boolean] Boolean, ESVLbl "lt"),
("_<=_", Arr [Boolean, Boolean] Boolean, ESVLbl "le"),
("_==_", Arr [Boolean, Boolean] Boolean, ESVLbl "eq"),
("_!=_", Arr [Boolean, Boolean] Boolean, ESVLbl "ne"),
("_>=_", Arr [Boolean, Boolean] Boolean, ESVLbl "ge"),
("_>_", Arr [Boolean, Boolean] Boolean, ESVLbl "gt"),
("_&&_", Arr [Boolean, Boolean] Boolean, ESVLbl "and"),
("_||_", Arr [Boolean, Boolean] Boolean, ESVLbl "or"),
("!_", Arr [Boolean] Boolean, ESVLbl "not"),
("getchr", Arr [Snk Character] Void, ESVLbl "getchr"),
("putchr", Arr [Character] Void, ESVLbl "putchr"),
("getint", Arr [Snk Integer] Void, ESVLbl "getint"),
("putint", Arr [Integer] Void, ESVLbl "putint"),
("skip", Arr [] Void, ESVLbl "skip")]
| jbracker/supermonad-plugin | examples/monad/hmtc/supermonad/MTStdEnv.hs | bsd-3-clause | 4,706 | 0 | 10 | 1,595 | 974 | 583 | 391 | 51 | 1 |
-- Use GtkSocket and GtkPlug for cross-process embedded.
-- Just startup program, press 'm' to create tab with new button.
-- Click button for hang to simulate plug hanging process,
-- but socket process still running, can switch to other tab.
module Main where
import System.Process
import System.Environment
import System.Directory
import System.FilePath ((</>))
import Control.Monad
import Control.Monad.Trans
import Control.Concurrent
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.DrawWindow
import Graphics.UI.Gtk.Gdk.EventM
-- | Main.
main :: IO ()
main = do
-- Get program arguments.
args <- getArgs
case args of
-- Entry plug main when have two arguments.
[id] -> plugMain (toNativeWindowId $ read id :: NativeWindowId) -- get GtkSocket id
-- Othersise entry socket main when no arguments.
_ -> socketMain
-- | GtkSocekt main.
socketMain :: IO ()
socketMain = do
initGUI
-- Create top-level window.
window <- windowNew
windowSetPosition window WinPosCenter
windowSetDefaultSize window 600 400
windowSetTitle window "Press `m` to new tab, press `q` exit."
window `onDestroy` mainQuit
-- Create notebook to contain GtkSocekt.
notebook <- notebookNew
window `containerAdd` notebook
-- Handle key press.
window `on` keyPressEvent $ tryEvent $ do
keyName <- eventKeyName
liftIO $
case keyName of
"m" -> do
-- Create new GtkSocket.
socket <- socketNew
widgetShow socket -- must show before add GtkSocekt to container
notebookAppendPage notebook socket "Tab" -- add to GtkSocekt notebook
id <- socketGetId socket -- get GtkSocket id
-- Fork process to add GtkPlug into GtkSocekt.
path <- liftM2 (</>) getCurrentDirectory getProgName -- get program full path
runCommand $ path ++ " " ++ (show $ fromNativeWindowId id) -- don't use `forkProcess`
return ()
"q" -> mainQuit -- quit
widgetShowAll window
mainGUI
-- | GtkPlug main.
plugMain :: NativeWindowId -> IO ()
plugMain id = do
initGUI
plug <- plugNew $ Just id
plug `onDestroy` mainQuit
button <- buttonNewWithLabel "Click me to hang."
plug `containerAdd` button
-- Simulate a plugin hanging to see if it blocks the outer process.
button `onClicked` threadDelay 5000000
widgetShowAll plug
mainGUI
| phischu/gtk2hs | gtk/demo/embedded/Embedded.hs | lgpl-3.0 | 2,460 | 0 | 19 | 628 | 454 | 237 | 217 | 52 | 2 |
{-|
Module : Idris.IdrisDoc
Description : Generation of HTML documentation for Idris code
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE OverloadedStrings, PatternGuards #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.IdrisDoc (generateDocs) where
import Idris.AbsSyntax
import Idris.Core.Evaluate (Accessibility(..), Def(..), ctxtAlist, isDConName,
isFnName, isTConName, lookupDefAcc)
import Idris.Core.TT (Name(..), OutputAnnotation(..), SpecialName(..),
TextFormatting(..), constIsType, nsroot, sUN, str,
toAlist, txt)
import Idris.Docs
import Idris.Docstrings (nullDocstring)
import qualified Idris.Docstrings as Docstrings
import Idris.Parser.Helpers (opChars)
import IRTS.System (getIdrisDataFileByName)
import Control.Applicative ((<|>))
import Control.Monad (forM_)
import Control.Monad.Trans.Except
import Control.Monad.Trans.State.Strict
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BS2
import qualified Data.List as L
import qualified Data.List.Split as LS
import qualified Data.Map as M hiding ((!))
import Data.Maybe
import Data.Monoid (mempty)
import qualified Data.Ord (compare)
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import System.Directory
import System.FilePath
import System.IO
import System.IO.Error
import Text.Blaze (contents, toValue)
import qualified Text.Blaze.Html.Renderer.String as R
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Text.Blaze.Html5 (preEscapedToHtml, toHtml, (!))
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes as A
import Text.Blaze.Internal (MarkupM(Empty))
import Text.Blaze.Renderer.String (renderMarkup)
import Text.PrettyPrint.Annotated.Leijen (displayDecorated, renderCompact)
-- ---------------------------------------------------------------- [ Public ]
-- | Generates HTML documentation for a series of loaded namespaces
-- and their dependencies.
generateDocs :: IState -- ^ IState where all necessary information is
-- extracted from.
-> [Name] -- ^ List of namespaces to generate
-- documentation for.
-> FilePath -- ^ The directory to which documentation will
-- be written.
-> IO (Either String ())
generateDocs ist nss' out =
do let nss = map toNsName nss'
docs <- fetchInfo ist nss
let (c, io) = foldl (checker docs) (0, return ()) nss
io
if c < length nss
then catchIOError (createDocs ist docs out) (err . show)
else err "No namespaces to generate documentation for"
where checker docs st ns | M.member ns docs = st
checker docs (c, io) ns = (c+1, do prev <- io; warnMissing ns)
warnMissing ns =
putStrLn $ "Warning: Ignoring empty or non-existing namespace '" ++
(nsName2Str ns) ++ "'"
-- ----------------------------------------------------------------- [ Types ]
-- | Either an error message or a result
type Failable = Either String
-- | Internal representation of a fully qualified namespace name
type NsName = [T.Text]
-- | All information to be documented about a single namespace member
type NsItem = (Name, Maybe Docs, Accessibility)
-- | Docstrings containing fully elaborated term annotations
type FullDocstring = Docstrings.Docstring Docstrings.DocTerm
-- | All information to be documented about a namespace
data NsInfo = NsInfo { nsDocstring :: Maybe FullDocstring,
nsContents :: [NsItem]
}
-- | A map from namespace names to information about them
type NsDict = M.Map NsName NsInfo
-- --------------------------------------------------------------- [ Utility ]
-- | Make an error message
err :: String -> IO (Failable ())
err s = return $ Left s
-- | IdrisDoc version
version :: String
version = "1.0"
-- | Converts a Name into a [Text] corresponding to the namespace
-- part of a NS Name.
toNsName :: Name -- ^ Name to convert
-> NsName
toNsName (UN n) = [n]
toNsName (NS n ns) = (toNsName n) ++ ns
toNsName _ = []
-- | Retrieves the namespace part of a Name
getNs :: Name -- ^ Name to retrieve namespace for
-> NsName
getNs (NS _ ns) = ns
getNs _ = []
-- | String to replace for the root namespace
rootNsStr :: String
rootNsStr = "[builtins]"
-- | Converts a NsName to string form
nsName2Str :: NsName -- ^ NsName to convert
-> String
nsName2Str n = if null n then rootNsStr else name n
where name [] = []
name [ns] = str ns
name (ns:nss) = (name nss) ++ ('.' : str ns)
-- --------------------------------------------------------- [ Info Fetching ]
-- | Fetch info about namespaces and their contents
fetchInfo :: IState -- ^ IState to fetch info from
-> [NsName] -- ^ List of namespaces to fetch info for
-> IO NsDict -- ^ Mapping from namespace name to
-- info about its contents
fetchInfo ist nss =
do let originNss = S.fromList nss
info <- nsDict ist
let accessible = M.map (filterContents filterInclude) info
nonOrphan = M.map (updateContents removeOrphans) accessible
nonEmpty = M.filter (not . null . nsContents) nonOrphan
reachedNss = traceNss nonEmpty originNss S.empty
return $ M.filterWithKey (\k _ -> S.member k reachedNss) nonEmpty
where
-- TODO: lensify
filterContents p (NsInfo md ns) = NsInfo md (filter p ns)
updateContents f x = x { nsContents = f (nsContents x) }
-- | Removes loose interface methods and data constructors,
-- leaving them documented only under their parent.
removeOrphans :: [NsItem] -- ^ List to remove orphans from
-> [NsItem] -- ^ Orphan-free list
removeOrphans list =
let children = S.fromList $ concatMap (names . (\(_, d, _) -> d)) list
in filter ((flip S.notMember children) . (\(n, _, _) -> n)) list
where names (Just (DataDoc _ fds)) = map (\(FD n _ _ _ _) -> n) fds
names (Just (InterfaceDoc _ _ fds _ _ _ _ _ c)) = map (\(FD n _ _ _ _) -> n) fds ++ map (\(FD n _ _ _ _) -> n) (maybeToList c)
names _ = []
-- | Whether a Name names something which should be documented
filterName :: Name -- ^ Name to check
-> Bool -- ^ Predicate result
filterName (UN _) = True
filterName (NS n _) = filterName n
filterName _ = False
-- | Whether a NsItem should be included in the documentation.
-- It must not be Hidden/Private and filterName must return True for the name.
-- Also it must have Docs -- without Docs, nothing can be done.
filterInclude :: NsItem -- ^ Accessibility to check
-> Bool -- ^ Predicate result
filterInclude (name, Just _, Public) | filterName name = True
filterInclude (name, Just _, Frozen) | filterName name = True
filterInclude _ = False
-- | Finds all namespaces indirectly referred by a set of namespaces.
-- The NsItems of the namespaces are searched for references.
traceNss :: NsDict -- ^ Mappings of namespaces and their contents
-> S.Set NsName -- ^ Set of namespaces to trace
-> S.Set NsName -- ^ Set of namespaces which has been traced
-> S.Set NsName -- ^ Set of namespaces to trace and all traced one
traceNss nsd sT sD =
let nsTracer ns | Just nsis <- M.lookup ns nsd = map referredNss (nsContents nsis)
nsTracer _ = [S.empty] -- Ignore
reached = S.unions $ concatMap nsTracer (S.toList sT)
processed = S.union sT sD
untraced = S.difference reached processed
in if S.null untraced then processed
else traceNss nsd untraced processed
-- | Gets all namespaces directly referred by a NsItem
referredNss :: NsItem -- ^ The name to get all directly
-- referred namespaces for
-> S.Set NsName
referredNss (_, Nothing, _) = S.empty
referredNss (n, Just d, _) =
let fds = getFunDocs d
ts = concatMap types fds
names = concatMap (extractPTermNames) ts
in S.map getNs $ S.fromList names
where getFunDocs (FunDoc f) = [f]
getFunDocs (DataDoc f fs) = f:fs
getFunDocs (InterfaceDoc _ _ fs _ _ _ _ _ _) = fs
getFunDocs (RecordDoc _ _ f fs _) = f:fs
getFunDocs (NamedImplementationDoc _ fd) = [fd]
getFunDocs (ModDoc _ _) = []
types (FD _ _ args t _) = t:(map second args)
second (_, x, _, _) = x
-- | Returns an NsDict of containing all known namespaces and their contents
nsDict :: IState
-> IO NsDict
nsDict ist = flip (foldl addModDoc) modDocs $ foldl adder (return M.empty) nameDefList
where nameDefList = ctxtAlist $ tt_ctxt ist
adder m (n, _) = do map <- m
doc <- loadDocs ist n
let access = getAccess ist n
nInfo = NsInfo Nothing [(n, doc, access)]
return $ M.insertWith addNameInfo (getNs n) nInfo map
addNameInfo (NsInfo m ns) (NsInfo m' ns') = NsInfo (m <|> m') (ns ++ ns')
modDocs = map (\(mn, d) -> (mn, NsInfo (Just d) [])) $ toAlist (idris_moduledocs ist)
addModDoc :: IO NsDict -> (Name, NsInfo) -> IO NsDict
addModDoc dict (mn, d) = fmap (M.insertWith addNameInfo (getNs mn) d) dict
-- | Gets the Accessibility for a Name
getAccess :: IState -- ^ IState containing accessibility information
-> Name -- ^ The Name to retrieve access for
-> Accessibility
getAccess ist n =
let res = lookupDefAcc n False (tt_ctxt ist)
in case res of
[(_, acc)] -> acc
_ -> Private
-- | Simple predicate for whether an NsItem has Docs
hasDoc :: NsItem -- ^ The NsItem to test
-> Bool -- ^ The result
hasDoc (_, Just _, _) = True
hasDoc _ = False
-- | Predicate saying whether a Name possibly may have docs defined
-- Without this, getDocs from Idris.Docs may fail a pattern match.
mayHaveDocs :: Name -- ^ The Name to test
-> Bool -- ^ The result
mayHaveDocs (UN _) = True
mayHaveDocs (NS n _) = mayHaveDocs n
mayHaveDocs _ = False
-- | Retrieves the Docs for a Name
loadDocs :: IState -- ^ IState to extract infomation from
-> Name -- ^ Name to load Docs for
-> IO (Maybe Docs)
loadDocs ist n
| mayHaveDocs n = do docs <- runExceptT $ evalStateT (getDocs n FullDocs) ist
case docs of Right d -> return (Just d)
Left _ -> return Nothing
| otherwise = return Nothing
-- | Extracts names referred from a type.
-- The covering of all PTerms ensures that we avoid unanticipated cases,
-- though all of them are not needed. The author just did not know which!
-- TODO: Remove unnecessary cases
extractPTermNames :: PTerm -- ^ Where to extract names from
-> [Name] -- ^ Extracted names
extractPTermNames (PRef _ _ n) = [n]
extractPTermNames (PInferRef _ _ n) = [n]
extractPTermNames (PPatvar _ n) = [n]
extractPTermNames (PLam _ n _ p1 p2) = n : concatMap extract [p1, p2]
extractPTermNames (PPi _ n _ p1 p2) = n : concatMap extract [p1, p2]
extractPTermNames (PLet _ n _ p1 p2 p3) = n : concatMap extract [p1, p2, p3]
extractPTermNames (PTyped p1 p2) = concatMap extract [p1, p2]
extractPTermNames (PApp _ p pas) = let names = concatMap extractPArg pas
in (extract p) ++ names
extractPTermNames (PAppBind _ p pas) = let names = concatMap extractPArg pas
in (extract p) ++ names
extractPTermNames (PMatchApp _ n) = [n]
extractPTermNames (PCase _ p ps) = let (ps1, ps2) = unzip ps
in concatMap extract (p:(ps1 ++ ps2))
extractPTermNames (PIfThenElse _ c t f) = concatMap extract [c, t, f]
extractPTermNames (PRewrite _ _ a b m) | Just c <- m =
concatMap extract [a, b, c]
extractPTermNames (PRewrite _ _ a b _) = concatMap extract [a, b]
extractPTermNames (PPair _ _ _ p1 p2) = concatMap extract [p1, p2]
extractPTermNames (PDPair _ _ _ a b c) = concatMap extract [a, b, c]
extractPTermNames (PAlternative _ _ l) = concatMap extract l
extractPTermNames (PHidden p) = extract p
extractPTermNames (PGoal _ p1 n p2) = n : concatMap extract [p1, p2]
extractPTermNames (PDoBlock pdos) = concatMap extractPDo pdos
extractPTermNames (PIdiom _ p) = extract p
extractPTermNames (PMetavar _ n) = [n]
extractPTermNames (PProof tacts) = concatMap extractPTactic tacts
extractPTermNames (PTactics tacts) = concatMap extractPTactic tacts
extractPTermNames (PCoerced p) = extract p
extractPTermNames (PDisamb _ p) = extract p
extractPTermNames (PUnifyLog p) = extract p
extractPTermNames (PNoImplicits p) = extract p
extractPTermNames (PRunElab _ p _) = extract p
extractPTermNames (PConstSugar _ tm) = extract tm
extractPTermNames _ = []
-- | Shorter name for extractPTermNames
extract :: PTerm -- ^ Where to extract names from
-> [Name] -- ^ Extracted names
extract = extractPTermNames
-- | Helper function for extractPTermNames
extractPArg :: PArg -> [Name]
extractPArg (PImp {pname=n, getTm=p}) = n : extract p
extractPArg (PExp {getTm=p}) = extract p
extractPArg (PConstraint {getTm=p}) = extract p
extractPArg (PTacImplicit {pname=n, getScript=p1, getTm=p2})
= n : (concatMap extract [p1, p2])
-- | Helper function for extractPTermNames
extractPDo :: PDo -> [Name]
extractPDo (DoExp _ p) = extract p
extractPDo (DoBind _ n _ p) = n : extract p
extractPDo (DoBindP _ p1 p2 ps) = let (ps1, ps2) = unzip ps
ps' = ps1 ++ ps2
in concatMap extract (p1 : p2 : ps')
extractPDo (DoLet _ n _ p1 p2) = n : concatMap extract [p1, p2]
extractPDo (DoLetP _ p1 p2) = concatMap extract [p1, p2]
-- | Helper function for extractPTermNames
extractPTactic :: PTactic -> [Name]
extractPTactic (Intro ns) = ns
extractPTactic (Focus n) = [n]
extractPTactic (Refine n _) = [n]
extractPTactic (Rewrite p) = extract p
extractPTactic (Induction p) = extract p
extractPTactic (CaseTac p) = extract p
extractPTactic (Equiv p) = extract p
extractPTactic (MatchRefine n) = [n]
extractPTactic (LetTac n p) = n : extract p
extractPTactic (LetTacTy n p1 p2) = n : concatMap extract [p1, p2]
extractPTactic (Exact p) = extract p
extractPTactic (ProofSearch _ _ _ m _ ns) | Just n <- m = n : ns
extractPTactic (ProofSearch _ _ _ _ _ ns) = ns
extractPTactic (Try t1 t2) = concatMap extractPTactic [t1, t2]
extractPTactic (TSeq t1 t2) = concatMap extractPTactic [t1, t2]
extractPTactic (ApplyTactic p) = extract p
extractPTactic (ByReflection p) = extract p
extractPTactic (Reflect p) = extract p
extractPTactic (Fill p) = extract p
extractPTactic (GoalType _ t) = extractPTactic t
extractPTactic (TCheck p) = extract p
extractPTactic (TEval p) = extract p
extractPTactic _ = []
-- ------------------------------------------------------- [ HTML Generation ]
-- | Generates the actual HTML output based on info from a NsDict
-- A merge of the new docs and any existing docs located in the output dir
-- is attempted.
-- TODO: Ensure the merge always succeeds.
-- Currently the content of 'docs/<builtins>.html' may change between
-- runs, thus not always containing all items referred from other
-- namespace .html files.
createDocs :: IState -- ^ Needed to determine the types of names
-> NsDict -- ^ All info from which to generate docs
-> FilePath -- ^ The base directory to which
-- documentation will be written.
-> IO (Failable ())
createDocs ist nsd out =
do new <- not `fmap` (doesFileExist $ out </> "IdrisDoc")
existing_nss <- existingNamespaces out
let nss = S.union (M.keysSet nsd) existing_nss
dExists <- doesDirectoryExist out
if new && dExists then err $ "Output directory (" ++ out ++ ") is" ++
" already in use for other than IdrisDoc."
else do
createDirectoryIfMissing True out
foldl docGen (return ()) (M.toList nsd)
createIndex nss out
-- Create an empty IdrisDoc file to signal 'out' is used for IdrisDoc
if new -- But only if it not already existed...
then withFile (out </> "IdrisDoc") WriteMode ((flip hPutStr) "")
else return ()
copyDependencies out
return $ Right ()
where docGen io (n, c) = do io; createNsDoc ist n c out
-- | (Over)writes the 'index.html' file in the given directory with
-- an (updated) index of namespaces in the documentation
createIndex :: S.Set NsName -- ^ Set of namespace names to
-- include in the index
-> FilePath -- ^ The base directory to which
-- documentation will be written.
-> IO ()
createIndex nss out =
do (path, h) <- openTempFile out "index.html"
BS2.hPut h $ renderHtml $ wrapper Nothing $ do
H.h1 "Namespaces"
H.ul ! class_ "names" $ do
let path ns = "docs" ++ "/" ++ genRelNsPath ns "html"
item ns = do let n = toHtml $ nsName2Str ns
link = toValue $ path ns
H.li $ H.a ! href link ! class_ "code" $ n
sort = L.sortBy (\n1 n2 -> reverse n1 `compare` reverse n2)
forM_ (sort $ S.toList nss) item
hClose h
renameFile path (out </> "index.html")
-- | Generates a HTML file for a namespace and its contents.
-- The location for e.g. Prelude.Algebra is <base>/Prelude/Algebra.html
createNsDoc :: IState -- ^ Needed to determine the types of names
-> NsName -- ^ The name of the namespace to
-- create documentation for
-> NsInfo -- ^ The contents of the namespace
-> FilePath -- ^ The base directory to which
-- documentation will be written.
-> IO ()
createNsDoc ist ns content out =
do let tpath = out </> "docs" </> (genRelNsPath ns "html")
dir = takeDirectory tpath
file = takeFileName tpath
haveDocs (_, Just d, _) = [d]
haveDocs _ = []
-- We cannot do anything without a Doc
content' = concatMap haveDocs (nsContents content)
createDirectoryIfMissing True dir
(path, h) <- openTempFile dir file
BS2.hPut h $ renderHtml $ wrapper (Just ns) $ do
H.h1 $ toHtml (nsName2Str ns)
case nsDocstring content of
Nothing -> mempty
Just docstring -> Docstrings.renderHtml docstring
H.dl ! class_ "decls" $ forM_ content' (createOtherDoc ist)
hClose h
renameFile path tpath
-- | Generates a relative filepath for a namespace, appending an extension
genRelNsPath :: NsName -- ^ Namespace to generate a path for
-> String -- ^ Extension suffix
-> FilePath
genRelNsPath ns suffix = nsName2Str ns <.> suffix
-- | Generates a HTML type signature with proper tags
-- TODO: Turn docstrings into title attributes more robustly
genTypeHeader :: IState -- ^ Needed to determine the types of names
-> FunDoc -- ^ Type to generate type declaration for
-> H.Html -- ^ Resulting HTML
genTypeHeader ist (FD n _ args ftype _) = do
H.span ! class_ (toValue $ "name " ++ getType n)
! title (toValue $ show n)
$ toHtml $ name $ nsroot n
H.span ! class_ "word" $ do nbsp; ":"; nbsp
H.span ! class_ "signature" $ preEscapedToHtml htmlSignature
where
htmlSignature = displayDecorated decorator $ renderCompact signature
signature = pprintPTerm defaultPPOption [] names (idris_infixes ist) ftype
names = [ n | (n@(UN n'), _, _, _) <- args,
not (T.isPrefixOf (txt "__") n') ]
decorator (AnnConst c) str | constIsType c = htmlSpan str "type" str
| otherwise = htmlSpan str "data" str
decorator (AnnData _ _) str = htmlSpan str "data" str
decorator (AnnType _ _) str = htmlSpan str "type" str
decorator AnnKeyword str = htmlSpan "" "keyword" str
decorator (AnnBoundName n i) str | Just t <- M.lookup n docs =
let cs = (if i then "implicit " else "") ++ "documented boundvar"
in htmlSpan t cs str
decorator (AnnBoundName _ i) str =
let cs = (if i then "implicit " else "") ++ "boundvar"
in htmlSpan "" cs str
decorator (AnnName n _ _ _) str
| filterName n = htmlLink (show n) (getType n) (link n) str
| otherwise = htmlSpan "" (getType n) str
decorator (AnnTextFmt BoldText) str = "<b>" ++ str ++ "</b>"
decorator (AnnTextFmt UnderlineText) str = "<u>" ++ str ++ "</u>"
decorator (AnnTextFmt ItalicText) str = "<i>" ++ str ++ "</i>"
decorator _ str = str
htmlSpan :: String -> String -> String -> String
htmlSpan t cs str = do
R.renderHtml $ H.span ! class_ (toValue cs)
! title (toValue t)
$ toHtml str
htmlLink :: String -> String -> String -> String -> String
htmlLink t cs a str = do
R.renderHtml $ H.a ! class_ (toValue cs)
! title (toValue t) ! href (toValue a)
$ toHtml str
docs = M.fromList $ mapMaybe docExtractor args
docExtractor (_, _, _, Nothing) = Nothing
docExtractor (n, _, _, Just d) = Just (n, doc2Str d)
-- TODO: Remove <p> tags more robustly
doc2Str d = let dirty = renderMarkup $ contents $ Docstrings.renderHtml d
in take (length dirty - 8) $ drop 3 dirty
name (NS n ns) = show (NS (sUN $ name n) ns)
name n = let n' = show n
in if (head n') `elem` opChars
then '(':(n' ++ ")")
else n'
link n = let path = genRelNsPath (getNs n) "html"
in path ++ "#" ++ (show n)
getType :: Name -> String
getType n = let ctxt = tt_ctxt ist
in case () of
_ | isDConName n ctxt -> "constructor"
_ | isFnName n ctxt -> "function"
_ | isTConName n ctxt -> "type"
_ | otherwise -> ""
-- | Generates HTML documentation for a function.
createFunDoc :: IState -- ^ Needed to determine the types of names
-> FunDoc -- ^ Function to generate block for
-> H.Html -- ^ Resulting HTML
createFunDoc ist fd@(FD name docstring args ftype fixity) = do
H.dt ! (A.id $ toValue $ show name) $ genTypeHeader ist fd
H.dd $ do
(if nullDocstring docstring then Empty else Docstrings.renderHtml docstring)
let args' = filter (\(_, _, _, d) -> isJust d) args
if (not $ null args') || (isJust fixity)
then H.dl $ do
if (isJust fixity) then do
H.dt ! class_ "fixity" $ "Fixity"
let f = fromJust fixity
H.dd ! class_ "fixity" ! title (toValue $ show f) $ genFix f
else Empty
forM_ args' genArg
else Empty
where genFix (Infixl {prec=p}) =
toHtml $ "Left associative, precedence " ++ show p
genFix (Infixr {prec=p}) =
toHtml $ "Left associative, precedence " ++ show p
genFix (InfixN {prec=p}) =
toHtml $ "Non-associative, precedence " ++ show p
genFix (PrefixN {prec=p}) =
toHtml $ "Prefix, precedence " ++ show p
genArg (_, _, _, Nothing) = Empty
genArg (name, _, _, Just docstring) = do
H.dt $ toHtml $ show name
H.dd $ Docstrings.renderHtml docstring
-- | Generates HTML documentation for any Docs type
-- TODO: Generate actual signatures for interfaces
createOtherDoc :: IState -- ^ Needed to determine the types of names
-> Docs -- ^ Namespace item to generate HTML block for
-> H.Html -- ^ Resulting HTML
createOtherDoc ist (FunDoc fd) = createFunDoc ist fd
createOtherDoc ist (InterfaceDoc n docstring fds _ _ _ _ _ c) = do
H.dt ! (A.id $ toValue $ show n) $ do
H.span ! class_ "word" $ do "interface"; nbsp
H.span ! class_ "name type"
! title (toValue $ show n)
$ toHtml $ name $ nsroot n
H.span ! class_ "signature" $ nbsp
H.dd $ do
(if nullDocstring docstring then Empty else Docstrings.renderHtml docstring)
H.dl ! class_ "decls" $ (forM_ (maybeToList c ++ fds) (createFunDoc ist))
where name (NS n ns) = show (NS (sUN $ name n) ns)
name n = let n' = show n
in if (head n') `elem` opChars
then '(':(n' ++ ")")
else n'
createOtherDoc ist (RecordDoc n doc ctor projs params) = do
H.dt ! (A.id $ toValue $ show n) $ do
H.span ! class_ "word" $ do "record"; nbsp
H.span ! class_ "name type"
! title (toValue $ show n)
$ toHtml $ name $ nsroot n
H.span ! class_ "type" $ do nbsp ; prettyParameters
H.dd $ do
(if nullDocstring doc then Empty else Docstrings.renderHtml doc)
if not $ null params
then H.dl $ forM_ params genParam
else Empty
H.dl ! class_ "decls" $ createFunDoc ist ctor
H.dl ! class_ "decls" $ forM_ projs (createFunDoc ist)
where name (NS n ns) = show (NS (sUN $ name n) ns)
name n = let n' = show n
in if (head n') `elem` opChars
then '(':(n' ++ ")")
else n'
genParam (name, pt, docstring) = do
H.dt $ toHtml $ show (nsroot name)
H.dd $ maybe nbsp Docstrings.renderHtml docstring
prettyParameters = toHtml $ unwords [show $ nsroot n | (n,_,_) <- params]
createOtherDoc ist (DataDoc fd@(FD n docstring args _ _) fds) = do
H.dt ! (A.id $ toValue $ show n) $ do
H.span ! class_ "word" $ do "data"; nbsp
genTypeHeader ist fd
H.dd $ do
(if nullDocstring docstring then Empty else Docstrings.renderHtml docstring)
let args' = filter (\(_, _, _, d) -> isJust d) args
if not $ null args'
then H.dl $ forM_ args' genArg
else Empty
H.dl ! class_ "decls" $ forM_ fds (createFunDoc ist)
where genArg (_, _, _, Nothing) = Empty
genArg (name, _, _, Just docstring) = do
H.dt $ toHtml $ show name
H.dd $ Docstrings.renderHtml docstring
createOtherDoc ist (NamedImplementationDoc _ fd) = createFunDoc ist fd
createOtherDoc ist (ModDoc _ docstring) = do
Docstrings.renderHtml docstring
-- | Generates everything but the actual content of the page
wrapper :: Maybe NsName -- ^ Namespace name, unless it is the index
-> H.Html -- ^ Inner HTML
-> H.Html
wrapper ns inner =
let (index, str) = extract ns
base = if index then "" else "../"
styles = base ++ "styles.css" :: String
indexPage = base ++ "index.html" :: String
in H.docTypeHtml $ do
H.head $ do
H.title $ do
"IdrisDoc"
if index then " Index" else do
": "
toHtml str
H.link ! type_ "text/css" ! rel "stylesheet"
! href (toValue styles)
H.body ! class_ (if index then "index" else "namespace") $ do
H.div ! class_ "wrapper" $ do
H.header $ do
H.strong "IdrisDoc"
if index then Empty else do
": "
toHtml str
H.nav $ H.a ! href (toValue indexPage) $ "Index"
H.div ! class_ "container" $ inner
H.footer $ do
"Produced by IdrisDoc version "
toHtml version
where extract (Just ns) = (False, nsName2Str ns)
extract _ = (True, "")
-- | Non-break space character
nbsp :: H.Html
nbsp = preEscapedToHtml (" " :: String)
-- | Returns a list of namespaces already documented in a IdrisDoc directory
existingNamespaces :: FilePath -- ^ The base directory containing the
-- 'docs' directory with existing
-- namespace pages
-> IO (S.Set NsName)
existingNamespaces out = do
let docs = out ++ "/" ++ "docs"
str2Ns s | s == rootNsStr = []
str2Ns s = reverse $ T.splitOn (T.singleton '.') (txt s)
toNs fp = do isFile <- doesFileExist $ docs </> fp
let isHtml = ".html" == takeExtension fp
name = dropExtension fp
ns = str2Ns name
return $ if isFile && isHtml then Just ns else Nothing
docsExists <- doesDirectoryExist docs
if not docsExists
then return S.empty
else do contents <- getDirectoryContents docs
namespaces <- catMaybes `fmap` (sequence $ map toNs contents)
return $ S.fromList namespaces
-- | Copies IdrisDoc dependencies such as stylesheets to a directory
copyDependencies :: FilePath -- ^ The base directory to which
-- dependencies should be written
-> IO ()
copyDependencies dir =
do styles <- getIdrisDataFileByName $ "idrisdoc" </> "styles.css"
copyFile styles (dir </> "styles.css")
| bravit/Idris-dev | src/Idris/IdrisDoc.hs | bsd-3-clause | 30,519 | 0 | 23 | 9,649 | 8,779 | 4,486 | 4,293 | 529 | 19 |
{-# LANGUAGE CPP
, DataKinds
, EmptyCase
, ExistentialQuantification
, FlexibleContexts
, GADTs
, GeneralizedNewtypeDeriving
, KindSignatures
, MultiParamTypeClasses
, OverloadedStrings
, PolyKinds
, ScopedTypeVariables
, TypeFamilies
, TypeOperators
#-}
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
----------------------------------------------------------------
-- 2017.02.01
-- |
-- Module : Language.Hakaru.Syntax.CSE
-- Copyright : Copyright (c) 2016 the Hakaru team
-- License : BSD3
-- Maintainer :
-- Stability : experimental
-- Portability : GHC-only
--
--
----------------------------------------------------------------
module Language.Hakaru.Syntax.CSE (cse) where
import Control.Monad.Reader
import Language.Hakaru.Syntax.ABT
import Language.Hakaru.Syntax.AST
import Language.Hakaru.Syntax.AST.Eq
import Language.Hakaru.Syntax.IClasses
import Language.Hakaru.Syntax.TypeOf
import Language.Hakaru.Types.DataKind
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
-- What we need is an environment like data structure which maps Terms (or
-- general abts?) to other abts. Can such a mapping be implemented efficiently?
-- This would seem to require a hash operation to make efficient.
data EAssoc (abt :: [Hakaru] -> Hakaru -> *)
= forall a . EAssoc !(abt '[] a) !(abt '[] a)
-- An association list for now
newtype Env (abt :: [Hakaru] -> Hakaru -> *) = Env [EAssoc abt]
emptyEnv :: Env a
emptyEnv = Env []
trivial :: (ABT Term abt) => abt '[] a -> Bool
trivial abt = case viewABT abt of
Var _ -> True
Syn (Literal_ _) -> True
_ -> False
-- Attempt to find a new expression in the environment. The lookup is chained
-- to iteratively perform lookup until no match is found, resulting in an
-- equivalence-relation in the environment. This could be made faster with path
-- compression and a more efficient lookup structure.
-- NB: This code could potentially produce an infinite loop depending on how
-- terms are added to the environment. How do we want to prevent this?
lookupEnv
:: forall abt a . (ABT Term abt)
=> abt '[] a
-> Env abt
-> abt '[] a
lookupEnv start (Env env) = go start env
where
go :: abt '[] a -> [EAssoc abt] -> abt '[] a
go ast [] = ast
go ast (EAssoc a b : xs) =
case jmEq1 (typeOf ast) (typeOf a) of
Just Refl | alphaEq ast a -> go b env
_ -> go ast xs
insertEnv
:: forall abt a . (ABT Term abt)
=> abt '[] a
-> abt '[] a
-> Env abt
-> Env abt
insertEnv ast1 ast2 (Env env)
-- Point new variables to the older ones, this does not affect the amount of
-- work done, since ast2 is always a variable. This allows the pass to
-- eliminate redundant variables, as we only eliminate binders during CSE.
| trivial ast1 = Env (EAssoc ast2 ast1 : env)
-- Otherwise map expressions to their binding variables
| otherwise = Env (EAssoc ast1 ast2 : env)
newtype CSE (abt :: [Hakaru] -> Hakaru -> *) a = CSE { runCSE :: Reader (Env abt) a }
deriving (Functor, Applicative, Monad, MonadReader (Env abt))
replaceCSE
:: (ABT Term abt)
=> abt '[] a
-> CSE abt (abt '[] a)
replaceCSE abt = lookupEnv abt `fmap` ask
cse :: forall abt a . (ABT Term abt) => abt '[] a -> abt '[] a
cse abt = runReader (runCSE (cse' abt)) emptyEnv
cse' :: forall abt xs a . (ABT Term abt) => abt xs a -> CSE abt (abt xs a)
cse' = loop . viewABT
where
loop :: View (Term abt) ys a -> CSE abt (abt ys a)
loop (Var v) = cseVar v
loop (Syn s) = cseTerm s
loop (Bind v b) = fmap (bind v) (loop b)
-- Variables can be equivalent to other variables
-- TODO: A good sanity check would be to ensure the result in this case is
-- always a variable or constant. A variable should never be substituted for
-- a more complex expression.
cseVar
:: (ABT Term abt)
=> Variable a
-> CSE abt (abt '[] a)
cseVar = replaceCSE . var
mklet :: ABT Term abt => Variable b -> abt '[] b -> abt '[] a -> abt '[] a
mklet v rhs body = syn (Let_ :$ rhs :* bind v body :* End)
-- Thanks to A-normalization, the only case we need to care about is let bindings.
-- Everything else is just structural recursion.
cseTerm
:: (ABT Term abt)
=> Term abt a
-> CSE abt (abt '[] a)
cseTerm (Let_ :$ rhs :* body :* End) = do
rhs' <- cse' rhs
caseBind body $ \v body' ->
local (insertEnv rhs' (var v)) $
if trivial rhs'
then cse' body'
else fmap (mklet v rhs') (cse' body')
cseTerm term = traverse21 cse' term >>= replaceCSE . syn
| zachsully/hakaru | haskell/Language/Hakaru/Syntax/CSE.hs | bsd-3-clause | 4,858 | 0 | 14 | 1,340 | 1,280 | 670 | 610 | 93 | 3 |
module Proposal229b ((~), (@)) where
(~) :: a -> b -> (a, b)
x ~ y = (x, y)
(@) :: a -> b -> (a, b)
x @ y = (x, y)
r :: ((Bool, Bool), Bool)
r = True ~ False @ True
| sdiehl/ghc | testsuite/tests/parser/should_compile/proposal-229b.hs | bsd-3-clause | 168 | 7 | 10 | 48 | 129 | 74 | 55 | -1 | -1 |
{-# LANGUAGE MagicHash, NoImplicitPrelude, UnboxedTuples #-}
module GHC.PrimopWrappers where
import qualified GHC.Prim
import GHC.Tuple ()
import GHC.Prim (Char#, Int#, Word#, Float#, Double#, Word64#, Int64#, State#, MutableArray#, Array#, SmallMutableArray#, SmallArray#, MutableByteArray#, ByteArray#, Addr#, StablePtr#, MutableArrayArray#, ArrayArray#, MutVar#, RealWorld, TVar#, MVar#, ThreadId#, Weak#, StableName#, BCO#)
{-# NOINLINE gtChar# #-}
gtChar# :: Char# -> Char# -> Int#
gtChar# a1 a2 = (GHC.Prim.gtChar#) a1 a2
{-# NOINLINE geChar# #-}
geChar# :: Char# -> Char# -> Int#
geChar# a1 a2 = (GHC.Prim.geChar#) a1 a2
{-# NOINLINE eqChar# #-}
eqChar# :: Char# -> Char# -> Int#
eqChar# a1 a2 = (GHC.Prim.eqChar#) a1 a2
{-# NOINLINE neChar# #-}
neChar# :: Char# -> Char# -> Int#
neChar# a1 a2 = (GHC.Prim.neChar#) a1 a2
{-# NOINLINE ltChar# #-}
ltChar# :: Char# -> Char# -> Int#
ltChar# a1 a2 = (GHC.Prim.ltChar#) a1 a2
{-# NOINLINE leChar# #-}
leChar# :: Char# -> Char# -> Int#
leChar# a1 a2 = (GHC.Prim.leChar#) a1 a2
{-# NOINLINE ord# #-}
ord# :: Char# -> Int#
ord# a1 = (GHC.Prim.ord#) a1
{-# NOINLINE (+#) #-}
(+#) :: Int# -> Int# -> Int#
(+#) a1 a2 = (GHC.Prim.+#) a1 a2
{-# NOINLINE (-#) #-}
(-#) :: Int# -> Int# -> Int#
(-#) a1 a2 = (GHC.Prim.-#) a1 a2
{-# NOINLINE (*#) #-}
(*#) :: Int# -> Int# -> Int#
(*#) a1 a2 = (GHC.Prim.*#) a1 a2
{-# NOINLINE mulIntMayOflo# #-}
mulIntMayOflo# :: Int# -> Int# -> Int#
mulIntMayOflo# a1 a2 = (GHC.Prim.mulIntMayOflo#) a1 a2
{-# NOINLINE quotInt# #-}
quotInt# :: Int# -> Int# -> Int#
quotInt# a1 a2 = (GHC.Prim.quotInt#) a1 a2
{-# NOINLINE remInt# #-}
remInt# :: Int# -> Int# -> Int#
remInt# a1 a2 = (GHC.Prim.remInt#) a1 a2
{-# NOINLINE quotRemInt# #-}
quotRemInt# :: Int# -> Int# -> (# Int#,Int# #)
quotRemInt# a1 a2 = (GHC.Prim.quotRemInt#) a1 a2
{-# NOINLINE andI# #-}
andI# :: Int# -> Int# -> Int#
andI# a1 a2 = (GHC.Prim.andI#) a1 a2
{-# NOINLINE orI# #-}
orI# :: Int# -> Int# -> Int#
orI# a1 a2 = (GHC.Prim.orI#) a1 a2
{-# NOINLINE xorI# #-}
xorI# :: Int# -> Int# -> Int#
xorI# a1 a2 = (GHC.Prim.xorI#) a1 a2
{-# NOINLINE notI# #-}
notI# :: Int# -> Int#
notI# a1 = (GHC.Prim.notI#) a1
{-# NOINLINE negateInt# #-}
negateInt# :: Int# -> Int#
negateInt# a1 = (GHC.Prim.negateInt#) a1
{-# NOINLINE addIntC# #-}
addIntC# :: Int# -> Int# -> (# Int#,Int# #)
addIntC# a1 a2 = (GHC.Prim.addIntC#) a1 a2
{-# NOINLINE subIntC# #-}
subIntC# :: Int# -> Int# -> (# Int#,Int# #)
subIntC# a1 a2 = (GHC.Prim.subIntC#) a1 a2
{-# NOINLINE (>#) #-}
(>#) :: Int# -> Int# -> Int#
(>#) a1 a2 = (GHC.Prim.>#) a1 a2
{-# NOINLINE (>=#) #-}
(>=#) :: Int# -> Int# -> Int#
(>=#) a1 a2 = (GHC.Prim.>=#) a1 a2
{-# NOINLINE (==#) #-}
(==#) :: Int# -> Int# -> Int#
(==#) a1 a2 = (GHC.Prim.==#) a1 a2
{-# NOINLINE (/=#) #-}
(/=#) :: Int# -> Int# -> Int#
(/=#) a1 a2 = (GHC.Prim./=#) a1 a2
{-# NOINLINE (<#) #-}
(<#) :: Int# -> Int# -> Int#
(<#) a1 a2 = (GHC.Prim.<#) a1 a2
{-# NOINLINE (<=#) #-}
(<=#) :: Int# -> Int# -> Int#
(<=#) a1 a2 = (GHC.Prim.<=#) a1 a2
{-# NOINLINE chr# #-}
chr# :: Int# -> Char#
chr# a1 = (GHC.Prim.chr#) a1
{-# NOINLINE int2Word# #-}
int2Word# :: Int# -> Word#
int2Word# a1 = (GHC.Prim.int2Word#) a1
{-# NOINLINE int2Float# #-}
int2Float# :: Int# -> Float#
int2Float# a1 = (GHC.Prim.int2Float#) a1
{-# NOINLINE int2Double# #-}
int2Double# :: Int# -> Double#
int2Double# a1 = (GHC.Prim.int2Double#) a1
{-# NOINLINE word2Float# #-}
word2Float# :: Word# -> Float#
word2Float# a1 = (GHC.Prim.word2Float#) a1
{-# NOINLINE word2Double# #-}
word2Double# :: Word# -> Double#
word2Double# a1 = (GHC.Prim.word2Double#) a1
{-# NOINLINE uncheckedIShiftL# #-}
uncheckedIShiftL# :: Int# -> Int# -> Int#
uncheckedIShiftL# a1 a2 = (GHC.Prim.uncheckedIShiftL#) a1 a2
{-# NOINLINE uncheckedIShiftRA# #-}
uncheckedIShiftRA# :: Int# -> Int# -> Int#
uncheckedIShiftRA# a1 a2 = (GHC.Prim.uncheckedIShiftRA#) a1 a2
{-# NOINLINE uncheckedIShiftRL# #-}
uncheckedIShiftRL# :: Int# -> Int# -> Int#
uncheckedIShiftRL# a1 a2 = (GHC.Prim.uncheckedIShiftRL#) a1 a2
{-# NOINLINE plusWord# #-}
plusWord# :: Word# -> Word# -> Word#
plusWord# a1 a2 = (GHC.Prim.plusWord#) a1 a2
{-# NOINLINE plusWord2# #-}
plusWord2# :: Word# -> Word# -> (# Word#,Word# #)
plusWord2# a1 a2 = (GHC.Prim.plusWord2#) a1 a2
{-# NOINLINE minusWord# #-}
minusWord# :: Word# -> Word# -> Word#
minusWord# a1 a2 = (GHC.Prim.minusWord#) a1 a2
{-# NOINLINE timesWord# #-}
timesWord# :: Word# -> Word# -> Word#
timesWord# a1 a2 = (GHC.Prim.timesWord#) a1 a2
{-# NOINLINE timesWord2# #-}
timesWord2# :: Word# -> Word# -> (# Word#,Word# #)
timesWord2# a1 a2 = (GHC.Prim.timesWord2#) a1 a2
{-# NOINLINE quotWord# #-}
quotWord# :: Word# -> Word# -> Word#
quotWord# a1 a2 = (GHC.Prim.quotWord#) a1 a2
{-# NOINLINE remWord# #-}
remWord# :: Word# -> Word# -> Word#
remWord# a1 a2 = (GHC.Prim.remWord#) a1 a2
{-# NOINLINE quotRemWord# #-}
quotRemWord# :: Word# -> Word# -> (# Word#,Word# #)
quotRemWord# a1 a2 = (GHC.Prim.quotRemWord#) a1 a2
{-# NOINLINE quotRemWord2# #-}
quotRemWord2# :: Word# -> Word# -> Word# -> (# Word#,Word# #)
quotRemWord2# a1 a2 a3 = (GHC.Prim.quotRemWord2#) a1 a2 a3
{-# NOINLINE and# #-}
and# :: Word# -> Word# -> Word#
and# a1 a2 = (GHC.Prim.and#) a1 a2
{-# NOINLINE or# #-}
or# :: Word# -> Word# -> Word#
or# a1 a2 = (GHC.Prim.or#) a1 a2
{-# NOINLINE xor# #-}
xor# :: Word# -> Word# -> Word#
xor# a1 a2 = (GHC.Prim.xor#) a1 a2
{-# NOINLINE not# #-}
not# :: Word# -> Word#
not# a1 = (GHC.Prim.not#) a1
{-# NOINLINE uncheckedShiftL# #-}
uncheckedShiftL# :: Word# -> Int# -> Word#
uncheckedShiftL# a1 a2 = (GHC.Prim.uncheckedShiftL#) a1 a2
{-# NOINLINE uncheckedShiftRL# #-}
uncheckedShiftRL# :: Word# -> Int# -> Word#
uncheckedShiftRL# a1 a2 = (GHC.Prim.uncheckedShiftRL#) a1 a2
{-# NOINLINE word2Int# #-}
word2Int# :: Word# -> Int#
word2Int# a1 = (GHC.Prim.word2Int#) a1
{-# NOINLINE gtWord# #-}
gtWord# :: Word# -> Word# -> Int#
gtWord# a1 a2 = (GHC.Prim.gtWord#) a1 a2
{-# NOINLINE geWord# #-}
geWord# :: Word# -> Word# -> Int#
geWord# a1 a2 = (GHC.Prim.geWord#) a1 a2
{-# NOINLINE eqWord# #-}
eqWord# :: Word# -> Word# -> Int#
eqWord# a1 a2 = (GHC.Prim.eqWord#) a1 a2
{-# NOINLINE neWord# #-}
neWord# :: Word# -> Word# -> Int#
neWord# a1 a2 = (GHC.Prim.neWord#) a1 a2
{-# NOINLINE ltWord# #-}
ltWord# :: Word# -> Word# -> Int#
ltWord# a1 a2 = (GHC.Prim.ltWord#) a1 a2
{-# NOINLINE leWord# #-}
leWord# :: Word# -> Word# -> Int#
leWord# a1 a2 = (GHC.Prim.leWord#) a1 a2
{-# NOINLINE popCnt8# #-}
popCnt8# :: Word# -> Word#
popCnt8# a1 = (GHC.Prim.popCnt8#) a1
{-# NOINLINE popCnt16# #-}
popCnt16# :: Word# -> Word#
popCnt16# a1 = (GHC.Prim.popCnt16#) a1
{-# NOINLINE popCnt32# #-}
popCnt32# :: Word# -> Word#
popCnt32# a1 = (GHC.Prim.popCnt32#) a1
{-# NOINLINE popCnt64# #-}
popCnt64# :: Word64# -> Word#
popCnt64# a1 = (GHC.Prim.popCnt64#) a1
{-# NOINLINE popCnt# #-}
popCnt# :: Word# -> Word#
popCnt# a1 = (GHC.Prim.popCnt#) a1
{-# NOINLINE clz8# #-}
clz8# :: Word# -> Word#
clz8# a1 = (GHC.Prim.clz8#) a1
{-# NOINLINE clz16# #-}
clz16# :: Word# -> Word#
clz16# a1 = (GHC.Prim.clz16#) a1
{-# NOINLINE clz32# #-}
clz32# :: Word# -> Word#
clz32# a1 = (GHC.Prim.clz32#) a1
{-# NOINLINE clz64# #-}
clz64# :: Word64# -> Word#
clz64# a1 = (GHC.Prim.clz64#) a1
{-# NOINLINE clz# #-}
clz# :: Word# -> Word#
clz# a1 = (GHC.Prim.clz#) a1
{-# NOINLINE ctz8# #-}
ctz8# :: Word# -> Word#
ctz8# a1 = (GHC.Prim.ctz8#) a1
{-# NOINLINE ctz16# #-}
ctz16# :: Word# -> Word#
ctz16# a1 = (GHC.Prim.ctz16#) a1
{-# NOINLINE ctz32# #-}
ctz32# :: Word# -> Word#
ctz32# a1 = (GHC.Prim.ctz32#) a1
{-# NOINLINE ctz64# #-}
ctz64# :: Word64# -> Word#
ctz64# a1 = (GHC.Prim.ctz64#) a1
{-# NOINLINE ctz# #-}
ctz# :: Word# -> Word#
ctz# a1 = (GHC.Prim.ctz#) a1
{-# NOINLINE byteSwap16# #-}
byteSwap16# :: Word# -> Word#
byteSwap16# a1 = (GHC.Prim.byteSwap16#) a1
{-# NOINLINE byteSwap32# #-}
byteSwap32# :: Word# -> Word#
byteSwap32# a1 = (GHC.Prim.byteSwap32#) a1
{-# NOINLINE byteSwap64# #-}
byteSwap64# :: Word64# -> Word64#
byteSwap64# a1 = (GHC.Prim.byteSwap64#) a1
{-# NOINLINE byteSwap# #-}
byteSwap# :: Word# -> Word#
byteSwap# a1 = (GHC.Prim.byteSwap#) a1
{-# NOINLINE narrow8Int# #-}
narrow8Int# :: Int# -> Int#
narrow8Int# a1 = (GHC.Prim.narrow8Int#) a1
{-# NOINLINE narrow16Int# #-}
narrow16Int# :: Int# -> Int#
narrow16Int# a1 = (GHC.Prim.narrow16Int#) a1
{-# NOINLINE narrow32Int# #-}
narrow32Int# :: Int# -> Int#
narrow32Int# a1 = (GHC.Prim.narrow32Int#) a1
{-# NOINLINE narrow8Word# #-}
narrow8Word# :: Word# -> Word#
narrow8Word# a1 = (GHC.Prim.narrow8Word#) a1
{-# NOINLINE narrow16Word# #-}
narrow16Word# :: Word# -> Word#
narrow16Word# a1 = (GHC.Prim.narrow16Word#) a1
{-# NOINLINE narrow32Word# #-}
narrow32Word# :: Word# -> Word#
narrow32Word# a1 = (GHC.Prim.narrow32Word#) a1
{-# NOINLINE (>##) #-}
(>##) :: Double# -> Double# -> Int#
(>##) a1 a2 = (GHC.Prim.>##) a1 a2
{-# NOINLINE (>=##) #-}
(>=##) :: Double# -> Double# -> Int#
(>=##) a1 a2 = (GHC.Prim.>=##) a1 a2
{-# NOINLINE (==##) #-}
(==##) :: Double# -> Double# -> Int#
(==##) a1 a2 = (GHC.Prim.==##) a1 a2
{-# NOINLINE (/=##) #-}
(/=##) :: Double# -> Double# -> Int#
(/=##) a1 a2 = (GHC.Prim./=##) a1 a2
{-# NOINLINE (<##) #-}
(<##) :: Double# -> Double# -> Int#
(<##) a1 a2 = (GHC.Prim.<##) a1 a2
{-# NOINLINE (<=##) #-}
(<=##) :: Double# -> Double# -> Int#
(<=##) a1 a2 = (GHC.Prim.<=##) a1 a2
{-# NOINLINE (+##) #-}
(+##) :: Double# -> Double# -> Double#
(+##) a1 a2 = (GHC.Prim.+##) a1 a2
{-# NOINLINE (-##) #-}
(-##) :: Double# -> Double# -> Double#
(-##) a1 a2 = (GHC.Prim.-##) a1 a2
{-# NOINLINE (*##) #-}
(*##) :: Double# -> Double# -> Double#
(*##) a1 a2 = (GHC.Prim.*##) a1 a2
{-# NOINLINE (/##) #-}
(/##) :: Double# -> Double# -> Double#
(/##) a1 a2 = (GHC.Prim./##) a1 a2
{-# NOINLINE negateDouble# #-}
negateDouble# :: Double# -> Double#
negateDouble# a1 = (GHC.Prim.negateDouble#) a1
{-# NOINLINE double2Int# #-}
double2Int# :: Double# -> Int#
double2Int# a1 = (GHC.Prim.double2Int#) a1
{-# NOINLINE double2Float# #-}
double2Float# :: Double# -> Float#
double2Float# a1 = (GHC.Prim.double2Float#) a1
{-# NOINLINE expDouble# #-}
expDouble# :: Double# -> Double#
expDouble# a1 = (GHC.Prim.expDouble#) a1
{-# NOINLINE logDouble# #-}
logDouble# :: Double# -> Double#
logDouble# a1 = (GHC.Prim.logDouble#) a1
{-# NOINLINE sqrtDouble# #-}
sqrtDouble# :: Double# -> Double#
sqrtDouble# a1 = (GHC.Prim.sqrtDouble#) a1
{-# NOINLINE sinDouble# #-}
sinDouble# :: Double# -> Double#
sinDouble# a1 = (GHC.Prim.sinDouble#) a1
{-# NOINLINE cosDouble# #-}
cosDouble# :: Double# -> Double#
cosDouble# a1 = (GHC.Prim.cosDouble#) a1
{-# NOINLINE tanDouble# #-}
tanDouble# :: Double# -> Double#
tanDouble# a1 = (GHC.Prim.tanDouble#) a1
{-# NOINLINE asinDouble# #-}
asinDouble# :: Double# -> Double#
asinDouble# a1 = (GHC.Prim.asinDouble#) a1
{-# NOINLINE acosDouble# #-}
acosDouble# :: Double# -> Double#
acosDouble# a1 = (GHC.Prim.acosDouble#) a1
{-# NOINLINE atanDouble# #-}
atanDouble# :: Double# -> Double#
atanDouble# a1 = (GHC.Prim.atanDouble#) a1
{-# NOINLINE sinhDouble# #-}
sinhDouble# :: Double# -> Double#
sinhDouble# a1 = (GHC.Prim.sinhDouble#) a1
{-# NOINLINE coshDouble# #-}
coshDouble# :: Double# -> Double#
coshDouble# a1 = (GHC.Prim.coshDouble#) a1
{-# NOINLINE tanhDouble# #-}
tanhDouble# :: Double# -> Double#
tanhDouble# a1 = (GHC.Prim.tanhDouble#) a1
{-# NOINLINE (**##) #-}
(**##) :: Double# -> Double# -> Double#
(**##) a1 a2 = (GHC.Prim.**##) a1 a2
{-# NOINLINE decodeDouble_2Int# #-}
decodeDouble_2Int# :: Double# -> (# Int#,Word#,Word#,Int# #)
decodeDouble_2Int# a1 = (GHC.Prim.decodeDouble_2Int#) a1
{-# NOINLINE decodeDouble_Int64# #-}
decodeDouble_Int64# :: Double# -> (# Int64#,Int# #)
decodeDouble_Int64# a1 = (GHC.Prim.decodeDouble_Int64#) a1
{-# NOINLINE gtFloat# #-}
gtFloat# :: Float# -> Float# -> Int#
gtFloat# a1 a2 = (GHC.Prim.gtFloat#) a1 a2
{-# NOINLINE geFloat# #-}
geFloat# :: Float# -> Float# -> Int#
geFloat# a1 a2 = (GHC.Prim.geFloat#) a1 a2
{-# NOINLINE eqFloat# #-}
eqFloat# :: Float# -> Float# -> Int#
eqFloat# a1 a2 = (GHC.Prim.eqFloat#) a1 a2
{-# NOINLINE neFloat# #-}
neFloat# :: Float# -> Float# -> Int#
neFloat# a1 a2 = (GHC.Prim.neFloat#) a1 a2
{-# NOINLINE ltFloat# #-}
ltFloat# :: Float# -> Float# -> Int#
ltFloat# a1 a2 = (GHC.Prim.ltFloat#) a1 a2
{-# NOINLINE leFloat# #-}
leFloat# :: Float# -> Float# -> Int#
leFloat# a1 a2 = (GHC.Prim.leFloat#) a1 a2
{-# NOINLINE plusFloat# #-}
plusFloat# :: Float# -> Float# -> Float#
plusFloat# a1 a2 = (GHC.Prim.plusFloat#) a1 a2
{-# NOINLINE minusFloat# #-}
minusFloat# :: Float# -> Float# -> Float#
minusFloat# a1 a2 = (GHC.Prim.minusFloat#) a1 a2
{-# NOINLINE timesFloat# #-}
timesFloat# :: Float# -> Float# -> Float#
timesFloat# a1 a2 = (GHC.Prim.timesFloat#) a1 a2
{-# NOINLINE divideFloat# #-}
divideFloat# :: Float# -> Float# -> Float#
divideFloat# a1 a2 = (GHC.Prim.divideFloat#) a1 a2
{-# NOINLINE negateFloat# #-}
negateFloat# :: Float# -> Float#
negateFloat# a1 = (GHC.Prim.negateFloat#) a1
{-# NOINLINE float2Int# #-}
float2Int# :: Float# -> Int#
float2Int# a1 = (GHC.Prim.float2Int#) a1
{-# NOINLINE expFloat# #-}
expFloat# :: Float# -> Float#
expFloat# a1 = (GHC.Prim.expFloat#) a1
{-# NOINLINE logFloat# #-}
logFloat# :: Float# -> Float#
logFloat# a1 = (GHC.Prim.logFloat#) a1
{-# NOINLINE sqrtFloat# #-}
sqrtFloat# :: Float# -> Float#
sqrtFloat# a1 = (GHC.Prim.sqrtFloat#) a1
{-# NOINLINE sinFloat# #-}
sinFloat# :: Float# -> Float#
sinFloat# a1 = (GHC.Prim.sinFloat#) a1
{-# NOINLINE cosFloat# #-}
cosFloat# :: Float# -> Float#
cosFloat# a1 = (GHC.Prim.cosFloat#) a1
{-# NOINLINE tanFloat# #-}
tanFloat# :: Float# -> Float#
tanFloat# a1 = (GHC.Prim.tanFloat#) a1
{-# NOINLINE asinFloat# #-}
asinFloat# :: Float# -> Float#
asinFloat# a1 = (GHC.Prim.asinFloat#) a1
{-# NOINLINE acosFloat# #-}
acosFloat# :: Float# -> Float#
acosFloat# a1 = (GHC.Prim.acosFloat#) a1
{-# NOINLINE atanFloat# #-}
atanFloat# :: Float# -> Float#
atanFloat# a1 = (GHC.Prim.atanFloat#) a1
{-# NOINLINE sinhFloat# #-}
sinhFloat# :: Float# -> Float#
sinhFloat# a1 = (GHC.Prim.sinhFloat#) a1
{-# NOINLINE coshFloat# #-}
coshFloat# :: Float# -> Float#
coshFloat# a1 = (GHC.Prim.coshFloat#) a1
{-# NOINLINE tanhFloat# #-}
tanhFloat# :: Float# -> Float#
tanhFloat# a1 = (GHC.Prim.tanhFloat#) a1
{-# NOINLINE powerFloat# #-}
powerFloat# :: Float# -> Float# -> Float#
powerFloat# a1 a2 = (GHC.Prim.powerFloat#) a1 a2
{-# NOINLINE float2Double# #-}
float2Double# :: Float# -> Double#
float2Double# a1 = (GHC.Prim.float2Double#) a1
{-# NOINLINE decodeFloat_Int# #-}
decodeFloat_Int# :: Float# -> (# Int#,Int# #)
decodeFloat_Int# a1 = (GHC.Prim.decodeFloat_Int#) a1
{-# NOINLINE newArray# #-}
newArray# :: Int# -> a -> State# s -> (# State# s,MutableArray# s a #)
newArray# a1 a2 a3 = (GHC.Prim.newArray#) a1 a2 a3
{-# NOINLINE sameMutableArray# #-}
sameMutableArray# :: MutableArray# s a -> MutableArray# s a -> Int#
sameMutableArray# a1 a2 = (GHC.Prim.sameMutableArray#) a1 a2
{-# NOINLINE readArray# #-}
readArray# :: MutableArray# s a -> Int# -> State# s -> (# State# s,a #)
readArray# a1 a2 a3 = (GHC.Prim.readArray#) a1 a2 a3
{-# NOINLINE writeArray# #-}
writeArray# :: MutableArray# s a -> Int# -> a -> State# s -> State# s
writeArray# a1 a2 a3 a4 = (GHC.Prim.writeArray#) a1 a2 a3 a4
{-# NOINLINE sizeofArray# #-}
sizeofArray# :: Array# a -> Int#
sizeofArray# a1 = (GHC.Prim.sizeofArray#) a1
{-# NOINLINE sizeofMutableArray# #-}
sizeofMutableArray# :: MutableArray# s a -> Int#
sizeofMutableArray# a1 = (GHC.Prim.sizeofMutableArray#) a1
{-# NOINLINE indexArray# #-}
indexArray# :: Array# a -> Int# -> (# a #)
indexArray# a1 a2 = (GHC.Prim.indexArray#) a1 a2
{-# NOINLINE unsafeFreezeArray# #-}
unsafeFreezeArray# :: MutableArray# s a -> State# s -> (# State# s,Array# a #)
unsafeFreezeArray# a1 a2 = (GHC.Prim.unsafeFreezeArray#) a1 a2
{-# NOINLINE unsafeThawArray# #-}
unsafeThawArray# :: Array# a -> State# s -> (# State# s,MutableArray# s a #)
unsafeThawArray# a1 a2 = (GHC.Prim.unsafeThawArray#) a1 a2
{-# NOINLINE copyArray# #-}
copyArray# :: Array# a -> Int# -> MutableArray# s a -> Int# -> Int# -> State# s -> State# s
copyArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copyArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE copyMutableArray# #-}
copyMutableArray# :: MutableArray# s a -> Int# -> MutableArray# s a -> Int# -> Int# -> State# s -> State# s
copyMutableArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copyMutableArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE cloneArray# #-}
cloneArray# :: Array# a -> Int# -> Int# -> Array# a
cloneArray# a1 a2 a3 = (GHC.Prim.cloneArray#) a1 a2 a3
{-# NOINLINE cloneMutableArray# #-}
cloneMutableArray# :: MutableArray# s a -> Int# -> Int# -> State# s -> (# State# s,MutableArray# s a #)
cloneMutableArray# a1 a2 a3 a4 = (GHC.Prim.cloneMutableArray#) a1 a2 a3 a4
{-# NOINLINE freezeArray# #-}
freezeArray# :: MutableArray# s a -> Int# -> Int# -> State# s -> (# State# s,Array# a #)
freezeArray# a1 a2 a3 a4 = (GHC.Prim.freezeArray#) a1 a2 a3 a4
{-# NOINLINE thawArray# #-}
thawArray# :: Array# a -> Int# -> Int# -> State# s -> (# State# s,MutableArray# s a #)
thawArray# a1 a2 a3 a4 = (GHC.Prim.thawArray#) a1 a2 a3 a4
{-# NOINLINE casArray# #-}
casArray# :: MutableArray# s a -> Int# -> a -> a -> State# s -> (# State# s,Int#,a #)
casArray# a1 a2 a3 a4 a5 = (GHC.Prim.casArray#) a1 a2 a3 a4 a5
{-# NOINLINE newSmallArray# #-}
newSmallArray# :: Int# -> a -> State# s -> (# State# s,SmallMutableArray# s a #)
newSmallArray# a1 a2 a3 = (GHC.Prim.newSmallArray#) a1 a2 a3
{-# NOINLINE sameSmallMutableArray# #-}
sameSmallMutableArray# :: SmallMutableArray# s a -> SmallMutableArray# s a -> Int#
sameSmallMutableArray# a1 a2 = (GHC.Prim.sameSmallMutableArray#) a1 a2
{-# NOINLINE readSmallArray# #-}
readSmallArray# :: SmallMutableArray# s a -> Int# -> State# s -> (# State# s,a #)
readSmallArray# a1 a2 a3 = (GHC.Prim.readSmallArray#) a1 a2 a3
{-# NOINLINE writeSmallArray# #-}
writeSmallArray# :: SmallMutableArray# s a -> Int# -> a -> State# s -> State# s
writeSmallArray# a1 a2 a3 a4 = (GHC.Prim.writeSmallArray#) a1 a2 a3 a4
{-# NOINLINE sizeofSmallArray# #-}
sizeofSmallArray# :: SmallArray# a -> Int#
sizeofSmallArray# a1 = (GHC.Prim.sizeofSmallArray#) a1
{-# NOINLINE sizeofSmallMutableArray# #-}
sizeofSmallMutableArray# :: SmallMutableArray# s a -> Int#
sizeofSmallMutableArray# a1 = (GHC.Prim.sizeofSmallMutableArray#) a1
{-# NOINLINE indexSmallArray# #-}
indexSmallArray# :: SmallArray# a -> Int# -> (# a #)
indexSmallArray# a1 a2 = (GHC.Prim.indexSmallArray#) a1 a2
{-# NOINLINE unsafeFreezeSmallArray# #-}
unsafeFreezeSmallArray# :: SmallMutableArray# s a -> State# s -> (# State# s,SmallArray# a #)
unsafeFreezeSmallArray# a1 a2 = (GHC.Prim.unsafeFreezeSmallArray#) a1 a2
{-# NOINLINE unsafeThawSmallArray# #-}
unsafeThawSmallArray# :: SmallArray# a -> State# s -> (# State# s,SmallMutableArray# s a #)
unsafeThawSmallArray# a1 a2 = (GHC.Prim.unsafeThawSmallArray#) a1 a2
{-# NOINLINE copySmallArray# #-}
copySmallArray# :: SmallArray# a -> Int# -> SmallMutableArray# s a -> Int# -> Int# -> State# s -> State# s
copySmallArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copySmallArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE copySmallMutableArray# #-}
copySmallMutableArray# :: SmallMutableArray# s a -> Int# -> SmallMutableArray# s a -> Int# -> Int# -> State# s -> State# s
copySmallMutableArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copySmallMutableArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE cloneSmallArray# #-}
cloneSmallArray# :: SmallArray# a -> Int# -> Int# -> SmallArray# a
cloneSmallArray# a1 a2 a3 = (GHC.Prim.cloneSmallArray#) a1 a2 a3
{-# NOINLINE cloneSmallMutableArray# #-}
cloneSmallMutableArray# :: SmallMutableArray# s a -> Int# -> Int# -> State# s -> (# State# s,SmallMutableArray# s a #)
cloneSmallMutableArray# a1 a2 a3 a4 = (GHC.Prim.cloneSmallMutableArray#) a1 a2 a3 a4
{-# NOINLINE freezeSmallArray# #-}
freezeSmallArray# :: SmallMutableArray# s a -> Int# -> Int# -> State# s -> (# State# s,SmallArray# a #)
freezeSmallArray# a1 a2 a3 a4 = (GHC.Prim.freezeSmallArray#) a1 a2 a3 a4
{-# NOINLINE thawSmallArray# #-}
thawSmallArray# :: SmallArray# a -> Int# -> Int# -> State# s -> (# State# s,SmallMutableArray# s a #)
thawSmallArray# a1 a2 a3 a4 = (GHC.Prim.thawSmallArray#) a1 a2 a3 a4
{-# NOINLINE casSmallArray# #-}
casSmallArray# :: SmallMutableArray# s a -> Int# -> a -> a -> State# s -> (# State# s,Int#,a #)
casSmallArray# a1 a2 a3 a4 a5 = (GHC.Prim.casSmallArray#) a1 a2 a3 a4 a5
{-# NOINLINE newByteArray# #-}
newByteArray# :: Int# -> State# s -> (# State# s,MutableByteArray# s #)
newByteArray# a1 a2 = (GHC.Prim.newByteArray#) a1 a2
{-# NOINLINE newPinnedByteArray# #-}
newPinnedByteArray# :: Int# -> State# s -> (# State# s,MutableByteArray# s #)
newPinnedByteArray# a1 a2 = (GHC.Prim.newPinnedByteArray#) a1 a2
{-# NOINLINE newAlignedPinnedByteArray# #-}
newAlignedPinnedByteArray# :: Int# -> Int# -> State# s -> (# State# s,MutableByteArray# s #)
newAlignedPinnedByteArray# a1 a2 a3 = (GHC.Prim.newAlignedPinnedByteArray#) a1 a2 a3
{-# NOINLINE byteArrayContents# #-}
byteArrayContents# :: ByteArray# -> Addr#
byteArrayContents# a1 = (GHC.Prim.byteArrayContents#) a1
{-# NOINLINE sameMutableByteArray# #-}
sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Int#
sameMutableByteArray# a1 a2 = (GHC.Prim.sameMutableByteArray#) a1 a2
{-# NOINLINE shrinkMutableByteArray# #-}
shrinkMutableByteArray# :: MutableByteArray# s -> Int# -> State# s -> State# s
shrinkMutableByteArray# a1 a2 a3 = (GHC.Prim.shrinkMutableByteArray#) a1 a2 a3
{-# NOINLINE resizeMutableByteArray# #-}
resizeMutableByteArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,MutableByteArray# s #)
resizeMutableByteArray# a1 a2 a3 = (GHC.Prim.resizeMutableByteArray#) a1 a2 a3
{-# NOINLINE unsafeFreezeByteArray# #-}
unsafeFreezeByteArray# :: MutableByteArray# s -> State# s -> (# State# s,ByteArray# #)
unsafeFreezeByteArray# a1 a2 = (GHC.Prim.unsafeFreezeByteArray#) a1 a2
{-# NOINLINE sizeofByteArray# #-}
sizeofByteArray# :: ByteArray# -> Int#
sizeofByteArray# a1 = (GHC.Prim.sizeofByteArray#) a1
{-# NOINLINE sizeofMutableByteArray# #-}
sizeofMutableByteArray# :: MutableByteArray# s -> Int#
sizeofMutableByteArray# a1 = (GHC.Prim.sizeofMutableByteArray#) a1
{-# NOINLINE indexCharArray# #-}
indexCharArray# :: ByteArray# -> Int# -> Char#
indexCharArray# a1 a2 = (GHC.Prim.indexCharArray#) a1 a2
{-# NOINLINE indexWideCharArray# #-}
indexWideCharArray# :: ByteArray# -> Int# -> Char#
indexWideCharArray# a1 a2 = (GHC.Prim.indexWideCharArray#) a1 a2
{-# NOINLINE indexIntArray# #-}
indexIntArray# :: ByteArray# -> Int# -> Int#
indexIntArray# a1 a2 = (GHC.Prim.indexIntArray#) a1 a2
{-# NOINLINE indexWordArray# #-}
indexWordArray# :: ByteArray# -> Int# -> Word#
indexWordArray# a1 a2 = (GHC.Prim.indexWordArray#) a1 a2
{-# NOINLINE indexAddrArray# #-}
indexAddrArray# :: ByteArray# -> Int# -> Addr#
indexAddrArray# a1 a2 = (GHC.Prim.indexAddrArray#) a1 a2
{-# NOINLINE indexFloatArray# #-}
indexFloatArray# :: ByteArray# -> Int# -> Float#
indexFloatArray# a1 a2 = (GHC.Prim.indexFloatArray#) a1 a2
{-# NOINLINE indexDoubleArray# #-}
indexDoubleArray# :: ByteArray# -> Int# -> Double#
indexDoubleArray# a1 a2 = (GHC.Prim.indexDoubleArray#) a1 a2
{-# NOINLINE indexStablePtrArray# #-}
indexStablePtrArray# :: ByteArray# -> Int# -> StablePtr# a
indexStablePtrArray# a1 a2 = (GHC.Prim.indexStablePtrArray#) a1 a2
{-# NOINLINE indexInt8Array# #-}
indexInt8Array# :: ByteArray# -> Int# -> Int#
indexInt8Array# a1 a2 = (GHC.Prim.indexInt8Array#) a1 a2
{-# NOINLINE indexInt16Array# #-}
indexInt16Array# :: ByteArray# -> Int# -> Int#
indexInt16Array# a1 a2 = (GHC.Prim.indexInt16Array#) a1 a2
{-# NOINLINE indexInt32Array# #-}
indexInt32Array# :: ByteArray# -> Int# -> Int#
indexInt32Array# a1 a2 = (GHC.Prim.indexInt32Array#) a1 a2
{-# NOINLINE indexInt64Array# #-}
indexInt64Array# :: ByteArray# -> Int# -> Int64#
indexInt64Array# a1 a2 = (GHC.Prim.indexInt64Array#) a1 a2
{-# NOINLINE indexWord8Array# #-}
indexWord8Array# :: ByteArray# -> Int# -> Word#
indexWord8Array# a1 a2 = (GHC.Prim.indexWord8Array#) a1 a2
{-# NOINLINE indexWord16Array# #-}
indexWord16Array# :: ByteArray# -> Int# -> Word#
indexWord16Array# a1 a2 = (GHC.Prim.indexWord16Array#) a1 a2
{-# NOINLINE indexWord32Array# #-}
indexWord32Array# :: ByteArray# -> Int# -> Word#
indexWord32Array# a1 a2 = (GHC.Prim.indexWord32Array#) a1 a2
{-# NOINLINE indexWord64Array# #-}
indexWord64Array# :: ByteArray# -> Int# -> Word64#
indexWord64Array# a1 a2 = (GHC.Prim.indexWord64Array#) a1 a2
{-# NOINLINE readCharArray# #-}
readCharArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Char# #)
readCharArray# a1 a2 a3 = (GHC.Prim.readCharArray#) a1 a2 a3
{-# NOINLINE readWideCharArray# #-}
readWideCharArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Char# #)
readWideCharArray# a1 a2 a3 = (GHC.Prim.readWideCharArray#) a1 a2 a3
{-# NOINLINE readIntArray# #-}
readIntArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Int# #)
readIntArray# a1 a2 a3 = (GHC.Prim.readIntArray#) a1 a2 a3
{-# NOINLINE readWordArray# #-}
readWordArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Word# #)
readWordArray# a1 a2 a3 = (GHC.Prim.readWordArray#) a1 a2 a3
{-# NOINLINE readAddrArray# #-}
readAddrArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Addr# #)
readAddrArray# a1 a2 a3 = (GHC.Prim.readAddrArray#) a1 a2 a3
{-# NOINLINE readFloatArray# #-}
readFloatArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Float# #)
readFloatArray# a1 a2 a3 = (GHC.Prim.readFloatArray#) a1 a2 a3
{-# NOINLINE readDoubleArray# #-}
readDoubleArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Double# #)
readDoubleArray# a1 a2 a3 = (GHC.Prim.readDoubleArray#) a1 a2 a3
{-# NOINLINE readStablePtrArray# #-}
readStablePtrArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,StablePtr# a #)
readStablePtrArray# a1 a2 a3 = (GHC.Prim.readStablePtrArray#) a1 a2 a3
{-# NOINLINE readInt8Array# #-}
readInt8Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Int# #)
readInt8Array# a1 a2 a3 = (GHC.Prim.readInt8Array#) a1 a2 a3
{-# NOINLINE readInt16Array# #-}
readInt16Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Int# #)
readInt16Array# a1 a2 a3 = (GHC.Prim.readInt16Array#) a1 a2 a3
{-# NOINLINE readInt32Array# #-}
readInt32Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Int# #)
readInt32Array# a1 a2 a3 = (GHC.Prim.readInt32Array#) a1 a2 a3
{-# NOINLINE readInt64Array# #-}
readInt64Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Int64# #)
readInt64Array# a1 a2 a3 = (GHC.Prim.readInt64Array#) a1 a2 a3
{-# NOINLINE readWord8Array# #-}
readWord8Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Word# #)
readWord8Array# a1 a2 a3 = (GHC.Prim.readWord8Array#) a1 a2 a3
{-# NOINLINE readWord16Array# #-}
readWord16Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Word# #)
readWord16Array# a1 a2 a3 = (GHC.Prim.readWord16Array#) a1 a2 a3
{-# NOINLINE readWord32Array# #-}
readWord32Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Word# #)
readWord32Array# a1 a2 a3 = (GHC.Prim.readWord32Array#) a1 a2 a3
{-# NOINLINE readWord64Array# #-}
readWord64Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Word64# #)
readWord64Array# a1 a2 a3 = (GHC.Prim.readWord64Array#) a1 a2 a3
{-# NOINLINE writeCharArray# #-}
writeCharArray# :: MutableByteArray# s -> Int# -> Char# -> State# s -> State# s
writeCharArray# a1 a2 a3 a4 = (GHC.Prim.writeCharArray#) a1 a2 a3 a4
{-# NOINLINE writeWideCharArray# #-}
writeWideCharArray# :: MutableByteArray# s -> Int# -> Char# -> State# s -> State# s
writeWideCharArray# a1 a2 a3 a4 = (GHC.Prim.writeWideCharArray#) a1 a2 a3 a4
{-# NOINLINE writeIntArray# #-}
writeIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
writeIntArray# a1 a2 a3 a4 = (GHC.Prim.writeIntArray#) a1 a2 a3 a4
{-# NOINLINE writeWordArray# #-}
writeWordArray# :: MutableByteArray# s -> Int# -> Word# -> State# s -> State# s
writeWordArray# a1 a2 a3 a4 = (GHC.Prim.writeWordArray#) a1 a2 a3 a4
{-# NOINLINE writeAddrArray# #-}
writeAddrArray# :: MutableByteArray# s -> Int# -> Addr# -> State# s -> State# s
writeAddrArray# a1 a2 a3 a4 = (GHC.Prim.writeAddrArray#) a1 a2 a3 a4
{-# NOINLINE writeFloatArray# #-}
writeFloatArray# :: MutableByteArray# s -> Int# -> Float# -> State# s -> State# s
writeFloatArray# a1 a2 a3 a4 = (GHC.Prim.writeFloatArray#) a1 a2 a3 a4
{-# NOINLINE writeDoubleArray# #-}
writeDoubleArray# :: MutableByteArray# s -> Int# -> Double# -> State# s -> State# s
writeDoubleArray# a1 a2 a3 a4 = (GHC.Prim.writeDoubleArray#) a1 a2 a3 a4
{-# NOINLINE writeStablePtrArray# #-}
writeStablePtrArray# :: MutableByteArray# s -> Int# -> StablePtr# a -> State# s -> State# s
writeStablePtrArray# a1 a2 a3 a4 = (GHC.Prim.writeStablePtrArray#) a1 a2 a3 a4
{-# NOINLINE writeInt8Array# #-}
writeInt8Array# :: MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
writeInt8Array# a1 a2 a3 a4 = (GHC.Prim.writeInt8Array#) a1 a2 a3 a4
{-# NOINLINE writeInt16Array# #-}
writeInt16Array# :: MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
writeInt16Array# a1 a2 a3 a4 = (GHC.Prim.writeInt16Array#) a1 a2 a3 a4
{-# NOINLINE writeInt32Array# #-}
writeInt32Array# :: MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
writeInt32Array# a1 a2 a3 a4 = (GHC.Prim.writeInt32Array#) a1 a2 a3 a4
{-# NOINLINE writeInt64Array# #-}
writeInt64Array# :: MutableByteArray# s -> Int# -> Int64# -> State# s -> State# s
writeInt64Array# a1 a2 a3 a4 = (GHC.Prim.writeInt64Array#) a1 a2 a3 a4
{-# NOINLINE writeWord8Array# #-}
writeWord8Array# :: MutableByteArray# s -> Int# -> Word# -> State# s -> State# s
writeWord8Array# a1 a2 a3 a4 = (GHC.Prim.writeWord8Array#) a1 a2 a3 a4
{-# NOINLINE writeWord16Array# #-}
writeWord16Array# :: MutableByteArray# s -> Int# -> Word# -> State# s -> State# s
writeWord16Array# a1 a2 a3 a4 = (GHC.Prim.writeWord16Array#) a1 a2 a3 a4
{-# NOINLINE writeWord32Array# #-}
writeWord32Array# :: MutableByteArray# s -> Int# -> Word# -> State# s -> State# s
writeWord32Array# a1 a2 a3 a4 = (GHC.Prim.writeWord32Array#) a1 a2 a3 a4
{-# NOINLINE writeWord64Array# #-}
writeWord64Array# :: MutableByteArray# s -> Int# -> Word64# -> State# s -> State# s
writeWord64Array# a1 a2 a3 a4 = (GHC.Prim.writeWord64Array#) a1 a2 a3 a4
{-# NOINLINE copyByteArray# #-}
copyByteArray# :: ByteArray# -> Int# -> MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
copyByteArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copyByteArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE copyMutableByteArray# #-}
copyMutableByteArray# :: MutableByteArray# s -> Int# -> MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
copyMutableByteArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copyMutableByteArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE copyByteArrayToAddr# #-}
copyByteArrayToAddr# :: ByteArray# -> Int# -> Addr# -> Int# -> State# s -> State# s
copyByteArrayToAddr# a1 a2 a3 a4 a5 = (GHC.Prim.copyByteArrayToAddr#) a1 a2 a3 a4 a5
{-# NOINLINE copyMutableByteArrayToAddr# #-}
copyMutableByteArrayToAddr# :: MutableByteArray# s -> Int# -> Addr# -> Int# -> State# s -> State# s
copyMutableByteArrayToAddr# a1 a2 a3 a4 a5 = (GHC.Prim.copyMutableByteArrayToAddr#) a1 a2 a3 a4 a5
{-# NOINLINE copyAddrToByteArray# #-}
copyAddrToByteArray# :: Addr# -> MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
copyAddrToByteArray# a1 a2 a3 a4 a5 = (GHC.Prim.copyAddrToByteArray#) a1 a2 a3 a4 a5
{-# NOINLINE setByteArray# #-}
setByteArray# :: MutableByteArray# s -> Int# -> Int# -> Int# -> State# s -> State# s
setByteArray# a1 a2 a3 a4 a5 = (GHC.Prim.setByteArray#) a1 a2 a3 a4 a5
{-# NOINLINE atomicReadIntArray# #-}
atomicReadIntArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Int# #)
atomicReadIntArray# a1 a2 a3 = (GHC.Prim.atomicReadIntArray#) a1 a2 a3
{-# NOINLINE atomicWriteIntArray# #-}
atomicWriteIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
atomicWriteIntArray# a1 a2 a3 a4 = (GHC.Prim.atomicWriteIntArray#) a1 a2 a3 a4
{-# NOINLINE casIntArray# #-}
casIntArray# :: MutableByteArray# s -> Int# -> Int# -> Int# -> State# s -> (# State# s,Int# #)
casIntArray# a1 a2 a3 a4 a5 = (GHC.Prim.casIntArray#) a1 a2 a3 a4 a5
{-# NOINLINE fetchAddIntArray# #-}
fetchAddIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> (# State# s,Int# #)
fetchAddIntArray# a1 a2 a3 a4 = (GHC.Prim.fetchAddIntArray#) a1 a2 a3 a4
{-# NOINLINE fetchSubIntArray# #-}
fetchSubIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> (# State# s,Int# #)
fetchSubIntArray# a1 a2 a3 a4 = (GHC.Prim.fetchSubIntArray#) a1 a2 a3 a4
{-# NOINLINE fetchAndIntArray# #-}
fetchAndIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> (# State# s,Int# #)
fetchAndIntArray# a1 a2 a3 a4 = (GHC.Prim.fetchAndIntArray#) a1 a2 a3 a4
{-# NOINLINE fetchNandIntArray# #-}
fetchNandIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> (# State# s,Int# #)
fetchNandIntArray# a1 a2 a3 a4 = (GHC.Prim.fetchNandIntArray#) a1 a2 a3 a4
{-# NOINLINE fetchOrIntArray# #-}
fetchOrIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> (# State# s,Int# #)
fetchOrIntArray# a1 a2 a3 a4 = (GHC.Prim.fetchOrIntArray#) a1 a2 a3 a4
{-# NOINLINE fetchXorIntArray# #-}
fetchXorIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> (# State# s,Int# #)
fetchXorIntArray# a1 a2 a3 a4 = (GHC.Prim.fetchXorIntArray#) a1 a2 a3 a4
{-# NOINLINE newArrayArray# #-}
newArrayArray# :: Int# -> State# s -> (# State# s,MutableArrayArray# s #)
newArrayArray# a1 a2 = (GHC.Prim.newArrayArray#) a1 a2
{-# NOINLINE sameMutableArrayArray# #-}
sameMutableArrayArray# :: MutableArrayArray# s -> MutableArrayArray# s -> Int#
sameMutableArrayArray# a1 a2 = (GHC.Prim.sameMutableArrayArray#) a1 a2
{-# NOINLINE unsafeFreezeArrayArray# #-}
unsafeFreezeArrayArray# :: MutableArrayArray# s -> State# s -> (# State# s,ArrayArray# #)
unsafeFreezeArrayArray# a1 a2 = (GHC.Prim.unsafeFreezeArrayArray#) a1 a2
{-# NOINLINE sizeofArrayArray# #-}
sizeofArrayArray# :: ArrayArray# -> Int#
sizeofArrayArray# a1 = (GHC.Prim.sizeofArrayArray#) a1
{-# NOINLINE sizeofMutableArrayArray# #-}
sizeofMutableArrayArray# :: MutableArrayArray# s -> Int#
sizeofMutableArrayArray# a1 = (GHC.Prim.sizeofMutableArrayArray#) a1
{-# NOINLINE indexByteArrayArray# #-}
indexByteArrayArray# :: ArrayArray# -> Int# -> ByteArray#
indexByteArrayArray# a1 a2 = (GHC.Prim.indexByteArrayArray#) a1 a2
{-# NOINLINE indexArrayArrayArray# #-}
indexArrayArrayArray# :: ArrayArray# -> Int# -> ArrayArray#
indexArrayArrayArray# a1 a2 = (GHC.Prim.indexArrayArrayArray#) a1 a2
{-# NOINLINE readByteArrayArray# #-}
readByteArrayArray# :: MutableArrayArray# s -> Int# -> State# s -> (# State# s,ByteArray# #)
readByteArrayArray# a1 a2 a3 = (GHC.Prim.readByteArrayArray#) a1 a2 a3
{-# NOINLINE readMutableByteArrayArray# #-}
readMutableByteArrayArray# :: MutableArrayArray# s -> Int# -> State# s -> (# State# s,MutableByteArray# s #)
readMutableByteArrayArray# a1 a2 a3 = (GHC.Prim.readMutableByteArrayArray#) a1 a2 a3
{-# NOINLINE readArrayArrayArray# #-}
readArrayArrayArray# :: MutableArrayArray# s -> Int# -> State# s -> (# State# s,ArrayArray# #)
readArrayArrayArray# a1 a2 a3 = (GHC.Prim.readArrayArrayArray#) a1 a2 a3
{-# NOINLINE readMutableArrayArrayArray# #-}
readMutableArrayArrayArray# :: MutableArrayArray# s -> Int# -> State# s -> (# State# s,MutableArrayArray# s #)
readMutableArrayArrayArray# a1 a2 a3 = (GHC.Prim.readMutableArrayArrayArray#) a1 a2 a3
{-# NOINLINE writeByteArrayArray# #-}
writeByteArrayArray# :: MutableArrayArray# s -> Int# -> ByteArray# -> State# s -> State# s
writeByteArrayArray# a1 a2 a3 a4 = (GHC.Prim.writeByteArrayArray#) a1 a2 a3 a4
{-# NOINLINE writeMutableByteArrayArray# #-}
writeMutableByteArrayArray# :: MutableArrayArray# s -> Int# -> MutableByteArray# s -> State# s -> State# s
writeMutableByteArrayArray# a1 a2 a3 a4 = (GHC.Prim.writeMutableByteArrayArray#) a1 a2 a3 a4
{-# NOINLINE writeArrayArrayArray# #-}
writeArrayArrayArray# :: MutableArrayArray# s -> Int# -> ArrayArray# -> State# s -> State# s
writeArrayArrayArray# a1 a2 a3 a4 = (GHC.Prim.writeArrayArrayArray#) a1 a2 a3 a4
{-# NOINLINE writeMutableArrayArrayArray# #-}
writeMutableArrayArrayArray# :: MutableArrayArray# s -> Int# -> MutableArrayArray# s -> State# s -> State# s
writeMutableArrayArrayArray# a1 a2 a3 a4 = (GHC.Prim.writeMutableArrayArrayArray#) a1 a2 a3 a4
{-# NOINLINE copyArrayArray# #-}
copyArrayArray# :: ArrayArray# -> Int# -> MutableArrayArray# s -> Int# -> Int# -> State# s -> State# s
copyArrayArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copyArrayArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE copyMutableArrayArray# #-}
copyMutableArrayArray# :: MutableArrayArray# s -> Int# -> MutableArrayArray# s -> Int# -> Int# -> State# s -> State# s
copyMutableArrayArray# a1 a2 a3 a4 a5 a6 = (GHC.Prim.copyMutableArrayArray#) a1 a2 a3 a4 a5 a6
{-# NOINLINE plusAddr# #-}
plusAddr# :: Addr# -> Int# -> Addr#
plusAddr# a1 a2 = (GHC.Prim.plusAddr#) a1 a2
{-# NOINLINE minusAddr# #-}
minusAddr# :: Addr# -> Addr# -> Int#
minusAddr# a1 a2 = (GHC.Prim.minusAddr#) a1 a2
{-# NOINLINE remAddr# #-}
remAddr# :: Addr# -> Int# -> Int#
remAddr# a1 a2 = (GHC.Prim.remAddr#) a1 a2
{-# NOINLINE addr2Int# #-}
addr2Int# :: Addr# -> Int#
addr2Int# a1 = (GHC.Prim.addr2Int#) a1
{-# NOINLINE int2Addr# #-}
int2Addr# :: Int# -> Addr#
int2Addr# a1 = (GHC.Prim.int2Addr#) a1
{-# NOINLINE gtAddr# #-}
gtAddr# :: Addr# -> Addr# -> Int#
gtAddr# a1 a2 = (GHC.Prim.gtAddr#) a1 a2
{-# NOINLINE geAddr# #-}
geAddr# :: Addr# -> Addr# -> Int#
geAddr# a1 a2 = (GHC.Prim.geAddr#) a1 a2
{-# NOINLINE eqAddr# #-}
eqAddr# :: Addr# -> Addr# -> Int#
eqAddr# a1 a2 = (GHC.Prim.eqAddr#) a1 a2
{-# NOINLINE neAddr# #-}
neAddr# :: Addr# -> Addr# -> Int#
neAddr# a1 a2 = (GHC.Prim.neAddr#) a1 a2
{-# NOINLINE ltAddr# #-}
ltAddr# :: Addr# -> Addr# -> Int#
ltAddr# a1 a2 = (GHC.Prim.ltAddr#) a1 a2
{-# NOINLINE leAddr# #-}
leAddr# :: Addr# -> Addr# -> Int#
leAddr# a1 a2 = (GHC.Prim.leAddr#) a1 a2
{-# NOINLINE indexCharOffAddr# #-}
indexCharOffAddr# :: Addr# -> Int# -> Char#
indexCharOffAddr# a1 a2 = (GHC.Prim.indexCharOffAddr#) a1 a2
{-# NOINLINE indexWideCharOffAddr# #-}
indexWideCharOffAddr# :: Addr# -> Int# -> Char#
indexWideCharOffAddr# a1 a2 = (GHC.Prim.indexWideCharOffAddr#) a1 a2
{-# NOINLINE indexIntOffAddr# #-}
indexIntOffAddr# :: Addr# -> Int# -> Int#
indexIntOffAddr# a1 a2 = (GHC.Prim.indexIntOffAddr#) a1 a2
{-# NOINLINE indexWordOffAddr# #-}
indexWordOffAddr# :: Addr# -> Int# -> Word#
indexWordOffAddr# a1 a2 = (GHC.Prim.indexWordOffAddr#) a1 a2
{-# NOINLINE indexAddrOffAddr# #-}
indexAddrOffAddr# :: Addr# -> Int# -> Addr#
indexAddrOffAddr# a1 a2 = (GHC.Prim.indexAddrOffAddr#) a1 a2
{-# NOINLINE indexFloatOffAddr# #-}
indexFloatOffAddr# :: Addr# -> Int# -> Float#
indexFloatOffAddr# a1 a2 = (GHC.Prim.indexFloatOffAddr#) a1 a2
{-# NOINLINE indexDoubleOffAddr# #-}
indexDoubleOffAddr# :: Addr# -> Int# -> Double#
indexDoubleOffAddr# a1 a2 = (GHC.Prim.indexDoubleOffAddr#) a1 a2
{-# NOINLINE indexStablePtrOffAddr# #-}
indexStablePtrOffAddr# :: Addr# -> Int# -> StablePtr# a
indexStablePtrOffAddr# a1 a2 = (GHC.Prim.indexStablePtrOffAddr#) a1 a2
{-# NOINLINE indexInt8OffAddr# #-}
indexInt8OffAddr# :: Addr# -> Int# -> Int#
indexInt8OffAddr# a1 a2 = (GHC.Prim.indexInt8OffAddr#) a1 a2
{-# NOINLINE indexInt16OffAddr# #-}
indexInt16OffAddr# :: Addr# -> Int# -> Int#
indexInt16OffAddr# a1 a2 = (GHC.Prim.indexInt16OffAddr#) a1 a2
{-# NOINLINE indexInt32OffAddr# #-}
indexInt32OffAddr# :: Addr# -> Int# -> Int#
indexInt32OffAddr# a1 a2 = (GHC.Prim.indexInt32OffAddr#) a1 a2
{-# NOINLINE indexInt64OffAddr# #-}
indexInt64OffAddr# :: Addr# -> Int# -> Int64#
indexInt64OffAddr# a1 a2 = (GHC.Prim.indexInt64OffAddr#) a1 a2
{-# NOINLINE indexWord8OffAddr# #-}
indexWord8OffAddr# :: Addr# -> Int# -> Word#
indexWord8OffAddr# a1 a2 = (GHC.Prim.indexWord8OffAddr#) a1 a2
{-# NOINLINE indexWord16OffAddr# #-}
indexWord16OffAddr# :: Addr# -> Int# -> Word#
indexWord16OffAddr# a1 a2 = (GHC.Prim.indexWord16OffAddr#) a1 a2
{-# NOINLINE indexWord32OffAddr# #-}
indexWord32OffAddr# :: Addr# -> Int# -> Word#
indexWord32OffAddr# a1 a2 = (GHC.Prim.indexWord32OffAddr#) a1 a2
{-# NOINLINE indexWord64OffAddr# #-}
indexWord64OffAddr# :: Addr# -> Int# -> Word64#
indexWord64OffAddr# a1 a2 = (GHC.Prim.indexWord64OffAddr#) a1 a2
{-# NOINLINE readCharOffAddr# #-}
readCharOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Char# #)
readCharOffAddr# a1 a2 a3 = (GHC.Prim.readCharOffAddr#) a1 a2 a3
{-# NOINLINE readWideCharOffAddr# #-}
readWideCharOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Char# #)
readWideCharOffAddr# a1 a2 a3 = (GHC.Prim.readWideCharOffAddr#) a1 a2 a3
{-# NOINLINE readIntOffAddr# #-}
readIntOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Int# #)
readIntOffAddr# a1 a2 a3 = (GHC.Prim.readIntOffAddr#) a1 a2 a3
{-# NOINLINE readWordOffAddr# #-}
readWordOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Word# #)
readWordOffAddr# a1 a2 a3 = (GHC.Prim.readWordOffAddr#) a1 a2 a3
{-# NOINLINE readAddrOffAddr# #-}
readAddrOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Addr# #)
readAddrOffAddr# a1 a2 a3 = (GHC.Prim.readAddrOffAddr#) a1 a2 a3
{-# NOINLINE readFloatOffAddr# #-}
readFloatOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Float# #)
readFloatOffAddr# a1 a2 a3 = (GHC.Prim.readFloatOffAddr#) a1 a2 a3
{-# NOINLINE readDoubleOffAddr# #-}
readDoubleOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Double# #)
readDoubleOffAddr# a1 a2 a3 = (GHC.Prim.readDoubleOffAddr#) a1 a2 a3
{-# NOINLINE readStablePtrOffAddr# #-}
readStablePtrOffAddr# :: Addr# -> Int# -> State# s -> (# State# s,StablePtr# a #)
readStablePtrOffAddr# a1 a2 a3 = (GHC.Prim.readStablePtrOffAddr#) a1 a2 a3
{-# NOINLINE readInt8OffAddr# #-}
readInt8OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Int# #)
readInt8OffAddr# a1 a2 a3 = (GHC.Prim.readInt8OffAddr#) a1 a2 a3
{-# NOINLINE readInt16OffAddr# #-}
readInt16OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Int# #)
readInt16OffAddr# a1 a2 a3 = (GHC.Prim.readInt16OffAddr#) a1 a2 a3
{-# NOINLINE readInt32OffAddr# #-}
readInt32OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Int# #)
readInt32OffAddr# a1 a2 a3 = (GHC.Prim.readInt32OffAddr#) a1 a2 a3
{-# NOINLINE readInt64OffAddr# #-}
readInt64OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Int64# #)
readInt64OffAddr# a1 a2 a3 = (GHC.Prim.readInt64OffAddr#) a1 a2 a3
{-# NOINLINE readWord8OffAddr# #-}
readWord8OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Word# #)
readWord8OffAddr# a1 a2 a3 = (GHC.Prim.readWord8OffAddr#) a1 a2 a3
{-# NOINLINE readWord16OffAddr# #-}
readWord16OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Word# #)
readWord16OffAddr# a1 a2 a3 = (GHC.Prim.readWord16OffAddr#) a1 a2 a3
{-# NOINLINE readWord32OffAddr# #-}
readWord32OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Word# #)
readWord32OffAddr# a1 a2 a3 = (GHC.Prim.readWord32OffAddr#) a1 a2 a3
{-# NOINLINE readWord64OffAddr# #-}
readWord64OffAddr# :: Addr# -> Int# -> State# s -> (# State# s,Word64# #)
readWord64OffAddr# a1 a2 a3 = (GHC.Prim.readWord64OffAddr#) a1 a2 a3
{-# NOINLINE writeCharOffAddr# #-}
writeCharOffAddr# :: Addr# -> Int# -> Char# -> State# s -> State# s
writeCharOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeCharOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeWideCharOffAddr# #-}
writeWideCharOffAddr# :: Addr# -> Int# -> Char# -> State# s -> State# s
writeWideCharOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeWideCharOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeIntOffAddr# #-}
writeIntOffAddr# :: Addr# -> Int# -> Int# -> State# s -> State# s
writeIntOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeIntOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeWordOffAddr# #-}
writeWordOffAddr# :: Addr# -> Int# -> Word# -> State# s -> State# s
writeWordOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeWordOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeAddrOffAddr# #-}
writeAddrOffAddr# :: Addr# -> Int# -> Addr# -> State# s -> State# s
writeAddrOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeAddrOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeFloatOffAddr# #-}
writeFloatOffAddr# :: Addr# -> Int# -> Float# -> State# s -> State# s
writeFloatOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeFloatOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeDoubleOffAddr# #-}
writeDoubleOffAddr# :: Addr# -> Int# -> Double# -> State# s -> State# s
writeDoubleOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeDoubleOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeStablePtrOffAddr# #-}
writeStablePtrOffAddr# :: Addr# -> Int# -> StablePtr# a -> State# s -> State# s
writeStablePtrOffAddr# a1 a2 a3 a4 = (GHC.Prim.writeStablePtrOffAddr#) a1 a2 a3 a4
{-# NOINLINE writeInt8OffAddr# #-}
writeInt8OffAddr# :: Addr# -> Int# -> Int# -> State# s -> State# s
writeInt8OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeInt8OffAddr#) a1 a2 a3 a4
{-# NOINLINE writeInt16OffAddr# #-}
writeInt16OffAddr# :: Addr# -> Int# -> Int# -> State# s -> State# s
writeInt16OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeInt16OffAddr#) a1 a2 a3 a4
{-# NOINLINE writeInt32OffAddr# #-}
writeInt32OffAddr# :: Addr# -> Int# -> Int# -> State# s -> State# s
writeInt32OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeInt32OffAddr#) a1 a2 a3 a4
{-# NOINLINE writeInt64OffAddr# #-}
writeInt64OffAddr# :: Addr# -> Int# -> Int64# -> State# s -> State# s
writeInt64OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeInt64OffAddr#) a1 a2 a3 a4
{-# NOINLINE writeWord8OffAddr# #-}
writeWord8OffAddr# :: Addr# -> Int# -> Word# -> State# s -> State# s
writeWord8OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeWord8OffAddr#) a1 a2 a3 a4
{-# NOINLINE writeWord16OffAddr# #-}
writeWord16OffAddr# :: Addr# -> Int# -> Word# -> State# s -> State# s
writeWord16OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeWord16OffAddr#) a1 a2 a3 a4
{-# NOINLINE writeWord32OffAddr# #-}
writeWord32OffAddr# :: Addr# -> Int# -> Word# -> State# s -> State# s
writeWord32OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeWord32OffAddr#) a1 a2 a3 a4
{-# NOINLINE writeWord64OffAddr# #-}
writeWord64OffAddr# :: Addr# -> Int# -> Word64# -> State# s -> State# s
writeWord64OffAddr# a1 a2 a3 a4 = (GHC.Prim.writeWord64OffAddr#) a1 a2 a3 a4
{-# NOINLINE newMutVar# #-}
newMutVar# :: a -> State# s -> (# State# s,MutVar# s a #)
newMutVar# a1 a2 = (GHC.Prim.newMutVar#) a1 a2
{-# NOINLINE readMutVar# #-}
readMutVar# :: MutVar# s a -> State# s -> (# State# s,a #)
readMutVar# a1 a2 = (GHC.Prim.readMutVar#) a1 a2
{-# NOINLINE writeMutVar# #-}
writeMutVar# :: MutVar# s a -> a -> State# s -> State# s
writeMutVar# a1 a2 a3 = (GHC.Prim.writeMutVar#) a1 a2 a3
{-# NOINLINE sameMutVar# #-}
sameMutVar# :: MutVar# s a -> MutVar# s a -> Int#
sameMutVar# a1 a2 = (GHC.Prim.sameMutVar#) a1 a2
{-# NOINLINE atomicModifyMutVar# #-}
atomicModifyMutVar# :: MutVar# s a -> (a -> b) -> State# s -> (# State# s,c #)
atomicModifyMutVar# a1 a2 a3 = (GHC.Prim.atomicModifyMutVar#) a1 a2 a3
{-# NOINLINE casMutVar# #-}
casMutVar# :: MutVar# s a -> a -> a -> State# s -> (# State# s,Int#,a #)
casMutVar# a1 a2 a3 a4 = (GHC.Prim.casMutVar#) a1 a2 a3 a4
{-# NOINLINE catch# #-}
catch# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> (b -> State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),a #)
catch# a1 a2 a3 = (GHC.Prim.catch#) a1 a2 a3
{-# NOINLINE raise# #-}
raise# :: a -> b
raise# a1 = (GHC.Prim.raise#) a1
{-# NOINLINE raiseIO# #-}
raiseIO# :: a -> State# (RealWorld) -> (# State# (RealWorld),b #)
raiseIO# a1 a2 = (GHC.Prim.raiseIO#) a1 a2
{-# NOINLINE maskAsyncExceptions# #-}
maskAsyncExceptions# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),a #)
maskAsyncExceptions# a1 a2 = (GHC.Prim.maskAsyncExceptions#) a1 a2
{-# NOINLINE maskUninterruptible# #-}
maskUninterruptible# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),a #)
maskUninterruptible# a1 a2 = (GHC.Prim.maskUninterruptible#) a1 a2
{-# NOINLINE unmaskAsyncExceptions# #-}
unmaskAsyncExceptions# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),a #)
unmaskAsyncExceptions# a1 a2 = (GHC.Prim.unmaskAsyncExceptions#) a1 a2
{-# NOINLINE getMaskingState# #-}
getMaskingState# :: State# (RealWorld) -> (# State# (RealWorld),Int# #)
getMaskingState# a1 = (GHC.Prim.getMaskingState#) a1
{-# NOINLINE atomically# #-}
atomically# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),a #)
atomically# a1 a2 = (GHC.Prim.atomically#) a1 a2
{-# NOINLINE retry# #-}
retry# :: State# (RealWorld) -> (# State# (RealWorld),a #)
retry# a1 = (GHC.Prim.retry#) a1
{-# NOINLINE catchRetry# #-}
catchRetry# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> (State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),a #)
catchRetry# a1 a2 a3 = (GHC.Prim.catchRetry#) a1 a2 a3
{-# NOINLINE catchSTM# #-}
catchSTM# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> (b -> State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),a #)
catchSTM# a1 a2 a3 = (GHC.Prim.catchSTM#) a1 a2 a3
{-# NOINLINE check# #-}
check# :: (State# (RealWorld) -> (# State# (RealWorld),a #)) -> State# (RealWorld) -> (# State# (RealWorld),() #)
check# a1 a2 = (GHC.Prim.check#) a1 a2
{-# NOINLINE newTVar# #-}
newTVar# :: a -> State# s -> (# State# s,TVar# s a #)
newTVar# a1 a2 = (GHC.Prim.newTVar#) a1 a2
{-# NOINLINE readTVar# #-}
readTVar# :: TVar# s a -> State# s -> (# State# s,a #)
readTVar# a1 a2 = (GHC.Prim.readTVar#) a1 a2
{-# NOINLINE readTVarIO# #-}
readTVarIO# :: TVar# s a -> State# s -> (# State# s,a #)
readTVarIO# a1 a2 = (GHC.Prim.readTVarIO#) a1 a2
{-# NOINLINE writeTVar# #-}
writeTVar# :: TVar# s a -> a -> State# s -> State# s
writeTVar# a1 a2 a3 = (GHC.Prim.writeTVar#) a1 a2 a3
{-# NOINLINE sameTVar# #-}
sameTVar# :: TVar# s a -> TVar# s a -> Int#
sameTVar# a1 a2 = (GHC.Prim.sameTVar#) a1 a2
{-# NOINLINE newMVar# #-}
newMVar# :: State# s -> (# State# s,MVar# s a #)
newMVar# a1 = (GHC.Prim.newMVar#) a1
{-# NOINLINE takeMVar# #-}
takeMVar# :: MVar# s a -> State# s -> (# State# s,a #)
takeMVar# a1 a2 = (GHC.Prim.takeMVar#) a1 a2
{-# NOINLINE tryTakeMVar# #-}
tryTakeMVar# :: MVar# s a -> State# s -> (# State# s,Int#,a #)
tryTakeMVar# a1 a2 = (GHC.Prim.tryTakeMVar#) a1 a2
{-# NOINLINE putMVar# #-}
putMVar# :: MVar# s a -> a -> State# s -> State# s
putMVar# a1 a2 a3 = (GHC.Prim.putMVar#) a1 a2 a3
{-# NOINLINE tryPutMVar# #-}
tryPutMVar# :: MVar# s a -> a -> State# s -> (# State# s,Int# #)
tryPutMVar# a1 a2 a3 = (GHC.Prim.tryPutMVar#) a1 a2 a3
{-# NOINLINE readMVar# #-}
readMVar# :: MVar# s a -> State# s -> (# State# s,a #)
readMVar# a1 a2 = (GHC.Prim.readMVar#) a1 a2
{-# NOINLINE tryReadMVar# #-}
tryReadMVar# :: MVar# s a -> State# s -> (# State# s,Int#,a #)
tryReadMVar# a1 a2 = (GHC.Prim.tryReadMVar#) a1 a2
{-# NOINLINE sameMVar# #-}
sameMVar# :: MVar# s a -> MVar# s a -> Int#
sameMVar# a1 a2 = (GHC.Prim.sameMVar#) a1 a2
{-# NOINLINE isEmptyMVar# #-}
isEmptyMVar# :: MVar# s a -> State# s -> (# State# s,Int# #)
isEmptyMVar# a1 a2 = (GHC.Prim.isEmptyMVar#) a1 a2
{-# NOINLINE delay# #-}
delay# :: Int# -> State# s -> State# s
delay# a1 a2 = (GHC.Prim.delay#) a1 a2
{-# NOINLINE waitRead# #-}
waitRead# :: Int# -> State# s -> State# s
waitRead# a1 a2 = (GHC.Prim.waitRead#) a1 a2
{-# NOINLINE waitWrite# #-}
waitWrite# :: Int# -> State# s -> State# s
waitWrite# a1 a2 = (GHC.Prim.waitWrite#) a1 a2
{-# NOINLINE fork# #-}
fork# :: a -> State# (RealWorld) -> (# State# (RealWorld),ThreadId# #)
fork# a1 a2 = (GHC.Prim.fork#) a1 a2
{-# NOINLINE forkOn# #-}
forkOn# :: Int# -> a -> State# (RealWorld) -> (# State# (RealWorld),ThreadId# #)
forkOn# a1 a2 a3 = (GHC.Prim.forkOn#) a1 a2 a3
{-# NOINLINE killThread# #-}
killThread# :: ThreadId# -> a -> State# (RealWorld) -> State# (RealWorld)
killThread# a1 a2 a3 = (GHC.Prim.killThread#) a1 a2 a3
{-# NOINLINE yield# #-}
yield# :: State# (RealWorld) -> State# (RealWorld)
yield# a1 = (GHC.Prim.yield#) a1
{-# NOINLINE myThreadId# #-}
myThreadId# :: State# (RealWorld) -> (# State# (RealWorld),ThreadId# #)
myThreadId# a1 = (GHC.Prim.myThreadId#) a1
{-# NOINLINE labelThread# #-}
labelThread# :: ThreadId# -> Addr# -> State# (RealWorld) -> State# (RealWorld)
labelThread# a1 a2 a3 = (GHC.Prim.labelThread#) a1 a2 a3
{-# NOINLINE isCurrentThreadBound# #-}
isCurrentThreadBound# :: State# (RealWorld) -> (# State# (RealWorld),Int# #)
isCurrentThreadBound# a1 = (GHC.Prim.isCurrentThreadBound#) a1
{-# NOINLINE noDuplicate# #-}
noDuplicate# :: State# (RealWorld) -> State# (RealWorld)
noDuplicate# a1 = (GHC.Prim.noDuplicate#) a1
{-# NOINLINE threadStatus# #-}
threadStatus# :: ThreadId# -> State# (RealWorld) -> (# State# (RealWorld),Int#,Int#,Int# #)
threadStatus# a1 a2 = (GHC.Prim.threadStatus#) a1 a2
{-# NOINLINE mkWeak# #-}
mkWeak# :: o -> b -> c -> State# (RealWorld) -> (# State# (RealWorld),Weak# b #)
mkWeak# a1 a2 a3 a4 = (GHC.Prim.mkWeak#) a1 a2 a3 a4
{-# NOINLINE mkWeakNoFinalizer# #-}
mkWeakNoFinalizer# :: o -> b -> State# (RealWorld) -> (# State# (RealWorld),Weak# b #)
mkWeakNoFinalizer# a1 a2 a3 = (GHC.Prim.mkWeakNoFinalizer#) a1 a2 a3
{-# NOINLINE addCFinalizerToWeak# #-}
addCFinalizerToWeak# :: Addr# -> Addr# -> Int# -> Addr# -> Weak# b -> State# (RealWorld) -> (# State# (RealWorld),Int# #)
addCFinalizerToWeak# a1 a2 a3 a4 a5 a6 = (GHC.Prim.addCFinalizerToWeak#) a1 a2 a3 a4 a5 a6
{-# NOINLINE deRefWeak# #-}
deRefWeak# :: Weak# a -> State# (RealWorld) -> (# State# (RealWorld),Int#,a #)
deRefWeak# a1 a2 = (GHC.Prim.deRefWeak#) a1 a2
{-# NOINLINE finalizeWeak# #-}
finalizeWeak# :: Weak# a -> State# (RealWorld) -> (# State# (RealWorld),Int#,State# (RealWorld) -> (# State# (RealWorld),() #) #)
finalizeWeak# a1 a2 = (GHC.Prim.finalizeWeak#) a1 a2
{-# NOINLINE touch# #-}
touch# :: o -> State# (RealWorld) -> State# (RealWorld)
touch# a1 a2 = (GHC.Prim.touch#) a1 a2
{-# NOINLINE makeStablePtr# #-}
makeStablePtr# :: a -> State# (RealWorld) -> (# State# (RealWorld),StablePtr# a #)
makeStablePtr# a1 a2 = (GHC.Prim.makeStablePtr#) a1 a2
{-# NOINLINE deRefStablePtr# #-}
deRefStablePtr# :: StablePtr# a -> State# (RealWorld) -> (# State# (RealWorld),a #)
deRefStablePtr# a1 a2 = (GHC.Prim.deRefStablePtr#) a1 a2
{-# NOINLINE eqStablePtr# #-}
eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
eqStablePtr# a1 a2 = (GHC.Prim.eqStablePtr#) a1 a2
{-# NOINLINE makeStableName# #-}
makeStableName# :: a -> State# (RealWorld) -> (# State# (RealWorld),StableName# a #)
makeStableName# a1 a2 = (GHC.Prim.makeStableName#) a1 a2
{-# NOINLINE eqStableName# #-}
eqStableName# :: StableName# a -> StableName# b -> Int#
eqStableName# a1 a2 = (GHC.Prim.eqStableName#) a1 a2
{-# NOINLINE stableNameToInt# #-}
stableNameToInt# :: StableName# a -> Int#
stableNameToInt# a1 = (GHC.Prim.stableNameToInt#) a1
{-# NOINLINE reallyUnsafePtrEquality# #-}
reallyUnsafePtrEquality# :: a -> a -> Int#
reallyUnsafePtrEquality# a1 a2 = (GHC.Prim.reallyUnsafePtrEquality#) a1 a2
{-# NOINLINE spark# #-}
spark# :: a -> State# s -> (# State# s,a #)
spark# a1 a2 = (GHC.Prim.spark#) a1 a2
{-# NOINLINE getSpark# #-}
getSpark# :: State# s -> (# State# s,Int#,a #)
getSpark# a1 = (GHC.Prim.getSpark#) a1
{-# NOINLINE numSparks# #-}
numSparks# :: State# s -> (# State# s,Int# #)
numSparks# a1 = (GHC.Prim.numSparks#) a1
{-# NOINLINE dataToTag# #-}
dataToTag# :: a -> Int#
dataToTag# a1 = (GHC.Prim.dataToTag#) a1
{-# NOINLINE addrToAny# #-}
addrToAny# :: Addr# -> (# a #)
addrToAny# a1 = (GHC.Prim.addrToAny#) a1
{-# NOINLINE mkApUpd0# #-}
mkApUpd0# :: BCO# -> (# a #)
mkApUpd0# a1 = (GHC.Prim.mkApUpd0#) a1
{-# NOINLINE newBCO# #-}
newBCO# :: ByteArray# -> ByteArray# -> Array# a -> Int# -> ByteArray# -> State# s -> (# State# s,BCO# #)
newBCO# a1 a2 a3 a4 a5 a6 = (GHC.Prim.newBCO#) a1 a2 a3 a4 a5 a6
{-# NOINLINE unpackClosure# #-}
unpackClosure# :: a -> (# Addr#,Array# b,ByteArray# #)
unpackClosure# a1 = (GHC.Prim.unpackClosure#) a1
{-# NOINLINE getApStackVal# #-}
getApStackVal# :: a -> Int# -> (# Int#,b #)
getApStackVal# a1 a2 = (GHC.Prim.getApStackVal#) a1 a2
{-# NOINLINE getCCSOf# #-}
getCCSOf# :: a -> State# s -> (# State# s,Addr# #)
getCCSOf# a1 a2 = (GHC.Prim.getCCSOf#) a1 a2
{-# NOINLINE getCurrentCCS# #-}
getCurrentCCS# :: a -> State# s -> (# State# s,Addr# #)
getCurrentCCS# a1 a2 = (GHC.Prim.getCurrentCCS#) a1 a2
{-# NOINLINE traceEvent# #-}
traceEvent# :: Addr# -> State# s -> State# s
traceEvent# a1 a2 = (GHC.Prim.traceEvent#) a1 a2
{-# NOINLINE traceMarker# #-}
traceMarker# :: Addr# -> State# s -> State# s
traceMarker# a1 a2 = (GHC.Prim.traceMarker#) a1 a2
{-# NOINLINE prefetchByteArray3# #-}
prefetchByteArray3# :: ByteArray# -> Int# -> State# s -> State# s
prefetchByteArray3# a1 a2 a3 = (GHC.Prim.prefetchByteArray3#) a1 a2 a3
{-# NOINLINE prefetchMutableByteArray3# #-}
prefetchMutableByteArray3# :: MutableByteArray# s -> Int# -> State# s -> State# s
prefetchMutableByteArray3# a1 a2 a3 = (GHC.Prim.prefetchMutableByteArray3#) a1 a2 a3
{-# NOINLINE prefetchAddr3# #-}
prefetchAddr3# :: Addr# -> Int# -> State# s -> State# s
prefetchAddr3# a1 a2 a3 = (GHC.Prim.prefetchAddr3#) a1 a2 a3
{-# NOINLINE prefetchValue3# #-}
prefetchValue3# :: a -> State# s -> State# s
prefetchValue3# a1 a2 = (GHC.Prim.prefetchValue3#) a1 a2
{-# NOINLINE prefetchByteArray2# #-}
prefetchByteArray2# :: ByteArray# -> Int# -> State# s -> State# s
prefetchByteArray2# a1 a2 a3 = (GHC.Prim.prefetchByteArray2#) a1 a2 a3
{-# NOINLINE prefetchMutableByteArray2# #-}
prefetchMutableByteArray2# :: MutableByteArray# s -> Int# -> State# s -> State# s
prefetchMutableByteArray2# a1 a2 a3 = (GHC.Prim.prefetchMutableByteArray2#) a1 a2 a3
{-# NOINLINE prefetchAddr2# #-}
prefetchAddr2# :: Addr# -> Int# -> State# s -> State# s
prefetchAddr2# a1 a2 a3 = (GHC.Prim.prefetchAddr2#) a1 a2 a3
{-# NOINLINE prefetchValue2# #-}
prefetchValue2# :: a -> State# s -> State# s
prefetchValue2# a1 a2 = (GHC.Prim.prefetchValue2#) a1 a2
{-# NOINLINE prefetchByteArray1# #-}
prefetchByteArray1# :: ByteArray# -> Int# -> State# s -> State# s
prefetchByteArray1# a1 a2 a3 = (GHC.Prim.prefetchByteArray1#) a1 a2 a3
{-# NOINLINE prefetchMutableByteArray1# #-}
prefetchMutableByteArray1# :: MutableByteArray# s -> Int# -> State# s -> State# s
prefetchMutableByteArray1# a1 a2 a3 = (GHC.Prim.prefetchMutableByteArray1#) a1 a2 a3
{-# NOINLINE prefetchAddr1# #-}
prefetchAddr1# :: Addr# -> Int# -> State# s -> State# s
prefetchAddr1# a1 a2 a3 = (GHC.Prim.prefetchAddr1#) a1 a2 a3
{-# NOINLINE prefetchValue1# #-}
prefetchValue1# :: a -> State# s -> State# s
prefetchValue1# a1 a2 = (GHC.Prim.prefetchValue1#) a1 a2
{-# NOINLINE prefetchByteArray0# #-}
prefetchByteArray0# :: ByteArray# -> Int# -> State# s -> State# s
prefetchByteArray0# a1 a2 a3 = (GHC.Prim.prefetchByteArray0#) a1 a2 a3
{-# NOINLINE prefetchMutableByteArray0# #-}
prefetchMutableByteArray0# :: MutableByteArray# s -> Int# -> State# s -> State# s
prefetchMutableByteArray0# a1 a2 a3 = (GHC.Prim.prefetchMutableByteArray0#) a1 a2 a3
{-# NOINLINE prefetchAddr0# #-}
prefetchAddr0# :: Addr# -> Int# -> State# s -> State# s
prefetchAddr0# a1 a2 a3 = (GHC.Prim.prefetchAddr0#) a1 a2 a3
{-# NOINLINE prefetchValue0# #-}
prefetchValue0# :: a -> State# s -> State# s
prefetchValue0# a1 a2 = (GHC.Prim.prefetchValue0#) a1 a2
| jtojnar/haste-compiler | libraries/ghc-7.10/ghc-prim/GHC/PrimopWrappers.hs | bsd-3-clause | 59,078 | 0 | 13 | 8,851 | 18,412 | 9,710 | 8,702 | 1,220 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
(~#) :: Comonad w => CascadeW w (t ': ts) -> w t -> Last (t ': ts)
(~#) = cascadeW
infixr 0 ~#
| sdiehl/ghc | testsuite/tests/ghc-api/annotations/Test15303.hs | bsd-3-clause | 176 | 0 | 10 | 55 | 66 | 36 | 30 | 5 | 1 |
module Crosscells.Tokens
( Direction(..)
, Token(..)
, parseTokens
) where
import Data.Char
import Data.Foldable
import Data.Vector (Vector)
import qualified Data.Vector as V
import Crosscells.Region
data Token
= Arrow Direction
| Box
| Plus Int
| Times Int
| Bracketed Int
| Number Int
deriving (Read, Show, Eq, Ord)
parseTokens :: String -> [(Region, Token)]
parseTokens = parseRaw . V.fromList . map V.fromList . lines
isStart :: Vector Char -> Int -> Bool
isStart row i = 0==i || (row V.! (i-1)) `elem` "] |"
isBoxStart :: Vector (Vector Char) -> Vector Char -> Char -> Int -> Int -> Bool
isBoxStart file row col rowIx colIx =
col == '+' && colR == Just '-' && colD == Just '|'
where
colR = row V.!? (colIx+1)
colD = do row1 <- file V.!? (rowIx+1)
row1 V.!? colIx
parseRaw :: Vector (Vector Char) -> [(Region, Token)]
parseRaw file =
[ result
| (rowIx, row) <- toList (V.indexed file)
, (colIx, col) <- toList (V.indexed row)
, isStart row colIx
, Just result <- [parseRaw1 file row col rowIx colIx]
]
parseRaw1 :: Vector (Vector Char) -> Vector Char -> Char -> Int -> Int -> Maybe (Region, Token)
parseRaw1 file row col rowIx colIx
| isBoxStart file row col rowIx colIx = Just (parseBox file rowIx colIx, Box)
| '+' == col, maybe False isDigit (row V.!? (colIx+1)) =
let (val, width) = parseNumber (V.drop (colIx+1) row)
in Just (Region (Coord rowIx colIx) (Coord rowIx (colIx + width)), Plus val)
| 'x' == col =
let (val, width) = parseNumber (V.drop (colIx+1) row)
in Just (Region (Coord rowIx colIx) (Coord rowIx (colIx + width)), Times val)
| '[' == col =
let (val, width) = parseNumber (V.drop (colIx+1) row)
in Just (Region (Coord rowIx colIx) (Coord rowIx (colIx + width + 1)), Bracketed val)
| '^' == col = Just (Region (Coord rowIx colIx) (Coord rowIx colIx), Arrow U)
| 'v' == col = Just (Region (Coord rowIx colIx) (Coord rowIx colIx), Arrow D)
| '<' == col = Just (Region (Coord rowIx colIx) (Coord rowIx colIx), Arrow L)
| '>' == col = Just (Region (Coord rowIx colIx) (Coord rowIx colIx), Arrow R)
| isDigit col =
let (val, width) = parseNumber (V.drop colIx row)
in Just (Region (Coord rowIx colIx) (Coord rowIx (colIx + width - 1)), Number val)
| otherwise = Nothing
parseNumber :: Vector Char -> (Int, Int)
parseNumber v = (read (toList fragment), V.length fragment)
where
fragment = V.takeWhile isDigit v
parseBox :: Vector (Vector Char) -> Int -> Int -> Region
parseBox file rowIx colIx = Region (Coord rowIx colIx) (Coord rowIx' colIx')
where
Just width = V.elemIndex '+' (V.drop (colIx+1) (file V.! rowIx))
colIx' = colIx + 1 + width
Just height = V.findIndex (\row -> row V.!? colIx' == Just '+')
(V.drop (rowIx+1) file)
rowIx' = rowIx + 1 + height
| glguy/5puzzle | Crosscells/Tokens.hs | isc | 2,899 | 0 | 15 | 701 | 1,384 | 703 | 681 | 64 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Futhark.CodeGen.Backends.COpenCL.Boilerplate
( generateBoilerplate
, kernelRuntime
, kernelRuns
) where
import Data.FileEmbed
import qualified Language.C.Syntax as C
import qualified Language.C.Quote.OpenCL as C
import Futhark.CodeGen.ImpCode.OpenCL
import qualified Futhark.CodeGen.Backends.GenericC as GC
import Futhark.CodeGen.OpenCL.Kernels
import Futhark.Util (chunk)
generateBoilerplate :: String -> String -> [String] -> GC.CompilerM OpenCL () ()
generateBoilerplate opencl_code opencl_prelude kernel_names = do
ctx_ty <- GC.contextType
final_inits <- GC.contextFinalInits
let (ctx_opencl_fields, ctx_opencl_inits, top_decls, later_top_decls) =
openClDecls ctx_ty final_inits kernel_names opencl_code opencl_prelude
GC.earlyDecls top_decls
cfg <- GC.publicName "context_config"
new_cfg <- GC.publicName "context_config_new"
free_cfg <- GC.publicName "context_config_free"
cfg_set_debugging <- GC.publicName "context_config_set_debugging"
cfg_set_device <- GC.publicName "context_config_set_device"
cfg_set_platform <- GC.publicName "context_config_set_platform"
cfg_dump_program_to <- GC.publicName "context_config_dump_program_to"
cfg_load_program_from <- GC.publicName "context_config_load_program_from"
cfg_set_group_size <- GC.publicName "context_config_set_group_size"
cfg_set_num_groups <- GC.publicName "context_config_set_num_groups"
GC.headerDecl GC.InitDecl [C.cedecl|struct $id:cfg;|]
GC.headerDecl GC.InitDecl [C.cedecl|struct $id:cfg* $id:new_cfg();|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:free_cfg(struct $id:cfg* cfg);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:cfg_set_debugging(struct $id:cfg* cfg, int flag);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:cfg_set_device(struct $id:cfg* cfg, const char *s);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:cfg_set_platform(struct $id:cfg* cfg, const char *s);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:cfg_dump_program_to(struct $id:cfg* cfg, const char *path);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:cfg_load_program_from(struct $id:cfg* cfg, const char *path);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:cfg_set_group_size(struct $id:cfg* cfg, int size);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:cfg_set_num_groups(struct $id:cfg* cfg, int num);|]
GC.libDecl [C.cedecl|struct $id:cfg {
struct opencl_config opencl;
};|]
GC.libDecl [C.cedecl|struct $id:cfg* $id:new_cfg() {
struct $id:cfg *cfg = malloc(sizeof(struct $id:cfg));
if (cfg == NULL) {
return NULL;
}
opencl_config_init(&cfg->opencl);
cfg->opencl.transpose_block_dim = $int:(transposeBlockDim::Int);
return cfg;
}|]
GC.libDecl [C.cedecl|void $id:free_cfg(struct $id:cfg* cfg) {
free(cfg);
}|]
GC.libDecl [C.cedecl|void $id:cfg_set_debugging(struct $id:cfg* cfg, int flag) {
cfg->opencl.debugging = flag;
}|]
GC.libDecl [C.cedecl|void $id:cfg_set_device(struct $id:cfg* cfg, const char *s) {
set_preferred_device(&cfg->opencl, s);
}|]
GC.libDecl [C.cedecl|void $id:cfg_set_platform(struct $id:cfg* cfg, const char *s) {
set_preferred_platform(&cfg->opencl, s);
}|]
GC.libDecl [C.cedecl|void $id:cfg_dump_program_to(struct $id:cfg* cfg, const char *path) {
cfg->opencl.dump_program_to = path;
}|]
GC.libDecl [C.cedecl|void $id:cfg_load_program_from(struct $id:cfg* cfg, const char *path) {
cfg->opencl.load_program_from = path;
}|]
GC.libDecl [C.cedecl|void $id:cfg_set_group_size(struct $id:cfg* cfg, int size) {
cfg->opencl.group_size = size;
}|]
GC.libDecl [C.cedecl|void $id:cfg_set_num_groups(struct $id:cfg* cfg, int num) {
cfg->opencl.num_groups = num;
}|]
ctx <- GC.publicName "context"
new_ctx <- GC.publicName "context_new"
free_ctx <- GC.publicName "context_free"
sync_ctx <- GC.publicName "context_sync"
GC.headerDecl GC.InitDecl [C.cedecl|struct $id:ctx;|]
GC.headerDecl GC.InitDecl [C.cedecl|struct $id:ctx* $id:new_ctx(struct $id:cfg* cfg);|]
GC.headerDecl GC.InitDecl [C.cedecl|void $id:free_ctx(struct $id:ctx* ctx);|]
GC.headerDecl GC.InitDecl [C.cedecl|int $id:sync_ctx(struct $id:ctx* ctx);|]
(fields, init_fields) <- GC.contextContents
GC.libDecl [C.cedecl|struct $id:ctx {
int detail_memory;
int debugging;
$sdecls:fields
$sdecls:ctx_opencl_fields
struct opencl_context opencl;
};|]
mapM_ GC.libDecl later_top_decls
GC.libDecl [C.cedecl|struct $id:ctx* $id:new_ctx(struct $id:cfg* cfg) {
struct $id:ctx* ctx = malloc(sizeof(struct $id:ctx));
if (ctx == NULL) {
return NULL;
}
ctx->detail_memory = cfg->opencl.debugging;
ctx->debugging = cfg->opencl.debugging;
ctx->opencl.cfg = cfg->opencl;
$stms:init_fields
$stms:ctx_opencl_inits
setup_opencl_and_load_kernels(ctx);
return ctx;
}|]
GC.libDecl [C.cedecl|void $id:free_ctx(struct $id:ctx* ctx) {
free(ctx);
}|]
GC.libDecl [C.cedecl|int $id:sync_ctx(struct $id:ctx* ctx) {
OPENCL_SUCCEED(clFinish(ctx->opencl.queue));
return 0;
}|]
mapM_ GC.debugReport $ openClReport kernel_names
openClDecls :: C.Type -> [C.Stm] -> [String] -> String -> String
-> ([C.FieldGroup], [C.Stm], [C.Definition], [C.Definition])
openClDecls ctx_ty final_inits kernel_names opencl_program opencl_prelude =
(ctx_fields, ctx_inits, openCL_boilerplate, openCL_load)
where opencl_program_fragments =
-- Some C compilers limit the size of literal strings, so
-- chunk the entire program into small bits here, and
-- concatenate it again at runtime.
[ [C.cinit|$string:s|] | s <- chunk 2000 (opencl_prelude++opencl_program) ]
nullptr = [C.cinit|NULL|]
ctx_fields =
[ [C.csdecl|int total_runs;|],
[C.csdecl|int total_runtime;|] ] ++
concat
[ [ [C.csdecl|typename cl_kernel $id:name;|]
, [C.csdecl|int $id:(kernelRuntime name);|]
, [C.csdecl|int $id:(kernelRuns name);|]
]
| name <- kernel_names ]
ctx_inits =
[ [C.cstm|ctx->total_runs = 0;|],
[C.cstm|ctx->total_runtime = 0;|] ] ++
concat
[ [ [C.cstm|ctx->$id:(kernelRuntime name) = 0;|]
, [C.cstm|ctx->$id:(kernelRuns name) = 0;|]
]
| name <- kernel_names ]
openCL_load = [
[C.cedecl|
void setup_opencl_and_load_kernels($ty:ctx_ty *ctx) {
typename cl_int error;
typename cl_program prog = setup_opencl(&ctx->opencl, opencl_program);
// Load all the kernels.
$stms:(map (loadKernelByName) kernel_names)
$stms:final_inits
}|],
[C.cedecl|
void post_opencl_setup(struct opencl_context *ctx, struct opencl_device_option *option) {
$stms:(map sizeHeuristicsCode sizeHeuristicsTable)
}|]]
openCL_h = $(embedStringFile "rts/c/opencl.h")
openCL_boilerplate = [C.cunit|
$esc:openCL_h
const char *opencl_program[] =
{$inits:(opencl_program_fragments++[nullptr])};|]
loadKernelByName :: String -> C.Stm
loadKernelByName name = [C.cstm|{
ctx->$id:name = clCreateKernel(prog, $string:name, &error);
assert(error == 0);
if (ctx->debugging) {
fprintf(stderr, "Created kernel %s.\n", $string:name);
}
}|]
kernelRuntime :: String -> String
kernelRuntime = (++"_total_runtime")
kernelRuns :: String -> String
kernelRuns = (++"_runs")
openClReport :: [String] -> [C.BlockItem]
openClReport names = report_kernels ++ [report_total]
where longest_name = foldl max 0 $ map length names
report_kernels = concatMap reportKernel names
format_string name =
let padding = replicate (longest_name - length name) ' '
in unwords ["Kernel",
name ++ padding,
"executed %6d times, with average runtime: %6ldus\tand total runtime: %6ldus\n"]
reportKernel name =
let runs = kernelRuns name
total_runtime = kernelRuntime name
in [[C.citem|
fprintf(stderr,
$string:(format_string name),
ctx->$id:runs,
(long int) ctx->$id:total_runtime / (ctx->$id:runs != 0 ? ctx->$id:runs : 1),
(long int) ctx->$id:total_runtime);
|],
[C.citem|ctx->total_runtime += ctx->$id:total_runtime;|],
[C.citem|ctx->total_runs += ctx->$id:runs;|]]
report_total = [C.citem|
if (ctx->debugging) {
fprintf(stderr, "Ran %d kernels with cumulative runtime: %6ldus\n",
ctx->total_runs, ctx->total_runtime);
}
|]
sizeHeuristicsCode :: SizeHeuristic -> C.Stm
sizeHeuristicsCode
(SizeHeuristic platform_name device_type which what) =
[C.cstm|
if ($exp:which' == 0 &&
strstr(option->platform_name, $string:platform_name) != NULL &&
option->device_type == $exp:(clDeviceType device_type)) {
$stm:get_size
}|]
where clDeviceType DeviceGPU = [C.cexp|CL_DEVICE_TYPE_GPU|]
clDeviceType DeviceCPU = [C.cexp|CL_DEVICE_TYPE_CPU|]
which' = case which of
LockstepWidth -> [C.cexp|ctx->lockstep_width|]
NumGroups -> [C.cexp|ctx->cfg.num_groups|]
GroupSize -> [C.cexp|ctx->cfg.group_size|]
get_size = case what of
HeuristicConst x ->
[C.cstm|$exp:which' = $int:x;|]
HeuristicDeviceInfo s ->
-- This only works for device info that fits.
let s' = "CL_DEVICE_" ++ s
in [C.cstm|clGetDeviceInfo(ctx->device,
$id:s',
sizeof($exp:which'),
&$exp:which',
NULL);|]
| ihc/futhark | src/Futhark/CodeGen/Backends/COpenCL/Boilerplate.hs | isc | 11,189 | 0 | 14 | 3,453 | 1,567 | 892 | 675 | 130 | 5 |
-- Compose
-- ref: https://wiki.haskell.org/Compose
-- compose :: [a -> a] -> (a -> a)
-- chaining function
-- sane solution
compose :: [a -> a] -> a -> a
compose fs v = foldl (flip (.)) id fs $ v
-- using State
composeState :: [a -> a] -> a -> a
composeState = execState . mapM modify
-- consider it in the less eta-reduced form:
-- composeState fs v = execState (mapM modify fs) v
-- mapM iterates over the list of functions, applying modify to each one. If we were to expand a list after it had been mapped over in this way,
{-
fs = mapM modify [(*2), (+1), \n -> (n - 5) * 4]
-- fs is entirely equivalent to the following do-block:
fs' = do modify (*2)
modify (+1)
modify (\n -> (n - 5) * 4)
-}
-- using Reader
composeReader :: [a -> a] -> a -> a
composeReader fs v = runReader (compose' fs) v
where compose' [] = ask
compose' (f:fs) = local f (compose' fs)
-- compose' = foldr local ask
-- alternative: no runReader or ask required
composeReader' :: [a -> a] -> a -> a
composeReader' = foldr local id
{-
fs = compose' [(*2), (+1), \n -> (n - 5) * 4]
-- again, this is entirely equivalent to the following:
fs' = local (*2) $
local (+1) $
local (\n -> (n - 5) * 4) ask
-}
-- using Writer
composeWriter :: [a -> a] -> a -> a
composeWriter fs v = (execWriter $ compose' fs) v
where compose' [] = return id
compose' (f:fs) = censor (. f) (compose' fs)
-- compose' = foldr (censor . flip (.)) (return id)
-- ensor, to quote All About Monad, "...takes a function and a Writer and produces a new Writer whose output is the same but whose log entry has been modified by the function.".
-- using Cont
-- GOTO-style checkpoint
getCC :: MonadCont m => m (m a)
getCC = callCC (\c -> let x = c x in return x)
getCC' :: MonadCont m => a -> m (a, a -> m b)
getCC' x0 = callCC (\c -> let f x = c (x, f) in return (x0, f)
-- This takes m-sized chunks off of u (which starts off being x) until u is in range.
x `modulo` m = (`runContT` return) $ do (u, jump) <- getCC' x
lift $ print u
case u of
_ | u < 0 -> jump (u + m)
| u >= m -> jump (u - m)
| otherwise -> return u
composeCont :: [a -> a] -> a -> a
composeCont fs = runCont compose' id where
compose' = do ((gs,f), jump) <- getCC' (fs,id)
case gs of
[] -> return f
(g:gs') -> jump (gs', g . f)
| Airtnp/Freshman_Simple_Haskell_Lib | Idioms/Compose.hs | mit | 2,656 | 7 | 16 | 898 | 658 | 347 | 311 | -1 | -1 |
module Main where
import Test.DocTest
main :: IO ()
main = doctest ["Hello.hs"]
| kagamilove0707/learn-cabal | test/doctest.hs | mit | 82 | 0 | 6 | 15 | 30 | 17 | 13 | 4 | 1 |
module Import.NoFoundation
( module Import
) where
import Model as Import
import Settings as Import
import Settings.StaticFiles as Import
import Token as Import
import ClassyPrelude.Yesod as Import
import Data.Aeson as Import
import Yesod.Core.Types as Import (loggerSet)
import Yesod.Default.Config2 as Import
| pbrisbin/tee-io | src/Import/NoFoundation.hs | mit | 322 | 0 | 5 | 51 | 69 | 50 | 19 | 10 | 0 |
{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-}
module Y2017.M10.D05.Solution where
{--
Yesterday, I said: "Go out to the database, get some data, analyze it and chart
it." Well, that's all good if you can work on the problem when you have access
to the internet at large to retrieve your data from the DaaS, but let's say,
hypothetically speaking, that you're behind a firewall, so you only have tiny
slots of time when you go out for that Pumpkin Spiced Latte with your friendies
to access those data. You can't write code, get the data, analyze the data and
then plot the results over just one 'PSL' (The TLAs are taking over smh).
So, what's the solution? Order a second PSL? But then that contributes to the
obesity pandemic, and I don't want that on my resume, thank you very much.
And then there's the credit ratings to consider.
(somebody cue the theme to the movie 'Brazil')
So, the data sets we're talking about aren't petabytes nor exobytes, so why not
just retain those data locally so the development and analyses can be done
off-line or behind the firewall?
Why not, indeed!
Today's Haskell problem: read the rows of data from the article, subject, and
article_subject tables, save them locally as JSON, do some magic hand-waving
or coffee-drinking while you analyze those data off-line, then read in the
data from the JSON store.
--}
import Data.Aeson
import Data.Aeson.Encode.Pretty
import Data.Aeson.Types
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.HashMap.Strict as HM
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Text as T
import Data.Time
import Database.PostgreSQL.Simple
-- We've got the database reads from yesterday exercise. Do that.
-- below imports available via 1HaskellADay git repository
import Data.Hierarchy
import Store.SQL.Util.Indexed
import Store.SQL.Util.Pivots
import Y2017.M10.D04.Solution
-- Now let's save out those data to JSON
instance ToJSON Subject where
toJSON (IxV i val) = object ["id" .= i, "subject" .= val]
instance ToJSON Pivot where
toJSON (Pvt k1 k2) = object ["article_id" .= k1, "subject_id" .= k2]
instance ToJSON ArticleSummary where
toJSON (ArtSum i title published) =
object ["id" .= i, "title" .= title, "publish_dt" .= published]
-- Okay, so we've enjsonified the rows of the tables, now let's enjsonify
-- the entire table!
data Table a = Table { name :: String, rows :: [a] }
deriving (Eq, Show)
instance ToJSON a => ToJSON (Table a) where
toJSON (Table name rows) = object [T.pack name .= rows]
-- save out the three tables as JSON to their own files
-- TIME PASSES -------------------------------------------------------------
-- Okay now do the same thing IN REVERSE! Load the tables from JSON files
instance FromJSON a => FromJSON (Table a) where
parseJSON o = parseJSON o >>= parseKV . head . HM.toList
-- from https://stackoverflow.com/questions/42578331/aeson-parse-json-with-unknown-key-in-haskell
parseKV :: FromJSON a => (String, Value) -> Parser (Table a)
parseKV (name,list) = Table name <$> parseJSON list
-- Well, would you look at that! 'save to JSON' on SQL whatever saves ids as
-- strings. Isn't that... 'cute'! smh
instance FromJSON Subject where
parseJSON (Object o) = IxV <$> (read <$> o .: "id") <*> o .: "subject"
instance FromJSON Pivot where
parseJSON (Object o) = Pvt <$> (read <$> o .: "article_id")
<*> (read <$> o .: "subject_id")
instance FromJSON ArticleSummary where
parseJSON (Object o) = ArtSum <$> (read <$> o .: "id")
<*> o .: "title" <*> o .: "publish_dt"
-- read in your tables back
-- run your analyses
-- celebrate with Pumpkin Spice Lattes!
{--
>>> subjs <- (rows . fromJust . decode <$> BL.readFile "Y2017/M10/D05/subj.json") :: IO [Subject]
>>> length subjs
1193
>>> pivs <- (rows . fromJust . decode <$> BL.readFile "Y2017/M10/D05/art-subj.json") :: IO [Pivot]
>>> arts <- (rows . fromJust . decode <$> BL.readFile "Y2017/M10/D05/art.json") :: IO [ArticleSummary]
>>> length arts
599
--}
{-- BONUS -----------------------------------------------------------------
Once you have the grouping from yesterday, you can output the result
graphically as:
1. 3D scatterplot of topics by date
2. Concentric circles: topics containing dates containing articles
3. N-dimentional graph of Topics x Dates x Articles
you choose, or create your own data visualization
--}
-- With the generalization of hierarchies:
data ArchiveNode = Date Day | Group Topic | Sum ArticleSummary | Archive String
instance Tuple ArchiveNode where
toPair (Date d) = ("date", toJSON d)
toPair (Group t) = ("topic", toJSON t)
toPair (Sum art) = ("article", toJSON art)
toPair (Archive arc) = ("archive", toJSON arc)
{--
instance ToJSON ArchiveNode where
toJSON (Date d) = object ["date" .= d]
toJSON (Group t) = object ["topic" .= t]
toJSON (Sum art) = object ["article" .= art]
toJSON (Archive arc) = object ["archive" .= arc]
--}
visualize :: FilePath -> Grouping -> IO ()
visualize file = BL.writeFile file . encodePretty . groupToHierarchy
groupToHierarchy :: Grouping -> Hierarchy ArchiveNode
groupToHierarchy =
Hier (Archive "NYT Archive") . Kids . map topicArts . Map.toList
topicArts :: (Topic, Map Day [ArticleSummary]) -> Hierarchy ArchiveNode
topicArts (topic, days) =
Hier (Group topic) (Kids (map dayArts (Map.toList days)))
dayArts :: (Day, [ArticleSummary]) -> Hierarchy ArchiveNode
dayArts (d, ts) =
Hier (Date d) (Kids (map (flip Hier (Size 1) . Sum) ts))
{--
>>> let grp = graphTopics subjs pivs arts
>>> length grp
976
>>> visualize "Y2017/M10/D05/topics.json" grp
{
"children": [
{
"children": [
{
"children": [
{
"size": 1,
"name": "From an Undervalued Region in France, New Energy, New Inspiration and Great Wines"
}
],
"name": "2017-09-07"
}
],
"name": "19th century"
}, ...
],
"name": "NYT Archive"
}
*Looks at circles of all topics.
HOLY SHNITZELS! THAT THERE IS A LOT OF DATA!
'Tomorrow' we'll look at narrowing the view and looking at only a few topics.
--}
| geophf/1HaskellADay | exercises/HAD/Y2017/M10/D05/Solution.hs | mit | 6,403 | 0 | 14 | 1,380 | 962 | 527 | 435 | 57 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Tile where
import Data.Aeson ((.=), ToJSON, toJSON)
import qualified Data.Aeson as J
import qualified Data.ByteString.Lazy.Char8 as L
import System.FilePath ((</>))
import Geometry.Point
import Geometry.Rect
import RoadLink
import RoadNode
data Tile = T
{ tRoadLinks :: [RoadLink]
, tRoadNodes :: [RoadNode]
, tLocalMinLength :: Double
, tLocalMaxLength :: Double
, tLocalMeanLength :: Double
, tLocalStdDevLength :: Double
, tGlobalMinLength :: Double
, tGlobalMaxLength :: Double
, tGlobalMeanLength :: Double
, tGlobalStdDevLength :: Double
}
instance ToJSON Tile where
toJSON t =
J.object
[ "roadLinks" .= tRoadLinks t
, "roadNodes" .= tRoadNodes t
, "localMinLength" .= tLocalMinLength t
, "localMaxLength" .= tLocalMaxLength t
, "localMeanLength" .= tLocalMeanLength t
, "localStdDevLength" .= tLocalStdDevLength t
, "globalMinLength" .= tGlobalMinLength t
, "globalMaxLength" .= tGlobalMaxLength t
, "globalMeanLength" .= tGlobalMeanLength t
, "globalStdDevLength" .= tGlobalStdDevLength t
]
newTile :: Tile
newTile =
T { tRoadLinks = []
, tRoadNodes = []
, tLocalMinLength = 0
, tLocalMaxLength = 0
, tLocalMeanLength = 0
, tLocalStdDevLength = 0
, tGlobalMinLength = 0
, tGlobalMaxLength = 0
, tGlobalMeanLength = 0
, tGlobalStdDevLength = 0
}
addRoadLink :: RoadLink -> Tile -> Tile
addRoadLink rl t =
t { tRoadLinks = rl : (tRoadLinks t)
}
addRoadNode :: RoadNode -> Tile -> Tile
addRoadNode rn t =
t { tRoadNodes = rn : (tRoadNodes t)
}
setLocalData :: Double -> Double -> Double -> Double -> Tile -> Tile
setLocalData lmin lmax lmean lstddev t =
t { tLocalMinLength = lmin
, tLocalMaxLength = lmax
, tLocalMeanLength = lmean
, tLocalStdDevLength = lstddev
}
setGlobalData :: Double -> Double -> Double -> Double -> Tile -> Tile
setGlobalData gmin gmax gmean gstddev t =
t { tGlobalMinLength = gmin
, tGlobalMaxLength = gmax
, tGlobalMeanLength = gmean
, tGlobalStdDevLength = gstddev
}
outputTile :: FilePath -> (Int, Int) -> Tile -> IO ()
outputTile out tc =
L.writeFile (out </> tileFileName tc) . J.encode
tileName :: (Int, Int) -> String
tileName (tx, ty) =
"tile-" ++ show tx ++ "-" ++ show ty
tileFileName :: (Int, Int) -> FilePath
tileFileName tc =
tileName tc ++ ".json"
tileCoords :: (Int, Int) -> Point Double -> (Int, Int)
tileCoords (width, height) (P x y) =
(tx, ty)
where
tx = floor (x / fromIntegral width)
ty = floor (y / fromIntegral height)
tileBounds :: (Int, Int) -> (Int, Int) -> Rect Double
tileBounds (width, height) (tx, ty) =
R left top right bottom
where
left = fromIntegral (width * tx)
top = fromIntegral (height * ty)
right = fromIntegral (width * (tx + 1))
bottom = fromIntegral (height * (ty + 1))
| mietek/map-cutter | src/Tile.hs | mit | 3,147 | 0 | 11 | 901 | 924 | 523 | 401 | 85 | 1 |
import Math.NumberTheory.Primes
main = print . sum . takeWhile (<2000000) $ primes
| chrisfosterelli/euler.hs | solutions/010.hs | mit | 83 | 0 | 8 | 12 | 31 | 17 | 14 | 2 | 1 |
module Database.Kafka (
module Database.Kafka.Core,
module Database.Kafka.Types
) where
import Database.Kafka.Core
import Database.Kafka.Types | yanatan16/haskell-kafka | src/Database/Kafka.hs | mit | 145 | 0 | 5 | 15 | 34 | 23 | 11 | 5 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module JPSubreddits.Source.Newsokur where
import Control.Applicative
import Control.Monad.IO.Class (MonadIO)
import Data.Maybe (listToMaybe, mapMaybe)
import qualified Data.Text as T
import JPSubreddits.Types
import Network.HTTP.Conduit (simpleHttp)
import qualified Text.HTML.DOM as HTML
import qualified Text.XML as XML
import Text.XML.Cursor (($/), ($//), (&//))
import qualified Text.XML.Cursor as XML
-- newsokurのwikiからスクレイピングでリストを取得
-- div.md.wiki下にある各tableに次の処理を行う
--
-- - 最初thのテキスト要素をカテゴリタイトルとする
-- - 以降のtdに含まれるa要素のhref属性をURL、テキスト要素をサブレ名として抽出
-- ただしhref属性の値がサブレのURLでない場合は無視する。
--
-- URL判定の方法
-- prefixが/r/
-- それ以降の最初の/又は終端までに文字列が存在する。
--
-- とりあえず取得してくるコード書く
data Newsokur = Newsokur
deriving (Show, Read)
instance DataSource Newsokur where
getListFromDataSource _ = getListFromNewsokur
getListFromNewsokur :: (Functor m, MonadIO m) => m [(CategoryName, [(Title, Url)])]
getListFromNewsokur = extract <$> getWiki
getWiki :: (Functor m, MonadIO m) => m XML.Document
getWiki = HTML.parseLBS <$> simpleHttp "http://www.reddit.com/r/newsokur/wiki/simple_list_ja"
extract :: XML.Document -> [(CategoryName, [(Title, Url)])]
extract doc = map category tables
where
c = XML.fromDocument doc
tables = c $// XML.attributeIs "class" "md wiki" &// XML.element "table"
-- | tableへのCursorを渡す
category :: XML.Cursor -> (CategoryName, [(Title, Url)])
category c = (CategoryName cn, ss)
where
cn = maybe "unknown" (\c' -> T.concat $ c' $/ XML.content) $ listToMaybe $ c $// XML.element "th"
ss = mapMaybe subreddit $ c $// XML.element "td" &// XML.element "a"
-- | aへのCursorを渡す
subreddit :: XML.Cursor -> Maybe (Title, Url)
subreddit c
| isSubredditUrl u = Just (t, dropSlash u)
| otherwise = Nothing
where
u = Url $ T.concat $ XML.attribute "href" c
t = Title $ T.concat $ c $/ XML.content
-- | subredditへの相対パスであるかどうかチェックする
isSubredditUrl :: Url -> Bool
isSubredditUrl (Url u) = "/r/" `T.isPrefixOf` u
-- | 末尾に/があれば取り除く
dropSlash :: Url -> Url
dropSlash = Url . T.dropWhileEnd (== '/') . unUrl
| sifisifi/jpsubreddits | src/JPSubreddits/Source/Newsokur.hs | mit | 2,597 | 0 | 15 | 460 | 616 | 352 | 264 | 38 | 1 |
-- | Data type for Mailgun API keys.
module Mailgun.APIKey
( APIKey(..)
) where
import Data.Aeson (FromJSON, parseJSON)
import Data.ByteArray (ByteArrayAccess)
import Data.ByteString (ByteString)
import Data.Text.Encoding (encodeUtf8)
-- | A Mailgun API key.
newtype APIKey = APIKey { unAPIKey :: ByteString }
deriving (Show, Eq, ByteArrayAccess)
instance FromJSON APIKey where
parseJSON value = APIKey . encodeUtf8 <$> parseJSON value
| fusionapp/catcher-in-the-rye | src/Mailgun/APIKey.hs | mit | 447 | 0 | 7 | 70 | 116 | 69 | 47 | 10 | 0 |
{- |
module: $Header$
description: Primitive 16-bit word functions
license: MIT
maintainer: Joe Leslie-Hurd <joe@gilith.com>
stability: provisional
portability: portable
-}
module OpenTheory.Primitive.Word16
( Word16,
and,
bit,
fromBytes,
fromNatural,
not,
or,
shiftLeft,
shiftRight,
toBytes )
where
import Prelude (Bool, (<), (&&), fromIntegral)
import qualified Data.Bits
import qualified Data.Word
import qualified OpenTheory.Primitive.Byte as Primitive.Byte
import qualified OpenTheory.Primitive.Natural as Primitive.Natural
type Word16 = Data.Word.Word16
and :: Word16 -> Word16 -> Word16
and w1 w2 = (Data.Bits..&.) w1 w2
bit :: Word16 -> Primitive.Natural.Natural -> Bool
bit w i = i < 16 && Data.Bits.testBit w (fromIntegral i)
fromBytes :: Primitive.Byte.Byte -> Primitive.Byte.Byte -> Word16
fromBytes b0 b1 = or (fromIntegral b0) (shiftLeft (fromIntegral b1) 8)
fromNatural :: Primitive.Natural.Natural -> Word16
fromNatural = fromIntegral
not :: Word16 -> Word16
not w = (Data.Bits.complement) w
or :: Word16 -> Word16 -> Word16
or w1 w2 = (Data.Bits..|.) w1 w2
shiftLeft :: Word16 -> Primitive.Natural.Natural -> Word16
shiftLeft w n =
if n < 16 then (Data.Bits.shiftL) w (fromIntegral n) else 0
shiftRight :: Word16 -> Primitive.Natural.Natural -> Word16
shiftRight w n =
if n < 16 then (Data.Bits.shiftR) w (fromIntegral n) else 0
toBytes :: Word16 -> (Primitive.Byte.Byte,Primitive.Byte.Byte)
toBytes w = (fromIntegral w, fromIntegral (shiftRight w 8))
| gilith/opentheory | data/haskell/opentheory-primitive/src/OpenTheory/Primitive/Word16.hs | mit | 1,527 | 0 | 9 | 260 | 474 | 272 | 202 | 37 | 2 |
type Point = (Int, Int)
data Direction = North | South | East | West
origin :: Point
origin = (0, 0)
displacement :: Point -> Point -> Int
displacement (x1, y1) (x2, y2) = xdiff + ydiff
where xdiff = abs (x1 - x2)
ydiff = abs (y1 - y2)
move :: Point -> Direction -> Int -> [Point]
move _ _ 0 = []
move (x, y) dir dist = (move p' dir (dist - 1)) ++ [p']
where p' = case dir of North -> (x, y + 1)
South -> (x, y - 1)
East -> (x + 1, y)
West -> (x - 1, y)
step :: [(Point, Direction)] -> String -> [(Point, Direction)]
step [] _ = [(origin, North)]
step l@((p, d):_) (t:a) = points ++ l
where points = map (\point -> (point, d')) $ move p d' a'
d' = turn d t
a' = read a :: Int
turn :: Direction -> Char -> Direction
turn North 'L' = West
turn North 'R' = East
turn South 'L' = East
turn South 'R' = West
turn East 'L' = North
turn East 'R' = South
turn West 'L' = South
turn West 'R' = North
count :: Eq a => a -> [a] -> Int
count _ [] = 0
count e (x:xs)
| e == x = 1 + count e xs
| otherwise = count e xs
main = do
input <- getContents
let history@(endpoint:_) = foldl step [(origin, North)] (lines input)
pointsInOrder = reverse $ map fst history
repeatPoints = filter (\x -> (count x pointsInOrder) > 1) pointsInOrder in
print $ (displacement origin $ fst $ endpoint, displacement origin $ head repeatPoints)
| ajm188/advent_of_code | 2016/01/Main.hs | mit | 1,486 | 0 | 16 | 460 | 724 | 388 | 336 | 41 | 4 |
module Interaction.FarmingProperties where
import TestFramework
import TestHelpers
import Rules
import Prelude hiding (lookup)
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.QuickCheck.Monadic
import Data.List ((\\))
import Data.Map (keys, lookup)
import Data.Maybe (listToMaybe)
import Data.Function ((&))
import Data.AdditiveGroup
farmingTests :: TestTree
farmingTests = localOption (QuickCheckMaxRatio 500) $ testGroup "Farming properties" $ [
testProperty "Planting crops adds crops" $ farmingProperty $ do
playerId <- findFarmingPlayer
cropsToPlant <- pickCropsToPlant playerId
pre $ not $ null $ cropsToPlant
applyToUniverse $ plantCrops playerId cropsToPlant
newCrops <- getsUniverse getPlantedCrops <*> pure playerId
let verifyCrop (Potatoes, pos) = lookup pos newCrops == Just (PlantedCrop Potatoes 2)
verifyCrop (Wheat, pos) = lookup pos newCrops == Just (PlantedCrop Wheat 3)
assert $ all verifyCrop cropsToPlant,
testProperty "Planting crops not on fields is not possible" $ farmingProperty $ do
playerId <- findFarmingPlayer
let nonFieldPositions (SmallBuilding buildingType pos) = if buildingType == Field then [] else [pos]
nonFieldPositions (LargeBuilding _ pos dir) = [pos, directionAddition dir ^+^ pos]
buildingSpace <- getsUniverse getBuildingSpace <*> pure playerId
validPositions <- pickPlantingPositions playerId
invalidPositions <- pick $ shuffle $ nonFieldPositions =<< buildingSpace
cropTypes <- pickCropTypes playerId True True
pre $ length cropTypes > 1
invalidCount <- pick $ choose (1, length cropTypes)
validCount <- pick $ choose (0, length cropTypes - invalidCount)
positions <- pick $ shuffle $ take invalidCount invalidPositions ++ take validCount validPositions
applyToUniverse $ plantCrops playerId (zip cropTypes positions)
shouldHaveFailed,
testProperty "Planting too many crops is not possible" $ farmingProperty $ do
playerId <- findFarmingPlayer
positions <- pickPlantingPositions playerId
pre $ length positions >= 3
tooManyType <- pick $ elements [Potatoes, Wheat]
additionalCount <- pick $ choose (0, length positions - 3)
additionalCrops <- pick $ vectorOf additionalCount $ elements [Potatoes, Wheat]
crops <- pick $ shuffle $ additionalCrops ++ (replicate 3 tooManyType)
applyToUniverse $ plantCrops playerId (zip crops positions)
shouldHaveFailed,
testProperty "Planting more than had is not possible" $ farmingProperty $ do
playerId <- findFarmingPlayer
positions <- pickPlantingPositions playerId
potatoCorrect <- pick $ elements [True, False]
wheatCorrect <- pick $ elements [not potatoCorrect, False]
crops <- pickCropTypes playerId wheatCorrect potatoCorrect
pre $ length positions >= length crops
applyToUniverse $ plantCrops playerId (zip crops positions)
shouldHaveFailed,
testProperty "Planting crops subtracts resources" $ farmingProperty $ do
playerId <- findFarmingPlayer
originalResources <- getsUniverse getPlayerResources <*> pure playerId
crops <- pickCropsToPlant playerId
pre $ not $ null $ crops
applyToUniverse $ plantCrops playerId crops
newResources <- getsUniverse getPlayerResources <*> pure playerId
let potatoCount = length $ filter (== Potatoes) $ fst <$> crops
wheatCount = length $ filter (== Wheat) $ fst <$> crops
assert $ potatoCount == getPotatoAmount originalResources - getPotatoAmount newResources
assert $ wheatCount == getWheatAmount originalResources - getWheatAmount newResources
]
farmingProperty :: Testable a => UniversePropertyMonad a -> Property
farmingProperty = propertyWithProperties $ defaultGeneratorProperties &
withWorkplaceProbability Farming 20 &
withFarmingProbability 20 &
withNoResourceChangeSteps
findFarmingPlayer :: UniversePropertyMonad PlayerId
findFarmingPlayer = do
universe <- getUniverse
plId <- preMaybe $ listToMaybe [plId | plId <- getPlayers universe, isPlantingCrops universe plId]
checkPlayerHasValidOccupants plId
return plId
pickPlantingPositions :: PlayerId -> UniversePropertyMonad [Position]
pickPlantingPositions plId = do
buildingSpace <- getsUniverse getBuildingSpace <*> pure plId
existingCrops <- getsUniverse getPlantedCrops <*> pure plId
let fieldPosition (SmallBuilding Field pos) = [pos]
fieldPosition _ = []
allFieldPositions = buildingSpace >>= fieldPosition
freeFieldPositions = allFieldPositions \\ keys existingCrops
pick $ shuffle freeFieldPositions
pickCropsToPlant :: PlayerId -> UniversePropertyMonad [(CropType, Position)]
pickCropsToPlant plId = do
positions <- pickPlantingPositions plId
count <- pick $ choose (0, 4)
cropTypes <- pickCropTypes plId True True
return $ take count $ zip cropTypes positions
pickCropTypes :: PlayerId -> Bool -> Bool -> UniversePropertyMonad [CropType]
pickCropTypes plId wheatCorrect potatoCorrect = do
resources <- getsUniverse getPlayerResources <*> pure plId
let getAmount correct getter = if correct then pick $ choose (0, min 2 (getter resources))
else do
pre $ getter resources < 2
pick $ choose (getter resources + 1, 2)
potatoCount <- getAmount potatoCorrect getPotatoAmount
wheatCount <- getAmount wheatCorrect getWheatAmount
pick $ shuffle (replicate potatoCount Potatoes ++ replicate wheatCount Wheat)
| martin-kolinek/some-board-game-rules | test/Interaction/FarmingProperties.hs | mit | 5,520 | 0 | 17 | 1,063 | 1,546 | 736 | 810 | 104 | 4 |
-- | A minimal Haskbot server can be run via:
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > import Network.Haskbot
-- > import Network.Haskbot.Config
-- > import Network.Haskbot.Plugin
-- > import qualified Network.Haskbot.Plugin.Help as Help
-- >
-- > main :: IO ()
-- > main = haskbot config registry
-- >
-- > config :: Config
-- > config = Config { listenOn = 3000
-- > , incEndpoint = "https://my-company.slack.com/services/hooks/incoming-webhook"
-- > , incToken = "my-incoming-token"
-- > }
-- >
-- > registry :: [Plugin]
-- > registry = [ Help.register registry "my-slash-token" ]
--
-- This will run Haskbot on port 3000 with the included
-- "Network.Haskbot.Plugin.Help" plugin installed, where @\"my-slash-token\"@
-- is the secret token of a Slack slash command integration corresponding to
-- the @/haskbot@ command and pointing to the Haskbot server.
--
-- Be sure to create a Slack incoming integration (usually named /Haskbot/)
-- and set the 'incEndpoint' and 'incToken' to their corresponding values, so
-- that Slack can receive replies from Haskbot.
module Haskbot
(
-- * Run a Haskbot server
haskbot
) where
import Haskbot.Internal.Server (webServer)
import Haskbot.Config (Config)
import Haskbot.Plugin (Plugin)
-- | Run the listed plugins on a Haskbot server with the given config
haskbot :: Config -- ^ Your custom-created config
-> [Plugin] -- ^ List of all Haskbot plugins to include
-> IO ()
haskbot = webServer
| Jonplussed/haskbot-core | src/Haskbot.hs | mit | 1,536 | 0 | 8 | 324 | 99 | 72 | 27 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-graphqlapi-logconfig.html
module Stratosphere.ResourceProperties.AppSyncGraphQLApiLogConfig where
import Stratosphere.ResourceImports
-- | Full data type definition for AppSyncGraphQLApiLogConfig. See
-- 'appSyncGraphQLApiLogConfig' for a more convenient constructor.
data AppSyncGraphQLApiLogConfig =
AppSyncGraphQLApiLogConfig
{ _appSyncGraphQLApiLogConfigCloudWatchLogsRoleArn :: Maybe (Val Text)
, _appSyncGraphQLApiLogConfigFieldLogLevel :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON AppSyncGraphQLApiLogConfig where
toJSON AppSyncGraphQLApiLogConfig{..} =
object $
catMaybes
[ fmap (("CloudWatchLogsRoleArn",) . toJSON) _appSyncGraphQLApiLogConfigCloudWatchLogsRoleArn
, fmap (("FieldLogLevel",) . toJSON) _appSyncGraphQLApiLogConfigFieldLogLevel
]
-- | Constructor for 'AppSyncGraphQLApiLogConfig' containing required fields
-- as arguments.
appSyncGraphQLApiLogConfig
:: AppSyncGraphQLApiLogConfig
appSyncGraphQLApiLogConfig =
AppSyncGraphQLApiLogConfig
{ _appSyncGraphQLApiLogConfigCloudWatchLogsRoleArn = Nothing
, _appSyncGraphQLApiLogConfigFieldLogLevel = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-graphqlapi-logconfig.html#cfn-appsync-graphqlapi-logconfig-cloudwatchlogsrolearn
asgqlalcCloudWatchLogsRoleArn :: Lens' AppSyncGraphQLApiLogConfig (Maybe (Val Text))
asgqlalcCloudWatchLogsRoleArn = lens _appSyncGraphQLApiLogConfigCloudWatchLogsRoleArn (\s a -> s { _appSyncGraphQLApiLogConfigCloudWatchLogsRoleArn = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-graphqlapi-logconfig.html#cfn-appsync-graphqlapi-logconfig-fieldloglevel
asgqlalcFieldLogLevel :: Lens' AppSyncGraphQLApiLogConfig (Maybe (Val Text))
asgqlalcFieldLogLevel = lens _appSyncGraphQLApiLogConfigFieldLogLevel (\s a -> s { _appSyncGraphQLApiLogConfigFieldLogLevel = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/AppSyncGraphQLApiLogConfig.hs | mit | 2,139 | 0 | 12 | 205 | 264 | 151 | 113 | 27 | 1 |
-- Copyright (c) 2005, 2008 Don Stewart - http://www.cse.unsw.edu.au/~dons
-- Introductory binding for the 'ee' editor
module Yi.Keymap.Ee ( keymap ) where
import Yi.Yi
import Control.Arrow
import Yi.Keymap.Emacs.KillRing
keymap :: Keymap
keymap = comap eventToChar (command +++ insert)
-- Control keys:
-- ^a ascii code ^i tab ^r right
-- ^b bottom of text ^j newline ^t top of text
-- ^c command ^k delete char ^u up
-- ^d down ^l left ^v undelete word
-- ^e search prompt ^m newline ^w delete word
-- ^f undelete char ^n next page ^x search
-- ^g begin of line ^o end of line ^y delete line
-- ^h backspace ^p prev page ^z undelete line
-- ^[ (escape) menu
insert :: Interact Char ()
insert = do c <- satisfy (const True); write (insertN c)
command :: Interact Char ()
command = choice [event c >> write act | (c, act) <- cmds]
where cmds = [('\^R', rightB ),
('\^B', botB ),
('\^T', topB ),
('\^K', deleteN 1 ),
('\^U', execB Move VLine Backward),
('\^D', execB Move VLine Forward),
('\^L', leftB ),
('\^G', moveToSol ),
('\^O', moveToEol ),
('\^Y', killLineE ),
('\^H', bdeleteB ),
('\^X', quitEditor )]
| codemac/yi-editor | src/Yi/Keymap/Ee.hs | gpl-2.0 | 1,579 | 0 | 10 | 667 | 288 | 172 | 116 | 22 | 1 |
module Settings.StaticFiles where
import Prelude (IO)
import Yesod.Static
import qualified Yesod.Static as Static
import Settings (staticDir)
import Settings.Development
import Language.Haskell.TH (Q, Exp, Name)
import Data.Default (def)
-- | use this to create your static file serving site
staticSite :: IO Static.Static
staticSite = if development then Static.staticDevel staticDir
else Static.static staticDir
-- | This generates easy references to files in the static directory at compile time,
-- giving you compile-time verification that referenced files exist.
-- Warning: any files added to your static directory during run-time can't be
-- accessed this way. You'll have to use their FilePath or URL to access them.
$(staticFiles Settings.staticDir)
combineSettings :: CombineSettings
combineSettings = def
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets' development combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts' development combineSettings
| marcellussiegburg/autotool | yesod/Settings/StaticFiles.hs | gpl-2.0 | 1,096 | 0 | 8 | 184 | 191 | 108 | 83 | -1 | -1 |
import Control.Monad.Reader
import System.Environment
import System.Console.Haskeline
import FQuoter.Commands
import FQuoter.Config.Config
import FQuoter.Parser.Parser
main :: IO ()
main = runInputT defaultSettings interpreter
interpreter :: InputT IO ()
interpreter = do args <- liftIO getArgs
config <- liftIO readConfig
case parseInput(unwords args) of
Left s -> outputStrLn $ show s
Right c -> executeCommand config c
| Raveline/FQuoter | src/FQuoter/Main.hs | gpl-3.0 | 502 | 0 | 11 | 134 | 138 | 69 | 69 | 14 | 2 |
{-|
Module : Lipid.Parsers.KnownSn.GlycerophospholipidSpec
Description :
Copyright : Michael Thomas
License : GPL-3
Maintainer : Michael Thomas <Michaelt293@gmail.com>
Stability : Experimental
-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeApplications #-}
module Lipid.Parsers.KnownSn.GlycerophospholipidSpec where
import Lipid.Blocks
import Test.Hspec
import Lipid.KnownSn.Glycerophospholipid
import Lipid.Parsers.KnownSn.Glycerophospholipid
spec :: Spec
spec = do
describe "Test for quasiquoters and Shorthand instances" $ do
it "QuasiQuoter for PA 14:0/16:0" $
shorthand @ (PA (Maybe DeltaPosition)) [paMaybeDelta|PA 14:0/16:0|] `shouldBe` "PA 14:0/16:0"
it "QuasiQuoter for PA 14:0/16:0" $
shorthand @ (PA DeltaPosition) [paDelta|PA 14:0/16:0|] `shouldBe` "PA 14:0/16:0"
it "QuasiQuoter for PA 14:0/18:1(9)" $
shorthand [paMaybeDelta|PA 14:0/18:1(9)|] `shouldBe` "PA 14:0/18:1(9)"
it "QuasiQuoter for PA 14:0/18:1(9)" $
shorthand [paDelta|PA 14:0/18:1(9)|] `shouldBe` "PA 14:0/18:1(9)"
it "QuasiQuoter for PA 14:0/18:1(9Z)" $
shorthand [paMaybeDelta|PA 14:0/18:1(9Z)|] `shouldBe` "PA 14:0/18:1(9Z)"
it "QuasiQuoter for PA 14:0/18:1(9Z)" $
shorthand [paDelta|PA 14:0/18:1(9Z)|] `shouldBe` "PA 14:0/18:1(9Z)"
it "QuasiQuoter for PA 14:0/18:1" $
shorthand @ (PA (Maybe DeltaPosition)) [paMaybeDelta|PA 14:0/18:1|] `shouldBe` "PA 14:0/18:1"
it "QuasiQuoter for PE 14:0/16:0" $
shorthand @ (PE (Maybe DeltaPosition)) [peMaybeDelta|PE 14:0/16:0|] `shouldBe` "PE 14:0/16:0"
it "QuasiQuoter for PE 14:0/16:0" $
shorthand @ (PE DeltaPosition) [peDelta|PE 14:0/16:0|] `shouldBe` "PE 14:0/16:0"
it "QuasiQuoter for PE 14:0/18:1(9)" $
shorthand [peMaybeDelta|PE 14:0/18:1(9)|] `shouldBe` "PE 14:0/18:1(9)"
it "QuasiQuoter for PE 14:0/18:1(9)" $
shorthand [peDelta|PE 14:0/18:1(9)|] `shouldBe` "PE 14:0/18:1(9)"
it "QuasiQuoter for PE 14:0/18:1(9Z)" $
shorthand [peMaybeDelta|PE 14:0/18:1(9Z)|] `shouldBe` "PE 14:0/18:1(9Z)"
it "QuasiQuoter for PE 14:0/18:1(9Z)" $
shorthand [peDelta|PE 14:0/18:1(9Z)|] `shouldBe` "PE 14:0/18:1(9Z)"
it "QuasiQuoter for PE 14:0/18:1" $
shorthand @ (PE (Maybe DeltaPosition)) [peMaybeDelta|PE 14:0/18:1|] `shouldBe` "PE 14:0/18:1"
it "QuasiQuoter for PG 14:0/18:1(9Z)" $
shorthand [pgMaybeDelta|PG 14:0/18:1(9Z)|] `shouldBe` "PG 14:0/18:1(9Z)"
it "QuasiQuoter for PG 14:0/18:1(9Z)" $
shorthand [pgDelta|PG 14:0/18:1(9Z)|] `shouldBe` "PG 14:0/18:1(9Z)"
it "QuasiQuoter for PG 14:0/18:1" $
shorthand @ (PG (Maybe DeltaPosition)) [pgMaybeDelta|PG 14:0/18:1|] `shouldBe` "PG 14:0/18:1"
it "QuasiQuoter for PS 14:0/18:1(9Z)" $
shorthand [psMaybeDelta|PS 14:0/18:1(9Z)|] `shouldBe` "PS 14:0/18:1(9Z)"
it "QuasiQuoter for PS 14:0/18:1(9Z)" $
shorthand [psDelta|PS 14:0/18:1(9Z)|] `shouldBe` "PS 14:0/18:1(9Z)"
it "QuasiQuoter for PS 14:0/18:1" $
shorthand @ (PS (Maybe DeltaPosition)) [psMaybeDelta|PS 14:0/18:1|] `shouldBe` "PS 14:0/18:1"
it "QuasiQuoter for PI 14:0/18:1(9Z)" $
shorthand [piMaybeDelta|PI 14:0/18:1(9Z)|] `shouldBe` "PI 14:0/18:1(9Z)"
it "QuasiQuoter for PI 14:0/18:1(9Z)" $
shorthand [piDelta|PI 14:0/18:1(9Z)|] `shouldBe` "PI 14:0/18:1(9Z)"
it "QuasiQuoter for PI 14:0/18:1" $
shorthand @ (PI (Maybe DeltaPosition)) [piMaybeDelta|PI 14:0/18:1|] `shouldBe` "PI 14:0/18:1"
it "QuasiQuoter for PGP 14:0/18:1(9Z)" $
shorthand [pgpMaybeDelta|PGP 14:0/18:1(9Z)|] `shouldBe` "PGP 14:0/18:1(9Z)"
it "QuasiQuoter for PGP 14:0/18:1(9Z)" $
shorthand [pgpDelta|PGP 14:0/18:1(9Z)|] `shouldBe` "PGP 14:0/18:1(9Z)"
it "QuasiQuoter for PGP 14:0/18:1" $
shorthand @ (PGP (Maybe DeltaPosition)) [pgpMaybeDelta|PGP 14:0/18:1|] `shouldBe` "PGP 14:0/18:1"
it "QuasiQuoter for PC 14:0/18:1(9Z)" $
shorthand [pcMaybeDelta|PC 14:0/18:1(9Z)|] `shouldBe` "PC 14:0/18:1(9Z)"
it "QuasiQuoter for PC 14:0/18:1(9Z)" $
shorthand [pcDelta|PC 14:0/18:1(9Z)|] `shouldBe` "PC 14:0/18:1(9Z)"
it "QuasiQuoter for PC 14:0/18:1" $
shorthand @ (PC (Maybe DeltaPosition)) [pcMaybeDelta|PC 14:0/18:1|] `shouldBe` "PC 14:0/18:1"
it "QuasiQuoter for PIP 14:0/18:1(9Z)" $
shorthand [pipMaybeDelta|PIP 14:0/18:1(9Z)|] `shouldBe` "PIP 14:0/18:1(9Z)"
it "QuasiQuoter for PIP 14:0/18:1(9Z)" $
shorthand [pipDelta|PIP 14:0/18:1(9Z)|] `shouldBe` "PIP 14:0/18:1(9Z)"
it "QuasiQuoter for PIP 14:0/18:1" $
shorthand @ (PIP (Maybe DeltaPosition)) [pipMaybeDelta|PIP 14:0/18:1|] `shouldBe` "PIP 14:0/18:1"
it "QuasiQuoter for PIP2 14:0/18:1(9Z)" $
shorthand [pip2MaybeDelta|PIP2 14:0/18:1(9Z)|] `shouldBe` "PIP2 14:0/18:1(9Z)"
it "QuasiQuoter for PIP2 14:0/18:1(9Z)" $
shorthand [pip2Delta|PIP2 14:0/18:1(9Z)|] `shouldBe` "PIP2 14:0/18:1(9Z)"
it "QuasiQuoter for PIP2 14:0/18:1" $
shorthand @ (PIP2 (Maybe DeltaPosition)) [pip2MaybeDelta|PIP2 14:0/18:1|] `shouldBe` "PIP2 14:0/18:1"
describe "Test for quasiquoters and nNomenclature instances" $ do
it "QuasiQuoter for PA 14:0/16:0" $
nNomenclature @ (PA (Maybe OmegaPosition)) [paMaybeOmega|PA 14:0/16:0|] `shouldBe` "PA 14:0/16:0"
it "QuasiQuoter for PA 14:0/16:0" $
nNomenclature @ (PA OmegaPosition) [paDelta|PA 14:0/16:0|] `shouldBe` "PA 14:0/16:0"
it "QuasiQuoter for PA 14:0/18:1(n-9)(n-6)" $
nNomenclature [paMaybeOmega|PA 14:0/18:1(n-9)|] `shouldBe` "PA 14:0/18:1(n-9)"
it "QuasiQuoter for PA 14:0/18:1(n-9)" $
nNomenclature [paOmega|PA 14:0/18:1(n-9)|] `shouldBe` "PA 14:0/18:1(n-9)"
it "QuasiQuoter for PA 14:0/18:1(n-9Z)" $
nNomenclature [paMaybeOmega|PA 14:0/18:1(n-9Z)|] `shouldBe` "PA 14:0/18:1(n-9)"
it "QuasiQuoter for PA 14:0/18:1(n-9)" $
nNomenclature [paOmega|PA 14:0/18:1(n-9)|] `shouldBe` "PA 14:0/18:1(n-9)"
it "QuasiQuoter for PA 14:0/18:1" $
nNomenclature @ (PA (Maybe OmegaPosition)) [paMaybeOmega|PA 14:0/18:1|] `shouldBe` "PA 14:0/18:1"
it "QuasiQuoter for PE 14:0/18:1(n-9Z)" $
nNomenclature [peMaybeOmega|PE 14:0/18:1(n-9Z)|] `shouldBe` "PE 14:0/18:1(n-9)"
it "QuasiQuoter for PE 14:0/18:1(n-9)(n-6)" $
nNomenclature [peOmega|PE 14:0/18:1(n-9)|] `shouldBe` "PE 14:0/18:1(n-9)"
it "QuasiQuoter for PE 14:0/18:1" $
nNomenclature @ (PE (Maybe OmegaPosition)) [peMaybeOmega|PE 14:0/18:1|] `shouldBe` "PE 14:0/18:1"
it "QuasiQuoter for PC 14:0/18:1(n-9Z)" $
nNomenclature [pcMaybeOmega|PC 14:0/18:1(n-9Z)|] `shouldBe` "PC 14:0/18:1(n-9)"
it "QuasiQuoter for PC 14:0/18:1(n-9)" $
nNomenclature [pcOmega|PC 14:0/18:1(n-9)|] `shouldBe` "PC 14:0/18:1(n-9)"
it "QuasiQuoter for PC 14:0/18:1" $
nNomenclature @ (PC (Maybe OmegaPosition)) [pcMaybeOmega|PC 14:0/18:1|] `shouldBe` "PC 14:0/18:1"
it "QuasiQuoter for PS 14:0/18:1(n-9Z)" $
nNomenclature [psMaybeOmega|PS 14:0/18:1(n-9Z)|] `shouldBe` "PS 14:0/18:1(n-9)"
it "QuasiQuoter for PS 14:0/18:1(n-9)" $
nNomenclature [psOmega|PS 14:0/18:1(n-9)|] `shouldBe` "PS 14:0/18:1(n-9)"
it "QuasiQuoter for PS 14:0/18:1" $
nNomenclature @ (PS (Maybe OmegaPosition)) [psMaybeOmega|PS 14:0/18:1|] `shouldBe` "PS 14:0/18:1"
it "QuasiQuoter for PG 14:0/18:1(n-9Z)" $
nNomenclature [pgMaybeOmega|PG 14:0/18:1(n-9Z)|] `shouldBe` "PG 14:0/18:1(n-9)"
it "QuasiQuoter for PG 14:0/18:1(n-9)" $
nNomenclature [pgOmega|PG 14:0/18:1(n-9)|] `shouldBe` "PG 14:0/18:1(n-9)"
it "QuasiQuoter for PG 14:0/18:1" $
nNomenclature @ (PG (Maybe OmegaPosition)) [pgMaybeOmega|PG 14:0/18:1|] `shouldBe` "PG 14:0/18:1"
it "QuasiQuoter for PGP 14:0/18:1(n-9Z)" $
nNomenclature [pgpMaybeOmega|PGP 14:0/18:1(n-9Z)|] `shouldBe` "PGP 14:0/18:1(n-9)"
it "QuasiQuoter for PGP 14:0/18:1(n-9)" $
nNomenclature [pgpOmega|PGP 14:0/18:1(n-9)|] `shouldBe` "PGP 14:0/18:1(n-9)"
it "QuasiQuoter for PGP 14:0/18:1" $
nNomenclature @ (PGP (Maybe OmegaPosition)) [pgpMaybeOmega|PGP 14:0/18:1|] `shouldBe` "PGP 14:0/18:1"
it "QuasiQuoter for PI 14:0/18:1(n-9Z)" $
nNomenclature [piMaybeOmega|PI 14:0/18:1(n-9Z)|] `shouldBe` "PI 14:0/18:1(n-9)"
it "QuasiQuoter for PI 14:0/18:1(n-9)(n-6)" $
nNomenclature [piOmega|PI 14:0/18:1(n-9)|] `shouldBe` "PI 14:0/18:1(n-9)"
it "QuasiQuoter for PI 14:0/18:1" $
nNomenclature @ (PI (Maybe OmegaPosition)) [piMaybeOmega|PI 14:0/18:1|] `shouldBe` "PI 14:0/18:1"
it "QuasiQuoter for PIP 14:0/18:1(n-9Z)" $
nNomenclature [pipMaybeOmega|PIP 14:0/18:1(n-9Z)|] `shouldBe` "PIP 14:0/18:1(n-9)"
it "QuasiQuoter for PIP 14:0/18:1(n-9)" $
nNomenclature [pipOmega|PIP 14:0/18:1(n-9)|] `shouldBe` "PIP 14:0/18:1(n-9)"
it "QuasiQuoter for PIP 14:0/18:1" $
nNomenclature @ (PIP (Maybe OmegaPosition)) [pipMaybeOmega|PIP 14:0/18:1|] `shouldBe` "PIP 14:0/18:1"
it "QuasiQuoter for PIP2 14:0/18:1(n-9Z)" $
nNomenclature [pip2MaybeOmega|PIP2 14:0/18:1(n-9Z)|] `shouldBe` "PIP2 14:0/18:1(n-9)"
it "QuasiQuoter for PIP2 14:0/18:1(n-9)" $
nNomenclature [pip2Omega|PIP2 14:0/18:1(n-9)|] `shouldBe` "PIP2 14:0/18:1(n-9)"
it "QuasiQuoter for PIP2 14:0/18:1" $
nNomenclature @ (PIP2 (Maybe OmegaPosition)) [pip2MaybeOmega|PIP2 14:0/18:1|] `shouldBe` "PIP2 14:0/18:1"
| Michaelt293/Lipid-Haskell | test/Lipid/Parsers/KnownSn/GlycerophospholipidSpec.hs | gpl-3.0 | 9,327 | 0 | 17 | 1,649 | 1,948 | 1,079 | 869 | 143 | 1 |
{---------------------------------------------------------------------}
{- Copyright 2015 Nathan Bloomfield -}
{- -}
{- This file is part of Feivel. -}
{- -}
{- Feivel is free software: you can redistribute it and/or modify -}
{- it under the terms of the GNU General Public License version 3, -}
{- as published by the Free Software Foundation. -}
{- -}
{- Feivel 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 Feivel. If not, see <http://www.gnu.org/licenses/>. -}
{---------------------------------------------------------------------}
module Carl.Algebra.Ring (
AlgErr(..),
Ringoid,
rAdd, rMul, rNeg, rZero, rIsZero, rSub, rSum, rDot, rEQ, rProd,
rNeutOf, rLAnnOf, rRAnnOf,
rAddT, rMulT, rNegT, rSubT, rSumT, rDotT,
RingoidDiv,
rDivides,
rDividesT,
CRingoid,
ORingoid,
rLT, rGT, rLEQ, rGEQ,
rMin, rMax, rMinim, rMaxim,
rIsPos, rIsNeg, rAbs, rIsNegOne,
rAbsT, rMinT, rMaxT, rMinimT, rMaximT,
URingoid,
rOne, rIsOne, rUProd, rInjInt, rChoose, rInv, rDiv, rPosPow,
rPow, rMean, rIsUnit, rLOneOf, rROneOf,
rDivT, rUProdT, rChooseT, rPowT, rMeanT, rIntMeanT, rMeanDevT,
rIntMeanDevT, rInvT, rPosPowT,
URingoidAssoc,
rAssoc,
GCDoid,
rGCD, rLCM, rGCDs, rLCMs,
rGCDT, rLCMT, rGCDsT, rLCMsT,
BDoid,
rBezout, rBezouts,
UFDoid,
rFactor, rRad, rIsSquare, rIsSqFree, rSqPart, rSqFreePart,
rRadT, rIsSquareT, rIsSqFreeT, rSqPartT, rSqFreePartT,
EDoid,
rNorm, rDivAlg, rQuo, rRem,
rNormT, rDivAlgT, rQuoT, rRemT,
rEuclidAlg, rEuclidGCD, rEuclidGCDs, rEuclidBezout, rEuclidBezouts,
rEuclidAlgT, rEuclidGCDT, rEuclidGCDsT, rEuclidBezoutT, rEuclidBezoutsT,
Fieldoid,
DagRingoid,
rDag,
BipRingoid,
rBipIn, rBipOut
) where
import Control.Monad.Instances ()
import Data.Numbers.Primes (primes)
import Carl.AlgErr
{------------------}
{- Contents -}
{- :Heirarchy -}
{- :Ringoid -}
{- :ORingoid -}
{- :CRingoid -}
{- :URingoid -}
{- :Domainoid -}
{- :GCDoid -}
{- :BDoid -}
{- :UFDoid -}
{- :EDoid -}
{- :Fieldoid -}
{- :Instances -}
{- :Integer -}
{- :Bool -}
{------------------}
{------------}
{- :Ringoid -}
{------------}
class Ringoid t where
rAdd :: t -> t -> Either AlgErr t
rMul :: t -> t -> Either AlgErr t
rNeg :: t -> t
rZero :: t
rIsZero :: t -> Bool
rNeutOf :: t -> Either AlgErr t
rLAnnOf :: t -> Either AlgErr t
rRAnnOf :: t -> Either AlgErr t
class RingoidDiv t where
rDivides :: t -> t -> Either AlgErr Bool
rEQ :: (Ringoid t) => t -> t -> Either AlgErr Bool
rEQ a b = do
z <- rSub a b
return $ rIsZero z
rSub :: (Ringoid t) => t -> t -> Either AlgErr t
rSub a b = rAdd a (rNeg b)
rSum :: (Ringoid t) => [t] -> Either AlgErr t
rSum [] = Right rZero
rSum [t] = Right t
rSum (t:ts) = do
s <- rSum ts
rAdd t s
rProd :: (Ringoid t) => [t] -> Either AlgErr t
rProd [] = Left (RingoidEmptyListErr "product")
rProd [t] = return t
rProd (t:ts) = do
s <- rProd ts
rMul t s
rDot :: (Ringoid t) => [t] -> [t] -> Either AlgErr t
rDot xs ys = do
zs <- sequence $ zipWith rMul xs ys
rSum zs
rPosPow :: (Ringoid t) => t -> Integer -> Either AlgErr t
rPosPow t k
| k < 0 = Left (RingoidNegativeExponentErr k)
| k == 0 = Left RingoidZeroExponentErr
| otherwise = rProd [t | _ <- [1..k]]
{- -}
rNegT :: (Ringoid t) => t -> t -> Either AlgErr t
rNegT _ = return . rNeg
rAddT, rMulT, rSubT :: (Ringoid t) => t -> t -> t -> Either AlgErr t
rAddT _ = rAdd
rMulT _ = rMul
rSubT _ = rSub
rSumT :: (Ringoid t) => t -> [t] -> Either AlgErr t
rSumT _ = rSum
rDividesT :: (RingoidDiv t) => t -> t -> t -> Either AlgErr Bool
rDividesT _ = rDivides
rDotT :: (Ringoid t) => t -> [t] -> [t] -> Either AlgErr t
rDotT _ = rDot
rPosPowT :: (Ringoid t) => t -> t -> Integer -> Either AlgErr t
rPosPowT _ = rPosPow
{-------------}
{- :ORingoid -}
{-------------}
class ORingoid t where
rLT :: t -> t -> Either AlgErr Bool
rIsPos :: t -> Bool
rIsNeg :: t -> Bool
rAbs :: (Ringoid t, ORingoid t) => t -> t
rAbs t = if rIsNeg t then (rNeg t) else t
rGT :: (ORingoid t) => t -> t -> Either AlgErr Bool
rGT x y = rLT y x
rLEQ :: (Ringoid t, ORingoid t) => t -> t -> Either AlgErr Bool
rLEQ x y = do
p <- rLT x y
q <- rEQ x y
return (p || q)
rGEQ :: (Ringoid t, ORingoid t) => t -> t -> Either AlgErr Bool
rGEQ x y = do
p <- rGT x y
q <- rEQ x y
return (p || q)
rMax :: (ORingoid t) => t -> t -> Either AlgErr t
rMax a b = do
p <- rLT a b
if p then return b else return a
rMin :: (ORingoid t) => t -> t -> Either AlgErr t
rMin a b = do
p <- rLT a b
if p then return a else return b
rMaxim :: (ORingoid t) => [t] -> Either AlgErr t
rMaxim [] = Left (RingoidEmptyListErr "maximum")
rMaxim [t] = return t
rMaxim (t:ts) = do
s <- rMaxim ts
rMax t s
rMinim :: (ORingoid t) => [t] -> Either AlgErr t
rMinim [] = Left (RingoidEmptyListErr "minimum")
rMinim [t] = return t
rMinim (t:ts) = do
s <- rMinim ts
rMin t s
{- -}
rAbsT :: (ORingoid t, Ringoid t) => t -> t -> Either AlgErr t
rAbsT _ = return . rAbs
rMinT, rMaxT :: (ORingoid t) => t -> t -> t -> Either AlgErr t
rMinT _ = rMin
rMaxT _ = rMax
rMaximT, rMinimT :: (ORingoid t) => t -> [t] -> Either AlgErr t
rMaximT _ = rMaxim
rMinimT _ = rMinim
{-------------}
{- :CRingoid -}
{-------------}
class CRingoid t
{-------------}
{- :URingoid -}
{-------------}
class URingoid t where
rOne :: t
rIsOne :: t -> Bool
rIsUnit :: t -> Either AlgErr Bool
rInjInt :: Integer -> Either AlgErr t
rInv :: t -> Either AlgErr t
rLOneOf :: t -> Either AlgErr t
rROneOf :: t -> Either AlgErr t
class URingoidAssoc t where
rAssoc :: t -> t -> Either AlgErr Bool
rIsNegOne :: (Ringoid t, URingoid t) => t -> Bool
rIsNegOne a = rIsOne (rNeg a)
rDiv :: (Ringoid t, URingoid t, CRingoid t) => t -> t -> Either AlgErr t
rDiv a b = do
c <- rInv b
rMul a c
rUProd :: (Ringoid t, URingoid t) => [t] -> Either AlgErr t
rUProd [] = return rOne
rUProd [t] = return t
rUProd (t:ts) = do
s <- rUProd ts
rMul t s
rChoose :: (URingoid t) => Integer -> Integer -> Either AlgErr t
rChoose n k
| n <= 0 || k < 0 || n < k = rInjInt 0
| otherwise = rInjInt $ (product [(k+1)..n]) `div` (product [1..n-k])
rPow :: (Ringoid t, URingoid t) => t -> Integer -> Either AlgErr t
rPow t n
| n > 0 = rPosPow t n
| n == 0 = return rOne
| otherwise = do
s <- rInv t
rPosPow s (-n)
rMean :: (Ringoid t, URingoid t, CRingoid t) => [t] -> Either AlgErr t
rMean [] = undefined
rMean ts = do
let n = sum $ map (const 1) ts
m <- rInjInt n
s <- rSum ts
rDiv s m
rMeanDev :: (Ringoid t, URingoid t, CRingoid t, ORingoid t) => [t] -> Either AlgErr t
rMeanDev [] = undefined
rMeanDev ts = do
mu <- rMean ts
as <- sequence $ map (`rSub` mu) ts
rMean $ map rAbs as
rIntMean :: (Ringoid t, URingoid t, CRingoid t) => [Integer] -> Either AlgErr t
rIntMean [] = Left (RingoidEmptyListErr "integer mean")
rIntMean ks = do
ts <- sequence $ map rInjInt ks
rMean ts
rIntMeanDev :: (Ringoid t, URingoid t, CRingoid t, ORingoid t) => [Integer] -> Either AlgErr t
rIntMeanDev [] = Left (RingoidEmptyListErr "integer mean deviation")
rIntMeanDev ks = do
ts <- sequence $ map rInjInt ks
rMeanDev ts
rInvT :: (Ringoid t, URingoid t, CRingoid t) => t -> t -> Either AlgErr t
rInvT _ = rInv
rDivT :: (Ringoid t, URingoid t, CRingoid t) => t -> t -> t -> Either AlgErr t
rDivT _ = rDiv
rUProdT :: (Ringoid t, URingoid t) => t -> [t] -> Either AlgErr t
rUProdT _ = rUProd
rChooseT :: (URingoid t) => t -> Integer -> Integer -> Either AlgErr t
rChooseT _ = rChoose
rPowT :: (Ringoid t, URingoid t) => t -> t -> Integer -> Either AlgErr t
rPowT _ = rPow
rMeanT :: (Ringoid t, URingoid t, CRingoid t) => t -> [t] -> Either AlgErr t
rMeanT _ = rMean
rMeanDevT :: (Ringoid t, URingoid t, CRingoid t, ORingoid t)
=> t -> [t] -> Either AlgErr t
rMeanDevT _ = rMeanDev
rIntMeanT :: (Ringoid t, URingoid t, CRingoid t) => t -> [Integer] -> Either AlgErr t
rIntMeanT _ = rIntMean
rIntMeanDevT :: (Ringoid t, URingoid t, CRingoid t, ORingoid t)
=> t -> [Integer] -> Either AlgErr t
rIntMeanDevT _ = rIntMeanDev
{--------------}
{- :Domainoid -}
{--------------}
class Domainoid t
{-----------}
{- :GCDoid -}
{-----------}
class GCDoid t where
rGCD :: t -> t -> Either AlgErr t
rLCM :: t -> t -> Either AlgErr t
rGCDs :: (Ringoid t, GCDoid t) => [t] -> Either AlgErr t
rGCDs [] = return rZero
rGCDs [t] = return t
rGCDs (t:ts) = rGCDs ts >>= rGCD t
rLCMs :: (URingoid t, GCDoid t) => [t] -> Either AlgErr t
rLCMs [] = return rOne
rLCMs [t] = return t
rLCMs (t:ts) = rLCMs ts >>= rLCM t
{- -}
rGCDT :: (GCDoid t) => t -> t -> t -> Either AlgErr t
rGCDT _ = rGCD
rLCMT :: (GCDoid t) => t -> t -> t -> Either AlgErr t
rLCMT _ = rLCM
rGCDsT :: (Ringoid t, GCDoid t) => t -> [t] -> Either AlgErr t
rGCDsT _ = rGCDs
rLCMsT :: (URingoid t, GCDoid t) => t -> [t] -> Either AlgErr t
rLCMsT _ = rLCMs
{----------}
{- :BDoid -}
{----------}
class BDoid t where
-- rBezout a b = Right (h,k) <==> ah+bk = gcd(a,b)
rBezout :: t -> t -> Either AlgErr (t,t)
rBezouts :: (Ringoid t, URingoid t, GCDoid t, BDoid t) => [t] -> Either AlgErr [t]
rBezouts [] = Right []
rBezouts [_] = return [rOne]
rBezouts [a,b] = do
(h,k) <- rBezout a b
return [h,k]
rBezouts (a:as) = do
d <- rGCDs as
(b1,b2) <- rBezout a d
ts <- rBezouts as
us <- sequence $ map (rMul b2) ts
return (b1:us)
{-----------}
{- :UFDoid -}
{-----------}
class UFDoid t where
rFactor :: t -> Either AlgErr (t, [(t, Integer)])
rIsSquare :: t -> Either AlgErr Bool
rIsSqFree :: t -> Either AlgErr Bool
rSqPart :: t -> Either AlgErr t
rSqFreePart :: t -> Either AlgErr t
rPrimeFactors :: (UFDoid t) => t -> Either AlgErr [t]
rPrimeFactors t = do
(_,xs) <- rFactor t
return $ map fst xs
rRad :: (Ringoid t, URingoid t, UFDoid t) => t -> Either AlgErr t
rRad t = do
ps <- rPrimeFactors t
rUProd ps
rIsSquareT, rIsSqFreeT :: (UFDoid t) => t -> t -> Either AlgErr Bool
rIsSquareT _ = rIsSquare
rIsSqFreeT _ = rIsSqFree
rSqPartT, rSqFreePartT :: (UFDoid t) => t -> t -> Either AlgErr t
rSqPartT _ = rSqPart
rSqFreePartT _ = rSqFreePart
rRadT :: (Ringoid t, URingoid t, UFDoid t) => t -> t -> Either AlgErr t
rRadT _ = rRad
{----------}
{- :EDoid -}
{----------}
class EDoid t where
rNorm :: t -> Either AlgErr Integer
rDivAlg :: t -> t -> Either AlgErr (t,t)
rQuo :: (EDoid t) => t -> t -> Either AlgErr t
rQuo a b = do
(q,_) <- rDivAlg a b
return q
rRem :: (EDoid t) => t -> t -> Either AlgErr t
rRem a b = do
(_,r) <- rDivAlg a b
return r
rEuclidAlg :: (Ringoid t, EDoid t) => t -> t -> Either AlgErr [(t,t)]
rEuclidAlg a b = do
(q,r) <- rDivAlg a b
if rIsZero r
then return [(q,r)]
else do
ts <- rEuclidAlg b r
return $ (q,r):ts
rEuclidGCD :: (Ringoid t, EDoid t) => t -> t -> Either AlgErr t
rEuclidGCD a b = do
ts <- rEuclidAlg a b
case tail $ reverse ts of
[] -> return b
(_,r):_ -> return r
rEuclidGCDs :: (Ringoid t, EDoid t) => [t] -> Either AlgErr t
rEuclidGCDs [] = return rZero
rEuclidGCDs [t] = return t
rEuclidGCDs (t:ts) = rEuclidGCDs ts >>= rEuclidGCD t
rEuclidBezout :: (Ringoid t, URingoid t, EDoid t) => t -> t -> Either AlgErr (t,t)
rEuclidBezout a b = do
if rIsZero b
then do
return (rOne, rZero)
else do
(q,r) <- rDivAlg a b
(h,k) <- rEuclidBezout b r
u <- rMul q k
v <- rSub h u
return (k,v)
rEuclidBezouts :: (Ringoid t, URingoid t, EDoid t) => [t] -> Either AlgErr [t]
rEuclidBezouts [] = Right []
rEuclidBezouts [_] = return [rOne]
rEuclidBezouts [a,b] = do
(h,k) <- rEuclidBezout a b
return [h,k]
rEuclidBezouts (a:as) = do
d <- rEuclidGCDs as
(b1,b2) <- rEuclidBezout a d
ts <- rEuclidBezouts as
us <- sequence $ map (rMul b2) ts
return (b1:us)
{- -}
rNormT :: (EDoid t) => t -> t -> Either AlgErr Integer
rNormT _ = rNorm
rDivAlgT :: (EDoid t) => t -> t -> t -> Either AlgErr (t,t)
rDivAlgT _ = rDivAlg
rQuoT, rRemT :: (EDoid t) => t -> t -> t -> Either AlgErr t
rQuoT _ = rQuo
rRemT _ = rRem
rEuclidAlgT :: (Ringoid t, EDoid t) => t -> t -> t -> Either AlgErr [(t,t)]
rEuclidAlgT _ = rEuclidAlg
rEuclidGCDT :: (Ringoid t, EDoid t) => t -> t -> t -> Either AlgErr t
rEuclidGCDT _ = rEuclidGCD
rEuclidGCDsT :: (Ringoid t, EDoid t) => t -> [t] -> Either AlgErr t
rEuclidGCDsT _ = rEuclidGCDs
rEuclidBezoutT :: (Ringoid t, URingoid t, EDoid t) => t -> t -> t -> Either AlgErr (t,t)
rEuclidBezoutT _ = rEuclidBezout
rEuclidBezoutsT :: (Ringoid t, URingoid t, EDoid t) => t -> [t] -> Either AlgErr [t]
rEuclidBezoutsT _ = rEuclidBezouts
{-------------}
{- :Fieldoid -}
{-------------}
class Fieldoid t
{------------------}
{- :DaggerRingoid -}
{------------------}
class DagRingoid t where
rDag :: t -> t -- transpose
{---------------------}
{- :BiproductRingoid -}
{---------------------}
class BipRingoid t where
rBipIn :: t -> t -> Either AlgErr t -- vcat
rBipOut :: t -> t -> Either AlgErr t -- hcat
{--------------}
{- :Instances -}
{--------------}
{------------}
{- :Integer -}
{------------}
instance Ringoid Integer where
rAdd a b = return (a+b)
rMul a b = return (a*b)
rNeg a = (-a)
rZero = 0
rIsZero a = (0 == a)
rNeutOf _ = return 0
rLAnnOf _ = return 0
rRAnnOf _ = return 0
instance RingoidDiv Integer where
rDivides 0 0 = return True
rDivides _ 0 = return False
rDivides a b = return (rem b a == 0)
instance ORingoid Integer where
rLT a b = return (a < b)
rIsPos a = (0 < a)
rIsNeg a = (a < 0)
instance CRingoid Integer
instance URingoid Integer where
rOne = 1
rIsOne a = (1 == a)
rIsUnit a = return (a==1 || a==(-1))
rInjInt a = return a
rInv 1 = return 1
rInv (-1) = return (-1)
rInv a = Left (RingoidNotInvertibleErr $ show a)
rLOneOf _ = return 1
rROneOf _ = return 1
instance URingoidAssoc Integer where
rAssoc a b = Right (a==b || a==(-b))
instance Domainoid Integer
instance GCDoid Integer where
rGCD a 0 = return (abs a)
rGCD 0 b = return (abs b)
rGCD a b = rEuclidGCD a b >>= (return . rAbs)
rLCM 0 _ = return 0
rLCM _ 0 = return 0
rLCM a b = return (lcm a b)
instance BDoid Integer where
rBezout = rEuclidBezout
instance UFDoid Integer where
rFactor 0 = Left undefined
rFactor n = do
let u = if n > 0 then 1 else (-1)
let ps = qux (abs n)
return (u,ps)
where
foo p = zip (iterate (p*) p) [1..]
baz h p = let (_,k) = head $ dropWhile (\(t,_) -> h`rem`t == 0) (foo p) in
(k-1, h `quot` (p^(k-1)))
qux = reverse . mung primes []
where
mung _ xs 1 = xs
mung (p:ps) xs m
= let (k,t) = baz m p in
if k==0
then mung ps xs m
else mung ps ((p,k):xs) t
mung _ _ _ = error "Integer UFDoid instance: rFactor"
rIsSquare n
| n < 0 = Right False
| n == 0 = Right True
| otherwise = Right $ foo 1
where
foo k = case compare (k^(2::Integer)) n of
GT -> False
EQ -> True
LT -> foo (k+1)
rIsSqFree 0 = return False
rIsSqFree n = do
k <- rSqPart n
return (k == 1)
rSqPart 0 = return 0
rSqPart n
| n < 0 = rSqPart (-n)
| n == 0 = Right 0
| otherwise = Right $ last $ filter (\k -> n`rem`(k*k) == 0) $ takeWhile (\k -> k*k <= n) [1..n]
rSqFreePart 0 = return 1
rSqFreePart n = do
d <- rSqPart n
return (div n (d*d))
instance EDoid Integer where
rNorm a = return (abs a)
rDivAlg a 1 = return (a,0)
rDivAlg a (-1) = return (-a,0)
rDivAlg 0 _ = return (0,0)
rDivAlg _ 0 = Left (RingoidDivideByZeroErr "")
rDivAlg a b
| b < 0 = do
(q,r) <- rDivAlg a (-b)
return (-q, r)
| a >= 0 = do
let q = (signum b) * (quot a (abs b))
let r = mod a (abs b)
return (q,r)
| otherwise = do
let t = mod (-a) (abs b)
let q = negate $ (signum b) * ((quot (-a) (abs b)) + (if t==0 then 0 else 1))
let r = if t==0 then 0 else (abs b) - t
return (q,r)
{---------}
{- :Bool -}
{---------}
instance Ringoid Bool where
-- xor
rAdd True True = return False
rAdd True False = return True
rAdd False True = return True
rAdd False False = return False
rMul p q = return (p && q)
rNeg = id
rZero = False
rIsZero t = (t == False)
rNeutOf _ = return False
rLAnnOf _ = return False
rRAnnOf _ = return False
instance RingoidDiv Bool where
-- implies
rDivides True True = return True
rDivides True False = return True
rDivides False True = return False
rDivides False False = return True
instance CRingoid Bool
instance URingoid Bool where
rOne = True
rIsOne t = (t == True)
rIsUnit = return . rIsOne
rInjInt k = return (odd k)
rInv True = return True
rInv False = Left (RingoidNotInvertibleErr "#f")
rLOneOf _ = return True
rROneOf _ = return True
instance URingoidAssoc Bool where
rAssoc a b = return (a == b)
instance Domainoid Bool
instance GCDoid Bool where
rGCD p q = return (p && q)
rLCM _ _ = return True
instance BDoid Bool where
rBezout False False = return (False, False)
rBezout False True = return (False, True)
rBezout True False = return (True, False)
rBezout True True = return (True, False)
instance EDoid Bool where
rNorm False = return 0
rNorm True = return 1
rDivAlg _ False = Left (RingoidDivideByZeroErr "#f")
rDivAlg True True = return (True, False)
rDivAlg False True = return (False, False)
instance Fieldoid Bool
{-----------}
{- :Tuples -}
{-----------}
instance (Ringoid a, Ringoid b) => Ringoid (a,b) where
rAdd (a1,b1) (a2,b2) = do
x <- rAdd a1 a2
y <- rAdd b1 b2
return (x,y)
rNeg (a,b) = (rNeg a, rNeg b)
rMul (a1,b1) (a2,b2) = do
x <- rMul a1 a2
y <- rMul b1 b2
return (x,y)
rZero = (rZero, rZero)
rIsZero (a,b) = (rIsZero a) && (rIsZero b)
rNeutOf (a,b) = do
x <- rNeutOf a
y <- rNeutOf b
return (x,y)
rLAnnOf (a,b) = do
x <- rLAnnOf a
y <- rLAnnOf b
return (x,y)
rRAnnOf (a,b) = do
x <- rRAnnOf a
y <- rRAnnOf b
return (x,y)
| nbloomf/carl | src/Carl/Algebra/Ring.hs | gpl-3.0 | 19,071 | 0 | 18 | 5,319 | 8,267 | 4,247 | 4,020 | -1 | -1 |
module Y2010.Q.C where
import Data.List
import Data.Maybe
solve :: Problem -> Solution
parse :: [String] -> [Problem]
data Solution = Solution Int
deriving Eq
instance Show Solution where
show (Solution x) = show x
data Problem = Problem { rides :: Int
, capacity :: Int
, ts :: [Int]
} deriving (Eq,Show)
parse (rkn:gs:rest) =
Problem _rides _capacity _queue : parse rest
where [_rides:_capacity:_] = [map read $ words rkn]
[_queue] = [map read $ words gs]
parse [] = []
solve (Problem _rides _capacity _queue) = Solution total
where total = sumRides _rides
sumRides cnt
| cnt <= length allGroups = sum $ take cnt allGroups
| otherwise =
sum (take cnt allGroups)
+ (((cnt - length allGroups) `div` length repeatingGroups) * sum repeatingGroups)
+ sum (take ((cnt - length allGroups) `mod` length repeatingGroups) repeatingGroups)
repeatingGroups = drop repeatingIndex allGroups
repeatingIndex = snd findGroups
allGroups = fst findGroups
findGroups = groups [] 0
groups pastGroups ind
| ind `elem` pastGroups = ([], fromMaybe 0 (elemIndex ind $ reverse pastGroups) `mod` length _queue)
| otherwise = (fst (cachedGroup ind) : fst (groups (ind:pastGroups) (snd (cachedGroup ind))), snd $ groups (ind:pastGroups) (snd (cachedGroup ind)))
realQueue = cycle _queue
cachedGroup ind = map group [0..(length _queue)] !! (ind `mod` length _queue)
group ind =
let group' cur ind
| cur == sum _queue = (cur, ind)
| cur + realQueue!!ind <= _capacity = group' (cur + realQueue!!ind) (ind+1)
| otherwise = (cur, ind)
in group' 0 ind
| joranvar/GoogleCodeJam | Y2010/Q/C.hs | gpl-3.0 | 1,939 | 0 | 16 | 666 | 708 | 361 | 347 | 41 | 1 |
module Test where
import Test.Tasty
import Test.Tasty.SmallCheck as SC
import Test.Tasty.QuickCheck as QC
import Test.Tasty.HUnit
import Environment.Discrete
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "FrABS Tests" [unitTests, propTests]
unitTests :: TestTree
unitTests =
testGroup
"FrABS Unit tests"
[test_environment_discrete_unitgroup]
propTests :: TestTree
propTests =
testGroup
"FrABS Property tests"
[test_environment_discrete_quickgroup] | thalerjonathan/phd | coding/libraries/chimera/src/tests/Test.hs | gpl-3.0 | 510 | 0 | 6 | 88 | 111 | 66 | 45 | 20 | 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.Licensing.LicenseAssignments.Get
-- 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)
--
-- Get a specific user\'s license by product SKU.
--
-- /See:/ <https://developers.google.com/admin-sdk/licensing/ Enterprise License Manager API Reference> for @licensing.licenseAssignments.get@.
module Network.Google.Resource.Licensing.LicenseAssignments.Get
(
-- * REST Resource
LicenseAssignmentsGetResource
-- * Creating a Request
, licenseAssignmentsGet
, LicenseAssignmentsGet
-- * Request Lenses
, lagXgafv
, lagUploadProtocol
, lagAccessToken
, lagSKUId
, lagUploadType
, lagUserId
, lagProductId
, lagCallback
) where
import Network.Google.AppsLicensing.Types
import Network.Google.Prelude
-- | A resource alias for @licensing.licenseAssignments.get@ method which the
-- 'LicenseAssignmentsGet' request conforms to.
type LicenseAssignmentsGetResource =
"apps" :>
"licensing" :>
"v1" :>
"product" :>
Capture "productId" Text :>
"sku" :>
Capture "skuId" Text :>
"user" :>
Capture "userId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] LicenseAssignment
-- | Get a specific user\'s license by product SKU.
--
-- /See:/ 'licenseAssignmentsGet' smart constructor.
data LicenseAssignmentsGet =
LicenseAssignmentsGet'
{ _lagXgafv :: !(Maybe Xgafv)
, _lagUploadProtocol :: !(Maybe Text)
, _lagAccessToken :: !(Maybe Text)
, _lagSKUId :: !Text
, _lagUploadType :: !(Maybe Text)
, _lagUserId :: !Text
, _lagProductId :: !Text
, _lagCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LicenseAssignmentsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lagXgafv'
--
-- * 'lagUploadProtocol'
--
-- * 'lagAccessToken'
--
-- * 'lagSKUId'
--
-- * 'lagUploadType'
--
-- * 'lagUserId'
--
-- * 'lagProductId'
--
-- * 'lagCallback'
licenseAssignmentsGet
:: Text -- ^ 'lagSKUId'
-> Text -- ^ 'lagUserId'
-> Text -- ^ 'lagProductId'
-> LicenseAssignmentsGet
licenseAssignmentsGet pLagSKUId_ pLagUserId_ pLagProductId_ =
LicenseAssignmentsGet'
{ _lagXgafv = Nothing
, _lagUploadProtocol = Nothing
, _lagAccessToken = Nothing
, _lagSKUId = pLagSKUId_
, _lagUploadType = Nothing
, _lagUserId = pLagUserId_
, _lagProductId = pLagProductId_
, _lagCallback = Nothing
}
-- | V1 error format.
lagXgafv :: Lens' LicenseAssignmentsGet (Maybe Xgafv)
lagXgafv = lens _lagXgafv (\ s a -> s{_lagXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
lagUploadProtocol :: Lens' LicenseAssignmentsGet (Maybe Text)
lagUploadProtocol
= lens _lagUploadProtocol
(\ s a -> s{_lagUploadProtocol = a})
-- | OAuth access token.
lagAccessToken :: Lens' LicenseAssignmentsGet (Maybe Text)
lagAccessToken
= lens _lagAccessToken
(\ s a -> s{_lagAccessToken = a})
-- | A product SKU\'s unique identifier. For more information about available
-- SKUs in this version of the API, see Products and SKUs.
lagSKUId :: Lens' LicenseAssignmentsGet Text
lagSKUId = lens _lagSKUId (\ s a -> s{_lagSKUId = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
lagUploadType :: Lens' LicenseAssignmentsGet (Maybe Text)
lagUploadType
= lens _lagUploadType
(\ s a -> s{_lagUploadType = a})
-- | The user\'s current primary email address. If the user\'s email address
-- changes, use the new email address in your API requests. Since a
-- \`userId\` is subject to change, do not use a \`userId\` value as a key
-- for persistent data. This key could break if the current user\'s email
-- address changes. If the \`userId\` is suspended, the license status
-- changes.
lagUserId :: Lens' LicenseAssignmentsGet Text
lagUserId
= lens _lagUserId (\ s a -> s{_lagUserId = a})
-- | A product\'s unique identifier. For more information about products in
-- this version of the API, see Products and SKUs.
lagProductId :: Lens' LicenseAssignmentsGet Text
lagProductId
= lens _lagProductId (\ s a -> s{_lagProductId = a})
-- | JSONP
lagCallback :: Lens' LicenseAssignmentsGet (Maybe Text)
lagCallback
= lens _lagCallback (\ s a -> s{_lagCallback = a})
instance GoogleRequest LicenseAssignmentsGet where
type Rs LicenseAssignmentsGet = LicenseAssignment
type Scopes LicenseAssignmentsGet =
'["https://www.googleapis.com/auth/apps.licensing"]
requestClient LicenseAssignmentsGet'{..}
= go _lagProductId _lagSKUId _lagUserId _lagXgafv
_lagUploadProtocol
_lagAccessToken
_lagUploadType
_lagCallback
(Just AltJSON)
appsLicensingService
where go
= buildClient
(Proxy :: Proxy LicenseAssignmentsGetResource)
mempty
| brendanhay/gogol | gogol-apps-licensing/gen/Network/Google/Resource/Licensing/LicenseAssignments/Get.hs | mpl-2.0 | 6,093 | 0 | 22 | 1,502 | 871 | 508 | 363 | 127 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module NGramCrackers.Parsers.Paragraph
( parseSent
, parseParagraph
, parseMultiPara
, wordString
) where
import Control.Applicative ((<$>), (<*), (*>), (<*>), (<|>), liftA3)
import Data.Functor (void)
import Data.List (concat, unwords)
import Data.Text as T
import Text.Parsec.Text as PT
import Text.ParserCombinators.Parsec hiding ((<|>))
import NGramCrackers.DataTypes
parseSent :: T.Text -> Either ParseError [T.Text]
parseSent = parse sentence "unknown"
parseParagraph :: T.Text -> Either ParseError [[T.Text]]
parseParagraph = parse paragraph "unknown"
parseMultiPara :: T.Text -> Either ParseError [[[T.Text]]]
parseMultiPara = parse docBody "unknown"
docMetadata :: [MetaTag]
docMetadata = undefined
docBody :: PT.Parser [[[T.Text]]]
docBody = endBy paragraph eop
paragraph :: PT.Parser [[T.Text]]
paragraph = endBy sentence eos
sentence :: PT.Parser [T.Text]
sentence = sepBy sentParts seppr
sentParts :: PT.Parser T.Text
sentParts = word <|> number
wordString :: PT.Parser T.Text
-- Useful for non-sentence word strings where no numbers need to be parsed.
-- Probably useful for parsing MetaTags
wordString = T.unwords <$> sepBy word seppr
word :: PT.Parser T.Text
-- The use of T.pack <$> is necessary because of the type many1 letter returns.
-- fmapping T.pack into the Parser makes it possible to return a parser of the
-- appropriate type.
word = T.pack <$> many1 letter
number :: PT.Parser T.Text
number = T.pack <$> many1 digit
seppr :: PT.Parser ()
-- Since the results of this parser are just thrown away, we need the `void`
-- function from Data.Functor
seppr = void sepprs <|> void newLn
where sepprs = space'
<|> (char ',' *> space')
<|> (char ';' *> space')
<|> (char ':' *> space')
newLn = many1 (char '\n')
space' = char ' '
eos :: PT.Parser ()
eos = void sepprs -- <|> void sngls
where sepprs = (char '.' <* space')
<|> (char '!' <* space')
<|> (char '?' <* space')
{- sngls = (char '.')
<|> (char '!')
<|> (char '?')
-}
space' = many (char ' ')
eop :: PT.Parser ()
eop = void $
char '<' >> many1 letter >> char '>' <* (void space' <|> void newLn)
where space' = char ' '
newLn = many1 (char '\n')
| R-Morgan/NGramCrackers | testsuite/NGramCrackers/Parsers/Paragraph.hs | agpl-3.0 | 2,528 | 0 | 12 | 714 | 679 | 373 | 306 | 54 | 1 |
module HelperSequences.A001057Spec (main, spec) where
import Test.Hspec
import HelperSequences.A001057 (a001057)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A001057" $
it "correctly computes the first 20 elements" $
take 20 (map a001057 [0..]) `shouldBe` expectedValue where
expectedValue = [0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10]
| peterokagey/haskellOEIS | test/HelperSequences/A001057Spec.hs | apache-2.0 | 375 | 0 | 10 | 59 | 178 | 104 | 74 | 10 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- XML Signature Syntax and Processing
--
-- <http://www.w3.org/TR/2008/REC-xmldsig-core-20080610/> (selected portions)
module SAML2.XML.Signature
( module SAML2.XML.Signature.Types
, generateReference
, SigningKey(..)
, PublicKeys(..)
, signingKeySignatureAlgorithm
, signBase64
, verifyBase64
, generateSignature
, verifySignature
) where
import Control.Applicative ((<|>))
import Control.Monad (guard, (<=<))
import Crypto.Number.Basic (numBytes)
import Crypto.Number.Serialize (i2ospOf_, os2ip)
import Crypto.Hash (hashlazy, SHA1(..), SHA256(..), SHA512(..), RIPEMD160(..))
import qualified Crypto.PubKey.DSA as DSA
import qualified Crypto.PubKey.RSA.Types as RSA
import qualified Crypto.PubKey.RSA.PKCS15 as RSA
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base64 as Base64
import qualified Data.ByteString.Lazy as BSL
import qualified Data.List.NonEmpty as NonEmpty
import Data.Maybe (isJust)
import Data.Monoid ((<>))
import qualified Data.X509 as X509
import Network.URI (URI(..))
import qualified Text.XML.HXT.Core as HXT
import qualified Text.XML.HXT.DOM.ShowXml as DOM
import qualified Text.XML.HXT.DOM.XmlNode as DOM
import qualified Text.XML.HXT.DOM.QualifiedName as DOM
import SAML2.XML
import SAML2.XML.Canonical
import qualified Text.XML.HXT.Arrow.Pickle.Xml.Invertible as XP
import SAML2.XML.Signature.Types
isDSElem :: HXT.ArrowXml a => String -> a HXT.XmlTree HXT.XmlTree
isDSElem n = HXT.isElem HXT.>>> HXT.hasQName (mkNName ns n)
getID :: HXT.ArrowXml a => String -> a HXT.XmlTree HXT.XmlTree
getID = HXT.deep . HXT.hasAttrValue "ID" . (==)
applyCanonicalization :: CanonicalizationMethod -> Maybe String -> HXT.XmlTree -> IO BS.ByteString
applyCanonicalization (CanonicalizationMethod (Identified a) ins []) x y = canonicalize a ins x y
applyCanonicalization m _ _ = fail $ "applyCanonicalization: unsupported " ++ show m
applyTransformsBytes :: [Transform] -> BSL.ByteString -> IO BSL.ByteString
applyTransformsBytes [] v = return v
applyTransformsBytes (t : _) _ = fail ("applyTransforms: unsupported Signature " ++ show t)
applyTransformsXML :: [Transform] -> HXT.XmlTree -> IO BSL.ByteString
applyTransformsXML (Transform (Identified (TransformCanonicalization a)) ins x : tl) =
applyTransformsBytes tl . BSL.fromStrict
<=< applyCanonicalization (CanonicalizationMethod (Identified a) ins (map (XP.pickleDoc XP.xpickle) x)) Nothing
applyTransformsXML (Transform (Identified TransformEnvelopedSignature) Nothing [] : tl) =
-- XXX assumes "this" signature in top-level
applyTransformsXML tl
. head . HXT.runLA (HXT.processChildren $ HXT.processChildren
$ HXT.neg (isDSElem "Signature"))
applyTransformsXML tl = applyTransformsBytes tl . DOM.xshowBlob . return
applyTransforms :: Maybe Transforms -> HXT.XmlTree -> IO BSL.ByteString
applyTransforms = applyTransformsXML . maybe [] (NonEmpty.toList . transforms)
asType :: a -> proxy a -> proxy a
asType _ = id
applyDigest :: DigestMethod -> BSL.ByteString -> BS.ByteString
applyDigest (DigestMethod (Identified DigestSHA1) []) = BA.convert . asType SHA1 . hashlazy
applyDigest (DigestMethod (Identified DigestSHA256) []) = BA.convert . asType SHA256 . hashlazy
applyDigest (DigestMethod (Identified DigestSHA512) []) = BA.convert . asType SHA512 . hashlazy
applyDigest (DigestMethod (Identified DigestRIPEMD160) []) = BA.convert . asType RIPEMD160 . hashlazy
applyDigest d = error $ "unsupported " ++ show d
generateReference :: Reference -> HXT.XmlTree -> IO Reference
generateReference r x = do
t <- applyTransforms (referenceTransforms r) x
let d = applyDigest (referenceDigestMethod r) t
return r
{ referenceDigestValue = d }
verifyReference :: Reference -> HXT.XmlTree -> IO (Maybe String)
verifyReference r doc = case referenceURI r of
Just URI{ uriScheme = "", uriAuthority = Nothing, uriPath = "", uriQuery = "", uriFragment = '#':xid }
| x@[_] <- HXT.runLA (getID xid) doc -> do
t <- applyTransforms (referenceTransforms r) $ DOM.mkRoot [] x
return $ xid <$ guard (applyDigest (referenceDigestMethod r) t == referenceDigestValue r)
_ -> return Nothing
data SigningKey
= SigningKeyDSA DSA.KeyPair
| SigningKeyRSA RSA.KeyPair
deriving (Eq, Show)
data PublicKeys = PublicKeys
{ publicKeyDSA :: Maybe DSA.PublicKey
, publicKeyRSA :: Maybe RSA.PublicKey
} deriving (Eq, Show)
#if MIN_VERSION_base(4,11,0)
instance Semigroup PublicKeys where
PublicKeys dsa1 rsa1 <> PublicKeys dsa2 rsa2 =
PublicKeys (dsa1 <|> dsa2) (rsa1 <|> rsa2)
#endif
instance Monoid PublicKeys where
mempty = PublicKeys Nothing Nothing
PublicKeys dsa1 rsa1 `mappend` PublicKeys dsa2 rsa2 =
PublicKeys (dsa1 <|> dsa2) (rsa1 <|> rsa2)
signingKeySignatureAlgorithm :: SigningKey -> SignatureAlgorithm
signingKeySignatureAlgorithm (SigningKeyDSA _) = SignatureDSA_SHA1
signingKeySignatureAlgorithm (SigningKeyRSA _) = SignatureRSA_SHA1
signingKeyValue :: SigningKey -> KeyValue
signingKeyValue (SigningKeyDSA (DSA.toPublicKey -> DSA.PublicKey p y)) = DSAKeyValue
{ dsaKeyValuePQ = Just (DSA.params_p p, DSA.params_q p)
, dsaKeyValueG = Just (DSA.params_g p)
, dsaKeyValueY = y
, dsaKeyValueJ = Nothing
, dsaKeyValueSeedPgenCounter = Nothing
}
signingKeyValue (SigningKeyRSA (RSA.toPublicKey -> RSA.PublicKey _ n e)) = RSAKeyValue
{ rsaKeyValueModulus = n
, rsaKeyValueExponent = e
}
publicKeyValues :: KeyValue -> PublicKeys
publicKeyValues DSAKeyValue{ dsaKeyValuePQ = Just (p, q), dsaKeyValueG = Just g, dsaKeyValueY = y } = mempty
{ publicKeyDSA = Just $ DSA.PublicKey
{ DSA.public_params = DSA.Params
{ DSA.params_p = p
, DSA.params_q = q
, DSA.params_g = g
}
, DSA.public_y = y
}
}
publicKeyValues RSAKeyValue{ rsaKeyValueModulus = n, rsaKeyValueExponent = e } = mempty
{ publicKeyRSA = Just $ RSA.PublicKey (numBytes n) n e
}
publicKeyValues _ = mempty
signBytes :: SigningKey -> BS.ByteString -> IO BS.ByteString
signBytes (SigningKeyDSA k) b = do
s <- DSA.sign (DSA.toPrivateKey k) SHA1 b
return $ i2ospOf_ 20 (DSA.sign_r s) <> i2ospOf_ 20 (DSA.sign_s s)
signBytes (SigningKeyRSA k) b =
either (fail . show) return =<< RSA.signSafer (Just SHA1) (RSA.toPrivateKey k) b
-- | indicate verification result; return 'Nothing' if no matching key/alg pair is found
verifyBytes :: PublicKeys -> IdentifiedURI SignatureAlgorithm -> BS.ByteString -> BS.ByteString -> Maybe Bool
verifyBytes PublicKeys{ publicKeyDSA = Just k } (Identified SignatureDSA_SHA1) sig m = Just $
BS.length sig == 40 &&
DSA.verify SHA1 k DSA.Signature{ DSA.sign_r = os2ip r, DSA.sign_s = os2ip s } m
where (r, s) = BS.splitAt 20 sig
verifyBytes PublicKeys{ publicKeyRSA = Just k } (Identified SignatureRSA_SHA1) sig m = Just $
RSA.verify (Just SHA1) k m sig
verifyBytes PublicKeys{ publicKeyRSA = Just k } (Identified SignatureRSA_SHA256) sig m = Just $
RSA.verify (Just SHA256) k m sig
verifyBytes _ _ _ _ = Nothing
signBase64 :: SigningKey -> BS.ByteString -> IO BS.ByteString
signBase64 sk = fmap Base64.encode . signBytes sk
verifyBase64 :: PublicKeys -> IdentifiedURI SignatureAlgorithm -> BS.ByteString -> BS.ByteString -> Maybe Bool
verifyBase64 pk alg sig m = either (const $ Just False) (\s -> verifyBytes pk alg s m) $ Base64.decode sig
generateSignature :: SigningKey -> SignedInfo -> IO Signature
generateSignature sk si = do
-- XXX: samlToDoc may not match later
six <- applyCanonicalization (signedInfoCanonicalizationMethod si) Nothing $ samlToDoc si
sv <- signBytes sk six
return Signature
{ signatureId = Nothing
, signatureSignedInfo = si
, signatureSignatureValue = SignatureValue Nothing sv
, signatureKeyInfo = Just $ KeyInfo Nothing $ KeyInfoKeyValue (signingKeyValue sk) NonEmpty.:| []
, signatureObject = []
}
-- Exception in IO: something is syntactically wrong with the input
-- Nothing: no matching key/alg pairs found
-- Just False: signature verification failed || dangling refs || explicit ref is not among the signed ones
-- Just True: everything is ok!
verifySignature :: PublicKeys -> String -> HXT.XmlTree -> IO (Maybe Bool)
verifySignature pks xid doc = do
let namespaces = DOM.toNsEnv $ HXT.runLA HXT.collectNamespaceDecl doc
x <- case HXT.runLA (getID xid HXT.>>> HXT.attachNsEnv namespaces) doc of
[x] -> return x
_ -> fail "verifySignature: element not found"
sx <- case child "Signature" x of
[sx] -> return sx
_ -> fail "verifySignature: Signature not found"
s@Signature{ signatureSignedInfo = si } <- either fail return $ docToSAML sx
six <- applyCanonicalization (signedInfoCanonicalizationMethod si) (Just xpath) $ DOM.mkRoot [] [x]
rl <- mapM (`verifyReference` x) (signedInfoReference si)
let verified :: Maybe Bool
verified = verifyBytes pks (signatureMethodAlgorithm $ signedInfoSignatureMethod si) (signatureValue $ signatureSignatureValue s) six
valid :: Bool
valid = elem (Just xid) rl && all isJust rl
return $ (valid &&) <$> verified
where
child n = HXT.runLA $ HXT.getChildren HXT.>>> isDSElem n HXT.>>> HXT.cleanupNamespaces HXT.collectPrefixUriPairs
keyinfo (KeyInfoKeyValue kv) = publicKeyValues kv
keyinfo (X509Data l) = foldMap keyx509d l
keyinfo _ = mempty
keyx509d (X509Certificate sc) = keyx509p $ X509.certPubKey $ X509.getCertificate sc
keyx509d _ = mempty
keyx509p (X509.PubKeyRSA r) = mempty{ publicKeyRSA = Just r }
keyx509p (X509.PubKeyDSA d) = mempty{ publicKeyDSA = Just d }
keyx509p _ = mempty
xpathsel t = "/*[local-name()='" ++ t ++ "' and namespace-uri()='" ++ namespaceURIString ns ++ "']"
xpathbase = "/*" ++ xpathsel "Signature" ++ xpathsel "SignedInfo" ++ "//"
xpath = xpathbase ++ ". | " ++ xpathbase ++ "@* | " ++ xpathbase ++ "namespace::*"
| dylex/hsaml2 | SAML2/XML/Signature.hs | apache-2.0 | 9,878 | 0 | 17 | 1,634 | 3,140 | 1,648 | 1,492 | -1 | -1 |
{- |
Module : Data.Time.Zones.Types
Copyright : (C) 2014 Mihaly Barasz
License : Apache-2.0, see LICENSE
Maintainer : Mihaly Barasz <klao@nilcons.com>
Stability : experimental
-}
{-# LANGUAGE DeriveDataTypeable #-}
module Data.Time.Zones.Types (
TZ(..),
utcTZ,
) where
import Control.DeepSeq
import Data.Data
import Data.Default
import Data.Int
import qualified Data.Vector as VB
import qualified Data.Vector.Unboxed as VU
data TZ = TZ {
_tzTrans :: !(VU.Vector Int64),
_tzDiffs :: !(VU.Vector Int),
-- TODO(klao): maybe we should store it as a vector of indices and a
-- (short) vector of expanded 'TimeZone's, similarly to how it's
-- stored?
_tzInfos :: !(VB.Vector (Bool, String)) -- (summer, name)
} deriving (Eq, Show, Typeable, Data, Read)
instance NFData TZ where
rnf (TZ { _tzInfos = infos }) = rnf infos
-- | The `TZ` definition for UTC.
utcTZ :: TZ
utcTZ = TZ (VU.singleton minBound) (VU.singleton 0) (VB.singleton (False, "UTC"))
instance Default TZ where
def = utcTZ
| nilcons/haskell-tz | Data/Time/Zones/Types.hs | apache-2.0 | 1,067 | 0 | 12 | 236 | 239 | 140 | 99 | 27 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
module DNA (
-- * Definition of actors
ActorDef
, actor
, simpleOut
, rule
, scatterGather
, producer
, startingState
-- * Definition of dataflow graph
, Dataflow
, A
, buildDataflow
, use
, connect
-- * Compilation
, compile
) where
import Control.Applicative
import Control.Monad.Trans.State.Strict
import Data.Typeable
import Data.Graph.Inductive.Graph hiding (match)
import qualified Data.Traversable as T
import qualified Data.Map as Map
import DNA.AST
import DNA.Actor
import DNA.Compiler.Types
import DNA.Compiler.Basic
import DNA.Compiler.Scheduler
----------------------------------------------------------------
-- Monad for defining actors
----------------------------------------------------------------
-- | Monad for defining actor
newtype ActorDef s a = ActorDef (State (ActorDefState s) a)
deriving (Functor,Applicative,Monad)
data ActorDefState s = ActorDefState
{ adsRules :: [Rule s]
-- Transition rules
, adsInit :: [Expr () s]
-- Initial state
, adsProd :: [Expr () (s -> (s,Out))]
--
, adsSG :: [SG]
--
, adsConns :: ConnMap
-- Outbound connections
}
-- | Simple connection information
simpleOut :: forall s a. Typeable a => ConnType -> ActorDef s (Conn a)
simpleOut ct = ActorDef $ do
st <- get
let conns = adsConns st
cid = ConnId $ Map.size conns
put $! st { adsConns = Map.insert cid (ActorConn ct (typeOf (undefined :: a))) conns }
return $ Conn cid ConnOne
-- | Transition rule for an actor
rule :: Expr () (s -> a -> (s,Out)) -> ActorDef s ()
rule f = ActorDef $ do
modify $ \st -> st { adsRules = Rule f : adsRules st }
-- | Producer actor. One which sends data indefinitely
producer :: Expr () (s -> (s,Out)) -> ActorDef s ()
producer f = ActorDef $ do
modify $ \st -> st { adsProd = f : adsProd st }
-- | Scatter-gather actor
scatterGather :: SG -> ActorDef s ()
scatterGather sg = ActorDef $ do
modify $ \st -> st { adsSG = sg : adsSG st }
-- | Set initial state for the actor
startingState :: Expr () s -> ActorDef s ()
startingState s = ActorDef $ do
modify $ \st -> st { adsInit = s : adsInit st }
-- | Generate actor representation
actor :: ActorDef s outs -> Actor outs
actor (ActorDef m) =
case s of
ActorDefState [] [] [] [sg] c -> Actor outs (RealActor c (ScatterGather sg))
ActorDefState _ [] _ _ _ -> oops "No initial state specified"
ActorDefState [] _ [] _ _ -> oops "No transition rules/producers"
ActorDefState rs [i] [] _ c -> Actor outs (RealActor c (StateM i rs))
ActorDefState [] [i] [f] _ c -> Actor outs (RealActor c (Producer i f))
ActorDefState [] _ _ _ _ -> oops "Several producer steps specified"
ActorDefState _ _ _ _ _ -> oops "Several initial states specified"
where
(outs,s) = runState m $ ActorDefState [] [] [] [] Map.empty
oops = Invalid . pure
----------------------------------------------------------------
-- Dataflow graph definition
----------------------------------------------------------------
-- | Monad for building dataflow graph
type Dataflow = (State (Int, [(Node,BuildNode)], [(Node,Node,ConnId)]))
-- | Node of a dataflow graph which is used during graph construction
data BuildNode where
BuildNode :: Actor outs -> BuildNode
-- | Handle for actor.
newtype A = A Node
-- | Construct dataflow graph from its description
buildDataflow :: Dataflow () -> Compile DataflowGraph
buildDataflow m
= applicatively
$ (\n -> mkGraph n es) <$> T.traverse validate ns
where
validate (_,BuildNode (Invalid errs)) = leftA errs
validate (i,BuildNode (Actor _ a)) = pure (i,ANode NotSched a)
(_,ns,es) = execState m (0,[],[])
-- | Bind actor as node in the dataflow graph. It returns handle to
-- the node and collection of its outputs.
use :: forall outs. ConnCollection outs => Actor outs -> Dataflow (A, Connected outs)
use a = do
(i,acts,conns) <- get
put (i+1, (i,BuildNode a) : acts, conns)
return (A i, case a of
Invalid _ -> nullConnection (undefined :: outs)
Actor o _ -> setActorId i o
)
-- | Connect graphs
connect :: Connection a -> A -> Dataflow ()
connect Failed _ = return ()
connect (Bound from (Conn i _)) (A to) = do
(j, acts, conns) <- get
put ( j
, acts
, (from,to, i) : conns
)
----------------------------------------------------------------
-- Compilation helpers
----------------------------------------------------------------
-- | Compile program and write generated program
compile
:: (DataflowGraph -> Compile a) -- ^ Code generator
-> (a -> IO ()) -- ^ Action to write code
-> CAD -- ^ Cluster description
-> Dataflow () -- ^ Graph
-> IO ()
compile codegen write cad gr = do
let r = runCompile $ codegen
=<< checkSchedule
=<< schedule cad
=<< checkGraph
=<< buildDataflow gr
case r of
Left errs -> mapM_ putStrLn errs
Right a -> write a
| SKA-ScienceDataProcessor/RC | MS1/dna/DNA.hs | apache-2.0 | 5,207 | 0 | 16 | 1,264 | 1,607 | 860 | 747 | 107 | 7 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExistentialQuantification #-}
module Example.Runner where
import System.IO
import Data.IORef
import Control.Monad
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Serialize as S
import qualified Data.Map as M
import qualified Data.Set as ST
import qualified Data.Foldable as DF
import System.Directory
import qualified Crypto.Hash.MD5 as MD5
import Control.Exception
import Control.Monad.Free
import Data.Int
import Solar.Continuum.Log
import Solar.Continuum.LogF
import Solar.Continuum.Types
data Logging = forall a. Loggable a => MkLogging a
packLogger :: Loggable a => a -> Logging
packLogger = MkLogging
data State = State
{ toDelete :: IORef (ST.Set LogName)
, toAppend :: IORef (M.Map LogName (Int64, IORef (BL.ByteString)))
, nextCalc :: IORef Int
, positions :: IORef (M.Map LogName (ST.Set Int))
, toRename :: IORef (ST.Set (LogName, LogName))
, readPosition :: IORef (M.Map LogName Int64)
, writePosition :: IORef (M.Map Int (LogName, Int64))
, unknown :: IORef (M.Map Int (Int64, Logging))
}
mkState :: IO State
mkState = do
d <- newIORef ST.empty -- toDelete
a <- newIORef M.empty -- toAppend
n <- newIORef 0 -- nextCalc
p <- newIORef M.empty -- positions
r <- newIORef ST.empty -- renames
rp <- newIORef M.empty -- readPosition
wp <- newIORef M.empty -- writePosition
uk <- newIORef M.empty -- unknown
-- Finally, give the state with all of those IORefs.
return $ State d a n p r rp wp uk
fName :: B.ByteString -> String
fName n = init $ drop 1 $ show n
runLogIO :: Log a -> IO a
runLogIO log = do
state <- mkState
res <- iterM (run state) log
commit state
return res
where
run :: State -> LogF (IO a) -> IO a
run state (LogExists name next) = do
exists <- doesFileExist $ fName name
if exists
then do
deleted <- readIORef $ toDelete state
next $ not $ ST.member name deleted
else do
append <- readIORef $ toAppend state
case M.lookup name append of
Nothing -> next False
Just _ -> next True
run state (TellLogReadPosition name next) = do
position <- readIORef $ readPosition state
case M.lookup name position of
Nothing -> next 0
Just x -> next $ fromIntegral x
run state (TellLogWritePosition name next) = readIORef (nextCalc state) >>= next.Unknown
run state (TellLogSize name next) = do
catch (getFileSize (fName name) >>= next) (\(e :: IOException) -> next 0)
run state (CheckSumLog name next) = do
catch (BL.readFile (fName name) >>= next.MD5.hashlazy) (\(e :: IOException) -> next $ MD5.hash "")
run state (ResetLogPosition name next) = do
modifyIORef' (readPosition state) $ M.adjust (\_ -> 0) name
next
run state (SkipForwardLog name dist next) = do
modifyIORef' (readPosition state) $ M.adjust (+ dist) name
next
run state (DeleteLog name next) = do
putStrLn ("Deleting log "
++ fName name
)
modifyIORef' (toAppend state) $ M.delete name
pos <- readIORef $ positions state
case M.lookup name pos of
Nothing -> return ()
Just x -> DF.forM_ x $ \i -> do
modifyIORef' (unknown state) $ M.delete i
modifyIORef' (writePosition state) $ M.delete i
modifyIORef' (positions state) $ M.delete name
modifyIORef' (toDelete state) $ ST.insert name
next
run state (RenameLog name1 name2 next) = do
app <- readIORef $ toAppend state
putStrLn ("Renaming log "
++ fName name1
++ " to "
++ fName name2
)
-- Add renames
modifyIORef' (toRename state) $ ST.insert (name1, name2)
-- prevent deleting, if it did happen
modifyIORef' (toDelete state) $ ST.delete name2
case M.lookup name1 app of
Nothing -> return ()
Just x -> modifyIORef' (toAppend state) $ M.insert name2 x
run state (DeleteLog name1 next)
run state (ReadFromLog name next) = do
-- This is a really bad way, please don't do this.
bs <- catch (BL.readFile $ fName name) (\(e ::IOException) -> return BL.empty)
pos <- readIORef $ readPosition state
let dist = case M.lookup name pos of
Nothing -> 0
Just x -> x
let toRead = BL.drop dist bs
putStrLn ("Attempting to read from "
++ fName name
++ " at "
++ show dist
)
case S.runGetLazyState S.get toRead of
Left s -> next $ Left s
Right (decoded, remaining) -> do
let readSize = BL.length toRead - BL.length remaining
-- Update the read position
modifyIORef' (readPosition state) $ M.insertWith (+) name readSize
next decoded
run state (AppendLogData name dat next) = do
ident <- readIORef $ nextCalc state
let enc = S.encodeLazy dat
let len = BL.length enc
writes <- readIORef $ toAppend state
-- Find out the write position, and the written reference
(wposition, written) <- case M.lookup name writes of
Just (s,w) -> do
appending <- readIORef w
let appendlen = BL.length appending
return (s+appendlen,w)
Nothing -> do
-- Make sure that we have something there, since next we actually
-- operate on appending byte strings and such.
size <- getFileSize $ fName name
emp <- newIORef BL.empty
modifyIORef' (toAppend state) $ M.insert name (0, emp)
return (size, emp)
when (unresolvedPositions dat > 0) $ do
-- when there's things to resolve, put it in a queue for later.
modifyIORef' (unknown state) $ M.insert ident $ (wposition, packLogger dat)
-- Append the stuff
modifyIORef' written $ \ws -> BL.append ws enc
-- Say that we wrote 'here' in case something points to this.
modifyIORef' (writePosition state) $ M.insert ident (name, wposition)
-- Increment the number used to identify the next uncommitted entry
modifyIORef' (nextCalc state) succ
putStrLn ("Attempting to append: "
++ fName name
++ " "
++ show ident
++ " "
++ show enc
)
next
commit state = do
-- Update references
-- TODO
-- Rename
mvs <- readIORef $ toRename state
DF.forM_ mvs $ \(n1, n2) -> do
catch
(renameFile (fName n1) (fName n2))
(\(e :: IOException) -> return ())
-- Delete
dels <- readIORef $ toDelete state
DF.forM_ dels $ \n -> do
catch (removeFile (fName n)) (\(e :: IOException) -> return ())
-- Append
app <- readIORef $ toAppend state
DF.forM_ (M.toList app) $ \(name, (_, dat)) -> do
putStrLn $ "Appending to " ++ fName name
readIORef dat >>= BL.appendFile (fName name)
return ()
getFileSize :: FilePath -> IO Int64
getFileSize name = catch (BL.readFile name >>= return.BL.length) (\(e :: IOException) -> return 0)
| Cordite-Studios/solar-continuum | examples/Example/Runner.hs | bsd-2-clause | 7,733 | 3 | 19 | 2,574 | 2,440 | 1,192 | 1,248 | 166 | 19 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( withMovieData
, withDevelAppPort
) where
import Import
import Settings
import Yesod.Static
import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Yesod.Logger (Logger)
import Data.Dynamic (Dynamic, toDyn)
import qualified Database.Persist.Base
import Database.Persist.GenericSql (runMigration)
-- Import all relevant handler modules here.
import Handler.Root
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see
-- the comments there for more details.
mkYesodDispatch "MovieData" resourcesMovieData
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
withMovieData :: AppConfig DefaultEnv -> Logger -> (Application -> IO ()) -> IO ()
withMovieData conf logger f = do
#ifdef PRODUCTION
s <- static Settings.staticDir
#else
s <- staticDevel Settings.staticDir
#endif
dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf)
$ either error return . Database.Persist.Base.loadConfig
Database.Persist.Base.withPool (dbconf :: Settings.PersistConfig) $ \p -> do
Database.Persist.Base.runPool dbconf (runMigration migrateAll) p
let h = MovieData conf logger s p
defaultRunner f h
-- for yesod devel
withDevelAppPort :: Dynamic
withDevelAppPort = toDyn $ defaultDevelApp withMovieData | axman6/MovieServer | Application.hs | bsd-2-clause | 1,657 | 0 | 14 | 271 | 299 | 166 | 133 | -1 | -1 |
module Propellor.Property.HostingProvider.DigitalOcean (
distroKernel
) where
import Propellor.Base
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Reboot as Reboot
import Data.List
-- | Digital Ocean does not provide any way to boot
-- the kernel provided by the distribution, except using kexec.
-- Without this, some old, and perhaps insecure kernel will be used.
--
-- This property causes the distro kernel to be loaded on reboot, using kexec.
--
-- If the power is cycled, the non-distro kernel still boots up.
-- So, this property also checks if the running kernel is present in /boot,
-- and if not, reboots immediately into a distro kernel.
distroKernel :: Property NoInfo
distroKernel = propertyList "digital ocean distro kernel hack"
[ Apt.installed ["grub-pc", "kexec-tools", "file"]
, "/etc/default/kexec" `File.containsLines`
[ "LOAD_KEXEC=true"
, "USE_GRUB_CONFIG=true"
] `describe` "kexec configured"
, check (not <$> runningInstalledKernel) Reboot.now
`describe` "running installed kernel"
]
runningInstalledKernel :: IO Bool
runningInstalledKernel = do
kernelver <- takeWhile (/= '\n') <$> readProcess "uname" ["-r"]
when (null kernelver) $
error "failed to read uname -r"
kernelimages <- concat <$> mapM kernelsIn ["/", "/boot/"]
when (null kernelimages) $
error "failed to find any installed kernel images"
findVersion kernelver <$>
readProcess "file" ("-L" : kernelimages)
-- | File output looks something like this, we want to unambiguously
-- match the running kernel version:
-- Linux kernel x86 boot executable bzImage, version 3.16-3-amd64 (debian-kernel@lists.debian.org) #1 SMP Debian 3.1, RO-rootFS, swap_dev 0x2, Normal VGA
findVersion :: String -> String -> Bool
findVersion ver s = (" version " ++ ver ++ " ") `isInfixOf` s
kernelsIn :: FilePath -> IO [FilePath]
kernelsIn d = filter ("vmlinu" `isInfixOf`) <$> dirContents d
| np/propellor | src/Propellor/Property/HostingProvider/DigitalOcean.hs | bsd-2-clause | 1,974 | 18 | 10 | 309 | 361 | 204 | 157 | 30 | 1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Common helper functions and instances for all Ganeti tests.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.TestCommon
( maxMem
, maxDsk
, maxCpu
, maxSpindles
, maxVcpuRatio
, maxSpindleRatio
, maxNodes
, maxOpCodes
, (==?)
, (/=?)
, failTest
, passTest
, stableCover
, pythonCmd
, runPython
, checkPythonResult
, DNSChar(..)
, genPrintableAsciiChar
, genPrintableAsciiString
, genPrintableAsciiStringNE
, genName
, genFQDN
, genUUID
, genMaybe
, genSublist
, genMap
, genTags
, genFields
, genUniquesList
, SmallRatio(..)
, genSetHelper
, genSet
, genListSet
, genAndRestArguments
, genIPv4Address
, genIPv4Network
, genIp6Addr
, genIp6Net
, genOpCodesTagName
, genLuxiTagName
, netmask2NumHosts
, testSerialisation
, testArraySerialisation
, testDeserialisationFail
, resultProp
, readTestData
, genSample
, testParser
, genPropParser
, genNonNegative
, relativeError
, getTempFileName
, listOfUniqueBy
, counterexample
, cover'
) where
import Control.Exception (catchJust)
import Control.Monad
import Data.Attoparsec.Text (Parser, parseOnly)
import Data.List
import qualified Data.Map as M
import Data.Text (pack)
import Data.Word
import qualified Data.Set as Set
import System.Directory (getTemporaryDirectory, removeFile)
import System.Environment (getEnv)
import System.Exit (ExitCode(..))
import System.IO (hClose, openTempFile)
import System.IO.Error (isDoesNotExistError)
import System.Process (readProcessWithExitCode)
import qualified Test.HUnit as HUnit
import Test.QuickCheck
import Test.QuickCheck.Monadic
import qualified Text.JSON as J
import Numeric
import qualified Ganeti.BasicTypes as BasicTypes
import Ganeti.JSON (ArrayObject(..))
import Ganeti.Objects (TagSet(..))
import Ganeti.Types
import Ganeti.Utils.Monad (unfoldrM)
-- * Arbitrary orphan instances
instance Arbitrary TagSet where
arbitrary = (TagSet . Set.fromList) <$> genTags
-- * Constants
-- | Maximum memory (1TiB, somewhat random value).
maxMem :: Int
maxMem = 1024 * 1024
-- | Maximum disk (8TiB, somewhat random value).
maxDsk :: Int
maxDsk = 1024 * 1024 * 8
-- | Max CPUs (1024, somewhat random value).
maxCpu :: Int
maxCpu = 1024
-- | Max spindles (1024, somewhat random value).
maxSpindles :: Int
maxSpindles = 1024
-- | Max vcpu ratio (random value).
maxVcpuRatio :: Double
maxVcpuRatio = 1024.0
-- | Max spindle ratio (random value).
maxSpindleRatio :: Double
maxSpindleRatio = 1024.0
-- | Max nodes, used just to limit arbitrary instances for smaller
-- opcode definitions (e.g. list of nodes in OpTestDelay).
maxNodes :: Int
maxNodes = 32
-- | Max opcodes or jobs in a submit job and submit many jobs.
maxOpCodes :: Int
maxOpCodes = 16
-- * Helper functions
-- | Checks for equality with proper annotation. The first argument is
-- the computed value, the second one the expected value.
(==?) :: (Show a, Eq a) => a -> a -> Property
(==?) x y = counterexample
("Expected equality, but got mismatch\nexpected: " ++
show y ++ "\n but got: " ++ show x) (x == y)
infix 3 ==?
-- | Checks for inequality with proper annotation. The first argument
-- is the computed value, the second one the expected (not equal)
-- value.
(/=?) :: (Show a, Eq a) => a -> a -> Property
(/=?) x y = counterexample
("Expected inequality, but got equality: '" ++
show x ++ "'.") (x /= y)
infix 3 /=?
-- | Show a message and fail the test.
failTest :: String -> Property
failTest msg = counterexample msg False
-- | A 'True' property.
passTest :: Property
passTest = property True
-- | QuickCheck 2.12 swapped the order of the first two arguments, so provide a
-- compatibility function here
cover' :: Testable prop => Double -> Bool -> String -> prop -> Property
#if MIN_VERSION_QuickCheck(2, 12, 0)
cover' = cover
#else
cover' p x = cover x (round p)
#endif
-- | A stable version of QuickCheck's `cover`. In its current implementation,
-- cover will not detect insufficient coverage if the actual coverage in the
-- sample is 0. Work around this by lifting the probability to at least
-- 10 percent.
-- The underlying issue is tracked at
-- https://github.com/nick8325/quickcheck/issues/26
stableCover :: Testable prop => Bool -> Double -> String -> prop -> Property
stableCover p percent s prop =
let newlabel = "(stabilized to at least 10%) " ++ s
in forAll (frequency [(1, return True), (9, return False)]) $ \ basechance ->
cover' (10 + (percent * 9 / 10)) (basechance || p) newlabel prop
-- | Return the python binary to use. If the PYTHON environment
-- variable is defined, use its value, otherwise use just \"python3\".
pythonCmd :: IO String
pythonCmd = catchJust (guard . isDoesNotExistError)
(getEnv "PYTHON") (const (return "python3"))
-- | Run Python with an expression, returning the exit code, standard
-- output and error.
runPython :: String -> String -> IO (ExitCode, String, String)
runPython expr stdin = do
py_binary <- pythonCmd
readProcessWithExitCode py_binary ["-c", expr] stdin
-- | Check python exit code, and fail via HUnit assertions if
-- non-zero. Otherwise, return the standard output.
checkPythonResult :: (ExitCode, String, String) -> IO String
checkPythonResult (py_code, py_stdout, py_stderr) = do
HUnit.assertEqual ("python exited with error: " ++ py_stderr)
ExitSuccess py_code
return py_stdout
-- * Arbitrary instances
-- | Defines a DNS name.
newtype DNSChar = DNSChar { dnsGetChar::Char }
instance Arbitrary DNSChar where
arbitrary = liftM DNSChar $ elements (['a'..'z'] ++ ['0'..'9'] ++ "_-")
instance Show DNSChar where
show = show . dnsGetChar
-- * Generators
-- | Generates printable ASCII characters (from ' ' to '~').
genPrintableAsciiChar :: Gen Char
genPrintableAsciiChar = choose ('\x20', '\x7e')
-- | Generates a short string (0 <= n <= 40 chars) from printable ASCII.
genPrintableAsciiString :: Gen String
genPrintableAsciiString = do
n <- choose (0, 40)
vectorOf n genPrintableAsciiChar
-- | Generates a short string (1 <= n <= 40 chars) from printable ASCII.
genPrintableAsciiStringNE :: Gen NonEmptyString
genPrintableAsciiStringNE = do
n <- choose (1, 40)
vectorOf n genPrintableAsciiChar >>= mkNonEmpty
-- | Generates a single name component.
genName :: Gen String
genName = do
n <- choose (1, 16)
dn <- vector n
return (map dnsGetChar dn)
-- | Generates an entire FQDN.
genFQDN :: Gen String
genFQDN = do
ncomps <- choose (1, 4)
names <- vectorOf ncomps genName
return $ intercalate "." names
-- | Generates a UUID-like string.
--
-- Only to be used for QuickCheck testing. For obtaining actual UUIDs use
-- the newUUID function in Ganeti.Utils
genUUID :: Gen String
genUUID = do
c1 <- vector 6
c2 <- vector 4
c3 <- vector 4
c4 <- vector 4
c5 <- vector 4
c6 <- vector 4
c7 <- vector 6
return $ map dnsGetChar c1 ++ "-" ++ map dnsGetChar c2 ++ "-" ++
map dnsGetChar c3 ++ "-" ++ map dnsGetChar c4 ++ "-" ++
map dnsGetChar c5 ++ "-" ++ map dnsGetChar c6 ++ "-" ++
map dnsGetChar c7
-- | Combinator that generates a 'Maybe' using a sub-combinator.
genMaybe :: Gen a -> Gen (Maybe a)
genMaybe subgen = frequency [ (1, pure Nothing), (3, Just <$> subgen) ]
-- | Generates a sublist of a given list, keeping the ordering.
-- The generated elements are always a subset of the list.
--
-- In order to better support corner cases, the size of the sublist is
-- chosen to have the uniform distribution.
genSublist :: [a] -> Gen [a]
genSublist xs = choose (0, l) >>= g xs l
where
l = length xs
g _ _ 0 = return []
g [] _ _ = return []
g ys n k | k == n = return ys
g (y:ys) n k = frequency [ (k, liftM (y :) (g ys (n - 1) (k - 1)))
, (n - k, g ys (n - 1) k)
]
-- | Generates a map given generators for keys and values.
genMap :: (Ord k, Ord v) => Gen k -> Gen v -> Gen (M.Map k v)
genMap kg vg = M.fromList <$> listOf ((,) <$> kg <*> vg)
-- | Defines a tag type.
newtype TagChar = TagChar { tagGetChar :: Char }
-- | All valid tag chars. This doesn't need to match _exactly_
-- Ganeti's own tag regex, just enough for it to be close.
tagChar :: String
tagChar = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ".+*/:@-"
instance Arbitrary TagChar where
arbitrary = liftM TagChar $ elements tagChar
-- | Generates a tag
genTag :: Gen [TagChar]
genTag = do
-- the correct value would be C.maxTagLen, but that's way too
-- verbose in unittests, and at the moment I don't see any possible
-- bugs with longer tags and the way we use tags in htools
n <- choose (1, 10)
vector n
-- | Generates a list of tags (correctly upper bounded).
genTags :: Gen [String]
genTags = do
-- the correct value would be C.maxTagsPerObj, but per the comment
-- in genTag, we don't use tags enough in htools to warrant testing
-- such big values
n <- choose (0, 10::Int)
tags <- mapM (const genTag) [1..n]
return $ map (map tagGetChar) tags
-- | Generates a fields list. This uses the same character set as a
-- DNS name (just for simplicity).
genFields :: Gen [String]
genFields = do
n <- choose (1, 32)
vectorOf n genName
-- | Generates a list of a given size with non-duplicate elements.
genUniquesList :: (Eq a, Arbitrary a, Ord a) => Int -> Gen a -> Gen [a]
genUniquesList cnt generator = do
set <- foldM (\set _ -> do
newelem <- generator `suchThat` (`Set.notMember` set)
return (Set.insert newelem set)) Set.empty [1..cnt]
return $ Set.toList set
newtype SmallRatio = SmallRatio Double deriving Show
instance Arbitrary SmallRatio where
arbitrary = liftM SmallRatio $ choose (0, 1)
-- | Helper for 'genSet', declared separately due to type constraints.
genSetHelper :: (Ord a) => [a] -> Maybe Int -> Gen (Set.Set a)
genSetHelper candidates size = do
size' <- case size of
Nothing -> choose (0, length candidates)
Just s | s > length candidates ->
error $ "Invalid size " ++ show s ++ ", maximum is " ++
show (length candidates)
| otherwise -> return s
foldM (\set _ -> do
newelem <- elements candidates `suchThat` (`Set.notMember` set)
return (Set.insert newelem set)) Set.empty [1..size']
-- | Generates a 'Set' of arbitrary elements.
genSet :: (Ord a, Bounded a, Enum a) => Maybe Int -> Gen (Set.Set a)
genSet = genSetHelper [minBound..maxBound]
-- | Generates a 'Set' of arbitrary elements wrapped in a 'ListSet'
genListSet :: (Ord a, Bounded a, Enum a) => Maybe Int
-> Gen (BasicTypes.ListSet a)
genListSet is = BasicTypes.ListSet <$> genSet is
-- | Generate an arbitrary element of and AndRestArguments field.
genAndRestArguments :: Gen (M.Map String J.JSValue)
genAndRestArguments = do
n <- choose (0::Int, 10)
let oneParam _ = do
name <- choose (15 ::Int, 25)
>>= flip vectorOf (elements tagChar)
intvalue <- arbitrary
value <- oneof [ J.JSString . J.toJSString <$> genName
, return $ J.showJSON (intvalue :: Int)
]
return (name, value)
M.fromList `liftM` mapM oneParam [1..n]
-- | Generate an arbitrary IPv4 address in textual form.
genIPv4 :: Gen String
genIPv4 = do
a <- choose (1::Int, 255)
b <- choose (0::Int, 255)
c <- choose (0::Int, 255)
d <- choose (0::Int, 255)
return . intercalate "." $ map show [a, b, c, d]
genIPv4Address :: Gen IPv4Address
genIPv4Address = mkIPv4Address =<< genIPv4
-- | Generate an arbitrary IPv4 network in textual form.
genIPv4AddrRange :: Gen String
genIPv4AddrRange = do
pfxLen <- choose (8::Int, 30)
-- Generate a number that fits in pfxLen bits
addr <- choose(1::Int, 2^pfxLen-1)
let hostLen = 32 - pfxLen
-- ...and shift it left until it becomes a 32-bit number
-- with the low hostLen bits unset
net = addr * 2^hostLen
netBytes = [(net `div` 2^x) `mod` 256 | x <- [24::Int, 16, 8, 0]]
return $ intercalate "." (map show netBytes) ++ "/" ++ show pfxLen
genIPv4Network :: Gen IPv4Network
genIPv4Network = mkIPv4Network =<< genIPv4AddrRange
-- | Helper function to compute the number of hosts in a network
-- given the netmask. (For IPv4 only.)
netmask2NumHosts :: Word8 -> Int
netmask2NumHosts n = 2^(32-n)
-- | Generates an arbitrary IPv6 network address in textual form.
-- The generated address is not simpflified, e. g. an address like
-- "2607:f0d0:1002:0051:0000:0000:0000:0004" does not become
-- "2607:f0d0:1002:51::4"
genIp6Addr :: Gen String
genIp6Addr = do
rawIp <- vectorOf 8 $ choose (0::Integer, 65535)
return $ intercalate ":" (map (`showHex` "") rawIp)
-- | Helper function to convert an integer in to an IPv6 address in textual
-- form
ip6AddressFromNumber :: Integer -> [Char]
ip6AddressFromNumber ipInt =
-- chunksOf splits a sequence in chunks of n elements length each
-- chunksOf 4 "20010db80000" = ["2001", "0db8", "0000"]
let chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n lst = take n lst : (chunksOf n $ drop n lst)
-- Left-pad a sequence with a fixed element if it's shorter than n
-- elements, or trim it to the first n elements otherwise
-- e.g. lPadTrim 6 '0' "abcd" = "00abcd"
lPadTrim :: Int -> a -> [a] -> [a]
lPadTrim n p lst
| length lst < n = lPadTrim n p $ p : lst
| otherwise = take n lst
rawIp = lPadTrim 32 '0' $ (`showHex` "") ipInt
in intercalate ":" $ chunksOf 4 rawIp
-- | Generates an arbitrary IPv6 network in textual form.
genIp6Net :: Gen String
genIp6Net = do
netmask <- choose (8::Int, 126)
raw_ip <- (* 2^(128-netmask)) <$> choose(1::Integer, 2^netmask-1)
return $ ip6AddressFromNumber raw_ip ++ "/" ++ show netmask
-- | Generates a valid, arbitrary tag name with respect to the given
-- 'TagKind' for opcodes.
genOpCodesTagName :: TagKind -> Gen (Maybe String)
genOpCodesTagName TagKindCluster = return Nothing
genOpCodesTagName _ = Just <$> genFQDN
-- | Generates a valid, arbitrary tag name with respect to the given
-- 'TagKind' for Luxi.
genLuxiTagName :: TagKind -> Gen String
genLuxiTagName TagKindCluster = return ""
genLuxiTagName _ = genFQDN
-- * Helper functions
-- | Checks for serialisation idempotence.
testSerialisation :: (Eq a, Show a, J.JSON a) => a -> Property
testSerialisation a =
case J.readJSON (J.showJSON a) of
J.Error msg -> failTest $ "Failed to deserialise: " ++ msg
J.Ok a' -> a ==? a'
-- | Checks for array serialisation idempotence.
testArraySerialisation :: (Eq a, Show a, ArrayObject a) => a -> Property
testArraySerialisation a =
case fromJSArray (toJSArray a) of
J.Error msg -> failTest $ "Failed to deserialise: " ++ msg
J.Ok a' -> a ==? a'
-- | Checks if the deserializer doesn't accept forbidden values.
-- The first argument is ignored, it just enforces the correct type.
testDeserialisationFail :: (Eq a, Show a, J.JSON a)
=> a -> J.JSValue -> Property
testDeserialisationFail a val =
case liftM (`asTypeOf` a) $ J.readJSON val of
J.Error _ -> passTest
J.Ok x -> failTest $ "Parsed invalid value " ++ show val ++
" to: " ++ show x
-- | Result to PropertyM IO.
resultProp :: (Show a) => BasicTypes.GenericResult a b -> PropertyM IO b
resultProp (BasicTypes.Bad err) = stop . failTest $ show err
resultProp (BasicTypes.Ok val) = return val
-- | Return the source directory of Ganeti.
getSourceDir :: IO FilePath
getSourceDir = catchJust (guard . isDoesNotExistError)
(getEnv "TOP_SRCDIR")
(const (return "."))
-- | Returns the path of a file in the test data directory, given its name.
testDataFilename :: String -> String -> IO FilePath
testDataFilename datadir name = do
src <- getSourceDir
return $ src ++ datadir ++ name
-- | Returns the content of the specified haskell test data file.
readTestData :: String -> IO String
readTestData filename = do
name <- testDataFilename "/test/data/" filename
readFile name
-- | Generate arbitrary values in the IO monad. This is a simple
-- wrapper over 'sample''.
genSample :: Gen a -> IO a
genSample gen = do
values <- sample' gen
case values of
[] -> error "sample' returned an empty list of values??"
x:_ -> return x
-- | Function for testing whether a file is parsed correctly.
testParser :: (Show a, Eq a) => Parser a -> String -> a -> HUnit.Assertion
testParser parser fileName expectedContent = do
fileContent <- readTestData fileName
case parseOnly parser $ pack fileContent of
Left msg -> HUnit.assertFailure $ "Parsing failed: " ++ msg
Right obtained -> HUnit.assertEqual fileName expectedContent obtained
-- | Generate a property test for parsers.
genPropParser :: (Show a, Eq a) => Parser a -> String -> a -> Property
genPropParser parser s expected =
case parseOnly parser $ pack s of
Left msg -> failTest $ "Parsing failed: " ++ msg
Right obtained -> expected ==? obtained
-- | Generate an arbitrary non negative integer number
genNonNegative :: Gen Int
genNonNegative =
fmap fromEnum (arbitrary::Gen (Test.QuickCheck.NonNegative Int))
-- | Computes the relative error of two 'Double' numbers.
--
-- This is the \"relative error\" algorithm in
-- http:\/\/randomascii.wordpress.com\/2012\/02\/25\/
-- comparing-floating-point-numbers-2012-edition (URL split due to too
-- long line).
relativeError :: Double -> Double -> Double
relativeError d1 d2 =
let delta = abs $ d1 - d2
a1 = abs d1
a2 = abs d2
greatest = max a1 a2
in if delta == 0
then 0
else delta / greatest
-- | Helper to a get a temporary file name.
getTempFileName :: String -> IO FilePath
getTempFileName filename = do
tempdir <- getTemporaryDirectory
(fpath, handle) <- openTempFile tempdir filename
_ <- hClose handle
removeFile fpath
return fpath
-- | @listOfUniqueBy gen keyFun forbidden@: Generates a list of random length,
-- where all generated elements will be unique by the keying function
-- @keyFun@. They will also be distinct from all elements in @forbidden@ by
-- the keying function.
--
-- As for 'listOf', the maximum output length depends on the size parameter.
--
-- Example:
--
-- > listOfUniqueBy (arbitrary :: Gen String) (length) ["hey"]
-- > -- Generates a list of strings of different length, but not of length 3.
--
-- The passed @gen@ should not make key collisions too likely, since the
-- implementation uses `suchThat`, looping until enough unique elements
-- have been generated. If the @gen@ makes collisions likely, this function
-- will consequently be slow, or not terminate if it is not possible to
-- generate enough elements, like in:
--
-- > listOfUniqueBy (arbitrary :: Gen Int) (`mod` 2) []
-- > -- May not terminate depending on the size parameter of the Gen,
-- > -- since there are only 2 unique keys (0 and 1).
listOfUniqueBy :: (Ord b) => Gen a -> (a -> b) -> [a] -> Gen [a]
listOfUniqueBy gen keyFun forbidden = do
let keysOf = Set.fromList . map keyFun
k <- sized $ \n -> choose (0, n)
flip unfoldrM (0, keysOf forbidden) $ \(i, usedKeys) ->
if i == k
then return Nothing
else do
x <- gen `suchThat` ((`Set.notMember` usedKeys) . keyFun)
return $ Just (x, (i + 1, Set.insert (keyFun x) usedKeys))
| mbakke/ganeti | test/hs/Test/Ganeti/TestCommon.hs | bsd-2-clause | 20,889 | 0 | 20 | 4,537 | 4,834 | 2,581 | 2,253 | 362 | 4 |
{-# LANGUAGE FlexibleInstances #-}
module Distribution.Server.Framework.MemSize (
MemSize(..),
memSizeMb, memSizeKb,
memSize0, memSize1, memSize2, memSize3, memSize4,
memSize5, memSize6, memSize7, memSize8, memSize9, memSize10,
memSizeUArray, memSizeUVector
) where
import Data.Word
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.IntMap as IntMap
import Data.IntMap (IntMap)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.IntSet as IntSet
import Data.IntSet (IntSet)
import Data.Sequence (Seq)
import qualified Data.Foldable as Foldable
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Short as BSS
import qualified Data.Text as T
import Data.Time (UTCTime, Day)
import Data.Ix
import qualified Data.Array.Unboxed as A
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as V.U
import Distribution.Package (PackageIdentifier(..), PackageName(..))
import Distribution.PackageDescription (FlagName(..))
import Distribution.Version (Version(..), VersionRange, foldVersionRange')
import Distribution.System (Arch(..), OS(..))
import Distribution.Compiler (CompilerFlavor(..), CompilerId(..))
-------------------------------------------------------------------------------
-- Mem size class and instances
--
memSizeMb, memSizeKb :: Int -> Int
memSizeMb w = wordSize * w `div` (1024 * 1024)
memSizeKb w = wordSize * w `div` 1024
wordSize :: Int
wordSize = 8
-- | Size in the heap of values, in words (so multiply by 4 or 8)
class MemSize a where
memSize :: a -> Int
memSize0 :: Int
memSize1 :: MemSize a => a -> Int
memSize2 :: (MemSize a1, MemSize a) => a -> a1 -> Int
memSize3 :: (MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> Int
memSize4 :: (MemSize a3, MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> a3 -> Int
memSize5 :: (MemSize a4, MemSize a3, MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> a3 -> a4 -> Int
memSize6 :: (MemSize a5, MemSize a4, MemSize a3, MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> a3 -> a4 -> a5 -> Int
memSize7 :: (MemSize a6, MemSize a5, MemSize a4, MemSize a3, MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> Int
memSize8 :: (MemSize a7, MemSize a6, MemSize a5, MemSize a4, MemSize a3, MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7 -> Int
memSize9 :: (MemSize a8, MemSize a7, MemSize a6, MemSize a5, MemSize a4, MemSize a3, MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7 -> a8 -> Int
memSize10 :: (MemSize a9, MemSize a8, MemSize a7, MemSize a6, MemSize a5, MemSize a4, MemSize a3, MemSize a2, MemSize a1, MemSize a) => a -> a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7 -> a8 -> a9 -> Int
memSize0 = 0
memSize1 a = 2 + memSize a
memSize2 a b = 3 + memSize a + memSize b
memSize3 a b c = 4 + memSize a + memSize b + memSize c
memSize4 a b c d = 5 + memSize a + memSize b + memSize c
+ memSize d
memSize5 a b c d e = 6 + memSize a + memSize b + memSize c
+ memSize d + memSize e
memSize6 a b c d e f = 7 + memSize a + memSize b + memSize c
+ memSize d + memSize e + memSize f
memSize7 a b c d e
f g = 8 + memSize a + memSize b + memSize c
+ memSize d + memSize e + memSize f
+ memSize g
memSize8 a b c d e
f g h = 9 + memSize a + memSize b + memSize c
+ memSize d + memSize e + memSize f
+ memSize g + memSize h
memSize9 a b c d e
f g h i = 10 + memSize a + memSize b + memSize c
+ memSize d + memSize e + memSize f
+ memSize g + memSize h + memSize i
memSize10 a b c d e
f g h i j = 11 + memSize a + memSize b + memSize c
+ memSize d + memSize e + memSize f
+ memSize g + memSize h + memSize i
+ memSize j
instance MemSize (a -> b) where
memSize _ = 0
instance MemSize Int where
memSize _ = 2
instance MemSize Word where
memSize _ = 2
instance MemSize Word32 where
memSize _ = 2
instance MemSize Char where
memSize _ = 0
instance MemSize Bool where
memSize _ = 0
instance MemSize Integer where
memSize _ = 2
instance MemSize Float where
memSize _ = 2
instance MemSize UTCTime where
memSize _ = 7
instance MemSize Day where
memSize _ = 2
instance MemSize a => MemSize [a] where
memSize [] = memSize0
memSize (x:xs) = memSize2 x xs
-- memSize xs = 2 + length xs + sum (map memSize xs)
instance (MemSize a, MemSize b) => MemSize (a,b) where
memSize (a,b) = memSize2 a b
instance (MemSize a, MemSize b, MemSize c) => MemSize (a,b,c) where
memSize (a,b,c) = memSize3 a b c
instance (MemSize a, MemSize b, MemSize c, MemSize d) => MemSize (a,b,c,d) where
memSize (a,b,c,d) = memSize4 a b c d
instance MemSize a => MemSize (Maybe a) where
memSize Nothing = memSize0
memSize (Just a) = memSize1 a
instance (MemSize a, MemSize b) => MemSize (Either a b) where
memSize (Left a) = memSize1 a
memSize (Right b) = memSize1 b
instance (MemSize a, MemSize b) => MemSize (Map a b) where
memSize m = sum [ 6 + memSize k + memSize v | (k,v) <- Map.toList m ]
instance MemSize a => MemSize (IntMap a) where
memSize m = sum [ 8 + memSize v | v <- IntMap.elems m ]
instance MemSize a => MemSize (Set a) where
memSize m = sum [ 5 + memSize v | v <- Set.elems m ]
instance MemSize IntSet where
memSize s = 4 * IntSet.size s --estimate
instance MemSize a => MemSize (Seq a) where
memSize s = sum [ 5 + memSize v | v <- Foldable.toList s ] --estimate
instance MemSize BS.ByteString where
memSize s = let (w,t) = divMod (BS.length s) wordSize
in 5 + w + signum t
instance MemSize BSS.ShortByteString where
memSize s = let (w,t) = divMod (BSS.length s) wordSize
in 1 + w + signum t
instance MemSize LBS.ByteString where
memSize s = sum [ 1 + memSize c | c <- LBS.toChunks s ]
instance MemSize T.Text where
memSize s = let (w,t) = divMod (T.length s) (wordSize `div` 2)
in 5 + w + signum t
memSizeUArray :: (Ix i, A.IArray a e) => Int -> a i e -> Int
memSizeUArray sz a = 13 + (rangeSize (A.bounds a) * sz) `div` wordSize
instance MemSize e => MemSize (V.Vector e) where
memSize a = 5 + V.length a + V.foldl' (\s e -> s + memSize e) 0 a
memSizeUVector :: V.U.Unbox e => Int -> V.U.Vector e -> Int
memSizeUVector sz a = 5 + (V.U.length a * sz) `div` wordSize
----
instance MemSize PackageName where
memSize (PackageName n) = memSize n
instance MemSize Version where
memSize (Version a b) = memSize2 a b
instance MemSize VersionRange where
memSize =
foldVersionRange' memSize0 -- any
memSize1 -- == v
memSize1 -- > v
memSize1 -- < v
(\v -> 7 + 2 * memSize v) -- >= v
(\v -> 7 + 2 * memSize v) -- <= v
(\v _v' -> memSize1 v) -- == v.*
memSize2 -- _ || _
memSize2 -- _ && _
memSize1 -- (_)
instance MemSize PackageIdentifier where
memSize (PackageIdentifier a b) = memSize2 a b
instance MemSize Arch where
memSize _ = memSize0
instance MemSize OS where
memSize _ = memSize0
instance MemSize FlagName where
memSize (FlagName n) = memSize n
instance MemSize CompilerFlavor where
memSize _ = memSize0
instance MemSize CompilerId where
memSize (CompilerId a b) = memSize2 a b
| agrafix/hackage-server | Distribution/Server/Framework/MemSize.hs | bsd-3-clause | 7,902 | 0 | 15 | 2,292 | 3,118 | 1,618 | 1,500 | 167 | 1 |
{-# LANGUAGE CPP, DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
#if __GLASGOW_HASKELL__ < 707
{-# LANGUAGE StandaloneDeriving #-}
#endif
-- Hack approach to support bootstrapping.
-- When MIN_VERSION_binary macro is available, use it. But it's not available
-- during bootstrapping (or anyone else building Setup.hs directly). If the
-- builder specifies -DMIN_VERSION_binary_0_8_0=1 or =0 then we respect that.
-- Otherwise we pick a default based on GHC version: assume binary <0.8 when
-- GHC < 8.0, and binary >=0.8 when GHC >= 8.0.
#ifdef MIN_VERSION_binary
#define MIN_VERSION_binary_0_8_0 MIN_VERSION_binary(0,8,0)
#else
#ifndef MIN_VERSION_binary_0_8_0
#if __GLASGOW_HASKELL__ >= 800
#define MIN_VERSION_binary_0_8_0 1
#else
#define MIN_VERSION_binary_0_8_0 0
#endif
#endif
#endif
#if !MIN_VERSION_binary_0_8_0
{-# OPTIONS_GHC -fno-warn-orphans #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Version
-- Copyright : Isaac Jones, Simon Marlow 2003-2004
-- Duncan Coutts 2008
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Exports the 'Version' type along with a parser and pretty printer. A version
-- is something like @\"1.3.3\"@. It also defines the 'VersionRange' data
-- types. Version ranges are like @\">= 1.2 && < 2\"@.
module Distribution.Version (
-- * Package versions
Version(..),
-- * Version ranges
VersionRange(..),
-- ** Constructing
anyVersion, noVersion,
thisVersion, notThisVersion,
laterVersion, earlierVersion,
orLaterVersion, orEarlierVersion,
unionVersionRanges, intersectVersionRanges,
invertVersionRange,
withinVersion,
betweenVersionsInclusive,
-- ** Inspection
withinRange,
isAnyVersion,
isNoVersion,
isSpecificVersion,
simplifyVersionRange,
foldVersionRange,
foldVersionRange',
hasUpperBound,
hasLowerBound,
-- ** Modification
removeUpperBound,
-- * Version intervals view
asVersionIntervals,
VersionInterval,
LowerBound(..),
UpperBound(..),
Bound(..),
-- ** 'VersionIntervals' abstract type
-- | The 'VersionIntervals' type and the accompanying functions are exposed
-- primarily for completeness and testing purposes. In practice
-- 'asVersionIntervals' is the main function to use to
-- view a 'VersionRange' as a bunch of 'VersionInterval's.
--
VersionIntervals,
toVersionIntervals,
fromVersionIntervals,
withinIntervals,
versionIntervals,
mkVersionIntervals,
unionVersionIntervals,
intersectVersionIntervals,
invertVersionIntervals
) where
import Distribution.Compat.Binary ( Binary(..) )
import Data.Data ( Data )
import Data.Typeable ( Typeable )
import Data.Version ( Version(..) )
import GHC.Generics ( Generic )
import Distribution.Text
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP hiding (get)
import qualified Text.PrettyPrint as Disp
import Text.PrettyPrint ((<>), (<+>))
import qualified Data.Char as Char (isDigit)
import Control.Exception (assert)
-- -----------------------------------------------------------------------------
-- Version ranges
-- Todo: maybe move this to Distribution.Package.Version?
-- (package-specific versioning scheme).
data VersionRange
= AnyVersion
| ThisVersion Version -- = version
| LaterVersion Version -- > version (NB. not >=)
| EarlierVersion Version -- < version
| WildcardVersion Version -- == ver.* (same as >= ver && < ver+1)
| UnionVersionRanges VersionRange VersionRange
| IntersectVersionRanges VersionRange VersionRange
| VersionRangeParens VersionRange -- just '(exp)' parentheses syntax
deriving (Data, Eq, Generic, Read, Show, Typeable)
instance Binary VersionRange
#if __GLASGOW_HASKELL__ < 707
-- starting with ghc-7.7/base-4.7 this instance is provided in "Data.Data"
deriving instance Data Version
#endif
#if !(MIN_VERSION_binary_0_8_0)
-- Deriving this instance from Generic gives trouble on GHC 7.2 because the
-- Generic instance has to be standalone-derived. So, we hand-roll our own.
-- We can't use a generic Binary instance on later versions because we must
-- maintain compatibility between compiler versions.
instance Binary Version where
get = do
br <- get
tags <- get
return $ Version br tags
put (Version br tags) = put br >> put tags
#endif
{-# DEPRECATED AnyVersion "Use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED ThisVersion "use 'thisVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED LaterVersion "use 'laterVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED EarlierVersion "use 'earlierVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED WildcardVersion "use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED UnionVersionRanges "use 'unionVersionRanges', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED IntersectVersionRanges "use 'intersectVersionRanges', 'foldVersionRange' or 'asVersionIntervals'" #-}
-- | The version range @-any@. That is, a version range containing all
-- versions.
--
-- > withinRange v anyVersion = True
--
anyVersion :: VersionRange
anyVersion = AnyVersion
-- | The empty version range, that is a version range containing no versions.
--
-- This can be constructed using any unsatisfiable version range expression,
-- for example @> 1 && < 1@.
--
-- > withinRange v noVersion = False
--
noVersion :: VersionRange
noVersion = IntersectVersionRanges (LaterVersion v) (EarlierVersion v)
where v = Version [1] []
-- | The version range @== v@
--
-- > withinRange v' (thisVersion v) = v' == v
--
thisVersion :: Version -> VersionRange
thisVersion = ThisVersion
-- | The version range @< v || > v@
--
-- > withinRange v' (notThisVersion v) = v' /= v
--
notThisVersion :: Version -> VersionRange
notThisVersion v = UnionVersionRanges (EarlierVersion v) (LaterVersion v)
-- | The version range @> v@
--
-- > withinRange v' (laterVersion v) = v' > v
--
laterVersion :: Version -> VersionRange
laterVersion = LaterVersion
-- | The version range @>= v@
--
-- > withinRange v' (orLaterVersion v) = v' >= v
--
orLaterVersion :: Version -> VersionRange
orLaterVersion v = UnionVersionRanges (ThisVersion v) (LaterVersion v)
-- | The version range @< v@
--
-- > withinRange v' (earlierVersion v) = v' < v
--
earlierVersion :: Version -> VersionRange
earlierVersion = EarlierVersion
-- | The version range @<= v@
--
-- > withinRange v' (orEarlierVersion v) = v' <= v
--
orEarlierVersion :: Version -> VersionRange
orEarlierVersion v = UnionVersionRanges (ThisVersion v) (EarlierVersion v)
-- | The version range @vr1 || vr2@
--
-- > withinRange v' (unionVersionRanges vr1 vr2)
-- > = withinRange v' vr1 || withinRange v' vr2
--
unionVersionRanges :: VersionRange -> VersionRange -> VersionRange
unionVersionRanges = UnionVersionRanges
-- | The version range @vr1 && vr2@
--
-- > withinRange v' (intersectVersionRanges vr1 vr2)
-- > = withinRange v' vr1 && withinRange v' vr2
--
intersectVersionRanges :: VersionRange -> VersionRange -> VersionRange
intersectVersionRanges = IntersectVersionRanges
-- | The inverse of a version range
--
-- > withinRange v' (invertVersionRange vr)
-- > = not (withinRange v' vr)
--
invertVersionRange :: VersionRange -> VersionRange
invertVersionRange =
fromVersionIntervals . invertVersionIntervals . VersionIntervals . asVersionIntervals
-- | The version range @== v.*@.
--
-- For example, for version @1.2@, the version range @== 1.2.*@ is the same as
-- @>= 1.2 && < 1.3@
--
-- > withinRange v' (laterVersion v) = v' >= v && v' < upper v
-- > where
-- > upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
--
withinVersion :: Version -> VersionRange
withinVersion = WildcardVersion
-- | The version range @>= v1 && <= v2@.
--
-- In practice this is not very useful because we normally use inclusive lower
-- bounds and exclusive upper bounds.
--
-- > withinRange v' (laterVersion v) = v' > v
--
betweenVersionsInclusive :: Version -> Version -> VersionRange
betweenVersionsInclusive v1 v2 =
IntersectVersionRanges (orLaterVersion v1) (orEarlierVersion v2)
{-# DEPRECATED betweenVersionsInclusive
"In practice this is not very useful because we normally use inclusive lower bounds and exclusive upper bounds" #-}
-- | Given a version range, remove the highest upper bound. Example: @(>= 1 && <
-- 3) || (>= 4 && < 5)@ is converted to @(>= 1 && < 3) || (>= 4)@.
removeUpperBound :: VersionRange -> VersionRange
removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals
where
relaxLastInterval (VersionIntervals intervals) =
VersionIntervals (relaxLastInterval' intervals)
relaxLastInterval' [] = []
relaxLastInterval' [(l,_)] = [(l, NoUpperBound)]
relaxLastInterval' (i:is) = i : relaxLastInterval' is
-- | Fold over the basic syntactic structure of a 'VersionRange'.
--
-- This provides a syntactic view of the expression defining the version range.
-- The syntactic sugar @\">= v\"@, @\"<= v\"@ and @\"== v.*\"@ is presented
-- in terms of the other basic syntax.
--
-- For a semantic view use 'asVersionIntervals'.
--
foldVersionRange :: a -- ^ @\"-any\"@ version
-> (Version -> a) -- ^ @\"== v\"@
-> (Version -> a) -- ^ @\"> v\"@
-> (Version -> a) -- ^ @\"< v\"@
-> (a -> a -> a) -- ^ @\"_ || _\"@ union
-> (a -> a -> a) -- ^ @\"_ && _\"@ intersection
-> VersionRange -> a
foldVersionRange anyv this later earlier union intersect = fold
where
fold AnyVersion = anyv
fold (ThisVersion v) = this v
fold (LaterVersion v) = later v
fold (EarlierVersion v) = earlier v
fold (WildcardVersion v) = fold (wildcard v)
fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2)
fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2)
fold (VersionRangeParens v) = fold v
wildcard v = intersectVersionRanges
(orLaterVersion v)
(earlierVersion (wildcardUpperBound v))
-- | An extended variant of 'foldVersionRange' that also provides a view of the
-- expression in which the syntactic sugar @\">= v\"@, @\"<= v\"@ and @\"==
-- v.*\"@ is presented explicitly rather than in terms of the other basic
-- syntax.
--
foldVersionRange' :: a -- ^ @\"-any\"@ version
-> (Version -> a) -- ^ @\"== v\"@
-> (Version -> a) -- ^ @\"> v\"@
-> (Version -> a) -- ^ @\"< v\"@
-> (Version -> a) -- ^ @\">= v\"@
-> (Version -> a) -- ^ @\"<= v\"@
-> (Version -> Version -> a) -- ^ @\"== v.*\"@ wildcard. The
-- function is passed the
-- inclusive lower bound and the
-- exclusive upper bounds of the
-- range defined by the wildcard.
-> (a -> a -> a) -- ^ @\"_ || _\"@ union
-> (a -> a -> a) -- ^ @\"_ && _\"@ intersection
-> (a -> a) -- ^ @\"(_)\"@ parentheses
-> VersionRange -> a
foldVersionRange' anyv this later earlier orLater orEarlier
wildcard union intersect parens = fold
where
fold AnyVersion = anyv
fold (ThisVersion v) = this v
fold (LaterVersion v) = later v
fold (EarlierVersion v) = earlier v
fold (UnionVersionRanges (ThisVersion v)
(LaterVersion v')) | v==v' = orLater v
fold (UnionVersionRanges (LaterVersion v)
(ThisVersion v')) | v==v' = orLater v
fold (UnionVersionRanges (ThisVersion v)
(EarlierVersion v')) | v==v' = orEarlier v
fold (UnionVersionRanges (EarlierVersion v)
(ThisVersion v')) | v==v' = orEarlier v
fold (WildcardVersion v) = wildcard v (wildcardUpperBound v)
fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2)
fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2)
fold (VersionRangeParens v) = parens (fold v)
-- | Does this version fall within the given range?
--
-- This is the evaluation function for the 'VersionRange' type.
--
withinRange :: Version -> VersionRange -> Bool
withinRange v = foldVersionRange
True
(\v' -> versionBranch v == versionBranch v')
(\v' -> versionBranch v > versionBranch v')
(\v' -> versionBranch v < versionBranch v')
(||)
(&&)
-- | View a 'VersionRange' as a union of intervals.
--
-- This provides a canonical view of the semantics of a 'VersionRange' as
-- opposed to the syntax of the expression used to define it. For the syntactic
-- view use 'foldVersionRange'.
--
-- Each interval is non-empty. The sequence is in increasing order and no
-- intervals overlap or touch. Therefore only the first and last can be
-- unbounded. The sequence can be empty if the range is empty
-- (e.g. a range expression like @< 1 && > 2@).
--
-- Other checks are trivial to implement using this view. For example:
--
-- > isNoVersion vr | [] <- asVersionIntervals vr = True
-- > | otherwise = False
--
-- > isSpecificVersion vr
-- > | [(LowerBound v InclusiveBound
-- > ,UpperBound v' InclusiveBound)] <- asVersionIntervals vr
-- > , v == v' = Just v
-- > | otherwise = Nothing
--
asVersionIntervals :: VersionRange -> [VersionInterval]
asVersionIntervals = versionIntervals . toVersionIntervals
-- | Does this 'VersionRange' place any restriction on the 'Version' or is it
-- in fact equivalent to 'AnyVersion'.
--
-- Note this is a semantic check, not simply a syntactic check. So for example
-- the following is @True@ (for all @v@).
--
-- > isAnyVersion (EarlierVersion v `UnionVersionRanges` orLaterVersion v)
--
isAnyVersion :: VersionRange -> Bool
isAnyVersion vr = case asVersionIntervals vr of
[(LowerBound v InclusiveBound, NoUpperBound)] | isVersion0 v -> True
_ -> False
-- | This is the converse of 'isAnyVersion'. It check if the version range is
-- empty, if there is no possible version that satisfies the version range.
--
-- For example this is @True@ (for all @v@):
--
-- > isNoVersion (EarlierVersion v `IntersectVersionRanges` LaterVersion v)
--
isNoVersion :: VersionRange -> Bool
isNoVersion vr = case asVersionIntervals vr of
[] -> True
_ -> False
-- | Is this version range in fact just a specific version?
--
-- For example the version range @\">= 3 && <= 3\"@ contains only the version
-- @3@.
--
isSpecificVersion :: VersionRange -> Maybe Version
isSpecificVersion vr = case asVersionIntervals vr of
[(LowerBound v InclusiveBound
,UpperBound v' InclusiveBound)]
| v == v' -> Just v
_ -> Nothing
-- | Simplify a 'VersionRange' expression. For non-empty version ranges
-- this produces a canonical form. Empty or inconsistent version ranges
-- are left as-is because that provides more information.
--
-- If you need a canonical form use
-- @fromVersionIntervals . toVersionIntervals@
--
-- It satisfies the following properties:
--
-- > withinRange v (simplifyVersionRange r) = withinRange v r
--
-- > withinRange v r = withinRange v r'
-- > ==> simplifyVersionRange r = simplifyVersionRange r'
-- > || isNoVersion r
-- > || isNoVersion r'
--
simplifyVersionRange :: VersionRange -> VersionRange
simplifyVersionRange vr
-- If the version range is inconsistent then we just return the
-- original since that has more information than ">1 && < 1", which
-- is the canonical inconsistent version range.
| null (versionIntervals vi) = vr
| otherwise = fromVersionIntervals vi
where
vi = toVersionIntervals vr
----------------------------
-- Wildcard range utilities
--
wildcardUpperBound :: Version -> Version
wildcardUpperBound (Version lowerBound ts) = Version upperBound ts
where
upperBound = init lowerBound ++ [last lowerBound + 1]
isWildcardRange :: Version -> Version -> Bool
isWildcardRange (Version branch1 _) (Version branch2 _) = check branch1 branch2
where check (n:[]) (m:[]) | n+1 == m = True
check (n:ns) (m:ms) | n == m = check ns ms
check _ _ = False
------------------
-- Intervals view
--
-- | A complementary representation of a 'VersionRange'. Instead of a boolean
-- version predicate it uses an increasing sequence of non-overlapping,
-- non-empty intervals.
--
-- The key point is that this representation gives a canonical representation
-- for the semantics of 'VersionRange's. This makes it easier to check things
-- like whether a version range is empty, covers all versions, or requires a
-- certain minimum or maximum version. It also makes it easy to check equality
-- or containment. It also makes it easier to identify \'simple\' version
-- predicates for translation into foreign packaging systems that do not
-- support complex version range expressions.
--
newtype VersionIntervals = VersionIntervals [VersionInterval]
deriving (Eq, Show)
-- | Inspect the list of version intervals.
--
versionIntervals :: VersionIntervals -> [VersionInterval]
versionIntervals (VersionIntervals is) = is
type VersionInterval = (LowerBound, UpperBound)
data LowerBound = LowerBound Version !Bound deriving (Eq, Show)
data UpperBound = NoUpperBound | UpperBound Version !Bound deriving (Eq, Show)
data Bound = ExclusiveBound | InclusiveBound deriving (Eq, Show)
minLowerBound :: LowerBound
minLowerBound = LowerBound (Version [0] []) InclusiveBound
isVersion0 :: Version -> Bool
isVersion0 (Version [0] _) = True
isVersion0 _ = False
instance Ord LowerBound where
LowerBound ver bound <= LowerBound ver' bound' = case compare ver ver' of
LT -> True
EQ -> not (bound == ExclusiveBound && bound' == InclusiveBound)
GT -> False
instance Ord UpperBound where
_ <= NoUpperBound = True
NoUpperBound <= UpperBound _ _ = False
UpperBound ver bound <= UpperBound ver' bound' = case compare ver ver' of
LT -> True
EQ -> not (bound == InclusiveBound && bound' == ExclusiveBound)
GT -> False
invariant :: VersionIntervals -> Bool
invariant (VersionIntervals intervals) = all validInterval intervals
&& all doesNotTouch' adjacentIntervals
where
doesNotTouch' :: (VersionInterval, VersionInterval) -> Bool
doesNotTouch' ((_,u), (l',_)) = doesNotTouch u l'
adjacentIntervals :: [(VersionInterval, VersionInterval)]
adjacentIntervals
| null intervals = []
| otherwise = zip intervals (tail intervals)
checkInvariant :: VersionIntervals -> VersionIntervals
checkInvariant is = assert (invariant is) is
-- | Directly construct a 'VersionIntervals' from a list of intervals.
--
-- Each interval must be non-empty. The sequence must be in increasing order
-- and no intervals may overlap or touch. If any of these conditions are not
-- satisfied the function returns @Nothing@.
--
mkVersionIntervals :: [VersionInterval] -> Maybe VersionIntervals
mkVersionIntervals intervals
| invariant (VersionIntervals intervals) = Just (VersionIntervals intervals)
| otherwise = Nothing
validVersion :: Version -> Bool
validVersion (Version [] _) = False
validVersion (Version vs _) = all (>=0) vs
validInterval :: (LowerBound, UpperBound) -> Bool
validInterval i@(l, u) = validLower l && validUpper u && nonEmpty i
where
validLower (LowerBound v _) = validVersion v
validUpper NoUpperBound = True
validUpper (UpperBound v _) = validVersion v
-- Check an interval is non-empty
--
nonEmpty :: VersionInterval -> Bool
nonEmpty (_, NoUpperBound ) = True
nonEmpty (LowerBound l lb, UpperBound u ub) =
(l < u) || (l == u && lb == InclusiveBound && ub == InclusiveBound)
-- Check an upper bound does not intersect, or even touch a lower bound:
--
-- ---| or ---) but not ---] or ---) or ---]
-- |--- (--- (--- [--- [---
--
doesNotTouch :: UpperBound -> LowerBound -> Bool
doesNotTouch NoUpperBound _ = False
doesNotTouch (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && ub == ExclusiveBound && lb == ExclusiveBound)
-- | Check an upper bound does not intersect a lower bound:
--
-- ---| or ---) or ---] or ---) but not ---]
-- |--- (--- (--- [--- [---
--
doesNotIntersect :: UpperBound -> LowerBound -> Bool
doesNotIntersect NoUpperBound _ = False
doesNotIntersect (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && not (ub == InclusiveBound && lb == InclusiveBound))
-- | Test if a version falls within the version intervals.
--
-- It exists mostly for completeness and testing. It satisfies the following
-- properties:
--
-- > withinIntervals v (toVersionIntervals vr) = withinRange v vr
-- > withinIntervals v ivs = withinRange v (fromVersionIntervals ivs)
--
withinIntervals :: Version -> VersionIntervals -> Bool
withinIntervals v (VersionIntervals intervals) = any withinInterval intervals
where
withinInterval (lowerBound, upperBound) = withinLower lowerBound
&& withinUpper upperBound
withinLower (LowerBound v' ExclusiveBound) = v' < v
withinLower (LowerBound v' InclusiveBound) = v' <= v
withinUpper NoUpperBound = True
withinUpper (UpperBound v' ExclusiveBound) = v' > v
withinUpper (UpperBound v' InclusiveBound) = v' >= v
-- | Convert a 'VersionRange' to a sequence of version intervals.
--
toVersionIntervals :: VersionRange -> VersionIntervals
toVersionIntervals = foldVersionRange
( chkIvl (minLowerBound, NoUpperBound))
(\v -> chkIvl (LowerBound v InclusiveBound, UpperBound v InclusiveBound))
(\v -> chkIvl (LowerBound v ExclusiveBound, NoUpperBound))
(\v -> if isVersion0 v then VersionIntervals [] else
chkIvl (minLowerBound, UpperBound v ExclusiveBound))
unionVersionIntervals
intersectVersionIntervals
where
chkIvl interval = checkInvariant (VersionIntervals [interval])
-- | Convert a 'VersionIntervals' value back into a 'VersionRange' expression
-- representing the version intervals.
--
fromVersionIntervals :: VersionIntervals -> VersionRange
fromVersionIntervals (VersionIntervals []) = noVersion
fromVersionIntervals (VersionIntervals intervals) =
foldr1 UnionVersionRanges [ interval l u | (l, u) <- intervals ]
where
interval (LowerBound v InclusiveBound)
(UpperBound v' InclusiveBound) | v == v'
= ThisVersion v
interval (LowerBound v InclusiveBound)
(UpperBound v' ExclusiveBound) | isWildcardRange v v'
= WildcardVersion v
interval l u = lowerBound l `intersectVersionRanges'` upperBound u
lowerBound (LowerBound v InclusiveBound)
| isVersion0 v = AnyVersion
| otherwise = orLaterVersion v
lowerBound (LowerBound v ExclusiveBound) = LaterVersion v
upperBound NoUpperBound = AnyVersion
upperBound (UpperBound v InclusiveBound) = orEarlierVersion v
upperBound (UpperBound v ExclusiveBound) = EarlierVersion v
intersectVersionRanges' vr AnyVersion = vr
intersectVersionRanges' AnyVersion vr = vr
intersectVersionRanges' vr vr' = IntersectVersionRanges vr vr'
unionVersionIntervals :: VersionIntervals -> VersionIntervals
-> VersionIntervals
unionVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) =
checkInvariant (VersionIntervals (union is0 is'0))
where
union is [] = is
union [] is' = is'
union (i:is) (i':is') = case unionInterval i i' of
Left Nothing -> i : union is (i' :is')
Left (Just i'') -> union is (i'':is')
Right Nothing -> i' : union (i :is) is'
Right (Just i'') -> union (i'':is) is'
unionInterval :: VersionInterval -> VersionInterval
-> Either (Maybe VersionInterval) (Maybe VersionInterval)
unionInterval (lower , upper ) (lower', upper')
-- Non-intersecting intervals with the left interval ending first
| upper `doesNotTouch` lower' = Left Nothing
-- Non-intersecting intervals with the right interval first
| upper' `doesNotTouch` lower = Right Nothing
-- Complete or partial overlap, with the left interval ending first
| upper <= upper' = lowerBound `seq`
Left (Just (lowerBound, upper'))
-- Complete or partial overlap, with the left interval ending first
| otherwise = lowerBound `seq`
Right (Just (lowerBound, upper))
where
lowerBound = min lower lower'
intersectVersionIntervals :: VersionIntervals -> VersionIntervals
-> VersionIntervals
intersectVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) =
checkInvariant (VersionIntervals (intersect is0 is'0))
where
intersect _ [] = []
intersect [] _ = []
intersect (i:is) (i':is') = case intersectInterval i i' of
Left Nothing -> intersect is (i':is')
Left (Just i'') -> i'' : intersect is (i':is')
Right Nothing -> intersect (i:is) is'
Right (Just i'') -> i'' : intersect (i:is) is'
intersectInterval :: VersionInterval -> VersionInterval
-> Either (Maybe VersionInterval) (Maybe VersionInterval)
intersectInterval (lower , upper ) (lower', upper')
-- Non-intersecting intervals with the left interval ending first
| upper `doesNotIntersect` lower' = Left Nothing
-- Non-intersecting intervals with the right interval first
| upper' `doesNotIntersect` lower = Right Nothing
-- Complete or partial overlap, with the left interval ending first
| upper <= upper' = lowerBound `seq`
Left (Just (lowerBound, upper))
-- Complete or partial overlap, with the right interval ending first
| otherwise = lowerBound `seq`
Right (Just (lowerBound, upper'))
where
lowerBound = max lower lower'
invertVersionIntervals :: VersionIntervals
-> VersionIntervals
invertVersionIntervals (VersionIntervals xs) =
case xs of
-- Empty interval set
[] -> VersionIntervals [(noLowerBound, NoUpperBound)]
-- Interval with no lower bound
((lb, ub) : more) | lb == noLowerBound -> VersionIntervals $ invertVersionIntervals' ub more
-- Interval with a lower bound
((lb, ub) : more) ->
VersionIntervals $ (noLowerBound, invertLowerBound lb) : invertVersionIntervals' ub more
where
-- Invert subsequent version intervals given the upper bound of
-- the intervals already inverted.
invertVersionIntervals' :: UpperBound
-> [(LowerBound, UpperBound)]
-> [(LowerBound, UpperBound)]
invertVersionIntervals' NoUpperBound [] = []
invertVersionIntervals' ub0 [] = [(invertUpperBound ub0, NoUpperBound)]
invertVersionIntervals' ub0 [(lb, NoUpperBound)] =
[(invertUpperBound ub0, invertLowerBound lb)]
invertVersionIntervals' ub0 ((lb, ub1) : more) =
(invertUpperBound ub0, invertLowerBound lb)
: invertVersionIntervals' ub1 more
invertLowerBound :: LowerBound -> UpperBound
invertLowerBound (LowerBound v b) = UpperBound v (invertBound b)
invertUpperBound :: UpperBound -> LowerBound
invertUpperBound (UpperBound v b) = LowerBound v (invertBound b)
invertUpperBound NoUpperBound = error "NoUpperBound: unexpected"
invertBound :: Bound -> Bound
invertBound ExclusiveBound = InclusiveBound
invertBound InclusiveBound = ExclusiveBound
noLowerBound :: LowerBound
noLowerBound = LowerBound (Version [0] []) InclusiveBound
-------------------------------
-- Parsing and pretty printing
--
instance Text VersionRange where
disp = fst
. foldVersionRange' -- precedence:
( Disp.text "-any" , 0 :: Int)
(\v -> (Disp.text "==" <> disp v , 0))
(\v -> (Disp.char '>' <> disp v , 0))
(\v -> (Disp.char '<' <> disp v , 0))
(\v -> (Disp.text ">=" <> disp v , 0))
(\v -> (Disp.text "<=" <> disp v , 0))
(\v _ -> (Disp.text "==" <> dispWild v , 0))
(\(r1, p1) (r2, p2) -> (punct 2 p1 r1 <+> Disp.text "||" <+> punct 2 p2 r2 , 2))
(\(r1, p1) (r2, p2) -> (punct 1 p1 r1 <+> Disp.text "&&" <+> punct 1 p2 r2 , 1))
(\(r, _) -> (Disp.parens r, 0))
where dispWild (Version b _) =
Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b))
<> Disp.text ".*"
punct p p' | p < p' = Disp.parens
| otherwise = id
parse = expr
where
expr = do Parse.skipSpaces
t <- term
Parse.skipSpaces
(do _ <- Parse.string "||"
Parse.skipSpaces
e <- expr
return (UnionVersionRanges t e)
+++
return t)
term = do f <- factor
Parse.skipSpaces
(do _ <- Parse.string "&&"
Parse.skipSpaces
t <- term
return (IntersectVersionRanges f t)
+++
return f)
factor = Parse.choice $ parens expr
: parseAnyVersion
: parseNoVersion
: parseWildcardRange
: map parseRangeOp rangeOps
parseAnyVersion = Parse.string "-any" >> return AnyVersion
parseNoVersion = Parse.string "-none" >> return noVersion
parseWildcardRange = do
_ <- Parse.string "=="
Parse.skipSpaces
branch <- Parse.sepBy1 digits (Parse.char '.')
_ <- Parse.char '.'
_ <- Parse.char '*'
return (WildcardVersion (Version branch []))
parens p = Parse.between (Parse.char '(' >> Parse.skipSpaces)
(Parse.char ')' >> Parse.skipSpaces)
(do a <- p
Parse.skipSpaces
return (VersionRangeParens a))
digits = do
first <- Parse.satisfy Char.isDigit
if first == '0'
then return 0
else do rest <- Parse.munch Char.isDigit
return (read (first : rest))
parseRangeOp (s,f) = Parse.string s >> Parse.skipSpaces >> fmap f parse
rangeOps = [ ("<", EarlierVersion),
("<=", orEarlierVersion),
(">", LaterVersion),
(">=", orLaterVersion),
("==", ThisVersion) ]
-- | Does the version range have an upper bound?
--
-- @since 1.24.0.0
hasUpperBound :: VersionRange -> Bool
hasUpperBound = foldVersionRange
False
(const True)
(const False)
(const True)
(&&) (||)
-- | Does the version range have an explicit lower bound?
--
-- Note: this function only considers the user-specified lower bounds, but not
-- the implicit >=0 lower bound.
--
-- @since 1.24.0.0
hasLowerBound :: VersionRange -> Bool
hasLowerBound = foldVersionRange
False
(const True)
(const True)
(const False)
(&&) (||)
| edsko/cabal | Cabal/src/Distribution/Version.hs | bsd-3-clause | 32,803 | 0 | 17 | 8,822 | 6,294 | 3,390 | 2,904 | 455 | 12 |
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
-- | This module provides various simple ways to query and manipulate
-- fundamental Futhark terms, such as types and values. The intent is to
-- keep "Futhark.Language.Syntax" simple, and put whatever embellishments
-- we need here.
module Language.Futhark.Attributes
(
builtInFunctions
-- * Parameter handling
, toParam
, fromParam
, paramType
, paramDeclaredType
-- * Queries on expressions
, typeOf
, commutative
-- * Queries on patterns
, patNameSet
, patIdents
-- * Queries on types
, primType
, uniqueness
, unique
, tupleArrayElemUniqueness
, aliases
, diet
, subtypeOf
, similarTo
, arrayRank
, arrayDims
, arrayDims'
, nestedDims
, nestedDims'
, setArrayShape
, removeShapeAnnotations
, vacuousShapeAnnotations
, returnType
, lambdaReturnType
-- * Operations on types
, peelArray
, arrayOf
, arrayType
, toStructural
, toStruct
, fromStruct
, setAliases
, addAliases
, setUniqueness
, tupleArrayElemToType
, contractTypeBase
-- ** Removing and adding names
--
-- $names
, removeNames
, nameToQualName
-- * Queries on values
, valueType
-- * Getters for decs
, isType
, isFun
, isFunOrType
, isMod
, isSig
, funsFromProg
, typesFromProg
, sigsFromProg
, modsFromProg
, decLoc
-- | Values of these types are produces by the parser. They use
-- unadorned names and have no type information, apart from that
-- which is syntactically required.
, NoInfo(..)
, UncheckedType
, UncheckedUserType
, UncheckedArrayType
, UncheckedIdent
, UncheckedTypeDecl
, UncheckedUserTypeDecl
, UncheckedExp
, UncheckedLambda
, UncheckedPattern
, UncheckedFunDef
, UncheckedProg
, UncheckedProgWithHeaders
)
where
import Control.Monad.Writer
import Data.Hashable
import Data.List
import Data.Loc
import Data.Maybe
import qualified Data.HashSet as HS
import qualified Data.HashMap.Lazy as HM
import Prelude
import Language.Futhark.Syntax
-- | Return the dimensionality of a type. For non-arrays, this is
-- zero. For a one-dimensional array it is one, for a two-dimensional
-- it is two, and so forth.
arrayRank :: ArrayShape (shape vn) =>
TypeBase shape as vn -> Int
arrayRank = shapeRank . arrayShape
-- | Return the shape of a type - for non-arrays, this is 'mempty'.
arrayShape :: ArrayShape (shape vn) =>
TypeBase shape as vn -> shape vn
arrayShape (Array (PrimArray _ ds _ _)) = ds
arrayShape (Array (TupleArray _ ds _)) = ds
arrayShape _ = mempty
-- | Return the shape of a type - for non-arrays, this is 'mempty'.
arrayShape' :: UserType vn -> ShapeDecl vn
arrayShape' (UserArray t d _) = ShapeDecl [d] <> arrayShape' t
arrayShape' (UserUnique t _) = arrayShape' t
arrayShape' _ = mempty
-- | Return the dimensions of a type with (possibly) known dimensions.
arrayDims :: Ord vn => TypeBase ShapeDecl as vn -> [DimDecl vn]
arrayDims = shapeDims . arrayShape
-- | Return the dimensions of a type with (possibly) known dimensions.
arrayDims' :: UserType vn -> [DimDecl vn]
arrayDims' = shapeDims . arrayShape'
-- | Return any shape declaration in the type, with duplicates removed.
nestedDims :: Ord vn => TypeBase ShapeDecl as vn -> [DimDecl vn]
nestedDims t =
case t of Array a -> nub $ arrayNestedDims a
Tuple ts -> nub $ mconcat $ map nestedDims ts
Prim{} -> mempty
where arrayNestedDims (PrimArray _ ds _ _) =
shapeDims ds
arrayNestedDims (TupleArray ts ds _) =
shapeDims ds <> mconcat (map tupleArrayElemNestedDims ts)
tupleArrayElemNestedDims (ArrayArrayElem a) =
arrayNestedDims a
tupleArrayElemNestedDims (TupleArrayElem ts) =
mconcat $ map tupleArrayElemNestedDims ts
tupleArrayElemNestedDims PrimArrayElem{} =
mempty
-- | Return any shape declaration in the type, with duplicates removed.
nestedDims' :: Ord vn => UserType vn -> [DimDecl vn]
nestedDims' (UserArray t d _) = nub $ d : nestedDims' t
nestedDims' (UserTuple ts _) = nub $ mconcat $ map nestedDims' ts
nestedDims' (UserUnique t _) = nestedDims' t
nestedDims' _ = mempty
-- | Set the dimensions of an array. If the given type is not an
-- array, return the type unchanged.
setArrayShape :: shape vn -> TypeBase shape as vn -> TypeBase shape as vn
setArrayShape ds (Array (PrimArray et _ u as)) = Array $ PrimArray et ds u as
setArrayShape ds (Array (TupleArray et _ u)) = Array $ TupleArray et ds u
setArrayShape _ (Tuple ts) = Tuple ts
setArrayShape _ (Prim t) = Prim t
-- | Change the shape of a type to be just the 'Rank'.
removeShapeAnnotations :: ArrayShape (shape vn) =>
TypeBase shape as vn -> TypeBase Rank as vn
removeShapeAnnotations = modifyShapeAnnotations $ Rank . shapeRank
-- | Change the shape of a type to be a 'ShapeDecl' where all
-- dimensions are 'Nothing'.
vacuousShapeAnnotations :: ArrayShape (shape vn) =>
TypeBase shape as vn -> TypeBase ShapeDecl as vn
vacuousShapeAnnotations = modifyShapeAnnotations $ \shape ->
ShapeDecl (replicate (shapeRank shape) AnyDim)
-- | Change the shape of a type.
modifyShapeAnnotations :: (oldshape vn -> newshape vn)
-> TypeBase oldshape as vn
-> TypeBase newshape as vn
modifyShapeAnnotations f (Array at) =
Array $ modifyShapeAnnotationsFromArray f at
modifyShapeAnnotations f (Tuple ts) =
Tuple $ map (modifyShapeAnnotations f) ts
modifyShapeAnnotations _ (Prim t) =
Prim t
modifyShapeAnnotationsFromArray :: (oldshape vn -> newshape vn)
-> ArrayTypeBase oldshape as vn
-> ArrayTypeBase newshape as vn
modifyShapeAnnotationsFromArray f (PrimArray et shape u as) =
PrimArray et (f shape) u as
modifyShapeAnnotationsFromArray f (TupleArray ts shape u) =
TupleArray
(map (modifyShapeAnnotationsFromTupleArrayElem f) ts)
(f shape) u
-- Try saying this one three times fast.
modifyShapeAnnotationsFromTupleArrayElem :: (oldshape vn -> newshape vn)
-> TupleArrayElemTypeBase oldshape as vn
-> TupleArrayElemTypeBase newshape as vn
modifyShapeAnnotationsFromTupleArrayElem
_ (PrimArrayElem bt as u) = PrimArrayElem bt as u
modifyShapeAnnotationsFromTupleArrayElem
f (ArrayArrayElem at) = ArrayArrayElem $ modifyShapeAnnotationsFromArray f at
modifyShapeAnnotationsFromTupleArrayElem
f (TupleArrayElem ts) = TupleArrayElem $ map (modifyShapeAnnotationsFromTupleArrayElem f) ts
-- | @x `subuniqueOf` y@ is true if @x@ is not less unique than @y@.
subuniqueOf :: Uniqueness -> Uniqueness -> Bool
subuniqueOf Nonunique Unique = False
subuniqueOf _ _ = True
-- | @x \`subtypeOf\` y@ is true if @x@ is a subtype of @y@ (or equal to
-- @y@), meaning @x@ is valid whenever @y@ is.
subtypeOf :: (ArrayShape (shape vn), Monoid (as1 vn), Monoid (as2 vn)) =>
TypeBase shape as1 vn -> TypeBase shape as2 vn -> Bool
subtypeOf
(Array (PrimArray t1 dims1 u1 _))
(Array (PrimArray t2 dims2 u2 _)) =
u1 `subuniqueOf` u2
&& t1 == t2
&& dims1 == dims2
subtypeOf
(Array (TupleArray et1 dims1 u1))
(Array (TupleArray et2 dims2 u2)) =
u1 `subuniqueOf` u2
&& length et1 == length et2
&& and (zipWith subtypeOf
(map tupleArrayElemToType et1)
(map tupleArrayElemToType et2))
&& dims1 == dims2
subtypeOf (Tuple ts1) (Tuple ts2) =
length ts1 == length ts2 && and (zipWith subtypeOf ts1 ts2)
subtypeOf (Prim bt1) (Prim bt2) = bt1 == bt2
subtypeOf _ _ = False
-- | @x \`similarTo\` y@ is true if @x@ and @y@ are the same type,
-- ignoring uniqueness.
similarTo :: (ArrayShape (shape vn), Monoid (as vn)) =>
TypeBase shape as vn
-> TypeBase shape as vn
-> Bool
similarTo t1 t2 = t1 `subtypeOf` t2 || t2 `subtypeOf` t1
-- | Return the uniqueness of a type.
uniqueness :: TypeBase shape as vn -> Uniqueness
uniqueness (Array (PrimArray _ _ u _)) = u
uniqueness (Array (TupleArray _ _ u)) = u
uniqueness _ = Nonunique
tupleArrayElemUniqueness :: TupleArrayElemTypeBase shape as vn -> Uniqueness
tupleArrayElemUniqueness (PrimArrayElem _ _ u) = u
tupleArrayElemUniqueness (ArrayArrayElem (PrimArray _ _ u _)) = u
tupleArrayElemUniqueness (ArrayArrayElem (TupleArray _ _ u)) = u
tupleArrayElemUniqueness (TupleArrayElem ts) = mconcat $ map tupleArrayElemUniqueness ts
-- | @unique t@ is 'True' if the type of the argument is unique.
unique :: TypeBase shape as vn -> Bool
unique = (==Unique) . uniqueness
-- | Return the set of all variables mentioned in the aliasing of a
-- type.
aliases :: Monoid (as vn) => TypeBase shape as vn -> as vn
aliases (Array (PrimArray _ _ _ als)) = als
aliases (Array (TupleArray ts _ _)) = mconcat $ map tupleArrayElemAliases ts
aliases (Tuple et) = mconcat $ map aliases et
aliases (Prim _) = mempty
tupleArrayElemAliases :: Monoid (as vn) =>
TupleArrayElemTypeBase shape as vn -> as vn
tupleArrayElemAliases (PrimArrayElem _ als _) = als
tupleArrayElemAliases (ArrayArrayElem (PrimArray _ _ _ als)) =
als
tupleArrayElemAliases (ArrayArrayElem (TupleArray ts _ _)) =
mconcat $ map tupleArrayElemAliases ts
tupleArrayElemAliases (TupleArrayElem ts) =
mconcat $ map tupleArrayElemAliases ts
-- | @diet t@ returns a description of how a function parameter of
-- type @t@ might consume its argument.
diet :: TypeBase shape as vn -> Diet
diet (Tuple ets) = TupleDiet $ map diet ets
diet (Prim _) = Observe
diet (Array (PrimArray _ _ Unique _)) = Consume
diet (Array (PrimArray _ _ Nonunique _)) = Observe
diet (Array (TupleArray _ _ Unique)) = Consume
diet (Array (TupleArray _ _ Nonunique)) = Observe
-- | @t `maskAliases` d@ removes aliases (sets them to 'mempty') from
-- the parts of @t@ that are denoted as 'Consumed' by the 'Diet' @d@.
maskAliases :: Monoid (as vn) =>
TypeBase shape as vn
-> Diet
-> TypeBase shape as vn
maskAliases t Consume = t `setAliases` mempty
maskAliases t Observe = t
maskAliases (Tuple ets) (TupleDiet ds) =
Tuple $ zipWith maskAliases ets ds
maskAliases _ _ = error "Invalid arguments passed to maskAliases."
-- | Convert any type to one that has rank information, no alias
-- information, and no embedded names.
toStructural :: (ArrayShape (shape vn)) =>
TypeBase shape as vn
-> TypeBase Rank NoInfo ()
toStructural = removeNames . removeShapeAnnotations
-- | -- | Remove aliasing information from a type.
-- | toStruct :: TypeBase shape as vn
-- | -> TypeBase shape NoInfo vn
-- | toStruct t = t `setAliases` NoInfo
-- | Remove aliasing information from a type.
toStruct :: TypeBase shape as vn
-> TypeBase shape NoInfo vn
toStruct t = t `setAliases` NoInfo
-- | Replace no aliasing with an empty alias set.
fromStruct :: TypeBase shape as vn
-> TypeBase shape Names vn
fromStruct t = t `setAliases` HS.empty
-- | @peelArray n t@ returns the type resulting from peeling the first
-- @n@ array dimensions from @t@. Returns @Nothing@ if @t@ has less
-- than @n@ dimensions.
peelArray :: ArrayShape (shape vn) =>
Int -> TypeBase shape as vn -> Maybe (TypeBase shape as vn)
peelArray 0 t = Just t
peelArray n (Array (PrimArray et shape _ _))
| shapeRank shape == n =
Just $ Prim et
peelArray n (Array (TupleArray ts shape _))
| shapeRank shape == n =
Just $ Tuple $ map asType ts
where asType (PrimArrayElem bt _ _) = Prim bt
asType (ArrayArrayElem at) = Array at
asType (TupleArrayElem ts') = Tuple $ map asType ts'
peelArray n (Array (PrimArray et shape u als)) = do
shape' <- stripDims n shape
return $ Array $ PrimArray et shape' u als
peelArray n (Array (TupleArray et shape u)) = do
shape' <- stripDims n shape
return $ Array $ TupleArray et shape' u
peelArray _ _ = Nothing
-- | Return the immediate row-type of an array. For @[[int]]@, this
-- would be @[int]@.
rowType :: (ArrayShape (shape vn), Monoid (as vn)) =>
TypeBase shape as vn -> TypeBase shape as vn
rowType = stripArray 1
-- | A type is a primitive type if it is not an array and any component
-- types are prim types.
primType :: TypeBase shape as vn -> Bool
primType (Tuple ts) = all primType ts
primType (Prim _) = True
primType (Array _) = False
-- $names
--
-- The element type annotation of 'ArrayVal' values is a 'TypeBase'
-- with '()' for variable names. This means that when we construct
-- 'ArrayVal's based on a type with a more common name representation,
-- we need to remove the names and replace them with '()'s. Since the
-- only place names appear in types is in the array size annotations,
-- we have to replace the shape with a 'Rank'.
-- | Remove names from a type - this involves removing all size
-- annotations from arrays, as well as all aliasing.
removeNames :: ArrayShape (shape vn) =>
TypeBase shape as vn
-> TypeBase Rank NoInfo ()
removeNames (Prim et) = Prim et
removeNames (Tuple ts) = Tuple $ map removeNames ts
removeNames (Array at) = Array $ removeArrayNames at
removeArrayNames :: ArrayShape (shape vn) =>
ArrayTypeBase shape as vn
-> ArrayTypeBase Rank NoInfo ()
removeArrayNames (PrimArray et shape u _) =
PrimArray et (Rank $ shapeRank shape) u NoInfo
removeArrayNames (TupleArray et shape u) =
TupleArray (map removeTupleArrayElemNames et) (Rank $ shapeRank shape) u
removeTupleArrayElemNames :: ArrayShape (shape vn) =>
TupleArrayElemTypeBase shape as vn
-> TupleArrayElemTypeBase Rank NoInfo ()
removeTupleArrayElemNames (PrimArrayElem bt _ u) =
PrimArrayElem bt NoInfo u
removeTupleArrayElemNames (ArrayArrayElem et) =
ArrayArrayElem $ removeArrayNames et
removeTupleArrayElemNames (TupleArrayElem ts) =
TupleArrayElem $ map removeTupleArrayElemNames ts
-- | Add names to a type.
addNames :: TypeBase Rank NoInfo ()
-> TypeBase Rank NoInfo vn
addNames (Prim et) = Prim et
addNames (Tuple ts) = Tuple $ map addNames ts
addNames (Array at) = Array $ addArrayNames at
addArrayNames :: ArrayTypeBase Rank NoInfo ()
-> ArrayTypeBase Rank NoInfo vn
addArrayNames (PrimArray et (Rank n) u _) =
PrimArray et (Rank n) u NoInfo
addArrayNames (TupleArray et (Rank n) u) =
TupleArray (map addTupleArrayElemNames et) (Rank n) u
addTupleArrayElemNames :: TupleArrayElemTypeBase Rank NoInfo ()
-> TupleArrayElemTypeBase Rank NoInfo vn
addTupleArrayElemNames (PrimArrayElem bt _ u) =
PrimArrayElem bt NoInfo u
addTupleArrayElemNames (ArrayArrayElem et) =
ArrayArrayElem $ addArrayNames et
addTupleArrayElemNames (TupleArrayElem ts) =
TupleArrayElem $ map addTupleArrayElemNames ts
-- | @arrayOf t s u@ constructs an array type. The convenience
-- compared to using the 'Array' constructor directly is that @t@ can
-- itself be an array. If @t@ is an @n@-dimensional array, and @s@ is
-- a list of length @n@, the resulting type is of an @n+m@ dimensions.
-- The uniqueness of the new array will be @u@, no matter the
-- uniqueness of @t@.
arrayOf :: (ArrayShape (shape vn), Monoid (as vn)) =>
TypeBase shape as vn
-> shape vn
-> Uniqueness
-> TypeBase shape as vn
arrayOf (Array (PrimArray et shape1 _ als)) shape2 u =
Array $ PrimArray et (shape2 <> shape1) u als
arrayOf (Array (TupleArray et shape1 _)) shape2 u =
Array $ TupleArray et (shape2 <> shape1) u
arrayOf (Prim et) shape u =
Array $ PrimArray et shape u mempty
arrayOf (Tuple ts) shape u =
Array $ TupleArray (map (`typeToTupleArrayElem` u) ts) shape u
typeToTupleArrayElem :: Monoid (as vn) =>
TypeBase shape as vn
-> Uniqueness
-> TupleArrayElemTypeBase shape as vn
typeToTupleArrayElem (Prim bt) u = PrimArrayElem bt mempty u
typeToTupleArrayElem (Tuple ts') u = TupleArrayElem $ map (`typeToTupleArrayElem` u) ts'
typeToTupleArrayElem (Array at) _ = ArrayArrayElem at
tupleArrayElemToType :: Monoid (as vn) =>
TupleArrayElemTypeBase shape as vn
-> TypeBase shape as vn
tupleArrayElemToType (PrimArrayElem bt _ _) = Prim bt
tupleArrayElemToType (TupleArrayElem ts) = Tuple $ map tupleArrayElemToType ts
tupleArrayElemToType (ArrayArrayElem at) = Array at
-- | @array n t@ is the type of @n@-dimensional arrays having @t@ as
-- the base type. If @t@ is itself an m-dimensional array, the result
-- is an @n+m@-dimensional array with the same base type as @t@. If
-- you need to specify size information for the array, use 'arrayOf'
-- instead.
arrayType :: (ArrayShape (shape vn), Monoid (as vn)) =>
Int
-> TypeBase shape as vn
-> Uniqueness
-> TypeBase Rank as vn
arrayType 0 t _ = removeShapeAnnotations t
arrayType n t u = arrayOf (removeShapeAnnotations t) (Rank n) u
-- | @stripArray n t@ removes the @n@ outermost layers of the array.
-- Essentially, it is the type of indexing an array of type @t@ with
-- @n@ indexes.
stripArray :: (ArrayShape (shape vn), Monoid (as vn)) =>
Int -> TypeBase shape as vn -> TypeBase shape as vn
stripArray n (Array (PrimArray et shape u als))
| Just shape' <- stripDims n shape =
Array $ PrimArray et shape' u als
| otherwise = Prim et
stripArray n (Array (TupleArray et shape u))
| Just shape' <- stripDims n shape =
Array $ TupleArray et shape' u
| otherwise = Tuple $ map tupleArrayElemToType et
stripArray _ t = t
-- | Set the uniqueness attribute of a type. If the type is a tuple,
-- the uniqueness of its components will be modified.
setUniqueness :: TypeBase shape as vn -> Uniqueness -> TypeBase shape as vn
setUniqueness (Array at) u =
Array $ setArrayUniqueness at u
setUniqueness (Tuple ets) u =
Tuple $ map (`setUniqueness` u) ets
setUniqueness t _ = t
setArrayUniqueness :: ArrayTypeBase shape as vn -> Uniqueness
-> ArrayTypeBase shape as vn
setArrayUniqueness (PrimArray et dims _ als) u =
PrimArray et dims u als
setArrayUniqueness (TupleArray et dims _) u =
TupleArray (map (`setTupleArrayElemUniqueness` u) et) dims u
setTupleArrayElemUniqueness :: TupleArrayElemTypeBase shape as vn -> Uniqueness
-> TupleArrayElemTypeBase shape as vn
setTupleArrayElemUniqueness (PrimArrayElem bt als _) u =
PrimArrayElem bt als u
setTupleArrayElemUniqueness (ArrayArrayElem at) u =
ArrayArrayElem $ setArrayUniqueness at u
setTupleArrayElemUniqueness (TupleArrayElem ts) u =
TupleArrayElem $ map (`setTupleArrayElemUniqueness` u) ts
-- | @t \`setAliases\` als@ returns @t@, but with @als@ substituted for
-- any already present aliasing.
setAliases :: TypeBase shape asf vn -> ast vn -> TypeBase shape ast vn
setAliases t = addAliases t . const
-- | @t \`addAliases\` f@ returns @t@, but with any already present
-- aliasing replaced by @f@ applied to that aliasing.
addAliases :: TypeBase shape asf vn -> (asf vn -> ast vn)
-> TypeBase shape ast vn
addAliases (Array at) f =
Array $ addArrayAliases at f
addAliases (Tuple ts) f =
Tuple $ map (`addAliases` f) ts
addAliases (Prim et) _ =
Prim et
addArrayAliases :: ArrayTypeBase shape asf vn
-> (asf vn -> ast vn)
-> ArrayTypeBase shape ast vn
addArrayAliases (PrimArray et dims u als) f =
PrimArray et dims u $ f als
addArrayAliases (TupleArray et dims u) f =
TupleArray (map (`addTupleArrayElemAliases` f) et) dims u
addTupleArrayElemAliases :: TupleArrayElemTypeBase shape asf vn
-> (asf vn -> ast vn)
-> TupleArrayElemTypeBase shape ast vn
addTupleArrayElemAliases (PrimArrayElem bt als u) f =
PrimArrayElem bt (f als) u
addTupleArrayElemAliases (ArrayArrayElem at) f =
ArrayArrayElem $ addArrayAliases at f
addTupleArrayElemAliases (TupleArrayElem ts) f =
TupleArrayElem $ map (`addTupleArrayElemAliases` f) ts
intValueType :: IntValue -> IntType
intValueType Int8Value{} = Int8
intValueType Int16Value{} = Int16
intValueType Int32Value{} = Int32
intValueType Int64Value{} = Int64
floatValueType :: FloatValue -> FloatType
floatValueType Float32Value{} = Float32
floatValueType Float64Value{} = Float64
-- | The type of a basic value.
primValueType :: PrimValue -> PrimType
primValueType (SignedValue v) = Signed $ intValueType v
primValueType (UnsignedValue v) = Unsigned $ intValueType v
primValueType (FloatValue v) = FloatType $ floatValueType v
primValueType BoolValue{} = Bool
-- | The type of an Futhark value.
valueType :: Value -> TypeBase Rank NoInfo vn
valueType (PrimValue bv) = Prim $ primValueType bv
valueType (TupValue vs) = Tuple (map valueType vs)
valueType (ArrayValue _ (Prim et)) =
Array $ PrimArray et (Rank 1) Nonunique NoInfo
valueType (ArrayValue _ (Tuple ts)) =
addNames $ Array $ TupleArray (map (`typeToTupleArrayElem` Nonunique) ts) (Rank 1) Nonunique
valueType (ArrayValue _ (Array (PrimArray et shape _ _))) =
Array $ PrimArray et (Rank $ 1 + shapeRank shape) Nonunique NoInfo
valueType (ArrayValue _ (Array (TupleArray et shape _))) =
addNames $ Array $ TupleArray et (Rank $ 1 + shapeRank shape) Nonunique
-- | The type of an Futhark term. The aliasing will refer to itself, if
-- the term is a non-tuple-typed variable.
typeOf :: (Ord vn, Hashable vn) => ExpBase Info vn -> CompTypeBase vn
typeOf (Literal val _) = fromStruct $ valueType val
typeOf (TupLit es _) = Tuple $ map typeOf es
typeOf (ArrayLit es (Info t) _) =
arrayType 1 t $ mconcat $ map (uniqueness . typeOf) es
typeOf (Empty (TypeDecl _ (Info t)) _) =
arrayType 1 (fromStruct t) Unique
typeOf (BinOp _ _ _ (Info t) _) = t
typeOf (UnOp Not _ _) = Prim Bool
typeOf (UnOp Negate e _) = typeOf e
typeOf (UnOp Complement e _) = typeOf e
typeOf (UnOp Abs e _) = typeOf e
typeOf (UnOp Signum e _) = typeOf e
typeOf (UnOp (ToFloat t) _ _) = Prim $ FloatType t
typeOf (UnOp (ToSigned t) _ _) = Prim $ Signed t
typeOf (UnOp (ToUnsigned t) _ _) = Prim $ Unsigned t
typeOf (If _ _ _ (Info t) _) = t
typeOf (Var ident) =
case unInfo $ identType ident of
Tuple ets -> Tuple ets
t -> t `addAliases` HS.insert (identName ident)
typeOf (Apply _ _ (Info t) _) = t
typeOf (LetPat _ _ body _) = typeOf body
typeOf (LetWith _ _ _ _ body _) = typeOf body
typeOf (Index ident idx _) =
stripArray (length idx) (typeOf ident)
typeOf (TupleIndex _ _ (Info t) _) = t
typeOf (Iota _ _) = Array $ PrimArray (Signed Int32) (Rank 1) Unique mempty
typeOf Size{} = Prim $ Signed Int32
typeOf (Replicate _ e _) = arrayType 1 (typeOf e) Unique
typeOf (Reshape shape e _) =
Rank (length shape) `setArrayShape` typeOf e
typeOf (Rearrange _ e _) = typeOf e
typeOf (Transpose e _) = typeOf e
typeOf (Rotate _ _ e _) = typeOf e
typeOf (Map f _ _) = arrayType 1 et Unique `setAliases` HS.empty
where et = lambdaReturnType f
typeOf (Reduce _ fun _ _ _) =
lambdaReturnType fun `setAliases` mempty
typeOf (Zip es _) =
Array $ TupleArray (zipWith typeToTupleArrayElem es_ts es_us) (Rank 1) u
where es_ts = map (rowType . unInfo . snd) es
es_us = map (uniqueness . unInfo . snd) es
u = mconcat es_us
typeOf (Unzip _ ts _) =
Tuple $ map unInfo ts
typeOf (Unsafe e _) =
typeOf e
typeOf (Scan fun _ _ _) =
arrayType 1 et Unique
where et = lambdaReturnType fun `setAliases` mempty
typeOf (Filter _ arr _) =
typeOf arr
typeOf (Partition funs arr _) =
Tuple $ replicate (length funs + 1) $ typeOf arr
typeOf (Stream form lam _ _) =
case form of
MapLike{} -> lambdaReturnType lam
`setAliases` HS.empty
`setUniqueness` Unique
RedLike{} -> lambdaReturnType lam
`setAliases` HS.empty
`setUniqueness` Unique
Sequential{} -> lambdaReturnType lam
`setAliases` HS.empty
`setUniqueness` Unique
typeOf (Concat _ x _ _) =
typeOf x `setUniqueness` Unique `setAliases` HS.empty
typeOf (Split _ splitexps e _) =
Tuple $ replicate (1 + length splitexps) (typeOf e)
typeOf (Copy e _) = typeOf e `setUniqueness` Unique `setAliases` HS.empty
typeOf (DoLoop _ _ _ _ body _) = typeOf body
typeOf (Write _i _v as _) = case as of
[a] -> typeOf a `setAliases` HS.empty
_ -> Tuple $ map (\a -> typeOf a `setAliases` HS.empty) as
-- | The result of applying the arguments of the given types to a
-- function with the given return type, consuming its parameters with
-- the given diets.
returnType :: (Ord vn, Hashable vn) =>
TypeBase shape NoInfo vn
-> [Diet]
-> [CompTypeBase vn]
-> TypeBase shape Names vn
returnType (Array at) ds args =
Array $ arrayReturnType at ds args
returnType (Tuple ets) ds args =
Tuple $ map (\et -> returnType et ds args) ets
returnType (Prim t) _ _ = Prim t
arrayReturnType :: (Eq vn, Hashable vn) =>
ArrayTypeBase shape NoInfo vn
-> [Diet]
-> [CompTypeBase vn]
-> ArrayTypeBase shape Names vn
arrayReturnType (PrimArray bt sz Nonunique NoInfo) ds args =
PrimArray bt sz Nonunique als
where als = mconcat $ map aliases $ zipWith maskAliases args ds
arrayReturnType (TupleArray et sz Nonunique) ds args =
TupleArray (map (\t -> tupleArrayElemReturnType t ds args) et) sz Nonunique
arrayReturnType (PrimArray et sz Unique NoInfo) _ _ =
PrimArray et sz Unique mempty
arrayReturnType (TupleArray et sz Unique) _ _ =
TupleArray (map (`addTupleArrayElemAliases` const mempty) et) sz Unique
tupleArrayElemReturnType :: (Eq vn, Hashable vn) =>
TupleArrayElemTypeBase shape NoInfo vn
-> [Diet]
-> [CompTypeBase vn]
-> TupleArrayElemTypeBase shape Names vn
tupleArrayElemReturnType (PrimArrayElem bt NoInfo u) ds args =
PrimArrayElem bt als u
where als = mconcat $ map aliases $ zipWith maskAliases args ds
tupleArrayElemReturnType (ArrayArrayElem at) ds args =
ArrayArrayElem $ arrayReturnType at ds args
tupleArrayElemReturnType (TupleArrayElem ts) ds args =
TupleArrayElem $ map (\t -> tupleArrayElemReturnType t ds args) ts
-- | The specified return type of a lambda.
lambdaReturnType :: Ord vn =>
LambdaBase Info vn -> TypeBase Rank NoInfo vn
lambdaReturnType (AnonymFun _ _ t _) = removeShapeAnnotations $ unInfo $ expandedType t
lambdaReturnType (CurryFun _ _ (Info t) _) = toStruct t
lambdaReturnType (UnOpFun _ _ (Info t) _) = toStruct t
lambdaReturnType (BinOpFun _ _ _ (Info t) _) = toStruct t
lambdaReturnType (CurryBinOpLeft _ _ _ (Info t) _) = toStruct t
lambdaReturnType (CurryBinOpRight _ _ _ (Info t) _) = toStruct t
-- | Is the given binary operator commutative?
commutative :: BinOp -> Bool
commutative = flip elem [Plus, Pow, Times, Band, Xor, Bor, LogAnd, LogOr, Equal]
-- | Turn an identifier into a parameter.
toParam :: Ord vn =>
IdentBase Info vn
-> ParamBase Info vn
toParam (Ident name (Info t) loc) =
Param name (TypeDecl t' $ Info t'') loc
where
t' = contractTypeBase t
t'' = vacuousShapeAnnotations $ toStruct t
-- | Turn a parameter into an identifier.
fromParam :: Ord vn =>
ParamBase Info vn
-> IdentBase Info vn
fromParam (Param name (TypeDecl _ (Info t)) loc) =
Ident name (Info $ removeShapeAnnotations $ fromStruct t) loc
paramType :: ParamBase Info vn
-> StructTypeBase vn
paramType = unInfo . expandedType . paramTypeDecl
paramDeclaredType :: ParamBase f vn
-> UserType vn
paramDeclaredType = declaredType . paramTypeDecl
-- | As 'patNames', but returns a the set of names (which means that
-- information about ordering is destroyed - make sure this is what
-- you want).
patNameSet :: (Eq vn, Hashable vn) => PatternBase ty vn -> HS.HashSet vn
patNameSet = HS.map identName . patIdentSet
-- | The list of idents bound in the given pattern. The order of
-- idents is given by the pre-order traversal of the pattern.
patIdents :: (Eq vn, Hashable vn) => PatternBase ty vn -> [IdentBase ty vn]
patIdents (Id ident) = [ident]
patIdents (TuplePattern pats _) = mconcat $ map patIdents pats
patIdents (Wildcard _ _) = []
-- | As 'patIdents', but returns a the set of names (which means that
-- information about ordering is destroyed - make sure this is what
-- you want).
patIdentSet :: (Eq vn, Hashable vn) => PatternBase ty vn -> HS.HashSet (IdentBase ty vn)
patIdentSet = HS.fromList . patIdents
-- | A map of all built-in functions and their types.
builtInFunctions :: HM.HashMap Name (PrimType,[PrimType])
builtInFunctions = HM.fromList $ map namify
[("sqrt32", (FloatType Float32, [FloatType Float32]))
,("log32", (FloatType Float32, [FloatType Float32]))
,("exp32", (FloatType Float32, [FloatType Float32]))
,("cos32", (FloatType Float32, [FloatType Float32]))
,("sin32", (FloatType Float32, [FloatType Float32]))
,("atan2_32", (FloatType Float32, [FloatType Float32, FloatType Float32]))
,("isinf32", (Bool, [FloatType Float32]))
,("isnan32", (Bool, [FloatType Float32]))
,("sqrt64", (FloatType Float64, [FloatType Float64]))
,("log64", (FloatType Float64, [FloatType Float64]))
,("exp64", (FloatType Float64, [FloatType Float64]))
,("cos64", (FloatType Float64, [FloatType Float64]))
,("sin64", (FloatType Float64, [FloatType Float64]))
,("atan2_64", (FloatType Float64, [FloatType Float64, FloatType Float64]))
,("isinf64", (Bool, [FloatType Float64]))
,("isnan64", (Bool, [FloatType Float64]))
]
where namify (k,v) = (nameFromString k, v)
contractTypeBase :: (ArrayShape (shape vn), Ord vn) =>
TypeBase shape als vn
-> UserType vn
contractTypeBase (Prim p) = UserPrim p noLoc
contractTypeBase arrtp@(Array tps) =
let grow t d = UserArray t d noLoc
roottype = contractArrayTypeBase tps
array = foldl grow roottype $ replicate (arrayRank arrtp) AnyDim
in case uniqueness arrtp of
Unique -> UserUnique array noLoc
Nonunique -> array
contractTypeBase (Tuple types) =
UserTuple (map contractTypeBase types) noLoc
contractArrayTypeBase :: ArrayTypeBase shape als vn
-> UserType vn
contractArrayTypeBase (PrimArray p _ _ _) =
UserPrim p noLoc
contractArrayTypeBase (TupleArray tps _ _) =
UserTuple (map contractTupleArrayElemTypeBase tps) noLoc
contractTupleArrayElemTypeBase :: TupleArrayElemTypeBase shape als vn
-> UserType vn
contractTupleArrayElemTypeBase (PrimArrayElem p _ _) =
UserPrim p noLoc
contractTupleArrayElemTypeBase (ArrayArrayElem arrtpbase) =
contractArrayTypeBase arrtpbase
contractTupleArrayElemTypeBase (TupleArrayElem tps) =
UserTuple (map contractTupleArrayElemTypeBase tps) noLoc
funsFromProg :: ProgBase f vn -> [FunDefBase f vn]
funsFromProg prog = mapMaybe isFun $ progDecs prog
typesFromProg :: ProgBase f vn -> [TypeDefBase f vn]
typesFromProg prog = mapMaybe isType $ progDecs prog
sigsFromProg :: ProgBase f vn -> [SigDefBase f vn]
sigsFromProg prog = mapMaybe isSig $ progDecs prog
modsFromProg :: ProgBase f vn -> [ModDefBase f vn]
modsFromProg prog = mapMaybe isMod $ progDecs prog
isFun :: DecBase f vn -> Maybe (FunDefBase f vn)
isFun (FunOrTypeDec (FunDec a)) = Just a
isFun _ = Nothing
isType :: DecBase f vn -> Maybe (TypeDefBase f vn)
isType (FunOrTypeDec (TypeDec t)) = Just t
isType _ = Nothing
isFunOrType :: DecBase f vn -> Maybe (FunOrTypeDecBase f vn)
isFunOrType (FunOrTypeDec ft) = Just ft
isFunOrType _ = Nothing
isSig :: DecBase f vn -> Maybe (SigDefBase f vn)
isSig (SigDec sig) = Just sig
isSig _ = Nothing
isMod :: DecBase f vn -> Maybe (ModDefBase f vn)
isMod (ModDec modd) = Just modd
isMod _ = Nothing
nameToQualName :: Name -> QualName
nameToQualName n = ([], n)
decLoc :: DecBase f vn -> SrcLoc
decLoc (FunOrTypeDec (FunDec (FunDef _ _ _ _ _ loc))) = loc
decLoc (FunOrTypeDec (TypeDec (TypeDef _ _ loc))) = loc
decLoc (SigDec (SigDef _ _ loc)) = loc
decLoc (ModDec (ModDef _ _ loc)) = loc
-- | A type with no aliasing information but shape annotations.
type UncheckedType = TypeBase ShapeDecl NoInfo Name
type UncheckedUserType = UserType Name
-- | An array type with no aliasing information.
type UncheckedArrayType = ArrayTypeBase ShapeDecl NoInfo Name
-- | A type declaration with no expanded type.
type UncheckedUserTypeDecl = TypeDeclBase NoInfo Name
-- | A type declaration with no expanded type.
type UncheckedTypeDecl = TypeDeclBase NoInfo Name
-- | An identifier with no type annotations.
type UncheckedIdent = IdentBase NoInfo Name
-- | An expression with no type annotations.
type UncheckedExp = ExpBase NoInfo Name
-- | A lambda with no type annotations.
type UncheckedLambda = LambdaBase NoInfo Name
-- | A pattern with no type annotations.
type UncheckedPattern = PatternBase NoInfo Name
-- | A function declaration with no type annotations.
type UncheckedFunDef = FunDefBase NoInfo Name
-- | An Futhark program with no type annotations.
type UncheckedProg = ProgBase NoInfo Name
-- | An Futhark program with no type annotations, but with headers.
type UncheckedProgWithHeaders = ProgBaseWithHeaders NoInfo Name
| mrakgr/futhark | src/Language/Futhark/Attributes.hs | bsd-3-clause | 33,874 | 0 | 13 | 7,890 | 10,091 | 5,114 | 4,977 | 647 | 6 |
module Generator where
import Control.Applicative
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.ByteString.Char8 (cons, pack, unpack)
import Data.List as L (drop, length, take)
import Data.Time (UTCTime)
import Data.Time.Clock.POSIX (POSIXTime,
posixSecondsToUTCTime)
import Pipes as P
import Pipes.Prelude as P
import System.Random
import Parser
import Types
data Parameters = P
{ pOrdered :: Double
, pNewline :: Double
, pMutate :: Double
} deriving (Show, Eq, Ord)
-- Clean input. 100% successful parse.
perfectInput :: MonadIO m => Producer ByteString m ()
perfectInput = paramStream p
where p = P { pOrdered = 0
, pNewline = 0
, pMutate = 0
}
-- Stream of semi-garbled input. ~95% successful parse.
realisticInput :: MonadIO m => Producer ByteString m ()
realisticInput = paramStream p
where p = P { pOrdered = 0.05
, pNewline = 0.05
, pMutate = 0.005
}
-- Stream of very garbled input. ~10% successful parse.
nightmareInput :: MonadIO m => Producer ByteString m ()
nightmareInput = paramStream p
where p = P { pOrdered = 0.5
, pNewline = 0.5
, pMutate = 0.5
}
paramStream :: MonadIO m => Parameters -> Producer ByteString m ()
paramStream p = do
g <- liftIO getStdGen
let (g1, g') = split g
(g2, g'') = split g'
(g3, g''') = split g''
(g4, g'''') = split g'''
(g5, _) = split g''''
cleanMeasure g1 >-> orderedEntries g2
>-> reorderedEntries (pOrdered p) g3
>-> prettyPipe False
>-> newlineChaos (pNewline p) g4
>-> mutateEntry (pMutate p) g5
-- XXX kinda arbitrary bound on our random integers
maxInt :: Integer
maxInt = 4294967296
-- XXX arbitrary
medInt :: Integer
medInt = 10000
-- XXX also arbitrary
smallInt :: Integer
smallInt = 720
-- First we need a stream of "Correct" log entries
cleanMeasure :: Monad m => StdGen -> Producer Measurement m ()
cleanMeasure g = do
let rand0 x g = randomR (0, x) g :: (Integer, StdGen)
(x, g1) = rand0 medInt g
(y, g2) = rand0 medInt g1
(t, g3) = rand0 smallInt g2
(s, g4) = rand0 3 g3
(c1, g5) = randomR ('A', 'Z') g4
(c2, g6) = randomR ('A', 'Z') g5
station = if | s == 0 -> AUS
| s == 1 -> FRA
| s == 2 -> USA
| otherwise -> Other [c1, c2]
yield (mkMeasure station (fromIntegral x, fromIntegral y) (fromIntegral t))
cleanMeasure g6
-- ... Then we need to give them timestamps
orderedEntries :: Monad m => StdGen -> Pipe Measurement LogEntry m ()
orderedEntries g =
-- Initial time is bounded between 1970 and 2106.
-- Each step is between 0 and smallInt seconds.
let (initialTime, g2) = randomR (0, maxInt) g :: (Integer, StdGen)
in go (fromIntegral initialTime) g2
where go :: Monad m => POSIXTime -> StdGen -> Pipe Measurement LogEntry m ()
go last h = do
m <- await
let (diff, h1) = randomR (0, smallInt) h :: (Integer, StdGen)
newTime = last + fromIntegral diff
yield (LogEntry { leTime = posixSecondsToUTCTime newTime
, leMeasure = m
})
go newTime h1
-- ... Optionally, we reorder them (hang onto an item and reinsert it randomly)
reorderedEntries :: Monad m => Double -> StdGen -> Pipe LogEntry LogEntry m ()
reorderedEntries r g = go Nothing g
where go stashed g = do
next <- await
let (f, g1) = randomR (0, 1) g :: (Double, StdGen)
if f >= r
then yield next >> go stashed g1
else maybe (return ()) yield stashed >> go (Just next) g1
-- ... Give them between 0 and 3 newlines as separation...
newlineChaos :: Monad m => Double -> StdGen -> Pipe ByteString ByteString m ()
newlineChaos r g = do
next <- await
let (f, g1) = randomR (0, 1) g :: (Double, StdGen)
(c, g2) = randomR (0, 3) g1 :: (Int, StdGen)
if f >= r
then yield $ next `B.append` "\n"
else yield $ next `B.append` pack (L.take c (repeat '\n'))
newlineChaos r g2
-- ... Mutate. remove some characters, add other characters.
mutateEntry :: Monad m => Double -> StdGen -> Pipe ByteString ByteString m ()
mutateEntry r g = do
next <- await
let (f, g1) = randomR (0, 1) g :: (Double, StdGen)
(c, g2) = randomR (0, 5) g1 :: (Int, StdGen)
mutated = mutate (B.length next) c g2 next
if f >= r then yield next else yield mutated
mutateEntry r (fst (split g2))
where mutate :: Int -> Int -> StdGen -> ByteString -> ByteString
mutate _ 0 _ s = s
mutate len n h s =
let (f, h1) = randomR (0, r) h :: (Double, StdGen)
(pos, h2) = randomR (0, len) h1 :: (Int, StdGen)
(act, h3) = randomR (0, 2) h2 :: (Int, StdGen)
(ins, h4) = randomR (' ', '~') h3 :: (Char, StdGen)
(a, b) = B.splitAt pos s
(len', warped) =
if | act == 0 -> -- Delete
(len - 1, a `B.append` B.drop 1 b)
| act == 1 -> -- Replace
(len, a `B.append` (ins `cons` B.drop 1 b))
| act == 2 -> -- Insert
(len + 1, a `B.append` (ins `cons` b))
| otherwise -> error "randomR invariant broke!"
in if f >= r
then mutate len (n - 1) h4 s
else mutate len' (n - 1) h4 warped
| thumphries/weather | src/Generator.hs | bsd-3-clause | 5,904 | 0 | 18 | 2,097 | 1,969 | 1,054 | 915 | -1 | -1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.Http
( handler
) where
--------------------------------------------------------------------------------
import Control.Exception (SomeException (..), handle)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.HTTP.Conduit as H
import qualified Network.HTTP.Types as H
--------------------------------------------------------------------------------
import NumberSix.Bang
import NumberSix.Irc
import NumberSix.Util
import NumberSix.Util.Http (httpPrefix)
--------------------------------------------------------------------------------
http :: Text -> IO Text
http uri = do
req <- H.parseUrl uri'
let req' = req {H.redirectCount = 0, H.checkStatus = \_ _ _ -> Nothing}
mgr <- H.newManager H.tlsManagerSettings
rsp <- H.httpLbs req' mgr
let status = H.responseStatus rsp
location
| H.statusCode status < 300 = ""
| H.statusCode status >= 400 = ""
| otherwise =
case lookup "Location" (H.responseHeaders rsp) of
Nothing -> ""
Just loc -> " (Location: " <> loc <> ")"
return $ T.pack (show $ H.responseVersion rsp) <> " " <>
T.pack (show $ H.statusCode status) <> " " <>
T.decodeUtf8 (H.statusMessage status) <> T.decodeUtf8 location
where
uri' = T.unpack $ httpPrefix uri
--------------------------------------------------------------------------------
-- | Catch possible network errors
wrapped :: Text -> IO Text
wrapped uri = handle
(\(SomeException e) -> return $ T.pack $ show e)
(http uri)
--------------------------------------------------------------------------------
handler :: UninitializedHandler
handler = makeBangHandler "Http" ["!http"] $ liftIO . wrapped
| jaspervdj/number-six | src/NumberSix/Handlers/Http.hs | bsd-3-clause | 2,112 | 0 | 17 | 502 | 495 | 264 | 231 | 38 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Utils.Scotty.MustacheRender(
module Text.Mustache
,hastache
) where
import Data.Text as T
import Data.Maybe
import Text.Mustache
hastache :: (ToMustache k) => [FilePath] ->
FilePath -> k -> IO (Maybe T.Text)
hastache searchSpace tpl ctx = do
eitherTemplate <- automaticCompile searchSpace tpl
case eitherTemplate of
Left err -> return $ Nothing
Right compiledTemplate ->
return $ Just $ substitute compiledTemplate ctx
| DavidAlphaFox/sblog | src/Utils/Scotty/MustacheRender.hs | bsd-3-clause | 486 | 0 | 12 | 88 | 142 | 75 | 67 | 15 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
-- NOTICE: Some of these tests are /unsafe/, and will fail intermittently, since
-- they rely on ordering constraints which the Cloud Haskell runtime does not
-- guarantee.
module Main where
import Control.Concurrent.MVar
( MVar
, newMVar
, putMVar
, takeMVar
)
import qualified Control.Exception as Ex
import Control.Exception (throwIO)
import Control.Distributed.Process hiding (call, monitor)
import Control.Distributed.Process.Closure
import Control.Distributed.Process.Node
import Control.Distributed.Process.Platform hiding (__remoteTable, send, sendChan)
-- import Control.Distributed.Process.Platform as Alt (monitor)
import Control.Distributed.Process.Platform.Test
import Control.Distributed.Process.Platform.Time
import Control.Distributed.Process.Platform.Timer
import Control.Distributed.Process.Platform.Supervisor hiding (start, shutdown)
import qualified Control.Distributed.Process.Platform.Supervisor as Supervisor
import Control.Distributed.Process.Platform.ManagedProcess.Client (shutdown)
import Control.Distributed.Process.Serializable()
import Control.Distributed.Static (staticLabel)
import Control.Monad (void, forM_, forM)
import Control.Rematch
( equalTo
, is
, isNot
, isNothing
, isJust
)
import Data.ByteString.Lazy (empty)
import Data.Maybe (catMaybes)
#if !MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import Test.HUnit (Assertion, assertFailure)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import TestUtils hiding (waitForExit)
import qualified Network.Transport as NT
-- test utilities
expectedExitReason :: ProcessId -> String
expectedExitReason sup = "killed-by=" ++ (show sup) ++
",reason=TerminatedBySupervisor"
defaultWorker :: ChildStart -> ChildSpec
defaultWorker clj =
ChildSpec
{
childKey = ""
, childType = Worker
, childRestart = Temporary
, childStop = TerminateImmediately
, childStart = clj
, childRegName = Nothing
}
tempWorker :: ChildStart -> ChildSpec
tempWorker clj =
(defaultWorker clj)
{
childKey = "temp-worker"
, childRestart = Temporary
}
transientWorker :: ChildStart -> ChildSpec
transientWorker clj =
(defaultWorker clj)
{
childKey = "transient-worker"
, childRestart = Transient
}
intrinsicWorker :: ChildStart -> ChildSpec
intrinsicWorker clj =
(defaultWorker clj)
{
childKey = "intrinsic-worker"
, childRestart = Intrinsic
}
permChild :: ChildStart -> ChildSpec
permChild clj =
(defaultWorker clj)
{
childKey = "perm-child"
, childRestart = Permanent
}
ensureProcessIsAlive :: ProcessId -> Process ()
ensureProcessIsAlive pid = do
result <- isProcessAlive pid
expectThat result $ is True
runInTestContext :: LocalNode
-> MVar ()
-> RestartStrategy
-> [ChildSpec]
-> (ProcessId -> Process ())
-> Assertion
runInTestContext node lock rs cs proc = do
Ex.bracket (takeMVar lock) (putMVar lock) $ \() -> runProcess node $ do
sup <- Supervisor.start rs ParallelShutdown cs
(proc sup) `finally` (exit sup ExitShutdown)
verifyChildWasRestarted :: ChildKey -> ProcessId -> ProcessId -> Process ()
verifyChildWasRestarted key pid sup = do
void $ waitForExit pid
cSpec <- lookupChild sup key
-- TODO: handle (ChildRestarting _) too!
case cSpec of
Just (ref, _) -> do Just pid' <- resolve ref
expectThat pid' $ isNot $ equalTo pid
_ -> do
liftIO $ assertFailure $ "unexpected child ref: " ++ (show (key, cSpec))
verifyChildWasNotRestarted :: ChildKey -> ProcessId -> ProcessId -> Process ()
verifyChildWasNotRestarted key pid sup = do
void $ waitForExit pid
cSpec <- lookupChild sup key
case cSpec of
Just (ChildStopped, _) -> return ()
_ -> liftIO $ assertFailure $ "unexpected child ref: " ++ (show (key, cSpec))
verifyTempChildWasRemoved :: ProcessId -> ProcessId -> Process ()
verifyTempChildWasRemoved pid sup = do
void $ waitForExit pid
sleepFor 500 Millis
cSpec <- lookupChild sup "temp-worker"
expectThat cSpec isNothing
waitForExit :: ProcessId -> Process DiedReason
waitForExit pid = do
monitor pid >>= waitForDown
waitForDown :: Maybe MonitorRef -> Process DiedReason
waitForDown Nothing = error "invalid mref"
waitForDown (Just ref) =
receiveWait [ matchIf (\(ProcessMonitorNotification ref' _ _) -> ref == ref')
(\(ProcessMonitorNotification _ _ dr) -> return dr) ]
drainChildren :: [Child] -> ProcessId -> Process ()
drainChildren children expected = do
-- Receive all pids then verify they arrived in the correct order.
-- Any out-of-order messages (such as ProcessMonitorNotification) will
-- violate the invariant asserted below, and fail the test case
pids <- forM children $ \_ -> expect :: Process ProcessId
let first' = head pids
Just exp' <- resolve expected
-- however... we do allow for the scheduler and accept `head $ tail pids` in
-- lieu of the correct result, since when there are multiple senders we have
-- no causal guarantees
if first' /= exp'
then let second' = head $ tail pids in second' `shouldBe` equalTo exp'
else first' `shouldBe` equalTo exp'
exitIgnore :: Process ()
exitIgnore = liftIO $ throwIO ChildInitIgnore
noOp :: Process ()
noOp = return ()
blockIndefinitely :: Process ()
blockIndefinitely = runTestProcess noOp
notifyMe :: ProcessId -> Process ()
notifyMe me = getSelfPid >>= send me >> obedient
sleepy :: Process ()
sleepy = (sleepFor 5 Minutes)
`catchExit` (\_ (_ :: ExitReason) -> return ()) >> sleepy
obedient :: Process ()
obedient = (sleepFor 5 Minutes)
{- supervisor inserts handlers that act like we wrote:
`catchExit` (\_ (r :: ExitReason) -> do
case r of
ExitShutdown -> return ()
_ -> die r)
-}
$(remotable [ 'exitIgnore
, 'noOp
, 'blockIndefinitely
, 'sleepy
, 'obedient
, 'notifyMe])
-- test cases start here...
normalStartStop :: ProcessId -> Process ()
normalStartStop sup = do
ensureProcessIsAlive sup
void $ monitor sup
shutdown sup
sup `shouldExitWith` DiedNormal
sequentialShutdown :: TestResult (Maybe ()) -> Process ()
sequentialShutdown result = do
(sp, rp) <- newChan
(sg, rg) <- newChan
core' <- toChildStart $ runCore sp
app' <- toChildStart $ runApp sg
let core = (permChild core') { childRegName = Just (LocalName "core")
, childStop = TerminateTimeout (Delay $ within 2 Seconds)
, childKey = "child-1"
}
let app = (permChild app') { childRegName = Just (LocalName "app")
, childStop = TerminateTimeout (Delay $ within 2 Seconds)
, childKey = "child-2"
}
sup <- Supervisor.start restartRight
(SequentialShutdown RightToLeft)
[core, app]
() <- receiveChan rg
exit sup ExitShutdown
res <- receiveChanTimeout (asTimeout $ seconds 2) rp
-- whereis "core" >>= liftIO . putStrLn . ("core :" ++) . show
-- whereis "app" >>= liftIO . putStrLn . ("app :" ++) . show
sleepFor 1 Seconds
stash result res
where
runCore :: SendPort () -> Process ()
runCore sp = (expect >>= say) `catchExit` (\_ ExitShutdown -> sendChan sp ())
runApp :: SendPort () -> Process ()
runApp sg = do
Just pid <- whereis "core"
link pid -- if the real "core" exits first, we go too
sendChan sg ()
expect >>= say
configuredTemporaryChildExitsWithIgnore ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
configuredTemporaryChildExitsWithIgnore cs withSupervisor =
let spec = tempWorker cs in do
withSupervisor restartOne [spec] verifyExit
where
verifyExit :: ProcessId -> Process ()
verifyExit sup = do
-- sa <- isProcessAlive sup
child <- lookupChild sup "temp-worker"
case child of
Nothing -> return () -- the child exited and was removed ok
Just (ref, _) -> do
Just pid <- resolve ref
verifyTempChildWasRemoved pid sup
configuredNonTemporaryChildExitsWithIgnore ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
configuredNonTemporaryChildExitsWithIgnore cs withSupervisor =
let spec = transientWorker cs in do
withSupervisor restartOne [spec] $ verifyExit spec
where
verifyExit :: ChildSpec -> ProcessId -> Process ()
verifyExit spec sup = do
sleep $ milliSeconds 100 -- make sure our super has seen the EXIT signal
child <- lookupChild sup (childKey spec)
case child of
Nothing -> liftIO $ assertFailure $ "lost non-temp spec!"
Just (ref, spec') -> do
rRef <- resolve ref
maybe (return DiedNormal) waitForExit rRef
cSpec <- lookupChild sup (childKey spec')
case cSpec of
Just (ChildStartIgnored, _) -> return ()
_ -> do
liftIO $ assertFailure $ "unexpected lookup: " ++ (show cSpec)
startTemporaryChildExitsWithIgnore :: ChildStart -> ProcessId -> Process ()
startTemporaryChildExitsWithIgnore cs sup =
-- if a temporary child exits with "ignore" then we must
-- have deleted its specification from the supervisor
let spec = tempWorker cs in do
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
verifyTempChildWasRemoved pid sup
startNonTemporaryChildExitsWithIgnore :: ChildStart -> ProcessId -> Process ()
startNonTemporaryChildExitsWithIgnore cs sup =
let spec = transientWorker cs in do
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
void $ waitForExit pid
sleep $ milliSeconds 250
cSpec <- lookupChild sup (childKey spec)
case cSpec of
Just (ChildStartIgnored, _) -> return ()
_ -> do
liftIO $ assertFailure $ "unexpected lookup: " ++ (show cSpec)
addChildWithoutRestart :: ChildStart -> ProcessId -> Process ()
addChildWithoutRestart cs sup =
let spec = transientWorker cs in do
response <- addChild sup spec
response `shouldBe` equalTo (ChildAdded ChildStopped)
addChildThenStart :: ChildStart -> ProcessId -> Process ()
addChildThenStart cs sup =
let spec = transientWorker cs in do
(ChildAdded _) <- addChild sup spec
response <- startChild sup (childKey spec)
case response of
ChildStartOk (ChildRunning pid) -> do
alive <- isProcessAlive pid
alive `shouldBe` equalTo True
_ -> do
liftIO $ putStrLn (show response)
die "Ooops"
startUnknownChild :: ChildStart -> ProcessId -> Process ()
startUnknownChild cs sup = do
response <- startChild sup (childKey (transientWorker cs))
response `shouldBe` equalTo ChildStartUnknownId
setupChild :: ChildStart -> ProcessId -> Process (ChildRef, ChildSpec)
setupChild cs sup = do
let spec = transientWorker cs
response <- addChild sup spec
response `shouldBe` equalTo (ChildAdded ChildStopped)
Just child <- lookupChild sup "transient-worker"
return child
addDuplicateChild :: ChildStart -> ProcessId -> Process ()
addDuplicateChild cs sup = do
(ref, spec) <- setupChild cs sup
dup <- addChild sup spec
dup `shouldBe` equalTo (ChildFailedToStart $ StartFailureDuplicateChild ref)
startDuplicateChild :: ChildStart -> ProcessId -> Process ()
startDuplicateChild cs sup = do
(ref, spec) <- setupChild cs sup
dup <- startNewChild sup spec
dup `shouldBe` equalTo (ChildFailedToStart $ StartFailureDuplicateChild ref)
startBadClosure :: ChildStart -> ProcessId -> Process ()
startBadClosure cs sup = do
let spec = tempWorker cs
child <- startNewChild sup spec
child `shouldBe` equalTo
(ChildFailedToStart $ StartFailureBadClosure
"user error (Could not resolve closure: Invalid static label 'non-existing')")
-- configuredBadClosure withSupervisor = do
-- let spec = permChild (closure (staticLabel "non-existing") empty)
-- -- we make sure we don't hit the supervisor's limits
-- let strategy = RestartOne $ limit (maxRestarts 500000000) (milliSeconds 1)
-- withSupervisor strategy [spec] $ \sup -> do
-- -- ref <- monitor sup
-- children <- (listChildren sup)
-- let specs = map fst children
-- expectThat specs $ equalTo []
deleteExistingChild :: ChildStart -> ProcessId -> Process ()
deleteExistingChild cs sup = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
result <- deleteChild sup "transient-worker"
result `shouldBe` equalTo (ChildNotStopped ref)
deleteStoppedTempChild :: ChildStart -> ProcessId -> Process ()
deleteStoppedTempChild cs sup = do
let spec = tempWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
-- child needs to be stopped
waitForExit pid
result <- deleteChild sup (childKey spec)
result `shouldBe` equalTo ChildNotFound
deleteStoppedChild :: ChildStart -> ProcessId -> Process ()
deleteStoppedChild cs sup = do
let spec = transientWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
-- child needs to be stopped
waitForExit pid
result <- deleteChild sup (childKey spec)
result `shouldBe` equalTo ChildDeleted
permanentChildrenAlwaysRestart :: ChildStart -> ProcessId -> Process ()
permanentChildrenAlwaysRestart cs sup = do
let spec = permChild cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid -- a normal stop should *still* trigger a restart
verifyChildWasRestarted (childKey spec) pid sup
temporaryChildrenNeverRestart :: ChildStart -> ProcessId -> Process ()
temporaryChildrenNeverRestart cs sup = do
let spec = tempWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
kill pid "bye bye"
verifyTempChildWasRemoved pid sup
transientChildrenNormalExit :: ChildStart -> ProcessId -> Process ()
transientChildrenNormalExit cs sup = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
verifyChildWasNotRestarted (childKey spec) pid sup
transientChildrenAbnormalExit :: ChildStart -> ProcessId -> Process ()
transientChildrenAbnormalExit cs sup = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
kill pid "bye bye"
verifyChildWasRestarted (childKey spec) pid sup
transientChildrenExitShutdown :: ChildStart -> ProcessId -> Process ()
transientChildrenExitShutdown cs sup = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
exit pid ExitShutdown
verifyChildWasNotRestarted (childKey spec) pid sup
intrinsicChildrenAbnormalExit :: ChildStart -> ProcessId -> Process ()
intrinsicChildrenAbnormalExit cs sup = do
let spec = intrinsicWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
kill pid "bye bye"
verifyChildWasRestarted (childKey spec) pid sup
intrinsicChildrenNormalExit :: ChildStart -> ProcessId -> Process ()
intrinsicChildrenNormalExit cs sup = do
let spec = intrinsicWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
reason <- waitForExit sup
expectThat reason $ equalTo DiedNormal
explicitRestartRunningChild :: ChildStart -> ProcessId -> Process ()
explicitRestartRunningChild cs sup = do
let spec = tempWorker cs
ChildAdded ref <- startNewChild sup spec
result <- restartChild sup (childKey spec)
expectThat result $ equalTo $ ChildRestartFailed (StartFailureAlreadyRunning ref)
explicitRestartUnknownChild :: ProcessId -> Process ()
explicitRestartUnknownChild sup = do
result <- restartChild sup "unknown-id"
expectThat result $ equalTo ChildRestartUnknownId
explicitRestartRestartingChild :: ChildStart -> ProcessId -> Process ()
explicitRestartRestartingChild cs sup = do
let spec = permChild cs
ChildAdded _ <- startNewChild sup spec
-- TODO: we've seen a few explosions here (presumably of the supervisor?)
-- expecially when running with +RTS -N1 - it's possible that there's a bug
-- tucked away that we haven't cracked just yet
restarted <- (restartChild sup (childKey spec))
`catchExit` (\_ (r :: ExitReason) -> (liftIO $ putStrLn (show r)) >>
die r)
-- this is highly timing dependent, so we have to allow for both
-- possible outcomes - on a dual core machine, the first clause
-- will match approx. 1 / 200 times when running with +RTS -N
case restarted of
ChildRestartFailed (StartFailureAlreadyRunning (ChildRestarting _)) -> return ()
ChildRestartFailed (StartFailureAlreadyRunning (ChildRunning _)) -> return ()
other -> liftIO $ assertFailure $ "unexpected result: " ++ (show other)
explicitRestartStoppedChild :: ChildStart -> ProcessId -> Process ()
explicitRestartStoppedChild cs sup = do
let spec = transientWorker cs
let key = childKey spec
ChildAdded ref <- startNewChild sup spec
void $ terminateChild sup key
restarted <- restartChild sup key
sleepFor 500 Millis
Just (ref', _) <- lookupChild sup key
expectThat ref $ isNot $ equalTo ref'
case restarted of
ChildRestartOk (ChildRunning _) -> return ()
_ -> liftIO $ assertFailure $ "unexpected termination: " ++ (show restarted)
terminateChildImmediately :: ChildStart -> ProcessId -> Process ()
terminateChildImmediately cs sup = do
let spec = tempWorker cs
ChildAdded ref <- startNewChild sup spec
-- Just pid <- resolve ref
mRef <- monitor ref
void $ terminateChild sup (childKey spec)
reason <- waitForDown mRef
expectThat reason $ equalTo $ DiedException (expectedExitReason sup)
terminatingChildExceedsDelay :: ProcessId -> Process ()
terminatingChildExceedsDelay sup = do
let spec = (tempWorker (RunClosure $(mkStaticClosure 'sleepy)))
{ childStop = TerminateTimeout (Delay $ within 1 Seconds) }
ChildAdded ref <- startNewChild sup spec
-- Just pid <- resolve ref
mRef <- monitor ref
void $ terminateChild sup (childKey spec)
reason <- waitForDown mRef
expectThat reason $ equalTo $ DiedException (expectedExitReason sup)
terminatingChildObeysDelay :: ProcessId -> Process ()
terminatingChildObeysDelay sup = do
let spec = (tempWorker (RunClosure $(mkStaticClosure 'obedient)))
{ childStop = TerminateTimeout (Delay $ within 1 Seconds) }
ChildAdded child <- startNewChild sup spec
Just pid <- resolve child
testProcessGo pid
void $ monitor pid
void $ terminateChild sup (childKey spec)
child `shouldExitWith` DiedNormal
restartAfterThreeAttempts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
restartAfterThreeAttempts cs withSupervisor = do
let spec = permChild cs
let strategy = RestartOne $ limit (maxRestarts 500) (seconds 2)
withSupervisor strategy [spec] $ \sup -> do
mapM_ (\_ -> do
[(childRef, _)] <- listChildren sup
Just pid <- resolve childRef
ref <- monitor pid
testProcessStop pid
void $ waitForDown ref) [1..3 :: Int]
[(_, _)] <- listChildren sup
return ()
{-
delayedRestartAfterThreeAttempts ::
(RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
delayedRestartAfterThreeAttempts withSupervisor = do
let restartPolicy = DelayedRestart Permanent (within 1 Seconds)
let spec = (permChild $(mkStaticClosure 'blockIndefinitely))
{ childRestart = restartPolicy }
let strategy = RestartOne $ limit (maxRestarts 2) (seconds 1)
withSupervisor strategy [spec] $ \sup -> do
mapM_ (\_ -> do
[(childRef, _)] <- listChildren sup
Just pid <- resolve childRef
ref <- monitor pid
testProcessStop pid
void $ waitForDown ref) [1..3 :: Int]
Just (ref, _) <- lookupChild sup $ childKey spec
case ref of
ChildRestarting _ -> return ()
_ -> liftIO $ assertFailure $ "Unexpected ChildRef: " ++ (show ref)
sleep $ seconds 2
[(ref', _)] <- listChildren sup
liftIO $ putStrLn $ "it is: " ++ (show ref')
Just pid <- resolve ref'
mRef <- monitor pid
testProcessStop pid
void $ waitForDown mRef
-}
permanentChildExceedsRestartsIntensity ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
permanentChildExceedsRestartsIntensity cs withSupervisor = do
let spec = permChild cs -- child that exits immediately
let strategy = RestartOne $ limit (maxRestarts 50) (seconds 2)
withSupervisor strategy [spec] $ \sup -> do
ref <- monitor sup
-- if the supervisor dies whilst the call is in-flight,
-- *this* process will exit, therefore we handle that exit reason
void $ ((startNewChild sup spec >> return ())
`catchExit` (\_ (_ :: ExitReason) -> return ()))
reason <- waitForDown ref
expectThat reason $ equalTo $
DiedException $ "exit-from=" ++ (show sup) ++
",reason=ReachedMaxRestartIntensity"
terminateChildIgnoresSiblings ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
terminateChildIgnoresSiblings cs withSupervisor = do
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..3 :: Int]]
withSupervisor restartAll specs $ \sup -> do
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
mRef <- monitor ref
terminateChild sup toStop
waitForDown mRef
children <- listChildren sup
forM_ (tail $ map fst children) $ \cRef -> do
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve cRef
restartAllWithLeftToRightSeqRestarts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
restartAllWithLeftToRightSeqRestarts cs withSupervisor = do
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..100 :: Int]]
withSupervisor restartAll specs $ \sup -> do
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
children <- listChildren sup
Just pid <- resolve ref
kill pid "goodbye"
forM_ (map fst children) $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
forM_ (map snd children) $ \cSpec -> do
Just (ref', _) <- lookupChild sup (childKey cSpec)
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref'
restartLeftWithLeftToRightSeqRestarts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
restartLeftWithLeftToRightSeqRestarts cs withSupervisor = do
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..500 :: Int]]
withSupervisor restartLeft specs $ \sup -> do
let (toRestart, _notToRestart) = splitAt 100 specs
let toStop = childKey $ last toRestart
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
children <- listChildren sup
let (children', survivors) = splitAt 100 children
kill pid "goodbye"
forM_ (map fst children') $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
forM_ (map snd children') $ \cSpec -> do
Just (ref', _) <- lookupChild sup (childKey cSpec)
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref'
resolved <- forM (map fst survivors) resolve
let possibleBadRestarts = catMaybes resolved
r <- receiveTimeout (after 1 Seconds) [
match (\(ProcessMonitorNotification _ pid' _) -> do
case (elem pid' possibleBadRestarts) of
True -> liftIO $ assertFailure $ "unexpected exit from " ++ show pid'
False -> return ())
]
expectThat r isNothing
restartRightWithLeftToRightSeqRestarts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
restartRightWithLeftToRightSeqRestarts cs withSupervisor = do
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..50 :: Int]]
withSupervisor restartRight specs $ \sup -> do
let (_notToRestart, toRestart) = splitAt 40 specs
let toStop = childKey $ head toRestart
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
children <- listChildren sup
let (survivors, children') = splitAt 40 children
kill pid "goodbye"
forM_ (map fst children') $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
forM_ (map snd children') $ \cSpec -> do
Just (ref', _) <- lookupChild sup (childKey cSpec)
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref'
resolved <- forM (map fst survivors) resolve
let possibleBadRestarts = catMaybes resolved
r <- receiveTimeout (after 1 Seconds) [
match (\(ProcessMonitorNotification _ pid' _) -> do
case (elem pid' possibleBadRestarts) of
True -> liftIO $ assertFailure $ "unexpected exit from " ++ show pid'
False -> return ())
]
expectThat r isNothing
restartAllWithLeftToRightRestarts :: ProcessId -> Process ()
restartAllWithLeftToRightRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..100 :: Int]]
-- add the specs one by one
forM_ specs $ \s -> void $ startNewChild sup s
-- assert that we saw the startup sequence working...
children <- listChildren sup
drainAllChildren children
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
kill pid "goodbye"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst children) $ \cRef -> do
Just mRef <- monitor cRef
receiveWait [
matchIf (\(ProcessMonitorNotification ref' _ _) -> ref' == mRef)
(\_ -> return ())
-- we should NOT see *any* process signalling that it has started
-- whilst waiting for all the children to be terminated
, match (\(pid' :: ProcessId) -> do
liftIO $ assertFailure $ "unexpected signal from " ++ (show pid'))
]
-- Now assert that all the children were restarted in the same order.
-- THIS is the bit that is technically unsafe, though it's also unlikely
-- to change, since the architecture of the node controller is pivotal to CH
children' <- listChildren sup
drainAllChildren children'
let [c1, c2] = [map fst cs | cs <- [children, children']]
forM_ (zip c1 c2) $ \(p1, p2) -> expectThat p1 $ isNot $ equalTo p2
where
drainAllChildren children = do
-- Receive all pids then verify they arrived in the correct order.
-- Any out-of-order messages (such as ProcessMonitorNotification) will
-- violate the invariant asserted below, and fail the test case
pids <- forM children $ \_ -> expect :: Process ProcessId
forM_ pids ensureProcessIsAlive
restartAllWithRightToLeftSeqRestarts :: ProcessId -> Process ()
restartAllWithRightToLeftSeqRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..100 :: Int]]
-- add the specs one by one
forM_ specs $ \s -> do
ChildAdded ref <- startNewChild sup s
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref
-- assert that we saw the startup sequence working...
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
children <- listChildren sup
drainChildren children pid
kill pid "fooboo"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst children) $ \cRef -> do
Just mRef <- monitor cRef
receiveWait [
matchIf (\(ProcessMonitorNotification ref' _ _) -> ref' == mRef)
(\_ -> return ())
]
-- ensure that both ends of the pids we've seen are in the right order...
-- in this case, we expect the last child to be the first notification,
-- since they were started in right to left order
children' <- listChildren sup
let (ref', _) = last children'
Just pid' <- resolve ref'
drainChildren children' pid'
expectLeftToRightRestarts :: ProcessId -> Process ()
expectLeftToRightRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..100 :: Int]]
-- add the specs one by one
forM_ specs $ \s -> do
ChildAdded c <- startNewChild sup s
Just p <- resolve c
p' <- expect
p' `shouldBe` equalTo p
-- assert that we saw the startup sequence working...
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
children <- listChildren sup
-- wait for all the exit signals and ensure they arrive in RightToLeft order
refs <- forM children $ \(ch, _) -> monitor ch >>= \r -> return (ch, r)
kill pid "fooboo"
initRes <- receiveTimeout
(asTimeout $ seconds 1)
[ matchIf
(\(ProcessMonitorNotification r _ _) -> (Just r) == (snd $ head refs))
(\sig@(ProcessMonitorNotification _ _ _) -> return sig) ]
expectThat initRes $ isJust
forM_ (reverse (filter ((/= ref) .fst ) refs)) $ \(_, Just mRef) -> do
(ProcessMonitorNotification ref' _ _) <- expect
if ref' == mRef then (return ()) else (die "unexpected monitor signal")
-- in this case, we expect the first child to be the first notification,
-- since they were started in left to right order
children' <- listChildren sup
let (ref', _) = head children'
Just pid' <- resolve ref'
drainChildren children' pid'
expectRightToLeftRestarts :: ProcessId -> Process ()
expectRightToLeftRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..10 :: Int]]
-- add the specs one by one
forM_ specs $ \s -> do
ChildAdded ref <- startNewChild sup s
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref
-- assert that we saw the startup sequence working...
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
children <- listChildren sup
drainChildren children pid
kill pid "fooboo"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst children) $ \cRef -> do
Just mRef <- monitor cRef
receiveWait [
matchIf (\(ProcessMonitorNotification ref' _ _) -> ref' == mRef)
(\_ -> return ())
-- we should NOT see *any* process signalling that it has started
-- whilst waiting for all the children to be terminated
, match (\(pid' :: ProcessId) -> do
liftIO $ assertFailure $ "unexpected signal from " ++ (show pid'))
]
-- ensure that both ends of the pids we've seen are in the right order...
-- in this case, we expect the last child to be the first notification,
-- since they were started in right to left order
children' <- listChildren sup
let (ref', _) = last children'
Just pid' <- resolve ref'
drainChildren children' pid'
restartLeftWhenLeftmostChildDies :: ChildStart -> ProcessId -> Process ()
restartLeftWhenLeftmostChildDies cs sup = do
let spec = permChild cs
(ChildAdded ref) <- startNewChild sup spec
(ChildAdded ref2) <- startNewChild sup $ spec { childKey = "child2" }
Just pid <- resolve ref
Just pid2 <- resolve ref2
testProcessStop pid -- a normal stop should *still* trigger a restart
verifyChildWasRestarted (childKey spec) pid sup
Just (ref3, _) <- lookupChild sup "child2"
Just pid2' <- resolve ref3
pid2 `shouldBe` equalTo pid2'
restartWithoutTempChildren :: ChildStart -> ProcessId -> Process ()
restartWithoutTempChildren cs sup = do
(ChildAdded refTrans) <- startNewChild sup $ transientWorker cs
(ChildAdded _) <- startNewChild sup $ tempWorker cs
(ChildAdded refPerm) <- startNewChild sup $ permChild cs
Just pid2 <- resolve refTrans
Just pid3 <- resolve refPerm
kill pid2 "foobar"
void $ waitForExit pid2 -- this wait reduces the likelihood of a race in the test
Nothing <- lookupChild sup "temp-worker"
verifyChildWasRestarted "transient-worker" pid2 sup
verifyChildWasRestarted "perm-child" pid3 sup
restartRightWhenRightmostChildDies :: ChildStart -> ProcessId -> Process ()
restartRightWhenRightmostChildDies cs sup = do
let spec = permChild cs
(ChildAdded ref2) <- startNewChild sup $ spec { childKey = "child2" }
(ChildAdded ref) <- startNewChild sup $ spec { childKey = "child1" }
[ch1, ch2] <- listChildren sup
(fst ch1) `shouldBe` equalTo ref2
(fst ch2) `shouldBe` equalTo ref
Just pid <- resolve ref
Just pid2 <- resolve ref2
-- ref (and therefore pid) is 'rightmost' now
testProcessStop pid -- a normal stop should *still* trigger a restart
verifyChildWasRestarted "child1" pid sup
Just (ref3, _) <- lookupChild sup "child2"
Just pid2' <- resolve ref3
pid2 `shouldBe` equalTo pid2'
restartLeftWithLeftToRightRestarts :: ProcessId -> Process ()
restartLeftWithLeftToRightRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..20 :: Int]]
forM_ specs $ \s -> void $ startNewChild sup s
-- assert that we saw the startup sequence working...
let toStart = childKey $ head specs
Just (ref, _) <- lookupChild sup toStart
Just pid <- resolve ref
children <- listChildren sup
drainChildren children pid
let (toRestart, _) = splitAt 7 specs
let toStop = childKey $ last toRestart
Just (ref', _) <- lookupChild sup toStop
Just stopPid <- resolve ref'
kill stopPid "goodbye"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst (fst $ splitAt 7 children)) $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
children' <- listChildren sup
let (restarted, notRestarted) = splitAt 7 children'
-- another (technically) unsafe check
let firstRestart = childKey $ snd $ head restarted
Just (rRef, _) <- lookupChild sup firstRestart
Just fPid <- resolve rRef
drainChildren restarted fPid
let [c1, c2] = [map fst cs | cs <- [(snd $ splitAt 7 children), notRestarted]]
forM_ (zip c1 c2) $ \(p1, p2) -> p1 `shouldBe` equalTo p2
restartRightWithLeftToRightRestarts :: ProcessId -> Process ()
restartRightWithLeftToRightRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..20 :: Int]]
forM_ specs $ \s -> void $ startNewChild sup s
-- assert that we saw the startup sequence working...
let toStart = childKey $ head specs
Just (ref, _) <- lookupChild sup toStart
Just pid <- resolve ref
children <- listChildren sup
drainChildren children pid
let (_, toRestart) = splitAt 3 specs
let toStop = childKey $ head toRestart
Just (ref', _) <- lookupChild sup toStop
Just stopPid <- resolve ref'
kill stopPid "goodbye"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst (snd $ splitAt 3 children)) $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
children' <- listChildren sup
let (notRestarted, restarted) = splitAt 3 children'
-- another (technically) unsafe check
let firstRestart = childKey $ snd $ head restarted
Just (rRef, _) <- lookupChild sup firstRestart
Just fPid <- resolve rRef
drainChildren restarted fPid
let [c1, c2] = [map fst cs | cs <- [(fst $ splitAt 3 children), notRestarted]]
forM_ (zip c1 c2) $ \(p1, p2) -> p1 `shouldBe` equalTo p2
restartRightWithRightToLeftRestarts :: ProcessId -> Process ()
restartRightWithRightToLeftRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..20 :: Int]]
forM_ specs $ \s -> void $ startNewChild sup s
-- assert that we saw the startup sequence working...
let toStart = childKey $ head specs
Just (ref, _) <- lookupChild sup toStart
Just pid <- resolve ref
children <- listChildren sup
drainChildren children pid
let (_, toRestart) = splitAt 3 specs
let toStop = childKey $ head toRestart
Just (ref', _) <- lookupChild sup toStop
Just stopPid <- resolve ref'
kill stopPid "goodbye"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst (snd $ splitAt 3 children)) $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
children' <- listChildren sup
let (notRestarted, restarted) = splitAt 3 children'
-- another (technically) unsafe check
let firstRestart = childKey $ snd $ last restarted
Just (rRef, _) <- lookupChild sup firstRestart
Just fPid <- resolve rRef
drainChildren restarted fPid
let [c1, c2] = [map fst cs | cs <- [(fst $ splitAt 3 children), notRestarted]]
forM_ (zip c1 c2) $ \(p1, p2) -> p1 `shouldBe` equalTo p2
restartLeftWithRightToLeftRestarts :: ProcessId -> Process ()
restartLeftWithRightToLeftRestarts sup = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..20 :: Int]]
forM_ specs $ \s -> void $ startNewChild sup s
-- assert that we saw the startup sequence working...
let toStart = childKey $ head specs
Just (ref, _) <- lookupChild sup toStart
Just pid <- resolve ref
children <- listChildren sup
drainChildren children pid
let (toRestart, _) = splitAt 7 specs
let (restarts, toSurvive) = splitAt 7 children
let toStop = childKey $ last toRestart
Just (ref', _) <- lookupChild sup toStop
Just stopPid <- resolve ref'
kill stopPid "goodbye"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst restarts) $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
children' <- listChildren sup
let (restarted, notRestarted) = splitAt 7 children'
-- another (technically) unsafe check
let firstRestart = childKey $ snd $ last restarted
Just (rRef, _) <- lookupChild sup firstRestart
Just fPid <- resolve rRef
drainChildren (reverse restarted) fPid
let [c1, c2] = [map fst cs | cs <- [toSurvive, notRestarted]]
forM_ (zip c1 c2) $ \(p1, p2) -> p1 `shouldBe` equalTo p2
localChildStartLinking :: TestResult Bool -> Process ()
localChildStartLinking result = do
s1 <- toChildStart procExpect
s2 <- toChildStart procLinkExpect
pid <- Supervisor.start restartOne ParallelShutdown [ (tempWorker s1) { childKey = "w1" }
, (tempWorker s2) { childKey = "w2" } ]
[(r1, _), (r2, _)] <- listChildren pid
Just p1 <- resolve r1
Just p2 <- resolve r2
monitor p1
monitor p2
shutdownAndWait pid
waitForChildShutdown [p1, p2]
stash result True
where
procExpect :: Process ()
procExpect = expect >>= return
procLinkExpect :: SupervisorPid -> Process ProcessId
procLinkExpect p = spawnLocal $ link p >> procExpect
waitForChildShutdown [] = return ()
waitForChildShutdown pids = do
p <- receiveWait [
match (\(ProcessMonitorNotification _ p _) -> return p)
]
waitForChildShutdown $ filter (/= p) pids
-- remote table definition and main
myRemoteTable :: RemoteTable
myRemoteTable = Main.__remoteTable initRemoteTable
withClosure :: (ChildStart -> ProcessId -> Process ())
-> (Closure (Process ()))
-> ProcessId -> Process ()
withClosure fn clj supervisor = do
cs <- toChildStart clj
fn cs supervisor
withChan :: (ChildStart -> ProcessId -> Process ())
-> Process ()
-> ProcessId
-> Process ()
withChan fn proc supervisor = do
cs <- toChildStart proc
fn cs supervisor
tests :: NT.Transport -> IO [Test]
tests transport = do
putStrLn $ concat [ "NOTICE: Branch Tests (Relying on Non-Guaranteed Message Order) "
, "Can Fail Intermittently"]
localNode <- newLocalNode transport myRemoteTable
singleTestLock <- newMVar ()
let withSupervisor = runInTestContext localNode singleTestLock
return
[ testGroup "Supervisor Processes"
[
testGroup "Starting And Adding Children"
[
testCase "Normal (Managed Process) Supervisor Start Stop"
(withSupervisor restartOne [] normalStartStop)
, testGroup "Specified By Closure"
[
testCase "Add Child Without Starting"
(withSupervisor restartOne []
(withClosure addChildWithoutRestart
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Start Previously Added Child"
(withSupervisor restartOne []
(withClosure addChildThenStart
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Start Unknown Child"
(withSupervisor restartOne []
(withClosure startUnknownChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Add Duplicate Child"
(withSupervisor restartOne []
(withClosure addDuplicateChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Start Duplicate Child"
(withSupervisor restartOne []
(withClosure startDuplicateChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Started Temporary Child Exits With Ignore"
(withSupervisor restartOne []
(withClosure startTemporaryChildExitsWithIgnore
$(mkStaticClosure 'exitIgnore)))
, testCase "Configured Temporary Child Exits With Ignore"
(configuredTemporaryChildExitsWithIgnore
(RunClosure $(mkStaticClosure 'exitIgnore)) withSupervisor)
, testCase "Start Bad Closure"
(withSupervisor restartOne []
(withClosure startBadClosure
(closure (staticLabel "non-existing") empty)))
, testCase "Configured Bad Closure"
(configuredTemporaryChildExitsWithIgnore
(RunClosure $(mkStaticClosure 'exitIgnore)) withSupervisor)
, testCase "Started Non-Temporary Child Exits With Ignore"
(withSupervisor restartOne [] $
(withClosure startNonTemporaryChildExitsWithIgnore
$(mkStaticClosure 'exitIgnore)))
, testCase "Configured Non-Temporary Child Exits With Ignore"
(configuredNonTemporaryChildExitsWithIgnore
(RunClosure $(mkStaticClosure 'exitIgnore)) withSupervisor)
]
, testGroup "Specified By Delegate/Restarter"
[
testCase "Add Child Without Starting (Chan)"
(withSupervisor restartOne []
(withChan addChildWithoutRestart blockIndefinitely))
, testCase "Start Previously Added Child"
(withSupervisor restartOne []
(withChan addChildThenStart blockIndefinitely))
, testCase "Start Unknown Child"
(withSupervisor restartOne []
(withChan startUnknownChild blockIndefinitely))
, testCase "Add Duplicate Child (Chan)"
(withSupervisor restartOne []
(withChan addDuplicateChild blockIndefinitely))
, testCase "Start Duplicate Child (Chan)"
(withSupervisor restartOne []
(withChan startDuplicateChild blockIndefinitely))
, testCase "Started Temporary Child Exits With Ignore (Chan)"
(withSupervisor restartOne []
(withChan startTemporaryChildExitsWithIgnore exitIgnore))
, testCase "Started Non-Temporary Child Exits With Ignore (Chan)"
(withSupervisor restartOne [] $
(withChan startNonTemporaryChildExitsWithIgnore exitIgnore))
]
]
, testGroup "Stopping And Deleting Children"
[
testCase "Delete Existing Child Fails"
(withSupervisor restartOne []
(withClosure deleteExistingChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Delete Stopped Temporary Child (Doesn't Exist)"
(withSupervisor restartOne []
(withClosure deleteStoppedTempChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Delete Stopped Child Succeeds"
(withSupervisor restartOne []
(withClosure deleteStoppedChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Restart Minus Dropped (Temp) Child"
(withSupervisor restartAll []
(withClosure restartWithoutTempChildren
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Sequential Shutdown Ordering"
(delayedAssertion
"expected the shutdown order to hold"
localNode (Just ()) sequentialShutdown)
]
, testGroup "Stopping and Restarting Children"
[
testCase "Permanent Children Always Restart (Closure)"
(withSupervisor restartOne []
(withClosure permanentChildrenAlwaysRestart
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Permanent Children Always Restart (Chan)"
(withSupervisor restartOne []
(withChan permanentChildrenAlwaysRestart blockIndefinitely))
, testCase "Temporary Children Never Restart (Closure)"
(withSupervisor restartOne []
(withClosure temporaryChildrenNeverRestart
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Temporary Children Never Restart (Chan)"
(withSupervisor restartOne []
(withChan temporaryChildrenNeverRestart blockIndefinitely))
, testCase "Transient Children Do Not Restart When Exiting Normally (Closure)"
(withSupervisor restartOne []
(withClosure transientChildrenNormalExit
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Transient Children Do Not Restart When Exiting Normally (Chan)"
(withSupervisor restartOne []
(withChan transientChildrenNormalExit blockIndefinitely))
, testCase "Transient Children Do Restart When Exiting Abnormally (Closure)"
(withSupervisor restartOne []
(withClosure transientChildrenAbnormalExit
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Transient Children Do Restart When Exiting Abnormally (Chan)"
(withSupervisor restartOne []
(withChan transientChildrenAbnormalExit blockIndefinitely))
, testCase "ExitShutdown Is Considered Normal (Closure)"
(withSupervisor restartOne []
(withClosure transientChildrenExitShutdown
$(mkStaticClosure 'blockIndefinitely)))
, testCase "ExitShutdown Is Considered Normal (Chan)"
(withSupervisor restartOne []
(withChan transientChildrenExitShutdown blockIndefinitely))
, testCase "Intrinsic Children Do Restart When Exiting Abnormally (Closure)"
(withSupervisor restartOne []
(withClosure intrinsicChildrenAbnormalExit
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Intrinsic Children Do Restart When Exiting Abnormally (Chan)"
(withSupervisor restartOne []
(withChan intrinsicChildrenAbnormalExit blockIndefinitely))
, testCase (concat [ "Intrinsic Children Cause Supervisor Exits "
, "When Exiting Normally (Closure)"])
(withSupervisor restartOne []
(withClosure intrinsicChildrenNormalExit
$(mkStaticClosure 'blockIndefinitely)))
, testCase (concat [ "Intrinsic Children Cause Supervisor Exits "
, "When Exiting Normally (Chan)"])
(withSupervisor restartOne []
(withChan intrinsicChildrenNormalExit blockIndefinitely))
, testCase "Explicit Restart Of Running Child Fails (Closure)"
(withSupervisor restartOne []
(withClosure explicitRestartRunningChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Explicit Restart Of Running Child Fails (Chan)"
(withSupervisor restartOne []
(withChan explicitRestartRunningChild blockIndefinitely))
, testCase "Explicit Restart Of Unknown Child Fails"
(withSupervisor restartOne [] explicitRestartUnknownChild)
, testCase "Explicit Restart Whilst Child Restarting Fails (Closure)"
(withSupervisor
(RestartOne (limit (maxRestarts 500000000) (milliSeconds 1))) []
(withClosure explicitRestartRestartingChild $(mkStaticClosure 'noOp)))
, testCase "Explicit Restart Whilst Child Restarting Fails (Chan)"
(withSupervisor
(RestartOne (limit (maxRestarts 500000000) (milliSeconds 1))) []
(withChan explicitRestartRestartingChild noOp))
, testCase "Explicit Restart Stopped Child (Closure)"
(withSupervisor restartOne []
(withClosure explicitRestartStoppedChild
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Explicit Restart Stopped Child (Chan)"
(withSupervisor restartOne []
(withChan explicitRestartStoppedChild blockIndefinitely))
, testCase "Immediate Child Termination (Brutal Kill) (Closure)"
(withSupervisor restartOne []
(withClosure terminateChildImmediately
$(mkStaticClosure 'blockIndefinitely)))
, testCase "Immediate Child Termination (Brutal Kill) (Chan)"
(withSupervisor restartOne []
(withChan terminateChildImmediately blockIndefinitely))
-- TODO: Chan tests
, testCase "Child Termination Exceeds Timeout/Delay (Becomes Brutal Kill)"
(withSupervisor restartOne [] terminatingChildExceedsDelay)
, testCase "Child Termination Within Timeout/Delay"
(withSupervisor restartOne [] terminatingChildObeysDelay)
]
-- TODO: test for init failures (expecting $ ChildInitFailed r)
, testGroup "Branch Restarts"
[
testGroup "Restart All"
[
testCase "Terminate Child Ignores Siblings"
(terminateChildIgnoresSiblings
(RunClosure $(mkStaticClosure 'blockIndefinitely))
withSupervisor)
, testCase "Restart All, Left To Right (Sequential) Restarts"
(restartAllWithLeftToRightSeqRestarts
(RunClosure $(mkStaticClosure 'blockIndefinitely))
withSupervisor)
, testCase "Restart All, Right To Left (Sequential) Restarts"
(withSupervisor
(RestartAll defaultLimits (RestartEach RightToLeft)) []
restartAllWithRightToLeftSeqRestarts)
, testCase "Restart All, Left To Right Stop, Left To Right Start"
(withSupervisor
(RestartAll defaultLimits (RestartInOrder LeftToRight)) []
restartAllWithLeftToRightRestarts)
, testCase "Restart All, Right To Left Stop, Right To Left Start"
(withSupervisor
(RestartAll defaultLimits (RestartInOrder RightToLeft)) []
expectRightToLeftRestarts)
, testCase "Restart All, Left To Right Stop, Reverse Start"
(withSupervisor
(RestartAll defaultLimits (RestartRevOrder LeftToRight)) []
expectRightToLeftRestarts)
, testCase "Restart All, Right To Left Stop, Reverse Start"
(withSupervisor
(RestartAll defaultLimits (RestartRevOrder RightToLeft)) []
expectLeftToRightRestarts)
],
testGroup "Restart Left"
[
testCase "Restart Left, Left To Right (Sequential) Restarts"
(restartLeftWithLeftToRightSeqRestarts
(RunClosure $(mkStaticClosure 'blockIndefinitely))
withSupervisor)
, testCase "Restart Left, Leftmost Child Dies"
(withSupervisor restartLeft [] $
restartLeftWhenLeftmostChildDies
(RunClosure $(mkStaticClosure 'blockIndefinitely)))
, testCase "Restart Left, Left To Right Stop, Left To Right Start"
(withSupervisor
(RestartLeft defaultLimits (RestartInOrder LeftToRight)) []
restartLeftWithLeftToRightRestarts)
, testCase "Restart Left, Right To Left Stop, Right To Left Start"
(withSupervisor
(RestartLeft defaultLimits (RestartInOrder RightToLeft)) []
restartLeftWithRightToLeftRestarts)
, testCase "Restart Left, Left To Right Stop, Reverse Start"
(withSupervisor
(RestartLeft defaultLimits (RestartRevOrder LeftToRight)) []
restartLeftWithRightToLeftRestarts)
, testCase "Restart Left, Right To Left Stop, Reverse Start"
(withSupervisor
(RestartLeft defaultLimits (RestartRevOrder RightToLeft)) []
restartLeftWithLeftToRightRestarts)
],
testGroup "Restart Right"
[
testCase "Restart Right, Left To Right (Sequential) Restarts"
(restartRightWithLeftToRightSeqRestarts
(RunClosure $(mkStaticClosure 'blockIndefinitely))
withSupervisor)
, testCase "Restart Right, Rightmost Child Dies"
(withSupervisor restartRight [] $
restartRightWhenRightmostChildDies
(RunClosure $(mkStaticClosure 'blockIndefinitely)))
, testCase "Restart Right, Left To Right Stop, Left To Right Start"
(withSupervisor
(RestartRight defaultLimits (RestartInOrder LeftToRight)) []
restartRightWithLeftToRightRestarts)
, testCase "Restart Right, Right To Left Stop, Right To Left Start"
(withSupervisor
(RestartRight defaultLimits (RestartInOrder RightToLeft)) []
restartRightWithRightToLeftRestarts)
, testCase "Restart Right, Left To Right Stop, Reverse Start"
(withSupervisor
(RestartRight defaultLimits (RestartRevOrder LeftToRight)) []
restartRightWithRightToLeftRestarts)
, testCase "Restart Right, Right To Left Stop, Reverse Start"
(withSupervisor
(RestartRight defaultLimits (RestartRevOrder RightToLeft)) []
restartRightWithLeftToRightRestarts)
]
]
, testGroup "Restart Intensity"
[
testCase "Three Attempts Before Successful Restart"
(restartAfterThreeAttempts
(RunClosure $(mkStaticClosure 'blockIndefinitely)) withSupervisor)
, testCase "Permanent Child Exceeds Restart Limits"
(permanentChildExceedsRestartsIntensity
(RunClosure $(mkStaticClosure 'noOp)) withSupervisor)
-- , testCase "Permanent Child Delayed Restart"
-- (delayedRestartAfterThreeAttempts withSupervisor)
]
, testGroup "ToChildStart Link Setup"
[
testCase "Both Local Process Instances Link Appropriately"
(delayedAssertion
"expected the server to return the task outcome"
localNode True localChildStartLinking)
]
]
]
main :: IO ()
main = testMain $ tests
| haskell-distributed/distributed-process-platform | tests/TestSupervisor.hs | bsd-3-clause | 57,885 | 1 | 24 | 15,416 | 14,605 | 7,065 | 7,540 | 1,111 | 3 |
module Settings where
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Database.Persist.Sqlite (SqliteConf)
import Yesod.Default.Config
import Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Data.Default
import Control.Applicative
import Settings.Development
import Text.Hamlet
type PersistConf = SqliteConf
-- Static setting below. Changing these requires a recompile
-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticDir :: FilePath
staticDir = "static"
-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Foundation.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Foundation.hs
staticRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/static|]
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
{ wfsHamletSettings = defaultHamletSettings
{ hamletNewlines = AlwaysNewlines
}
}
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if development then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
data Extra = Extra
{ extraCopyright :: Text
, extraAnalytics :: Maybe Text -- ^ Google Analytics
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "copyright"
<*> o .:? "analytics"
-- | /search?$(queryParamName)=search-query
searchQueryParamName :: Text
searchQueryParamName = "q"
| pxqr/bitidx | Settings.hs | bsd-3-clause | 2,458 | 0 | 9 | 431 | 287 | 180 | 107 | -1 | -1 |
module Main where
import Test.Hspec
import System.Process
import qualified Spec
main :: IO ()
main = do
_ <- system "cd ../../example/todo && make"
hspec Spec.spec
| nrolland/react-flux | test/spec/Main.hs | bsd-3-clause | 174 | 0 | 8 | 36 | 51 | 27 | 24 | 8 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs, FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
import System.GitControl
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as BS
import System.Posix.Env.ByteString
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
share [mkPersist sqlSettings, mkMigrate "migrateAll"]
[persistLowerCase|
Repo
path BS.ByteString
UniqueRepo path
deriving Show
User
ident BS.ByteString
UniqueUser ident
deriving Show
Mode
prjId RepoId Eq
personId UserId Eq
priv String
UniqueMode prjId personId
deriving Show
|]
getPath :: IO T.Text
getPath = maybe (error "no HOME defined")
(T.pack.BS.unpack.(flip BS.append "/gitcontrol.db"))
`fmap` getEnv "HOME"
instance GitControl (T.Text) where
isAuthorized _ _ _ None = return False
isAuthorized path (Username rName) (RepositoryPath rName) aMode = do
runSqlite path $ do
uEntity <- getBy $ UniqueUser uName
rEntity <- getBy $ UniqueRepo rName
case (uEntity, rEntity) of
(Just (Entity uK _), Just (Entity rK _)) -> do
mEntity <- getBy $ UniqueMode rK uK
case mEntity of
Nothing -> return False
Just (Entity _ (Mode _ _ access)) -> return $ aMode <= (read access :: AccessMode)
_ -> return False
doCreateDatabase = getPath >>= \h ->
runSqlite h $ runMigration migrateAll
main :: IO ()
main =
(maybe (error "no HOME defined") (flip BS.append "/")) `fmap` getEnv "HOME"
>>= \h -> defaultMain h (return $ T.pack $ BS.unpack $ BS.append h "gitcontrol.db")
| NicolasDP/gitcontrol-sqlite | src/GitControlSQLite.hs | bsd-3-clause | 1,969 | 2 | 23 | 530 | 476 | 249 | 227 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] tr
[@ISO639-2@] tur
[@ISO639-3@] tur
[@Native name@] Türkçe
[@English name@] Turkish
-}
module Text.Numeral.Language.TUR
( -- * Language entry
entry
-- * Conversions
, cardinal
-- * Structure
, struct
-- * Bounds
, bounds
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Data.Bool ( otherwise )
import "base" Data.Function ( ($), const, fix )
import "base" Data.Maybe ( Maybe(Just) )
import "base" Prelude ( Integral, (-), divMod, negate )
import "base-unicode-symbols" Data.Eq.Unicode ( (≡) )
import "base-unicode-symbols" Data.Function.Unicode ( (∘) )
import "base-unicode-symbols" Data.List.Unicode ( (∉) )
import "base-unicode-symbols" Prelude.Unicode ( ℤ, (⋅) )
import qualified "containers" Data.Map as M ( fromList, lookup )
import "this" Text.Numeral
import qualified "this" Text.Numeral.BigNum as BN ( rule, scaleRepr, forms )
import qualified "this" Text.Numeral.Exp as E
import "this" Text.Numeral.Misc ( dec )
import "this" Text.Numeral.Entry
import "text" Data.Text ( Text )
--------------------------------------------------------------------------------
-- TUR
--------------------------------------------------------------------------------
entry ∷ Entry
entry = emptyEntry
{ entIso639_1 = Just "tr"
, entIso639_2 = ["tur"]
, entIso639_3 = Just "tur"
, entNativeNames = ["Türkçe"]
, entEnglishName = Just "Turkish"
, entCardinal = Just Conversion
{ toNumeral = cardinal
, toStructure = struct
}
}
cardinal ∷ (Integral α, E.Scale α) ⇒ i → α → Maybe Text
cardinal inf = cardinalRepr inf ∘ struct
struct ∷ (Integral α, E.Scale α, E.Unknown β, E.Lit β, E.Add β, E.Mul β, E.Scale β)
⇒ α → β
struct = checkPos $ fix $ rule `combine` shortScale1 R L BN.rule
rule ∷ (Integral α, E.Unknown β, E.Lit β, E.Add β, E.Mul β) ⇒ Rule α β
rule = findRule ( 0, lit )
[ ( 11, addToTens )
, ( 100, step 100 10 R L)
, (1000, step 1000 1000 R L)
]
(dec 6 - 1)
addToTens ∷ (Integral α, E.Lit β, E.Add β) ⇒ Rule α β
addToTens f n = let (m, r) = n `divMod` 10
tens = m ⋅ 10
in if r ≡ 0
then lit f tens
else f tens `E.add` f r
bounds ∷ (Integral α) ⇒ (α, α)
bounds = let x = dec 60000 - 1 in (negate x, x)
cardinalRepr ∷ i → Exp i → Maybe Text
cardinalRepr = render defaultRepr
{ reprValue = \_ n → M.lookup n syms
, reprScale = scaleRepr
, reprAdd = Just (⊞)
, reprMul = Just $ \_ _ _ → " "
}
where
(Lit 10 ⊞ _) (CtxMul {}) = ""
(_ ⊞ _) _ = " "
syms =
M.fromList
[ (0, const "sıfır")
, (1, const "bir")
, (2, const "iki")
, (3, const "üç")
, (4, const "dört")
, (5, const "beş")
, (6, const "altı")
, (7, const "yedi")
, (8, const "sekiz")
, (9, const "dokuz")
, (10, const "on")
, (20, const "yirmi")
, (30, const "otuz")
, (40, const "kırk")
, (50, const "elli")
, (60, const "altmış")
, (70, const "yetmiş")
, (80, const "seksen")
, (90, const "doksan")
, (100, const "yüz")
, (1000, const "bin")
]
scaleRepr ∷ i → ℤ → ℤ → Exp i → Ctx (Exp i) → Maybe Text
scaleRepr = BN.scaleRepr
(\_ _ → "ilyon")
[ (1, BN.forms "m" "an" "an" "" "")
, (2, BN.forms "b" "do" "do" "vi" "du")
, (3, \c → case c of
CtxAdd _ (Lit 10) _ → "tre"
CtxAdd _ (Lit 100) _ → "tre"
CtxAdd {} → "tres"
CtxMul _ (Lit 100) _ → "tre"
CtxMul {} → "tri"
_ → "tr"
)
, (4, BN.forms "katr" "kator" "kator" "katra" "katrin")
, (5, BN.forms "kent" "ken" "kenka" "kenka" "ken")
, (6, BN.forms "sekst" "seks" "ses" "seksa" "se")
, (7, BN.forms "sept" "septen" "septem" "septe" "septin")
, (8, BN.forms "okt" "okto" "okto" "okto" "oktin")
, (10, \c → case c of
CtxAdd _ (Lit 100) _ → "desi"
CtxAdd _ (Lit 1) (CtxAdd {}) → "desi"
CtxMul _ (Lit n) (CtxAdd L (Lit 100) _)
| n ≡ 2 → "ginti"
| otherwise → "ginta"
CtxMul _ (Lit _) (CtxAdd _ _ CtxEmpty) → "gint"
CtxMul _ (Lit _) CtxEmpty → "gint"
CtxMul {} → "ginti"
_ → "des"
)
, (100, \c → case c of
CtxMul _ (Lit n) _ | n ∉ [2,3,6] → "gent"
_ → "sent"
)
]
| telser/numerals | src/Text/Numeral/Language/TUR.hs | bsd-3-clause | 5,957 | 27 | 14 | 2,469 | 1,691 | 957 | 734 | 115 | 13 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Compiler.UniqueFM where
import Data.Monoid
import Data.Maybe
import Data.Traversable
import Data.Foldable hiding (foldl)
import qualified Data.IntMap as I
import Compiler.Unique
newtype UniqueFM a = UFM { unUFM :: I.IntMap a } deriving (Show, Functor, Monoid, Foldable, Traversable)
emptyUFM :: UniqueFM a
emptyUFM = UFM I.empty
singletonUFM :: Uniquable k => k -> a -> UniqueFM a
singletonUFM k a = UFM $ I.singleton (getKey $ getUnique k) a
insertUFM :: Uniquable k => k -> a -> UniqueFM a -> UniqueFM a
insertUFM k a m = insertUFM_u (getUnique k) a m
insertUFM_u :: Unique -> a -> UniqueFM a -> UniqueFM a
insertUFM_u k a (UFM m) = UFM $ I.insert (getKey k) a m
listToUFM :: Uniquable k => [(k, a)] -> UniqueFM a
listToUFM = foldl (\m (k, a) -> insertUFM k a m) emptyUFM
listToUFM_u :: [(Unique, a)] -> UniqueFM a
listToUFM_u = foldl (\m (k, a) -> insertUFM_u k a m) emptyUFM
lookupUFM :: Uniquable k => k -> UniqueFM a -> Maybe a
lookupUFM k m = lookupUFM_u (getUnique k) m
lookupUFM_u :: Unique -> UniqueFM a -> Maybe a
lookupUFM_u k (UFM m) = I.lookup (getKey k) m
memberUFM :: Uniquable k => k -> UniqueFM a -> Bool
memberUFM k = isJust . lookupUFM k
memberUFM_u :: Unique -> UniqueFM a -> Bool
memberUFM_u k = isJust . lookupUFM_u k
unsafeLookup_u :: Unique -> UniqueFM a -> a
unsafeLookup_u k (UFM m) = m I.! (getKey k)
unsafeLookup :: Uniquable k => k -> UniqueFM a -> a
unsafeLookup k = unsafeLookup_u (getUnique k)
unionUFM_u :: UniqueFM a -> UniqueFM a -> UniqueFM a
unionUFM_u (UFM l) (UFM r) = UFM $ I.union l r
updateUFM :: Uniquable k => (a -> Maybe a) -> k -> UniqueFM a -> UniqueFM a
updateUFM f k m = updateUFM_u f (getUnique k) m
updateUFM_u :: (a -> Maybe a) -> Unique -> UniqueFM a -> UniqueFM a
updateUFM_u f k (UFM m) = UFM $ I.update f (getKey k) m
elemsUFM :: UniqueFM a -> [a]
elemsUFM (UFM m) = I.elems m
filterUFM :: (a -> Bool) -> UniqueFM a -> UniqueFM a
filterUFM f (UFM m) = UFM $ I.filter f m
| YoEight/hk-coolc | src/Compiler/UniqueFM.hs | bsd-3-clause | 2,004 | 0 | 9 | 399 | 915 | 460 | 455 | 43 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Feldspar.Core.Constructs.Switch where
import Language.Syntactic
import Language.Syntactic.Constructs.Binding
import Feldspar.Core.Types
import Feldspar.Core.Interpretation
import Feldspar.Core.Constructs.Eq
import Feldspar.Core.Constructs.Condition
import Data.Typeable
data Switch a
where
Switch :: (Type b) => Switch (b :-> Full b)
instance Semantic Switch
where
semantics Switch = Sem "switch" id
semanticInstances ''Switch
instance EvalBind Switch where evalBindSym = evalBindSymDefault
instance AlphaEq dom dom dom env => AlphaEq Switch Switch dom env
where
alphaEqSym = alphaEqSymDefault
instance Sharable Switch
instance Cumulative Switch
instance SizeProp (Switch :|| Type)
where
sizeProp (C' Switch) (WrapFull sz :* Nil) = infoSize sz
instance
( (Switch :|| Type) :<: dom
, (EQ :|| Type) :<: dom
, (Condition :|| Type) :<: dom
, OptimizeSuper dom
) =>
Optimize (Switch :|| Type) dom
where
-- If the arguments still have the shape of a condition tree (right
-- spine), keep it as a Switch otherwise just return the expressions within
constructFeatOpt opts sym@(C' Switch) args@((cond :$ (op :$ _ :$ s) :$ _ :$ f ) :* Nil)
| Just (C' Condition) <- prjF cond
, Just (C' Equal) <- prjF op
, isTree s f
= constructFeatUnOptDefault opts sym args
constructFeatOpt _ (C' Switch) (a :* Nil) = return a
constructFeatUnOpt opts x@(C' _) = constructFeatUnOptDefault opts x
isTree :: ( (EQ :|| Type) :<: dom
, (Condition :|| Type) :<: dom
, AlphaEq dom dom (Decor Info (dom :|| Typeable)) [(VarId,VarId)]
)
=> ASTF (Decor Info (dom :|| Typeable)) a -> ASTF (Decor Info (dom :|| Typeable)) b -> Bool
isTree s (cond :$ (op :$ c :$ a) :$ t :$ f)
| Just (C' Condition) <- prjF cond
, Just (C' Equal) <- prjF op
= alphaEq s a && isTree s f
isTree _ _ = True
| emwap/feldspar-language | src/Feldspar/Core/Constructs/Switch.hs | bsd-3-clause | 2,183 | 0 | 15 | 508 | 686 | 359 | 327 | 49 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-missing-signatures -fno-warn-type-defaults #-}
-- | Take in Haskell code and output a vector of source spans and
-- their associated node type and case.
module Main (main) where
import Control.Applicative
import Control.Applicative.QQ.Idiom
import Data.Data
import Data.List
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Descriptive
import Descriptive.Options
import GHC.Tuple
import Language.Haskell.Exts.Annotated
import System.Environment
-- | A generic Dynamic-like constructor -- but more convenient to
-- write and pattern match on.
data D = forall a. Data a => D a
-- | A parser. Presently there is only 'parseTopLevel', but in the
-- past, and in the future, there will be the facility to parse
-- specific parse of declarations, rather than re-parsing the whole
-- declaration which can be both slow and brittle.
type Parser = ParseMode -> String -> ParseResult D
-- | The 'empty' method isn't (shouldn't be) used, so this isn't a
-- real Alternative instance (perhaps a Semigroup might do?). But it's
-- handy.
instance Alternative ParseResult where
empty = ParseFailed undefined undefined
ParseFailed{} <|> x = x
x <|> _ = x
--- | Main entry point.
main :: IO ()
main =
do code <- getContents
args <- getArgs
case consume options (map T.pack args) of
Succeeded (action,typ,exts) ->
outputWith action typ exts code
_ ->
error (T.unpack (textDescription (describe options [])))
-- | Action to perform.
data Action = Parse | Check
-- | Thing to parse.
data ParseType = Decl | Stmt
-- | Command line options.
options :: Monad m => Consumer [Text] (Option ()) m (Action,ParseType,[Extension])
options = [i|(,,) action typ exts|]
where action =
constant "parse" "Parse and spit out spans" Parse <|>
constant "check" "Just check the syntax" Check
typ =
constant "decl" "Parse a declaration" Decl <|>
constant "stmt" "Parse a statement" Stmt
exts =
fmap getExtensions
(many (prefix "X" "Language extension"))
-- | Output some result with the given action (check/parse/etc.),
-- parsing the given type of AST node. In the past, the type was any
-- kind of AST node. Today, it's just a "decl" which is covered by
-- 'parseTopLevel'.
outputWith :: Action -> ParseType -> [Extension] -> String -> IO ()
outputWith action typ exts code =
case typ of
Decl -> output action parseTopLevel exts code
Stmt -> output action parseSomeStmt exts code
-- | Output AST info for the given Haskell code.
output :: Action -> Parser -> [Extension] -> String -> IO ()
output action parser exts code =
case parser mode code of
ParseFailed _ e -> error e
ParseOk (D ast) ->
case action of
Check -> return ()
Parse ->
putStrLn ("[" ++
concat (genHSE mode ast) ++
"]")
where mode = parseMode {extensions = exts}
-- | An umbrella parser to parse:
--
-- * A declaration.
--
-- * An import line (not normally counted as a declaration).
--
-- * A module header (not normally counted either).
--
-- * A module pragma (normally part of the module header).
--
parseTopLevel :: ParseMode -> String -> ParseResult D
parseTopLevel mode code =
[i|(D . fix) (parseDeclWithMode mode code)|] <|>
[i|D (parseImport mode code)|] <|>
[i|(D . fix) (parseModuleWithMode mode code)|] <|>
[i|D (parseModulePragma mode code)|]
-- | Parse a do-notation statement.
parseSomeStmt :: ParseMode -> String -> ParseResult D
parseSomeStmt mode code =
[i|(D . fix) (parseStmtWithMode mode code)|] <|>
[i|(D . fix) (parseExpWithMode mode code)|] <|>
[i|D (parseImport mode code)|]
-- | Apply fixities after parsing.
fix ast = fromMaybe ast (applyFixities baseFixities ast)
-- | Parse mode, includes all extensions, doesn't assume any fixities.
parseMode :: ParseMode
parseMode =
defaultParseMode {extensions = defaultExtensions
,fixities = Nothing}
-- | Generate a list of spans from the HSE AST.
genHSE :: Data a => ParseMode -> a -> [String]
genHSE mode x =
case gmapQ D x of
zs@(D y:ys) ->
case cast y of
Just s ->
spanHSE (show (show (typeOf x)))
(showConstr (toConstr x))
(srcInfoSpan s) :
concatMap (\(i,D d) -> pre x i ++ genHSE mode d)
(zip [0..] ys) ++
post mode x
_ ->
concatMap (\(D d) -> genHSE mode d) zs
_ -> []
-- | Pre-children tweaks for a given parent at index i.
--
pre :: (Typeable a) => a -> Integer -> [String]
pre x i =
case cast x of
-- <foo { <foo = 1> }> becomes <foo <{ <foo = 1> }>>
Just (RecUpdate SrcSpanInfo{srcInfoPoints=(start:_),srcInfoSpan=end} _ _)
| i == 1 ->
[spanHSE (show "RecUpdates")
"RecUpdates"
(SrcSpan (srcSpanFilename start)
(srcSpanStartLine start)
(srcSpanStartColumn start)
(srcSpanEndLine end)
(srcSpanEndColumn end))]
_ -> case cast x :: Maybe (Deriving SrcSpanInfo) of
-- <deriving (X,Y,Z)> becomes <deriving (<X,Y,Z>)
Just (Deriving _ ds@(_:_)) ->
[spanHSE (show "InstHeads")
"InstHeads"
(SrcSpan (srcSpanFilename start)
(srcSpanStartLine start)
(srcSpanStartColumn start)
(srcSpanEndLine end)
(srcSpanEndColumn end))
|Just (IRule _ _ _ (IHCon (SrcSpanInfo start _) _)) <- [listToMaybe ds]
,Just (IRule _ _ _ (IHCon (SrcSpanInfo end _) _)) <- [listToMaybe (reverse ds)]]
_ -> []
-- | Post-node tweaks for a parent, e.g. adding more children.
post :: (Typeable a) => ParseMode -> a -> [String]
post mode x =
case cast x of
Just (QuasiQuote (base :: SrcSpanInfo) qname content) ->
case parseExpWithMode mode content of
ParseOk ex -> genHSE mode (fmap (redelta qname base) ex)
ParseFailed _ e -> error e
_ -> []
-- | Apply a delta to the positions in the given span from the base.
redelta :: String -> SrcSpanInfo -> SrcSpanInfo -> SrcSpanInfo
redelta qname base (SrcSpanInfo (SrcSpan fp sl sc el ec) pts) =
SrcSpanInfo
(if sl == 1
then SrcSpan fp
(sl + lineOffset)
(sc + columnOffset)
(el + lineOffset)
(if el == sl
then ec + columnOffset
else ec)
else SrcSpan fp
(sl + lineOffset)
sc
(el + lineOffset)
ec)
pts
where lineOffset = sl' - 1
columnOffset =
sc' - 1 +
length ("[" :: String) +
length qname +
length ("|" :: String)
(SrcSpanInfo (SrcSpan _ sl' sc' _ _) _) = base
-- | Generate a span from a HSE SrcSpan.
spanHSE :: String -> String -> SrcSpan -> String
spanHSE typ cons SrcSpan{..} = "[" ++ spanContent ++ "]"
where unqualify = dropUntilLast '.'
spanContent =
unwords [unqualify typ
,cons
,show srcSpanStartLine
,show srcSpanStartColumn
,show srcSpanEndLine
,show srcSpanEndColumn]
------------------------------------------------------------------------------
-- General Utility
-- | Like 'dropWhile', but repeats until the last match.
dropUntilLast :: Char -> String -> String
dropUntilLast ch = go []
where
go _ (c:cs) | c == ch = go [] cs
go acc (c:cs) = go (c:acc) cs
go acc [] = reverse acc
--------------------------------------------------------------------------------
-- Parsers that HSE hackage doesn't have
parseImport :: ParseMode -> String -> ParseResult (ImportDecl SrcSpanInfo)
parseImport mode code =
case parseModuleWithMode mode code of
ParseOk (Module _ _ _ [i] _) -> return i
ParseOk _ -> ParseFailed noLoc "parseImport"
ParseFailed x y -> ParseFailed x y
parseModulePragma :: ParseMode -> String -> ParseResult (ModulePragma SrcSpanInfo)
parseModulePragma mode code =
case parseModuleWithMode mode (code ++ "\nmodule X where") of
ParseOk (Module _ _ [p] _ _) -> return p
ParseOk _ -> ParseFailed noLoc "parseModulePragma"
ParseFailed x y -> ParseFailed x y
--------------------------------------------------------------------------------
-- Extensions stuff stolen from hlint
-- | Consume an extensions list from arguments.
getExtensions :: [Text] -> [Extension]
getExtensions = foldl f defaultExtensions . map T.unpack
where f _ "Haskell98" = []
f a ('N':'o':x)
| Just x' <- readExtension x =
delete x' a
f a x
| Just x' <- readExtension x =
x' :
delete x' a
f _ x = error $ "Unknown extension: " ++ x
-- | Parse an extension.
readExtension :: String -> Maybe Extension
readExtension x =
case classifyExtension x of
UnknownExtension _ -> Nothing
x' -> Just x'
-- | Default extensions.
defaultExtensions :: [Extension]
defaultExtensions =
[e | e@EnableExtension{} <- knownExtensions] \\
map EnableExtension badExtensions
-- | Extensions which steal too much syntax.
badExtensions :: [KnownExtension]
badExtensions =
[Arrows -- steals proc
,TransformListComp -- steals the group keyword
,XmlSyntax, RegularPatterns -- steals a-b
,UnboxedTuples -- breaks (#) lens operator
-- ,QuasiQuotes -- breaks [x| ...], making whitespace free list comps break
]
| pharpend/structured-haskell-mode | src/Main.hs | bsd-3-clause | 10,188 | 0 | 20 | 2,966 | 2,453 | 1,289 | 1,164 | 206 | 4 |
{-# OPTIONS_GHC -fno-warn-tabs #-}
{- $Id: TestsArr.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* Y A M P A *
* *
* Module: TestsArr *
* Purpose: Test cases for arr *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module TestsArr (
arr_trs,
arr_tr,
arr_st0,
arr_st0r,
arr_st1,
arr_st1r
) where
import FRP.Yampa
import TestsCommon
------------------------------------------------------------------------------
-- Test cases for arr
------------------------------------------------------------------------------
arr_t0 = testSF1 (arr (+1))
arr_t0r =
[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,
17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0,25.0]
arr_t1 = testSF2 (arr (+1))
arr_t1r =
[1.0,1.0,1.0,1.0,1.0,2.0,2.0,2.0,2.0,2.0,3.0,3.0,3.0,3.0,3.0,4.0,4.0,4.0,
4.0,4.0,5.0,5.0,5.0,5.0,5.0]
arr_trs =
[ arr_t0 ~= arr_t0r,
arr_t1 ~= arr_t1r
]
arr_tr = and arr_trs
arr_st0 = testSFSpaceLeak 2000000 (arr (+1))
arr_st0r = 1000000.5
arr_st1 = testSFSpaceLeak 2000000 identity
arr_st1r = 999999.5
| ivanperez-keera/Yampa | yampa/tests/TestsArr.hs | bsd-3-clause | 1,697 | 0 | 8 | 606 | 300 | 189 | 111 | 26 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
module Cataskell.Serialize where
import Cataskell.SerializeOpts
import Cataskell.Game
import Cataskell.GameData.Actions
import Cataskell.GameData.Basics
import Cataskell.GameData.Board
import Cataskell.GameData.Location
import Cataskell.GameData.Player
import Cataskell.GameData.PlayerView
import Cataskell.GameData.Resources
import Data.Map (Map)
import qualified Data.Map.Strict as Map
import Control.Applicative ((<$>))
import Data.Aeson
import Data.Aeson.TH
-- location instances
deriveJSON myOptions ''VertexPosition
deriveJSON myOptionsNoLens ''Point
deriveJSON myOptionsNoLens ''CentralPoint
deriveJSON myOptionsNoLens ''UndirectedEdge
-- basics
deriveJSON myOptions ''ResourceType
deriveJSON myOptionsNoLens ''ResourceCount
deriveJSON myOptions ''Terrain
deriveJSON myOptions ''Color
deriveJSON myOptions ''DevelopmentCard
deriveJSON myOptions ''Inhabited
deriveJSON myOptions ''ItemType
deriveJSON myOptions ''OnPoint
deriveJSON myOptions ''OnEdge
deriveJSON myOptions ''Construct
deriveJSON myOptions ''Item
-- board
deriveJSON myOptions ''Harbor
deriveJSON myOptions ''HexCenter
instance (ToJSON k, ToJSON a) => ToJSON (Map k a) where
toJSON = toJSON . Map.toList
instance (Ord k, FromJSON k, FromJSON a) => FromJSON (Map k a) where
parseJSON j = Map.fromList <$> parseJSON j
deriveJSON myOptions ''HexMap
deriveJSON myOptions ''RoadMap
deriveJSON myOptions ''BuildingMap
deriveJSON myOptions ''HarborMap
deriveJSON myOptions ''Board
-- player
deriveJSON myOptions ''PlayerIndex
deriveJSON myOptions ''Bonus
deriveJSON myOptions ''Player
-- actions
deriveJSON myOptions ''Monopoly
deriveJSON myOptions ''Invention
deriveJSON myOptions ''MoveRobber
deriveJSON myOptions ''SpecialAction
deriveJSON myOptions ''TradeOffer
deriveJSON myOptions ''TradeAction
deriveJSON myOptions ''DiscardAction
deriveJSON myOptions ''PlayerAction
deriveJSON myOptions ''GameAction
-- game state
deriveJSON myOptions ''SpecialPhase
deriveJSON myOptions ''Phase
deriveJSON myOptions ''Game
deriveJSON myOptions { fieldLabelModifier = drop 3 } ''PlayerView
| corajr/cataskell | src/Cataskell/Serialize.hs | bsd-3-clause | 2,234 | 0 | 8 | 267 | 597 | 283 | 314 | 61 | 0 |
data X = X { foo :: Int
, bar :: String
} deriving Eq
| itchyny/vim-haskell-indent | test/recordtype/record.out.hs | mit | 76 | 0 | 8 | 37 | 25 | 15 | 10 | 3 | 0 |
{-# LANGUAGE BangPatterns #-}
--
-- Copyright : (c) T.Mishima 2014
-- License : Apache-2.0
--
module GLFWWindow
( GLFWHandle
, UIMode (..)
--
, initGLFW
, pollGLFW
, getDeltTime
, setUIMode
, togleUIMode
, getWindowSize
, swapBuff
, getExitReqGLFW
, exitGLFW
, toggleFullScreenMode
--
, getSystemKeyOpe
, getMoveKeyOpe
, getScreenModeKeyOpe
--
, getScrollMotion
, getCursorMotion
, getCursorPosition
, BottonMode (..)
, setMouseBtnMode
, getButtonClick
, getWindowHdl
)
where
import qualified Graphics.UI.GLFW as GLFW
import Control.Monad ( replicateM, when )
import Data.IORef
data GLFWHandle = GLFWHandle
{ winHdl :: IORef (Maybe GLFW.Window,Bool)
, winSize :: (Int,Int)
, mouseStat :: MouseStatusHdl
, keyStat :: KeyStatusHdl
, exitFlg :: ProgCtrlStat
, uiMode :: IORef UIMode
, oldTime :: IORef Double
, winTitle :: IORef String
}
data UIMode = Mode2D | Mode3D
deriving (Eq,Show)
type ProgCtrlStat = IORef Bool
getWindowHdl :: GLFWHandle -> IO (Maybe GLFW.Window)
getWindowHdl glfwHdl =
fmap fst $ readIORef (winHdl glfwHdl)
initGLFW :: (Int,Int) -> String -> Bool -> IO GLFWHandle
initGLFW winSize' winTitle' fullScreenSW = do
True <- GLFW.init
GLFW.defaultWindowHints
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor (3::Int)
--GLFW.windowHint $ GLFW.WindowHint'ContextVersionMinor (3::Int)
--GLFW.windowHint $ GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Compat
--GLFW.windowHint $ GLFW.WindowHint'RefreshRate (60::Int)
--
exitFlg' <- newIORef False
uiMode' <- newIORef Mode2D
keyStat' <- createKeyStatHdl
mouseStat' <- createMouseStatHdl
--
oldTime' <- newIORef 0.0
--
--GLFW.swapInterval 0
win <- createDefWindow winSize' fullScreenSW
exitFlg' keyStat' uiMode' mouseStat'
winTitle'
--
winTitle'' <- newIORef winTitle'
--
return GLFWHandle
{ winHdl = win
, winSize = winSize'
, mouseStat = mouseStat'
, keyStat = keyStat'
, exitFlg = exitFlg'
, uiMode = uiMode'
, oldTime = oldTime'
, winTitle = winTitle''
}
setCallBacktoWin :: GLFW.Window
-> ProgCtrlStat
-> KeyStatusHdl -> IORef UIMode
-> MouseStatusHdl
-> IO ()
setCallBacktoWin win' exitFlg' keyStat' uiMode' mouseStat' = do
GLFW.setWindowCloseCallback win' (Just $ finishGLFW exitFlg')
GLFW.setKeyCallback win' (Just (keyPress keyStat'))
GLFW.setCursorPosCallback win'
(Just (setCursorMotion uiMode' mouseStat'))
GLFW.setMouseButtonCallback win' (Just (setButtonClick mouseStat'))
GLFW.setScrollCallback win' (Just (setScrollMotion mouseStat'))
createDefWindow :: (Int, Int) -> Bool -> ProgCtrlStat
-> KeyStatusHdl -> IORef UIMode
-> MouseStatusHdl -> String
-> IO (IORef (Maybe GLFW.Window, Bool))
createDefWindow (wWidth,wHight) isFullScr exitFlg' keyStat'
uiMode' mouseStat' winTitle' = do
win <- if isFullScr
then do
moni <- GLFW.getPrimaryMonitor
GLFW.createWindow wWidth wHight winTitle' moni Nothing
else
GLFW.createWindow wWidth wHight winTitle' Nothing Nothing
GLFW.makeContextCurrent win
case win of
Just win' -> -- Callback
setCallBacktoWin win' exitFlg' keyStat' uiMode' mouseStat'
Nothing -> return ()
newIORef (win, isFullScr)
toggleFullScreenMode :: GLFWHandle -> IO ()
toggleFullScreenMode glfwHdl = do
winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just win,scmd) -> do
(wWidth,wHight) <- getWindowSize glfwHdl
GLFW.windowShouldClose win
GLFW.destroyWindow win
winTitle' <- readIORef $ winTitle glfwHdl
newwin' <- if scmd
then
GLFW.createWindow wWidth wHight winTitle' Nothing Nothing
else do
moni <- GLFW.getPrimaryMonitor
GLFW.createWindow wWidth wHight winTitle' moni Nothing
GLFW.makeContextCurrent newwin'
case newwin' of
Just win' -> -- Callback
setCallBacktoWin win' exitFlg' keyStat' uiMode' mouseStat'
Nothing -> return ()
writeIORef (winHdl glfwHdl) (newwin',not scmd)
return ()
(Nothing,_) -> return ()
where
mouseStat' = mouseStat glfwHdl
keyStat' = keyStat glfwHdl
exitFlg' = exitFlg glfwHdl
uiMode' = uiMode glfwHdl
setUIMode :: GLFWHandle -> UIMode -> IO ()
setUIMode glfwHdl mode = do
writeIORef ui' mode
winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just win,_) -> case mode of
Mode2D -> -- 2D
GLFW.setCursorInputMode win GLFW.CursorInputMode'Normal
Mode3D ->
GLFW.setCursorInputMode win GLFW.CursorInputMode'Hidden
(Nothing,_) -> return ()
where
!ui' = uiMode glfwHdl
togleUIMode :: GLFWHandle -> IO ()
togleUIMode glfwHdl = do
winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just win,_) -> do
md <- readIORef ui'
nmd <- case md of
Mode3D ->
GLFW.setCursorInputMode win GLFW.CursorInputMode'Normal
>> return Mode2D
Mode2D ->
GLFW.setCursorInputMode win GLFW.CursorInputMode'Hidden
>> return Mode3D
writeIORef ui' nmd
(Nothing,_) -> return ()
where
ui' = uiMode glfwHdl
pollGLFW :: IO ()
pollGLFW = GLFW.pollEvents
swapBuff :: GLFWHandle -> IO ()
swapBuff glfwHdl = do
winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just win,_) -> GLFW.swapBuffers win
(Nothing,_) -> return ()
getExitReqGLFW :: GLFWHandle -> IO Bool
getExitReqGLFW glfwHdl = readIORef $ exitFlg glfwHdl
getDeltTime :: GLFWHandle -> IO Double
getDeltTime glfwHdl = do
Just newTime' <- GLFW.getTime
oldTime' <- readIORef $ oldTime glfwHdl
writeIORef (oldTime glfwHdl) newTime'
return $! newTime' - oldTime'
getWindowSize :: GLFWHandle -> IO (Int,Int)
getWindowSize glfwHdl =
return $ winSize glfwHdl
{- winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just w,_) -> GLFW.getFramebufferSize w
(Nothing,_) -> return (0,0)
-}
exitGLFW :: GLFWHandle -> IO ()
exitGLFW glfwHdl = do
winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just win',_) -> do
GLFW.destroyWindow win'
GLFW.terminate
(Nothing,_) -> return ()
finishGLFW :: ProgCtrlStat -> GLFW.WindowCloseCallback
finishGLFW exitflg _ = do
writeIORef exitflg True
return ()
-- ##################### Keybord ###########################
data KeyStatusHdl = KeyStatusHdl
{ fKey :: IORef Int
, bKey :: IORef Int
, rKey :: IORef Int
, lKey :: IORef Int
, jmpKey :: IORef Int
, tolKey :: IORef Int
, escKey :: IORef Int
, tabKey :: IORef Int
, scrMdKey :: IORef Int
, dbgModeKey :: IORef Int
, dbg2 :: IORef Int
}
getSystemKeyOpe :: GLFWHandle -> IO (Bool, Bool)
getSystemKeyOpe glfwHdl = do
esc <- readIORef (escKey opeKeyS)
writeIORef (escKey opeKeyS) 0
tol <- readIORef (tolKey opeKeyS)
writeIORef (tolKey opeKeyS) 0
return (esc > 0, tol > 0)
where
opeKeyS = keyStat glfwHdl
getScreenModeKeyOpe :: GLFWHandle -> IO Bool
getScreenModeKeyOpe glfwHdl = do
ope <- readIORef (scrMdKey opeKeyS)
writeIORef (scrMdKey opeKeyS) 0
return (ope > 0)
where
opeKeyS = keyStat glfwHdl
getMoveKeyOpe :: GLFWHandle -> IO (Int, Int, Int, Int, Int)
getMoveKeyOpe glfwHdl = do
f <- readIORef (fKey opeKeyS)
b <- readIORef (bKey opeKeyS)
l <- readIORef (lKey opeKeyS)
r <- readIORef (rKey opeKeyS)
jmp <- readIORef (jmpKey opeKeyS)
writeIORef (jmpKey opeKeyS) 1
return (f,b,l,r,jmp)
where
opeKeyS = keyStat glfwHdl
{-
getDebugKey :: ViewCtrl -> IO (Bool, Bool)
getDebugKey viewCtrl = do
d1 <- readIORef (dbg1 opeKeyS)
writeIORef (dbg1 opeKeyS) 0
d2 <- readIORef (dbg2 opeKeyS)
writeIORef (dbg2 opeKeyS) 0
return ( d1 > 0, d2 > 0)
where
opeKeyS = keyStat viewCtrl
-}
createKeyStatHdl :: IO KeyStatusHdl
createKeyStatHdl = do
sl <- replicateM 10 (newIORef (0 :: Int))
return KeyStatusHdl
{ fKey = head sl
, bKey = sl!!1
, rKey = sl!!2
, lKey = sl!!3
, jmpKey = sl!!4
, tolKey = sl!!5
, escKey = sl!!6
, tabKey = sl!!7
, scrMdKey = sl!!8
, dbgModeKey = sl!!9
, dbg2 = sl!!10
}
keyPress :: KeyStatusHdl -> GLFW.KeyCallback
keyPress s _ GLFW.Key'Escape _ GLFW.KeyState'Pressed _
= writeIORef (escKey s) 1
--keyPress s _ GLFW.Key'Escape _ GLFW.KeyState'Released _
-- = writeIORef (escKey s) 0
keyPress s _ GLFW.Key'W _ GLFW.KeyState'Pressed _
= writeIORef (fKey s) 1
keyPress s _ GLFW.Key'W _ GLFW.KeyState'Released _
= writeIORef (fKey s) 0
keyPress s _ GLFW.Key'S _ GLFW.KeyState'Pressed _
= writeIORef (bKey s) 1
keyPress s _ GLFW.Key'S _ GLFW.KeyState'Released _
= writeIORef (bKey s) 0
keyPress s _ GLFW.Key'A _ GLFW.KeyState'Pressed _
= writeIORef (lKey s) 1
keyPress s _ GLFW.Key'A _ GLFW.KeyState'Released _
= writeIORef (lKey s) 0
keyPress s _ GLFW.Key'D _ GLFW.KeyState'Pressed _
= writeIORef (rKey s) 1
keyPress s _ GLFW.Key'D _ GLFW.KeyState'Released _
= writeIORef (rKey s) 0
--keyPress s _ GLFW.Key'E _ GLFW.KeyState'Pressed _
-- = writeIORef (tolKey s) 1
keyPress s _ GLFW.Key'E _ GLFW.KeyState'Released _
= writeIORef (tolKey s) 1
keyPress s _ GLFW.Key'Space _ GLFW.KeyState'Pressed _
= writeIORef (jmpKey s) 2
keyPress s _ GLFW.Key'Space _ GLFW.KeyState'Released _
= writeIORef (jmpKey s) 0
--keyPress s _ GLFW.Key'Tab _ GLFW.KeyState'Pressed _
-- = writeIORef (tabKey s) 1
--keyPress s _ GLFW.Key'Tab _ GLFW.KeyState'Released _
-- = writeIORef (tabKey s) 1
keyPress s _ GLFW.Key'F3 _ GLFW.KeyState'Pressed _
= writeIORef (dbgModeKey s) 1
keyPress s _ GLFW.Key'Down _ GLFW.KeyState'Released _
= writeIORef (dbg2 s) 1
keyPress s _ GLFW.Key'F11 _ GLFW.KeyState'Released _
= writeIORef (scrMdKey s) 1
keyPress _ _ _ _ _ _
= return ()
-- ##################### Mouse ############################
data MouseStatusHdl = MouseStatusHdl
{ deltMove :: IORef (Double,Double)
, btn1Clk :: IORef Bool
, btn2Clk :: IORef Bool
, btn3Clk :: IORef Bool
, scrlMove :: IORef (Double,Double)
, btnMode :: IORef BottonMode
}
data BottonMode = REdgeMode | StateMode
deriving (Eq,Show)
createMouseStatHdl :: IO MouseStatusHdl
createMouseStatHdl = do
dltmv <- newIORef (0,0)
btn1 <- newIORef False
btn2 <- newIORef False
btn3 <- newIORef False
scr <- newIORef (0,0)
btnMd <- newIORef REdgeMode
return MouseStatusHdl {
deltMove = dltmv
, btn1Clk = btn1
, btn2Clk = btn2
, btn3Clk = btn3
, scrlMove = scr
, btnMode = btnMd
}
setScrollMotion :: MouseStatusHdl -> GLFW.ScrollCallback
setScrollMotion opeMus _ x y =
modifyIORef (scrlMove opeMus) (\ (xo,yo) -> (xo + x, yo + y))
getScrollMotion :: GLFWHandle -> IO (Int, Int)
getScrollMotion glfwHdl = do
(x,y) <- readIORef $ scrlMove opeMus
writeIORef (scrlMove opeMus) (0,0)
return (floor x, floor y)
where
opeMus = mouseStat glfwHdl
setCursorMotion :: IORef UIMode -> MouseStatusHdl
-> GLFW.CursorPosCallback
setCursorMotion mode opeMus w x y = do
m' <- readIORef mode
case m' of
Mode2D -> return ()
Mode3D -> do
(wsx,wsy) <- GLFW.getWindowSize w
let cx = fromIntegral wsx / 2.0
cy = fromIntegral wsy / 2.0
GLFW.setCursorPos w cx cy
modifyIORef (deltMove opeMus) (\ (xo,yo) -> ( xo + cx -x
, yo + cy -y))
getCursorMotion :: GLFWHandle -> IO (Double, Double)
getCursorMotion glfwHdl = do
(dx,dy) <- readIORef (deltMove opeMus)
writeIORef (deltMove opeMus) (0,0)
return (dx,dy)
where
opeMus = mouseStat glfwHdl
getCursorPosition :: GLFWHandle -> IO (Double, Double)
getCursorPosition glfwHdl = do
winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just w,_) -> do
(_,h) <- getWindowSize glfwHdl
fmap (\ (x,y) -> (x,fromIntegral h - y))
$ GLFW.getCursorPos w
(Nothing,_) -> return (0,0)
setMouseBtnMode :: GLFWHandle -> BottonMode -> IO ()
setMouseBtnMode glfwHdl = writeIORef (btnMode opeMusS)
where
opeMusS = mouseStat glfwHdl
getButtonClick :: GLFWHandle -> IO (Double,Double,Bool,Bool,Bool)
getButtonClick glfwHdl = do
winStat <- readIORef $ winHdl glfwHdl
case winStat of
(Just w,_) -> do
(_,h) <- getWindowSize glfwHdl
(x,y) <- fmap (\ (x,y) -> (x,fromIntegral h - y))
$ GLFW.getCursorPos w
btn1 <- readIORef (btn1Clk opeMusS)
btn2 <- readIORef (btn2Clk opeMusS)
btn3 <- readIORef (btn3Clk opeMusS)
btnMd <- readIORef (btnMode opeMusS)
when (btnMd == REdgeMode) $ do
writeIORef (btn1Clk opeMusS) False
writeIORef (btn2Clk opeMusS) False
writeIORef (btn3Clk opeMusS) False
return (x,y,btn1, btn2, btn3)
(Nothing,_) -> return (0.0,0.0,False, False, False)
where
opeMusS = mouseStat glfwHdl
-- | button press
setButtonClick :: MouseStatusHdl -> GLFW.MouseButtonCallback
setButtonClick s _ GLFW.MouseButton'1 GLFW.MouseButtonState'Pressed _
= writeIORef (btn1Clk s) True
setButtonClick s _ GLFW.MouseButton'1 GLFW.MouseButtonState'Released _
= writeIORef (btn1Clk s) False
setButtonClick s _ GLFW.MouseButton'2 GLFW.MouseButtonState'Pressed _
= writeIORef (btn2Clk s) True
setButtonClick s _ GLFW.MouseButton'2 GLFW.MouseButtonState'Released _
= writeIORef (btn2Clk s) False
setButtonClick s _ GLFW.MouseButton'3 GLFW.MouseButtonState'Pressed _
= writeIORef (btn3Clk s) True
setButtonClick s _ GLFW.MouseButton'3 GLFW.MouseButtonState'Released _
= writeIORef (btn3Clk s) False
setButtonClick _ _ _ _ _
= return ()
| tmishima/bindings-Oculus | test/case2/GLFWWindow.hs | apache-2.0 | 13,983 | 0 | 19 | 3,485 | 4,311 | 2,178 | 2,133 | 361 | 4 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings, BangPatterns, ScopedTypeVariables #-}
module Main where
-- import Control.Concurrent.Async
import Control.Concurrent.ParallelIO.Global
import Control.DeepSeq
import Control.Exception
import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Csv
import qualified Data.Graph.Inductive.Graph as Graph
import qualified Data.HashSet as HashSet
import Data.List
import Data.Maybe
import Data.Time.Clock.POSIX
import GHC.Generics (Generic)
import System.Environment
import System.IO
import qualified System.Timeout as T
import Text.Printf
import NanoML hiding (force, Expr(Hole))
import NanoML.Misc
import NanoML.Parser
import NanoML.Pretty
import Debug.Trace
isRight Right {} = True
isRight _ = False
data ST = ST { total :: !Int, safe :: !Int, timeout :: !Int
, unbound :: !Int, output :: !Int, unsafe :: !Int
, diverge :: !Int
}
data O = Safe | Unsafe | Unbound | Output | Diverge | Timeout | Hole
deriving (Show, Read, Eq, Generic)
instance NFData O
instance FromField O where
parseField s
| s == "S" = pure Safe
| s == "U" = pure Unsafe
| s == "B" = pure Unbound
| s == "O" = pure Output
| s == "D" = pure Diverge
| s == "T" = pure Timeout
| s == "H" = pure Hole
| otherwise = mzero
instance ToField O where
toField Safe = "S"
toField Unsafe = "U"
toField Unbound = "B"
toField Output = "O"
toField Diverge = "D"
toField Timeout = "T"
toField Hole = "H"
data R = R { file :: !String
, stepLimit :: !Int, time :: !Double, tests :: !Int
, outcome :: !O, steps :: !Int, jumps :: !Int
} deriving Generic
instance NFData R
instance FromNamedRecord R
instance ToNamedRecord R
instance DefaultOrdered R
initST = ST 0 0 0 0 0 0 0
reduceM xs z f = foldM f z xs
bumpIf True = 1
bumpIf False = 0
initOpts = stdOpts { maxTests = 1000, produceTrace = True, maxSteps = 500 }
extendOpts opts = opts { maxSteps = 500 + maxSteps opts }
upperBound = 3000
getTime :: IO Double
getTime = realToFrac `fmap` getPOSIXTime
timed x = do start <- getTime
!v <- x
end <- getTime
return (end-start, v)
checkLoop opts f e p = do
(t, r) <- timed $ T.timeout (60 * (10^6)) $ checkWith opts e p
case r of
-- timed out after x minutes..
Nothing -> do
putStrLn $ "TIMED OUT: " ++ f
return (Just (Failure 1 1 1 (pretty $ VU Nothing) (TimeoutError (maxSteps opts)) initState, t, maxSteps opts))
Just Nothing -> do
putStrLn "WHAT IS THIS?"
return Nothing
Just (Just r)
| not (isSuccess r) && becauseOf "timeout" r
-> if maxSteps opts == upperBound
then return (Just (r,t, maxSteps opts))
else checkLoop (extendOpts opts) f e p
| otherwise -> do
putStrLn "SUCCESS!"
when (isSuccess r ||
becauseOf "cannot compare two holes" r ||
becauseOf "timeout" r) $
putStrLn $ "NO WITNESS: " ++ f
return (Just (r,t, maxSteps opts))
becauseOf r = (r `isInfixOf`) . show . pretty . errorMsg
mkOutcome f r
| isSuccess r = Just Safe
| becauseOf "timeout" r = Just Timeout
| becauseOf "Unbound" r = Just Unbound
| becauseOf "unbound" r = Just Unbound
| becauseOf "OutputType" r = Just Output
| becauseOf "Type error" r = Just Unsafe
| becauseOf "infinite recursion" r = Just Diverge
| becauseOf "cannot compare two holes" r = Just Hole
| otherwise = trace ("mkOutcome: " ++ f ++ " (" ++ show (pretty (errorMsg r)) ++ ")") (Just Unsafe)
makePath :: Result -> [StepKind]
makePath r =
let fs = finalState r
gr = buildGraph (HashSet.toList $ stEdges fs)
-- st = ancestor gr $ findRoot gr ( if isSuccess r
-- then result r
-- else stCurrentExpr fs
-- , stVarEnv fs )
root = findRoot gr (stRoot fs)
in myunfoldr (forward gr) $! root
myunfoldr f x = go [] x
where
go xs x =
case f x of
Nothing -> []
Just (a, x')
| x' `elem` xs -> []
| otherwise -> a : go (x' : xs) x'
forward :: Graph -> Graph.Node -> Maybe (StepKind, Graph.Node)
forward gr n = case find (isStepsTo . snd) $ Graph.lsuc gr n of
Nothing -> Nothing
Just (n', _) | n == n' -> Nothing -- self loop? shouldn't be possible...
Just (n', StepsTo k) -> Just (k, n')
forConcurrently xs f = parallel (map f xs) -- mapConcurrently f xs
main = do
hSetBuffering stdout LineBuffering
[dir, csv] <- getArgs
ps <- parseAllIn dir
-- rs <- reduceM ps [] $ \rs (f,e,p) -> do
rs <- fmap catMaybes . forConcurrently ps $ \(f,e,p) -> do
putStrLn ("\n" ++ f)
r <- (evaluate =<< checkLoop initOpts f e p) `catch` \(e::SomeException) -> do
print ("UNCAUGHT EXCEPTION", e)
return Nothing
case r of
Nothing -> do
putStrLn "WTF IS THIS?"
return Nothing
Just (r,t,ms)
| Nothing <- mkOutcome f r -> return Nothing
| Just x <- mkOutcome f r -> do
printResult r
let path = makePath $! r
let ss = [CallStep, ReturnStep] -- could also look at ReturnStep, but we don't mention it in the paper
let o = R { file = f
, stepLimit = ms
, time = t
, tests = numTests r
, outcome = x
, steps = if x `elem` [Safe,Diverge,Timeout] then 0 else 1 + length path
, jumps = if x `elem` [Safe,Diverge,Timeout] then 0 else 1 + length (filter (`elem` ss) path)
}
return $!! (Just o)
`catch` \(e :: SomeException) -> do
print ("UNCAUGHT EXN2", e)
return Nothing
LBS.writeFile csv {- "out.csv" -} (encodeDefaultOrderedByName rs)
-- case r of
-- Nothing -> return st
-- Just r -> do
-- printResult r
-- let bumpIfFail b = bumpIf (not (isSuccess r) && b)
-- return $! st { total = total st + 1
-- , safe = safe st + bumpIf (isSuccess r)
-- , timeout = timeout st + bumpIfFail (becauseOf "timeout" r)
-- , unbound = unbound st + bumpIfFail (becauseOf "Unbound" r)
-- , output = output st + bumpIfFail (becauseOf "OutputType" r)
-- , unsafe = unsafe st + bumpIfFail (becauseOf "Type error" r)
-- , diverge = diverge st + bumpIfFail (becauseOf "infinite recursion" r)
-- }
-- printf "\nDONE!\n"
-- printf "%d programs:\n" (total st)
-- printf " %d did not fail at runtime\n" (safe st)
-- printf " %d timed out\n" (timeout st)
-- printf " %d did fail at runtime:\n"
-- (total st - safe st - timeout st)
-- printf " %d due to an unbound variable or datacon\n"
-- (unbound st)
-- -- length (filter (becauseOf "unknown") fs))
-- printf " %d due to an output-type-mismatch\n"
-- (output st)
-- printf " %d due to infinite recursion\n"
-- (diverge st)
-- printf " %d due to a type error (%02.02f %%)\n"
-- (unsafe st)
-- ((fromIntegral (unsafe st)
-- / fromIntegral (total st) :: Double)
-- * 100)
| ucsd-progsys/nanomaly | bin/CheckAllFrom.hs | bsd-3-clause | 7,381 | 0 | 28 | 2,322 | 2,110 | 1,091 | 1,019 | 180 | 4 |
{-
Teak synthesiser for the Balsa language
Copyright (C) 2007-2010 The University of Manchester
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,
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/>.
Andrew Bardsley <bardsley@cs.man.ac.uk> (and others, see AUTHORS)
School of Computer Science, The University of Manchester
Oxford Road, MANCHESTER, M13 9PL, UK
-}
module NetParts (
Access (..),
AccessBody (..),
AccessRef (..),
NetworkComp (..),
NetworkCompRef (..),
NetworkLink (..),
NetworkLinkConn (..),
NetworkLinkRef (..),
NetworkLinkUsage (..),
NetworkMonad (..),
NetworkPort (..),
NetworkProperty (..),
NetworkIF (..),
NetworkPortInfo (..),
Latching (..),
TeakCompInfo (..),
Part (..),
RW (..),
TeakCompType (..),
TeakOSlice,
TeakOTerm (..),
TeakOp (..),
TeakParam (..),
directionToSense,
trimPart,
exprToTeakParam,
funcActualToTeakParam,
teakParamToFuncActual,
isFork,
isTeakI,
isInstanceComp,
isTeakR,
isTeakA,
isTeakJ,
isLinkComp,
isMerge,
isTeakO,
isSteer,
isMux,
isTeakV,
teakOOpNames,
oTermExtractSlices,
oTermInsertSlices,
makeLinkUsage,
addUsagePair,
addUsagePairUnsafe,
removeUsagePair,
runWhyTPart,
runWhyTPart_,
runPart,
runPart_,
tryPart,
networkPortToPortInfo,
nwFuncToNetworkMonad,
nwAccessLinkUsage,
nwAccessLinks,
nwAddLinkRef,
nwAddPortAccess,
nwAddProperty,
nwBreakLink,
nwCombineAccesses,
nwCompLinkUsage,
nwCompPortNames,
nwCompPortSenses,
nwCompPortCardinalities,
nwCompShortName,
nwCompShortNameToTest,
nwCompShortNameToSampleTeakType,
nwConnectedComps,
nwFindPart,
nwFindPartIndex,
nwFoldComps,
nwFoldCompsIf,
nwGetAccess,
nwFindAccess,
nwFindPortByRef,
nwFindPortIndexByRef,
nwFoldLinks,
nwGetAttributeVal,
nwGetLinkName,
nwGetLinkNames,
nwGetLinkWidth,
nwGetLinkLatching,
nwGetPortAccess,
nwGetPosArray,
nwLinkIsPort,
nwLinkIsUnused,
nwLinkToComp,
nwLinkToCompIf,
nwMapComps,
nwMapCompsIf,
nwMapCompsIf_,
nwMapLinks,
nwMapLinks_,
nwMatchAccess,
nwNewLink,
nwNewLinkRef,
nwNewTeakComp,
nwNoLinkUsage,
nwRemapLink,
nwRemoveComp,
nwRemovePortAccess,
nwRemoveUnusedLinks,
nwReplaceLinkAtConn,
nwReplaceLinkInAccess,
nwReplaceLinkInComp,
nwSetLinkName,
nwTeakCompInfo,
oSliceIncrementTermNo,
oSliceIndex,
oSliceWidth,
oTermIncrementTermNo,
oTermResultWidth,
oTermVisitSlices,
oTermsLastIndex,
prettyPrintOTerms,
prettyPrintOTermPrec,
refComp,
refLink,
runNetwork,
runNetwork0,
runNetwork_,
tryNetwork,
showPart,
showPosForNetwork,
showPrettyNetwork,
readNetworkFile,
uniquifyPart,
checkPart,
writeNetworkFile
) where
import Misc
import Context
import ParseTree
import Report
import Show
import Type
import Bits
import State
import Print
import System.IO
import Data.Maybe
-- import Control.Monad
import Data.List
import Data.Char (toLower, isDigit)
import qualified Data.Map as Map
import Data.Array
import Control.Monad.State
import Control.Applicative
data RW = Read | Write
deriving (Show, Read, Eq)
newtype NetworkLinkRef = Link { nwLink :: Int }
deriving (Eq, Ord, Ix)
newtype NetworkCompRef = Comp { nwComp :: Int }
deriving (Eq, Ord, Ix)
newtype Latching = HalfBuffer { latchingDepth :: Int }
deriving Eq
data NetworkLink = NetworkLink { nwLinkIndex :: ! Int, nwLinkWidth :: ! Int, nwLinkLatching :: Latching }
deriving (Eq)
refLink :: NetworkLink -> NetworkLinkRef
refLink link = Link $ nwLinkIndex link
refComp :: NetworkComp -> NetworkCompRef
refComp comp = Comp $ nwCompIndex comp
data NetworkLinkConn = NoConn
| LinkComp ! NetworkCompRef ! [Int]
| LinkAccess ! AccessRef ! [Int]
deriving (Eq, Show, Read)
instance ShowTab NetworkLinkConn
nwNoLinkUsage :: NetworkLinkUsage
nwNoLinkUsage = NetworkLinkUsage NoConn NoConn
data NetworkLinkUsage = NetworkLinkUsage {
nwPassiveLinkUsage :: ! NetworkLinkConn, nwActiveLinkUsage :: ! NetworkLinkConn }
deriving (Eq)
type TeakOSlice = (Int, Slice Int) -- index, slice
data TeakParam = TeakParamInt Integer
| TeakParamString String
| TeakParamType Type
deriving (Eq, Ord, Show, Read)
data TeakOp =
TeakOpAdd | TeakOpSub -- add, subtract equal width
| TeakOpAnd | TeakOpOr | TeakOpNot | TeakOpXor -- logical equal width
| TeakOpSignedGT | TeakOpSignedGE -- signed comparison, 1 bit result
| TeakOpUnsignedGT | TeakOpUnsignedGE -- unsigned comparison, 1 bit result
| TeakOpEqual | TeakOpNotEqual -- comparison, 1 bit result
deriving (Eq, Ord, Read, Show)
data TeakOTerm =
TeakOConstant { teakOWidth :: Int, teakOValue :: Integer }
| TeakOAppend { teakOCount :: Int, teakOSlices :: [TeakOSlice] }
| TeakOBuiltin { teakOBuiltin :: String, teakOWidth :: Int,
teakOParams :: [TeakParam], teakOSlices :: [TeakOSlice] }
| TeakOp { teakOOp :: TeakOp, teakOSlices :: [TeakOSlice] }
| TeakOMux { teakOSpec :: [[Implicant]], teakOSlices :: [TeakOSlice] }
deriving (Eq, Ord)
oSliceWidth :: TeakOSlice -> Int
oSliceWidth (_, slice) = sliceWidth slice
oSliceIndex :: TeakOSlice -> Int
oSliceIndex (i, _) = i
oTermExtractSlices :: TeakOTerm -> [TeakOSlice]
oTermExtractSlices (TeakOConstant {}) = []
oTermExtractSlices term = teakOSlices term
oTermInsertSlices :: TeakOTerm -> [TeakOSlice] -> TeakOTerm
oTermInsertSlices term@(TeakOConstant {}) _ = term
oTermInsertSlices term slices = term { teakOSlices = slices }
oTermResultWidth :: TeakOTerm -> Int
oTermResultWidth (TeakOConstant width _) = width
oTermResultWidth (TeakOAppend count slices) = count * (sum (map oSliceWidth slices))
oTermResultWidth (TeakOBuiltin _ width _ _) = width
oTermResultWidth (TeakOp op slices)
| isEqualWidthOp op = oSliceWidth (head slices)
| otherwise = 1
oTermResultWidth (TeakOMux _ (_:slice:_)) = oSliceWidth slice
oTermResultWidth term = error $ "oTermResultWidth: unrecognised term `" ++ show term ++ "'"
isEqualWidthOp :: TeakOp -> Bool
isEqualWidthOp TeakOpAdd = True
isEqualWidthOp TeakOpSub = True
isEqualWidthOp TeakOpAnd = True
isEqualWidthOp TeakOpOr = True
isEqualWidthOp TeakOpXor = True
isEqualWidthOp TeakOpNot = True
isEqualWidthOp _ = False
-- teakOOpNames : (justAlphabetic, infix/pretty) names for TeakOps
teakOOpNames :: TeakOp -> (String, String)
teakOOpNames TeakOpAdd = ("add", "+")
teakOOpNames TeakOpAnd = ("and", "and")
teakOOpNames TeakOpEqual = ("eq", "=")
teakOOpNames TeakOpSignedGE = ("sge", "s>=")
teakOOpNames TeakOpSignedGT = ("sgt", "s>")
teakOOpNames TeakOpUnsignedGT = ("ugt", ">")
teakOOpNames TeakOpUnsignedGE = ("uge", ">=")
teakOOpNames TeakOpNotEqual = ("ne", "/=")
teakOOpNames TeakOpNot = ("not", "not")
teakOOpNames TeakOpOr = ("or", "or")
teakOOpNames TeakOpSub = ("sub", "-")
teakOOpNames TeakOpXor = ("xor", "xor")
oSliceIncrementTermNo :: Int -> TeakOSlice -> TeakOSlice
oSliceIncrementTermNo incr (term, slice) = (term + incr, slice)
oTermsLastIndex :: [(Int, TeakOTerm)] -> Int
oTermsLastIndex [] = 0
oTermsLastIndex terms = fst $ last terms
oTermIncrementTermNo :: Int -> (Int, TeakOTerm) -> (Int, TeakOTerm)
oTermIncrementTermNo incr (i, term) = (i + incr, oTermVisitSlices (oSliceIncrementTermNo incr) term)
oTermVisitSlices :: (TeakOSlice -> TeakOSlice) -> TeakOTerm -> TeakOTerm
oTermVisitSlices f term = body term
where
slices = teakOSlices term
term' = term { teakOSlices = map f slices }
body (TeakOAppend {}) = term'
body (TeakOBuiltin {}) = term'
body (TeakOp {}) = term'
body (TeakOMux {}) = term'
body term = term
data TeakCompType =
TeakA
| TeakF [Int] -- [2, 3], low indices of outputs in order. Widths determined by links.
| TeakJ
| TeakM
| TeakO [(Int, TeakOTerm)]
| TeakS (Slice Int) [([Implicant], Int)] -- condition/low index for each output
| TeakX [[Implicant]] -- condition for each input
| TeakV String Int [Int] [Int] [Int] -- name, overall width, builtin offsets, write offsets, read offsets
-- Newer, optimisation parts
| TeakI
| TeakR
deriving (Eq, Ord, Read)
-- FIXME, write a Read for TeakCompType
data NetworkComp =
TeakComp {
nwCompIndex :: ! Int,
nwTeakType :: ! TeakCompType,
nwCompLinks :: ! [Some NetworkLinkRef],
nwCompPos :: ! Pos }
| InstanceComp {
nwCompIndex :: ! Int,
nwPartName :: ! String,
nwCompPorts :: ! [NetworkPort],
nwCompLinks :: ! [Some NetworkLinkRef],
nwCompPos :: ! Pos }
instance Eq NetworkComp where
c1 == c2 = nwCompIndex c1 == nwCompIndex c2
instance Ord NetworkComp where
compare c1 c2 = compare (nwCompIndex c1) (nwCompIndex c2)
data NetworkPort = NetworkPort { nwPortName :: ! String,
nwPortDirection :: ! Direction, nwPortWidth :: ! Int,
nwPortRef :: ! (Maybe AccessRef) }
deriving Eq
networkPortToPortInfo :: NetworkPort -> NetworkPortInfo
networkPortToPortInfo port = NetworkPortInfo (nwPortName port)
(directionToSense $ nwPortDirection port) False
data NetworkProperty = NetworkComment String
| NetworkPosArray PosArray
| NetworkAttrs [(String, TeakParam)]
| NetworkLinkNames (Map.Map NetworkLinkRef String)
deriving (Read, Eq, Ord)
data AccessBody =
ChanInputAccess { chanAccessGo :: NetworkLinkRef, chanAccessDone :: NetworkLinkRef }
| ChanBareInputAccess { chanAccessData :: NetworkLinkRef }
| ChanOutputAccess { chanAccessGo :: NetworkLinkRef, chanAccessDone :: NetworkLinkRef }
| ChanBareOutputAccess { chanAccessData :: NetworkLinkRef }
| VarAccess { accessRW :: RW, accessCtrl :: NetworkLinkRef,
accessData :: NetworkLinkRef, accessRange :: Slice Int }
| SharedCallAccess { accessGo :: NetworkLinkRef, accessDone :: NetworkLinkRef }
| PortLinkAccess { accessSense :: Sense, accessLink :: NetworkLinkRef }
deriving (Eq)
data AccessRef =
GoAccess
| DoneAccess
| InstanceAccess Ref
deriving (Show, Read, Eq, Ord)
data Access = Access { accessRef :: AccessRef, accessBodys :: ! [AccessBody] }
deriving (Eq)
nwCombineAccesses :: [Access] -> [Access] -> [Access]
nwCombineAccesses accesses1 accesses2 = mergeByWith by with accesses1 accesses2
where
by (Access ref1 _) (Access ref2 _) = ref1 `compare` ref2
with (Access ref bodysL) (Access _ bodysR) = Access ref (bodysL ++ bodysR)
instance Ord Access where
compare (Access refL _) (Access refR _) = compare refL refR
nwAccessLinks :: Access -> [NetworkLinkRef]
nwAccessLinks (Access _ body) = concatMap inAccessBody body
where
inAccessBody (ChanInputAccess go done) = [go, done]
inAccessBody (ChanOutputAccess go done) = [go, done]
inAccessBody (ChanBareInputAccess link) = [link]
inAccessBody (ChanBareOutputAccess dat) = [dat]
inAccessBody (VarAccess _ ctrlLink dataLink _) = [ctrlLink, dataLink]
inAccessBody (SharedCallAccess go done) = [go, done]
inAccessBody (PortLinkAccess _ link) = [link]
data NetworkPortInfo = NetworkPortInfo {
networkPortName :: String,
networkPortSense :: Sense,
networkPortIsArrayed :: Bool }
deriving Show
data TeakCompInfo = TeakCompInfo {
teakCompShortName :: String,
teakCompTest :: NetworkComp -> Bool,
teakCompPortInfo :: [NetworkPortInfo] }
nwTeakCompInfo :: TeakCompType -> TeakCompInfo
nwTeakCompInfo typ = body typ
where
port = NetworkPortInfo
body (TeakJ {}) = TeakCompInfo "j" isTeakJ [port "i" Passive True, port "o" Active False]
body (TeakM {}) = TeakCompInfo "m" isMerge [port "i" Passive True, port "o" Active False]
body (TeakF {}) = TeakCompInfo "f" isFork [port "i" Passive False, port "o" Active True]
body (TeakS {}) = TeakCompInfo "s" isSteer [port "i" Passive False, port "o" Active True]
body (TeakX {}) = TeakCompInfo "x" isMux [port "i" Passive True, port "s" Passive False,
port "o" Active False]
body (TeakO {}) = TeakCompInfo "o" isTeakO [port "i" Passive False, port "o" Active False]
body (TeakV {}) = TeakCompInfo "v" isTeakV
[port "wg" Passive True, port "wd" Active True, port "rg" Passive True, port "rd" Active True]
body (TeakA {}) = TeakCompInfo "a" isTeakA [port "i" Passive True, port "o" Active False]
body (TeakI {}) = TeakCompInfo "i" isTeakI [port "i" Passive False, port "o" Active False]
body (TeakR {}) = TeakCompInfo "r" isTeakR [port "o" Active False]
nwCompShortNameToSampleTeakType :: String -> Maybe TeakCompType
nwCompShortNameToSampleTeakType name = body (map toLower name)
where
body "j" = Just $ TeakJ
body "m" = Just $ TeakM
body "f" = Just $ TeakF []
body "s" = Just $ TeakS emptySlice []
body "x" = Just $ TeakX []
body "o" = Just $ TeakO []
body "v" = Just $ TeakV "" 0 [] [] []
body "a" = Just $ TeakA
body "i" = Just $ TeakI
body "r" = Just $ TeakR
body _ = Nothing
nwCompShortName :: NetworkComp -> String
nwCompShortName (TeakComp { nwTeakType = typ }) = teakCompShortName $ nwTeakCompInfo typ
nwCompShortName _ = ""
nwCompShortNameToTest :: String -> Maybe (NetworkComp -> Bool)
nwCompShortNameToTest name = do
sample <- nwCompShortNameToSampleTeakType name
return $ teakCompTest $ nwTeakCompInfo sample
nwCompPortNames :: NetworkComp -> [String]
nwCompPortNames comp = body comp
where
body (TeakComp {}) = map networkPortName $ teakCompPortInfo $ nwTeakCompInfo $ nwTeakType comp
body (InstanceComp { nwCompPorts = ports }) = map nwPortName ports
-- body comp = map show [0..length (nwCompPortSenses comp) - 1]
directionToSense :: Direction -> Sense
directionToSense Input = Passive
directionToSense Output = Active
nwCompPortSenses :: NetworkComp -> [Sense]
nwCompPortSenses comp = body comp
where
body (TeakComp {}) = map networkPortSense $ teakCompPortInfo $ nwTeakCompInfo $ nwTeakType comp
body (InstanceComp { nwCompPorts = ports }) = map (directionToSense . nwPortDirection) ports
-- body _ = []
nwCompPortCardinalities :: NetworkComp -> [Some ()]
nwCompPortCardinalities comp = body comp
where
isMany True = Many [()]
isMany False = One ()
body (TeakComp {}) = map (isMany . networkPortIsArrayed) $
teakCompPortInfo $ nwTeakCompInfo $ nwTeakType comp
body (InstanceComp { nwCompPorts = ports }) = replicate (length ports) (One ())
-- body _ = []
isFork :: NetworkComp -> Bool
isFork (TeakComp { nwTeakType = (TeakF {}) }) = True
isFork _ = False
isSteer :: NetworkComp -> Bool
isSteer (TeakComp { nwTeakType = (TeakS {}) }) = True
isSteer _ = False
isMux :: NetworkComp -> Bool
isMux (TeakComp { nwTeakType = (TeakX {}) }) = True
isMux _ = False
isTeakJ :: NetworkComp -> Bool
isTeakJ (TeakComp { nwTeakType = (TeakJ {}) }) = True
isTeakJ _ = False
isMerge :: NetworkComp -> Bool
isMerge (TeakComp { nwTeakType = (TeakM {}) }) = True
isMerge _ = False
isTeakA :: NetworkComp -> Bool
isTeakA (TeakComp { nwTeakType = (TeakA {}) }) = True
isTeakA _ = False
isTeakV :: NetworkComp -> Bool
isTeakV (TeakComp { nwTeakType = (TeakV {}) }) = True
isTeakV _ = False
isTeakO :: NetworkComp -> Bool
isTeakO (TeakComp { nwTeakType = (TeakO {}) }) = True
isTeakO _ = False
isTeakI :: NetworkComp -> Bool
isTeakI (TeakComp { nwTeakType = (TeakI {}) }) = True
isTeakI _ = False
isTeakR :: NetworkComp -> Bool
isTeakR (TeakComp { nwTeakType = (TeakR {}) }) = True
isTeakR _ = False
isInstanceComp :: NetworkComp -> Bool
isInstanceComp (InstanceComp {}) = True
isInstanceComp _ = False
-- nwConnectedComps : returns all the components reachable from the given
-- one to the requested depth
nwConnectedComps :: NetworkIF network => Int -> NetworkCompRef -> NetworkMonad network [NetworkCompRef]
nwConnectedComps depth comp = liftM Map.keys $ body depth Map.empty comp
where
body depth visited comp
| depth <= 0 || alreadyVisited comp visited depth = return visited
| otherwise = do
newComps <- connectedComps1 comp
foldM (body (depth - 1)) (Map.insert comp depth visited) newComps
alreadyVisited thisComp visited depth = fromMaybe False $ do
lastDepth <- Map.lookup thisComp visited
return $ lastDepth >= depth
connectedComps1 compRef = do
comp <- nwGetComp compRef
if isJust comp
then do
let links = nwCompLinks (fromJust comp)
liftM concat $ mapM linkComps $ concatMap flattenSome links
else return []
linkComps link = do
pas <- nwLinkToComp Passive link
act <- nwLinkToComp Active link
return $ map (refComp . fst) $ catMaybes [pas, act]
makeUsage :: Sense -> (Int, NetworkLinkConn) -> (Int, NetworkLinkUsage)
makeUsage Passive (i, conn) = (i, NetworkLinkUsage conn NoConn)
makeUsage Active (i, conn) = (i, NetworkLinkUsage NoConn conn)
nwCompLinkUsage :: NetworkComp -> [(Int, NetworkLinkUsage)]
nwCompLinkUsage comp = concatMap makePortUsage $ zip3 [0..] (nwCompPortSenses comp) (nwCompLinks comp)
where
compNo = refComp comp
makePortUsage (linkPos, sense, One (Link linkNo)) = [makeUsage sense (linkNo, LinkComp compNo [linkPos])]
makePortUsage (linkPos, sense, Many links) = map (makeUsage sense . makeMany) $ zip [0..] links
where makeMany (linkPos2, (Link linkNo)) = (linkNo, LinkComp compNo [linkPos, linkPos2])
makePortUsage _ = error "nwCompLinkUsage makePortUsage: can't happen"
nwReplaceLinkInComp :: NetworkComp -> [Int] -> NetworkLinkRef -> NetworkComp
nwReplaceLinkInComp comp addr link = comp { nwCompLinks = links' }
where Some links' = replaceElemInSome addr link (Some (nwCompLinks comp))
nwAccessLinkUsage :: Int -> Access -> [(Int, NetworkLinkUsage)]
nwAccessLinkUsage bodyOffset (Access ref bodys) = concatMap makeAccessUsage $ zip [bodyOffset..] bodys
where
makeAccessUsage (bodyNo, access) = body access
where
mkAccess link sense addr = makeUsage sense (link, LinkAccess ref (bodyNo:addr))
-- body returns usage for passive/active connections of the
-- relative to the unplaced components which form the access implementation.
-- For example, ChanInput has a passive go (sourced from the circuit to the unplaced
-- portion) and a data-carrying active done
body (ChanInputAccess (Link go) (Link done)) = [
mkAccess go Passive [0],
mkAccess done Active [1] ]
body (ChanOutputAccess (Link go) (Link done)) = [
mkAccess go Passive [0],
mkAccess done Active [1] ]
body (ChanBareInputAccess (Link dataLink)) = [mkAccess dataLink Active [0]]
body (ChanBareOutputAccess (Link dat)) = [mkAccess dat Passive [0]]
-- variable accesses
body (VarAccess Read (Link ctrlLink) (Link dataLink) _) = [
mkAccess dataLink Active [1],
mkAccess ctrlLink Passive [0] ]
body (VarAccess Write (Link ctrlLink) (Link dataLink) _) = [
mkAccess ctrlLink Active [0],
mkAccess dataLink Passive [1] ]
body (SharedCallAccess (Link go) (Link done)) = [
mkAccess go Passive [0],
mkAccess done Active [1] ]
-- ports are viewed from the environment, hence the sense inversion
body (PortLinkAccess sense (Link link)) = [mkAccess link (invertSense sense) [0]]
nwReplaceLinkInAccess :: Access -> [Int] -> NetworkLinkRef -> Access
nwReplaceLinkInAccess (Access ref bodys) (bodyNo:addr) link = Access ref bodys'
where
bodys' = replaceAt bodys bodyNo $ replace (bodys !! bodyNo) addr
replace (ChanInputAccess _ done) [0] = ChanInputAccess link done
replace (ChanInputAccess go _) [1] = ChanInputAccess go link
replace (ChanBareInputAccess _) [0] = ChanBareInputAccess link
replace (ChanOutputAccess _ done) [0] = ChanOutputAccess link done
replace (ChanOutputAccess go _) [1] = ChanOutputAccess go link
replace (ChanBareOutputAccess _) [0] = ChanBareOutputAccess link
replace (VarAccess Read _ dataLink range) [0] = VarAccess Read link dataLink range
replace (VarAccess Read ctrlLink _ range) [1] = VarAccess Read ctrlLink link range
replace (SharedCallAccess _ done) [0] = SharedCallAccess link done
replace (SharedCallAccess go _) [1] = SharedCallAccess go link
replace (PortLinkAccess sense _) [0] = PortLinkAccess sense link
replace body addr = error $ "nwReplaceLinkInAccess: can't replace " ++ show body ++ " " ++ show addr
nwReplaceLinkInAccess _ _ _ = error "nwReplaceLinkInAccess: need port number"
escDoubleQuote :: String -> String
escDoubleQuote str = concatMap escChar str
where
escChar '"' = ['\\', '"']
escChar chr = [chr]
prettyPrintOSlice :: Int -> [(Int, TeakOTerm)] -> (Int -> ShowS) -> TeakOSlice -> String
prettyPrintOSlice prec terms inputName (index,slice) =
showParen (prec > thisPrec) (showString $ prefix
++ (if wholeSlice then "" else verilogShowSlice slice "")
) ""
where
thisPrec
| wholeSlice = prec
| otherwise = 10
prefix
| index == 0 = inputName (thisPrec + 1) ""
| isNothing term = "?" ++ show index
| otherwise = "t" ++ show index
term = lookup index terms
wholeSlice = index /= 0 && sliceOffset slice == 0 &&
isJust term && sliceWidth slice == oTermResultWidth (fromJust term)
prettyPrintSubterm :: Int -> [(Int, TeakOTerm)] -> (Int -> ShowS) -> [Int] -> Bool -> TeakOSlice -> String
prettyPrintSubterm prec terms inputName _ _ slice@(0,_) = prettyPrintOSlice prec terms inputName slice
prettyPrintSubterm prec terms inputName noDescendSlices inPrint (index,slice)
| isNothing maybeTerm = "?"
| termWidth == sliceWidth slice && sliceOffset slice == 0 =
prettyPrintOTerm prec terms inputName noDescendSlices inPrint (index, term)
| otherwise = showParen (prec > thisPrec) (showString $
prettyPrintOTerm (thisPrec + 1) terms inputName noDescendSlices False (index, term) ++
verilogShowSlice slice ""
) ""
where
thisPrec = 10
maybeTerm = lookup index terms
Just term = maybeTerm
termWidth = oTermResultWidth term
prettyPrintOTermPrec :: TeakOTerm -> Int
prettyPrintOTermPrec (TeakOp op _) = prettyPrintTeakOpPrec op
prettyPrintOTermPrec (TeakOMux {}) = 0
prettyPrintOTermPrec _ = 10
prettyPrintTeakOpPrec :: TeakOp -> Int
prettyPrintTeakOpPrec TeakOpAdd = 6
prettyPrintTeakOpPrec TeakOpSub = 6
prettyPrintTeakOpPrec TeakOpAnd = 3
prettyPrintTeakOpPrec TeakOpOr = 2
prettyPrintTeakOpPrec TeakOpXor = 2
prettyPrintTeakOpPrec TeakOpNot = 10
prettyPrintTeakOpPrec TeakOpSignedGT = 4
prettyPrintTeakOpPrec TeakOpSignedGE = 4
prettyPrintTeakOpPrec TeakOpUnsignedGT = 4
prettyPrintTeakOpPrec TeakOpUnsignedGE = 4
prettyPrintTeakOpPrec TeakOpEqual = 4
prettyPrintTeakOpPrec TeakOpNotEqual = 4
prettyPrintOTerm :: Int -> [(Int, TeakOTerm)] -> (Int -> ShowS) -> [Int] -> Bool -> (Int, TeakOTerm) -> String
prettyPrintOTerm prec terms inputName noDescendSlices inPrint (index, term) = paren $ case term of
TeakOConstant width constant
| intWidth constant == width -> show constant
| otherwise -> show width ++ "'d" ++ show constant
TeakOAppend count slices
| count == 1 && length slices == 1 -> subTerm 0 (head slices)
| otherwise -> (if count == 1 then "" else show count) ++
"{" ++ joinWith "," (map (subTerm 0) (reverse slices)) ++ "}"
TeakOMux spec (choiceSlice:slices) -> "case " ++ subTerm 0 choiceSlice ++ " of " ++
joinWith " | " (map makeTerm $ zip spec slices)
where makeTerm (imps, slice) = joinWith "," (map (showImp True True 4) imps) ++ " -> " ++ subTerm 0 slice
TeakOp TeakOpNot [slice] -> "not " ++ subTerm (thisPrec + 1) slice
TeakOp binOp [sliceL, sliceR] -> subTerm (thisPrec + 1) sliceL ++ " " ++ snd (teakOOpNames binOp) ++ " " ++
subTerm (thisPrec + 1) sliceR
TeakOBuiltin "StringAppend" _ _ [str1, str2]
| inPrint -> subTerm 0 str1 ++ ", " ++ subTerm 0 str2
TeakOBuiltin "ToString" _ [TeakParamType typ] [slice] -> "$#(" ++ showTypeName [] typ ++ ")(" ++
subTerm 0 slice ++ ")"
TeakOBuiltin "String" _ [TeakParamString str] _ -> "\"" ++ escDoubleQuote str ++ "\""
TeakOBuiltin "tWriteMessage" _ _ [slice] -> "print " ++ subTermInPrint 0 slice
TeakOBuiltin name _ [] slices -> builtinName name ++ " (" ++ joinWith "," (map (subTerm 0) slices) ++ ")"
TeakOBuiltin name _ params slices -> builtinName name ++
" #(" ++ joinWith "," (map showParam params) ++ ")" ++
" (" ++ joinWith "," (map (subTerm 0) slices) ++ ")"
_ -> error $ "prettyPrintOTerm: unhandled term `" ++ show term ++ "'"
where
thisPrec = prettyPrintOTermPrec term
paren str = showParen (prec > thisPrec) (showString str) ""
subTerm prec slice@(subIndex, _)
| subIndex > index = "?" ++ show slice
| subIndex `elem` noDescendSlices = prettyPrintOSlice prec terms inputName slice
| otherwise = prettyPrintSubterm prec terms inputName noDescendSlices inPrint slice
subTermInPrint prec slice@(subIndex, _)
| subIndex > index = "?" ++ show slice
| subIndex `elem` noDescendSlices = prettyPrintOSlice prec terms inputName slice
| otherwise = prettyPrintSubterm prec terms inputName noDescendSlices True slice
showParam (TeakParamType typ) = "type " ++ showTypeName [] typ
showParam (TeakParamInt int) = show int
showParam (TeakParamString str) = "\"" ++ escDoubleQuote str ++ "\""
builtinName = id
prettyPrintOTerms :: Int -> (Int -> ShowS) -> [(Int, TeakOTerm)] -> [String]
prettyPrintOTerms _ _ [] = []
prettyPrintOTerms prec inputName terms = mapMaybe showTerm sharedSlices ++
[prettyPrintOTerm prec terms inputName sharedSlices False (last terms)]
where
sharedSlices = map snd $ filter ((> 1) . fst) $ frequencyBy (==) $
map oSliceIndex $ concatMap (oTermExtractSlices . snd) terms
showTerm 0 = Nothing
showTerm i
| isNothing term = Just $ "t" ++ show i ++ " = bad slice ref"
| otherwise = Just $ "t" ++ show i ++ " = " ++
prettyPrintOTerm 0 terms inputName sharedSlices False (i, fromJust term)
where term = lookup i terms
instance Show NetworkLinkRef where
showsPrec _ (Link link) = showString "L" . shows link
instance Show NetworkCompRef where
showsPrec _ (Comp comp) = showString "C" . shows comp
instance Read NetworkLinkRef where
readsPrec _ = readParen False readNetworkLinkRef
instance Read NetworkLinkUsage where
readsPrec _ = readParen False readNetworkLinkUsage
instance Read NetworkCompRef where
readsPrec _ = readParen False readNetworkCompRef
instance Show NetworkLink where
showsPrec prec (NetworkLink index width latching) = showParen (prec > applyPrecedence) $
showString "NetworkLink " . shows (Link index) . space . shows width . space . showsPrec 11 latching
instance Show Latching where
showsPrec prec (HalfBuffer depth) = showParen (prec > applyPrecedence) $
showString "HalfBuffer " . shows depth
instance Read NetworkLink where
readsPrec _ = readParen False readNetworkLink
instance Read Latching where
readsPrec _ = readParen False readLatching
instance Show NetworkComp where
showsPrec prec comp = showsPrecTab prec 0 comp
instance Show TeakCompType where
showsPrec prec comp = showsPrecTab prec 0 comp
instance ShowTab TeakOTerm where
showListTab = showListWithComment showDropListWith False (shows . (+1))
instance Show NetworkLinkUsage where
showsPrec prec (NetworkLinkUsage passive active) = showParen (prec > applyPrecedence) $
showString "NetworkLinkUsage " . showsPrec 11 passive . space . showsPrec 11 active
instance Show TeakOTerm where
showsPrec prec term = showParen (prec > applyPrecedence) $ body term
where
body (TeakOConstant width value) = showString "TeakOConstant " . shows width . space . shows value
body (TeakOAppend count slices) = showString "TeakOAppend " . shows count . space . shows slices
body (TeakOBuiltin builtin width params slices) = showString "TeakOBuiltin " . shows builtin .
space . shows width . space . shows params . space . shows slices
body (TeakOp op slices) = showString "TeakOp " . shows op . space . shows slices
body (TeakOMux spec slices) = showString "TeakOMux " . shows spec . space . shows slices
instance ShowTab NetworkComp where
showsPrecTab prec tabs (TeakComp i typ links pos) = showParen (prec > applyPrecedence) $
showString "TeakComp " . shows (Comp i) . space . showsPrecTab 11 (tabs + 1) typ . space . shows links .
space . showsPrec 11 pos
showsPrecTab prec _ (InstanceComp i name ports links pos) = showParen (prec > applyPrecedence) $
showString "InstanceComp " . shows (Comp i) . space . shows name . space . shows ports . space .
shows links . space . showsPrec 11 pos
instance ShowTab TeakCompType where
showListTab = showListWithComment showBlockListWith False shows
showsPrecTab prec tabs typ = showParen (prec > applyPrecedence) $ body typ
where
body TeakA = showString "TeakA"
body (TeakF offsets) = showString "TeakF " . shows offsets
body TeakJ = showString "TeakJ"
body TeakM = showString "TeakM"
body (TeakO terms) = showString "TeakO " . showsPrecTab 11 tabs terms
body (TeakS slice matches) = showString "TeakS " . showsPrec 11 slice . space . shows matches
body (TeakX matches) = showString "TeakX " . shows matches
body (TeakV name width bOffsets wOffsets rOffsets) = showString "TeakV " .
shows name . space . shows width . space .
shows bOffsets . space . shows wOffsets . space . shows rOffsets
body TeakI = showString "TeakI"
body TeakR = showString "TeakR"
instance Read NetworkComp where
readsPrec _ = readParen False readNetworkComp
instance Show NetworkPort where
showsPrec prec (NetworkPort name direction width ref) = showParen (prec > applyPrecedence) $
showString "NetworkPort " . shows name . space .
shows direction . space . shows width . space . shows ref
where
shows :: Show a => a -> ShowS
shows = showsPrec (applyPrecedence + 1)
instance Read NetworkPort where
readsPrec _ = readParen False readNetworkPort
instance ShowTab NetworkLink where
showListTab = showBlockList
instance ShowTab NetworkLinkUsage where
showListTab = showBlockList
instance ShowTab NetworkLinkRef where
showListTab = showBlockList
instance Show Access where
showsPrec prec (Access ref bodys) = showParen (prec > applyPrecedence) $
showString "Access " . showsPrec 11 ref . space . showList bodys
instance ShowTab Access where
showListTab = showBlockList
instance Read Access where
readsPrec _ = readParen False readAccess
instance Read AccessBody where
readsPrec _ = readParen False readAccessBody
readAccess :: String -> [(Access, String)]
readAccess str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"Access" -> readFields fields (Access GoAccess []) rest
where fields = [
ReadField "accessRef" readsC (\o f -> o { accessRef = f }),
ReadField "accessBodys" readListC (\o f -> o { accessBodys = f }) ]
_ -> Nothing
initLink :: NetworkLinkRef
initLink = Link 0
readAccessBody :: String -> [(AccessBody, String)]
readAccessBody str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"ChanInputAccess" -> readFields fields (ChanInputAccess initLink initLink) rest
where fields = [
ReadField "chanAccessGo" readsC (\o f -> o { chanAccessGo = f }),
ReadField "chanAccessDone" readsC (\o f -> o { chanAccessDone = f }) ]
"ChanOutputAccess" -> readFields fields (ChanOutputAccess initLink initLink) rest
where fields = [
ReadField "chanAccessGo" readsC (\o f -> o { chanAccessGo = f }),
ReadField "chanAccessDone" readsC (\o f -> o { chanAccessDone = f }) ]
"ChanBareOutputAccess" -> readFields fields (ChanBareOutputAccess initLink) rest
where fields = [
ReadField "chanAccessData" readsC (\o f -> o { chanAccessData = f }) ]
"ChanBareInputAccess" -> readFields fields (ChanBareInputAccess initLink) rest
where fields = [
ReadField "chanAccessData" readsC (\o f -> o { chanAccessData = f }) ]
"VarAccess" -> readFields fields (VarAccess Read initLink initLink emptySlice) rest
where fields = [
ReadField "accessRW" readsC (\o f -> o { accessRW = f }),
ReadField "accessCtrl" readsC (\o f -> o { accessCtrl = f }),
ReadField "accessData" readsC (\o f -> o { accessData = f }),
ReadField "accessRange" readsC (\o f -> o { accessRange = f }) ]
"SharedCallAccess" -> readFields fields (SharedCallAccess initLink initLink) rest
where fields = [
ReadField "accessGo" readsC (\o f -> o { accessGo = f }),
ReadField "accessDone" readsC (\o f -> o { accessDone = f }) ]
"PortLinkAccess" -> readFields fields (PortLinkAccess Passive initLink) rest
where fields = [
ReadField "accessSense" readsC (\o f -> o { accessSense = f }),
ReadField "accessLink" readsC (\o f -> o { accessLink = f }) ]
_ -> Nothing
instance Show AccessBody where
showsPrec prec accessBody = showParen (prec > applyPrecedence) (body accessBody)
where
shows e = space . showsPrec 11 e
body (ChanInputAccess go done) = showString "ChanInputAccess" . shows go . shows done
body (ChanOutputAccess go done) = showString "ChanOutputAccess" . shows go . shows done
body (ChanBareOutputAccess dat) = showString "ChanBareOutputAccess" . shows dat
body (ChanBareInputAccess dat) = showString "ChanBareInputAccess" . shows dat
body (VarAccess rw ctrlLink dataLink range) =
showString "VarAccess" . shows rw . shows ctrlLink . shows dataLink . shows range
body (SharedCallAccess go done) = showString "SharedCallAccess" . shows go . shows done
body (PortLinkAccess sense link) = showString "PortLinkAccess" . shows sense . shows link
instance ShowTab NetworkPort where
showListTab = showBlockList
instance ShowTab TeakParam
instance Show NetworkProperty where
showsPrec prec comp = showsPrecTab prec 0 comp
instance ShowTab NetworkProperty where
showsPrecTab prec _ (NetworkComment str) = showParen (prec > applyPrecedence) $
showString "NetworkComment " . shows str
showsPrecTab prec tabs (NetworkPosArray poss) = showParen (prec > applyPrecedence)
$ showString "NetworkPosArray " . showsPrecTab 11 tabs poss
showsPrecTab prec _ (NetworkLinkNames names) = showParen (prec > applyPrecedence)
$ showString "NetworkLinkNames (" . shows names . showString ")"
showsPrecTab prec tabs (NetworkAttrs attrs) = showParen (prec > applyPrecedence)
$ showString "NetworkAttrs " . showDropListWith showAttr tabs attrs
where
showAttr tabs (name, value) = showString "(" . shows name .
showString ", " . showsPrecTab 0 tabs value . showString ")"
readNetworkLinkRef :: String -> [(NetworkLinkRef, String)]
readNetworkLinkRef str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"Link" -> readFields fields (Link 0) rest
where fields = [
ReadField "nwLink" readsC (\o f -> o { nwLink = f }) ]
'L':num | all isDigit num -> return (Link $ read num, rest)
_ -> Nothing
readNetworkCompRef :: String -> [(NetworkCompRef, String)]
readNetworkCompRef str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"Comp" -> readFields fields (Comp 0) rest
where fields = [
ReadField "nwComp" readsC (\o f -> o { nwComp = f }) ]
'C':num | all isDigit num -> return (Comp $ read num, rest)
_ -> Nothing
readNetworkLink :: String -> [(NetworkLink, String)]
readNetworkLink str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"NetworkLink" -> readFields fields (NetworkLink 0 0 (HalfBuffer 0)) rest
where fields = [
ReadField "nwLinkIndex" readsC (\o f -> o { nwLinkIndex = nwLink f }),
ReadField "nwLinkWidth" readsC (\o f -> o { nwLinkWidth = f }),
ReadField "nwLinkLatching" readsC (\o f -> o { nwLinkLatching = f }) ]
_ -> Nothing
readLatching :: String -> [(Latching, String)]
readLatching str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"HalfBuffer" -> readFields fields (HalfBuffer 0) rest
where fields = [
ReadField "latchingDepth" readsC (\o f -> o { latchingDepth = f }) ]
_ -> Nothing
readNetworkLinkUsage :: String -> [(NetworkLinkUsage, String)]
readNetworkLinkUsage str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"NetworkLinkUsage" -> readFields fields nwNoLinkUsage rest
where fields = [
ReadField "nwPassiveLinkUsage" readsC (\o f -> o { nwPassiveLinkUsage = f }),
ReadField "nwActiveLinkUsage" readsC (\o f -> o { nwActiveLinkUsage = f }) ]
_ -> Nothing
readNetworkComp :: String -> [(NetworkComp, String)]
readNetworkComp str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"TeakComp" -> readFields fields (TeakComp 0 TeakA [] NoPos) rest
where fields = [
ReadField "nwCompIndex" readsC (\o f -> o { nwCompIndex = nwComp f }),
ReadField "nwTeakType" readsC (\o f -> o { nwTeakType = f }),
ReadField "nwCompLinks" readListC (\o f -> o { nwCompLinks = f }),
ReadField "nwCompPos" readsC (\o f -> o { nwCompPos = f }) ]
"InstanceComp" -> readFields fields (InstanceComp 0 "" [] [] NoPos) rest
where fields = [
ReadField "nwCompIndex" readsC (\o f -> o { nwCompIndex = nwComp f }),
ReadField "nwPartName" readsC (\o f -> o { nwPartName = f }),
ReadField "nwCompPorts" readListC (\o f -> o { nwCompPorts = f }),
ReadField "nwCompLinks" readListC (\o f -> o { nwCompLinks = f }),
ReadField "nwCompPos" readsC (\o f -> o { nwCompPos = f }) ]
_ -> Nothing
readNetworkPort :: String -> [(NetworkPort, String)]
readNetworkPort str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"NetworkPort" -> readFields fields (NetworkPort "" Input 0 Nothing) rest
where fields = [
ReadField "nwPortName" readsC (\o f -> o { nwPortName = f }),
ReadField "nwPortDirection" readsC (\o f -> o { nwPortDirection = f }),
ReadField "nwPortWidth" readsC (\o f -> o { nwPortWidth = f }),
ReadField "nwPortRef" readsC (\o f -> o { nwPortRef = f }) ]
_ -> Nothing
instance Read TeakOTerm where
readList = readListC
readsPrec _ = readParen False readTeakOTerm
readTeakOTerm :: String -> [(TeakOTerm, String)]
readTeakOTerm str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"TeakOConstant" -> readFields fields (TeakOConstant 1 0) rest
where fields = [
ReadField "teakOWidth" readsC (\o f -> o { teakOWidth = f }),
ReadField "teakOValue" readsC (\o f -> o { teakOValue = f }) ]
"TeakOAppend" -> readFields fields (TeakOAppend 1 []) rest
where fields = [
ReadField "teakOCount" readsC (\o f -> o { teakOCount = f }),
ReadField "teakOSlices" readListC (\o f -> o { teakOSlices = f }) ]
"TeakOBuiltin" -> readFields fields (TeakOBuiltin "" 0 [] []) rest
where fields = [
ReadField "teakOBuiltin" readsC (\o f -> o { teakOBuiltin = f }),
ReadField "teakOWidth" readsC (\o f -> o { teakOWidth = f }),
ReadField "teakOParams" readListC (\o f -> o { teakOParams = f }),
ReadField "teakOSlices" readListC (\o f -> o { teakOSlices = f }) ]
"TeakOp" -> readFields fields (TeakOp TeakOpAdd []) rest
where fields = [
ReadField "teakOOp" readsC (\o f -> o { teakOOp = f }),
ReadField "teakOSlices" readListC (\o f -> o { teakOSlices = f }) ]
"TeakOMux" -> readFields fields (TeakOMux [] []) rest
where fields = [
ReadField "teakOSpec" readsC (\o f -> o { teakOSpec = f }),
ReadField "teakOSlices" readListC (\o f -> o { teakOSlices = f }) ]
_ -> Nothing
newtype {- NetworkIF network => -}
NetworkMonad network a = NetworkMonad { networkMonadM :: State network a }
instance NetworkIF network => Functor (NetworkMonad network) where
fmap = liftM
instance NetworkIF network => Applicative (NetworkMonad network) where
pure = return
(<*>) = ap
instance NetworkIF network => Monad (NetworkMonad network) where
l >>= k = NetworkMonad $ (networkMonadM l) >>= k'
where k' v = networkMonadM $ k v
return r = NetworkMonad $ return r
fail str = NetworkMonad $ fail str
class ShowTab network => NetworkIF network where
nwAddAccess :: Access -> NetworkMonad network ()
nwAddComp :: NetworkComp -> NetworkMonad network NetworkComp
nwAddLink :: NetworkLink -> NetworkMonad network NetworkLink
nwGetAccesses :: NetworkMonad network [Access]
nwGetComp :: NetworkCompRef -> NetworkMonad network (Maybe NetworkComp)
nwGetCompBounds :: NetworkMonad network (Int,Int)
nwGetLink :: NetworkLinkRef -> NetworkMonad network NetworkLink
nwGetLinkBounds :: NetworkMonad network (Int,Int)
nwSetProperties :: [NetworkProperty] -> NetworkMonad network ()
nwGetProperties :: NetworkMonad network [NetworkProperty]
nwGetLinkUsage :: Sense -> NetworkLinkRef -> NetworkMonad network (Maybe NetworkLinkConn)
nwLinkIsValid :: NetworkLinkRef -> NetworkMonad network Bool
nwNewNetwork :: network
nwRemoveAccess :: AccessRef -> NetworkMonad network (Maybe Access)
nwRemoveCompRef :: NetworkCompRef -> NetworkMonad network ()
nwRemoveLinkRef :: NetworkLinkRef -> NetworkMonad network (Maybe NetworkLink)
nwUpdateComp :: NetworkComp -> NetworkMonad network ()
nwUpdateLink :: NetworkLink -> NetworkMonad network ()
data Part network = Part {
networkName :: String,
networkPorts :: [NetworkPort],
networkBody :: network }
nwAddProperty :: NetworkIF network => NetworkProperty -> NetworkMonad network ()
nwAddProperty prop = do
props <- nwGetProperties
nwSetProperties (prop:props)
nwFindPartIndex :: [Part network] -> String -> Maybe Int
nwFindPartIndex parts name = findIndex ((== name) . networkName) parts
nwFindPart :: [Part network] -> String -> Maybe (Part network)
nwFindPart parts name = do
i <- nwFindPartIndex parts name
return $ parts !! i
nwAddLinkRef :: NetworkIF network => NetworkLink -> NetworkMonad network NetworkLinkRef
nwAddLinkRef link = liftM refLink $ nwAddLink link
-- nwNewLink : create and add new push link of the given width
nwNewLink :: NetworkIF network => Int -> NetworkMonad network NetworkLink
nwNewLink width = nwAddLink $ NetworkLink 0 width $ HalfBuffer 0
nwNewLinkRef :: NetworkIF network => Int -> NetworkMonad network NetworkLinkRef
nwNewLinkRef width = liftM refLink $ nwNewLink width
nwAddPortAccess :: NetworkIF network => Sense -> AccessRef -> NetworkLinkRef -> NetworkMonad network ()
nwAddPortAccess sense ref link = nwAddAccess $ Access ref [PortLinkAccess sense link]
nwGetLinkWidth :: NetworkIF network => NetworkLinkRef -> NetworkMonad network Int
nwGetLinkWidth ref = liftM nwLinkWidth $ nwGetLink ref
nwGetLinkLatching :: NetworkIF network => NetworkLinkRef -> NetworkMonad network Latching
nwGetLinkLatching ref = liftM nwLinkLatching $ nwGetLink ref
portAccessLinks :: Access -> [NetworkLinkRef]
portAccessLinks access = map accessLink (accessBodys access)
nwMapComps :: NetworkIF network => (NetworkComp -> NetworkMonad network r) -> NetworkMonad network [r]
nwMapComps f = liftM reverse $ nwFoldComps f' []
where f' acc comp = do
r <- f comp
return (r:acc)
nwMapLinks :: NetworkIF network => (NetworkLink -> NetworkMonad network r) -> NetworkMonad network [r]
nwMapLinks f = do
linkBounds <- nwGetLinkBounds
liftM catMaybes $ mapM f' (range linkBounds)
where
f' i = do
unused <- nwLinkIsUnused (Link i)
if unused
then return Nothing
else do
decl <- nwGetLink (Link i)
liftM Just $ f decl
nwMapLinks_ :: NetworkIF network => (NetworkLink -> NetworkMonad network r) -> NetworkMonad network ()
nwMapLinks_ f = nwMapLinks f >> return ()
nwFoldLinks :: NetworkIF network => (a -> NetworkLink -> NetworkMonad network a) -> a -> NetworkMonad network a
nwFoldLinks f a = do
linkBounds <- nwGetLinkBounds
foldM f' a (range linkBounds)
where
f' a i = do
unused <- nwLinkIsUnused (Link i)
if unused
then return a
else do
decl <- nwGetLink (Link i)
f a decl
nwRemoveComp :: NetworkIF network => NetworkComp -> NetworkMonad network ()
nwRemoveComp = nwRemoveCompRef . refComp
nwMapCompsIf_ :: NetworkIF network =>
(NetworkComp -> NetworkMonad network Bool) ->
(NetworkComp -> NetworkMonad network r) -> NetworkMonad network ()
nwMapCompsIf_ p f = do
nwMapCompsIf p f
return ()
nwMapCompsIf :: NetworkIF network =>
(NetworkComp -> NetworkMonad network Bool) ->
(NetworkComp -> NetworkMonad network r) -> NetworkMonad network [r]
nwMapCompsIf p f = liftM reverse $ nwFoldComps f' []
where
f' ret comp = do
predResult <- p comp
if predResult
then do
r <- f comp
return (r:ret)
else return ret
nwFoldCompsIf :: NetworkIF network =>
(NetworkComp -> NetworkMonad network Bool) ->
(a -> NetworkComp -> NetworkMonad network a) -> a -> NetworkMonad network a
nwFoldCompsIf p f a = nwFoldComps f' a
where
f' a comp = do
predResult <- p comp
if predResult
then f a comp
else return a
nwGetPortAccess :: NetworkIF network => AccessRef -> NetworkMonad network [NetworkLinkRef]
nwGetPortAccess ref = do
access <- nwGetAccess ref
return (maybe [] portAccessLinks access)
nwRemovePortAccess :: NetworkIF network => AccessRef -> NetworkMonad network [NetworkLinkRef]
nwRemovePortAccess ref = do
access <- nwRemoveAccess ref
return (maybe [] portAccessLinks access)
nwLinkIsPort :: NetworkIF network => NetworkLinkRef -> NetworkMonad network Bool
nwLinkIsPort link = do
p <- linkIsPort Passive
a <- linkIsPort Active
return $ p || a
where
linkIsPort sense = do
usage <- nwGetLinkUsage sense link
if isJust usage
then do
let maybeRef = isAccessLink (fromJust usage)
if isJust maybeRef
then do
access <- nwGetAccess (fromJust maybeRef)
return $ isPortLinkAccess $ fromJust access
else return False
else return False
isAccessLink (LinkAccess ref _) = Just ref
isAccessLink _ = Nothing
isPortLinkAccess (Access _ [PortLinkAccess {}]) = True
isPortLinkAccess _ = False
isLinkComp :: Maybe NetworkLinkConn -> Bool
isLinkComp (Just (LinkComp {})) = True
isLinkComp _ = False
nwLinkToComp :: NetworkIF network => Sense -> NetworkLinkRef ->
NetworkMonad network (Maybe (NetworkComp, [Int]))
nwLinkToComp sense link = do
conn <- nwGetLinkUsage sense link
if isLinkComp conn
then do
let Just (LinkComp compNo addr) = conn
comp <- nwGetComp compNo
when (isNothing comp) $
error $ "nwLinkToCompUsage: no component at compNo " ++ show compNo
return $ Just (fromJust comp, addr)
else return Nothing
nwLinkToCompIf :: NetworkIF network => Sense ->
(NetworkComp -> NetworkMonad network Bool) ->
NetworkLinkRef -> NetworkMonad network (Maybe (NetworkComp, [Int]))
nwLinkToCompIf sense pred link = do
usage <- nwLinkToComp sense link
if isJust usage
then do
let Just (comp, _) = usage
predResult <- pred comp
if predResult
then return usage
else return Nothing
else return Nothing
-- nwReplaceLinkAtConn : replace the link referenced by conn with the new given link
nwReplaceLinkAtConn :: NetworkIF network => NetworkLinkConn -> NetworkLinkRef ->
NetworkMonad network ()
nwReplaceLinkAtConn conn link = do
case conn of
LinkComp compNo addr -> do
Just comp <- nwGetComp compNo
nwUpdateComp (nwReplaceLinkInComp comp addr link)
LinkAccess ref addr -> do
Just access <- nwGetAccess ref
nwRemoveAccess ref
nwAddAccess (nwReplaceLinkInAccess access addr link)
NoConn -> error "nwReplaceLinkAtConn: no conn"
return ()
-- nwBreakLink : break the given link into 2 halves. The active component end will be
-- the original link, and passive component end will be a new link. Returns (active,passive)
-- link pair with their passive and active ends. respectively, unconnected. The passive end
-- component will also be replaced with a new component
-- NB. At the moment this only works where both ends are connected to components
nwBreakLink :: NetworkIF network => NetworkLinkRef -> NetworkMonad network (NetworkLinkRef, NetworkLinkRef)
nwBreakLink link = do
width <- nwGetLinkWidth link
newLink <- nwNewLinkRef width
passiveUsage <- nwGetLinkUsage Passive link
case passiveUsage of
Just conn -> nwReplaceLinkAtConn conn newLink
Nothing -> error $ "nwBreakLink: passive end not connected " ++ show link
return (link, newLink)
nwNewTeakComp :: NetworkIF network => TeakCompType -> [Some NetworkLinkRef] -> Pos ->
NetworkMonad network NetworkComp
nwNewTeakComp typ links pos = nwAddComp $ TeakComp 0 typ links pos
nwGetPosArray :: NetworkIF network => NetworkMonad network (Maybe PosArray)
nwGetPosArray = do
properties <- nwGetProperties
let npa = find isPosArray properties
if isJust npa
then do
let Just (NetworkPosArray pa) = npa
return $ Just pa
else return Nothing
where
isPosArray (NetworkPosArray _) = True
isPosArray _ = False
nwGetLinkNames :: NetworkIF network => NetworkMonad network (Maybe (Map.Map NetworkLinkRef String))
nwGetLinkNames = do
properties <- nwGetProperties
return $ do
NetworkLinkNames names <- find isLinkNames properties
return names
isLinkNames :: NetworkProperty -> Bool
isLinkNames (NetworkLinkNames {}) = True
isLinkNames _ = False
nwGetLinkName :: NetworkIF network => NetworkLinkRef -> NetworkMonad network (Maybe String)
nwGetLinkName link = runMaybeT $ do
linkNames <- MaybeT $ nwGetLinkNames
MaybeT $ return $ Map.lookup link linkNames
nwSetLinkName :: NetworkIF network => NetworkLinkRef -> String -> NetworkMonad network ()
nwSetLinkName link name = do
properties <- nwGetProperties
let
NetworkLinkNames linkNames = fromMaybe (NetworkLinkNames Map.empty) $ find isLinkNames properties
linkNames' = Map.insert link name linkNames
nwSetProperties $ NetworkLinkNames linkNames' : filter (not . isLinkNames) properties
nwGetAttributeVal :: NetworkIF network => String -> NetworkMonad network (Maybe TeakParam)
nwGetAttributeVal attrName = do
properties <- nwGetProperties
return $ do
NetworkAttrs attrList <- find isAttrList properties
(_, val) <- find ((== attrName) . fst) attrList
return val
where
isAttrList (NetworkAttrs _) = True
isAttrList _ = False
nwRemoveUnusedLinks :: NetworkIF network => NetworkMonad network ()
nwRemoveUnusedLinks = do
linkBounds <- nwGetLinkBounds
mapM_ removeUnusedLink (range linkBounds)
where
removeUnusedLink i = do
unused <- nwLinkIsUnused (Link i)
when unused $ do
nwRemoveLinkRef (Link i)
return ()
nwRemapLink :: NetworkIF network => NetworkLinkRef -> NetworkLinkRef -> NetworkMonad network ()
nwRemapLink from to = do
activeFrom <- nwGetLinkUsage Active from
passiveFrom <- nwGetLinkUsage Passive from
when (isJust activeFrom) $ nwReplaceLinkAtConn (fromJust activeFrom) to
when (isJust passiveFrom) $ nwReplaceLinkAtConn (fromJust passiveFrom) to
nwRemoveLinkRef from
return ()
nwFoldComps :: NetworkIF network => (a -> NetworkComp -> NetworkMonad network a)
-> a -> NetworkMonad network a
nwFoldComps f acc = do
compBounds <- nwGetCompBounds
foldM visitComp acc (range compBounds)
where
visitComp a i = do
comp <- nwGetComp $ Comp i
if isJust comp
then do
a' <- f a (fromJust comp)
return a'
else return a
nwLinkIsUnused :: NetworkIF network => NetworkLinkRef -> NetworkMonad network Bool
nwLinkIsUnused link = do
pas <- nwGetLinkUsage Passive link
act <- nwGetLinkUsage Active link
return $ isNothing pas && isNothing act
nwGetAccess :: NetworkIF network => AccessRef -> NetworkMonad network (Maybe Access)
nwGetAccess ref = do
accesses <- nwGetAccesses
return $ nwFindAccess accesses ref
nwFindAccess :: [Access] -> AccessRef -> Maybe Access
nwFindAccess accesses ref = find (nwMatchAccess ref) accesses
nwFindPortIndexByRef :: [NetworkPort] -> AccessRef -> Maybe Int
nwFindPortIndexByRef ports ref = findIndex ((== Just ref) . nwPortRef) ports
nwFindPortByRef :: [NetworkPort] -> AccessRef -> Maybe NetworkPort
nwFindPortByRef ports ref = nwFindPortIndexByRef ports ref >>= return . (ports !!)
nwMatchAccess :: AccessRef -> Access -> Bool
nwMatchAccess ref1 (Access ref2 _) = ref1 == ref2
showPart :: (Int -> Int -> network -> ShowS) ->
Int -> Int -> Part network -> ShowS
showPart showNetwork prec tabs network = showParen (prec > applyPrecedence) (showBody network)
where
showBody (Part name ports body) = showString "Part " .
tabbedNL tabs . showChar '{' .
tabbedNL tabs' . showString "networkName = " . shows name . showChar ',' .
tabbedNL tabs' . showString "networkPorts = " . showListTab tabs' ports . showChar ',' .
tabbedNL tabs' . showString "networkBody = " . showNetwork prec' tabs' body .
tabbedNL tabs . showChar '}'
tabs' = tabs + 1
prec' = applyPrecedence + 1
readPart :: Read network => ReadS (Part network)
readPart str = maybeToList $ do
(headToken, rest) <- maybeLex str
case headToken of
"Part" -> readFields fields (Part "" [] undefined) rest
where fields = [
ReadField "networkName" readsC (\o f -> o { networkName = f }),
ReadField "networkPorts" readListC (\o f -> o { networkPorts = f }),
ReadField "networkBody" readsC (\o f -> o { networkBody = f }) ]
_ -> Nothing
instance (Read network) => Read (Part network) where
readsPrec _ = readParen False readPart
instance ShowTab network => ShowTab (Part network) where
showsPrecTab = showPart showsPrecTab
showListTab = showBlockList
instance ShowTab network => Show (Part network) where
showsPrec prec = showsPrecTab prec 0
runNetwork :: NetworkIF network => network -> NetworkMonad network a -> (a, network)
runNetwork nw nm = runState (networkMonadM nm) nw
runNetwork_ :: NetworkIF network => network -> NetworkMonad network a -> network
runNetwork_ nw nm = snd $ runNetwork nw nm
runNetwork0 :: NetworkIF network => NetworkMonad network a -> (a, network)
runNetwork0 nm = runNetwork nwNewNetwork nm
tryNetwork :: NetworkIF network => network -> NetworkMonad network a -> a
tryNetwork nw nm = fst $ runNetwork nw nm
runPart :: NetworkIF network =>
Part network -> NetworkMonad network r -> (r, Part network)
runPart (Part name ports body) f = (r, Part name ports body')
where (r, body') = runNetwork body f
runPart_ :: NetworkIF network =>
Part network -> NetworkMonad network r -> Part network
runPart_ part f = snd $ runPart part f
tryPart :: NetworkIF network =>
Part network -> NetworkMonad network r -> r
tryPart part f = fst $ runPart part f
nwFuncToNetworkMonad :: NetworkIF network => (network -> a) -> NetworkMonad network a
nwFuncToNetworkMonad f = NetworkMonad $ do
nw <- get
return $ f nw
addConn :: String -> NetworkLinkConn -> NetworkLinkConn -> NetworkLinkConn
addConn _ NoConn new = new
addConn _ old NoConn = old
addConn msg old new
| old /= new = error $ "addConn: " ++ msg ++ " " ++ show old ++ " " ++ show new
| otherwise = new
addConnUnsafe :: NetworkLinkConn -> NetworkLinkConn -> NetworkLinkConn
addConnUnsafe NoConn new = new
addConnUnsafe old NoConn = old
addConnUnsafe old _ = old
addUsagePair :: String -> NetworkLinkUsage -> NetworkLinkUsage -> NetworkLinkUsage
addUsagePair msg (NetworkLinkUsage pas1 act1) (NetworkLinkUsage pas2 act2) =
NetworkLinkUsage (addConn (msg ++ "(P)") pas1 pas2) (addConn (msg ++ "(A)") act1 act2)
addUsagePairUnsafe :: NetworkLinkUsage -> NetworkLinkUsage -> NetworkLinkUsage
addUsagePairUnsafe (NetworkLinkUsage pas1 act1) (NetworkLinkUsage pas2 act2) =
NetworkLinkUsage (addConnUnsafe pas1 pas2) (addConnUnsafe act1 act2)
removeConn :: NetworkLinkConn -> NetworkLinkConn -> NetworkLinkConn
removeConn old NoConn = old
removeConn old rm
| old /= rm = error $ "removeConn: " ++ show old ++ " " ++ show rm
| otherwise = NoConn
removeUsagePair :: NetworkLinkUsage -> NetworkLinkUsage -> NetworkLinkUsage
removeUsagePair (NetworkLinkUsage pas1 act1) (NetworkLinkUsage pas2 act2) =
NetworkLinkUsage (removeConn pas1 pas2) (removeConn act1 act2)
addUsages :: [(Int, NetworkLinkUsage)] -> (Int, NetworkLinkUsage)
addUsages usages@((i, _):_) = (i, foldl' (addUsagePair "") nwNoLinkUsage $ map snd usages)
addUsages [] = error "addUsages: no usages"
makeLinkUsage :: [NetworkComp] -> [Access] -> [(Int, NetworkLinkUsage)]
makeLinkUsage comps accesses = mixedUsages
where
rawCompUsages = concatMap nwCompLinkUsage comps
rawAccessUsages = concatMap (nwAccessLinkUsage 0) accesses
mixedUsages = map addUsages $ groupBy eqFst $ sortBy compareFst $ rawAccessUsages ++ rawCompUsages
showPosForNetwork :: Maybe PosArray -> Pos -> String
showPosForNetwork (Just posArray) = showPos (Just posArray)
showPosForNetwork Nothing = showPos noPosContext
showPrettyCompRef :: NetworkCompRef -> ShowS
showPrettyCompRef (Comp compNo) = showChar 'C' . shows compNo -- . showChar 'o'
showPrettyLinkRef :: NetworkLinkRef -> ShowS
showPrettyLinkRef (Link linkNo) = showChar 'L' . shows linkNo -- . showChar 'o'
embrace :: String -> String -> ShowS -> ShowS
embrace before after localShows = showString before . localShows . showString after
comment :: ShowS -> ShowS
comment = embrace "(-- " " --)"
quote :: String -> ShowS
quote string = shows string
paren :: ShowS -> ShowS
paren = embrace " (" ")"
space :: ShowS
space = showChar ' '
dot :: ShowS
dot = showChar '.'
showPrettyPort :: NetworkIF network => NetworkPort -> NetworkMonad network ShowS
showPrettyPort (NetworkPort name dir width maybeAccess) = do
accesses <- accessShows
return $ showDirection dir . space . quote name . showString " : " .
shows width . showString " bits" . accesses
where
accessShows
| isJust maybeAccess = do
access <- nwGetAccess $ fromJust maybeAccess
case access of
Just (Access ref [PortLinkAccess _ link]) ->
return $ (paren $ showString "link " . showPrettyLinkRef link) . case ref of
GoAccess -> showString " -- go"
DoneAccess -> showString " -- done"
_ -> id
_ -> return id
| otherwise = return id
showPrettyLink :: NetworkIF network => [NetworkPort] -> NetworkLink -> NetworkMonad network ShowS
showPrettyLink ports link@(NetworkLink i width _) = do
pas <- liftM (fromMaybe NoConn) $ nwGetLinkUsage Passive $ refLink link
act <- liftM (fromMaybe NoConn) $ nwGetLinkUsage Active $ refLink link
let hasConn = NetworkLinkUsage pas act /= nwNoLinkUsage
pasShows <- showPrettyLinkConn ports pas
actShows <- showPrettyLinkConn ports act
return $ showString "link " . showPrettyLinkRef (Link i) . showString " : " .
shows width . showString " bits" . (if hasConn
then paren $ showString "path " . actShows . showString " -> " . pasShows
else id)
showPrettyLinkConn :: NetworkIF network => [NetworkPort] -> NetworkLinkConn ->
NetworkMonad network ShowS
showPrettyLinkConn _ NoConn = return $ showString "unconnected"
showPrettyLinkConn _ (LinkComp (Comp _) []) = return $ showString "no port given"
showPrettyLinkConn _ (LinkComp compRef@(Comp compNo) (portNo:portIndices)) = do
maybeComp <- nwGetComp compRef
case maybeComp of
Just comp -> do
let portName = nwCompPortNames comp !! portNo
return $ showPrettyCompRef compRef . dot . showString portName . (if null portIndices then
id else shows portIndices)
_ -> return $ comment $ showString "comp not found: " . shows compNo . shows (portNo:portIndices)
where
showPrettyLinkConn ports (LinkAccess ref _) = return $ fromMaybe (shows ref) $ do
NetworkPort { nwPortName = name } <- nwFindPortByRef ports ref
return $ showString "\"" . showString name . showString "\""
showPrettyTeakCompParameters :: NetworkIF network => [Some NetworkLinkRef] -> TeakCompType ->
NetworkMonad network ShowS
showPrettyTeakCompParameters conns typ = body typ
where
paramParen params = showString " #(" . showString (joinWith ", " params) . showString ")"
slice :: Slice Int -> String
slice slice = show slice
list ls = "[" ++ joinWith "," ls ++ "]"
body TeakJ = do
inpWidths <- mapM nwGetLinkWidth inps
outWidth <- nwGetLinkWidth out
return $ paramParen [show outWidth, list (map show inpWidths)]
where [Many inps, One out] = conns
body TeakM = do
inpWidths <- mapM nwGetLinkWidth inps
outWidth <- nwGetLinkWidth out
return $ paramParen [show outWidth, list (map show inpWidths)]
where [Many inps, One out] = conns
body (TeakF offsets) = do
inpWidth <- nwGetLinkWidth inp
outWidths <- mapM nwGetLinkWidth outs
let outSlices = zipWith (+:) offsets outWidths
return $ paramParen [show inpWidth, list (map slice outSlices)]
where [One inp, Many outs] = conns
body (TeakV name width builtinOffsets writeOffsets readOffsets) = do
wgWidths <- mapM nwGetLinkWidth wgs
rdWidths <- mapM nwGetLinkWidth rds
let
writeSlices = map slice $ zipWith (+:) writeOffsets wgWidths
readSlices = map slice $ zipWith (+:) readOffsets rdWidths
return $ paramParen [quote name "",
show width, list (map show builtinOffsets), list writeSlices, list readSlices]
where [Many wgs, _, _, Many rds] = conns
body (TeakS matchSlice matches) = do
inpWidth <- nwGetLinkWidth inp
outWidths <- mapM nwGetLinkWidth outs
let
showMatch (_, outWidth, (imps, offset)) = "([" ++
joinWith "," (map (showImp True True 4) imps) ++
"]," ++ slice (offset +: outWidth) ++ ")"
return $ paramParen [show inpWidth,
slice matchSlice, list (map showMatch $ zip3 outs outWidths matches)]
where [One inp, Many outs] = conns
body (TeakX matches) = do
width <- nwGetLinkWidth out
let
showMatch (_, imps) = "[" ++
joinWith "," (map (showImp True True 4) imps) ++
"]"
return $ paramParen [show width,
list (map showMatch $ zip inps matches)]
where [Many inps, One _sel, One out] = conns
body (TeakO {}) = return $ paramParen ["(-- FIXME --)"]
body _ = return $ id -- A I R
showPrettyComp :: NetworkIF network => NetworkComp -> NetworkMonad network ShowS
showPrettyComp comp = body comp
where
body (TeakComp compNo typ conns _) = do
paramShows <- showPrettyTeakCompParameters conns typ
return $ showString "teak." . showString (nwCompShortName comp) . space .
showPrettyCompRef (Comp compNo) . paramShows . showLinks (nwCompPortNames comp) conns
body (InstanceComp compNo part compPorts compLinks _) = do
return $ showString "part " . quote part .
showPrettyCompRef (Comp compNo) .
showLinks (map nwPortName compPorts) compLinks
showLink link = showPrettyLinkRef link ""
showLinks portNames compLinks = paren $
showListWithSep (showString ", ") showPort (zip portNames compLinks)
where
showPort (name, someLinks) =
showChar '.' . showString name . embrace "(" ")" (
showString (showSomeHaskell showLink someLinks))
showPrettyNetwork :: NetworkIF network => Bool -> Int -> Int -> Part network -> ShowS
showPrettyNetwork _ prec tabs part@(Part partName ports _) = tryPart part $ do
portShows <- mapM showPrettyPort ports
linkShows <- nwMapLinks (showPrettyLink ports)
compShows <- nwMapComps showPrettyComp
let
sPNBody = showString "part " . quote partName . showString " (" .
tabbedNL tabs' .
showListWithSep (tabbedNL tabs') id portShows .
tabbedNL tabs . showString ") is" .
tabbedNL tabs' .
showListWithSep (tabbedNL tabs') id linkShows .
tabbedNL tabs . showString "begin" .
tabbedNL tabs' .
showListWithSep (tabbedNL tabs') id compShows .
{-
showChar ',' .
tabbedNL tabs' . showString "networkAccesses = " .
showListTab tabs' accesses .
showChar ',' .
tabbedNL tabs' . showString "networkProperties = " .
showListTab tabs' properties .
-}
tabbedNL tabs . showString "end"
return $ showParen (prec > applyPrecedence) sPNBody
where
tabs' = tabs + 1
-- trimPart : make a new part which only contains the components referenced from comps
trimPart :: NetworkIF network => Part network -> [NetworkCompRef] -> Part network
trimPart (Part name ports nw) comps = uncurry ($) $ runNetwork nw $ do
nwMapComps removeComp
ports' <- liftM catMaybes $ mapM removePort ports
return $ Part name ports'
where
removeComp comp = when (refComp comp `notElem` comps) $ nwRemoveComp comp
removePort port@(NetworkPort { nwPortRef = Just ref }) = runMaybeT $ do
access <- MaybeT $ nwGetAccess ref
let Access _ [PortLinkAccess _ link] = access
keepPort <- lift $ connectedToComp link
if keepPort
then return port
else do
lift $ nwRemoveAccess ref
fail ""
removePort _ = return Nothing
connectedToComp link = do
act <- nwGetLinkUsage Active link
pas <- nwGetLinkUsage Passive link
return $ isLinkComp act || isLinkComp pas
writeNetworkFile :: NetworkIF network => Bool -> String -> String -> [Part network] -> IO ()
writeNetworkFile pretty flatArgs teakFilename parts = do
teakFile <- openFile teakFilename WriteMode
if pretty
then do
hPutStrLn teakFile "-- Teak output file"
when (flatArgs /= "") $ do
hPutStrLn teakFile $ "-- from command: teak " ++ flatArgs ++ "\n"
mapM_ (\nw -> do
hPutStr teakFile $ showPrettyNetwork True 0 0 nw ""
hPutStr teakFile "\n\n") parts
else do
hPutStrLn teakFile "-- Teak output file"
when (flatArgs /= "") $ do
hPutStrLn teakFile $ "-- from command: teak " ++ flatArgs ++ "\n"
mapM_ (\part -> hPutStrLn teakFile $ showsPrecTab 0 0 part "") parts
hClose teakFile
readNetworkFile :: (Read network, NetworkIF network) => String -> WhyT IO [Part network]
readNetworkFile teakFilename = do
contents <- whyTReadFile NoPos teakFilename
let (parts, trailing) = readBareListC contents -- :: ([Part network], String)
if skipComments trailing == ""
then return parts
else failPos PosTopLevel $ "can't parse Teak network file: `" ++ teakFilename
++ "', remaining: `" ++ take 100 trailing ++ "'"
-- uniquifyPart : starting from part `topLevel', make each InstanceComp instantiate a unique
-- part (copied from an element in `parts'). Returns the newly created parts.
uniquifyPart :: NetworkIF network => [Part network] -> String -> [Part network]
uniquifyPart originalParts topLevelName = snd $ uniquifyPartBody [] topLevel topLevelName
where
Just topLevel = nwFindPart originalParts topLevelName
uniquifyPartBody counts part newName = (counts', newParts ++ [renamedPartCopy])
where
((counts', newParts), renamedPartCopy) = runPart (part { networkName = newName }) uniquifyInstances
uniquifyInstances = nwFoldCompsIf (return . isInstanceComp) uniquifyInstance (counts, [])
uniquifyInstance (counts, accumNewParts) comp = do
nwUpdateComp $ comp { nwPartName = newPartName }
let (counts'', newParts) = uniquifyPartBody counts' part newPartName
return (counts'', accumNewParts ++ newParts)
where
partName = nwPartName comp
Just part = nwFindPart originalParts partName
count = if null oldCount
then (1 :: Int)
else (snd (head oldCount)) + 1
(oldCount, otherCount) = partition ((== partName) . fst) counts
counts' = (partName, count) : otherCount
newPartName = partName ++ if count == 1 then "" else "_v" ++ show count
nwCheckComp :: NetworkIF network => NetworkComp -> WhyT (NetworkMonad network) ()
nwCheckComp comp = decorateErrorsT pos' $ do
let links = nwCompLinks comp
gatherFailMap checkLink $ concatMap flattenSome links
gatherFailMap checkPortStruct links
checkComp comp
return ()
where
pos' = PosLabel NoPos $ "C" ++ show (nwCompIndex comp)
checkPortStruct (One {}) = return ()
checkPortStruct (Many []) = fail "arrayed port with no connections"
checkPortStruct (Many (_:_)) = return ()
checkPortStruct _ = fail badPortStructure
checkLink link = do
valid <- lift $ nwLinkIsValid link
when (not valid) $ fail $ "invalid link" ++ show link
checkSlice maxWidth slice
| offset < 0 = fail "slice offset < 0"
| offset + width > maxWidth = fail "slice top exceeds bounding width"
| width == 0 && offset /= 0 = fail "token slice not at offset 0"
| otherwise = return ()
where
offset = sliceOffset slice
width = sliceWidth slice
checkComp (InstanceComp {}) = return () -- FIXME
checkComp (TeakComp { nwTeakType = TeakA, nwCompLinks = [Many inps, One out] })
| length inps /= 2 = fail "wrong number of inputs, must be exactly 2"
| otherwise = do
inpWidths <- lift $ mapM nwGetLinkWidth inps
outWidth <- lift $ nwGetLinkWidth out
when (not (all (== outWidth) inpWidths)) $ fail "input and output widths must match"
checkComp (TeakComp { nwTeakType = TeakF offsets, nwCompLinks = [One inp, Many outs] })
| length offsets /= length outs = fail "offset list and outputs must be the same length"
| otherwise = do
inpWidth <- lift $ nwGetLinkWidth inp
outWidths <- lift $ mapM nwGetLinkWidth outs
let
checkFOffset (i, offset, width) = decorateErrorsT pos $ checkSlice inpWidth (offset +: width)
where pos = PosLabel NoPos $ "out[" ++ show i ++ "]"
gatherFailMap checkFOffset $ zip3 [(0::Int)..] offsets outWidths
return ()
checkComp (TeakComp { nwTeakType = TeakJ, nwCompLinks = [Many inps, One out] }) = do
outWidth <- lift $ nwGetLinkWidth out
inpWidths <- lift $ mapM nwGetLinkWidth inps
when (outWidth /= sum inpWidths) $ fail "output width must equal sum of input widths"
return ()
checkComp (TeakComp { nwTeakType = TeakM, nwCompLinks = [Many inps, One out] }) = do
inpWidths <- lift $ mapM nwGetLinkWidth inps
outWidth <- lift $ nwGetLinkWidth out
when (not (all (== outWidth) inpWidths)) $ fail "input and output widths must match"
checkComp (TeakComp { nwTeakType = TeakO terms, nwCompLinks = [One _inp, One _out] })
| length terms == 0 = fail "must have at least one term"
| otherwise = return () -- FIXME
checkComp (TeakComp { nwTeakType = TeakS selSlice terms, nwCompLinks = [One inp, Many outs] })
| length terms /= length outs = fail "offset/imps list and outputs must be the same length"
| otherwise = do
inpWidth <- lift $ nwGetLinkWidth inp
outWidths <- lift $ mapM nwGetLinkWidth outs
let
checkTerm (i, (_imps, offset), width) = decorateErrorsT pos $
checkSlice inpWidth (offset +: width)
where pos = PosLabel NoPos $ "out[" ++ show i ++ "]"
gatherFailMap id [
decorateErrorsT (PosLabel NoPos $ "select slice") $ checkSlice inpWidth selSlice,
(gatherFailMap checkTerm $ zip3 [(0::Int)..] terms outWidths) >> return ()
]
return ()
-- FIXME, check slice and coverage?
checkComp (TeakComp { nwTeakType = TeakX terms, nwCompLinks = [Many inps, One _, One out] })
| length terms /= length inps = fail "imps list and inputs must be the same length"
| otherwise = do
outWidth <- lift $ nwGetLinkWidth out
inpWidths <- lift $ mapM nwGetLinkWidth inps
when (not (all (== outWidth) inpWidths)) $ fail "input and output widths must match"
return ()
-- FIXME, check slice and coverage?
checkComp (TeakComp { nwTeakType = TeakV _ varWidth _bOffsets wOffsets rOffsets,
nwCompLinks = [Many wgs, Many wds, Many rgs, Many rds] })
| length wOffsets /= length wgs || length wOffsets /= length wds =
fail "write offset/write port length mismatch"
| length rOffsets /= length rgs || length rOffsets /= length rds =
fail "read offset/write port length mismatch"
| otherwise = do
-- FIXME, check bOffsets
wgWidths <- lift $ mapM nwGetLinkWidth wgs
wdWidths <- lift $ mapM nwGetLinkWidth wds
rgWidths <- lift $ mapM nwGetLinkWidth rgs
rdWidths <- lift $ mapM nwGetLinkWidth rds
let
checkWrite (i, offset, width) = decorateErrorsT pos $ checkSlice varWidth (offset +: width)
where pos = PosLabel NoPos $ "write[" ++ show i ++ "]"
checkRead (i, offset, width) = decorateErrorsT pos $ checkSlice varWidth (offset +: width)
where pos = PosLabel NoPos $ "read[" ++ show i ++ "]"
gatherFailMap id [
when (not (all (== 0) wdWidths)) $ fail "some write dones not token links",
when (not (all (== 0) rgWidths)) $ fail "some read gos not token links",
when (not (all (/= 0) wgWidths)) $ fail "some write gos are token links",
when (not (all (/= 0) rdWidths)) $ fail "some read dones are token links",
gatherFailMap checkWrite (zip3 [(0::Int)..] wOffsets wgWidths) >> return (),
gatherFailMap checkRead (zip3 [(0::Int)..] rOffsets rdWidths) >> return ()
]
return ()
checkComp (TeakComp { nwTeakType = TeakI, nwCompLinks = [One inp, One out] }) = do
inpWidth <- lift $ nwGetLinkWidth inp
outWidth <- lift $ nwGetLinkWidth out
gatherFailMap id [
when (inpWidth /= 0) $ fail "input must be a token link",
when (outWidth /= 0) $ fail "output must be a token link"
]
return ()
checkComp (TeakComp { nwTeakType = TeakR, nwCompLinks = [One out] }) = do
outWidth <- lift $ nwGetLinkWidth out
when (outWidth /= 0) $ fail "output must be a token link"
checkComp (TeakComp {}) = fail badPortStructure
badPortStructure = "bad port structure"
checkPart :: NetworkIF network => Part network -> Completeness
checkPart part = comp
where
Why comp _ = decorateErrors pos $ gatherFail $ tryPart part $ nwMapComps (runWhyT . nwCheckComp)
pos = PosLabel PosTopLevel $ networkName part
runWhyTPart :: NetworkIF network => Part network -> WhyT (NetworkMonad network) r -> Why (r, Part network)
runWhyTPart part nm = Why comp (ret, part')
where (Why comp ret, part') = runPart part $ runWhyT nm
runWhyTPart_ :: NetworkIF network => Part network -> WhyT (NetworkMonad network) r -> Why (Part network)
runWhyTPart_ part nm = Why comp part'
where (Why comp _, part') = runPart part $ runWhyT nm
funcActualToTeakParam :: FuncActual -> TeakParam
funcActualToTeakParam (TypeFuncActual typ) = TeakParamType typ
funcActualToTeakParam (ExprFuncActual _ expr) = exprToTeakParam expr
exprToTeakParam :: Expr -> TeakParam
exprToTeakParam (ValueExpr _ _ (StringValue str)) = TeakParamString str
exprToTeakParam (ValueExpr _ _ (IntValue val)) = TeakParamInt val
exprToTeakParam expr = error $ "exprToTeakParam: bad expr " ++ show expr
teakParamToFuncActual :: TeakParam -> FuncActual
teakParamToFuncActual (TeakParamInt int) = ExprFuncActual False
(ValueExpr undefined undefined (IntValue int))
teakParamToFuncActual (TeakParamString str) = ExprFuncActual False
(ValueExpr undefined undefined (StringValue str))
teakParamToFuncActual (TeakParamType typ) = TypeFuncActual typ
| Mahdi89/eTeak | src/NetParts.hs | bsd-3-clause | 87,647 | 39 | 25 | 27,770 | 24,567 | 12,392 | 12,175 | -1 | -1 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Network/HTTP/Date/Converter.hs" #-}
{-# LANGUAGE BangPatterns #-}
module Network.HTTP.Date.Converter (epochTimeToHTTPDate) where
import Control.Applicative
import Data.ByteString.Internal
import Data.Word
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.Storable
import Network.HTTP.Date.Types
import System.IO.Unsafe (unsafePerformIO)
import System.Posix.Types
{-|
Translating 'EpochTime' to 'HTTPDate'.
-}
epochTimeToHTTPDate :: EpochTime -> HTTPDate
epochTimeToHTTPDate x = defaultHTTPDate {
hdYear = y
, hdMonth = m
, hdDay = d
, hdHour = h
, hdMinute = n
, hdSecond = s
, hdWkday = w
}
where
w64 :: Word64
w64 = fromIntegral $ fromEnum x
(days',secs') = w64 `quotRem` 86400
days = fromIntegral days'
secs = fromIntegral secs'
-- 1970/1/1 is Thu (4)
w = (days + 3) `rem` 7 + 1
(y,m,d) = toYYMMDD days
(h,n,s) = toHHMMSS secs
toYYMMDD :: Int -> (Int,Int,Int)
toYYMMDD x = (yy, mm, dd)
where
(y,d) = x `quotRem` 365
cy = 1970 + y
cy' = cy - 1
leap = cy' `quot` 4 - cy' `quot` 100 + cy' `quot` 400 - 477
(yy,days) = adjust cy d leap
(mm,dd) = findMonth days
adjust !ty td aj
| td >= aj = (ty, td - aj)
| isLeap (ty - 1) = if td + 366 >= aj
then (ty - 1, td + 366 - aj)
else adjust (ty - 1) (td + 366) aj
| otherwise = if td + 365 >= aj
then (ty - 1, td + 365 - aj)
else adjust (ty - 1) (td + 365) aj
isLeap year = year `rem` 4 == 0
&& (year `rem` 400 == 0 ||
year `rem` 100 /= 0)
(months, daysArr) = if isLeap yy
then (leapMonth, leapDayInMonth)
else (normalMonth, normalDayInMonth)
findMonth n = inlinePerformIO $ (,) <$> (peekElemOff months n) <*> (peekElemOff daysArr n)
----------------------------------------------------------------
normalMonthDays :: [Int]
normalMonthDays = [31,28,31,30,31,30,31,31,30,31,30,31]
leapMonthDays :: [Int]
leapMonthDays = [31,29,31,30,31,30,31,31,30,31,30,31]
mkPtrInt :: [Int] -> Ptr Int
mkPtrInt = unsafePerformIO . newArray . concat . zipWith (flip replicate) [1..]
mkPtrInt2 :: [Int] -> Ptr Int
mkPtrInt2 = unsafePerformIO . newArray . concatMap (enumFromTo 1)
normalMonth :: Ptr Int
normalMonth = mkPtrInt normalMonthDays
normalDayInMonth :: Ptr Int
normalDayInMonth = mkPtrInt2 normalMonthDays
leapMonth :: Ptr Int
leapMonth = mkPtrInt leapMonthDays
leapDayInMonth :: Ptr Int
leapDayInMonth = mkPtrInt2 leapMonthDays
----------------------------------------------------------------
toHHMMSS :: Int -> (Int,Int,Int)
toHHMMSS x = (hh,mm,ss)
where
(hhmm,ss) = x `quotRem` 60
(hh,mm) = hhmm `quotRem` 60
| phischu/fragnix | tests/packages/scotty/Network.HTTP.Date.Converter.hs | bsd-3-clause | 2,811 | 0 | 13 | 706 | 1,002 | 575 | 427 | 73 | 4 |
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TupleSections #-}
module Language.Fixpoint.Solver.Graph (
-- * Remove Constraints that don't affect Targets
slice
-- * Predicate describing Targets
, isTarget
-- * Compute Ranks / SCCs
, graphRanks
-- * Compute Kvar dependencies
, cGraph, gSccs
-- * Kvars written and read by a constraint
, kvWriteBy, kvReadBy
) where
-- import Debug.Trace (trace)
import Prelude hiding (init)
import Language.Fixpoint.Types.Visitor (rhsKVars, envKVars, kvars, isConcC)
import Language.Fixpoint.Misc (errorstar, fst3, sortNub, group)
import qualified Language.Fixpoint.Types as F
import Language.Fixpoint.Solver.Types
import qualified Data.HashMap.Strict as M
import qualified Data.List as L
import Data.Maybe (fromMaybe)
import qualified Data.HashSet as S
import Data.Graph (transposeG, graphFromEdges, dfs, scc, Graph, Vertex)
import Data.Tree (flatten)
---------------------------------------------------------------------------
-- | Compute constraints that transitively affect target constraints,
-- and delete everything else from F.SInfo a
---------------------------------------------------------------------------
slice :: (F.TaggedC c a) => F.GInfo c a -> F.GInfo c a
---------------------------------------------------------------------------
slice fi = fi { F.cm = cm'
, F.ws = ws' }
where
cm' = M.filterWithKey inC (F.cm fi)
ws' = M.filterWithKey inW (F.ws fi)
ks = sliceKVars fi sl
is = S.fromList (slKVarCs sl ++ slConcCs sl)
sl = mkSlice fi
inC i _ = S.member i is
inW k _ = S.member k ks
sliceKVars :: (F.TaggedC c a) => F.GInfo c a -> Slice -> S.HashSet F.KVar
sliceKVars fi sl = S.fromList $ concatMap (subcKVars be) cs
where
cs = lookupCMap cm <$> slKVarCs sl ++ slConcCs sl
be = F.bs fi
cm = F.cm fi
subcKVars :: (F.TaggedC c a) => F.BindEnv -> c a -> [F.KVar]
subcKVars be c = envKVars be c ++ rhsKVars c
---------------------------------------------------------------------------
mkSlice :: (F.TaggedC c a) => F.GInfo c a -> Slice
---------------------------------------------------------------------------
mkSlice fi = mkSlice_ (F.cm fi) g' es v2i i2v
where
g' = transposeG g -- "inverse" of g (reverse the dep-edges)
(g, vf, cf) = graphFromEdges es
es = gEdges $ cGraph fi
v2i = fst3 . vf
i2v i = fromMaybe (errU i) $ cf i
errU i = errorstar $ "graphSlice: nknown constraint " ++ show i
mkSlice_ cm g' es v2i i2v = Slice { slKVarCs = kvarCs
, slConcCs = concCs
, slEdges = sliceEdges kvarCs es
}
where
-- n = length kvarCs
concCs = [ i | (i, c) <- M.toList cm, isTarget c ]
kvarCs = v2i <$> reachVs
rootVs = i2v <$> concCs
reachVs = concatMap flatten $ dfs g' rootVs
sliceEdges :: [CId] -> [DepEdge] -> [DepEdge]
sliceEdges is es = [ (i, i, filter inSlice js) | (i, _, js) <- es, inSlice i ]
where
inSlice i = M.member i im
im = M.fromList $ (, ()) <$> is
-- | DO NOT DELETE!
-- sliceCSucc :: Slice -> CSucc
-- sliceCSucc sl = \i -> M.lookupDefault [] i im
-- where
-- im = M.fromList [(i, is) | (i,_,is) <- slEdges sl]
---------------------------------------------------------------------------
-- | Dependencies ---------------------------------------------------------
---------------------------------------------------------------------------
kvSucc :: (F.TaggedC c a) => F.GInfo c a -> CSucc
---------------------------------------------------------------------------
kvSucc fi = succs cm rdBy
where
rdBy = kvReadBy fi
cm = F.cm fi
succs :: (F.TaggedC c a) => CMap (c a) -> KVRead -> CSucc
succs cm rdBy i = sortNub $ concatMap kvReads iKs
where
iKs = kvWriteBy cm i
kvReads k = M.lookupDefault [] k rdBy
---------------------------------------------------------------------------
kvWriteBy :: (F.TaggedC c a) => CMap (c a) -> CId -> [F.KVar]
---------------------------------------------------------------------------
kvWriteBy cm = kvars . F.crhs . lookupCMap cm
---------------------------------------------------------------------------
kvReadBy :: (F.TaggedC c a) => F.GInfo c a -> KVRead
---------------------------------------------------------------------------
kvReadBy fi = group [ (k, i) | (i, ci) <- M.toList cm
, k <- envKVars bs ci]
where
cm = F.cm fi
bs = F.bs fi
---------------------------------------------------------------------------
isTarget :: (F.TaggedC c a) => c a -> Bool
---------------------------------------------------------------------------
isTarget c = isConcC c && isNonTriv c
where
isNonTriv = not . F.isTautoPred . F.crhs
---------------------------------------------------------------------------
-- | Constraint Graph -----------------------------------------------------
---------------------------------------------------------------------------
cGraph :: (F.TaggedC c a) => F.GInfo c a -> CGraph
---------------------------------------------------------------------------
cGraph fi = CGraph { gEdges = es
, gRanks = outRs
, gSucc = next
, gSccs = length sccs }
where
es = [(i, i, next i) | i <- M.keys $ F.cm fi]
next = kvSucc fi
(g, vf, _) = graphFromEdges es
(outRs, sccs) = graphRanks g vf
---------------------------------------------------------------------------
-- | Ranks from Graph -----------------------------------------------------
---------------------------------------------------------------------------
graphRanks :: Graph -> (Vertex -> DepEdge) -> (CMap Int, [[Vertex]])
---------------------------------------------------------------------------
graphRanks g vf = (M.fromList irs, sccs)
where
irs = [(v2i v, r) | (r, vs) <- rvss, v <- vs ]
rvss = zip [0..] sccs
sccs = L.reverse $ map flatten $ scc g
v2i = fst3 . vf
| rolph-recto/liquid-fixpoint | src/Language/Fixpoint/Solver/Graph.hs | bsd-3-clause | 6,417 | 0 | 12 | 1,641 | 1,591 | 868 | 723 | 88 | 1 |
{- |
Module : $Header$
Description : keywords used for XML conversion
Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013
License : GPLv2 or higher, see LICENSE.txt
Maintainer : dcalegar@fing.edu.uy
Stability : provisional
Portability : portable
-}
module CSMOF.XMLKeywords where
import Text.XML.Light
metamodelK :: QName
metamodelK = QName {qName = "Metamodel", qURI = Just "urn:CSMOF.ecore", qPrefix = Just "CSMOF"}
metamodelNameK :: QName
metamodelNameK = QName {qName = "name", qURI = Nothing, qPrefix = Nothing}
modelK :: QName
modelK = QName {qName = "model", qURI = Nothing, qPrefix = Nothing}
modelNameK :: QName
modelNameK = QName {qName = "name", qURI = Nothing, qPrefix = Nothing}
elementK :: QName
elementK = QName {qName = "element", qURI = Nothing, qPrefix = Nothing}
elementNameK :: QName
elementNameK = QName {qName = "name", qURI = Nothing, qPrefix = Nothing}
elementTypeK :: QName
elementTypeK = QName {qName = "type", qURI = Just "http://www.w3.org/2001/XMLSchema-instance", qPrefix = Just "xsi"}
elementIsAbstractK :: QName
elementIsAbstractK = QName {qName = "isAbstract", qURI = Nothing, qPrefix = Nothing}
elementSuperClassK :: QName
elementSuperClassK = QName {qName = "superClass", qURI = Nothing, qPrefix = Nothing}
ownedAttributeK :: QName
ownedAttributeK = QName {qName = "ownedAttribute", qURI = Nothing, qPrefix = Nothing}
ownedAttributeLowerK :: QName
ownedAttributeLowerK = QName {qName = "lower", qURI = Nothing, qPrefix = Nothing}
ownedAttributeUpperK :: QName
ownedAttributeUpperK = QName {qName = "upper", qURI = Nothing, qPrefix = Nothing}
ownedAttributeNameK :: QName
ownedAttributeNameK = QName {qName = "name", qURI = Nothing, qPrefix = Nothing}
ownedAttributeTypeK :: QName
ownedAttributeTypeK = QName {qName = "type", qURI = Nothing, qPrefix = Nothing}
ownedAttributeOppositeK :: QName
ownedAttributeOppositeK = QName {qName = "opposite", qURI = Nothing, qPrefix = Nothing}
objectK :: QName
objectK = QName {qName = "object", qURI = Nothing, qPrefix = Nothing}
objectNameK :: QName
objectNameK = QName {qName = "name", qURI = Nothing, qPrefix = Nothing}
objectTypeK :: QName
objectTypeK = QName {qName = "type", qURI = Nothing, qPrefix = Nothing}
linkK :: QName
linkK = QName {qName = "link", qURI = Nothing, qPrefix = Nothing}
linkTypeK :: QName
linkTypeK = QName {qName = "type", qURI = Nothing, qPrefix = Nothing}
linkSourceK :: QName
linkSourceK = QName {qName = "source", qURI = Nothing, qPrefix = Nothing}
linkTargetK :: QName
linkTargetK = QName {qName = "target", qURI = Nothing, qPrefix = Nothing}
| keithodulaigh/Hets | CSMOF/XMLKeywords.hs | gpl-2.0 | 2,616 | 0 | 7 | 424 | 685 | 431 | 254 | 46 | 1 |
module HaskelineExport where
import System.Console.Haskeline
import System.Console.Haskeline.IO
import Foreign
import Foreign.C.String
foreign export ccall initialize_input :: IO (StablePtr InputState)
foreign export ccall close_input :: StablePtr InputState -> IO ()
foreign export ccall cancel_input :: StablePtr InputState -> IO ()
foreign export ccall get_input_line :: StablePtr InputState -> CString
-> IO CString
-- TODO: allocate string results with the malloc from stdlib
-- so that c code can free it.
initialize_input = do
hd <- initializeInput defaultSettings
newStablePtr hd
close_input sptr = do
hd <- deRefStablePtr sptr
closeInput hd
freeStablePtr sptr
cancel_input sptr = do
hd <- deRefStablePtr sptr
cancelInput hd
freeStablePtr sptr
get_input_line sptr c_prefix = do
hd <- deRefStablePtr sptr
prefix <- peekCString c_prefix
result <- queryInput hd (getInputLine prefix)
case result of
Nothing -> return nullPtr
Just str -> newCString str
| DavidAlphaFox/ghc | libraries/haskeline/examples/export/HaskelineExport.hs | bsd-3-clause | 1,076 | 0 | 10 | 252 | 272 | 130 | 142 | 28 | 2 |
module ShouldCompile where
import Prelude hiding ((<>))
(<>) :: (a -> Maybe b) -> (b -> Maybe c) -> (a -> Maybe c)
(m1 <> m2) a1 = case m1 a1 of
Nothing -> Nothing
Just a2 -> m2 a2
| sdiehl/ghc | testsuite/tests/parser/should_compile/read026.hs | bsd-3-clause | 239 | 0 | 11 | 98 | 102 | 54 | 48 | 6 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.