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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
--
-- Replacer.hs
--
-- Replace a subexpression with a different one.
--
-- Gregory Wright, 18 September 2012
--
module Math.Symbolic.Wheeler.Replacer where
import qualified Data.DList as DList
import qualified Data.Map as Map
import Data.Maybe
import Math.Symbolic.Wheeler.Canonicalize
import Math.Symbolic.Wheeler.Common
import Math.Symbolic.Wheeler.Expr
import Math.Symbolic.Wheeler.Matchable
import Math.Symbolic.Wheeler.Matcher2
import Math.Symbolic.Wheeler.Pattern
import Math.Symbolic.Wheeler.Symbol
import Math.Symbolic.Wheeler.Tensor
import Math.Symbolic.Wheeler.TensorUtilities
multiMatchAndReplace :: [ (Expr, Expr) ] -> Expr -> Expr
multiMatchAndReplace prs subj = foldr matchAndReplace subj prs
matchAndReplace :: (Expr, Expr) -> Expr -> Expr
matchAndReplace (pat, repl) subj =
let
minfos = matches pat subj
in
canonicalize $ replaceAll minfos repl subj
replaceAll :: [ MatchInfo ] -> Expr -> Expr -> Expr
replaceAll minfos repl subj =
let
subj' = deleteMatches minfos subj
replace' minfo s = let
repl' = unPattern minfo repl
bcs = matchPaths minfo
in
replaceIn bcs repl' s
in
foldr replace' subj' minfos
-- Remove the items at the paths specified in minfo,
-- the use the environment to insert the expression
-- repl into the to expression subj.
--
replace :: MatchInfo -> Expr -> Expr -> Expr
replace minfo repl subj =
let
repl' = unPattern minfo repl
subj' = deleteMatches [minfo] subj
bcs = matchPaths minfo
in
replaceIn bcs repl' subj'
replaceIn :: [ Breadcrumbs' ] -> Expr -> Expr -> Expr
replaceIn bcs repl subj =
let
subjSpaces = zip (map (\bc -> repSpaces $ exprAt bc subj) bcs) bcs
replSpaces = repSpaces repl
in
if null replSpaces
then replaceAt (head bcs) repl subj
else if length replSpaces == 1
then let
bc = lookup replSpaces subjSpaces
in if isJust bc
then replaceAt (fromJust bc) repl subj
else error "replaceIn: no matching repSpace"
else error "replaceIn: replacement expression must be in single repSpace."
-- Take an expression an replace all of the patterns
-- with their values from the match environment.
--
-- XXX FIXME XXX
-- Doesn't replace all of the patterns.
--
unPattern :: MatchInfo -> Expr -> Expr
unPattern minfo ex =
let
env = matchEnviron minfo
in
mapExpr (replacePattern env) ex
replacePattern :: (Map.Map PatternVar Binding) -> Expr -> Expr
replacePattern env e@(Symbol (Tensor t)) =
if isPattern e
then
let
repl = Map.lookup (getPattern e) env
in
if isJust repl
then let
TVar t' = fromJust repl
s' = map (replaceSlot env) (slots t)
in Symbol $ Tensor $ t' { slots = s'}
else error "replacePattern pattern without binding"
else
let
s' = map (replaceSlot env) (slots t)
in Symbol $ Tensor $ t { slots = s' }
replacePattern env e = if isPattern e
then let repl = Map.lookup (getPattern e) env
in if isJust repl
then unBind $ fromJust repl
else error "replacePattern: pattern without binding"
else e
replaceSlot :: (Map.Map PatternVar Binding) -> VarIndex -> VarIndex
replaceSlot env s = if isPatternVarIndex s
then
let
s' = Map.lookup (getVarIndexPattern s) env
in if isJust s'
then if isCovariant s
then Covariant (Abstract (unBindIndex $ fromJust s'))
else Contravariant (Abstract (unBindIndex $ fromJust s'))
else error "replaceSlot: pattern without binding"
else s
deleteMatches :: [ MatchInfo ] -> Expr -> Expr
deleteMatches minfos ex = foldr (\m e -> deleteExprs (matchPaths m) e) ex minfos
-- A convenience function to delete several subexpressions
-- from an expression tree.
--
deleteExprs :: [ Breadcrumbs' ] -> Expr -> Expr
deleteExprs bcs e = foldr deleteExpr e bcs
replaceInContext :: Breadcrumbs' -> Expr -> Expr
replaceInContext _ e =
let
rs = repSpaces e
in
if null rs
then Symbol $ mkPlaceholder
else Symbol $ mkNcPlaceholder (head rs)
-- deleteExpr removes the expression subtree at the
-- specified location.
--
deleteExpr :: Breadcrumbs' -> Expr -> Expr
deleteExpr bc e = snd $ de bc (DList.empty, e)
where
de targetLoc (currentLoc, expr) = if currentLoc == targetLoc
then (currentLoc, replaceInContext currentLoc expr)
else de' targetLoc (currentLoc, expr)
de' targetLoc (currentLoc, Sum ts) = (currentLoc, Sum (zipWith (\n x -> snd (de targetLoc (currentLoc `DList.snoc` Scxt n, x))) [1..] ts))
de' targetLoc (currentLoc, Product fs) = (currentLoc, Product (zipWith (\n x -> snd (de targetLoc (currentLoc `DList.snoc` Pcxt n, x))) [1..] fs))
de' _ u@(_, _) = u
-- A limited expression replacement function: replaceExpr
-- replaces the subtree at the specified location with
-- a new expression subtree.
--
replaceExpr :: Breadcrumbs -> Expr -> Expr -> Expr
replaceExpr bc repl subj = snd $ re bc repl ([], subj)
where
re targetLoc rexpr (currentLoc, expr) = if currentLoc == targetLoc
then (currentLoc, rexpr)
else re' targetLoc rexpr (currentLoc, expr)
re' targetLoc rexpr (currentLoc, Sum ts) = (currentLoc, Sum (zipWith (\n x -> snd (re targetLoc rexpr ((Scxt n) : currentLoc, x))) [1..] ts))
re' targetLoc rexpr (currentLoc, Product fs) = (currentLoc, Product (zipWith (\n x -> snd (re targetLoc rexpr ((Pcxt n) : currentLoc, x))) [1..] fs))
re' _ _ u@(_, _) = u
-- A utility funtion to return the subexpression at a
-- given location in the expression tree.
--
exprAt :: Breadcrumbs' -> Expr -> Expr
exprAt bc e = exat (DList.toList bc) e
where
exat [] ex = ex
exat ((Scxt n) : bcs) (Sum ts) = exat bcs (ts !! (n - 1))
exat ((Pcxt n) : bcs) (Product fs) = exat bcs (fs !! (n - 1))
exat _ _ = error "exprAt: incompatible Expr and Breadcrumbs"
-- A utility function to insert a given expression at a specified location.
-- No different than replaceExpr, but the location is given as
-- Breadcrumbs' instead of Breadcrumbs. (This really ought to be
-- fixed, as there is no need for two ways of doing this.)
--
replaceAt :: Breadcrumbs' -> Expr -> Expr -> Expr
replaceAt bc repl subj = snd $ re bc repl (DList.empty, subj)
where
re targetLoc rexpr (currentLoc, expr) = if currentLoc == targetLoc
then (currentLoc, rexpr)
else re' targetLoc rexpr (currentLoc, expr)
re' targetLoc rexpr (currentLoc, Sum ts) = (currentLoc, Sum (zipWith (\n x -> snd (re targetLoc rexpr (currentLoc `DList.snoc` Scxt n, x))) [1..] ts))
re' targetLoc rexpr (currentLoc, Product fs) = (currentLoc, Product (zipWith (\n x -> snd (re targetLoc rexpr (currentLoc `DList.snoc` Pcxt n, x))) [1..] fs))
re' _ _ u@(_, _) = u
|
gwright83/Wheeler
|
src/Math/Symbolic/Wheeler/Replacer.hs
|
bsd-3-clause
| 7,631 | 0 | 19 | 2,391 | 2,155 | 1,151 | 1,004 | 126 | 5 |
-- Commented out exports represent things left
-- to do, or things that no longer make sense
module Graphics.Xhb.Connection
( Connection
, connect
, connect'
-- , I.parseDisplay -- no reason not to export, but not sure why we would?
, writeRequests
, maximumRequestLength
, prefetchMaximumReuestLength
, connectionHasError
, I.Cookie(..)
, waitForEvent
, waitForReply
, generateId
, getSetup
, withForeignConnection
, withConnectionPtr
) where
import qualified Graphics.Xhb.Internal as I
import Graphics.Xhb.Types
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Control.Applicative ((<$>))
import Data.IORef
import Data.List (foldl')
import Data.Word
import Foreign
{-
XCB socket handoff works as follows:
* When we want to use the socket, we tell XCB and
give it a callback to use to take it back (and a callback
closure).
* XCB either flushes its own buffers, or asks the
current socket owner to give the socket back.
* XCB calls the supplied callback when it wants us
to return ownership of the socket.
Creating C-usable callbacks from Haskell functions
which have indeterminate lifetimes is hard.
Since the only thing we need to know is if the
socket has been taken back or not (there are
no buffers to flush on the Haskell end yet) we
can do all of the callbacks with C code.
-}
-- | For passing to foreign libraries which
-- can make use of a libxcb connection.
withConnectionPtr :: Connection -> (Ptr Connection -> IO a) -> IO a
withConnectionPtr c k = I.withConnection (c_conn c) (k . castPtr)
-- | For a libxcb connection passed in from another library.
-- Be carefule forking threads or saving off a reference to the connection -
-- we can't coordinate the closing of the connection with the source
-- of the connection.
withForeignConnection :: Ptr Connection -> (Connection -> IO a) -> IO a
withForeignConnection ptr k =
I.mkConnection_ (castPtr ptr) >>= dressIConn >>= k
-- | The the Haskell xcb connection.
-- This has nothing to do with the lock used
-- on the inside of libxcb.
lockCon :: Connection -> IO a -> IO a
lockCon c = withLock (c_lock c)
foreign import ccall "&xcb_ffi_return_socket"
c_return_socket :: FunPtr (Ptr () -> IO ())
hasSocket :: Connection -> IO Bool
hasSocket c =
toBool <$> withForeignPtr (c_has_socket c) peek
takeSocket :: Connection -> [I.RequestFlags] -> IO Bool
takeSocket c fs = do
has <- hasSocket c
if has then return True else do
withForeignPtr (c_has_socket c) $ \hasPtr -> do
let flags = foldl' (.&.) 0 (map (fromIntegral . fromEnum) fs)
res <- I.takeSocket (c_conn c) c_return_socket (castPtr hasPtr) flags
case res of
Nothing -> return False
Just lastSeq
-> do
writeIORef (c_last_req c) lastSeq
withForeignPtr (c_has_socket c) (flip poke $ fromBool True)
return True
guardIO :: Bool -> IO ()
guardIO p = if p then return () else fail "guard failed"
{- |
Write raw bytes on to the connection with the server.
Returns the sequence number of the last request sent.
-}
writeRequests :: Connection -> L.ByteString -> Int -> IO Word64
writeRequests c bytes num
= lockCon c $ do
-- should probably have better error here
takeSocket c [] >>= guardIO
lastSeq <- readIORef (c_last_req c)
let newLast = lastSeq + fromIntegral num
ret <- I.writev (c_conn c) bytes (fromIntegral num)
guardIO ret -- should have better error here
writeIORef (c_last_req c) newLast
return newLast
connect :: IO (Maybe Connection)
connect = connect' ""
connect' :: String -> IO (Maybe Connection)
connect' displayStr
= do
ret <- I.connect displayStr
case ret of
Nothing -> return Nothing
Just (icon,_)
-> Just <$> dressIConn icon
dressIConn :: I.Connection -> IO Connection
dressIConn ptr = do
lastRef <- newIORef 0
hasPtr <- mallocForeignPtr
withForeignPtr hasPtr (flip poke 0)
lock <- newLock
return $ C ptr hasPtr lock lastRef
-- | Maximum size of a single request.
-- May not be an asynchronous call, as we'll make a call out
-- on the big-requests extension to find out if we can use that.
maximumRequestLength :: Connection -> IO Word32
maximumRequestLength = I.maximumRequestLength . c_conn
-- | Asynchronous version of 'maximumRequestLength'. The return
-- from the server is cached for subsequent callse to 'maximumRequestLength'.
prefetchMaximumReuestLength :: Connection -> IO ()
prefetchMaximumReuestLength = I.prefetchMaximumReuestLength . c_conn
-- | Is the connection in an error state?
connectionHasError :: Connection -> IO Bool
connectionHasError = I.connectionHasError . c_conn
-- | Allocation a new xid. May involve server interaction
-- (but likely won't).
generateId :: Connection -> IO Word32
generateId = I.generateId . c_conn
-- | Returns an event or error from the queue.
-- Errors associated with checked requests will not
-- be available from this call.
waitForEvent :: Connection -> IO S.ByteString
waitForEvent c = I.waitForEvent (c_conn c) >>= I.unsafeEventData
-- I haven't convinced myself this is safe to do without a lock.
-- Maybe a separate events lock on the connection?
waitForReply :: Connection -> I.Cookie -> IO (Either S.ByteString S.ByteString)
waitForReply c cookie
= do
resp <- I.waitForReply (c_conn c) cookie
case resp of
Left err -> Left <$> I.unsafeErrorData err
Right rep -> Right <$> I.unsafeReplyData rep
-- for locking, we might want to put a lock in the cookie
getSetup :: Connection -> IO S.ByteString
getSetup c = do
ret <- S.copy <$> (I.unsafeGetSetup (c_conn c) >>= I.unsafeSetupData)
-- there are still some cases where we don't copy the bytestring in time
I.touchConnection $ c_conn c
return ret
|
aslatter/xcb-core
|
Graphics/Xhb/Connection.hs
|
bsd-3-clause
| 5,758 | 0 | 22 | 1,140 | 1,250 | 635 | 615 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module BitD.Protocol.VarData
( VarInt(..)
, VarString(..)
) where
import qualified Data.ByteString as BS
import Data.String (IsString)
import qualified Data.Binary.Get as BinG
import qualified Data.Binary.Put as BinP
import qualified Data.Binary as Bin
import qualified Data.Serialize.Get as SerG
import qualified Data.Serialize.Put as SerP
import qualified Data.Serialize as Ser
import Control.Applicative ((<$>))
import Data.Word (Word64)
newtype VarInt = VarInt Word64
instance Bin.Binary VarInt where
get = VarInt <$> (BinG.getWord8 >>= go)
where go w | w < 0xfd = return $ fromIntegral w
| w == 0xfd = fromIntegral <$> BinG.getWord16le
| w == 0xfe = fromIntegral <$> BinG.getWord32le
| w == 0xff = fromIntegral <$> BinG.getWord64le
| otherwise = fail ""
put (VarInt v) | v < 0xfd = BinP.putWord8 $ fromIntegral v
| v <= 0xffff = do BinP.putWord8 0xfd
BinP.putWord16le $ fromIntegral v
| v <= 0xffffffff = do BinP.putWord8 0xfe
BinP.putWord32le $ fromIntegral v
| otherwise = do BinP.putWord8 0xff
BinP.putWord64le v
instance Ser.Serialize VarInt where
get = Bin.decode <$> (SerG.remaining >>= (SerG.getLazyByteString . fromIntegral))
put = SerP.putLazyByteString . Bin.encode
newtype VarString = VarString BS.ByteString
deriving (Show, IsString)
instance Bin.Binary VarString where
get = do
VarInt len <- Bin.get
VarString <$> BinG.getByteString (fromIntegral len)
put (VarString bs) = do
Bin.put $ VarInt $ fromIntegral $ BS.length bs
BinP.putByteString bs
|
benma/bitd
|
src/BitD/Protocol/VarData.hs
|
bsd-3-clause
| 1,812 | 0 | 11 | 519 | 534 | 281 | 253 | 41 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Data.Array.Accelerate.Pretty.HTML
-- Copyright : [2010..2011] Sean Seefried
-- License : BSD3
--
-- Maintainer : Manuel M T Chakravarty <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.Pretty.HTML (
-- * HTML printing function
dumpHtmlAST
) where
-- standard libraries
import Data.String
import Data.Monoid
import Text.Blaze.Html.Renderer.Utf8
import Text.Blaze.Html4.Transitional ( (!) )
import qualified Data.Text as T
import qualified Text.Blaze.Html4.Transitional as H
import qualified Text.Blaze.Html4.Transitional.Attributes as A
import System.IO.Error
import Control.Exception
import qualified Data.ByteString.Lazy as BS
-- friends
import Data.Array.Accelerate.AST
import Data.Array.Accelerate.Pretty.Traverse
combineHtml :: String -> String -> [H.Html] -> H.Html
combineHtml cssClass label nodes = do
let inner = foldl (>>) (return ()) nodes
H.div ! A.class_ ("node " `mappend` fromString cssClass `mappend` " expanded") $ do
H.span ! A.class_ "selector" $ H.toMarkup label
inner
leafHtml :: String -> String -> H.Html
leafHtml cssClass label =
H.div ! A.class_ ("node " `mappend` fromString cssClass `mappend` " leaf") $
H.span $ H.toMarkup label
htmlLabels :: Labels
htmlLabels = Labels { accFormat = "array-node"
, expFormat = "exp-node"
, funFormat = "fun-node"
, primFunFormat = "prim-fun-node"
, tupleFormat = "tuple-node"
, arrayFormat = "array-node"
, boundaryFormat = "boundary-node" }
-- combine :: Monad m => String -> String -> [m a] -> m a
-- combine = undefined
--
-- leafNode :: Monad m => String -> String -> m a
-- leafNode = undefined
htmlAST :: OpenAcc aenv a -> H.Html
htmlAST acc = H.docTypeHtml $
H.head $ do
H.meta ! A.httpEquiv "Content-Type" ! A.content "text/html; charset=UTF-8"
H.script ! A.type_ "text/javascript" !
A.src "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" $ mempty
H.link ! A.rel "stylesheet" ! A.href "accelerate.css" ! A.type_ "text/css"
H.script ! A.type_ "text/javascript" $ H.toMarkup $
T.unlines ["function collapse() {"
," var parent=$(this).parent();"
," var that = $(this);"
," parent.addClass(\"collapsed\").removeClass(\"expanded\");"
," parent.children().each(function (i) {"
," if ($(this).get(0) != that.get(0)) {"
," $(this).hide(100);"
," }"
," });"
," $(this).unbind();"
," $(this).click(expand);"
,"}"
, ""
, "function expand() {"
, "var parent=$(this).parent();"
, "parent.removeClass(\"collapsed\").addClass(\"expanded\");"
, "parent.children().show(100);"
, "$(this).show();"
, "$(this).unbind();"
, "$(this).click(collapse);"
, "}"
, "$(document).ready(function () {"
, " $('.expanded>.selector').click(collapse);"
, " $('.collapsed>.selector').click(expand);"
, "});"]
H.body $ do
H.table ! A.border "0" $
H.tr $ do
H.td ! A.class_ "acc-node" $ H.span "OpenAcc"
H.td ! A.class_ "fun-node" $ H.span "OpenFun"
H.td ! A.class_ "exp-node" $ H.span "OpenExp"
H.td ! A.class_ "prim-fun-node" $ H.span "PrimFun"
H.td ! A.class_ "tuple-node" $ H.span "Tuple"
H.td ! A.class_ "boundary-node" $ H.span "Boundary"
H.hr
travAcc htmlLabels combineHtml leafHtml acc
accelerateCSS :: String
accelerateCSS =
unlines
[ "body {"
, " font-family: Helvetica;"
, " font-size: 10pt;"
, "}"
, ".node {"
, " padding-left: 5px;"
, ""
, "}"
, ""
, ".expanded .node {"
, " padding-left: 12px;"
, "}"
, ""
, ".expanded .node.leaf {"
, " padding-left: 23px;"
, "}"
, ""
, ".acc-node>span { color: red; }"
, ".exp-node>span { color: blue;}"
, ".array-node>span { color: purple;}"
, ".fun-node>span { color: orange;}"
, ".prim-fun-node>span { color: magenta;}"
, ".tuple-node>span { color: green;}"
, ".boundary-node>span { color: darkcyan;} "
, ""
, ".selector, .leaf>span {"
, " padding: 2px 7px 2px 5px; "
, "}"
, ""
, ".selector:hover, .leaf>span:hover {"
, " background: #FC9;"
, " -webkit-border-radius: 10px;"
, " -moz-border-radius: 10px;"
, "}"
, ""
, ".leaf>span:hover {"
, " cursor: default;"
, "}"
, ""
, ".selector:hover {"
, " cursor: pointer;"
, "}"
, ""
, ".expanded .selector::before {"
, " font-size: 8pt;"
, " color: #999;"
, " content: \"\\25bc\";"
, "}"
, ""
, ".collapsed .selector::before {"
, " font-size: 8pt;"
, " color: #999;"
, " content: \"\\25ba\";"
, " position: relative;"
, ""
, "}"
, ""
, ".selector:hover::before {"
, " color: orange;"
, "}" ]
dumpHtmlAST :: String -> OpenAcc aenv a -> IO ()
dumpHtmlAST basename acc =
catch writeHtmlFile handler
where
writeHtmlFile = do
let cssPath = "accelerate.css"
let path = basename ++ ".html"
--
writeFile cssPath accelerateCSS
BS.writeFile path (renderHtml $ htmlAST acc)
putStrLn ("HTML file successfully written to `" ++ path ++ "'\n" ++
"CSS file written to `" ++ cssPath ++ "'")
handler :: IOError -> IO ()
handler e =
case True of
_ | isAlreadyInUseError e -> putStrLn "isAlreadyInUseError"
| isDoesNotExistError e -> putStrLn "isDoesNotExistError"
| isFullError e -> putStrLn "isFullError"
| isEOFError e -> putStrLn "isEOFError"
| isPermissionError e -> putStrLn "isPermissionError"
| isIllegalOperation e -> putStrLn "isIllegalOperation"
| isUserError e -> putStrLn "isUserError"
| otherwise -> putStrLn "Unknown error"
|
robeverest/accelerate
|
Data/Array/Accelerate/Pretty/HTML.hs
|
bsd-3-clause
| 6,668 | 2 | 19 | 2,160 | 1,247 | 679 | 568 | 163 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Site ( app ) where
------------------------------------------------------------------------------
import Control.Applicative
import Data.IORef
import Control.Monad.IO.Class
import Data.ByteString (ByteString)
import qualified Data.Text as T
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Auth
import Snap.Snaplet.Auth.Backends.JsonFile
import Snap.Snaplet.Heist
import Snap.Snaplet.Session.Backends.CookieSession
import Snap.Util.FileServe
import Heist
import qualified Heist.Interpreted as I
import Filter
------------------------------------------------------------------------------
import Application
import Snaplets
------------------------------------------------------------------------------
-- | The application's routes.
app :: SnapletInit App App
app = makeSnaplet "snapplejack" "The SnappleJack Web Server" Nothing $ do
hs <- nestSnaplet "heist" heist $ heistInit ""
fs <- nestSnaplet "foo" foo $ fooInit
bs <- nestSnaplet "bar" bar $ nameSnaplet "newname" $ barInit foo
addRoutes routes
ref <- liftIO $ newIORef "snapplejack"
return $ App hs fs bs ref
where
routes :: [(ByteString, Handler App App ())]
routes = [ ("/card", cardHandler)
, ("/deck", deckHandler)
, ("/res", serveDirectory "../res")
, ("", heistServe)
]
|
archaephyrryx/CCG-Project
|
src/Site.hs
|
bsd-3-clause
| 1,551 | 0 | 11 | 407 | 305 | 174 | 131 | 32 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Mandelbrot.NikolaV3.Implementation where
import qualified Prelude as P
import Prelude hiding (iterate, map, zipWith)
import Data.Array.Nikola.Backend.CUDA
import Data.Array.Nikola.Combinators
import Data.Array.Nikola.Eval
import Data.Int
import Data.Word
type R = Double
type RGBA = Word32
type Complex = (Exp R, Exp R)
type Bitmap r = Array r DIM2 (Exp RGBA)
type MBitmap r = MArray r DIM2 (Exp RGBA)
type ComplexPlane r = Array r DIM2 Complex
type MComplexPlane r = MArray r DIM2 Complex
type StepPlane r = Array r DIM2 (Complex, Exp Int32)
type MStepPlane r = MArray r DIM2 (Complex, Exp Int32)
magnitude :: Complex -> Exp R
magnitude (x,y) = x*x + y*y
instance Num Complex where
(x,y) + (x',y') = (x+x' ,y+y')
(x,y) - (x',y') = (x-x', y-y')
(x,y) * (x',y') = (x*x'-y*y', x*y'+y*x')
negate (x,y) = (negate x, negate y)
abs z = (magnitude z, 0)
signum (0,0) = 0
signum z@(x,y) = (x/r, y/r) where r = magnitude z
fromInteger n = (fromInteger n, 0)
stepN :: Exp Int32 -> ComplexPlane G -> MStepPlane G -> P ()
stepN n cs mzs = do
zs <- unsafeFreezeMArray mzs
loadP (zipWith stepPoint cs zs) mzs
where
stepPoint :: Complex -> (Complex, Exp Int32) -> (Complex, Exp Int32)
stepPoint c (z,i) = iterateWhile n go (z,i)
where
go :: (Complex, Exp Int32) -> (Exp Bool, (Complex, Exp Int32))
go (z,i) =
if magnitude z' >* 4.0
then (lift False, (z, i))
else (lift True, (z', i+1))
where
z' = next c z
next :: Complex -> Complex -> Complex
next c z = c + (z * z)
genPlane :: Exp R
-> Exp R
-> Exp R
-> Exp R
-> Exp Int32
-> Exp Int32
-> MComplexPlane G
-> P ()
genPlane lowx lowy highx highy viewx viewy mcs =
flip loadP mcs $
fromFunction (Z:.viewy:.viewx) $ \(Z:.y:.x) ->
(lowx + (fromInt x*xsize)/fromInt viewx, lowy + (fromInt y*ysize)/fromInt viewy)
where
xsize, ysize :: Exp R
xsize = highx - lowx
ysize = highy - lowy
mkinit :: ComplexPlane G -> MStepPlane G -> P ()
mkinit cs mzs = loadP (map f cs) mzs
where
f :: Complex -> (Complex, Exp Int32)
f z = (z,0)
prettyRGBA :: Exp Int32 -> (Complex, Exp Int32) -> Exp RGBA
{-# INLINE prettyRGBA #-}
prettyRGBA limit (_, s) = r + g + b + a
where
t = fromInt $ ((limit - s) * 255) `quot` limit
r = (t `mod` 128 + 64) * 0x1000000
g = (t * 2 `mod` 128 + 64) * 0x10000
b = (t * 3 `mod` 256 ) * 0x100
a = 0xFF
prettyMandelbrot :: Exp Int32 -> StepPlane G -> MBitmap G -> P ()
prettyMandelbrot limit zs mbmap =
loadP (map (prettyRGBA limit) zs) mbmap
mandelbrot :: Exp R
-> Exp R
-> Exp R
-> Exp R
-> Exp Int32
-> Exp Int32
-> Exp Int32
-> MComplexPlane G
-> MStepPlane G
-> P ()
mandelbrot lowx lowy highx highy viewx viewy depth mcs mzs = do
genPlane lowx lowy highx highy viewx viewy mcs
cs <- unsafeFreezeMArray mcs
mkinit cs mzs
stepN depth cs mzs
|
mainland/nikola
|
examples/mandelbrot/Mandelbrot/NikolaV3/Implementation.hs
|
bsd-3-clause
| 3,277 | 0 | 15 | 973 | 1,425 | 757 | 668 | 91 | 2 |
module Sexy.Data.Bool (
bool'
, otherwise
, module X
) where
import GHC.Types as X (Bool(..))
bool' :: a -> a -> Bool -> a
bool' x _ True = x
bool' _ x False = x
otherwise :: Bool
otherwise = True
|
DanBurton/sexy
|
src/Sexy/Data/Bool.hs
|
bsd-3-clause
| 211 | 0 | 7 | 57 | 86 | 51 | 35 | 10 | 1 |
{-# LANGUAGE TypeOperators, Rank2Types, ConstraintKinds, FlexibleContexts, CPP #-}
{-# LANGUAGE ViewPatterns, TupleSections #-}
{-# LANGUAGE DeriveFunctor, DeriveFoldable #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fcontext-stack=34 #-} -- for N32
-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : TypeEncode.Plugin
-- Copyright : (c) 2014 Tabula, Inc.
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Type-encode algebraic types. To test, compile and
--
-- cd ../../test; hermit Test.hs -v0 -opt=TypeEncode.Plugin +Test Auto.hss
----------------------------------------------------------------------
#define OnlyLifted
module TypeEncode.Plugin
( encodeOf, decodeOf
, reCaseR, reConstructR, encodeTypesR, plugin
, externals
) where
import Prelude hiding (id,(.),foldr)
import Control.Category (Category(..))
import Data.Functor ((<$>))
import Data.Foldable (Foldable(..))
import Control.Monad (mplus)
import Control.Arrow (Arrow(..),(>>>))
#ifdef OnlyLifted
import Data.List (isSuffixOf)
#endif
import Data.Maybe (fromMaybe)
import HERMIT.Monad (newIdH)
-- Note that HERMIT.Dictionary re-exports HERMIT.Dictionary.*
import HERMIT.Dictionary (findIdT, callNameT, callDataConT)
-- import HERMIT.Dictionary (traceR)
import HERMIT.External (External,external,ExternalName)
import HERMIT.GHC hiding (FastString(..))
import HERMIT.Kure hiding (apply)
import HERMIT.Plugin (hermitPlugin,phase,interactive)
-- From hermit-extras
import HERMIT.Extras
{--------------------------------------------------------------------
Misc
--------------------------------------------------------------------}
-- Binary leaf tree. Used to construct balanced nested sum and product types.
data Tree a = Empty | Leaf a | Branch (Tree a) (Tree a)
deriving (Show,Functor,Foldable)
toTree :: [a] -> Tree a
toTree [] = Empty
toTree [a] = Leaf a
toTree xs = Branch (toTree l) (toTree r)
where
(l,r) = splitAt (length xs `div` 2) xs
foldMapT :: b -> (a -> b) -> Binop b -> Tree a -> b
foldMapT e l b = h
where
h Empty = e
h (Leaf a) = l a
h (Branch u v) = b (h u) (h v)
foldT :: a -> Binop a -> Tree a -> a
foldT e b = foldMapT e id b
#if 0
-- I could almost use fold (from Data.Foldable) along with EitherTy and PairTy
-- monoids, each newtype-wrapping Type:
newtype PairTy = PairTy Type
instance Monoid PairTy where
mempty = PairTy unitTy
PairTy u `mappend` PairTy v = PairTy (u `pairTy` v)
newtype EitherTy = EitherTy Type
instance Monoid EitherTy where
mempty = EitherTy voidTy
EitherTy u `mappend` EitherTy v = EitherTy (u `eitherTy` v)
-- Sadly, voidTy and eitherTy require looking up names. I'm tempted to use
-- unsafePerformIO to give pure interfaces to all of these lookups.
-- However, I don't know how, since I'm using TransformU rather than IO.
#endif
#ifdef OnlyLifted
dcUnboxedArg :: DataCon -> Bool
dcUnboxedArg = isSuffixOf "#" . uqName . dataConName
-- TODO: use unliftedType instead of dcUnboxedArg.
#endif
mkPairTree :: TransformU ([CoreExpr] -> CoreExpr)
mkPairTree = do unit <- mkUnit
pair <- mkPair
return (foldT unit pair . toTree)
-- TODO: mkUnit, mkPair, mkPairTree needn't be in TransformU
-- <https://github.com/conal/type-encode/issues/3>
mkVoidTy :: TransformU Type
mkVoidTy = tcFind0 "TypeEncode.Encode.Void"
{--------------------------------------------------------------------
Rewrites
--------------------------------------------------------------------}
encName :: Unop String
encName = ("TypeEncode.Encode." ++)
appsE :: String -> [Type] -> [CoreExpr] -> TransformU CoreExpr
appsE = apps' . encName
callNameEnc :: String -> TransformH CoreExpr (CoreExpr, [CoreExpr])
callNameEnc = callNameT . encName
encodeOf :: Type -> Type -> CoreExpr -> TransformU CoreExpr
encodeOf ty ty' e = do -- guardMsg (not (unliftedType ty')) "encodeOf: unlifted type"
appsE "encodeF" [ty,ty'] [e]
decodeOf :: Type -> Type -> CoreExpr -> TransformU CoreExpr
decodeOf ty ty' e = do -- guardMsg (not (unliftedType ty)) "decodeOf: unlifted type"
appsE "decodeF" [ty',ty] [e]
-- Those guards don't really fit. I want to ensure that no constructed
-- expressions are of unlifted types.
standardTy :: Type -> Bool
standardTy (coreView -> Just ty) = standardTy ty
standardTy ty = any ($ ty) [isPairTy,isEitherTy,isUnitTy] -- ,isBoolTy
#if 0
-- Old code. Remove after handling 'case' expressions.
-- e --> decode (encode e)
decodeEncodeR :: ReExpr
decodeEncodeR = do e <- idR
guardMsg (not (isType e)) "Given a Type expression"
let ty = exprType' e
ty' <- encodeTy ty
decodeR ty ty' . encodeR ty ty'
-- TODO: Drop decodeEncodeR
encodeTy :: Type -> TransformU Type
encodeTy (coreView -> Just ty) = encodeTy ty
encodeTy (standardTy -> True) = fail "Already a standard type"
encodeTy (TyConApp tc tcTys) = do enc <- mkEncodeDCs
return (enc tcTys (tcCons tc))
encodeTy _ = fail "encodeTy: not handled"
type EncodeDCsT = [Type] -> Tree DataCon -> Type
mkEncodeDCs :: TransformU EncodeDCsT
mkEncodeDCs = liftM2 encodeDCs mkVoidTy mkEither
encodeDCs :: Type -> Binop Type -> EncodeDCsT
encodeDCs voidTy eitherTy tcTys dcs =
foldT voidTy eitherTy (encodeDC tcTys <$> dcs)
#endif
-- encode @a @b u --> ((a,b),u) (with type arguments)
unEncode' :: TransformH CoreExpr ((Type,Type),CoreExpr)
unEncode' = do (_encode, [Type a, Type b, arg]) <- callNameEnc "encodeF"
return ((a,b),arg)
-- decode @a @b u --> ((a,b),u) (with type arguments)
unDecode' :: TransformH CoreExpr ((Type,Type),CoreExpr)
unDecode' = do (_decode, [Type a, Type b, arg]) <- callNameEnc "decodeF"
return ((a,b),arg)
-- encode u --> u (without type arguments)
unEncode :: ReExpr
unEncode = snd <$> unEncode'
-- decode e --> e (without type arguments)
unDecode :: ReExpr
unDecode = snd <$> unDecode'
-- encode (decode e) --> e
unEncodeDecode :: ReExpr
unEncodeDecode = unEncode >>> unDecode
-- To encode Bool also, remove isBoolTy from standardTy.
tcCons :: TyCon -> Tree DataCon
tcCons = toTree . tyConDataCons
encodeDC :: [Type] -> DataCon -> Type
encodeDC tcTys dc = foldT unitTy pairTy (toTree argTys)
where
(tvs,body) = splitForAllTys (dataConRepType dc)
argTys = substTysWith tvs tcTys (fst (splitFunTys body))
-- Given a constructor application of a "nonstandard", ground type, construct
-- its sum-of-products encoding and the type of that encoding.
findCon :: TransformH (DataCon, [Type], [CoreExpr]) (Type,CoreExpr)
findCon =
do (dc, tys, args) <- idR
#ifdef OnlyLifted
guardMsg (not (dcUnboxedArg dc)) "Unboxed constructor argument"
#endif
inside <- ($ args) <$> mkPairTree
voidTy <- mkVoidTy
eitherTy <- mkEither
lft <- mkLeft
rht <- mkRight
let find :: Tree DataCon -> (Type,Maybe CoreExpr)
find = foldMapT e l b
where
e = (voidTy,Nothing)
l dc' = ( encodeDC tys dc'
, if dc == dc' then Just inside else Nothing )
b (tl,mbl) (tr,mbr) =
(eitherTy tl tr, (lft tl tr <$> mbl) `mplus` (rht tl tr <$> mbr))
return $
second (fromMaybe (error "findCon: Didn't find data con")) $
find (tcCons (dataConTyCon dc))
-- Not a function and not a forall
groundType :: Type -> Bool
groundType (coreView -> Just ty) = groundType ty
groundType (FunTy {}) = False
groundType (ForAllTy {}) = False
groundType _ = True
acceptGroundTyped :: RewriteH Type
acceptGroundTyped =
acceptWithFailMsgR ( groundType) "Not ground" >>>
acceptWithFailMsgR (not . standardTy) "Already a standard type"
-- | Rewrite a constructor application, eta-expanding if necessary.
-- Must be saturated with type and value arguments.
reConstructR :: ReExpr
reConstructR = acceptWithFailMsgR (not . isType) "Given a Type" >>>
(arr exprType' &&& id) >>> encodeCon >>> decodeCon
where
encodeCon :: TransformH (Type,CoreExpr) (Type,(Type,CoreExpr))
encodeCon = acceptGroundTyped *** (callDataConT >>> findCon)
decodeCon :: TransformH (Type,(Type,CoreExpr)) CoreExpr
decodeCon = do (ty,(ty',e)) <- idR
decodeOf ty ty' e
-- TODO: Eta-expand as necessary
-- <https://github.com/conal/type-encode/issues/4>
-- mkEitherF :: TransformU (Binop CoreExpr)
-- mkEitherF = error "mkEitherF: not yet implemented"
-- Build a tree of either applications and return the domain of the resulting
-- function. The range is given.
mkEitherTree :: Type -> Tree CoreExpr -> TransformU (Type,CoreExpr)
mkEitherTree ran funs =
do eitherF <- findIdT "either"
eitherTy <- mkEither
let eithers :: Tree CoreExpr -> (Type,CoreExpr)
eithers Empty = error "empty either" -- What to do here?
eithers (Leaf f) = (fst (splitFunTy (exprType' f)), f)
eithers (Branch fs gs) =
(eitherTy domf domg, apps eitherF [domf,ran,domg] [f,g])
where
(domf,f) = eithers fs
(domg,g) = eithers gs
return (eithers funs)
-- either :: forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
case1 :: CoreExpr -> Tree Var -> CoreExpr -> TransformH a CoreExpr
case1 scrut Empty rhs =
do wild <- constT (newIdH "wild" (exprType' scrut))
return $
Case scrut wild (exprType' rhs) [(DataAlt unitCon,[],rhs)]
case1 _ (Leaf _) _ = error "case1: Leaf"
case1 scrut (Branch (Leaf u) (Leaf v)) rhs =
do wild <- constT (newIdH "wild" (exprType' scrut))
return $
Case scrut wild (exprType' rhs) [(DataAlt pairCon,[u,v],rhs)]
case1 scrut (Branch (Leaf u) vs) rhs =
do v <- constT (newIdH "v" (varsType vs))
rhsv <- case1 (Var v) vs rhs
case1 scrut (Branch (Leaf u) (Leaf v)) rhsv
case1 scrut (Branch us (Leaf v)) rhs =
do u <- constT (newIdH "u" (varsType us))
rhsu <- case1 (Var u) us rhs
case1 scrut (Branch (Leaf u) (Leaf v)) rhsu
case1 scrut (Branch us vs) rhs =
do u <- constT (newIdH "u" (varsType us))
rhsu <- case1 (Var u) us rhs
v <- constT (newIdH "v" (varsType vs))
rhsv <- case1 (Var v) vs rhsu
case1 scrut (Branch (Leaf u) (Leaf v)) rhsv
-- TODO: Refactor much more neatly!
-- <https://github.com/conal/type-encode/issues/5>
varsType :: Tree Var -> Type
varsType = foldT unitTy pairTy . fmap varType
reCaseR :: ReExpr
reCaseR =
do Case scrut _wild bodyTy alts <- idR
let scrutTy = exprType' scrut
(_,tyArgs) = splitAppTys scrutTy
reAlt :: CoreAlt -> TransformH a CoreExpr
reAlt (DataAlt con, vars, rhs) =
do
#ifdef OnlyLifted
let lifteds = (not . unliftedType . varType) <$> vars
guardMsg (and lifteds) "reCaseR: unlifted type"
#endif
case vars of
[var] -> return (Lam var rhs)
_ -> do z <- constT (newIdH "z" (encodeDC tyArgs con))
Lam z <$> case1 (Var z) (toTree vars) rhs
reAlt _ = fail "Alternative is not a DataAlt"
guardMsg (not (standardTy scrutTy)) "Already a standard type"
(scrutTy',alts') <- mkEitherTree bodyTy =<< (toTree <$> mapM reAlt alts)
scrut' <- encodeOf scrutTy scrutTy' scrut
return (App alts' scrut')
-- TODO: check for use of _wild
-- <https://github.com/conal/type-encode/issues/6>
-- TODO: Check that all constructors are present.
-- <https://github.com/conal/type-encode/issues/7>
unitCon, pairCon :: DataCon
unitCon = tupleCon BoxedTuple 0
pairCon = tupleCon BoxedTuple 2
-- lamPairTree = error "lamPairTree: Please implement"
-- -- | Apply a rewrite at most n times.
-- tryN :: MonadCatch m => Int -> Unop (Rewrite c m b)
-- tryN n = foldr (\ r rest -> tryR (r >>> rest)) idR . replicate n
{--------------------------------------------------------------------
Plugin
--------------------------------------------------------------------}
plugin :: Plugin
plugin = hermitPlugin (phase 0 . interactive externals)
-- | Combination of type-decoding transformations.
encodeTypesR :: ReExpr
encodeTypesR = reConstructR <+ reCaseR
externC :: Injection a Core =>
ExternalName -> RewriteH a -> String -> External
externC name rew help = external name (promoteR rew :: ReCore) [help]
externals :: [External]
externals =
[ externC "un-encode-decode" unEncodeDecode "encode (decode e) -> e"
, externC "re-construct" reConstructR "encode constructor application"
, externC "re-case" reCaseR "encode case expression"
, externC "encode-types" encodeTypesR
"encode case expressions and constructor applications"
-- , externC "decode-encode" decodeEncodeR "e --> decode (encode e)"
-- , external "try-n" ((\ n r -> promoteExprR (tryN n r)) :: Int -> ReExpr -> ReCore)
-- ["Apply a rewrite at most n times"]
]
|
conal/type-encode
|
src/TypeEncode/Plugin.hs
|
bsd-3-clause
| 13,134 | 0 | 22 | 2,907 | 3,456 | 1,826 | 1,630 | 189 | 3 |
{-# LANGUAGE NoImplicitPrelude #-}
module HMenu.Provider (module X) where
import HMenu.Provider.Path as X
import HMenu.Provider.Types as X
import HMenu.Provider.XDG as X
|
Adirelle/hmenu
|
src/HMenu/Provider.hs
|
bsd-3-clause
| 205 | 0 | 4 | 56 | 37 | 27 | 10 | 5 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE GADTs #-}
module Llvm.Pass.Rewriter where
import Control.Monad
import Data.Maybe
import Prelude hiding (succ)
import qualified Compiler.Hoopl as H
import Llvm.Hir.Data
import Llvm.Query.Type
import Llvm.Util.Monadic (maybeM)
import Debug.Trace
type MaybeChange a = a -> Maybe a
{-
f2t :: (a -> Maybe a) -> (Typed a, Typed a) -> Maybe (Typed a, Typed a)
f2t f ((TypedData t1 a1), (TypedData t2 a2)) = case (f a1, f a2) of
(Nothing, Nothing) -> Nothing
(a1', a2') -> Just (TypedData t1 $ fromMaybe a1 a1', TypedData t2 $ fromMaybe a2 a2')
f2 :: (a -> Maybe a) -> (a, a) -> Maybe (a, a)
f2 f (a1, a2) = case (f a1, f a2) of
(Nothing, Nothing) -> Nothing
(a1', a2') -> Just (fromMaybe a1 a1', fromMaybe a2 a2')
f3 :: (a -> Maybe a) -> (Typed a, Typed a, Typed a) -> Maybe (Typed a, Typed a, Typed a)
f3 f (TypedData t1 a1, TypedData t2 a2, TypedData t3 a3) = case (f a1, f a2, f a3) of
(Nothing, Nothing, Nothing) -> Nothing
(a1', a2', a3') -> Just (TypedData t1 $ fromMaybe a1 a1'
, TypedData t2 $ fromMaybe a2 a2'
, TypedData t3 $ fromMaybe a3 a3')
fs :: Eq a => (a -> Maybe a) -> [Typed a] -> Maybe [Typed a]
fs f ls = let ls' = map (\(TypedData t x) -> TypedData t (fromMaybe x (f x))) ls
in if ls == ls' then Nothing else Just ls'
rwIbinExpr :: MaybeChange a -> MaybeChange (IbinExpr a)
rwIbinExpr f e = let (v1, v2) = operandOfIbinExpr e
t = typeOfIbinExpr e
in do { (v1', v2') <- f2 f (v1, v2)
; return $ newBinExpr t v1' v2'
}
where newBinExpr t v1 v2 =
case e of
Add nw _ _ _ -> Add nw t v1 v2
Sub nw _ _ _ -> Sub nw t v1 v2
Mul nw _ _ _ -> Mul nw t v1 v2
Udiv nw _ _ _ -> Udiv nw t v1 v2
Sdiv nw _ _ _ -> Sdiv nw t v1 v2
Urem _ _ _ -> Urem t v1 v2
Srem _ _ _ -> Srem t v1 v2
Shl nw _ _ _ -> Shl nw t v1 v2
Lshr nw _ _ _ -> Lshr nw t v1 v2
Ashr nw _ _ _ -> Ashr nw t v1 v2
And _ _ _ -> And t v1 v2
Or _ _ _ -> Or t v1 v2
Xor _ _ _ -> Xor t v1 v2
rwFbinExpr :: MaybeChange a -> MaybeChange (FbinExpr a)
rwFbinExpr f e = let (v1, v2) = operandOfFbinExpr e
t = typeOfFbinExpr e
in do { (v1', v2') <- f2 f (v1, v2)
; return $ newBinExpr t v1' v2'
}
where newBinExpr t v1 v2 =
case e of
Fadd fg _ _ _ -> Fadd fg t v1 v2
Fsub fg _ _ _ -> Fsub fg t v1 v2
Fmul fg _ _ _ -> Fmul fg t v1 v2
Fdiv fg _ _ _ -> Fdiv fg t v1 v2
Frem fg _ _ _ -> Frem fg t v1 v2
rwBinExpr :: MaybeChange a -> MaybeChange (BinExpr a)
rwBinExpr f (Ie e) = liftM Ie (rwIbinExpr f e)
rwBinExpr f (Fe e) = liftM Fe (rwFbinExpr f e)
rwConversion :: MaybeChange a -> MaybeChange (Conversion a)
rwConversion f (Conversion co (TypedData ts v) t) =
do { v1 <- f v
; return $ Conversion co (TypedData ts v1) t
}
rwGetElemPtr :: Eq a => MaybeChange a -> MaybeChange (GetElemPtr a)
rwGetElemPtr f (GetElemPtr b (TypedData ts (Pointer v)) indices) =
do { v1 <- f v
-- ; indices1 <- fs f indices
; return $ GetElemPtr b (TypedData ts (Pointer v1)) indices
}
rwSelect :: MaybeChange a -> MaybeChange (Select a)
rwSelect f (Select tv1 tv2 tv3) = do { (tv1', tv2', tv3') <- f3 f (tv1, tv2, tv3)
; return $ Select tv1' tv2' tv3'
}
rwIcmp :: MaybeChange a -> MaybeChange (Icmp a)
rwIcmp f (Icmp op t v1 v2) = do { (v1', v2') <- f2 f (v1, v2)
; return $ Icmp op t v1' v2'
}
rwFcmp :: MaybeChange a -> MaybeChange (Fcmp a)
rwFcmp f (Fcmp op t v1 v2) = do { (v1', v2') <- f2 f (v1, v2)
; return $ Fcmp op t v1' v2'
}
tv2v :: MaybeChange Value -> MaybeChange (Typed Value)
tv2v f (TypedData t x) = liftM (TypedData t) (f x)
tp2p :: MaybeChange Value -> MaybeChange (Typed (Pointer Value))
tp2p f x | trace ("tp2p " ++ (show x)) False = undefined
tp2p f (TypedData t (Pointer x)) = liftM (\p -> TypedData t (Pointer p)) (f x)
rwExpr :: MaybeChange Value -> MaybeChange Expr
rwExpr f (EgEp gep) = rwGetElemPtr f gep >>= return . EgEp
rwExpr f (EiC a) = rwIcmp f a >>= return . EiC
rwExpr f (EfC a) = rwFcmp f a >>= return . EfC
rwExpr f (Eb a) = rwBinExpr f a >>= return . Eb
rwExpr f (Ec a) = rwConversion f a >>= return . Ec
rwExpr f (Es a) = rwSelect f a >>= return . Es
rwExpr f (Ev x) = (tv2v f x) >>= return . Ev
rwMemOp :: MaybeChange Value -> MaybeChange Rhs
rwMemOp f x | trace ("rwMemOp " ++ (show x)) False = undefined
rwMemOp f (RmO (Allocate m t ms ma)) = do { ms' <- maybeM (tv2v f) ms
; return $ RmO $ Allocate m t ms' ma
}
rwMemOp f (RmO (Load x ptr a1 a2 a3 a4)) =
do { tp <- (tp2p f) ptr
; traceM $ "tp:" ++ show tp
; return $ RmO (Load x tp a1 a2 a3 a4)
}
{-
rwMemOp f (RmO (LoadAtomic _ _ (TypedData (Tpointer t _) ptr) _)) = do { tv <- (tv2v f) (TypedData t (Deref ptr))
; return $ Re $ Ev tv
}
-}
-- rwMemOp f (RmO (Free tv)) = (tv2v f) tv >>= return . RmO . Free
rwMemOp f (RmO (Store a tv1 tv2 ma nt)) = do { tv1' <- (tv2v f) tv1
; return $ RmO $ Store a tv1' tv2 ma nt
}
rwMemOp f (RmO (StoreAtomic at a tv1 tv2 ma)) = do { tv1' <- (tv2v f) tv1
; return $ RmO $ StoreAtomic at a tv1' tv2 ma
}
rwMemOp f (RmO (CmpXchg wk b ptr v1 v2 b2 fe ff)) = do { (v1', v2') <- f2 (tv2v f) (v1, v2)
; return $ RmO $ CmpXchg wk b ptr v1' v2' b2 fe ff
}
rwMemOp f (RmO (AtomicRmw b ao ptr v1 b2 fe)) = do { v1' <- (tv2v f) v1
; return $ RmO $ AtomicRmw b ao ptr v1' b2 fe
}
rwMemOp _ _ = error "impossible case"
rwShuffleVector :: MaybeChange a -> MaybeChange (ShuffleVector a)
rwShuffleVector f (ShuffleVector tv1 tv2 tv3) =
do { (tv1', tv2', tv3') <- f3 f (tv1, tv2, tv3)
; return $ ShuffleVector tv1' tv2' tv3'
}
rwExtractValue :: MaybeChange a -> MaybeChange (ExtractValue a)
rwExtractValue f (ExtractValue (TypedData t v) s) =
f v >>= \v1 -> return $ ExtractValue (TypedData t v1) s
rwInsertValue :: MaybeChange a -> MaybeChange (InsertValue a)
rwInsertValue f (InsertValue tv1 tv2 s) = do { (tv1', tv2') <- f2t f (tv1, tv2)
; return $ InsertValue tv1' tv2' s
}
rwExtractElem :: MaybeChange a -> MaybeChange (ExtractElem a)
rwExtractElem f (ExtractElem tv1 tv2) = do { (tv1', tv2') <- f2t f (tv1, tv2)
; return $ ExtractElem tv1' tv2'
}
rwInsertElem :: MaybeChange a -> MaybeChange (InsertElem a)
rwInsertElem f (InsertElem tv1 tv2 tv3) = do { (tv1', tv2', tv3') <- f3 f (tv1, tv2, tv3)
; return $ InsertElem tv1' tv2' tv3'
}
rwRhs :: MaybeChange Value -> MaybeChange Rhs
rwRhs f (RmO a) = rwMemOp f (RmO a)
rwRhs _ (Call _ _) = Nothing
rwRhs f (Re a) = rwExpr f a >>= return . Re
rwRhs f (ReE a) = rwExtractElem f a >>= return . ReE
rwRhs f (RiE a) = rwInsertElem f a >>= return . RiE
rwRhs f (RsV a) = rwShuffleVector f a >>= return . RsV
rwRhs f (ReV a) = rwExtractValue f a >>= return . ReV
rwRhs f (RiV a) = rwInsertValue f a >>= return . RiV
rwRhs f (VaArg tv t) = (tv2v f) tv >>= \tv' -> return $ VaArg tv' t
rwRhs _ (LandingPad _ _ _ _ _) = Nothing
rwComputingInst :: MaybeChange Value -> MaybeChange ComputingInst
rwComputingInst f (ComputingInst lhs rhs) = rwRhs f rhs >>= return . (ComputingInst lhs)
rwComputingInstWithDbg :: MaybeChange Value -> MaybeChange ComputingInstWithDbg
rwComputingInstWithDbg f (ComputingInstWithDbg cinst dbgs) =
rwComputingInst f cinst >>= \cinst' -> return $ ComputingInstWithDbg cinst' dbgs
rwCinst :: MaybeChange Value -> MaybeChange (Node e x)
rwCinst f (Cinst c) = rwComputingInstWithDbg f c >>= return . Cinst
rwCinst _ _ = Nothing
rwTerminatorInst :: MaybeChange Value -> MaybeChange TerminatorInst
rwTerminatorInst f (Return ls) = do { ls' <- fs f ls
; return $ Return ls'
}
rwTerminatorInst f (Cbr v tl fl) = do { v' <- f v
; return $ Cbr v' tl fl
}
rwTerminatorInst _ _ = Nothing
-- rwTerminatorInst f e = error ("unhandled case " ++ (show e))
rwTerminatorInstWithDbg :: MaybeChange Value -> MaybeChange TerminatorInstWithDbg
rwTerminatorInstWithDbg f (TerminatorInstWithDbg cinst dbgs) =
rwTerminatorInst f cinst >>= \cinst' -> return $ TerminatorInstWithDbg cinst' dbgs
rwTinst :: MaybeChange Value -> MaybeChange (Node e x)
rwTinst f (Tinst c) = rwTerminatorInstWithDbg f c >>= return . Tinst
rwTinst _ _ = Nothing
-}
rwNode :: MaybeChange Value -> MaybeChange (Node a e x)
rwNode = undefined
{-
rwNode f n@(Cinst _) = rwCinst f n
rwNode f n@(Tinst _) = rwTinst f n
rwNode _ _ = Nothing
-}
nodeToGraph :: Node a e x -> H.Graph (Node a) e x
nodeToGraph n@(Lnode _) = H.mkFirst n
nodeToGraph n@(Pnode _ _) = H.mkMiddle n
nodeToGraph n@(Cnode _ _) = H.mkMiddle n
nodeToGraph n@(Tnode _ _) = H.mkLast n
|
sanjoy/hLLVM
|
src/Llvm/Pass/Rewriter.hs
|
bsd-3-clause
| 10,436 | 0 | 8 | 3,972 | 235 | 130 | 105 | 19 | 1 |
module Main where
import FragnixServer (
application)
import Network.Wai.Handler.Warp (
run)
main :: IO ()
main = run 8081 application
|
phischu/fragnix-server
|
executable-src/Main.hs
|
bsd-3-clause
| 144 | 0 | 6 | 29 | 44 | 26 | 18 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Combined where
import Nero
import Nero.Application (nest)
import Data.Text.Lazy (Text)
name :: Request -> Maybe Text
name = preview (_GET . path . prefixed "/hello/")
surname :: Request -> Maybe Text
surname = preview (param "surname")
app1 :: Request -> Maybe Response
app1 = name <&> fmap (\n -> ok $ "<h1>Hello " <> n <> "</h1>")
app2 :: Request -> Maybe Response
app2 = surname <&> fmap (\s -> ok $ "<h1>Hello " <> s <> "</h1>")
app12 :: Request -> Maybe Response
app12 request = respond <$> name request <*> surname request
where
respond n s = ok $ "<h1>Hello " <> n <> " " <> s <> "</h1>"
nested :: Request -> Maybe Response
nested = nest (prefixed "/name") [app1, app2]
|
plutonbrb/nero-examples
|
examples/Combined.hs
|
bsd-3-clause
| 732 | 0 | 11 | 143 | 277 | 145 | 132 | 18 | 1 |
module Console
( defaultKeys
, draw
, getAction
) where
import Data.Array.IArray
import Data.Function (on)
import Data.List (groupBy)
import Graphics.Vty
import Types
draw :: Vty -> Level -> IO ()
draw vty level = do
let level' = amap drawCell level
cells = assocs level'
rows = (map.map) snd $ groupBy ((==) `on` fst.fst) cells
picture = picForImage . vertCat $ map horizCat rows
update vty $ picture { picCursor = NoCursor }
drawCell :: Block -> Image
drawCell Void = string (withForeColor defAttr brightBlack) "."
drawCell Empty = string defAttr " "
drawCell Wall = string (withForeColor defAttr brightBlack) "X"
drawCell (ActorBlock actor) = actorImage actor
type KeyMap = [(Event, GAction)]
defaultKeys :: KeyMap
defaultKeys =
[(EvKey KEsc [], Quit)
,(EvKey (KChar 'q') [], Quit)
,(EvKey KUp [], Move DUp)
,(EvKey (KChar 'w') [], Move DUp)
,(EvKey KDown [], Move DDown)
,(EvKey (KChar 's') [], Move DDown)
,(EvKey KLeft [], Move DLeft)
,(EvKey (KChar 'a') [], Move DLeft)
,(EvKey KRight [], Move DRight)
,(EvKey (KChar 'd') [], Move DRight)
,(EvKey (KChar ' ') [], Attack)
]
getAction :: KeyMap -> Vty -> IO GAction
getAction keyMap vty = do
ev <- nextEvent vty
case lookup ev keyMap of
Just action -> return action
_ -> getAction keyMap vty
|
bjornars/HaskellGame
|
src/Console.hs
|
bsd-3-clause
| 1,450 | 0 | 14 | 412 | 583 | 305 | 278 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module NanoParsec where
import Data.Char
import Control.Monad
import Control.Applicative
newtype Parser a = Parser { parse :: String -> [(a, String)] }
runParser :: Parser a -> String -> a
runParser m s =
case parse m s of
[(res, [])] -> res
[(_, rs)] -> error "Parser did not consume entire stream."
_ -> error "Parser error."
item :: Parser Char
item = Parser $ \s ->
case s of
[] -> []
(c:cs) -> [(c,cs)]
bind :: Parser a -> (a -> Parser b) -> Parser b
bind p f = Parser $ \s -> concatMap (\(a, s') -> parse (f a) s') $ parse p s
unit :: a -> Parser a
unit a = Parser (\s -> [(a, s)])
-- A Functor is a data structure that you can map over.
-- Calling fmap on a function and a Functor returns a Functor where each item
-- is mapped under the function.
instance Functor Parser where
fmap f (Parser cs) = Parser $ \s -> [(f a, b) | (a, b) <- cs s]
-- An Applicative Functor is a Functor which allows you to
-- bind a `Monad (a -> b)` with a `Monad a` to produce a `Monad b`.
instance Applicative Parser where
pure = unit
(Parser cs1) <*> (Parser cs2) = Parser $ apply cs1 cs2
where apply cs1 cs2 s = [(f a, s2) | (f, s1) <- cs1 s, (a, s2) <- cs2 s1]
-- A Monad is like an action to be performed and a context to perform it in.
-- Calling return on a value wraps the value in a Monad.
-- The bind (>>=) function composes two Monads together.
instance Monad Parser where
return = unit
(>>=) = bind
-- Produce the empty parser.
failure :: Parser a
failure = Parser (\cs -> [])
-- Concat the results of parsing with each of two parsers.
combine :: Parser a -> Parser a -> Parser a
combine p q = Parser $ \s -> parse p s ++ parse q s
-- Try parsing with the first parser, and if it fails use the second.
option :: Parser a -> Parser a -> Parser a
option p q = Parser $ \s ->
case parse p s of
[] -> parse q s
res -> res
instance MonadPlus Parser where
mzero = failure
mplus = combine
instance Alternative Parser where
empty = mzero
(<|>) = option
-- | One or more.
-- some :: Alternative f => f a -> f [a]
-- some v = some_v
-- where
-- many_v = some_v <|> pure []
-- some_v = (:) <$> v <*> many_v
-- | Zero or more.
-- many :: Alternative f => f a -> f [a]
-- many v = many_v
-- where
-- many_v = some_v <|> pure []
-- some_v = (:) <$> v <*> many_v
general_satisfy :: Parser a -> (a -> Bool) -> Parser a
general_satisfy parser pred = parser `bind` \a ->
if pred a
then unit a
else failure
satisfy = general_satisfy item
oneOf :: [Char] -> Parser Char
oneOf s = satisfy $ flip elem s
chainl :: Parser a -> Parser (a -> a -> a) -> a -> Parser a
chainl p op a = (p `chainl1` op) <|> return a
chainl1 :: Parser a -> Parser (a -> a ->a) -> Parser a
p `chainl1` op = do { a <- p; rest a }
where rest a = (do f <- op
b <- p
rest (f a b)
) <|> return a
char :: Char -> Parser Char
char c = satisfy (c ==)
natural :: Parser Integer
natural = read <$> some (satisfy isDigit)
string :: String -> Parser String
string [] = return []
string (c:cs) = do { char c; string cs; return (c:cs) }
token :: Parser a -> Parser a
token p = do { a <- p; spaces; return a }
reserved :: String -> Parser String
reserved s = token (string s)
spaces :: Parser String
spaces = many $ oneOf " \n\r"
digit :: Parser Char
digit = satisfy isDigit
number :: Parser Int
number = do
s <- string "-" <|> return []
cs <- some digit
return $ read (s ++ cs)
parens :: Parser a -> Parser a
parens m = do
reserved "("
n <- m
reserved ")"
return n
-- Expression types, evaluation, and parsing.
data Expr
= Add Expr Expr
| Mul Expr Expr
| Sub Expr Expr
| Lit Int
deriving Show
eval :: Expr -> Int
eval ex = case ex of
(Add a b) -> eval a + eval b
(Mul a b) -> eval a * eval b
(Sub a b) -> eval a - eval b
(Lit n) -> n
int :: Parser Expr
int = do
n <- number
return $ Lit n
expr :: Parser Expr
expr = term `chainl1` addop
term :: Parser Expr
term = factor `chainl1` mulop
factor :: Parser Expr
factor = int <|> parens expr
infixOp :: String -> (a -> a -> a) -> Parser (a -> a -> a)
infixOp s op = reserved s >> return op
addop = infixOp "+" Add
mulop = infixOp "*" Mul
run :: String -> Expr
run = runParser expr
|
zanesterling/haskell-compiler
|
src/NanoParsec/NanoParsec.hs
|
bsd-3-clause
| 4,361 | 0 | 13 | 1,148 | 1,644 | 850 | 794 | 115 | 4 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] -
[@ISO639-2B@] paa
[@ISO639-3@] hui
[@Native name@] -
[@English name@] Huli
-}
module Text.Numeral.Language.PAA.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Prelude ( Num )
import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
cardinals ∷ (Num i) ⇒ TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (1, "mbira")
, (2, "kira")
, (3, "tebira")
, (4, "maria")
, (5, "duria")
, (6, "waragaria")
, (7, "karia")
, (8, "halira")
, (9, "dira")
, (10, "pira")
, (11, "bearia")
, (12, "hombearia")
, (13, "haleria")
, (14, "deria")
, (15, "nguira")
, (16, "nguira-ni mbira")
, (17, "nguira-ni kira")
, (18, "nguira-ni tebira")
, (19, "nguira-ni maria")
, (20, "nguira-ni duria")
, (21, "nguira-ni waragaria")
, (22, "nguira-ni karia")
, (23, "nguira-ni halira")
, (24, "nguira-ni dira")
, (25, "nguira-ni pira")
, (26, "nguira-ni bearia")
, (27, "nguira-ni hombearia")
, (28, "nguira-ni haleria")
, (29, "nguira-ni deria")
, (30, "ngui ki")
, (31, "ngui ki, ngui tebone-gonaga mbira")
, (32, "ngui ki, ngui tebone-gonaga kira")
, (33, "ngui ki, ngui tebone-gonaga tebira")
, (34, "ngui ki, ngui tebone-gonaga maria")
, (35, "ngui ki, ngui tebone-gonaga duria")
, (36, "ngui ki, ngui tebone-gonaga waragaria")
, (37, "ngui ki, ngui tebone-gonaga karia")
, (38, "ngui ki, ngui tebone-gonaga halira")
, (39, "ngui ki, ngui tebone-gonaga dira")
, (40, "ngui ki, ngui tebone-gonaga pira")
, (41, "ngui ki, ngui tebone-gonaga bearia")
, (42, "ngui ki, ngui tebone-gonaga hombearia")
, (43, "ngui ki, ngui tebone-gonaga haleria")
, (44, "ngui ki, ngui tebone-gonaga deria")
, (45, "ngui tebo")
, (46, "ngui tebo, ngui mane-gonaga mbira")
, (47, "ngui tebo, ngui mane-gonaga kira")
, (48, "ngui tebo, ngui mane-gonaga tebira")
, (49, "ngui tebo, ngui mane-gonaga maria")
, (50, "ngui tebo, ngui mane-gonaga duria")
, (51, "ngui tebo, ngui mane-gonaga waragaria")
, (52, "ngui tebo, ngui mane-gonaga karia")
, (53, "ngui tebo, ngui mane-gonaga halira")
, (54, "ngui tebo, ngui mane-gonaga dira")
, (55, "ngui tebo, ngui mane-gonaga pira")
, (56, "ngui tebo, ngui mane-gonaga bearia")
, (57, "ngui tebo, ngui mane-gonaga hombearia")
, (58, "ngui tebo, ngui mane-gonaga haleria")
, (59, "ngui tebo, ngui mane-gonaga deria")
, (60, "ngui ma")
, (61, "ngui ma, ngui dauni-gonaga mbira")
, (62, "ngui ma, ngui dauni-gonaga kira")
, (63, "ngui ma, ngui dauni-gonaga tebira")
, (64, "ngui ma, ngui dauni-gonaga maria")
, (65, "ngui ma, ngui dauni-gonaga duria")
, (66, "ngui ma, ngui dauni-gonaga waragaria")
, (67, "ngui ma, ngui dauni-gonaga karia")
, (68, "ngui ma, ngui dauni-gonaga halira")
, (69, "ngui ma, ngui dauni-gonaga dira")
, (70, "ngui ma, ngui dauni-gonaga pira")
, (71, "ngui ma, ngui dauni-gonaga bearia")
, (72, "ngui ma, ngui dauni-gonaga hombearia")
, (73, "ngui ma, ngui dauni-gonaga haleria")
, (74, "ngui ma, ngui dauni-gonaga deria")
, (75, "ngui dau")
, (76, "ngui dau, ngui waragane-gonaga mbira")
, (77, "ngui dau, ngui waragane-gonaga kira")
, (78, "ngui dau, ngui waragane-gonaga tebira")
, (79, "ngui dau, ngui waragane-gonaga maria")
, (80, "ngui dau, ngui waragane-gonaga duria")
, (81, "ngui dau, ngui waragane-gonaga waragaria")
, (82, "ngui dau, ngui waragane-gonaga karia")
, (83, "ngui dau, ngui waragane-gonaga halira")
, (84, "ngui dau, ngui waragane-gonaga dira")
, (85, "ngui dau, ngui waragane-gonaga pira")
, (86, "ngui dau, ngui waragane-gonaga bearia")
, (87, "ngui dau, ngui waragane-gonaga hombearia")
, (88, "ngui dau, ngui waragane-gonaga haleria")
, (89, "ngui dau, ngui waragane-gonaga deria")
, (90, "ngui waraga")
, (91, "ngui waraga, ngui kane-gonaga mbira")
, (92, "ngui waraga, ngui kane-gonaga kira")
, (93, "ngui waraga, ngui kane-gonaga tebira")
, (94, "ngui waraga, ngui kane-gonaga maria")
, (95, "ngui waraga, ngui kane-gonaga duria")
, (96, "ngui waraga, ngui kane-gonaga waragaria")
, (97, "ngui waraga, ngui kane-gonaga karia")
, (98, "ngui waraga, ngui kane-gonaga halira")
, (99, "ngui waraga, ngui kane-gonaga dira")
, (100, "ngui waraga, ngui kane-gonaga pira")
]
)
]
|
telser/numerals
|
src-test/Text/Numeral/Language/PAA/TestData.hs
|
bsd-3-clause
| 5,244 | 0 | 8 | 1,324 | 993 | 664 | 329 | 112 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, LambdaCase, RecordWildCards #-}
-- | Stability: Experimental
module Mahjong.Riichi where
import Data.List as L (delete)
-- import Data.MultiSet as MS
import Mahjong.Class
-- import Mahjong.Hand
import Mahjong.Player
import Mahjong.Tile
-- * Riichi tiles
type RiichiPlayer
= Player (Dora, RiichiTile)
data RiichiTile
= CharacterT Character
| CircleT Circle
| BambooT Bamboo
| WindT Wind
| DragonT Dragon
deriving (Eq, Show)
instance Tile RiichiTile where
honor = \case
WindT _ -> True
DragonT _ -> True
_ -> False
terminal = \case
CharacterT a -> isBounds a
CircleT a -> isBounds a
BambooT a -> isBounds a
_ -> True
instance Cycle RiichiTile where
next = \case
CharacterT a -> CharacterT (next a)
CircleT a -> CircleT (next a)
BambooT a -> BambooT (next a)
WindT a -> WindT (next a)
DragonT a -> DragonT (next a)
prev = \case
CharacterT a -> CharacterT (prev a)
CircleT a -> CircleT (prev a)
BambooT a -> BambooT (prev a)
WindT a -> WindT (prev a)
DragonT a -> DragonT (prev a)
isBounds :: (Eq a, Bounded a) => a -> Bool
isBounds a | a == minBound || a == maxBound = True
| otherwise = False
-- | When you work with tiles you'll want some way to be able to check if two
-- tiles are of the same type.
sameGroup :: RiichiTile -> RiichiTile -> Bool
sameGroup (CharacterT _) (CharacterT _) = True
sameGroup (CircleT _) (CircleT _) = True
sameGroup (BambooT _) (BambooT _) = True
sameGroup (WindT _) (WindT _) = True
sameGroup (DragonT _) (DragonT _) = True
sameGroup _ _ = False
-- * Hand
-- toHand :: [(Dora, RiichiTile)] -> Hand
-- toHand = foldr insertTile mempty
-- where
-- insertTile :: (Dora, RiichiTile) -> Hand -> Hand
-- insertTile t h = case snd t of
-- CharacterT a -> insertOver a t h
-- CircleT a -> insertOver a t h
-- BambooT a -> insertOver a t h
-- WindT a -> insertOver a t h
-- DragonT a -> insertOver a t h
-- insertOver a b = transformBi (insert $ a <$ b)
-- * Game actions
-- | We want to look through the list and remove the elem from that list; using
-- Right signifies that the operation was successful and that we can continue on
-- with the process.
takeFrom :: (Eq a) => a -> [a] -> String -> Either String [a]
takeFrom t ts message
= if tz == ts
then Right tz
else Left message
where
tz = L.delete t ts
-- | Because the structure that a player draws from is pure, we don't have to
-- worry about side effects within the function. However, we do have to make
-- sure that at the end of the player's turn if there is no more tiles that the
-- game ends. Usually this means that the the hand (the current instance of the
-- game being played) will end in a draw unless the current player wins, or a
-- player wins off this player's discard.
playerDraw :: (Dora, RiichiTile) -> RiichiPlayer -> RiichiPlayer
playerDraw dt player@Player{..}
= player { hand = addToHand hand dt}
-- | Discarding has a few side effects that we have to watch out for like if a
-- player gives an invalid tile from the outside. To handle this we will return
-- an Either that will throw an error that will be returned to the client so
-- that they can pick a valid discard.
playerDiscard :: (Dora, RiichiTile) -> RiichiPlayer -> Either String RiichiPlayer
playerDiscard t p
= case takeFrom t ((\ (PlayerHand h) -> h ) . hand $ p) "Tile wasn't in the Hand" of
Right a -> Right p { discardPile = t : discardPile p
, hand = PlayerHand a }
Left a -> Left a
-- | When a player steals a tile it mutates both the original player and the
-- player stealing the tile. Because stolen tiles must always be kept together
-- with the tiles from the hand and can never be discarded they have to be kept
-- separate. WARNING: This function assumes that the previous player not only
-- discarded the tile, didn't win, but that the meld given to the function is
-- correct for the stealing player.
--
-- FIXME: Make the function perfectly pure in the sense that it cannot create an
-- unexpected board state.
-- playerStealDiscard :: Player -> Player -> Meld (Dora Tile) -> (Player, Player)
-- playerStealDiscard p1 p2 m = ( p1 & discardPile .~ maybe [] snd tupledStolen
-- , p2 & stolenMelds %~ cons m )
-- where
-- tupledStolen = p1 ^. discardPile & uncons
|
TakSuyu/mahjong
|
src/Mahjong/Riichi.hs
|
mit
| 4,623 | 0 | 13 | 1,235 | 867 | 459 | 408 | 63 | 2 |
module Crypto.Cipher.ECDSA.Util where
import Data.Text.Lazy (Text)
import Data.Text.Lazy.Read (hexadecimal)
import qualified Data.ByteString.Lazy as BS
readHexInteger :: Text -> Integer
readHexInteger = either error fst . hexadecimal
-- |Calulate the length in bits of an Integer (log2)
bitSize :: Integer -> Integer
bitSize n = case n of
0 -> 0
n -> 1 + bitSize (n `div` 2)
-- |I guess this is too slow and needs to be replaced
bytesToInteger :: BS.ByteString -> Integer
bytesToInteger = BS.foldl' (\n c -> n * 256 + fromIntegral c) 0
integerToBytes :: Integer -> BS.ByteString
integerToBytes = BS.pack . go
where
go c = case c of
0 -> []
c -> go (c `div` 256) ++ [fromIntegral (c `mod` 256)]
padTo :: Integer -> BS.ByteString -> BS.ByteString
padTo n s = BS.append padding s
where
padding = BS.pack
(replicate (fromIntegral n - fromIntegral (BS.length s)) 0)
|
fhaust/bitcoin
|
src/Crypto/Cipher/ECDSA/Util.hs
|
mit
| 936 | 0 | 15 | 220 | 314 | 172 | 142 | 21 | 2 |
{-# 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.Redshift.EnableLogging
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Starts logging information, such as queries and connection attempts, for
-- the specified Amazon Redshift cluster.
--
-- /See:/ <http://docs.aws.amazon.com/redshift/latest/APIReference/API_EnableLogging.html AWS API Reference> for EnableLogging.
module Network.AWS.Redshift.EnableLogging
(
-- * Creating a Request
enableLogging
, EnableLogging
-- * Request Lenses
, elS3KeyPrefix
, elClusterIdentifier
, elBucketName
-- * Destructuring the Response
, loggingStatus
, LoggingStatus
-- * Response Lenses
, lsLastFailureTime
, lsLastSuccessfulDeliveryTime
, lsS3KeyPrefix
, lsBucketName
, lsLoggingEnabled
, lsLastFailureMessage
) where
import Network.AWS.Prelude
import Network.AWS.Redshift.Types
import Network.AWS.Redshift.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- |
--
-- /See:/ 'enableLogging' smart constructor.
data EnableLogging = EnableLogging'
{ _elS3KeyPrefix :: !(Maybe Text)
, _elClusterIdentifier :: !Text
, _elBucketName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'EnableLogging' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'elS3KeyPrefix'
--
-- * 'elClusterIdentifier'
--
-- * 'elBucketName'
enableLogging
:: Text -- ^ 'elClusterIdentifier'
-> Text -- ^ 'elBucketName'
-> EnableLogging
enableLogging pClusterIdentifier_ pBucketName_ =
EnableLogging'
{ _elS3KeyPrefix = Nothing
, _elClusterIdentifier = pClusterIdentifier_
, _elBucketName = pBucketName_
}
-- | The prefix applied to the log file names.
--
-- Constraints:
--
-- - Cannot exceed 512 characters
-- - Cannot contain spaces( ), double quotes (\"), single quotes (\'), a
-- backslash (\\), or control characters. The hexadecimal codes for
-- invalid characters are:
-- - x00 to x20
-- - x22
-- - x27
-- - x5c
-- - x7f or larger
elS3KeyPrefix :: Lens' EnableLogging (Maybe Text)
elS3KeyPrefix = lens _elS3KeyPrefix (\ s a -> s{_elS3KeyPrefix = a});
-- | The identifier of the cluster on which logging is to be started.
--
-- Example: 'examplecluster'
elClusterIdentifier :: Lens' EnableLogging Text
elClusterIdentifier = lens _elClusterIdentifier (\ s a -> s{_elClusterIdentifier = a});
-- | The name of an existing S3 bucket where the log files are to be stored.
--
-- Constraints:
--
-- - Must be in the same region as the cluster
-- - The cluster must have read bucket and put object permissions
elBucketName :: Lens' EnableLogging Text
elBucketName = lens _elBucketName (\ s a -> s{_elBucketName = a});
instance AWSRequest EnableLogging where
type Rs EnableLogging = LoggingStatus
request = postQuery redshift
response
= receiveXMLWrapper "EnableLoggingResult"
(\ s h x -> parseXML x)
instance ToHeaders EnableLogging where
toHeaders = const mempty
instance ToPath EnableLogging where
toPath = const "/"
instance ToQuery EnableLogging where
toQuery EnableLogging'{..}
= mconcat
["Action" =: ("EnableLogging" :: ByteString),
"Version" =: ("2012-12-01" :: ByteString),
"S3KeyPrefix" =: _elS3KeyPrefix,
"ClusterIdentifier" =: _elClusterIdentifier,
"BucketName" =: _elBucketName]
|
fmapfmapfmap/amazonka
|
amazonka-redshift/gen/Network/AWS/Redshift/EnableLogging.hs
|
mpl-2.0
| 4,187 | 0 | 11 | 945 | 526 | 327 | 199 | 72 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fa-IR">
<title>SOAP Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_fa_IR/helpset_fa_IR.hs
|
apache-2.0
| 974 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{- safely running shell commands
-
- Copyright 2010-2013 Joey Hess <[email protected]>
-
- License: BSD-2-clause
-}
module Utility.SafeCommand where
import System.Exit
import Utility.Process
import System.Process (env)
import Data.String.Utils
import Control.Applicative
import System.FilePath
import Data.Char
{- A type for parameters passed to a shell command. A command can
- be passed either some Params (multiple parameters can be included,
- whitespace-separated, or a single Param (for when parameters contain
- whitespace), or a File.
-}
data CommandParam = Params String | Param String | File FilePath
deriving (Eq, Show, Ord)
{- Used to pass a list of CommandParams to a function that runs
- a command and expects Strings. -}
toCommand :: [CommandParam] -> [String]
toCommand = concatMap unwrap
where
unwrap (Param s) = [s]
unwrap (Params s) = filter (not . null) (split " " s)
-- Files that start with a non-alphanumeric that is not a path
-- separator are modified to avoid the command interpreting them as
-- options or other special constructs.
unwrap (File s@(h:_))
| isAlphaNum h || h `elem` pathseps = [s]
| otherwise = ["./" ++ s]
unwrap (File s) = [s]
-- '/' is explicitly included because it's an alternative
-- path separator on Windows.
pathseps = pathSeparator:"./"
{- Run a system command, and returns True or False
- if it succeeded or failed.
-}
boolSystem :: FilePath -> [CommandParam] -> IO Bool
boolSystem command params = boolSystemEnv command params Nothing
boolSystemEnv :: FilePath -> [CommandParam] -> Maybe [(String, String)] -> IO Bool
boolSystemEnv command params environ = dispatch <$> safeSystemEnv command params environ
where
dispatch ExitSuccess = True
dispatch _ = False
{- Runs a system command, returning the exit status. -}
safeSystem :: FilePath -> [CommandParam] -> IO ExitCode
safeSystem command params = safeSystemEnv command params Nothing
safeSystemEnv :: FilePath -> [CommandParam] -> Maybe [(String, String)] -> IO ExitCode
safeSystemEnv command params environ = do
(_, _, _, pid) <- createProcess (proc command $ toCommand params)
{ env = environ }
waitForProcess pid
{- Wraps a shell command line inside sh -c, allowing it to be run in a
- login shell that may not support POSIX shell, eg csh. -}
shellWrap :: String -> String
shellWrap cmdline = "sh -c " ++ shellEscape cmdline
{- Escapes a filename or other parameter to be safely able to be exposed to
- the shell.
-
- This method works for POSIX shells, as well as other shells like csh.
-}
shellEscape :: String -> String
shellEscape f = "'" ++ escaped ++ "'"
where
-- replace ' with '"'"'
escaped = join "'\"'\"'" $ split "'" f
{- Unescapes a set of shellEscaped words or filenames. -}
shellUnEscape :: String -> [String]
shellUnEscape [] = []
shellUnEscape s = word : shellUnEscape rest
where
(word, rest) = findword "" s
findword w [] = (w, "")
findword w (c:cs)
| c == ' ' = (w, cs)
| c == '\'' = inquote c w cs
| c == '"' = inquote c w cs
| otherwise = findword (w++[c]) cs
inquote _ w [] = (w, "")
inquote q w (c:cs)
| c == q = findword w cs
| otherwise = inquote q (w++[c]) cs
{- For quickcheck. -}
prop_idempotent_shellEscape :: String -> Bool
prop_idempotent_shellEscape s = [s] == (shellUnEscape . shellEscape) s
prop_idempotent_shellEscape_multiword :: [String] -> Bool
prop_idempotent_shellEscape_multiword s = s == (shellUnEscape . unwords . map shellEscape) s
{- Segements a list of filenames into groups that are all below the manximum
- command-line length limit. Does not preserve order. -}
segmentXargs :: [FilePath] -> [[FilePath]]
segmentXargs l = go l [] 0 []
where
go [] c _ r = c:r
go (f:fs) c accumlen r
| len < maxlen && newlen > maxlen = go (f:fs) [] 0 (c:r)
| otherwise = go fs (f:c) newlen r
where
len = length f
newlen = accumlen + len
{- 10k of filenames per command, well under Linux's 20k limit;
- allows room for other parameters etc. -}
maxlen = 10240
|
abailly/propellor-test2
|
src/Utility/SafeCommand.hs
|
bsd-2-clause
| 3,995 | 4 | 12 | 773 | 1,080 | 567 | 513 | 64 | 4 |
module SDL.Input
( module SDL.Input.GameController
, module SDL.Input.Joystick
, module SDL.Input.Keyboard
, module SDL.Input.Mouse
) where
import SDL.Input.GameController
import SDL.Input.Joystick
import SDL.Input.Keyboard
import SDL.Input.Mouse
|
svenkeidel/sdl2
|
src/SDL/Input.hs
|
bsd-3-clause
| 258 | 0 | 5 | 35 | 60 | 41 | 19 | 9 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Network.Hackage.CabalInstall.Setup
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
--
-----------------------------------------------------------------------------
module Network.Hackage.CabalInstall.Setup
( emptyTempFlags
, parseInstallArgs
, parseGlobalArgs
) where
import Text.ParserCombinators.ReadP (readP_to_S)
import Distribution.ParseUtils (parseDependency)
import Distribution.Setup (defaultCompilerFlavor, CompilerFlavor(..))
import Data.List (find)
import System.Console.GetOpt (ArgDescr (..), ArgOrder (..), OptDescr (..), usageInfo, getOpt')
import System.Exit (exitWith, ExitCode (..))
import System.Environment (getProgName)
import Network.Hackage.CabalInstall.Types (TempFlags (..), Flag (..), Action (..)
, UnresolvedDependency (..))
emptyTempFlags :: TempFlags
emptyTempFlags = TempFlags {
tempHcFlavor = defaultCompilerFlavor, -- Nothing,
tempHcPath = Nothing,
tempConfPath = Nothing,
tempHcPkg = Nothing,
tempPrefix = Nothing,
tempServers = [],
tempRunHc = Nothing,
tempTarPath = Nothing,
tempVerbose = 3,
-- tempUpgradeDeps = False,
tempUser = False,
tempUserIns = False
}
cmd_verbose :: OptDescr Flag
cmd_verbose = Option "v" ["verbose"] (OptArg verboseFlag "n")
"Control verbosity (n is 0--5, normal verbosity level is 1, -v alone is equivalent to -v3)"
where
verboseFlag mb_s = Verbose (maybe 3 read mb_s)
globalOptions :: [OptDescr Flag]
globalOptions =
[ Option "h?" ["help"] (NoArg HelpFlag) "Show this help text"
, cmd_verbose
, Option "g" ["ghc"] (NoArg GhcFlag) "compile with GHC"
, Option "n" ["nhc"] (NoArg NhcFlag) "compile with NHC"
, Option "" ["hugs"] (NoArg HugsFlag) "compile with hugs"
, Option "s" ["with-server"] (ReqArg WithServer "URL")
"give the URL to a Hackage server"
, Option "c" ["config-path"] (ReqArg WithConfPath "PATH")
"give the path to the config dir. Default is /etc/cabal-install"
, Option "" ["tar-path"] (ReqArg WithTarPath "PATH")
"give the path to tar"
, Option "w" ["with-compiler"] (ReqArg WithCompiler "PATH")
"give the path to a particular compiler"
, Option "" ["with-hc-pkg"] (ReqArg WithHcPkg "PATH")
"give the path to the package tool"
-- , Option "" ["upgrade-deps"] (NoArg UpgradeDeps)
-- "Upgrade all dependencies which depend on the newly installed packages"
, Option "" ["user-install"] (NoArg UserInstallFlag)
"upon registration, register this package in the user's local package database"
, Option "" ["global-install"] (NoArg GlobalInstallFlag)
"upon registration, register this package in the system-wide package database"
, Option "" ["user-deps"] (NoArg UserFlag)
"allow dependencies to be satisfied from the user package database"
, Option "" ["global-deps"] (NoArg GlobalFlag)
"(default) dependencies must be satisfied from the global package database"
]
data Cmd = Cmd {
cmdName :: String,
cmdHelp :: String, -- Short description
cmdDescription :: String, -- Long description
cmdOptions :: [OptDescr Flag ],
cmdAction :: Action
}
commandList :: [Cmd]
commandList = [fetchCmd, installCmd, buildDepCmd, updateCmd, cleanCmd, listCmd, infoCmd]
lookupCommand :: String -> [Cmd] -> Maybe Cmd
lookupCommand name = find ((==name) . cmdName)
printGlobalHelp :: IO ()
printGlobalHelp = do pname <- getProgName
let syntax_line = concat [ "Usage: ", pname
, " [GLOBAL FLAGS]\n or: ", pname
, " COMMAND [FLAGS]\n\nGlobal flags:"]
putStrLn (usageInfo syntax_line globalOptions)
putStrLn "Commands:"
let maxlen = maximum [ length (cmdName cmd) | cmd <- commandList ]
sequence_ [ do putStr " "
putStr (align maxlen (cmdName cmd))
putStr " "
putStrLn (cmdHelp cmd)
| cmd <- commandList ]
where align n str = str ++ replicate (n - length str) ' '
printCmdHelp :: Cmd -> IO ()
printCmdHelp cmd = do pname <- getProgName
let syntax_line = "Usage: " ++ pname ++ " " ++ cmdName cmd ++ " [FLAGS]\n\nFlags for " ++ cmdName cmd ++ ":"
putStrLn (usageInfo syntax_line (cmdOptions cmd))
putStr (cmdDescription cmd)
-- We don't want to use elem, because that imposes Eq a
hasHelpFlag :: [Flag] -> Bool
hasHelpFlag flags = not . null $ [ () | HelpFlag <- flags ]
parseGlobalArgs :: [String] -> IO (Action,TempFlags,[String])
parseGlobalArgs args =
case getOpt' RequireOrder globalOptions args of
(flags, _, _, []) | hasHelpFlag flags -> do
printGlobalHelp
exitWith ExitSuccess
(flags, cname:cargs, _, []) -> do
case lookupCommand cname commandList of
Just cmd -> return (cmdAction cmd,mkTempFlags flags emptyTempFlags, cargs)
Nothing -> do putStrLn $ "Unrecognised command: " ++ cname ++ " (try --help)"
exitWith (ExitFailure 1)
(_, [], _, []) -> do putStrLn $ "No command given (try --help)"
exitWith (ExitFailure 1)
(_, _, _, errs) -> do putStrLn "Errors:"
mapM_ putStrLn errs
exitWith (ExitFailure 1)
mkTempFlags :: [Flag] -> TempFlags -> TempFlags
mkTempFlags = updateCfg
where updateCfg (fl:flags) t = updateCfg flags $
case fl of
GhcFlag -> t { tempHcFlavor = Just GHC }
NhcFlag -> t { tempHcFlavor = Just NHC }
HugsFlag -> t { tempHcFlavor = Just Hugs }
WithCompiler path -> t { tempHcPath = Just path }
WithConfPath path -> t { tempConfPath = Just path }
WithHcPkg path -> t { tempHcPkg = Just path }
WithServer url -> t { tempServers = url:tempServers t }
Verbose n -> t { tempVerbose = n }
-- UpgradeDeps -> t { tempUpgradeDeps = True }
UserFlag -> t { tempUser = True }
GlobalFlag -> t { tempUser = False }
UserInstallFlag -> t { tempUserIns = True }
GlobalInstallFlag -> t { tempUserIns = False }
_ -> error $ "Unexpected flag!"
updateCfg [] t = t
mkCmd :: String -> String -> String -> Action -> Cmd
mkCmd name help desc action =
Cmd { cmdName = name
, cmdHelp = help
, cmdDescription = desc
, cmdOptions = []
, cmdAction = action
}
fetchCmd :: Cmd
fetchCmd = mkCmd "fetch" "Downloads packages for later installation or study." "" FetchCmd
installCmd :: Cmd
installCmd = mkCmd "install" "Installs a list of packages." "" InstallCmd
listCmd :: Cmd
listCmd = mkCmd "list" "List available packages on the server." "" ListCmd
buildDepCmd :: Cmd
buildDepCmd = mkCmd "build-dep" "Installs the dependencies for a list of packages." "" BuildDepCmd
updateCmd :: Cmd
updateCmd = mkCmd "update" "Updates list of known packages" "" UpdateCmd
cleanCmd :: Cmd
cleanCmd = mkCmd "clean" "Removes downloaded files" "" CleanCmd
infoCmd :: Cmd
infoCmd = mkCmd "info" "Emit some info"
"Emits information about dependency resolution" InfoCmd
parseInstallArgs :: [String] -> IO ([String],[UnresolvedDependency])
parseInstallArgs [] = do printCmdHelp installCmd
exitWith ExitSuccess
parseInstallArgs args
= return (globalArgs,parsePkgArgs pkgs)
where (globalArgs,pkgs) = break (not.(==)'-'.head) args
parseDep dep
= case readP_to_S parseDependency dep of
[] -> error ("Failed to parse package dependency: " ++ show dep)
x -> fst (last x)
parsePkgArgs [] = []
parsePkgArgs (x:xs)
= let (args,rest) = break (not.(==) '-'.head) xs
in (UnresolvedDependency
{ dependency = parseDep x
, depOptions = args }
):parsePkgArgs rest
|
FranklinChen/hugs98-plus-Sep2006
|
packages/Cabal/Network/Hackage/CabalInstall/Setup.hs
|
bsd-3-clause
| 8,823 | 2 | 17 | 2,806 | 2,072 | 1,116 | 956 | 159 | 14 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Test.Foundation.Network.IPv6
( testNetworkIPv6
) where
import Foundation
import Foundation.Check
import Foundation.Network.IPv6
import Test.Data.Network
import Test.Foundation.Storable
-- | test property equality for the given Collection
testEquality :: Gen IPv6 -> Test
testEquality genElement = Group "equality"
[ Property "x == x" $ forAll genElement (\x -> x === x)
, Property "x == y" $ forAll ((,) <$> genElement <*> genElement) $
\(x,y) -> (toTuple x == toTuple y) === (x == y)
]
-- | test ordering
testOrdering :: Gen IPv6 -> Test
testOrdering genElement = Property "ordering" $
forAll ((,) <$> genElement <*> genElement) $ \(x, y) ->
(toTuple x `compare` toTuple y) === x `compare` y
testNetworkIPv6 :: Test
testNetworkIPv6 = Group "IPv6"
#if __GLASGOW_HASKELL__ >= 710
[ Property "toTuple . fromTuple == id" $
forAll genIPv6Tuple $ \x -> x === toTuple (fromTuple x)
, Property "toString . fromString == id" $
forAll genIPv6String $ \x -> x === toString (fromString $ toList x)
, testEquality genIPv6
, testOrdering genIPv6
, testPropertyStorable "Storable" (Proxy :: Proxy IPv6)
, testPropertyStorableFixed "StorableFixed" (Proxy :: Proxy IPv6)
, Group "parse"
[ Property "::" $ fromTuple (0,0,0,0,0,0,0,0) === fromString "::"
, Property "::1" $ fromTuple (0,0,0,0,0,0,0,1) === fromString "::1"
, Property "2001:DB8::8:800:200C:417A" $ fromTuple (0x2001,0xDB8,0,0,0x8,0x800,0x200c,0x417a) === fromString "2001:DB8::8:800:200C:417A"
, Property "FF01::101" $ fromTuple (0xff01,0,0,0,0,0,0,0x101) === fromString "FF01::101"
, Property "::13.1.68.3" $ (fromTuple (0,0,0,0,0,0,0x0d01,0x4403)) === (fromString "::13.1.68.3")
, Property "::FFFF:129.144.52.38" $ (fromTuple (0,0,0,0,0,0xffff,0x8190,0x3426)) === (fromString "::FFFF:129.144.52.38")
, Property "0::FFFF:129.144.52.38" $ (fromTuple (0,0,0,0,0,0xffff,0x8190,0x3426)) === (fromString "0::FFFF:129.144.52.38")
, Property "0:0::FFFF:129.144.52.38" $ (fromTuple (0,0,0,0,0,0xffff,0x8190,0x3426)) === (fromString "0:0::FFFF:129.144.52.38")
]
]
#else
[]
#endif
|
vincenthz/hs-foundation
|
foundation/tests/Test/Foundation/Network/IPv6.hs
|
bsd-3-clause
| 2,307 | 0 | 13 | 459 | 768 | 428 | 340 | 22 | 1 |
module Sql
( module Sql.Init
, module Sql.Sessions
, module Sql.Users
, module Sql.Utils
) where
import Sql.Init
import Sql.Sessions
import Sql.Users
import Sql.Utils
|
hherman1/CatanServ
|
src/Sql.hs
|
bsd-3-clause
| 188 | 0 | 5 | 45 | 50 | 32 | 18 | 9 | 0 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
{-# OPTIONS -Wall #-}
module Main(main) where
import Control.Applicative
import Control.Monad hiding (forM)
import qualified Data.Text.IO as T
import Data.Foldable as Foldable
import Data.Traversable
import Data.Typeable
import Data.Tensor.TypeLevel
import Language.Paraiso.Annotation (Annotation)
import Language.Paraiso.Name
import Language.Paraiso.Generator (generateIO)
import qualified Language.Paraiso.Generator.Native as Native
import Language.Paraiso.OM
import Language.Paraiso.OM.Builder
import Language.Paraiso.OM.Builder.Boolean
import Language.Paraiso.OM.DynValue
import Language.Paraiso.OM.PrettyPrint
import qualified Language.Paraiso.OM.Realm as Rlm
import qualified Language.Paraiso.OM.Reduce as Reduce
import Language.Paraiso.Optimization
import Language.Paraiso.Prelude
import NumericPrelude hiding ((&&), (||), (++), foldl1)
-- a dynamic representation for a local static value (an array)
intDV :: DynValue
intDV = DynValue{realm = Rlm.Local, typeRep = typeOf (0::Int)}
-- a dynamic representation for a global static value (a single-point variable)
intGDV :: DynValue
intGDV = DynValue{realm = Rlm.Global, typeRep = typeOf (0::Int)}
-- the list of static variables for this machine
lifeVars :: [Named DynValue]
lifeVars =
[Named (mkName "population") intGDV] ++
[Named (mkName "generation") intGDV] ++
[Named (mkName "cell") intDV]
-- adjacency vectors in Conway's game of Life
adjVecs :: [Vec2 Int]
adjVecs = zipWith (\x y -> Vec :~ x :~ y)
[-1, 0, 1,-1, 1,-1, 0, 1]
[-1,-1,-1, 0, 0, 1, 1, 1]
-- R-pentomino pattern
r5mino :: [Vec2 Int]
r5mino = zipWith (\x y -> Vec :~ x :~ y)
[ 1, 2, 0, 1, 1]
[ 0, 0, 1, 1, 2]
bind :: (Functor f, Monad m) => f a -> f (m a)
bind = fmap return
buildProceed :: Builder Vec2 Int Annotation ()
buildProceed = do
-- load a Local variable called "cell."
cell <- bind $ load Rlm.TLocal (undefined::Int) $ mkName "cell"
-- load a Global variable called "generation."
gen <- bind $ load Rlm.TGlobal (undefined::Int) $ mkName "generation"
-- create a list of cell patterns, each shifted by an element of adjVects.
neighbours <- fmap (map return) $
forM adjVecs (\v -> shift v cell)
-- add them all.
num <- bind $ foldl1 (+) neighbours
-- The rule of Conway's game of Life.
isAlive <- bind $
(cell `eq` 0) && (num `eq` 3) ||
(cell `eq` 1) && (num `ge` 2) && (num `le` 3)
-- create the new cell state based on the judgement.
newCell <- bind $ select isAlive (1::BuilderOf Rlm.TLocal Int) 0
-- count the number of alive cells and store it into "population."
store (mkName "population") $ reduce Reduce.Sum newCell
-- increment the generation.
store (mkName "generation") $ gen + 1
-- store the new cell state.
store (mkName "cell") $ newCell
buildInit :: Builder Vec2 Int Annotation ()
buildInit = do
-- create the current coordinate vector.
coord <- sequenceA $ compose (\axis -> bind $ loadIndex (0::Int) axis)
-- load the size of the simulation region
size <- sequenceA $ compose (\axis -> bind $ loadSize Rlm.TLocal (0::Int) axis)
halfSize <- sequenceA $ compose (\axis -> bind $ (size!axis) `div` 2)
-- if the current coordinate equals one of the elements in r5mino, you are alive.
alive <- bind $ foldl1 (||) [agree (coord - halfSize) point | point <- r5mino ]
-- create the initial cell state based on the judgement.
cell <- bind $ select alive (1::BuilderOf Rlm.TLocal Int) 0
-- store the initial states.
store (mkName "cell") $ cell
store (mkName "population") $ reduce Reduce.Sum cell
store (mkName "generation") $ (0::BuilderOf Rlm.TGlobal Int)
where
agree coord point =
foldl1 (&&) $ compose (\i -> coord!i `eq` imm (point!i))
-- compose the machine.
myOM :: OM Vec2 Int Annotation
myOM = optimize O3 $
makeOM (mkName "Life") [] lifeVars
[(mkName "init" , buildInit),
(mkName "proceed", buildProceed)
]
cpuSetup :: Native.Setup Vec2 Int
cpuSetup =
(Native.defaultSetup $ Vec :~ 128 :~ 128)
{ Native.directory = "./dist/"
}
gpuSetup :: Native.Setup Vec2 Int
gpuSetup =
(Native.defaultSetup $ Vec :~ 128 :~ 128)
{ Native.directory = "./dist-cuda/" ,
Native.language = Native.CUDA
}
main :: IO ()
main = do
-- output the intermediate state.
T.writeFile "output/OM.txt" $ prettyPrintA1 $ myOM
-- generate the library
_ <- generateIO cpuSetup myOM
-- generate the library
_ <- generateIO gpuSetup myOM
return ()
|
nushio3/Paraiso
|
examples-old/Life/LifeMain.hs
|
bsd-3-clause
| 4,756 | 0 | 15 | 1,108 | 1,420 | 791 | 629 | 89 | 1 |
module Main where
import Hans.NetworkStack
import qualified Hans.Layer.Ethernet as Eth
import Hans.Device.Pcap
main :: IO ()
main = do
ns <- newNetworkStack
Just (dev,nd) <- openPcap "eth0" $ Just $ Mac 1 2 3 4 5 6
print nd
let Just mac = (ndMAC nd)
Eth.addEthernetDevice (nsEthernet ns) mac (pcapSend dev) (pcapReceiveLoop dev)
Eth.startEthernetDevice (nsEthernet ns) mac
-- and we can do whatever we could earlier
|
tolysz/hans-pcap
|
example/test.hs
|
bsd-3-clause
| 433 | 0 | 11 | 83 | 160 | 80 | 80 | 12 | 1 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Control/Monad/Trans/Control.hs" #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, RankNTypes
, TypeFamilies
, FunctionalDependencies
, FlexibleInstances
, UndecidableInstances
, MultiParamTypeClasses #-}
{-# LANGUAGE Safe #-}
-- Hide warnings for the deprecated ErrorT transformer:
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
{- |
Module : Control.Monad.Trans.Control
Copyright : Bas van Dijk, Anders Kaseorg
License : BSD-style
Maintainer : Bas van Dijk <[email protected]>
Stability : experimental
-}
module Control.Monad.Trans.Control
( -- * MonadTransControl
MonadTransControl(..), Run
-- ** Defaults
-- $MonadTransControlDefaults
, RunDefault, defaultLiftWith, defaultRestoreT
-- * MonadBaseControl
, MonadBaseControl (..), RunInBase
-- ** Defaults
-- $MonadBaseControlDefaults
, ComposeSt, RunInBaseDefault, defaultLiftBaseWith, defaultRestoreM
-- * Utility functions
, control, embed, embed_, captureT, captureM
, liftBaseOp, liftBaseOp_
, liftBaseDiscard, liftBaseOpDiscard
, liftThrough
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
-- from base:
import Data.Function ( (.), ($), const )
import Data.Monoid ( Monoid, mempty )
import Control.Monad ( Monad, (>>=), return, liftM )
import System.IO ( IO )
import Data.Maybe ( Maybe )
import Data.Either ( Either )
import Control.Monad.ST.Lazy.Safe ( ST )
import qualified Control.Monad.ST.Safe as Strict ( ST )
-- from stm:
import Control.Monad.STM ( STM )
-- from transformers:
import Control.Monad.Trans.Class ( MonadTrans )
import Control.Monad.Trans.Identity ( IdentityT(IdentityT), runIdentityT )
import Control.Monad.Trans.List ( ListT (ListT), runListT )
import Control.Monad.Trans.Maybe ( MaybeT (MaybeT), runMaybeT )
import Control.Monad.Trans.Error ( ErrorT (ErrorT), runErrorT, Error )
import Control.Monad.Trans.Reader ( ReaderT (ReaderT), runReaderT )
import Control.Monad.Trans.State ( StateT (StateT), runStateT )
import Control.Monad.Trans.Writer ( WriterT (WriterT), runWriterT )
import Control.Monad.Trans.RWS ( RWST (RWST), runRWST )
import Control.Monad.Trans.Except ( ExceptT (ExceptT), runExceptT )
import qualified Control.Monad.Trans.RWS.Strict as Strict ( RWST (RWST), runRWST )
import qualified Control.Monad.Trans.State.Strict as Strict ( StateT (StateT), runStateT )
import qualified Control.Monad.Trans.Writer.Strict as Strict ( WriterT(WriterT), runWriterT )
import Data.Functor.Identity ( Identity )
-- from transformers-base:
import Control.Monad.Base ( MonadBase )
import Control.Monad ( void )
import Prelude (id)
--------------------------------------------------------------------------------
-- MonadTransControl type class
--------------------------------------------------------------------------------
class MonadTrans t => MonadTransControl t where
-- | Monadic state of @t@.
type StT t a :: *
-- | @liftWith@ is similar to 'lift' in that it lifts a computation from
-- the argument monad to the constructed monad.
--
-- Instances should satisfy similar laws as the 'MonadTrans' laws:
--
-- @liftWith . const . return = return@
--
-- @liftWith (const (m >>= f)) = liftWith (const m) >>= liftWith . const . f@
--
-- The difference with 'lift' is that before lifting the @m@ computation
-- @liftWith@ captures the state of @t@. It then provides the @m@
-- computation with a 'Run' function that allows running @t n@ computations in
-- @n@ (for all @n@) on the captured state.
liftWith :: Monad m => (Run t -> m a) -> t m a
-- | Construct a @t@ computation from the monadic state of @t@ that is
-- returned from a 'Run' function.
--
-- Instances should satisfy:
--
-- @liftWith (\\run -> run t) >>= restoreT . return = t@
restoreT :: Monad m => m (StT t a) -> t m a
-- | A function that runs a transformed monad @t n@ on the monadic state that
-- was captured by 'liftWith'
--
-- A @Run t@ function yields a computation in @n@ that returns the monadic state
-- of @t@. This state can later be used to restore a @t@ computation using
-- 'restoreT'.
type Run t = forall n b. Monad n => t n b -> n (StT t b)
--------------------------------------------------------------------------------
-- Defaults for MonadTransControl
--------------------------------------------------------------------------------
-- $MonadTransControlDefaults
--
-- The following functions can be used to define a 'MonadTransControl' instance
-- for a monad transformer which simply wraps another monad transformer which
-- already has a @MonadTransControl@ instance. For example:
--
-- @
-- {-\# LANGUAGE GeneralizedNewtypeDeriving \#-}
--
-- newtype CounterT m a = CounterT {unCounterT :: StateT Int m a}
-- deriving (Monad, MonadTrans)
--
-- instance MonadTransControl CounterT where
-- type StT CounterT a = StT (StateT Int) a
-- liftWith = 'defaultLiftWith' CounterT unCounterT
-- restoreT = 'defaultRestoreT' CounterT
-- @
-- | A function like 'Run' that runs a monad transformer @t@ which wraps the
-- monad transformer @t'@. This is used in 'defaultLiftWith'.
type RunDefault t t' = forall n b. Monad n => t n b -> n (StT t' b)
-- | Default definition for the 'liftWith' method.
defaultLiftWith :: (Monad m, MonadTransControl n)
=> (forall b. n m b -> t m b) -- ^ Monad constructor
-> (forall o b. t o b -> n o b) -- ^ Monad deconstructor
-> (RunDefault t n -> m a)
-> t m a
defaultLiftWith t unT = \f -> t $ liftWith $ \run -> f $ run . unT
{-# INLINABLE defaultLiftWith #-}
-- | Default definition for the 'restoreT' method.
defaultRestoreT :: (Monad m, MonadTransControl n)
=> (n m a -> t m a) -- ^ Monad constructor
-> m (StT n a)
-> t m a
defaultRestoreT t = t . restoreT
{-# INLINABLE defaultRestoreT #-}
--------------------------------------------------------------------------------
-- MonadTransControl instances
--------------------------------------------------------------------------------
instance MonadTransControl IdentityT where
type StT IdentityT a = a
liftWith f = IdentityT $ f $ runIdentityT
restoreT = IdentityT
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance MonadTransControl MaybeT where
type StT MaybeT a = Maybe a
liftWith f = MaybeT $ liftM return $ f $ runMaybeT
restoreT = MaybeT
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance Error e => MonadTransControl (ErrorT e) where
type StT (ErrorT e) a = Either e a
liftWith f = ErrorT $ liftM return $ f $ runErrorT
restoreT = ErrorT
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance MonadTransControl (ExceptT e) where
type StT (ExceptT e) a = Either e a
liftWith f = ExceptT $ liftM return $ f $ runExceptT
restoreT = ExceptT
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance MonadTransControl ListT where
type StT ListT a = [a]
liftWith f = ListT $ liftM return $ f $ runListT
restoreT = ListT
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance MonadTransControl (ReaderT r) where
type StT (ReaderT r) a = a
liftWith f = ReaderT $ \r -> f $ \t -> runReaderT t r
restoreT = ReaderT . const
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance MonadTransControl (StateT s) where
type StT (StateT s) a = (a, s)
liftWith f = StateT $ \s ->
liftM (\x -> (x, s))
(f $ \t -> runStateT t s)
restoreT = StateT . const
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance MonadTransControl (Strict.StateT s) where
type StT (Strict.StateT s) a = (a, s)
liftWith f = Strict.StateT $ \s ->
liftM (\x -> (x, s))
(f $ \t -> Strict.runStateT t s)
restoreT = Strict.StateT . const
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance Monoid w => MonadTransControl (WriterT w) where
type StT (WriterT w) a = (a, w)
liftWith f = WriterT $ liftM (\x -> (x, mempty))
(f $ runWriterT)
restoreT = WriterT
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance Monoid w => MonadTransControl (Strict.WriterT w) where
type StT (Strict.WriterT w) a = (a, w)
liftWith f = Strict.WriterT $ liftM (\x -> (x, mempty))
(f $ Strict.runWriterT)
restoreT = Strict.WriterT
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance Monoid w => MonadTransControl (RWST r w s) where
type StT (RWST r w s) a = (a, s, w)
liftWith f = RWST $ \r s -> liftM (\x -> (x, s, mempty))
(f $ \t -> runRWST t r s)
restoreT mSt = RWST $ \_ _ -> mSt
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
instance Monoid w => MonadTransControl (Strict.RWST r w s) where
type StT (Strict.RWST r w s) a = (a, s, w)
liftWith f =
Strict.RWST $ \r s -> liftM (\x -> (x, s, mempty))
(f $ \t -> Strict.runRWST t r s)
restoreT mSt = Strict.RWST $ \_ _ -> mSt
{-# INLINABLE liftWith #-}
{-# INLINABLE restoreT #-}
--------------------------------------------------------------------------------
-- MonadBaseControl type class
--------------------------------------------------------------------------------
class MonadBase b m => MonadBaseControl b m | m -> b where
-- | Monadic state of @m@.
type StM m a :: *
-- | @liftBaseWith@ is similar to 'liftIO' and 'liftBase' in that it
-- lifts a base computation to the constructed monad.
--
-- Instances should satisfy similar laws as the 'MonadIO' and 'MonadBase' laws:
--
-- @liftBaseWith . const . return = return@
--
-- @liftBaseWith (const (m >>= f)) = liftBaseWith (const m) >>= liftBaseWith . const . f@
--
-- The difference with 'liftBase' is that before lifting the base computation
-- @liftBaseWith@ captures the state of @m@. It then provides the base
-- computation with a 'RunInBase' function that allows running @m@
-- computations in the base monad on the captured state.
liftBaseWith :: (RunInBase m b -> b a) -> m a
-- | Construct a @m@ computation from the monadic state of @m@ that is
-- returned from a 'RunInBase' function.
--
-- Instances should satisfy:
--
-- @liftBaseWith (\\runInBase -> runInBase m) >>= restoreM = m@
restoreM :: StM m a -> m a
-- | A function that runs a @m@ computation on the monadic state that was
-- captured by 'liftBaseWith'
--
-- A @RunInBase m@ function yields a computation in the base monad of @m@ that
-- returns the monadic state of @m@. This state can later be used to restore the
-- @m@ computation using 'restoreM'.
type RunInBase m b = forall a. m a -> b (StM m a)
--------------------------------------------------------------------------------
-- MonadBaseControl instances for all monads in the base library
--------------------------------------------------------------------------------
instance MonadBaseControl (IO) (IO) where { type StM (IO) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl (Maybe) (Maybe) where { type StM (Maybe) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl (Either e) (Either e) where { type StM (Either e) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl ([]) ([]) where { type StM ([]) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl ((->) r) ((->) r) where { type StM ((->) r) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl (Identity) (Identity) where { type StM (Identity) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl (STM) (STM) where { type StM (STM) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl (Strict.ST s) (Strict.ST s) where { type StM (Strict.ST s) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance MonadBaseControl ( ST s) ( ST s) where { type StM ( ST s) a = a; liftBaseWith f = f id; restoreM = return; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
--------------------------------------------------------------------------------
-- Defaults for MonadBaseControl
--------------------------------------------------------------------------------
-- $MonadBaseControlDefaults
--
-- Note that by using the following default definitions it's easy to make a
-- monad transformer @T@ an instance of 'MonadBaseControl':
--
-- @
-- instance MonadBaseControl b m => MonadBaseControl b (T m) where
-- type StM (T m) a = 'ComposeSt' T m a
-- liftBaseWith = 'defaultLiftBaseWith'
-- restoreM = 'defaultRestoreM'
-- @
--
-- Defining an instance for a base monad @B@ is equally straightforward:
--
-- @
-- instance MonadBaseControl B B where
-- type StM B a = a
-- liftBaseWith f = f 'id'
-- restoreM = 'return'
-- @
-- | Handy type synonym that composes the monadic states of @t@ and @m@.
--
-- It can be used to define the 'StM' for new 'MonadBaseControl' instances.
type ComposeSt t m a = StM m (StT t a)
-- | A function like 'RunInBase' that runs a monad transformer @t@ in its base
-- monad @b@. It is used in 'defaultLiftBaseWith'.
type RunInBaseDefault t m b = forall a. t m a -> b (ComposeSt t m a)
-- | Default defintion for the 'liftBaseWith' method.
--
-- Note that it composes a 'liftWith' of @t@ with a 'liftBaseWith' of @m@ to
-- give a 'liftBaseWith' of @t m@:
--
-- @
-- defaultLiftBaseWith = \\f -> 'liftWith' $ \\run ->
-- 'liftBaseWith' $ \\runInBase ->
-- f $ runInBase . run
-- @
defaultLiftBaseWith :: (MonadTransControl t, MonadBaseControl b m)
=> (RunInBaseDefault t m b -> b a) -> t m a
defaultLiftBaseWith = \f -> liftWith $ \run ->
liftBaseWith $ \runInBase ->
f $ runInBase . run
{-# INLINABLE defaultLiftBaseWith #-}
-- | Default definition for the 'restoreM' method.
--
-- Note that: @defaultRestoreM = 'restoreT' . 'restoreM'@
defaultRestoreM :: (MonadTransControl t, MonadBaseControl b m)
=> ComposeSt t m a -> t m a
defaultRestoreM = restoreT . restoreM
{-# INLINABLE defaultRestoreM #-}
--------------------------------------------------------------------------------
-- MonadBaseControl transformer instances
--------------------------------------------------------------------------------
instance ( MonadBaseControl b m) => MonadBaseControl b (IdentityT m) where { type StM (IdentityT m) a = ComposeSt (IdentityT) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance ( MonadBaseControl b m) => MonadBaseControl b (MaybeT m) where { type StM (MaybeT m) a = ComposeSt (MaybeT) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance ( MonadBaseControl b m) => MonadBaseControl b (ListT m) where { type StM (ListT m) a = ComposeSt (ListT) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance ( MonadBaseControl b m) => MonadBaseControl b (ReaderT r m) where { type StM (ReaderT r m) a = ComposeSt (ReaderT r) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance ( MonadBaseControl b m) => MonadBaseControl b (Strict.StateT s m) where { type StM (Strict.StateT s m) a = ComposeSt (Strict.StateT s) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance ( MonadBaseControl b m) => MonadBaseControl b ( StateT s m) where { type StM ( StateT s m) a = ComposeSt ( StateT s) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance ( MonadBaseControl b m) => MonadBaseControl b (ExceptT e m) where { type StM (ExceptT e m) a = ComposeSt (ExceptT e) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance (Error e, MonadBaseControl b m) => MonadBaseControl b ( ErrorT e m) where { type StM ( ErrorT e m) a = ComposeSt ( ErrorT e) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance (Monoid w, MonadBaseControl b m) => MonadBaseControl b ( Strict.WriterT w m) where { type StM ( Strict.WriterT w m) a = ComposeSt ( Strict.WriterT w) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance (Monoid w, MonadBaseControl b m) => MonadBaseControl b ( WriterT w m) where { type StM ( WriterT w m) a = ComposeSt ( WriterT w) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance (Monoid w, MonadBaseControl b m) => MonadBaseControl b ( Strict.RWST r w s m) where { type StM ( Strict.RWST r w s m) a = ComposeSt ( Strict.RWST r w s) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
instance (Monoid w, MonadBaseControl b m) => MonadBaseControl b ( RWST r w s m) where { type StM ( RWST r w s m) a = ComposeSt ( RWST r w s) m a; liftBaseWith = defaultLiftBaseWith; restoreM = defaultRestoreM; {-# INLINABLE liftBaseWith #-}; {-# INLINABLE restoreM #-}}
--------------------------------------------------------------------------------
-- * Utility functions
--------------------------------------------------------------------------------
-- | An often used composition: @control f = 'liftBaseWith' f >>= 'restoreM'@
control :: MonadBaseControl b m => (RunInBase m b -> b (StM m a)) -> m a
control f = liftBaseWith f >>= restoreM
{-# INLINABLE control #-}
-- | Embed a transformer function as an function in the base monad returning a
-- mutated transformer state.
embed :: MonadBaseControl b m => (a -> m c) -> m (a -> b (StM m c))
embed f = liftBaseWith $ \runInBase -> return (runInBase . f)
{-# INLINABLE embed #-}
-- | Performs the same function as 'embed', but discards transformer state
-- from the embedded function.
embed_ :: MonadBaseControl b m => (a -> m ()) -> m (a -> b ())
embed_ f = liftBaseWith $ \runInBase -> return (void . runInBase . f)
{-# INLINABLE embed_ #-}
-- | Capture the current state of a transformer
captureT :: (MonadTransControl t, Monad (t m), Monad m) => t m (StT t ())
captureT = liftWith $ \runInM -> runInM (return ())
{-# INLINABLE captureT #-}
-- | Capture the current state above the base monad
captureM :: MonadBaseControl b m => m (StM m ())
captureM = liftBaseWith $ \runInBase -> runInBase (return ())
{-# INLINABLE captureM #-}
-- | @liftBaseOp@ is a particular application of 'liftBaseWith' that allows
-- lifting control operations of type:
--
-- @((a -> b c) -> b c)@ to: @('MonadBaseControl' b m => (a -> m c) -> m c)@.
--
-- For example:
--
-- @liftBaseOp alloca :: 'MonadBaseControl' 'IO' m => (Ptr a -> m c) -> m c@
liftBaseOp :: MonadBaseControl b m
=> ((a -> b (StM m c)) -> b (StM m d))
-> ((a -> m c) -> m d)
liftBaseOp f = \g -> control $ \runInBase -> f $ runInBase . g
{-# INLINABLE liftBaseOp #-}
-- | @liftBaseOp_@ is a particular application of 'liftBaseWith' that allows
-- lifting control operations of type:
--
-- @(b a -> b a)@ to: @('MonadBaseControl' b m => m a -> m a)@.
--
-- For example:
--
-- @liftBaseOp_ mask_ :: 'MonadBaseControl' 'IO' m => m a -> m a@
liftBaseOp_ :: MonadBaseControl b m
=> (b (StM m a) -> b (StM m c))
-> ( m a -> m c)
liftBaseOp_ f = \m -> control $ \runInBase -> f $ runInBase m
{-# INLINABLE liftBaseOp_ #-}
-- | @liftBaseDiscard@ is a particular application of 'liftBaseWith' that allows
-- lifting control operations of type:
--
-- @(b () -> b a)@ to: @('MonadBaseControl' b m => m () -> m a)@.
--
-- Note that, while the argument computation @m ()@ has access to the captured
-- state, all its side-effects in @m@ are discarded. It is run only for its
-- side-effects in the base monad @b@.
--
-- For example:
--
-- @liftBaseDiscard forkIO :: 'MonadBaseControl' 'IO' m => m () -> m ThreadId@
liftBaseDiscard :: MonadBaseControl b m => (b () -> b a) -> (m () -> m a)
liftBaseDiscard f = \m -> liftBaseWith $ \runInBase -> f $ void $ runInBase m
{-# INLINABLE liftBaseDiscard #-}
-- | @liftBaseOpDiscard@ is a particular application of 'liftBaseWith' that allows
-- lifting control operations of type:
--
-- @((a -> b ()) -> b c)@ to: @('MonadBaseControl' b m => (a -> m ()) -> m c)@.
--
-- Note that, while the argument computation @m ()@ has access to the captured
-- state, all its side-effects in @m@ are discarded. It is run only for its
-- side-effects in the base monad @b@.
--
-- For example:
--
-- @liftBaseDiscard (runServer addr port) :: 'MonadBaseControl' 'IO' m => m () -> m ()@
liftBaseOpDiscard :: MonadBaseControl b m
=> ((a -> b ()) -> b c)
-> (a -> m ()) -> m c
liftBaseOpDiscard f g = liftBaseWith $ \runInBase -> f $ void . runInBase . g
{-# INLINABLE liftBaseOpDiscard #-}
-- | Transform an action in @t m@ using a transformer that operates on the underlying monad @m@
liftThrough
:: (MonadTransControl t, Monad (t m), Monad m)
=> (m (StT t a) -> m (StT t b)) -- ^
-> t m a -> t m b
liftThrough f t = do
st <- liftWith $ \run -> do
f $ run t
restoreT $ return st
|
phischu/fragnix
|
tests/packages/scotty/Control.Monad.Trans.Control.hs
|
bsd-3-clause
| 24,430 | 21 | 13 | 6,545 | 4,822 | 2,767 | 2,055 | 190 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | Take an existing build plan and bump all packages to the newest version in
-- the same major version number.
module Stackage.UpdateBuildPlan
( updateBuildConstraints
, updateBuildPlan
) where
import qualified Data.Map as Map
import Distribution.Version (anyVersion, earlierVersion,
orLaterVersion)
import Stackage.BuildConstraints
import Stackage.BuildPlan
import Stackage.Prelude
updateBuildPlan :: Map PackageName PackagePlan -> BuildPlan -> IO BuildPlan
updateBuildPlan packagesOrig
= newBuildPlan packagesOrig . updateBuildConstraints
updateBuildConstraints :: BuildPlan -> BuildConstraints
updateBuildConstraints BuildPlan {..} =
BuildConstraints {..}
where
bcSystemInfo = bpSystemInfo
bcPackages = Map.keysSet bpPackages
bcGithubUsers = bpGithubUsers
bcPackageConstraints name = PackageConstraints
{ pcVersionRange = addBumpRange (maybe anyVersion pcVersionRange moldPC)
, pcMaintainer = moldPC >>= pcMaintainer
, pcTests = maybe ExpectSuccess pcTests moldPC
, pcHaddocks = maybe ExpectSuccess pcHaddocks moldPC
, pcBuildBenchmarks = maybe True pcBuildBenchmarks moldPC
, pcFlagOverrides = maybe mempty pcFlagOverrides moldPC
, pcEnableLibProfile = maybe False pcEnableLibProfile moldPC
}
where
moldBP = lookup name bpPackages
moldPC = ppConstraints <$> moldBP
addBumpRange oldRange =
case moldBP of
Nothing -> oldRange
Just bp -> intersectVersionRanges oldRange
$ bumpRange $ ppVersion bp
bumpRange version = intersectVersionRanges
(orLaterVersion version)
(earlierVersion $ bumpVersion version)
bumpVersion (Version (x:y:_) _) = Version [x, y + 1] []
bumpVersion (Version [x] _) = Version [x, 1] []
bumpVersion (Version [] _) = assert False $ Version [1, 0] []
|
jeffreyrosenbluth/stackage
|
Stackage/UpdateBuildPlan.hs
|
mit
| 2,121 | 0 | 14 | 567 | 453 | 242 | 211 | 42 | 4 |
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where
import Data.List
import Data.Dynamic
import System.Directory
import System.IO
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import Text.Parsec
import qualified Data.Map.Strict as M
import qualified Data.Number.LogFloat as LF
import Mixture (Prob, empty, point, Mixture(..), mnull)
import Types (Cond(..), CSampler)
import InterpreterDynamic
import Lambda (dbl)
-- particle filtering
onlineFiltering
:: (Ord a, Show a)
=> (Mixture a -> Double -> Double -> Double -> Measure a)
-> Mixture a
-> [[Cond]]
-> Int
-> Double
-> Double
-> Double
-> IO (Mixture a)
onlineFiltering _ prior [] _ _ _ _ = return prior
onlineFiltering prog prior (cond:conds) n x y t = do
let curTime = convertTime (head cond)
let timeElapsed = curTime - t
posterior <- sample n (prog prior x y timeElapsed) (tail cond)
let mixtureList = M.toAscList (unMixture posterior)
let outputList = foldl (\acc (k, v) -> [(k, LF.fromLogFloat(v)::Double)] ++ acc) [] mixtureList
let (k, w) = head $ sortMix outputList
let output = removeBrackets (if null mixtureList then "" else (show (curTime, k, w) ++ "\n"))
appendFile "slam_out_data.csv" output
onlineFiltering prog posterior conds n x y curTime
-- quad rotor model (kalman filter)
prog_quadCopter
:: Mixture (Double, Double, Double, Double)
-> Double
-> Double
-> Double
-> Measure (Double, Double, Double, Double)
prog_quadCopter prevMix initX initY timeElapsed = do
velocity <- conditioned (uniform (dbl 0) (dbl 5))
steerAngle <- conditioned (uniform (dbl (-2)) (dbl 2))
(x0, y0, dirX, dirY) <- if mnull prevMix then return (initX, initY, 0, 1)
else unconditioned (categorical (M.toList(unMixture prevMix)))
let orientX = dirX * cos (-1 * steerAngle) - dirY * sin (-1 * steerAngle)
let orientY = dirY * cos (-1 * steerAngle) + dirX * sin (-1 * steerAngle)
x1 <- unconditioned (normal (x0 + orientX * velocity*timeElapsed) (dbl 7))
y1 <- unconditioned (normal (y0 + orientY * velocity*timeElapsed) (dbl 7))
_ <- conditioned (normal (x1 :: Double) (dbl 1))
_ <- conditioned (normal (y1 :: Double) (dbl 1))
return (x1, y1, orientX, orientY)
-- helper functions
compareMix (_, v1) (_, v2) = if v1 < v2 then GT else LT
sortMix = sortBy compareMix
csvFile = endBy line eol
line = sepBy cell (char ',')
cell = many (noneOf ",\n")
eol = char '\n'
parseCSV :: String -> Either ParseError [[String]]
parseCSV input = parse csvFile "(unknown)" input
removeBrackets :: String -> String
removeBrackets st = [c | c <- st, c `notElem` ['(', ')']]
convertTime :: Cond -> Double
convertTime (Lebesgue t) =
case fromDynamic t of
Just t -> t
Nothing -> error "Not conditioned data"
convertTime (Discrete t) =
case fromDynamic t of
Just t -> t
Nothing -> error "Not conditioned data"
convertTime (Unconditioned) = 0.0
convertC :: Either ParseError [[String]] -> [[Cond]]
convertC (Left _) = [[]]
convertC (Right s) =
map (map $ \x1 -> Lebesgue (toDyn (read x1 :: Double))) s
convertS :: Either ParseError [[String]] -> [[String]]
convertS (Left _) = [[]]
convertS (Right s) = s
convertD :: [[String]] -> [[Double]]
convertD str = map (\x0 -> map (\x1 -> read x1 :: Double) x0) str
convertTable :: [[String]] -> [String]
convertTable table =
foldl (\acc x -> acc ++ [convertCSV x (head x)]) [] table
convertCSV :: [String] -> String -> String
convertCSV list firstElement =
foldl (\acc x ->
if (x == firstElement)
then acc ++ x
else acc ++ "," ++ x)
"" list
mergeGPS :: [Double] -> [Double] -> [[Double]] -> Int -> [[String]] -> [[String]]
mergeGPS _ _ _ 0 list = list
mergeGPS time_g time_r results n list =
mergeGPS time_g time_r results (n - 1) $
if (time_r !! n) `elem` time_g
then [show (time_r !! n), show (results !! n !! 1), show (results !! n !! 2)] : list
else list
-- main program
main :: IO ()
main = do
args <- getArgs
writeFile "slam_out_landmarks.csv" ""
case args of
[numParticles, x, y] -> do
handle <- openFile "output.csv" ReadMode
contents <- hGetContents handle
let cond = convertS (parseCSV contents)
print ((show (length cond)) ++ " row(s)")
print ((show (length (head cond))) ++ " column(s)")
let condInput = convertC (parseCSV contents)
-- ignore orientation column
let condInputFix = transpose (init (transpose condInput))
exist <- doesFileExist "slam_out_data.csv"
if exist then removeFile "slam_out_data.csv" else return ()
output <- onlineFiltering prog_quadCopter empty condInputFix
(read numParticles :: Int)
(read x :: Double) (read y :: Double) 0.0
putStrLn (show output)
_ -> do
progName <- getProgName
hPutStrLn stderr ("Usage: " ++ progName ++
" <number of particles> <initial latitude> <initial longitude>")
hPutStrLn stderr ("Example: " ++ progName ++ " 30 0 -6")
exitFailure
gps_contents <- readFile "slam_gps.csv"
let gps = tail (convertD (convertS (parseCSV gps_contents)))
let gps_c = head (transpose gps)
results_contents <- readFile "slam_out_data.csv"
let results = convertD (convertS (parseCSV results_contents))
let results_c = head (transpose results)
let slam_output = mergeGPS gps_c results_c results ((length results) - 1) [[]]
writeFile "slam_out_path.csv" (show (head (head gps)) ++ "," ++
show ((head gps) !! 1) ++ "," ++ show ((head gps) !! 2) ++ "\n")
appendFile "slam_out_path.csv" (unlines (convertTable slam_output))
putStrLn "Output written to slam_out_path.csv"
|
zaxtax/hakaru
|
haskell/Examples/Quadrotor.hs
|
bsd-3-clause
| 5,892 | 13 | 17 | 1,422 | 2,296 | 1,197 | 1,099 | 136 | 3 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
DeriveTraversable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Abstract syntax of global declarations.
--
-- Definitions for: @SynDecl@ and @ConDecl@, @ClassDecl@,
-- @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
module HsDecls (
-- * Toplevel declarations
HsDecl(..), LHsDecl, HsDataDefn(..),
-- ** Class or type declarations
TyClDecl(..), LTyClDecl,
TyClGroup(..), tyClGroupConcat, mkTyClGroup,
isClassDecl, isDataDecl, isSynDecl, tcdName,
isFamilyDecl, isTypeFamilyDecl, isDataFamilyDecl,
isOpenTypeFamilyInfo, isClosedTypeFamilyInfo,
tyFamInstDeclName, tyFamInstDeclLName,
countTyClDecls, pprTyClDeclFlavour,
tyClDeclLName, tyClDeclTyVars,
hsDeclHasCusk, famDeclHasCusk,
FamilyDecl(..), LFamilyDecl,
-- ** Instance declarations
InstDecl(..), LInstDecl, NewOrData(..), FamilyInfo(..),
TyFamInstDecl(..), LTyFamInstDecl, instDeclDataFamInsts,
DataFamInstDecl(..), LDataFamInstDecl, pprDataFamInstFlavour,
TyFamEqn(..), TyFamInstEqn, LTyFamInstEqn, TyFamDefltEqn, LTyFamDefltEqn,
HsTyPats,
LClsInstDecl, ClsInstDecl(..),
-- ** Standalone deriving declarations
DerivDecl(..), LDerivDecl,
-- ** @RULE@ declarations
LRuleDecls,RuleDecls(..),RuleDecl(..), LRuleDecl, RuleBndr(..),LRuleBndr,
collectRuleBndrSigTys,
flattenRuleDecls,
-- ** @VECTORISE@ declarations
VectDecl(..), LVectDecl,
lvectDeclName, lvectInstDecl,
-- ** @default@ declarations
DefaultDecl(..), LDefaultDecl,
-- ** Template haskell declaration splice
SpliceExplicitFlag(..),
SpliceDecl(..), LSpliceDecl,
-- ** Foreign function interface declarations
ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
noForeignImportCoercionYet, noForeignExportCoercionYet,
CImportSpec(..),
-- ** Data-constructor declarations
ConDecl(..), LConDecl, ResType(..),
HsConDeclDetails, hsConDeclArgTys,
-- ** Document comments
DocDecl(..), LDocDecl, docDeclDoc,
-- ** Deprecations
WarnDecl(..), LWarnDecl,
WarnDecls(..), LWarnDecls,
-- ** Annotations
AnnDecl(..), LAnnDecl,
AnnProvenance(..), annProvenanceName_maybe,
-- ** Role annotations
RoleAnnotDecl(..), LRoleAnnotDecl, roleAnnotDeclName,
-- * Grouping
HsGroup(..), emptyRdrGroup, emptyRnGroup, appendGroups
) where
-- friends:
import {-# SOURCE #-} HsExpr( LHsExpr, HsExpr, HsSplice, pprExpr, pprSplice )
-- Because Expr imports Decls via HsBracket
import HsBinds
import HsPat
import HsTypes
import HsDoc
import TyCon
import Name
import BasicTypes
import Coercion
import ForeignCall
import PlaceHolder ( PostTc,PostRn,PlaceHolder(..),DataId )
import NameSet
-- others:
import InstEnv
import Class
import Outputable
import Util
import SrcLoc
import FastString
import Bag
import Data.Data hiding (TyCon,Fixity)
#if __GLASGOW_HASKELL__ < 709
import Data.Foldable ( Foldable )
import Data.Traversable ( Traversable )
#endif
import Data.Maybe
{-
************************************************************************
* *
\subsection[HsDecl]{Declarations}
* *
************************************************************************
-}
type LHsDecl id = Located (HsDecl id)
-- ^ When in a list this may have
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi'
--
-- For details on above see note [Api annotations] in ApiAnnotation
-- | A Haskell Declaration
data HsDecl id
= TyClD (TyClDecl id) -- ^ A type or class declaration.
| InstD (InstDecl id) -- ^ An instance declaration.
| DerivD (DerivDecl id)
| ValD (HsBind id)
| SigD (Sig id)
| DefD (DefaultDecl id)
| ForD (ForeignDecl id)
| WarningD (WarnDecls id)
| AnnD (AnnDecl id)
| RuleD (RuleDecls id)
| VectD (VectDecl id)
| SpliceD (SpliceDecl id) -- Includes quasi-quotes
| DocD (DocDecl)
| RoleAnnotD (RoleAnnotDecl id)
deriving (Typeable)
deriving instance (DataId id) => Data (HsDecl id)
-- NB: all top-level fixity decls are contained EITHER
-- EITHER SigDs
-- OR in the ClassDecls in TyClDs
--
-- The former covers
-- a) data constructors
-- b) class methods (but they can be also done in the
-- signatures of class decls)
-- c) imported functions (that have an IfacSig)
-- d) top level decls
--
-- The latter is for class methods only
-- | A 'HsDecl' is categorised into a 'HsGroup' before being
-- fed to the renamer.
data HsGroup id
= HsGroup {
hs_valds :: HsValBinds id,
hs_splcds :: [LSpliceDecl id],
hs_tyclds :: [TyClGroup id],
-- A list of mutually-recursive groups
-- No family-instances here; they are in hs_instds
-- Parser generates a singleton list;
-- renamer does dependency analysis
hs_instds :: [LInstDecl id],
-- Both class and family instance declarations in here
hs_derivds :: [LDerivDecl id],
hs_fixds :: [LFixitySig id],
-- Snaffled out of both top-level fixity signatures,
-- and those in class declarations
hs_defds :: [LDefaultDecl id],
hs_fords :: [LForeignDecl id],
hs_warnds :: [LWarnDecls id],
hs_annds :: [LAnnDecl id],
hs_ruleds :: [LRuleDecls id],
hs_vects :: [LVectDecl id],
hs_docs :: [LDocDecl]
} deriving (Typeable)
deriving instance (DataId id) => Data (HsGroup id)
emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup a
emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
emptyRnGroup = emptyGroup { hs_valds = emptyValBindsOut }
emptyGroup = HsGroup { hs_tyclds = [], hs_instds = [],
hs_derivds = [],
hs_fixds = [], hs_defds = [], hs_annds = [],
hs_fords = [], hs_warnds = [], hs_ruleds = [], hs_vects = [],
hs_valds = error "emptyGroup hs_valds: Can't happen",
hs_splcds = [],
hs_docs = [] }
appendGroups :: HsGroup a -> HsGroup a -> HsGroup a
appendGroups
HsGroup {
hs_valds = val_groups1,
hs_splcds = spliceds1,
hs_tyclds = tyclds1,
hs_instds = instds1,
hs_derivds = derivds1,
hs_fixds = fixds1,
hs_defds = defds1,
hs_annds = annds1,
hs_fords = fords1,
hs_warnds = warnds1,
hs_ruleds = rulds1,
hs_vects = vects1,
hs_docs = docs1 }
HsGroup {
hs_valds = val_groups2,
hs_splcds = spliceds2,
hs_tyclds = tyclds2,
hs_instds = instds2,
hs_derivds = derivds2,
hs_fixds = fixds2,
hs_defds = defds2,
hs_annds = annds2,
hs_fords = fords2,
hs_warnds = warnds2,
hs_ruleds = rulds2,
hs_vects = vects2,
hs_docs = docs2 }
=
HsGroup {
hs_valds = val_groups1 `plusHsValBinds` val_groups2,
hs_splcds = spliceds1 ++ spliceds2,
hs_tyclds = tyclds1 ++ tyclds2,
hs_instds = instds1 ++ instds2,
hs_derivds = derivds1 ++ derivds2,
hs_fixds = fixds1 ++ fixds2,
hs_annds = annds1 ++ annds2,
hs_defds = defds1 ++ defds2,
hs_fords = fords1 ++ fords2,
hs_warnds = warnds1 ++ warnds2,
hs_ruleds = rulds1 ++ rulds2,
hs_vects = vects1 ++ vects2,
hs_docs = docs1 ++ docs2 }
instance OutputableBndr name => Outputable (HsDecl name) where
ppr (TyClD dcl) = ppr dcl
ppr (ValD binds) = ppr binds
ppr (DefD def) = ppr def
ppr (InstD inst) = ppr inst
ppr (DerivD deriv) = ppr deriv
ppr (ForD fd) = ppr fd
ppr (SigD sd) = ppr sd
ppr (RuleD rd) = ppr rd
ppr (VectD vect) = ppr vect
ppr (WarningD wd) = ppr wd
ppr (AnnD ad) = ppr ad
ppr (SpliceD dd) = ppr dd
ppr (DocD doc) = ppr doc
ppr (RoleAnnotD ra) = ppr ra
instance OutputableBndr name => Outputable (HsGroup name) where
ppr (HsGroup { hs_valds = val_decls,
hs_tyclds = tycl_decls,
hs_instds = inst_decls,
hs_derivds = deriv_decls,
hs_fixds = fix_decls,
hs_warnds = deprec_decls,
hs_annds = ann_decls,
hs_fords = foreign_decls,
hs_defds = default_decls,
hs_ruleds = rule_decls,
hs_vects = vect_decls })
= vcat_mb empty
[ppr_ds fix_decls, ppr_ds default_decls,
ppr_ds deprec_decls, ppr_ds ann_decls,
ppr_ds rule_decls,
ppr_ds vect_decls,
if isEmptyValBinds val_decls
then Nothing
else Just (ppr val_decls),
ppr_ds (tyClGroupConcat tycl_decls),
ppr_ds inst_decls,
ppr_ds deriv_decls,
ppr_ds foreign_decls]
where
ppr_ds :: Outputable a => [a] -> Maybe SDoc
ppr_ds [] = Nothing
ppr_ds ds = Just (vcat (map ppr ds))
vcat_mb :: SDoc -> [Maybe SDoc] -> SDoc
-- Concatenate vertically with white-space between non-blanks
vcat_mb _ [] = empty
vcat_mb gap (Nothing : ds) = vcat_mb gap ds
vcat_mb gap (Just d : ds) = gap $$ d $$ vcat_mb blankLine ds
data SpliceExplicitFlag = ExplicitSplice | -- <=> $(f x y)
ImplicitSplice -- <=> f x y, i.e. a naked top level expression
deriving (Data, Typeable)
type LSpliceDecl name = Located (SpliceDecl name)
data SpliceDecl id
= SpliceDecl -- Top level splice
(Located (HsSplice id))
SpliceExplicitFlag
deriving (Typeable)
deriving instance (DataId id) => Data (SpliceDecl id)
instance OutputableBndr name => Outputable (SpliceDecl name) where
ppr (SpliceDecl (L _ e) _) = pprSplice e
{-
************************************************************************
* *
\subsection[SynDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
* *
************************************************************************
--------------------------------
THE NAMING STORY
--------------------------------
Here is the story about the implicit names that go with type, class,
and instance decls. It's a bit tricky, so pay attention!
"Implicit" (or "system") binders
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Each data type decl defines
a worker name for each constructor
to-T and from-T convertors
Each class decl defines
a tycon for the class
a data constructor for that tycon
the worker for that constructor
a selector for each superclass
All have occurrence names that are derived uniquely from their parent
declaration.
None of these get separate definitions in an interface file; they are
fully defined by the data or class decl. But they may *occur* in
interface files, of course. Any such occurrence must haul in the
relevant type or class decl.
Plan of attack:
- Ensure they "point to" the parent data/class decl
when loading that decl from an interface file
(See RnHiFiles.getSysBinders)
- When typechecking the decl, we build the implicit TyCons and Ids.
When doing so we look them up in the name cache (RnEnv.lookupSysName),
to ensure correct module and provenance is set
These are the two places that we have to conjure up the magic derived
names. (The actual magic is in OccName.mkWorkerOcc, etc.)
Default methods
~~~~~~~~~~~~~~~
- Occurrence name is derived uniquely from the method name
E.g. $dmmax
- If there is a default method name at all, it's recorded in
the ClassOpSig (in HsBinds), in the DefMeth field.
(DefMeth is defined in Class.hs)
Source-code class decls and interface-code class decls are treated subtly
differently, which has given me a great deal of confusion over the years.
Here's the deal. (We distinguish the two cases because source-code decls
have (Just binds) in the tcdMeths field, whereas interface decls have Nothing.
In *source-code* class declarations:
- When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
This is done by RdrHsSyn.mkClassOpSigDM
- The renamer renames it to a Name
- During typechecking, we generate a binding for each $dm for
which there's a programmer-supplied default method:
class Foo a where
op1 :: <type>
op2 :: <type>
op1 = ...
We generate a binding for $dmop1 but not for $dmop2.
The Class for Foo has a NoDefMeth for op2 and a DefMeth for op1.
The Name for $dmop2 is simply discarded.
In *interface-file* class declarations:
- When parsing, we see if there's an explicit programmer-supplied default method
because there's an '=' sign to indicate it:
class Foo a where
op1 = :: <type> -- NB the '='
op2 :: <type>
We use this info to generate a DefMeth with a suitable RdrName for op1,
and a NoDefMeth for op2
- The interface file has a separate definition for $dmop1, with unfolding etc.
- The renamer renames it to a Name.
- The renamer treats $dmop1 as a free variable of the declaration, so that
the binding for $dmop1 will be sucked in. (See RnHsSyn.tyClDeclFVs)
This doesn't happen for source code class decls, because they *bind* the default method.
Dictionary functions
~~~~~~~~~~~~~~~~~~~~
Each instance declaration gives rise to one dictionary function binding.
The type checker makes up new source-code instance declarations
(e.g. from 'deriving' or generic default methods --- see
TcInstDcls.tcInstDecls1). So we can't generate the names for
dictionary functions in advance (we don't know how many we need).
On the other hand for interface-file instance declarations, the decl
specifies the name of the dictionary function, and it has a binding elsewhere
in the interface file:
instance {Eq Int} = dEqInt
dEqInt :: {Eq Int} <pragma info>
So again we treat source code and interface file code slightly differently.
Source code:
- Source code instance decls have a Nothing in the (Maybe name) field
(see data InstDecl below)
- The typechecker makes up a Local name for the dict fun for any source-code
instance decl, whether it comes from a source-code instance decl, or whether
the instance decl is derived from some other construct (e.g. 'deriving').
- The occurrence name it chooses is derived from the instance decl (just for
documentation really) --- e.g. dNumInt. Two dict funs may share a common
occurrence name, but will have different uniques. E.g.
instance Foo [Int] where ...
instance Foo [Bool] where ...
These might both be dFooList
- The CoreTidy phase externalises the name, and ensures the occurrence name is
unique (this isn't special to dict funs). So we'd get dFooList and dFooList1.
- We can take this relaxed approach (changing the occurrence name later)
because dict fun Ids are not captured in a TyCon or Class (unlike default
methods, say). Instead, they are kept separately in the InstEnv. This
makes it easy to adjust them after compiling a module. (Once we've finished
compiling that module, they don't change any more.)
Interface file code:
- The instance decl gives the dict fun name, so the InstDecl has a (Just name)
in the (Maybe name) field.
- RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we
suck in the dfun binding
-}
type LTyClDecl name = Located (TyClDecl name)
-- | A type or class declaration.
data TyClDecl name
= -- | @type/data family T :: *->*@
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
-- 'ApiAnnotation.AnnData',
-- 'ApiAnnotation.AnnFamily','ApiAnnotation.AnnDcolon',
-- 'ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnDcolon',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
FamDecl { tcdFam :: FamilyDecl name }
| -- | @type@ declaration
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
-- 'ApiAnnotation.AnnEqual',
-- For details on above see note [Api annotations] in ApiAnnotation
SynDecl { tcdLName :: Located name -- ^ Type constructor
, tcdTyVars :: LHsTyVarBndrs name -- ^ Type variables; for an associated type
-- these include outer binders
, tcdRhs :: LHsType name -- ^ RHS of type declaration
, tcdFVs :: PostRn name NameSet }
| -- | @data@ declaration
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnData',
-- 'ApiAnnotation.AnnFamily',
-- 'ApiAnnotation.AnnNewType',
-- 'ApiAnnotation.AnnNewType','ApiAnnotation.AnnDcolon'
-- 'ApiAnnotation.AnnWhere',
-- For details on above see note [Api annotations] in ApiAnnotation
DataDecl { tcdLName :: Located name -- ^ Type constructor
, tcdTyVars :: LHsTyVarBndrs name -- ^ Type variables; for an assoicated type
-- these include outer binders
-- Eg class T a where
-- type F a :: *
-- type F a = a -> a
-- Here the type decl for 'f' includes 'a'
-- in its tcdTyVars
, tcdDataDefn :: HsDataDefn name
, tcdFVs :: PostRn name NameSet }
| ClassDecl { tcdCtxt :: LHsContext name, -- ^ Context...
tcdLName :: Located name, -- ^ Name of the class
tcdTyVars :: LHsTyVarBndrs name, -- ^ Class type variables
tcdFDs :: [Located (FunDep (Located name))],
-- ^ Functional deps
tcdSigs :: [LSig name], -- ^ Methods' signatures
tcdMeths :: LHsBinds name, -- ^ Default methods
tcdATs :: [LFamilyDecl name], -- ^ Associated types;
tcdATDefs :: [LTyFamDefltEqn name], -- ^ Associated type defaults
tcdDocs :: [LDocDecl], -- ^ Haddock docs
tcdFVs :: PostRn name NameSet
}
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnClass',
-- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- - The tcdFDs will have 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnComma'
-- 'ApiAnnotation.AnnRarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId id) => Data (TyClDecl id)
-- This is used in TcTyClsDecls to represent
-- strongly connected components of decls
-- No familiy instances in here
-- The role annotations must be grouped with their decls for the
-- type-checker to infer roles correctly
data TyClGroup name
= TyClGroup { group_tyclds :: [LTyClDecl name]
, group_roles :: [LRoleAnnotDecl name] }
deriving (Typeable)
deriving instance (DataId id) => Data (TyClGroup id)
tyClGroupConcat :: [TyClGroup name] -> [LTyClDecl name]
tyClGroupConcat = concatMap group_tyclds
mkTyClGroup :: [LTyClDecl name] -> TyClGroup name
mkTyClGroup decls = TyClGroup { group_tyclds = decls, group_roles = [] }
type LFamilyDecl name = Located (FamilyDecl name)
data FamilyDecl name = FamilyDecl
{ fdInfo :: FamilyInfo name -- type or data, closed or open
, fdLName :: Located name -- type constructor
, fdTyVars :: LHsTyVarBndrs name -- type variables
, fdKindSig :: Maybe (LHsKind name) } -- result kind
deriving( Typeable )
deriving instance (DataId id) => Data (FamilyDecl id)
data FamilyInfo name
= DataFamily
| OpenTypeFamily
-- | 'Nothing' if we're in an hs-boot file and the user
-- said "type family Foo x where .."
| ClosedTypeFamily (Maybe [LTyFamInstEqn name])
deriving( Typeable )
deriving instance (DataId name) => Data (FamilyInfo name)
{-
------------------------------
Simple classifiers
-}
-- | @True@ <=> argument is a @data@\/@newtype@
-- declaration.
isDataDecl :: TyClDecl name -> Bool
isDataDecl (DataDecl {}) = True
isDataDecl _other = False
-- | type or type instance declaration
isSynDecl :: TyClDecl name -> Bool
isSynDecl (SynDecl {}) = True
isSynDecl _other = False
-- | type class
isClassDecl :: TyClDecl name -> Bool
isClassDecl (ClassDecl {}) = True
isClassDecl _ = False
-- | type/data family declaration
isFamilyDecl :: TyClDecl name -> Bool
isFamilyDecl (FamDecl {}) = True
isFamilyDecl _other = False
-- | type family declaration
isTypeFamilyDecl :: TyClDecl name -> Bool
isTypeFamilyDecl (FamDecl (FamilyDecl { fdInfo = info })) = case info of
OpenTypeFamily -> True
ClosedTypeFamily {} -> True
_ -> False
isTypeFamilyDecl _ = False
-- | open type family info
isOpenTypeFamilyInfo :: FamilyInfo name -> Bool
isOpenTypeFamilyInfo OpenTypeFamily = True
isOpenTypeFamilyInfo _ = False
-- | closed type family info
isClosedTypeFamilyInfo :: FamilyInfo name -> Bool
isClosedTypeFamilyInfo (ClosedTypeFamily {}) = True
isClosedTypeFamilyInfo _ = False
-- | data family declaration
isDataFamilyDecl :: TyClDecl name -> Bool
isDataFamilyDecl (FamDecl (FamilyDecl { fdInfo = DataFamily })) = True
isDataFamilyDecl _other = False
-- Dealing with names
tyFamInstDeclName :: TyFamInstDecl name -> name
tyFamInstDeclName = unLoc . tyFamInstDeclLName
tyFamInstDeclLName :: TyFamInstDecl name -> Located name
tyFamInstDeclLName (TyFamInstDecl { tfid_eqn =
(L _ (TyFamEqn { tfe_tycon = ln })) })
= ln
tyClDeclLName :: TyClDecl name -> Located name
tyClDeclLName (FamDecl { tcdFam = FamilyDecl { fdLName = ln } }) = ln
tyClDeclLName decl = tcdLName decl
tcdName :: TyClDecl name -> name
tcdName = unLoc . tyClDeclLName
tyClDeclTyVars :: TyClDecl name -> LHsTyVarBndrs name
tyClDeclTyVars (FamDecl { tcdFam = FamilyDecl { fdTyVars = tvs } }) = tvs
tyClDeclTyVars d = tcdTyVars d
countTyClDecls :: [TyClDecl name] -> (Int, Int, Int, Int, Int)
-- class, synonym decls, data, newtype, family decls
countTyClDecls decls
= (count isClassDecl decls,
count isSynDecl decls, -- excluding...
count isDataTy decls, -- ...family...
count isNewTy decls, -- ...instances
count isFamilyDecl decls)
where
isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = DataType } } = True
isDataTy _ = False
isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = NewType } } = True
isNewTy _ = False
-- | Does this declaration have a complete, user-supplied kind signature?
-- See Note [Complete user-supplied kind signatures]
hsDeclHasCusk :: TyClDecl name -> Bool
hsDeclHasCusk (FamDecl { tcdFam = fam_decl }) = famDeclHasCusk fam_decl
hsDeclHasCusk (SynDecl { tcdTyVars = tyvars, tcdRhs = rhs })
= hsTvbAllKinded tyvars && rhs_annotated rhs
where
rhs_annotated (L _ ty) = case ty of
HsParTy lty -> rhs_annotated lty
HsKindSig {} -> True
_ -> False
hsDeclHasCusk (DataDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars
hsDeclHasCusk (ClassDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars
-- | Does this family declaration have a complete, user-supplied kind signature?
famDeclHasCusk :: FamilyDecl name -> Bool
famDeclHasCusk (FamilyDecl { fdInfo = ClosedTypeFamily _
, fdTyVars = tyvars
, fdKindSig = m_sig })
= hsTvbAllKinded tyvars && isJust m_sig
famDeclHasCusk _ = True -- all open families have CUSKs!
{-
Note [Complete user-supplied kind signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We kind-check declarations differently if they have a complete, user-supplied
kind signature (CUSK). This is because we can safely generalise a CUSKed
declaration before checking all of the others, supporting polymorphic recursion.
See https://ghc.haskell.org/trac/ghc/wiki/GhcKinds/KindInference#Proposednewstrategy
and #9200 for lots of discussion of how we got here.
A declaration has a CUSK if we can know its complete kind without doing any inference,
at all. Here are the rules:
- A class or datatype is said to have a CUSK if and only if all of its type
variables are annotated. Its result kind is, by construction, Constraint or *
respectively.
- A type synonym has a CUSK if and only if all of its type variables and its
RHS are annotated with kinds.
- A closed type family is said to have a CUSK if and only if all of its type
variables and its return type are annotated.
- An open type family always has a CUSK -- unannotated type variables (and return type) default to *.
-}
instance OutputableBndr name
=> Outputable (TyClDecl name) where
ppr (FamDecl { tcdFam = decl }) = ppr decl
ppr (SynDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdRhs = rhs })
= hang (ptext (sLit "type") <+>
pp_vanilla_decl_head ltycon tyvars [] <+> equals)
4 (ppr rhs)
ppr (DataDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdDataDefn = defn })
= pp_data_defn (pp_vanilla_decl_head ltycon tyvars) defn
ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
tcdFDs = fds,
tcdSigs = sigs, tcdMeths = methods,
tcdATs = ats, tcdATDefs = at_defs})
| null sigs && isEmptyBag methods && null ats && null at_defs -- No "where" part
= top_matter
| otherwise -- Laid out
= vcat [ top_matter <+> ptext (sLit "where")
, nest 2 $ pprDeclList (map ppr ats ++
map ppr_fam_deflt_eqn at_defs ++
pprLHsBindsForUser methods sigs) ]
where
top_matter = ptext (sLit "class")
<+> pp_vanilla_decl_head lclas tyvars (unLoc context)
<+> pprFundeps (map unLoc fds)
instance OutputableBndr name => Outputable (TyClGroup name) where
ppr (TyClGroup { group_tyclds = tyclds, group_roles = roles })
= ppr tyclds $$
ppr roles
instance (OutputableBndr name) => Outputable (FamilyDecl name) where
ppr (FamilyDecl { fdInfo = info, fdLName = ltycon,
fdTyVars = tyvars, fdKindSig = mb_kind})
= vcat [ pprFlavour info <+> pp_vanilla_decl_head ltycon tyvars [] <+> pp_kind <+> pp_where
, nest 2 $ pp_eqns ]
where
pp_kind = case mb_kind of
Nothing -> empty
Just kind -> dcolon <+> ppr kind
(pp_where, pp_eqns) = case info of
ClosedTypeFamily mb_eqns ->
( ptext (sLit "where")
, case mb_eqns of
Nothing -> ptext (sLit "..")
Just eqns -> vcat $ map ppr_fam_inst_eqn eqns )
_ -> (empty, empty)
pprFlavour :: FamilyInfo name -> SDoc
pprFlavour DataFamily = ptext (sLit "data family")
pprFlavour OpenTypeFamily = ptext (sLit "type family")
pprFlavour (ClosedTypeFamily {}) = ptext (sLit "type family")
instance Outputable (FamilyInfo name) where
ppr = pprFlavour
pp_vanilla_decl_head :: OutputableBndr name
=> Located name
-> LHsTyVarBndrs name
-> HsContext name
-> SDoc
pp_vanilla_decl_head thing tyvars context
= hsep [pprHsContext context, pprPrefixOcc (unLoc thing), ppr tyvars]
pp_fam_inst_lhs :: OutputableBndr name
=> Located name
-> HsTyPats name
-> HsContext name
-> SDoc
pp_fam_inst_lhs thing (HsWB { hswb_cts = typats }) context -- explicit type patterns
= hsep [ pprHsContext context, pprPrefixOcc (unLoc thing)
, hsep (map (pprParendHsType.unLoc) typats)]
pprTyClDeclFlavour :: TyClDecl a -> SDoc
pprTyClDeclFlavour (ClassDecl {}) = ptext (sLit "class")
pprTyClDeclFlavour (SynDecl {}) = ptext (sLit "type")
pprTyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
= pprFlavour info
pprTyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_ND = nd } })
= ppr nd
{-
************************************************************************
* *
\subsection[ConDecl]{A data-constructor declaration}
* *
************************************************************************
-}
data HsDataDefn name -- The payload of a data type defn
-- Used *both* for vanilla data declarations,
-- *and* for data family instances
= -- | Declares a data type or newtype, giving its constructors
-- @
-- data/newtype T a = <constrs>
-- data/newtype instance T [a] = <constrs>
-- @
HsDataDefn { dd_ND :: NewOrData,
dd_ctxt :: LHsContext name, -- ^ Context
dd_cType :: Maybe (Located CType),
dd_kindSig:: Maybe (LHsKind name),
-- ^ Optional kind signature.
--
-- @(Just k)@ for a GADT-style @data@,
-- or @data instance@ decl, with explicit kind sig
--
-- Always @Nothing@ for H98-syntax decls
dd_cons :: [LConDecl name],
-- ^ Data constructors
--
-- For @data T a = T1 | T2 a@
-- the 'LConDecl's all have 'ResTyH98'.
-- For @data T a where { T1 :: T a }@
-- the 'LConDecls' all have 'ResTyGADT'.
dd_derivs :: Maybe (Located [LHsType name])
-- ^ Derivings; @Nothing@ => not specified,
-- @Just []@ => derive exactly what is asked
--
-- These "types" must be of form
-- @
-- forall ab. C ty1 ty2
-- @
-- Typically the foralls and ty args are empty, but they
-- are non-empty for the newtype-deriving case
--
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnDeriving',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
}
deriving( Typeable )
deriving instance (DataId id) => Data (HsDataDefn id)
data NewOrData
= NewType -- ^ @newtype Blah ...@
| DataType -- ^ @data Blah ...@
deriving( Eq, Data, Typeable ) -- Needed because Demand derives Eq
type LConDecl name = Located (ConDecl name)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when
-- in a GADT constructor list
-- For details on above see note [Api annotations] in ApiAnnotation
-- |
--
-- @
-- data T b = forall a. Eq a => MkT a b
-- MkT :: forall b a. Eq a => MkT a b
--
-- data T b where
-- MkT1 :: Int -> T Int
--
-- data T = Int `MkT` Int
-- | MkT2
--
-- data T a where
-- Int `MkT` Int :: T Int
-- @
--
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnCLose',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnDarrow','ApiAnnotation.AnnDarrow',
-- 'ApiAnnotation.AnnForall','ApiAnnotation.AnnDot'
-- For details on above see note [Api annotations] in ApiAnnotation
data ConDecl name
= ConDecl
{ con_names :: [Located name]
-- ^ Constructor names. This is used for the DataCon itself, and for
-- the user-callable wrapper Id.
-- It is a list to deal with GADT constructors of the form
-- T1, T2, T3 :: <payload>
, con_explicit :: HsExplicitFlag
-- ^ Is there an user-written forall? (cf. 'HsTypes.HsForAllTy')
, con_qvars :: LHsTyVarBndrs name
-- ^ Type variables. Depending on 'con_res' this describes the
-- following entities
--
-- - ResTyH98: the constructor's *existential* type variables
-- - ResTyGADT: *all* the constructor's quantified type variables
--
-- If con_explicit is Implicit, then con_qvars is irrelevant
-- until after renaming.
, con_cxt :: LHsContext name
-- ^ The context. This /does not/ include the \"stupid theta\" which
-- lives only in the 'TyData' decl.
, con_details :: HsConDeclDetails name
-- ^ The main payload
, con_res :: ResType (LHsType name)
-- ^ Result type of the constructor
, con_doc :: Maybe LHsDocString
-- ^ A possible Haddock comment.
, con_old_rec :: Bool
-- ^ TEMPORARY field; True <=> user has employed now-deprecated syntax for
-- GADT-style record decl C { blah } :: T a b
-- Remove this when we no longer parse this stuff, and hence do not
-- need to report decprecated use
} deriving (Typeable)
deriving instance (DataId name) => Data (ConDecl name)
type HsConDeclDetails name
= HsConDetails (LBangType name) (Located [LConDeclField name])
hsConDeclArgTys :: HsConDeclDetails name -> [LBangType name]
hsConDeclArgTys (PrefixCon tys) = tys
hsConDeclArgTys (InfixCon ty1 ty2) = [ty1,ty2]
hsConDeclArgTys (RecCon flds) = map (cd_fld_type . unLoc) (unLoc flds)
data ResType ty
= ResTyH98 -- Constructor was declared using Haskell 98 syntax
| ResTyGADT SrcSpan ty -- Constructor was declared using GADT-style syntax,
-- and here is its result type, and the SrcSpan
-- of the original sigtype, for API Annotations
deriving (Data, Typeable)
instance Outputable ty => Outputable (ResType ty) where
-- Debugging only
ppr ResTyH98 = ptext (sLit "ResTyH98")
ppr (ResTyGADT _ ty) = ptext (sLit "ResTyGADT") <+> ppr ty
pp_data_defn :: OutputableBndr name
=> (HsContext name -> SDoc) -- Printing the header
-> HsDataDefn name
-> SDoc
pp_data_defn pp_hdr (HsDataDefn { dd_ND = new_or_data, dd_ctxt = L _ context
, dd_kindSig = mb_sig
, dd_cons = condecls, dd_derivs = derivings })
| null condecls
= ppr new_or_data <+> pp_hdr context <+> pp_sig
| otherwise
= hang (ppr new_or_data <+> pp_hdr context <+> pp_sig)
2 (pp_condecls condecls $$ pp_derivings)
where
pp_sig = case mb_sig of
Nothing -> empty
Just kind -> dcolon <+> ppr kind
pp_derivings = case derivings of
Nothing -> empty
Just (L _ ds) -> hsep [ptext (sLit "deriving"),
parens (interpp'SP ds)]
instance OutputableBndr name => Outputable (HsDataDefn name) where
ppr d = pp_data_defn (\_ -> ptext (sLit "Naked HsDataDefn")) d
instance Outputable NewOrData where
ppr NewType = ptext (sLit "newtype")
ppr DataType = ptext (sLit "data")
pp_condecls :: OutputableBndr name => [LConDecl name] -> SDoc
pp_condecls cs@(L _ ConDecl{ con_res = ResTyGADT _ _ } : _) -- In GADT syntax
= hang (ptext (sLit "where")) 2 (vcat (map ppr cs))
pp_condecls cs -- In H98 syntax
= equals <+> sep (punctuate (ptext (sLit " |")) (map ppr cs))
instance (OutputableBndr name) => Outputable (ConDecl name) where
ppr = pprConDecl
pprConDecl :: OutputableBndr name => ConDecl name -> SDoc
pprConDecl (ConDecl { con_names = cons, con_explicit = expl, con_qvars = tvs
, con_cxt = cxt, con_details = details
, con_res = ResTyH98, con_doc = doc })
= sep [ppr_mbDoc doc, pprHsForAll expl tvs cxt, ppr_details details]
where
ppr_details (InfixCon t1 t2) = hsep [ppr t1, pprInfixOcc cons, ppr t2]
ppr_details (PrefixCon tys) = hsep (pprPrefixOcc cons
: map (pprParendHsType . unLoc) tys)
ppr_details (RecCon fields) = ppr_con_names cons
<+> pprConDeclFields (unLoc fields)
pprConDecl (ConDecl { con_names = cons, con_explicit = expl, con_qvars = tvs
, con_cxt = cxt, con_details = PrefixCon arg_tys
, con_res = ResTyGADT _ res_ty })
= ppr_con_names cons <+> dcolon <+>
sep [pprHsForAll expl tvs cxt, ppr (foldr mk_fun_ty res_ty arg_tys)]
where
mk_fun_ty a b = noLoc (HsFunTy a b)
pprConDecl (ConDecl { con_names = cons, con_explicit = expl, con_qvars = tvs
, con_cxt = cxt, con_details = RecCon fields
, con_res = ResTyGADT _ res_ty })
= sep [ppr_con_names cons <+> dcolon <+> pprHsForAll expl tvs cxt,
pprConDeclFields (unLoc fields) <+> arrow <+> ppr res_ty]
pprConDecl decl@(ConDecl { con_details = InfixCon ty1 ty2, con_res = ResTyGADT {} })
= pprConDecl (decl { con_details = PrefixCon [ty1,ty2] })
-- In GADT syntax we don't allow infix constructors
-- so if we ever trip over one (albeit I can't see how that
-- can happen) print it like a prefix one
ppr_con_names :: (OutputableBndr name) => [Located name] -> SDoc
ppr_con_names [x] = ppr x
ppr_con_names xs = interpp'SP xs
instance (Outputable name) => OutputableBndr [Located name] where
pprBndr _bs xs = cat $ punctuate comma (map ppr xs)
pprPrefixOcc [x] = ppr x
pprPrefixOcc xs = cat $ punctuate comma (map ppr xs)
pprInfixOcc [x] = ppr x
pprInfixOcc xs = cat $ punctuate comma (map ppr xs)
{-
************************************************************************
* *
Instance declarations
* *
************************************************************************
Note [Type family instance declarations in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The data type TyFamEqn represents one equation of a type family instance.
It is parameterised over its tfe_pats field:
* An ordinary type family instance declaration looks like this in source Haskell
type instance T [a] Int = a -> a
(or something similar for a closed family)
It is represented by a TyFamInstEqn, with *type* in the tfe_pats field.
* On the other hand, the *default instance* of an associated type looksl like
this in source Haskell
class C a where
type T a b
type T a b = a -> b -- The default instance
It is represented by a TyFamDefltEqn, with *type variables8 in the tfe_pats field.
-}
----------------- Type synonym family instances -------------
type LTyFamInstEqn name = Located (TyFamInstEqn name)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi'
-- when in a list
-- For details on above see note [Api annotations] in ApiAnnotation
type LTyFamDefltEqn name = Located (TyFamDefltEqn name)
type HsTyPats name = HsWithBndrs name [LHsType name]
-- ^ Type patterns (with kind and type bndrs)
-- See Note [Family instance declaration binders]
type TyFamInstEqn name = TyFamEqn name (HsTyPats name)
type TyFamDefltEqn name = TyFamEqn name (LHsTyVarBndrs name)
-- See Note [Type family instance declarations in HsSyn]
-- | One equation in a type family instance declaration
-- See Note [Type family instance declarations in HsSyn]
data TyFamEqn name pats
= TyFamEqn
{ tfe_tycon :: Located name
, tfe_pats :: pats
, tfe_rhs :: LHsType name }
-- ^
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving( Typeable )
deriving instance (DataId name, Data pats) => Data (TyFamEqn name pats)
type LTyFamInstDecl name = Located (TyFamInstDecl name)
data TyFamInstDecl name
= TyFamInstDecl
{ tfid_eqn :: LTyFamInstEqn name
, tfid_fvs :: PostRn name NameSet }
-- ^
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
-- 'ApiAnnotation.AnnInstance',
-- For details on above see note [Api annotations] in ApiAnnotation
deriving( Typeable )
deriving instance (DataId name) => Data (TyFamInstDecl name)
----------------- Data family instances -------------
type LDataFamInstDecl name = Located (DataFamInstDecl name)
data DataFamInstDecl name
= DataFamInstDecl
{ dfid_tycon :: Located name
, dfid_pats :: HsTyPats name -- LHS
, dfid_defn :: HsDataDefn name -- RHS
, dfid_fvs :: PostRn name NameSet } -- Free vars for
-- dependency analysis
-- ^
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnData',
-- 'ApiAnnotation.AnnNewType','ApiAnnotation.AnnInstance',
-- 'ApiAnnotation.AnnDcolon'
-- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving( Typeable )
deriving instance (DataId name) => Data (DataFamInstDecl name)
----------------- Class instances -------------
type LClsInstDecl name = Located (ClsInstDecl name)
data ClsInstDecl name
= ClsInstDecl
{ cid_poly_ty :: LHsType name -- Context => Class Instance-type
-- Using a polytype means that the renamer conveniently
-- figures out the quantified type variables for us.
, cid_binds :: LHsBinds name -- Class methods
, cid_sigs :: [LSig name] -- User-supplied pragmatic info
, cid_tyfam_insts :: [LTyFamInstDecl name] -- Type family instances
, cid_datafam_insts :: [LDataFamInstDecl name] -- Data family instances
, cid_overlap_mode :: Maybe (Located OverlapMode)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
}
-- ^
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnInstance',
-- 'ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId id) => Data (ClsInstDecl id)
----------------- Instances of all kinds -------------
type LInstDecl name = Located (InstDecl name)
data InstDecl name -- Both class and family instances
= ClsInstD
{ cid_inst :: ClsInstDecl name }
| DataFamInstD -- data family instance
{ dfid_inst :: DataFamInstDecl name }
| TyFamInstD -- type family instance
{ tfid_inst :: TyFamInstDecl name }
deriving (Typeable)
deriving instance (DataId id) => Data (InstDecl id)
{-
Note [Family instance declaration binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A {Ty|Data}FamInstDecl is a data/type family instance declaration
the pats field is LHS patterns, and the tvs of the HsBSig
tvs are fv(pat_tys), *including* ones that are already in scope
Eg class C s t where
type F t p :: *
instance C w (a,b) where
type F (a,b) x = x->a
The tcdTyVars of the F decl are {a,b,x}, even though the F decl
is nested inside the 'instance' decl.
However after the renamer, the uniques will match up:
instance C w7 (a8,b9) where
type F (a8,b9) x10 = x10->a8
so that we can compare the type patter in the 'instance' decl and
in the associated 'type' decl
-}
instance (OutputableBndr name) => Outputable (TyFamInstDecl name) where
ppr = pprTyFamInstDecl TopLevel
pprTyFamInstDecl :: OutputableBndr name => TopLevelFlag -> TyFamInstDecl name -> SDoc
pprTyFamInstDecl top_lvl (TyFamInstDecl { tfid_eqn = eqn })
= ptext (sLit "type") <+> ppr_instance_keyword top_lvl <+> ppr_fam_inst_eqn eqn
ppr_instance_keyword :: TopLevelFlag -> SDoc
ppr_instance_keyword TopLevel = ptext (sLit "instance")
ppr_instance_keyword NotTopLevel = empty
ppr_fam_inst_eqn :: OutputableBndr name => LTyFamInstEqn name -> SDoc
ppr_fam_inst_eqn (L _ (TyFamEqn { tfe_tycon = tycon
, tfe_pats = pats
, tfe_rhs = rhs }))
= pp_fam_inst_lhs tycon pats [] <+> equals <+> ppr rhs
ppr_fam_deflt_eqn :: OutputableBndr name => LTyFamDefltEqn name -> SDoc
ppr_fam_deflt_eqn (L _ (TyFamEqn { tfe_tycon = tycon
, tfe_pats = tvs
, tfe_rhs = rhs }))
= pp_vanilla_decl_head tycon tvs [] <+> equals <+> ppr rhs
instance (OutputableBndr name) => Outputable (DataFamInstDecl name) where
ppr = pprDataFamInstDecl TopLevel
pprDataFamInstDecl :: OutputableBndr name => TopLevelFlag -> DataFamInstDecl name -> SDoc
pprDataFamInstDecl top_lvl (DataFamInstDecl { dfid_tycon = tycon
, dfid_pats = pats
, dfid_defn = defn })
= pp_data_defn pp_hdr defn
where
pp_hdr ctxt = ppr_instance_keyword top_lvl <+> pp_fam_inst_lhs tycon pats ctxt
pprDataFamInstFlavour :: DataFamInstDecl name -> SDoc
pprDataFamInstFlavour (DataFamInstDecl { dfid_defn = (HsDataDefn { dd_ND = nd }) })
= ppr nd
instance (OutputableBndr name) => Outputable (ClsInstDecl name) where
ppr (ClsInstDecl { cid_poly_ty = inst_ty, cid_binds = binds
, cid_sigs = sigs, cid_tyfam_insts = ats
, cid_overlap_mode = mbOverlap
, cid_datafam_insts = adts })
| null sigs, null ats, null adts, isEmptyBag binds -- No "where" part
= top_matter
| otherwise -- Laid out
= vcat [ top_matter <+> ptext (sLit "where")
, nest 2 $ pprDeclList $
map (pprTyFamInstDecl NotTopLevel . unLoc) ats ++
map (pprDataFamInstDecl NotTopLevel . unLoc) adts ++
pprLHsBindsForUser binds sigs ]
where
top_matter = ptext (sLit "instance") <+> ppOverlapPragma mbOverlap
<+> ppr inst_ty
ppOverlapPragma :: Maybe (Located OverlapMode) -> SDoc
ppOverlapPragma mb =
case mb of
Nothing -> empty
Just (L _ (NoOverlap _)) -> ptext (sLit "{-# NO_OVERLAP #-}")
Just (L _ (Overlappable _)) -> ptext (sLit "{-# OVERLAPPABLE #-}")
Just (L _ (Overlapping _)) -> ptext (sLit "{-# OVERLAPPING #-}")
Just (L _ (Overlaps _)) -> ptext (sLit "{-# OVERLAPS #-}")
Just (L _ (Incoherent _)) -> ptext (sLit "{-# INCOHERENT #-}")
instance (OutputableBndr name) => Outputable (InstDecl name) where
ppr (ClsInstD { cid_inst = decl }) = ppr decl
ppr (TyFamInstD { tfid_inst = decl }) = ppr decl
ppr (DataFamInstD { dfid_inst = decl }) = ppr decl
-- Extract the declarations of associated data types from an instance
instDeclDataFamInsts :: [LInstDecl name] -> [DataFamInstDecl name]
instDeclDataFamInsts inst_decls
= concatMap do_one inst_decls
where
do_one (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fam_insts } }))
= map unLoc fam_insts
do_one (L _ (DataFamInstD { dfid_inst = fam_inst })) = [fam_inst]
do_one (L _ (TyFamInstD {})) = []
{-
************************************************************************
* *
\subsection[DerivDecl]{A stand-alone instance deriving declaration}
* *
************************************************************************
-}
type LDerivDecl name = Located (DerivDecl name)
data DerivDecl name = DerivDecl
{ deriv_type :: LHsType name
, deriv_overlap_mode :: Maybe (Located OverlapMode)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose',
-- 'ApiAnnotation.AnnDeriving',
-- 'ApiAnnotation.AnnInstance'
-- For details on above see note [Api annotations] in ApiAnnotation
}
deriving (Typeable)
deriving instance (DataId name) => Data (DerivDecl name)
instance (OutputableBndr name) => Outputable (DerivDecl name) where
ppr (DerivDecl ty o)
= hsep [ptext (sLit "deriving instance"), ppOverlapPragma o, ppr ty]
{-
************************************************************************
* *
\subsection[DefaultDecl]{A @default@ declaration}
* *
************************************************************************
There can only be one default declaration per module, but it is hard
for the parser to check that; we pass them all through in the abstract
syntax, and that restriction must be checked in the front end.
-}
type LDefaultDecl name = Located (DefaultDecl name)
data DefaultDecl name
= DefaultDecl [LHsType name]
-- ^ - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnDefault',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId name) => Data (DefaultDecl name)
instance (OutputableBndr name)
=> Outputable (DefaultDecl name) where
ppr (DefaultDecl tys)
= ptext (sLit "default") <+> parens (interpp'SP tys)
{-
************************************************************************
* *
\subsection{Foreign function interface declaration}
* *
************************************************************************
-}
-- foreign declarations are distinguished as to whether they define or use a
-- Haskell name
--
-- * the Boolean value indicates whether the pre-standard deprecated syntax
-- has been used
--
type LForeignDecl name = Located (ForeignDecl name)
data ForeignDecl name
= ForeignImport (Located name) -- defines this name
(LHsType name) -- sig_ty
(PostTc name Coercion) -- rep_ty ~ sig_ty
ForeignImport
| ForeignExport (Located name) -- uses this name
(LHsType name) -- sig_ty
(PostTc name Coercion) -- sig_ty ~ rep_ty
ForeignExport
-- ^
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForeign',
-- 'ApiAnnotation.AnnImport','ApiAnnotation.AnnExport',
-- 'ApiAnnotation.AnnDcolon'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId name) => Data (ForeignDecl name)
{-
In both ForeignImport and ForeignExport:
sig_ty is the type given in the Haskell code
rep_ty is the representation for this type, i.e. with newtypes
coerced away and type functions evaluated.
Thus if the declaration is valid, then rep_ty will only use types
such as Int and IO that we know how to make foreign calls with.
-}
noForeignImportCoercionYet :: PlaceHolder
noForeignImportCoercionYet = PlaceHolder
noForeignExportCoercionYet :: PlaceHolder
noForeignExportCoercionYet = PlaceHolder
-- Specification Of an imported external entity in dependence on the calling
-- convention
--
data ForeignImport = -- import of a C entity
--
-- * the two strings specifying a header file or library
-- may be empty, which indicates the absence of a
-- header or object specification (both are not used
-- in the case of `CWrapper' and when `CFunction'
-- has a dynamic target)
--
-- * the calling convention is irrelevant for code
-- generation in the case of `CLabel', but is needed
-- for pretty printing
--
-- * `Safety' is irrelevant for `CLabel' and `CWrapper'
--
CImport (Located CCallConv) -- ccall or stdcall
(Located Safety) -- interruptible, safe or unsafe
(Maybe Header) -- name of C header
CImportSpec -- details of the C entity
(Located SourceText) -- original source text for
-- the C entity
deriving (Data, Typeable)
-- details of an external C entity
--
data CImportSpec = CLabel CLabelString -- import address of a C label
| CFunction CCallTarget -- static or dynamic function
| CWrapper -- wrapper to expose closures
-- (former f.e.d.)
deriving (Data, Typeable)
-- specification of an externally exported entity in dependence on the calling
-- convention
--
data ForeignExport = CExport (Located CExportSpec) -- contains the calling
-- convention
(Located SourceText) -- original source text for
-- the C entity
deriving (Data, Typeable)
-- pretty printing of foreign declarations
--
instance OutputableBndr name => Outputable (ForeignDecl name) where
ppr (ForeignImport n ty _ fimport) =
hang (ptext (sLit "foreign import") <+> ppr fimport <+> ppr n)
2 (dcolon <+> ppr ty)
ppr (ForeignExport n ty _ fexport) =
hang (ptext (sLit "foreign export") <+> ppr fexport <+> ppr n)
2 (dcolon <+> ppr ty)
instance Outputable ForeignImport where
ppr (CImport cconv safety mHeader spec _) =
ppr cconv <+> ppr safety <+>
char '"' <> pprCEntity spec <> char '"'
where
pp_hdr = case mHeader of
Nothing -> empty
Just (Header header) -> ftext header
pprCEntity (CLabel lbl) =
ptext (sLit "static") <+> pp_hdr <+> char '&' <> ppr lbl
pprCEntity (CFunction (StaticTarget lbl _ isFun)) =
ptext (sLit "static")
<+> pp_hdr
<+> (if isFun then empty else ptext (sLit "value"))
<+> ppr lbl
pprCEntity (CFunction (DynamicTarget)) =
ptext (sLit "dynamic")
pprCEntity (CWrapper) = ptext (sLit "wrapper")
instance Outputable ForeignExport where
ppr (CExport (L _ (CExportStatic lbl cconv)) _) =
ppr cconv <+> char '"' <> ppr lbl <> char '"'
{-
************************************************************************
* *
\subsection{Transformation rules}
* *
************************************************************************
-}
type LRuleDecls name = Located (RuleDecls name)
-- Note [Pragma source text] in BasicTypes
data RuleDecls name = HsRules { rds_src :: SourceText
, rds_rules :: [LRuleDecl name] }
deriving (Typeable)
deriving instance (DataId name) => Data (RuleDecls name)
type LRuleDecl name = Located (RuleDecl name)
data RuleDecl name
= HsRule -- Source rule
(Located RuleName) -- Rule name
Activation
[LRuleBndr name] -- Forall'd vars; after typechecking this
-- includes tyvars
(Located (HsExpr name)) -- LHS
(PostRn name NameSet) -- Free-vars from the LHS
(Located (HsExpr name)) -- RHS
(PostRn name NameSet) -- Free-vars from the RHS
-- ^
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnTilde',
-- 'ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnClose',
-- 'ApiAnnotation.AnnForall','ApiAnnotation.AnnDot',
-- 'ApiAnnotation.AnnEqual',
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId name) => Data (RuleDecl name)
flattenRuleDecls :: [LRuleDecls name] -> [LRuleDecl name]
flattenRuleDecls decls = concatMap (rds_rules . unLoc) decls
type LRuleBndr name = Located (RuleBndr name)
data RuleBndr name
= RuleBndr (Located name)
| RuleBndrSig (Located name) (HsWithBndrs name (LHsType name))
-- ^
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId name) => Data (RuleBndr name)
collectRuleBndrSigTys :: [RuleBndr name] -> [HsWithBndrs name (LHsType name)]
collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ ty <- bndrs]
instance OutputableBndr name => Outputable (RuleDecls name) where
ppr (HsRules _ rules) = ppr rules
instance OutputableBndr name => Outputable (RuleDecl name) where
ppr (HsRule name act ns lhs _fv_lhs rhs _fv_rhs)
= sep [text "{-# RULES" <+> doubleQuotes (ftext $ unLoc name)
<+> ppr act,
nest 4 (pp_forall <+> pprExpr (unLoc lhs)),
nest 4 (equals <+> pprExpr (unLoc rhs) <+> text "#-}") ]
where
pp_forall | null ns = empty
| otherwise = forAllLit <+> fsep (map ppr ns) <> dot
instance OutputableBndr name => Outputable (RuleBndr name) where
ppr (RuleBndr name) = ppr name
ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
{-
************************************************************************
* *
\subsection{Vectorisation declarations}
* *
************************************************************************
A vectorisation pragma, one of
{-# VECTORISE f = closure1 g (scalar_map g) #-}
{-# VECTORISE SCALAR f #-}
{-# NOVECTORISE f #-}
{-# VECTORISE type T = ty #-}
{-# VECTORISE SCALAR type T #-}
-}
type LVectDecl name = Located (VectDecl name)
data VectDecl name
= HsVect
SourceText -- Note [Pragma source text] in BasicTypes
(Located name)
(LHsExpr name)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsNoVect
SourceText -- Note [Pragma source text] in BasicTypes
(Located name)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsVectTypeIn -- pre type-checking
SourceText -- Note [Pragma source text] in BasicTypes
Bool -- 'TRUE' => SCALAR declaration
(Located name)
(Maybe (Located name)) -- 'Nothing' => no right-hand side
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnType','ApiAnnotation.AnnClose',
-- 'ApiAnnotation.AnnEqual'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsVectTypeOut -- post type-checking
Bool -- 'TRUE' => SCALAR declaration
TyCon
(Maybe TyCon) -- 'Nothing' => no right-hand side
| HsVectClassIn -- pre type-checking
SourceText -- Note [Pragma source text] in BasicTypes
(Located name)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClass','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsVectClassOut -- post type-checking
Class
| HsVectInstIn -- pre type-checking (always SCALAR) !!!FIXME: should be superfluous now
(LHsType name)
| HsVectInstOut -- post type-checking (always SCALAR) !!!FIXME: should be superfluous now
ClsInst
deriving (Typeable)
deriving instance (DataId name) => Data (VectDecl name)
lvectDeclName :: NamedThing name => LVectDecl name -> Name
lvectDeclName (L _ (HsVect _ (L _ name) _)) = getName name
lvectDeclName (L _ (HsNoVect _ (L _ name))) = getName name
lvectDeclName (L _ (HsVectTypeIn _ _ (L _ name) _)) = getName name
lvectDeclName (L _ (HsVectTypeOut _ tycon _)) = getName tycon
lvectDeclName (L _ (HsVectClassIn _ (L _ name))) = getName name
lvectDeclName (L _ (HsVectClassOut cls)) = getName cls
lvectDeclName (L _ (HsVectInstIn _))
= panic "HsDecls.lvectDeclName: HsVectInstIn"
lvectDeclName (L _ (HsVectInstOut _))
= panic "HsDecls.lvectDeclName: HsVectInstOut"
lvectInstDecl :: LVectDecl name -> Bool
lvectInstDecl (L _ (HsVectInstIn _)) = True
lvectInstDecl (L _ (HsVectInstOut _)) = True
lvectInstDecl _ = False
instance OutputableBndr name => Outputable (VectDecl name) where
ppr (HsVect _ v rhs)
= sep [text "{-# VECTORISE" <+> ppr v,
nest 4 $
pprExpr (unLoc rhs) <+> text "#-}" ]
ppr (HsNoVect _ v)
= sep [text "{-# NOVECTORISE" <+> ppr v <+> text "#-}" ]
ppr (HsVectTypeIn _ False t Nothing)
= sep [text "{-# VECTORISE type" <+> ppr t <+> text "#-}" ]
ppr (HsVectTypeIn _ False t (Just t'))
= sep [text "{-# VECTORISE type" <+> ppr t, text "=", ppr t', text "#-}" ]
ppr (HsVectTypeIn _ True t Nothing)
= sep [text "{-# VECTORISE SCALAR type" <+> ppr t <+> text "#-}" ]
ppr (HsVectTypeIn _ True t (Just t'))
= sep [text "{-# VECTORISE SCALAR type" <+> ppr t, text "=", ppr t', text "#-}" ]
ppr (HsVectTypeOut False t Nothing)
= sep [text "{-# VECTORISE type" <+> ppr t <+> text "#-}" ]
ppr (HsVectTypeOut False t (Just t'))
= sep [text "{-# VECTORISE type" <+> ppr t, text "=", ppr t', text "#-}" ]
ppr (HsVectTypeOut True t Nothing)
= sep [text "{-# VECTORISE SCALAR type" <+> ppr t <+> text "#-}" ]
ppr (HsVectTypeOut True t (Just t'))
= sep [text "{-# VECTORISE SCALAR type" <+> ppr t, text "=", ppr t', text "#-}" ]
ppr (HsVectClassIn _ c)
= sep [text "{-# VECTORISE class" <+> ppr c <+> text "#-}" ]
ppr (HsVectClassOut c)
= sep [text "{-# VECTORISE class" <+> ppr c <+> text "#-}" ]
ppr (HsVectInstIn ty)
= sep [text "{-# VECTORISE SCALAR instance" <+> ppr ty <+> text "#-}" ]
ppr (HsVectInstOut i)
= sep [text "{-# VECTORISE SCALAR instance" <+> ppr i <+> text "#-}" ]
{-
************************************************************************
* *
\subsection[DocDecl]{Document comments}
* *
************************************************************************
-}
type LDocDecl = Located (DocDecl)
data DocDecl
= DocCommentNext HsDocString
| DocCommentPrev HsDocString
| DocCommentNamed String HsDocString
| DocGroup Int HsDocString
deriving (Data, Typeable)
-- Okay, I need to reconstruct the document comments, but for now:
instance Outputable DocDecl where
ppr _ = text "<document comment>"
docDeclDoc :: DocDecl -> HsDocString
docDeclDoc (DocCommentNext d) = d
docDeclDoc (DocCommentPrev d) = d
docDeclDoc (DocCommentNamed _ d) = d
docDeclDoc (DocGroup _ d) = d
{-
************************************************************************
* *
\subsection[DeprecDecl]{Deprecations}
* *
************************************************************************
We use exported entities for things to deprecate.
-}
type LWarnDecls name = Located (WarnDecls name)
-- Note [Pragma source text] in BasicTypes
data WarnDecls name = Warnings { wd_src :: SourceText
, wd_warnings :: [LWarnDecl name]
}
deriving (Data, Typeable)
type LWarnDecl name = Located (WarnDecl name)
data WarnDecl name = Warning [Located name] WarningTxt
deriving (Data, Typeable)
instance OutputableBndr name => Outputable (WarnDecls name) where
ppr (Warnings _ decls) = ppr decls
instance OutputableBndr name => Outputable (WarnDecl name) where
ppr (Warning thing txt)
= hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
{-
************************************************************************
* *
\subsection[AnnDecl]{Annotations}
* *
************************************************************************
-}
type LAnnDecl name = Located (AnnDecl name)
data AnnDecl name = HsAnnotation
SourceText -- Note [Pragma source text] in BasicTypes
(AnnProvenance name) (Located (HsExpr name))
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnType'
-- 'ApiAnnotation.AnnModule'
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Typeable)
deriving instance (DataId name) => Data (AnnDecl name)
instance (OutputableBndr name) => Outputable (AnnDecl name) where
ppr (HsAnnotation _ provenance expr)
= hsep [text "{-#", pprAnnProvenance provenance, pprExpr (unLoc expr), text "#-}"]
data AnnProvenance name = ValueAnnProvenance (Located name)
| TypeAnnProvenance (Located name)
| ModuleAnnProvenance
deriving (Data, Typeable, Functor)
deriving instance Foldable AnnProvenance
deriving instance Traversable AnnProvenance
annProvenanceName_maybe :: AnnProvenance name -> Maybe name
annProvenanceName_maybe (ValueAnnProvenance (L _ name)) = Just name
annProvenanceName_maybe (TypeAnnProvenance (L _ name)) = Just name
annProvenanceName_maybe ModuleAnnProvenance = Nothing
pprAnnProvenance :: OutputableBndr name => AnnProvenance name -> SDoc
pprAnnProvenance ModuleAnnProvenance = ptext (sLit "ANN module")
pprAnnProvenance (ValueAnnProvenance (L _ name))
= ptext (sLit "ANN") <+> ppr name
pprAnnProvenance (TypeAnnProvenance (L _ name))
= ptext (sLit "ANN type") <+> ppr name
{-
************************************************************************
* *
\subsection[RoleAnnot]{Role annotations}
* *
************************************************************************
-}
type LRoleAnnotDecl name = Located (RoleAnnotDecl name)
-- See #8185 for more info about why role annotations are
-- top-level declarations
data RoleAnnotDecl name
= RoleAnnotDecl (Located name) -- type constructor
[Located (Maybe Role)] -- optional annotations
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
-- 'ApiAnnotation.AnnRole'
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Data, Typeable)
instance OutputableBndr name => Outputable (RoleAnnotDecl name) where
ppr (RoleAnnotDecl ltycon roles)
= ptext (sLit "type role") <+> ppr ltycon <+>
hsep (map (pp_role . unLoc) roles)
where
pp_role Nothing = underscore
pp_role (Just r) = ppr r
roleAnnotDeclName :: RoleAnnotDecl name -> name
roleAnnotDeclName (RoleAnnotDecl (L _ name) _) = name
|
fmthoma/ghc
|
compiler/hsSyn/HsDecls.hs
|
bsd-3-clause
| 70,357 | 4 | 17 | 21,025 | 12,156 | 6,609 | 5,547 | 872 | 6 |
{-# LANGUAGE CPP #-}
-- | Handy functions for creating much Core syntax
module ETA.Core.MkCore (
-- * Constructing normal syntax
mkCoreLet, mkCoreLets,
mkCoreApp, mkCoreApps, mkCoreConApps,
mkCoreLams, mkWildCase, mkIfThenElse,
mkWildValBinder, mkWildEvBinder,
sortQuantVars, castBottomExpr,
-- * Constructing boxed literals
mkWordExpr, mkWordExprWord,
mkIntExpr, mkIntExprInt,
mkIntegerExpr,
mkFloatExpr, mkDoubleExpr,
mkCharExpr, mkStringExpr, mkStringExprFS,
-- * Floats
FloatBind(..), wrapFloat,
-- * Constructing equality evidence boxes
mkEqBox,
-- * Constructing general big tuples
-- $big_tuples
mkChunkified,
-- * Constructing small tuples
mkCoreVarTup, mkCoreVarTupTy, mkCoreTup,
-- * Constructing big tuples
mkBigCoreVarTup, mkBigCoreVarTupTy,
mkBigCoreTup, mkBigCoreTupTy,
-- * Deconstructing small tuples
mkSmallTupleSelector, mkSmallTupleCase,
-- * Deconstructing big tuples
mkTupleSelector, mkTupleCase,
-- * Constructing list expressions
mkNilExpr, mkConsExpr, mkListExpr,
mkFoldrExpr, mkBuildExpr,
-- * Error Ids
mkRuntimeErrorApp, mkImpossibleExpr, errorIds,
rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
pAT_ERROR_ID, eRROR_ID, rEC_SEL_ERROR_ID, aBSENT_ERROR_ID,
uNDEFINED_ID, undefinedName
) where
#include "HsVersions.h"
import ETA.BasicTypes.Id
import ETA.BasicTypes.Var ( EvVar, setTyVarUnique )
import ETA.Core.CoreSyn
import ETA.Core.CoreUtils ( exprType, needsCaseBinding, bindNonRec )
import ETA.BasicTypes.Literal
import ETA.Main.HscTypes
import ETA.Prelude.TysWiredIn
import ETA.Prelude.PrelNames
import ETA.TypeCheck.TcType ( mkSigmaTy )
import ETA.Types.Type
import ETA.Types.Coercion
import ETA.Prelude.TysPrim
import ETA.BasicTypes.DataCon ( DataCon, dataConWorkId )
import ETA.BasicTypes.IdInfo ( vanillaIdInfo, setStrictnessInfo,
setArityInfo )
import ETA.BasicTypes.Demand
import ETA.BasicTypes.Name hiding ( varName )
import ETA.Utils.Outputable
import ETA.Utils.FastString
import ETA.BasicTypes.UniqSupply
import ETA.BasicTypes.BasicTypes
import ETA.Utils.Util
import ETA.Utils.Pair
import ETA.Main.Constants
import ETA.Main.DynFlags
import Data.Char ( ord )
import Data.List
import Data.Ord
#if __GLASGOW_HASKELL__ < 709
import Data.Word ( Word )
#endif
infixl 4 `mkCoreApp`, `mkCoreApps`
{-
************************************************************************
* *
\subsection{Basic CoreSyn construction}
* *
************************************************************************
-}
sortQuantVars :: [Var] -> [Var]
-- Sort the variables (KindVars, TypeVars, and Ids)
-- into order: Kind, then Type, then Id
sortQuantVars = sortBy (comparing withCategory)
where
withCategory v = (category v, v)
category :: Var -> Int
category v
| isKindVar v = 1
| isTyVar v = 2
| otherwise = 3
-- | Bind a binding group over an expression, using a @let@ or @case@ as
-- appropriate (see "CoreSyn#let_app_invariant")
mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
mkCoreLet (NonRec bndr rhs) body -- See Note [CoreSyn let/app invariant]
| needsCaseBinding (idType bndr) rhs
= Case rhs bndr (exprType body) [(DEFAULT,[],body)]
mkCoreLet bind body
= Let bind body
-- | Bind a list of binding groups over an expression. The leftmost binding
-- group becomes the outermost group in the resulting expression
mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets binds body = foldr mkCoreLet body binds
-- | Construct an expression which represents the application of one expression
-- to the other
mkCoreApp :: CoreExpr -> CoreExpr -> CoreExpr
-- Respects the let/app invariant by building a case expression where necessary
-- See CoreSyn Note [CoreSyn let/app invariant]
mkCoreApp fun (Type ty) = App fun (Type ty)
mkCoreApp fun (Coercion co) = App fun (Coercion co)
mkCoreApp fun arg = ASSERT2( isFunTy fun_ty, ppr fun $$ ppr arg )
mk_val_app fun arg arg_ty res_ty
where
fun_ty = exprType fun
(arg_ty, res_ty) = splitFunTy fun_ty
-- | Construct an expression which represents the application of a number of
-- expressions to another. The leftmost expression in the list is applied first
-- Respects the let/app invariant by building a case expression where necessary
-- See CoreSyn Note [CoreSyn let/app invariant]
mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
-- Slightly more efficient version of (foldl mkCoreApp)
mkCoreApps orig_fun orig_args
= go orig_fun (exprType orig_fun) orig_args
where
go fun _ [] = fun
go fun fun_ty (Type ty : args) = go (App fun (Type ty)) (applyTy fun_ty ty) args
go fun fun_ty (Coercion co : args) = go (App fun (Coercion co)) (applyCo fun_ty co) args
go fun fun_ty (arg : args) = ASSERT2( isFunTy fun_ty, ppr fun_ty $$ ppr orig_fun
$$ ppr orig_args )
go (mk_val_app fun arg arg_ty res_ty) res_ty args
where
(arg_ty, res_ty) = splitFunTy fun_ty
-- | Construct an expression which represents the application of a number of
-- expressions to that of a data constructor expression. The leftmost expression
-- in the list is applied first
mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps con args = mkCoreApps (Var (dataConWorkId con)) args
mk_val_app :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
-- Build an application (e1 e2),
-- or a strict binding (case e2 of x -> e1 x)
-- using the latter when necessary to respect the let/app invariant
-- See Note [CoreSyn let/app invariant]
mk_val_app fun arg arg_ty res_ty
| not (needsCaseBinding arg_ty arg)
= App fun arg -- The vastly common case
| otherwise
= Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
where
arg_id = mkWildValBinder arg_ty
-- Lots of shadowing, but it doesn't matter,
-- because 'fun ' should not have a free wild-id
--
-- This is Dangerous. But this is the only place we play this
-- game, mk_val_app returns an expression that does not have
-- have a free wild-id. So the only thing that can go wrong
-- is if you take apart this case expression, and pass a
-- fragmet of it as the fun part of a 'mk_val_app'.
-----------
mkWildEvBinder :: PredType -> EvVar
mkWildEvBinder pred = mkWildValBinder pred
-- | Make a /wildcard binder/. This is typically used when you need a binder
-- that you expect to use only at a *binding* site. Do not use it at
-- occurrence sites because it has a single, fixed unique, and it's very
-- easy to get into difficulties with shadowing. That's why it is used so little.
-- See Note [WildCard binders] in SimplEnv
mkWildValBinder :: Type -> Id
mkWildValBinder ty = mkLocalId wildCardName ty
mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
-- Make a case expression whose case binder is unused
-- The alts should not have any occurrences of WildId
mkWildCase scrut scrut_ty res_ty alts
= Case scrut (mkWildValBinder scrut_ty) res_ty alts
mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
mkIfThenElse guard then_expr else_expr
-- Not going to be refining, so okay to take the type of the "then" clause
= mkWildCase guard boolTy (exprType then_expr)
[ (DataAlt falseDataCon, [], else_expr), -- Increasing order of tag!
(DataAlt trueDataCon, [], then_expr) ]
castBottomExpr :: CoreExpr -> Type -> CoreExpr
-- (castBottomExpr e ty), assuming that 'e' diverges,
-- return an expression of type 'ty'
-- See Note [Empty case alternatives] in CoreSyn
castBottomExpr e res_ty
| e_ty `eqType` res_ty = e
| otherwise = Case e (mkWildValBinder e_ty) res_ty []
where
e_ty = exprType e
{-
The functions from this point don't really do anything cleverer than
their counterparts in CoreSyn, but they are here for consistency
-}
-- | Create a lambda where the given expression has a number of variables
-- bound over it. The leftmost binder is that bound by the outermost
-- lambda in the result
mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
mkCoreLams = mkLams
{-
************************************************************************
* *
\subsection{Making literals}
* *
************************************************************************
-}
-- | Create a 'CoreExpr' which will evaluate to the given @Int@
mkIntExpr :: DynFlags -> Integer -> CoreExpr -- Result = I# i :: Int
mkIntExpr dflags i = mkConApp intDataCon [mkIntLit dflags i]
-- | Create a 'CoreExpr' which will evaluate to the given @Int@
mkIntExprInt :: DynFlags -> Int -> CoreExpr -- Result = I# i :: Int
mkIntExprInt dflags i = mkConApp intDataCon [mkIntLitInt dflags i]
-- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
mkWordExpr :: DynFlags -> Integer -> CoreExpr
mkWordExpr dflags w = mkConApp wordDataCon [mkWordLit dflags w]
-- | Create a 'CoreExpr' which will evaluate to the given @Word@
mkWordExprWord :: DynFlags -> Word -> CoreExpr
mkWordExprWord dflags w = mkConApp wordDataCon [mkWordLitWord dflags w]
-- | Create a 'CoreExpr' which will evaluate to the given @Integer@
mkIntegerExpr :: MonadThings m => Integer -> m CoreExpr -- Result :: Integer
mkIntegerExpr i = do t <- lookupTyCon integerTyConName
return (Lit (mkLitInteger i (mkTyConTy t)))
-- | Create a 'CoreExpr' which will evaluate to the given @Float@
mkFloatExpr :: Float -> CoreExpr
mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
-- | Create a 'CoreExpr' which will evaluate to the given @Double@
mkDoubleExpr :: Double -> CoreExpr
mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
-- | Create a 'CoreExpr' which will evaluate to the given @Char@
mkCharExpr :: Char -> CoreExpr -- Result = C# c :: Int
mkCharExpr c = mkConApp charDataCon [mkCharLit c]
-- | Create a 'CoreExpr' which will evaluate to the given @String@
mkStringExpr :: MonadThings m => String -> m CoreExpr -- Result :: String
-- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
mkStringExprFS :: MonadThings m => FastString -> m CoreExpr -- Result :: String
mkStringExpr str = mkStringExprFS (mkFastString str)
mkStringExprFS str
| nullFS str
= return (mkNilExpr charTy)
| all safeChar chars
= do unpack_id <- lookupId unpackCStringName
return (App (Var unpack_id) (Lit (MachStr (fastStringToByteString str))))
| otherwise
= do unpack_id <- lookupId unpackCStringUtf8Name
return (App (Var unpack_id) (Lit (MachStr (fastStringToByteString str))))
where
chars = unpackFS str
safeChar c = ord c >= 1 && ord c <= 0x7F
-- This take a ~# b (or a ~# R b) and returns a ~ b (or Coercible a b)
mkEqBox :: Coercion -> CoreExpr
mkEqBox co = ASSERT2( typeKind ty2 `eqKind` k, ppr co $$ ppr ty1 $$ ppr ty2 $$ ppr (typeKind ty1) $$ ppr (typeKind ty2) )
Var (dataConWorkId datacon) `mkTyApps` [k, ty1, ty2] `App` Coercion co
where (Pair ty1 ty2, role) = coercionKindRole co
k = typeKind ty1
datacon = case role of
Nominal -> eqBoxDataCon
Representational -> coercibleDataCon
Phantom -> pprPanic "mkEqBox does not support boxing phantom coercions"
(ppr co)
{-
************************************************************************
* *
\subsection{Tuple constructors}
* *
************************************************************************
-}
-- $big_tuples
-- #big_tuples#
--
-- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
-- we might concievably want to build such a massive tuple as part of the
-- output of a desugaring stage (notably that for list comprehensions).
--
-- We call tuples above this size \"big tuples\", and emulate them by
-- creating and pattern matching on >nested< tuples that are expressible
-- by GHC.
--
-- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
-- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
-- construction to be big.
--
-- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
-- and 'mkTupleCase' functions to do all your work with tuples you should be
-- fine, and not have to worry about the arity limitation at all.
-- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
-> [a] -- ^ Possible \"big\" list of things to construct from
-> a -- ^ Constructed thing made possible by recursive decomposition
mkChunkified small_tuple as = mk_big_tuple (chunkify as)
where
-- Each sub-list is short enough to fit in a tuple
mk_big_tuple [as] = small_tuple as
mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
chunkify :: [a] -> [[a]]
-- ^ Split a list into lists that are small enough to have a corresponding
-- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
-- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
chunkify xs
| n_xs <= mAX_TUPLE_SIZE = [xs]
| otherwise = split xs
where
n_xs = length xs
split [] = []
split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
{-
Creating tuples and their types for Core expressions
@mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.
* If it has only one element, it is the identity function.
* If there are more elements than a big tuple can have, it nests
the tuples.
-}
-- | Build a small tuple holding the specified variables
mkCoreVarTup :: [Id] -> CoreExpr
mkCoreVarTup ids = mkCoreTup (map Var ids)
-- | Bulid the type of a small tuple that holds the specified variables
mkCoreVarTupTy :: [Id] -> Type
mkCoreVarTupTy ids = mkBoxedTupleTy (map idType ids)
-- | Build a small tuple holding the specified expressions
mkCoreTup :: [CoreExpr] -> CoreExpr
mkCoreTup [] = Var unitDataConId
mkCoreTup [c] = c
mkCoreTup cs = mkConApp (tupleCon BoxedTuple (length cs))
(map (Type . exprType) cs ++ cs)
-- | Build a big tuple holding the specified variables
mkBigCoreVarTup :: [Id] -> CoreExpr
mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
-- | Build the type of a big tuple that holds the specified variables
mkBigCoreVarTupTy :: [Id] -> Type
mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
-- | Build a big tuple holding the specified expressions
mkBigCoreTup :: [CoreExpr] -> CoreExpr
mkBigCoreTup = mkChunkified mkCoreTup
-- | Build the type of a big tuple that holds the specified type of thing
mkBigCoreTupTy :: [Type] -> Type
mkBigCoreTupTy = mkChunkified mkBoxedTupleTy
{-
************************************************************************
* *
Floats
* *
************************************************************************
-}
data FloatBind
= FloatLet CoreBind
| FloatCase CoreExpr Id AltCon [Var]
-- case e of y { C ys -> ... }
-- See Note [Floating cases] in SetLevels
instance Outputable FloatBind where
ppr (FloatLet b) = ptext (sLit "LET") <+> ppr b
ppr (FloatCase e b c bs) = hang (ptext (sLit "CASE") <+> ppr e <+> ptext (sLit "of") <+> ppr b)
2 (ppr c <+> ppr bs)
wrapFloat :: FloatBind -> CoreExpr -> CoreExpr
wrapFloat (FloatLet defns) body = Let defns body
wrapFloat (FloatCase e b con bs) body = Case e b (exprType body) [(con, bs, body)]
{-
************************************************************************
* *
\subsection{Tuple destructors}
* *
************************************************************************
-}
-- | Builds a selector which scrutises the given
-- expression and extracts the one name from the list given.
-- If you want the no-shadowing rule to apply, the caller
-- is responsible for making sure that none of these names
-- are in scope.
--
-- If there is just one 'Id' in the tuple, then the selector is
-- just the identity.
--
-- If necessary, we pattern match on a \"big\" tuple.
mkTupleSelector :: [Id] -- ^ The 'Id's to pattern match the tuple against
-> Id -- ^ The 'Id' to select
-> Id -- ^ A variable of the same type as the scrutinee
-> CoreExpr -- ^ Scrutinee
-> CoreExpr -- ^ Selector expression
-- mkTupleSelector [a,b,c,d] b v e
-- = case e of v {
-- (p,q) -> case p of p {
-- (a,b) -> b }}
-- We use 'tpl' vars for the p,q, since shadowing does not matter.
--
-- In fact, it's more convenient to generate it innermost first, getting
--
-- case (case e of v
-- (p,q) -> p) of p
-- (a,b) -> b
mkTupleSelector vars the_var scrut_var scrut
= mk_tup_sel (chunkify vars) the_var
where
mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
mk_tup_sel (chunkify tpl_vs) tpl_v
where
tpl_tys = [mkBoxedTupleTy (map idType gp) | gp <- vars_s]
tpl_vs = mkTemplateLocals tpl_tys
[(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
the_var `elem` gp ]
-- | Like 'mkTupleSelector' but for tuples that are guaranteed
-- never to be \"big\".
--
-- > mkSmallTupleSelector [x] x v e = [| e |]
-- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
mkSmallTupleSelector :: [Id] -- The tuple args
-> Id -- The selected one
-> Id -- A variable of the same type as the scrutinee
-> CoreExpr -- Scrutinee
-> CoreExpr
mkSmallTupleSelector [var] should_be_the_same_var _ scrut
= ASSERT(var == should_be_the_same_var)
scrut
mkSmallTupleSelector vars the_var scrut_var scrut
= ASSERT( notNull vars )
Case scrut scrut_var (idType the_var)
[(DataAlt (tupleCon BoxedTuple (length vars)), vars, Var the_var)]
-- | A generalization of 'mkTupleSelector', allowing the body
-- of the case to be an arbitrary expression.
--
-- To avoid shadowing, we use uniques to invent new variables.
--
-- If necessary we pattern match on a \"big\" tuple.
mkTupleCase :: UniqSupply -- ^ For inventing names of intermediate variables
-> [Id] -- ^ The tuple identifiers to pattern match on
-> CoreExpr -- ^ Body of the case
-> Id -- ^ A variable of the same type as the scrutinee
-> CoreExpr -- ^ Scrutinee
-> CoreExpr
-- ToDo: eliminate cases where none of the variables are needed.
--
-- mkTupleCase uniqs [a,b,c,d] body v e
-- = case e of v { (p,q) ->
-- case p of p { (a,b) ->
-- case q of q { (c,d) ->
-- body }}}
mkTupleCase uniqs vars body scrut_var scrut
= mk_tuple_case uniqs (chunkify vars) body
where
-- This is the case where don't need any nesting
mk_tuple_case _ [vars] body
= mkSmallTupleCase vars body scrut_var scrut
-- This is the case where we must make nest tuples at least once
mk_tuple_case us vars_s body
= let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
in mk_tuple_case us' (chunkify vars') body'
one_tuple_case chunk_vars (us, vs, body)
= let (uniq, us') = takeUniqFromSupply us
scrut_var = mkSysLocal (fsLit "ds") uniq
(mkBoxedTupleTy (map idType chunk_vars))
body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
in (us', scrut_var:vs, body')
-- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
-- not to need nesting.
mkSmallTupleCase
:: [Id] -- ^ The tuple args
-> CoreExpr -- ^ Body of the case
-> Id -- ^ A variable of the same type as the scrutinee
-> CoreExpr -- ^ Scrutinee
-> CoreExpr
mkSmallTupleCase [var] body _scrut_var scrut
= bindNonRec var scrut body
mkSmallTupleCase vars body scrut_var scrut
-- One branch no refinement?
= Case scrut scrut_var (exprType body) [(DataAlt (tupleCon BoxedTuple (length vars)), vars, body)]
{-
************************************************************************
* *
\subsection{Common list manipulation expressions}
* *
************************************************************************
Call the constructor Ids when building explicit lists, so that they
interact well with rules.
-}
-- | Makes a list @[]@ for lists of the specified type
mkNilExpr :: Type -> CoreExpr
mkNilExpr ty = mkConApp nilDataCon [Type ty]
-- | Makes a list @(:)@ for lists of the specified type
mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
-- | Make a list containing the given expressions, where the list has the given type
mkListExpr :: Type -> [CoreExpr] -> CoreExpr
mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
-- | Make a fully applied 'foldr' expression
mkFoldrExpr :: MonadThings m
=> Type -- ^ Element type of the list
-> Type -- ^ Fold result type
-> CoreExpr -- ^ "Cons" function expression for the fold
-> CoreExpr -- ^ "Nil" expression for the fold
-> CoreExpr -- ^ List expression being folded acress
-> m CoreExpr
mkFoldrExpr elt_ty result_ty c n list = do
foldr_id <- lookupId foldrName
return (Var foldr_id `App` Type elt_ty
`App` Type result_ty
`App` c
`App` n
`App` list)
-- | Make a 'build' expression applied to a locally-bound worker function
mkBuildExpr :: (MonadThings m, MonadUnique m)
=> Type -- ^ Type of list elements to be built
-> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
-- of the binders for the build worker function, returns
-- the body of that worker
-> m CoreExpr
mkBuildExpr elt_ty mk_build_inside = do
[n_tyvar] <- newTyVars [alphaTyVar]
let n_ty = mkTyVarTy n_tyvar
c_ty = mkFunTys [elt_ty, n_ty] n_ty
[c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
build_id <- lookupId buildName
return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
where
newTyVars tyvar_tmpls = do
uniqs <- getUniquesM
return (zipWith setTyVarUnique tyvar_tmpls uniqs)
{-
************************************************************************
* *
Error expressions
* *
************************************************************************
-}
mkRuntimeErrorApp
:: Id -- Should be of type (forall a. Addr# -> a)
-- where Addr# points to a UTF8 encoded string
-> Type -- The type to instantiate 'a'
-> String -- The string to print
-> CoreExpr
mkRuntimeErrorApp err_id res_ty err_msg
= mkApps (Var err_id) [Type res_ty, err_string]
where
err_string = Lit (mkMachString err_msg)
mkImpossibleExpr :: Type -> CoreExpr
mkImpossibleExpr res_ty
= mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
{-
************************************************************************
* *
Error Ids
* *
************************************************************************
GHC randomly injects these into the code.
@patError@ is just a version of @error@ for pattern-matching
failures. It knows various ``codes'' which expand to longer
strings---this saves space!
@absentErr@ is a thing we put in for ``absent'' arguments. They jolly
well shouldn't be yanked on, but if one is, then you will get a
friendly message from @absentErr@ (rather than a totally random
crash).
@parError@ is a special version of @error@ which the compiler does
not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
templates, but we don't ever expect to generate code for it.
-}
errorIds :: [Id]
errorIds
= [ eRROR_ID, -- This one isn't used anywhere else in the compiler
-- But we still need it in wiredInIds so that when GHC
-- compiles a program that mentions 'error' we don't
-- import its type from the interface file; we just get
-- the Id defined here. Which has an 'open-tyvar' type.
uNDEFINED_ID, -- Ditto for 'undefined'. The big deal is to give it
-- an 'open-tyvar' type.
rUNTIME_ERROR_ID,
iRREFUT_PAT_ERROR_ID,
nON_EXHAUSTIVE_GUARDS_ERROR_ID,
nO_METHOD_BINDING_ERROR_ID,
pAT_ERROR_ID,
rEC_CON_ERROR_ID,
rEC_SEL_ERROR_ID,
aBSENT_ERROR_ID ]
recSelErrorName, runtimeErrorName, absentErrorName :: Name
irrefutPatErrorName, recConErrorName, patErrorName :: Name
nonExhaustiveGuardsErrorName, noMethodBindingErrorName :: Name
recSelErrorName = err_nm "recSelError" recSelErrorIdKey rEC_SEL_ERROR_ID
absentErrorName = err_nm "absentError" absentErrorIdKey aBSENT_ERROR_ID
runtimeErrorName = err_nm "runtimeError" runtimeErrorIdKey rUNTIME_ERROR_ID
irrefutPatErrorName = err_nm "irrefutPatError" irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
recConErrorName = err_nm "recConError" recConErrorIdKey rEC_CON_ERROR_ID
patErrorName = err_nm "patError" patErrorIdKey pAT_ERROR_ID
noMethodBindingErrorName = err_nm "noMethodBindingError"
noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
nonExhaustiveGuardsErrorName = err_nm "nonExhaustiveGuardsError"
nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
err_nm :: String -> Unique -> Id -> Name
err_nm str uniq id = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit str) uniq id
rEC_SEL_ERROR_ID, rUNTIME_ERROR_ID, iRREFUT_PAT_ERROR_ID, rEC_CON_ERROR_ID :: Id
pAT_ERROR_ID, nO_METHOD_BINDING_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID :: Id
aBSENT_ERROR_ID :: Id
rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
pAT_ERROR_ID = mkRuntimeErrorId patErrorName
nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
aBSENT_ERROR_ID = mkRuntimeErrorId absentErrorName
mkRuntimeErrorId :: Name -> Id
mkRuntimeErrorId name = pc_bottoming_Id1 name runtimeErrorTy
runtimeErrorTy :: Type
-- The runtime error Ids take a UTF8-encoded string as argument
runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy (mkObjectPrimTy jstringTy) openAlphaTy)
errorName :: Name
errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
eRROR_ID :: Id
eRROR_ID = pc_bottoming_Id1 errorName errorTy
errorTy :: Type -- See Note [Error and friends have an "open-tyvar" forall]
errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
undefinedName :: Name
undefinedName = mkWiredInIdName gHC_ERR (fsLit "undefined") undefinedKey uNDEFINED_ID
uNDEFINED_ID :: Id
uNDEFINED_ID = pc_bottoming_Id0 undefinedName undefinedTy
undefinedTy :: Type -- See Note [Error and friends have an "open-tyvar" forall]
undefinedTy = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
{-
Note [Error and friends have an "open-tyvar" forall]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'error' and 'undefined' have types
error :: forall (a::OpenKind). String -> a
undefined :: forall (a::OpenKind). a
Notice the 'OpenKind' (manifested as openAlphaTyVar in the code). This ensures that
"error" can be instantiated at
* unboxed as well as boxed types
* polymorphic types
This is OK because it never returns, so the return type is irrelevant.
See Note [OpenTypeKind accepts foralls] in TcUnify.
************************************************************************
* *
\subsection{Utilities}
* *
************************************************************************
-}
pc_bottoming_Id1 :: Name -> Type -> Id
-- Function of arity 1, which diverges after being given one argument
pc_bottoming_Id1 name ty
= mkVanillaGlobalWithInfo name ty bottoming_info
where
bottoming_info = vanillaIdInfo `setStrictnessInfo` strict_sig
`setArityInfo` 1
-- Make arity and strictness agree
-- Do *not* mark them as NoCafRefs, because they can indeed have
-- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
-- which has some CAFs
-- In due course we may arrange that these error-y things are
-- regarded by the GC as permanently live, in which case we
-- can give them NoCaf info. As it is, any function that calls
-- any pc_bottoming_Id will itself have CafRefs, which bloats
-- SRTs.
strict_sig = mkClosedStrictSig [evalDmd] botRes
-- These "bottom" out, no matter what their arguments
pc_bottoming_Id0 :: Name -> Type -> Id
-- Same but arity zero
pc_bottoming_Id0 name ty
= mkVanillaGlobalWithInfo name ty bottoming_info
where
bottoming_info = vanillaIdInfo `setStrictnessInfo` strict_sig
strict_sig = mkClosedStrictSig [] botRes
|
pparkkin/eta
|
compiler/ETA/Core/MkCore.hs
|
bsd-3-clause
| 31,881 | 0 | 16 | 8,639 | 4,890 | 2,671 | 2,219 | 365 | 4 |
-- GSoC 2015 - Haskell bindings for OpenCog.
{-# LANGUAGE TypeOperators #-}
-- | This library defines Haskell Bindings for the AtomSpace.
module OpenCog.AtomSpace
(
-- * AtomSpace Environment
AtomSpace
, AtomSpaceObj
, getParent
, newAtomSpace
, onAtomSpace
, (<:)
, runOnNewAtomSpace
, refToObj
-- * AtomSpace Interaction
, insert
, insertAndGetHandle
, remove
, get
, getByHandle
, debug
-- * AtomSpace Execution
, execute
, evaluate
-- * AtomSpace Query
, module OpenCog.AtomSpace.Query
-- * AtomSpace Printing
, printAtom
, showAtom
-- * AtomSpace Main Data Types
, TruthVal (..)
, AtomName (..)
, Atom (..)
-- * AtomSpace Syntactic Sugar
, module OpenCog.AtomSpace.Sugar
-- * Function for use in GSN
, exportFunction
, Handle
, HandleSeq
, AtomSpaceRef
-- * Utility Functions for working with Atoms
, atomMap
, atomMapM
, atomFold
, atomElem
, nodeName
, atomType
, atomGetAllNodes
) where
import OpenCog.AtomSpace.Api
import OpenCog.AtomSpace.Types
import OpenCog.AtomSpace.Env
import OpenCog.AtomSpace.Utils
import OpenCog.AtomSpace.Sugar
import OpenCog.AtomSpace.Query
import OpenCog.AtomSpace.Internal (Handle,HandleSeq)
|
inflector/atomspace
|
opencog/haskell/OpenCog/AtomSpace.hs
|
agpl-3.0
| 1,317 | 0 | 5 | 347 | 194 | 135 | 59 | 44 | 0 |
{-|
Module : Idris.Unlit
Description : Turn literate programs into normal programs.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.Unlit(unlit) where
import Idris.Core.TT
import Data.Char
unlit :: FilePath -> String -> TC String
unlit f s = do let s' = map ulLine (lines s)
check f 1 s'
return $ unlines (map snd s')
data LineType = Prog | Blank | Comm
ulLine :: String -> (LineType, String)
ulLine ('>':' ':xs) = (Prog, xs)
ulLine ('>':xs) = (Prog, xs)
ulLine xs | all isSpace xs = (Blank, "")
-- make sure it's not a doc comment
| otherwise = (Comm, '-':'-':' ':'>':xs)
check :: FilePath -> Int -> [(LineType, String)] -> TC ()
check f l (a:b:cs) = do chkAdj f l (fst a) (fst b)
check f (l+1) (b:cs)
check f l [x] = return ()
check f l [] = return ()
-- Issue #1593 on the issue checker.
--
-- https://github.com/idris-lang/Idris-dev/issues/1593
--
chkAdj :: FilePath -> Int -> LineType -> LineType -> TC ()
chkAdj f l Prog Comm = tfail $ At (FC f (l, 0) (l, 0)) ProgramLineComment --TODO: Span correctly
chkAdj f l Comm Prog = tfail $ At (FC f (l, 0) (l, 0)) ProgramLineComment --TODO: Span correctly
chkAdj f l _ _ = return ()
|
tpsinnem/Idris-dev
|
src/Idris/Unlit.hs
|
bsd-3-clause
| 1,276 | 0 | 12 | 334 | 510 | 268 | 242 | 22 | 1 |
{-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE NoPolyKinds #-}
module T16722 where
import Data.Kind
type D :: k -> Type
data D a
|
sdiehl/ghc
|
testsuite/tests/saks/should_fail/T16722.hs
|
bsd-3-clause
| 140 | 0 | 5 | 25 | 25 | 17 | 8 | -1 | -1 |
{-# LANGUAGE ViewPatterns #-}
-- Simple implementation of the Lambda Calculus.
module Lambda where
-- The datatype of Lambda Calculus terms.
data Term
= Lam !Term
| App !Term !Term
| Var !Int
deriving (Show,Eq,Ord)
-- Folds over a term.
fold :: (t -> t) -> (t -> t -> t) -> (Int -> t) -> Term -> t
fold lam app var term = go term where
go (Lam body) = lam (go body)
go (App left right) = app (go left) (go right)
go (Var idx) = var idx
-- Pretty prints a term.
pretty :: Term -> String
pretty (Var n) = show n
pretty (Lam a) = "λ"++pretty a
pretty (App a b) = "("++pretty a++" "++pretty b++")"
-- Reduces a strongly normalizing term to normal form.
-- Does not halt then the term isn't strongly normalizing.
reduce :: Term -> Term
reduce (Lam a) = Lam (reduce a)
reduce (Var a) = Var a
reduce (App a b) = case reduce a of
Lam body -> reduce (subs (reduce b) True 0 (-1) body)
otherwise -> App (reduce a) (reduce b)
where
subs t s d w (App a b) = App (subs t s d w a) (subs t s d w b)
subs t s d w (Lam a) = Lam (subs t s (d+1) w a)
subs t s d w (Var a)
| s && a == d = subs (Var 0) False (-1) d t
| otherwise = Var (a + (if a > d then w else 0))
-- How many occurrences of the bound variable are on the term?
countBoundVar :: Term -> Int
countBoundVar term = fold lam app var term (-1) where
lam body depth = body (depth+1)
app left right depth = left depth + right depth
var index depth | depth == index = 1
var index depth | otherwise = 0
|
shaunstanislaus/caramel
|
src/Lambda.hs
|
mit
| 1,620 | 0 | 13 | 496 | 717 | 357 | 360 | 41 | 5 |
{-# htermination (pt :: (c -> a) -> (b -> c) -> b -> a) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
pt :: (b -> a) -> (c -> b) -> c -> a;
pt f g x = f (g x);
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/DOT_1.hs
|
mit
| 235 | 0 | 8 | 81 | 91 | 51 | 40 | 5 | 1 |
module Euler.Problem3Spec ( spec ) where
import Helper
import Euler.Problem3
spec :: Spec
spec = do
describe "primeFactors" $ do
it "of 3" $ do
(primeFactors 3 :: [Int]) `shouldBe` ([3] :: [Int])
it "of 6" $ do
(primeFactors 6 :: [Int]) `shouldBe` ([2,3] :: [Int])
it "of 8" $ do
(primeFactors 8 :: [Int]) `shouldBe` ([2,2,2] :: [Int])
describe "largestPrimeFactor" $ do
it "of 3" $ do
(largestPrimeFactor 3 :: Int) `shouldBe` (3 :: Int)
it "of 6" $ do
(largestPrimeFactor 6 :: Int) `shouldBe` (3 :: Int)
it "of 8" $ do
(largestPrimeFactor 8 :: Int) `shouldBe` (2 :: Int)
|
slogsdon/haskell-exercises
|
pe/testsuite/specs/Euler/Problem3Spec.hs
|
mit
| 642 | 0 | 22 | 172 | 293 | 158 | 135 | 19 | 1 |
module HaskellCourse.UntypedLC.Parser (parseExp) where
import Data.Maybe (fromMaybe)
import HaskellCourse.Parsing
import HaskellCourse.Prim
import HaskellCourse.UntypedLC.AST
parseExp :: SExpr -> Exp
parseExp (AtomNum n) = LitInt n
parseExp (AtomSym s) = parseVar s
parseExp (List [AtomSym "let", List [AtomSym v, e], body]) =
Let v (parseExp e) (parseExp body)
parseExp (List [AtomSym v, AtomSym "->", b]) = Lambda v (parseExp b)
parseExp (List [AtomSym p, a, b]) = PrimApp (parsePrim p) (parseExp a) (parseExp b)
parseExp (List [a, b]) = App (parseExp a) (parseExp b)
parseExp bad = error $ "parse error, bad expression: " ++ show bad
parseVar :: String -> Exp
parseVar s = if isPrim s then error ("bad variable name: " ++ s) else Var s
|
joshcough/HaskellCourse
|
src/HaskellCourse/UntypedLC/Parser.hs
|
mit
| 745 | 0 | 11 | 123 | 326 | 169 | 157 | 16 | 2 |
-- module EventEmitter where
{-# LANGUAGE OverloadedStrings #-}
import Control.Concurrent
import Control.Monad
import Data.JSString
import Data.String
import GHCJS.Foreign
import GHCJS.Foreign.Callback
import GHCJS.Types
import JavaScript.Array
import JavaScript.Object
newtype EventEmitter = EventEmitter JSVal
newEmitter :: IO EventEmitter
newEmitter = EventEmitter <$> js_newEmitter
emit1 :: EventEmitter -> String -> JSVal -> IO JSVal
emit1 (EventEmitter emitter) name arg =
js_emit1 emitter (fromString name) arg
on1 :: EventEmitter -> String -> IO () -> IO ()
on1 (EventEmitter emitter) name action = do
let jsName = fromString name
callback <- asyncCallback action
js_on1 emitter jsName callback
getRegisterEmitter :: IO EventEmitter
getRegisterEmitter = EventEmitter <$> js_registerEmitter
foreign import javascript unsafe "$r = global.emitter"
js_registerEmitter :: IO JSVal
foreign import javascript unsafe "$r = $1.emit($2, $3)"
js_emit1 :: JSVal -> JSString -> JSVal -> IO JSVal
foreign import javascript unsafe "$1.on($2, $3)"
js_on1 :: JSVal -> JSString -> Callback (IO ()) -> IO ()
foreign import javascript unsafe "$r = new EventEmitter()"
js_newEmitter :: IO JSVal
exports :: String -> JSVal -> IO ()
exports name val = js_exports (fromString name) val
foreign import javascript unsafe "exports[$1] = $2"
js_exports :: JSString -> JSVal -> IO ()
main = do
putStrLn "[haskell] Starting Haskell"
putStrLn "[haskell] Getting reference to ghcjs-register emitter"
emitter <- getRegisterEmitter
putStrLn "[haskell] Emitting 'something' event!"
emit1 emitter "something" (jsval ("hello world" :: JSString))
forkIO $ forever $ do
tid <- myThreadId
putStrLn $ "[haskell - " ++ show tid ++ "] Emitting 'something' event!"
emit1 emitter "something" (jsval ("hello world" :: JSString))
threadDelay (1000 * 1000)
tid <- myThreadId
putStrLn $ "[haskell - " ++ show tid ++ "] Listening for 'foo'"
on1 emitter "foo" $ do
tid <- myThreadId
putStrLn $ "[haskell - " ++ show tid ++ "] Got 'foo' event!"
putStrLn $ "[haskell - " ++ show tid ++ "] This thread is still free to run"
|
beijaflor-io/ghcjs-commonjs
|
old-examples/EventEmitter.hs
|
mit
| 2,307 | 18 | 13 | 537 | 596 | 291 | 305 | 52 | 1 |
module Sgd.Num.Vector where
-- http://stackoverflow.com/questions/17892065/mutable-random-access-array-vector-with-high-performance-in-haskell
-- http://haskell.1045720.n5.nabble.com/fishing-for-ST-mutable-Vector-examples-td4333461.html
-- import qualified Data.IntMap as IntMap
import qualified Data.Vector.Unboxed as VU
-- type SparseVector = IntMap
type SparseVector = [(Int, Double)]
type FullVector = VU.Vector (Double)
-- type Sample = (SparseVector, Double) -- (input, response)
dotFS :: FullVector -> SparseVector -> Double
dotFS u v = foldl go 0 v
where
go :: Double -> (Int, Double) -> Double
go acc (ind, val) = acc + u VU.! ind * val
dotFS' :: FullVector -> SparseVector -> Double
--dotFS' u v = sum . zipWith (*) vals . VU.toList . map (\x -> u VU.! x) $ inds
dotFS' u v = sum . zipWith (*) vals . slice u $ inds
where
(inds, vals) = unzip v
slice :: FullVector -> [Int] -> [Double]
slice u v = map (\x -> u VU.! x) $ v
addFS :: FullVector -> SparseVector -> FullVector
addFS = VU.accum (+)
dot :: FullVector -> FullVector -> Double
dot u v = VU.sum $ VU.zipWith (*) u v
scale :: FullVector -> Double -> FullVector
scale u d = VU.map (*d) u
dim :: SparseVector -> Int
dim = foldl1 max . fst . unzip
rep :: Int -> Double -> FullVector
rep l x = VU.replicate l x
mul :: SparseVector -> Double -> SparseVector
mul x d = map (\(a1, a2) -> (a1, a2*d)) x
normalizeL2 :: SparseVector -> SparseVector
normalizeL2 v = mul v $ 1 / (l2norm v)
l2norm :: SparseVector -> Double
l2norm v = sqrt . sum . zipWith (\x y -> snd x * snd y) v $ v
|
daz-li/svm_sgd_haskell
|
src/Sgd/Num/Vector.hs
|
mit
| 1,594 | 0 | 11 | 324 | 538 | 292 | 246 | 29 | 1 |
import Configuration.Dotenv (loadFile)
import Database.PostgreSQL.Simple.Util (withTransactionRolledBack)
import RunMigrations (runAllMigrations)
import Test.Hspec (around_, describe, hspec)
import Util (getConn)
import qualified ConferenceSpec
main :: IO ()
main = do
loadFile False "config/config.env"
conn <- getConn
runAllMigrations conn
hspec $
around_ (withTransactionRolledBack conn) $
describe "All tests" $ do
ConferenceSpec.tests conn
|
robertjlooby/confsinfo
|
backend/test/Spec.hs
|
mit
| 499 | 0 | 12 | 102 | 130 | 68 | 62 | 15 | 1 |
import Haste
import Haste.DOM
import Haste.Graphics.Canvas
import Basal
steps :: Int
steps = 20000
size :: Int
size = 500
main = do
Just canv <- getCanvasById "field"
Just button <- elemById "button"
_ <- onEvent button OnClick (onButtonClick canv steps)
seed <- newSeed
renderRW canv seed steps
onButtonClick :: Canvas -> Int -> Int -> (Int,Int) -> IO ()
onButtonClick canv n _ _ = do
seed <- newSeed
renderRW canv seed n
renderRW :: Canvas -> Seed -> Int -> IO ()
renderRW canv seed n = let
r = fromIntegral (size `div` 2)
in
render canv . translate (r,r) . stroke . path $ randomWalkNPol 6 seed n
|
lesguillemets/schrammloewner
|
src/HexaRandom.hs
|
mit
| 650 | 0 | 12 | 161 | 263 | 130 | 133 | 22 | 1 |
{-# LANGUAGE InstanceSigs #-}
module TwentyFive where
import Control.Applicative (liftA2)
newtype Compose f g a =
Compose { getCompose :: f (g a) }
deriving (Eq, Show)
instance (Functor f, Functor g) =>
Functor (Compose f g) where
fmap f (Compose fga) = Compose $ (fmap . fmap) f fga
-- Twinplicative, GOTCHA! Exercise Time
instance (Applicative f, Applicative g) =>
Applicative (Compose f g) where
pure :: a -> Compose f g a
pure = Compose . pure . pure
(<*>) :: Compose f g (a -> b)
-> Compose f g a
-> Compose f g b
(Compose f) <*> (Compose a) = Compose $ (liftA2 (<*>)) f a
-- (Compose f) <*> (Compose a) = Compose $ (fmap (<*>) f) <*> a
-- Exercises: Compose Instances
instance (Foldable f, Foldable g) =>
Foldable (Compose f g) where
foldMap f (Compose fga) = foldMap (\a -> foldMap f a) fga
instance (Traversable f, Traversable g) =>
Traversable (Compose f g) where
-- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
traverse f (Compose fga) = sequenceA (f <$> (Compose fga))
-- And now for something completely different
class Bifunctor p where
{-# MINIMAL bimap | first, second #-}
bimap :: (a -> b) -> (c -> d) -> p a c -> p b d
bimap f g = first f . second g
first :: (a -> b) -> p a c -> p b c
first f = bimap f id
second :: (b -> c) -> p a b -> p a c
second = bimap id
-- 1
data Deux a b = Deux a b
instance Bifunctor Deux where
bimap f g = second g . first f
-- 2
data Const a b = Const a
instance Bifunctor Const where
bimap f g = second g . first f
-- 3
data Drei a b c = Drei a b c
instance Bifunctor (Drei a) where
bimap f g = second g . first f
-- 4
data SuperDrei a b c = SuperDrei a b
instance Bifunctor (SuperDrei a) where
bimap f g = second g . first f
-- 5
data SemiDrei a b c = SemiDrei a
instance Bifunctor (SemiDrei a) where
bimap f g = second g . first f
-- 6
data Quadriceps a b c d = Quadzzz a b c d
instance Bifunctor (Quadriceps a b) where
bimap f g = second g . first f
-- 7
data Either' a b = Left a | Right b
instance Bifunctor Either' where
bimap f g = second g . first f
|
mudphone/HaskellBook
|
src/TwentyFive.hs
|
mit
| 2,150 | 0 | 10 | 576 | 872 | 457 | 415 | 52 | 0 |
{-# LANGUAGE UnicodeSyntax #-}
module Pixs.Operations.Pixel where
import Codec.Picture (PixelRGBA8(..))
import Data.Word
import Control.Arrow ((***))
limit ∷ (Num c, Ord c) ⇒ c → c
limit = max 0 . min 255
-- TODO: PixelRGBA8 should not really have an instance of
-- Num since it doesn't behave like a number. For
-- now we declare a num instance for the convenience of
-- being able to use (+), (-) etc... It would be the best
-- it were a VectorSpace if a VectorSpace typeclass exists
-- somewhere. Or maybe, that's too much; I don't know.
instance Num PixelRGBA8 where
negate (PixelRGBA8 r g b _) = PixelRGBA8 r' g' b' 255
where (r', g', b') = (255 - r, 255 - g, 255 - b)
(+) = applyOp (+)
(-) = applyOp (-)
(*) = applyOp (*)
abs p = p
signum p = p
fromInteger _ = undefined
-- | Used for reducing repetition when declaring Num instance.
-- Our strategy for overflow/underflow checking is the same for all of the
-- operations so we define this function that takes in an operation and two
-- pixels and applies the operation to the components. Pixel addition for
-- example is implemented by simply passing (+) to `applyOp`.
applyOp ∷ (Int → Int → Int) → PixelRGBA8 → PixelRGBA8 → PixelRGBA8
applyOp op (PixelRGBA8 r₁ g₁ b₁ a₁) (PixelRGBA8 r₂ g₂ b₂ a₂)
= PixelRGBA8 r g b (max a₁ a₂)
where
f = fromIntegral . limit . uncurry op . (fromIntegral *** fromIntegral)
r = f (r₁, r₂)
g = f (g₁, g₂)
b = f (b₁, b₂)
pixelDiv ∷ PixelRGBA8 → PixelRGBA8 → PixelRGBA8
pixelDiv = applyOp div
-- | Flow-checked addition operation which we denote with ⊕.
-- Also has an ASCII alias @safeAdd@.
(⊕) ∷ Word8 → Int → Word8
(⊕) x y = let x' = fromIntegral x ∷ Int
in fromIntegral . limit $ x' + y
-- | ASCII alias for flow-checked addition.
safeAdd ∷ Word8 → Int → Word8
safeAdd = (⊕)
-- | Flow-checked multiplication operation.
-- Also has an ASCII alias `safeMultiply`.
(⊗) ∷ Word8 → Int → Word8
(⊗) x y = let x' = (fromIntegral x) ∷ Int
in fromIntegral . limit $ x' * y
-- | ASCII alias for flow-checked multiplication.
safeMultiply ∷ Word8 → Int → Word8
safeMultiply = (⊗)
-- | Scalar multiplication.
scale ∷ Double → PixelRGBA8 → PixelRGBA8
scale n (PixelRGBA8 r g b a) = PixelRGBA8 r' g' b' a
where
f = round . limit . (* n) . fromIntegral
r' = f r
g' = f g
b' = f b
-- | Take a list of pixels. Return the pixel that is the average color of
-- those pixels.
average ∷ [PixelRGBA8] → PixelRGBA8
average pixs = let avg xs = sum xs `div` length xs
redAvg ∷ Word8
redAvg = fromIntegral $ avg [fromIntegral r ∷ Int
| (PixelRGBA8 r _ _ _) ← pixs ]
greenAvg ∷ Word8
greenAvg = fromIntegral $ avg [fromIntegral g ∷ Int
| (PixelRGBA8 _ g _ _) ← pixs]
blueAvg ∷ Word8
blueAvg = fromIntegral $ avg [fromIntegral b ∷ Int
| (PixelRGBA8 _ _ b _) ← pixs]
in PixelRGBA8 redAvg greenAvg blueAvg 255
|
ayberkt/pixs
|
src/Pixs/Operations/Pixel.hs
|
mit
| 3,335 | 32 | 15 | 986 | 877 | 478 | 399 | 53 | 1 |
{-# LANGUAGE RankNTypes #-}
-- | A convenience wrapper around Options.Applicative.
module SimpleOptions
( simpleOptions
, Options.addCommand
, Options.simpleVersion
) where
import Control.Applicative
import Control.Monad.Trans.Either (EitherT)
import Control.Monad.Trans.Writer (Writer)
import Data.Monoid
import qualified Options.Applicative.Simple as Options
-- | This is a drop-in replacement for simpleOptions from
-- Options.Applicative.Simple, with the added feature of a `--summary` flag
-- that prints out the header. (Should be one line)
simpleOptions
:: String
-- ^ version string
-> String
-- ^ header
-> String
-- ^ program description
-> Options.Parser a
-- ^ global settings
-> EitherT b (Writer (Options.Mod Options.CommandFields b)) ()
-- ^ commands (use 'addCommand')
-> IO (a,b)
simpleOptions versionString h pd globalParser mcommands =
Options.simpleOptions
versionString h pd globalParser' mcommands
where
globalParser' = summaryOption <*> globalParser
summaryOption = Options.infoOption h
$ Options.long "summary"
<> Options.help "Show program summary"
|
fpco/stackage-cli
|
src/SimpleOptions.hs
|
mit
| 1,194 | 0 | 15 | 258 | 206 | 117 | 89 | 24 | 1 |
module Y2018.M07.D30.Exercise where
import Data.Set (Set)
-- We have two databases
pilot, entities, exDir :: FilePath
exDir = "Y2018/M07/D30/"
pilot = "pilot_db.csv"
entities = "entities_db.csv"
-- We want to merge those databases into one SUPER-database
-- Read in the tables from each database (mind the header information) and do
-- a set difference. What are the names of the tables that both databases share?
-- How many tables are common between both databases?
type Table = String
type Database = Set Table
readDatabase :: FilePath -> IO Database
readDatabase file = undefined
sharedTables :: Database -> Database -> Set Table
sharedTables db1 db2 = undefined
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M07/D30/Exercise.hs
|
mit
| 675 | 0 | 7 | 113 | 108 | 65 | 43 | 12 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module Sixteen where
import GHC.Arr
import Test.QuickCheck
a = fmap (+1) $ read "[1]" :: [Int]
b = (fmap . fmap) (++ "lol") (Just ["Hi,", "Hello"])
c = (*2) . (\x -> x - 2)
d = ((return '1' ++) . show) . (\x -> [x, 1..3])
e :: IO Integer
e = let ioi = readIO "1" :: IO Integer
changed = fmap read (fmap ("123"++) (fmap show ioi))
in fmap (*3) changed
-- 16.9 QuickChecking Functor instances
functorIdentity :: (Functor f, Eq (f a)) => f a -> Bool
functorIdentity f = fmap id f == f
functorCompose :: (Eq (f c), Functor f) => (a -> b) -> (b -> c) -> f a -> Bool
functorCompose f g x = (fmap g (fmap f x)) == (fmap (g . f) x)
-- Identity a
newtype Identity a = Identity a
deriving (Eq, Show)
instance Functor Identity where
fmap f (Identity a) = Identity (f a)
identityGen :: Arbitrary a => Gen (Identity a)
identityGen = do
a <- arbitrary
return (Identity a)
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = identityGen
-- Pair a
data Pair a = Pair a a
deriving (Eq, Show)
instance Functor Pair where
fmap f (Pair a b) = Pair (f a) (f b)
pairGen :: (Arbitrary a) => Gen (Pair a)
pairGen = do
a <- arbitrary
b <- arbitrary
return $ Pair a b
instance (Arbitrary a) => Arbitrary (Pair a) where
arbitrary = pairGen
-- Two a b
data Two a b = Two a b
deriving (Eq, Show)
instance Functor (Two a) where
fmap f (Two a b) = Two a (f b)
twoGen :: (Arbitrary a, Arbitrary b) => Gen (Two a b)
twoGen = do
a <- arbitrary
b <- arbitrary
return $ Two a b
instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where
arbitrary = twoGen
-- Three a b c
data Three a b c = Three a b c
deriving (Eq, Show)
instance Functor (Three a b) where
fmap f (Three a b c) = Three a b (f c)
threeGen :: (Arbitrary a, Arbitrary b, Arbitrary c) => Gen (Three a b c)
threeGen = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
return $ Three a b c
instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Three a b c) where
arbitrary = threeGen
-- Three' a b
data Three' a b = Three' a b b
deriving (Eq, Show)
instance Functor (Three' a) where
fmap f (Three' a b c) = Three' a (f b) (f c)
threePrimeGen :: (Arbitrary a, Arbitrary b) => Gen (Three' a b)
threePrimeGen = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
return $ Three' a b c
instance (Arbitrary a, Arbitrary b) => Arbitrary (Three' a b) where
arbitrary = threePrimeGen
-- Four a b c d
data Four a b c d = Four a b c d
deriving (Eq, Show)
instance Functor (Four a b c) where
fmap f (Four a b c d) = Four a b c (f d)
fourGen :: (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Gen (Four a b c d)
fourGen = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
d <- arbitrary
return $ Four a b c d
instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) =>
Arbitrary (Four a b c d) where
arbitrary = fourGen
-- Four' a b
data Four' a b = Four' a a a b
deriving (Eq, Show)
instance Functor (Four' a) where
fmap f (Four' a b c d) = Four' a b c (f d)
fourPrimeGen :: (Arbitrary a, Arbitrary b) => Gen (Four' a b)
fourPrimeGen = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
d <- arbitrary
return $ Four' a b c d
instance (Arbitrary a, Arbitrary b) => Arbitrary (Four' a b) where
arbitrary = fourPrimeGen
main :: IO ()
main = do
quickCheck $ \x -> functorIdentity (x :: Identity Int)
quickCheck $ \x -> functorCompose (+1) (*2) (x :: Identity Int)
quickCheck $ \x -> functorIdentity (x :: Pair Int)
quickCheck $ \x -> functorCompose (+1) (*2) (x :: Pair Int)
quickCheck $ \x -> functorIdentity (x :: Two Char Int)
quickCheck $ \x -> functorCompose (+1) (*2) (x :: Two Char Int)
quickCheck $ \x -> functorIdentity (x :: Three Char Char Int)
quickCheck $ \x -> functorCompose (+1) (*2) (x :: Three Char Char Int)
quickCheck $ \x -> functorIdentity (x :: Three' Char Int)
quickCheck $ \x -> functorCompose (+1) (*2) (x :: Three' Char Int)
quickCheck $ \x -> functorIdentity (x :: Four Char Char Char Int)
quickCheck $ \x -> functorCompose (+1) (*2) (x :: Four Char Char Char Int)
quickCheck $ \x -> functorIdentity (x :: Four' Char Int)
quickCheck $ \x -> functorCompose (+1) (*2) (x :: Four' Char Int)
-- Possibly
data Possibly a =
LolNope
| Yeppers a
deriving (Eq, Show)
instance Functor Possibly where
fmap f (Yeppers a) = Yeppers (f a)
fmap _ LolNope = LolNope
-- Sum
data Sum a b =
First a
| Second b
deriving (Eq, Show)
instance Functor (Sum a) where
fmap f (Second b) = Second (f b)
fmap _ (First a) = First a
--
-- Exercises
--
--
data BoolAndMaybeSomethingElse a = Fetish | Truish a
deriving (Eq, Show)
instance Functor BoolAndMaybeSomethingElse where
fmap _ Fetish = Fetish
fmap f (Truish a) = Truish (f a)
-- 1
data Sum1 b a = First1 a | Second1 b
deriving (Eq, Show)
instance Functor (Sum1 b) where
fmap f (First1 a) = First1 (f a)
fmap f (Second1 b) = Second1 b
-- 2
data Company a b c = DeepBlue a b | Something c
deriving (Eq, Show)
instance Functor (Company e e') where
fmap f (Something b) = Something (f b)
fmap _ (DeepBlue a c) = DeepBlue a c
-- 3
data More b a =
L a b a
| R b a b
deriving (Eq, Show)
instance Functor (More a) where
fmap f (L a b a') = L (f a) b (f a')
fmap f (R b a b') = R b (f a) b'
-- 1
data Quant a b =
Finance
| Desk a
| Bloor b
instance Functor (Quant a) where
fmap _ Finance = Finance
fmap _ (Desk a) = Desk a
fmap f (Bloor b) = Bloor (f b)
-- 2
data K a b = K a
instance Functor (K b) where
fmap _ (K a) = K a
-- 3
newtype Flip f a b =
Flip (f b a)
deriving (Eq, Show)
newtype K3 a b = K3 a
instance Functor (Flip K3 a) where
fmap f (Flip (K3 a)) = Flip (K3 (f a))
-- 4
data EvilGoateeConst a b = GoatyConst b
instance Functor (EvilGoateeConst a) where
fmap f (GoatyConst b) = GoatyConst (f b)
-- 5
data LiftItOut f a = LiftItOut (f a)
instance Functor f => Functor (LiftItOut f) where
fmap f2 (LiftItOut b) = LiftItOut (fmap f2 b)
-- 6
data Parappa f g a = DaWrappa (f a) (g a)
instance (Functor f, Functor g) => Functor (Parappa f g) where
fmap f2 (DaWrappa b c) = DaWrappa (fmap f2 b) (fmap f2 c)
-- 7
data IgnoreOne f g a b = IgnoringSomething (f a) (g b)
instance Functor g => Functor (IgnoreOne f g a) where
fmap f2 (IgnoringSomething c d) = IgnoringSomething c (fmap f2 d)
-- 8
data Notorious g o a t =
Notorious (g o) (g a) (g t)
instance Functor g => Functor (Notorious g o a) where
fmap f (Notorious b c d) = Notorious b c (fmap f d)
-- 9
data List a =
Nil
| Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons a list) = Cons (f a) (fmap f list)
-- 10
data GoatLord a =
NoGoat
| OneGoat a
| MoreGoats (GoatLord a) (GoatLord a) (GoatLord a)
deriving (Eq, Show)
instance Functor GoatLord where
fmap _ NoGoat = NoGoat
fmap f (OneGoat a) = OneGoat (f a)
fmap f (MoreGoats g1 g2 g3) = MoreGoats (fmap f g1) (fmap f g2) (fmap f g3)
-- 11
data TalkToMe a =
Halt
| Print String a
| Read (String -> a)
-- deriving (Eq, Show)
instance Functor TalkToMe where
fmap _ Halt = Halt
fmap f (Print s a) = Print s (f a)
fmap f (Read sta) = Read (f . sta)
|
mudphone/HaskellBook
|
src/Sixteen.hs
|
mit
| 7,282 | 0 | 13 | 1,808 | 3,571 | 1,865 | 1,706 | 208 | 1 |
module Proteome.Buffers.Syntax where
import qualified Data.Map.Strict as Map (fromList)
import Ribosome.Data.Syntax (
HiLink(HiLink),
Syntax(Syntax),
SyntaxItem(siOptions, siParams),
syntaxMatch,
syntaxVerbatim,
)
import Text.RawString.QQ (r)
asterisk :: SyntaxItem
asterisk =
item { siOptions = options, siParams = params }
where
item = syntaxMatch "ProBuffersAsterisk" [r|^ \*|]
options = ["skipwhite"]
params = Map.fromList [("nextgroup", "ProBuffersNumber")]
number :: SyntaxItem
number =
item { siOptions = options, siParams = params }
where
item = syntaxMatch "ProBuffersNumber" [r|\d\+|]
options = ["contained", "skipwhite"]
params = Map.fromList [("nextgroup", "ProBuffersName")]
line :: SyntaxItem
line =
item { siOptions = options }
where
item = syntaxMatch "ProBuffersName" ".*$"
options = ["contained"]
sync :: SyntaxItem
sync =
syntaxVerbatim "syntax sync minlines=1"
hlAsterisk :: HiLink
hlAsterisk =
HiLink "ProBuffersAsterisk" "Todo"
hlNumber :: HiLink
hlNumber =
HiLink "ProBuffersNumber" "Directory"
hlName :: HiLink
hlName =
HiLink "ProBuffersName" "Type"
buffersSyntax :: Syntax
buffersSyntax =
Syntax items [] links
where
items =
[asterisk, number, line, sync]
links =
[hlAsterisk, hlNumber, hlName]
|
tek/proteome
|
packages/proteome/lib/Proteome/Buffers/Syntax.hs
|
mit
| 1,318 | 0 | 9 | 251 | 355 | 217 | 138 | -1 | -1 |
{-# LANGUAGE GADTs, KindSignatures, MultiParamTypeClasses, FlexibleContexts,
FlexibleInstances, ScopedTypeVariables, TypeFamilies, EmptyDataDecls #-}
module Language.SPL.Intermediate (
Intermediate (..),
Index (..), Layout (..), peek,
Translate (..), translate, convert,
Accumulator (..),
stochastic
) where
import qualified Language.SPL.Syntax as S
import qualified Language.SPL.Operator as S
import qualified Language.SPL as S
import Language.SPL.SimulationResult (SimulationResult)
import System.Random
import Data.Typeable
import Data.Maybe
import Control.Monad (guard)
data Index :: * -> * -> * where
Zero :: Index (env, a) a
Succ :: Index env a -> Index (env, b) a
data Intermediate :: * -> * -> * where
Uniform :: Intermediate env Double
Normal :: Intermediate env Double
Let :: (S.Type a, S.Type b) =>
Intermediate env a -> Intermediate (env, a) b -> Intermediate env b
Constant :: (S.Type a) =>
(S.Constant a) -> Intermediate env a
Unary :: (S.Type a, S.Type b) =>
(S.UnaryOperator a b) -> Intermediate env a -> Intermediate env b
Binary :: (S.Type a, S.Type b, S.Type c) =>
(S.BinaryOperator a b c) -> Intermediate env a -> Intermediate env b ->
Intermediate env c
If :: (S.Type a) =>
Intermediate env Bool -> Intermediate env a -> Intermediate env a ->
Intermediate env a
Prefix :: (S.Type a) =>
Bool -> Intermediate env S.Time -> Accumulator env a -> Intermediate env a
Variable :: (S.Type a) =>
Index env a -> Intermediate env a
Split :: (S.Type a) =>
Intermediate (env, StdGen) a -> Intermediate env a
Use :: (S.Type a) =>
Index env StdGen -> Intermediate env a -> Intermediate env a
data Accumulator :: * -> * -> * where
Accumulate :: (S.Type a, S.Type b) =>
Intermediate (((env, S.Time), a), b) a ->
Bool -> Maybe (Intermediate env a) -> Maybe (Accumulator env b) ->
Accumulator env a
Zip :: (S.Type a, S.Type b) =>
Accumulator env a -> Accumulator env b -> Accumulator env (a, b)
Expression :: (S.Type a) =>
Bool -> Intermediate (env, S.Time) a -> Accumulator env a
Splitting :: (S.Type a) =>
Accumulator (env, StdGen) a -> Accumulator env a
Using :: (S.Type a) =>
Index env StdGen -> Accumulator env a -> Accumulator env a
data Layout :: * -> * -> * where
Empty :: Layout env ()
Push :: (S.Type a) =>
Layout env env’ -> Index env a -> Layout env (env’, a)
size :: Layout env env’ -> Int
size Empty = 0
size (Push layout _) = size layout + 1
increase :: Layout env env’ -> Layout (env, a) env’
increase Empty = Empty
increase (Push layout index) = Push (increase layout) (Succ index)
project :: (S.Type a) => Int -> Layout env env’ -> Index env a
project _ Empty = error "Cannot project an empty layout"
project 0 (Push _ index) = fromJust (gcast index)
project n (Push layout _) = project (n - 1) layout
peek :: Index env a -> env -> a
peek Zero (_, a) = a
peek (Succ n) (environment, _) = peek n environment
translate :: Translate () a => a -> Intermediate (EnvironmentOf () a) (ResultOf a)
translate = translate’ Empty
class Translate env a where
type EnvironmentOf env a
type ResultOf a
translate’ :: Layout env env -> a -> Intermediate (EnvironmentOf env a) (
ResultOf a)
instance S.Type a => Translate env (S.Dist a) where
type EnvironmentOf env (S.Dist a) = env
type ResultOf (S.Dist a) = a
translate’ = convert’
instance forall env a b. (Translate (env, a) b, S.Type a) => Translate env (S.Dist a
-> b) where
type EnvironmentOf env (S.Dist a -> b) = EnvironmentOf (env, a) b
type ResultOf (S.Dist a -> b) = ResultOf b
translate’ layout f = translate’ layout’ (f tag)
where
(tag, layout’) = distTag layout
instance forall env a b. (Translate (env, a) b, S.Type a) => Translate env (S.
Process a -> b) where
type EnvironmentOf env (S.Process a -> b) = EnvironmentOf (env, a) b
type ResultOf (S.Process a -> b) = ResultOf b
translate’ layout f = translate’ layout’ (f (S.always tag))
where
(tag, layout’) = distTag layout
convert :: S.Dist a -> Intermediate () a
convert = convert’ Empty
convert’ :: Layout env env -> S.Dist a -> Intermediate env a
convert’ layout term = case term of
S.TagD tag -> Variable (project (size layout - tag - 1) layout)
S.Certain constant -> Constant constant
S.Uniform -> Uniform
S.Normal -> Normal
S.Sample e f -> Let (convert’ layout e) (convert’ layout’ (f tag))
where
(tag, layout’) = distTag layout
S.Unary op e1 -> Unary op (convert’ layout e1)
S.Binary op e1 e2 -> Binary op (convert’ layout e1) (convert’ layout e2)
S.Ternary S.If e1 e2 e3 -> If (convert’ layout e1) (convert’ layout e2) (convert
’ layout e3)
S.Lookup e p -> lookup layout e p
where
lookup :: Layout env env -> S.Dist S.Time -> S.Process a -> Intermediate env
a
lookup layout time process = case process of
p@(S.Prefix _ _ p’) ->
Prefix (usesTimeInProcess p’) (convert’ layout time) (accumulator
layout p)
S.Zip p1 p2 ->
Binary S.Pair (lookup layout time p1) (lookup layout time p2)
S.Closed f ->
convert’ layout (f time)
S.Trace p f ->
Split (lookup layout’ time (f tag))
where
(tag, layout’) = processTag layout p
S.TagP tag p ->
Use (project (size layout - tag - 1) layout) (lookup layout time p)
accumulator :: (S.Type a) => Layout env env -> S.Process a -> Accumulator
env a
accumulator layout process = case process of
S.Zip p1 p2 ->
let a1 = accumulator layout p1 in
let a2 = accumulator layout p2 in
Zip a1 a2
S.Prefix f e p ->
let accumulator’ = accumulator layout p in
let initialValue = convert’ layout e in
let (timeTag, layout’) = distTag layout in
let (accumulateTag, layout’’) = distTag layout’ in
let (valueTag, layout’’’) = distTag layout’’ in
let f’ = convert’ layout’’’ (f timeTag accumulateTag valueTag) in
let (useDt, useAccumulator, useProcess) = S.examine f in
let justWhen :: Bool -> a -> Maybe a
justWhen condition a = guard condition >> return a in
Accumulate f’ useDt (justWhen useAccumulator initialValue) (justWhen
useProcess accumulator’)
S.Trace p f -> Splitting (accumulator layout’ (f tag))
where
(tag, layout’) = processTag layout p
S.TagP tag p ->
Using (project (size layout - tag - 1) layout) (accumulator layout p
)
p@(S.Closed _) ->
let (tag, layout’) = distTag layout in
Expression (usesTimeInProcess p) (lookup layout’ tag p)
distTag :: S.Type a =>
Layout env env’ ->
(S.Dist a, Layout (env, a) (env’, a))
distTag layout = (S.TagD (size layout), increase layout ‘Push‘ Zero)
processTag :: S.Type a =>
Layout env env’ ->
S.Process a ->
(S.Process a, Layout (env, StdGen) (env’, StdGen))
processTag layout p = (S.TagP (size layout) p, increase layout ‘Push‘ Zero)
usesTimeInProcess :: S.Process a -> Bool
usesTimeInProcess process = case process of
S.Zip p1 p2 -> usesTimeInProcess p1 || usesTimeInProcess p2
S.Prefix _ _ p -> usesTimeInProcess p
S.Trace p f -> usesTimeInProcess (f p)
S.Closed f -> S.varUsedInDist 0 (f (S.TagD 0))
S.TagP _ p -> usesTimeInProcess p
stochastic :: Intermediate env a -> Bool
stochastic process = case process of
Uniform -> True
Normal -> True
Let e1 e2 -> stochastic e1 || stochastic e2
Constant _ -> False
Unary _ e1 -> stochastic e1
Binary _ e1 e2 -> stochastic e1 || stochastic e2
If e1 e2 e3 -> stochastic e1 || stochastic e2 || stochastic e3
Prefix _ e a -> stochastic e || stochasticAccumulator a
Variable _ -> False
Split e -> stochastic e
Use _ e -> False
stochasticAccumulator :: Accumulator env a -> Bool
stochasticAccumulator accumulator = case accumulator of
Accumulate e1 _ e2 a -> stochastic e1 || maybe False stochastic e2 || maybe
False stochasticAccumulator a
Zip a1 a2 -> stochasticAccumulator a1 || stochasticAccumulator a2
Expression _ e -> stochastic e
Splitting a -> stochasticAccumulator a
Using _ a -> stochasticAccumulator a
instance Show (Intermediate env a) where
show intermediate = case intermediate of
Uniform -> "uniform"
Normal -> "normal"
Let e1 e2 -> "(let " ++ show e1 ++ " in " ++ show e2 ++ ")"
Constant (S.Double value) -> show value
Constant (S.Bool value) -> show value
Unary op e1 -> "(" ++ show op ++ " (" ++ show e1 ++ "))"
Binary op e1 e2 -> "(" ++ show e1 ++ show op ++ show e2 ++ ")"
If e1 e2 e3 -> "(if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show
e3 ++ ")"
Variable index -> "x" ++ show index
Split e -> "(split (" ++ show e ++ "))"
Use index e -> "(use g" ++ show index ++ " within " ++ show e ++ ")"
Prefix usingTime e a -> "(prefix " ++ show usingTime ++ " " ++ show e ++ " "
++ show a ++ ")"
instance Show (Accumulator env a) where
show accumulator = case accumulator of
Accumulate f useDt d0 acc -> "(accumulate " ++ show f ++ " " ++ show useDt
++ " " ++ show d0 ++ " " ++ show acc ++ ")"
Zip acc1 acc2 -> "(accumulateZip " ++ show acc1 ++ " " ++ show acc2 ++ ")"
Expression _ p -> "(accumulateOther " ++ show p ++ ")"
Splitting p -> "(splitting " ++ show p ++ ")"
Using index p -> "(using " ++ show index ++ " " ++ show p ++ ")"
instance Show (Index env a) where
show = show . indexToInt
indexToInt :: Index env a -> Int
indexToInt Zero = 0
indexToInt (Succ n) = indexToInt n + 1
|
vbalalla/financial_contract_language
|
Language/Intermediate.hs
|
mit
| 8,979 | 390 | 59 | 1,611 | 4,040 | 2,038 | 2,002 | -1 | -1 |
{-# LANGUAGE PatternGuards, FlexibleContexts #-}
module Crystal.Post (postprocess, DeclExpr) where
import Control.Lens hiding (transform, transformM, universe)
import Control.Monad
import Control.Monad.Reader
import Control.Monad.Writer
import Data.List
import Data.Generics
import Data.Generics.Uniplate.Operations
import qualified Data.Map as M
import Crystal.AST
import Crystal.Config
import Crystal.Misc
import Crystal.Tuple
import Crystal.Type
type Decl = (Ident, Expr TLabel)
type DeclExpr = ([Decl], Expr TLabel)
postprocess :: Expr TLabel -> Step DeclExpr
postprocess = undoLetrec <=< undoLetLet
undoLetrec :: Expr TLabel -> Step DeclExpr
undoLetrec expr = do addDefines <- not `fmap` asks (^.cfgAnnotateLabels)
if addDefines
then return (decls, core)
else return ([], expr)
where (decls, core) = go expr
go (Expr _ (LetRec bnds bod)) = go bod & _1 %~ (bnds++)
go (Expr _ (Let bnds bod)) = go bod & _1 %~ (bnds++)
go e = ([], e)
undoLetLet :: Expr TLabel -> Step (Expr TLabel)
undoLetLet expr = do let (expr', ps) = runWriter $ transformM f expr
let ps' = M.map (inline ps') ps
return $ inline ps' expr'
where f e@(Expr l (Let [(id, app)] b)) =
case b of
Expr l' (If cond cons alt)
| isTmp && oneMention -> tell (M.singleton id app) >> return b
Expr l' (Let bnds bod)
| isTmp && oneMention -> tell (M.singleton id app) >> return b
| otherwise -> return $ Expr l (Let ((id, app) : bnds) bod)
Expr l' (Appl f args)
| isTmp && not (isRefTo "check" f) -> tell (M.singleton id app) >> return b
Expr _ (Ref id') | oneMention -> return app
_ -> return e
where isTmp = "tmp-" `isPrefixOf` id
oneMention = Just 1 == (M.lookup id =<< M.lookup l mentions)
f x = return x
mentions = computeMentions expr
computeMentions :: Expr TLabel -> M.Map TLabel (M.Map Ident Int)
computeMentions expr = mentionsMap
where mentionsMap = M.fromList [(l, mentions e)| Expr l e <- universeBi expr ]
mentions (Lit l) = M.empty
mentions (Ref r) = M.singleton r 1
mentions (Appl f args) = M.unionsWith (+) (m f : map m args)
mentions (If cond cons alt) = M.unionsWith (+) [m cond, m cons, m alt]
mentions (Let bnds bod) = M.unionsWith (+) (m bod : map (m . snd) bnds)
mentions (LetRec bnds bod) = M.unionsWith (+) (m bod : map (m . snd) bnds)
mentions (Lambda ids r bod) = m bod
mentions (Begin es) = M.unionsWith (+) (map m es)
m e = mentionsMap M.! (e ^. ann)
inline :: M.Map Ident (Expr TLabel) -> Expr TLabel -> Expr TLabel
inline m expr = transformBi f expr
where f (Expr _ (Ref var)) | Just expr' <- M.lookup var m = expr'
f x = x
|
Botje/crystal
|
Crystal/Post.hs
|
gpl-2.0
| 3,003 | 0 | 17 | 932 | 1,233 | 626 | 607 | 63 | 8 |
-- This file is part of economy.
--
-- economy 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.
--
-- economy 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 economy. If not, see <http://www.gnu.org/licenses/>.
module Arithmetics (arithmetics) where
import Test.Hspec
import Text.Parsec
import Data.Bifunctor
import Data.Either
type Number = Int
arithmetics :: String -> Either String Number
arithmetics = second doArithmetics . parseArithmetics
data Expr = Literal Number | Plus Expr Expr | Minus Expr Expr | Mult Expr Expr | Div Expr Expr
deriving (Show, Eq)
arithmeticsParser :: Parsec String st Expr
arithmeticsParser = spaces >> chainl1 (literal) (binaryOps) <* eof
where
binaryOps = choice [plusOp, minusOp, multOp, divOp]
plusOp = char '+' >> spaces >> return Plus
minusOp = char '-' >> spaces >> return Minus
multOp = char '*' >> spaces >> return Mult
divOp = char '/' >> spaces >> return Div
literal :: Parsec String st Expr
literal = do
sign <- option 1 (char '-' >> spaces >> return (-1))
n <- many1 digit
spaces
return $ Literal (sign * (read n))
parseArithmetics :: String -> Either String Expr
parseArithmetics = first show . parse arithmeticsParser "parsing arithmetics"
doArithmetics :: Expr -> Number
doArithmetics (Literal n) = n
doArithmetics (Plus a b) = doArithmetics a + doArithmetics b
doArithmetics (Minus a b) = doArithmetics a - doArithmetics b
doArithmetics (Mult a b) = doArithmetics a * doArithmetics b
doArithmetics (Div a b) = doArithmetics a `div` doArithmetics b
main :: IO ()
main = hspec $ do
describe "doArithmetics" $ do
it "calculates 7 to 7" $ do
doArithmetics (Literal 7) `shouldBe` 7
it "calculates 1+2 to 3" $ do
doArithmetics (Plus (Literal 1) (Literal 2)) `shouldBe` 3
it "calculates (1+2)+3 to 6" $ do
doArithmetics (Plus (Plus (Literal 1) (Literal 2)) (Literal 3)) `shouldBe` 6
it "calculates 1-2 to -1" $ do
doArithmetics (Minus (Literal 1) (Literal 2)) `shouldBe` -1
it "calculates (4-3)-(1-2) to 2" $ do
doArithmetics (Minus (Minus (Literal 4) (Literal 3)) (Minus (Literal 1) (Literal 2))) `shouldBe` 2
it "calculates 4*3" $ do
doArithmetics (Mult (Literal 4) (Literal 3)) `shouldBe` 12
it "calculates 2*(1-3)" $ do
doArithmetics (Mult (Literal 2) (Minus (Literal 1) (Literal 3))) `shouldBe` -4
it "calculates 15/3" $ do
doArithmetics (Div (Literal 15) (Literal 3)) `shouldBe` 5
it "truncates division: 1/2 = 0" $ do
doArithmetics (Div (Literal 1) (Literal 2)) `shouldBe` 0
describe "parseArithmetics" $ do
it "parses a lone digit" $ do
parseArithmetics "7" `shouldBe` Right (Literal 7)
it "parses a number" $ do
parseArithmetics "142" `shouldBe` Right (Literal 142)
it "parses a negative number" $ do
parseArithmetics "-17" `shouldBe` Right (Literal (-17))
it "parses a negative number (with a space): - 17" $ do
parseArithmetics "- 17" `shouldBe` Right (Literal (-17))
it "ignores whitespace before a number" $ do
parseArithmetics " \t 79" `shouldBe` Right (Literal 79)
it "ignores whitespace after a number" $ do
parseArithmetics "79 \t \n " `shouldBe` Right (Literal 79)
it "parses 1+2" $ do
parseArithmetics "1+2" `shouldBe` Right (Plus (Literal 1) (Literal 2))
it "ignores whitespace before +" $ do
parseArithmetics "1 \n \t +2" `shouldBe` Right (Plus (Literal 1) (Literal 2))
it "ignores whitespace after +" $ do
parseArithmetics "1+ \t \n 2" `shouldBe` Right (Plus (Literal 1) (Literal 2))
it "parses 1+2+3 left-associatively" $ do
parseArithmetics "1+2+3" `shouldBe` Right (Plus (Plus (Literal 1) (Literal 2)) (Literal 3))
it "parses 1-2" $ do
parseArithmetics "1-2" `shouldBe` Right (Minus (Literal 1) (Literal 2))
it "parses 1--2" $ do
parseArithmetics "1--2" `shouldBe` Right (Minus (Literal 1) (Literal (-2)))
it "parses -1--2" $ do
parseArithmetics "-1--2" `shouldBe` Right (Minus (Literal (-1)) (Literal (-2)))
it "parses 1-2+3 left-associatively" $ do
parseArithmetics "1-2+3" `shouldBe` Right (Plus (Minus (Literal 1) (Literal 2)) (Literal 3))
it "parses 1+2-3 left-associatively" $ do
parseArithmetics "1+2-3" `shouldBe` Right (Minus (Plus (Literal 1) (Literal 2)) (Literal 3))
it "parses 3*4" $ do
parseArithmetics "3*4" `shouldBe` Right (Mult (Literal 3) (Literal 4))
it "parses 1+2*3 left-associatively" $ do
parseArithmetics "1+2*3" `shouldBe` Right (Mult (Plus (Literal 1) (Literal 2)) (Literal 3))
it "parses 1*2-3 left-associatively" $ do
parseArithmetics "1*2-3" `shouldBe` Right (Minus (Mult (Literal 1) (Literal 2)) (Literal 3))
it "parses 1/2" $ do
parseArithmetics "1/2" `shouldBe` Right (Div (Literal 1) (Literal 2))
it "parses 1+2/3 left-associatively" $ do
parseArithmetics "1+2/3" `shouldBe` Right (Div (Plus (Literal 1) (Literal 2)) (Literal 3))
it "parses 1+2/3+4 left-associatively" $ do
parseArithmetics "1+2/3+4" `shouldBe` Right (Plus (Div (Plus (Literal 1) (Literal 2)) (Literal 3)) (Literal 4))
it "complains when faced with unknown characters: before a number" $ do
parseArithmetics "a2" `shouldSatisfy` isLeft
it "complains when faced with unknown characters: before a number (after an operator)" $ do
parseArithmetics "1+a2" `shouldSatisfy` isLeft
it "complains when faced with unknown characters: before an operator" $ do
parseArithmetics "1a+2" `shouldSatisfy` isLeft
it "complains when faced with unknown characters: after an operator" $ do
parseArithmetics "1+a2" `shouldSatisfy` isLeft
|
rootmos/economy
|
src/Arithmetics.hs
|
gpl-3.0
| 6,511 | 0 | 23 | 1,662 | 2,053 | 993 | 1,060 | 103 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module InputChecker(
checkArgs,
InputError(..)
)where
--import qualified Data.Text as T
--import System.Directory
data InputError = InputError String deriving (Show)
usageText :: String
usageText = "Usage: 2 file inputs"
errorText :: String
errorText = "Invalid error parameters!"
invalidInputText :: String
invalidInputText = errorText ++ " " ++ usageText
checkArgs :: [a] -> IO (Maybe InputError)
checkArgs [] = return $ Just error
where error = InputError invalidInputText
checkArgs (x:[]) = return $ Just error
where error = InputError invalidInputText
checkArgs (x:y:[]) = return Nothing
checkArgs (_:xs) = return $ Just error
where error = InputError invalidInputText
|
mkarpis/hdiff
|
src/InputChecker.hs
|
gpl-3.0
| 740 | 0 | 9 | 130 | 211 | 114 | 97 | 19 | 1 |
-- | Lexer for P
-- | Juan García Garland (Nov. 2016)
module Lexer where
import Exception
import Data.Char
-- | Some tokens have attributes
type Lexeme = String
-- | DataType for tokens
data Token = TProgram | TResult
| TLParen | TRParen
| TVar Lexeme | TZero
| TAssignSym | TSuc | TPred
| TWhile | TDo | TEnd | TSemicol
| TNeq0
deriving (Eq,Show)
-- | Scanning one token
scan :: String -> Exc (Token,String)
-- returns the parsed token and the modified input strean, or an error
scan ('P':'R':'O':'G':'R':'A':'M':xs) = return (TProgram,xs)
scan ('R':'E':'S':'U':'L':'T':' ':xs) = return (TResult,xs)
scan ('W':'H':'I':'L':'E':' ':xs) = return (TWhile,xs)
scan ('D':'O':' ':xs) = return (TDo,xs)
scan ('E':'N':'D':xs) = return (TEnd,xs)
scan ('S':'U':'C':xs) = return (TSuc,xs)
scan ('P':'R':'E':'D':xs) = return (TPred,xs)
scan (';':xs) = return (TSemicol,xs)
scan ('/':'=':' ':'0':xs) = return (TNeq0,xs)
scan (':':'=':xs) = return (TAssignSym,xs)
scan ('(':xs) = return (TLParen,xs)
scan (')':xs) = return (TRParen,xs)
scan ('X':xs) = return (TVar ("X"++idf) ,xs')
where idf = takeWhile isDigit xs
xs' = dropWhile isDigit xs
scan ('0':xs) = return (TZero,xs)
scan (' ':xs) = scan xs
--scan(d:xs) = if isDigit d
-- then return (TDigit [d],xs)
-- else fail "Error: No Parse"
-- | Scanning function.
lexer :: String -> Exc [Token]
lexer [] = return []
lexer inp = scan inp >>= \(tok,tail) ->
lexer tail >>= \toks ->
return (tok:toks)
-- | Testing
t1 = (extract . lexer) $ "PROGRAM (X12) WHILE DO () END"
t2 = (extract . lexer) $ "X23 PROGRAM (X12) WHILE DO () END"
|
jota191/PLang
|
src/Lexer.hs
|
gpl-3.0
| 1,718 | 0 | 13 | 409 | 722 | 395 | 327 | 36 | 1 |
{-# LANGUAGE CPP #-}
----------------------------------------------------------------------
-- |
-- Module : Text.TeX.Parser.Basic
-- Copyright : 2015-2017 Mathias Schenner,
-- 2015-2016 Language Science Press.
-- License : GPL-3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- Basic TeX parsers.
----------------------------------------------------------------------
module Text.TeX.Parser.Basic
( -- * Main document parser
texParser
-- * Basic TeXAtom parsers
, atoms
, atom
, plain
, command
, group
, env
, mathgroup
, subscript
, supscript
, white
-- * Argument parsers
, parseArgSpec
, arg
, oblarg
, optarg
, optargParens
) where
#if MIN_VERSION_base(4,8,0)
-- Prelude exports all required operators from Control.Applicative
#else
import Control.Applicative ((<*), (<*>), (*>), (<$), (<$>))
#endif
import Control.Monad (void)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe (catMaybes)
import Text.Parsec
((<|>), choice, optional, optionMaybe, many, many1,
count, between, (<?>), parserFail, eof)
import Text.TeX.Filter (argspecsSyntactic)
import Text.TeX.Lexer.Catcode
import Text.TeX.Lexer.Token
import Text.TeX.Parser.Core
import Text.TeX.Parser.Types
-- | Main 'TeX' document parser.
texParser :: TeXParser TeX
texParser = atoms <* eof
-- | Parse any number of TeXAtoms.
atoms :: TeXParser TeX
atoms = many atom
-- | Parse a single TeXAtom.
atom :: TeXParser TeXAtom
atom = atomExcept []
-- | Parse a single TeXAtom,
-- unless we hit a character from the specified blacklist.
atomExcept :: [Char] -> TeXParser TeXAtom
atomExcept blacklist =
choice [ plainExcept blacklist
, group, command, white, alignMark
, mathgroup, subscript, supscript]
-- | Parse the exact token.
token :: Token -> TeXParser Token
token = satisfy . (==)
-- | Parse subscripted content.
subscript :: TeXParser TeXAtom
subscript = SubScript <$> (charCC Subscript *> argbody)
-- | Parse superscripted content.
supscript :: TeXParser TeXAtom
supscript = SupScript <$> (charCC Supscript *> argbody)
-- | Parse an align tab.
alignMark :: TeXParser TeXAtom
alignMark = AlignMark <$ charCC AlignTab
-- | Parse a control sequence and return its name.
ctrlseq :: TeXParser String
ctrlseq = getName <$> satisfy isCtrlSeq
-- | Parse an active character and return its name.
activechar :: TeXParser String
activechar = getName <$> satisfy isActiveChar
-- | Parse a single character irrespective of its catcode.
char :: Char -> TeXParser TeXAtom
char c = Plain [c] <$ satisfy (isCharSat (== c))
-- | Parse a character with the specified catcode.
charCC :: Catcode -> TeXParser Token
charCC = satisfy . hasCC
-- | Parse a character if it has category code 'Letter' or 'Other'.
plainChar :: Char -> TeXParser TeXAtom
plainChar c = Plain [c] <$ satisfy (\t ->
isCharSat (== c) t && (hasCC Letter t || hasCC Other t))
-- | Parse a single letter or other.
anyPlainChar :: TeXParser TeXAtom
anyPlainChar = (Plain . map getRawChar) <$> count 1 (charCC Letter <|> charCC Other)
-- | Parse letters and others.
plain :: TeXParser TeXAtom
plain = (Plain . map getRawChar) <$> many1 (charCC Letter <|> charCC Other)
-- Parse letters and others except for the specified characters (blacklist).
plainExcept :: [Char] -> TeXParser TeXAtom
plainExcept blacklist = (Plain . map getRawChar) <$> many1 (satisfy (\t ->
(hasCC Letter t || hasCC Other t) &&
not (isCharSat (`elem` blacklist) t)))
-- | Parse intra-paragraph whitespace.
white :: TeXParser TeXAtom
white = White <$ many1 (charCC Space <|> charCC Eol)
-- | Parse a delimiter that opens a TeX group (begin group).
bgroup :: TeXParser ()
bgroup = void $ charCC Bgroup
-- | Parse a delimiter that closes a TeX group (end group).
egroup :: TeXParser ()
egroup = void $ charCC Egroup
-- | Parse an anonymous TeX group.
group :: TeXParser TeXAtom
group = Group "" [] <$> groupbody
-- | Parse the content of a group.
groupbody :: TeXParser TeX
groupbody = between bgroup egroup atoms
-- | Parse a TeX math group.
mathgroup :: TeXParser TeXAtom
mathgroup = charCC Mathshift *> (displaymath <|> inlinemath)
-- Parse an inline math group.
inlinemath :: TeXParser TeXAtom
inlinemath = MathGroup MathInline <$> mathInner
<* charCC Mathshift <?> "end of inline math"
-- Parse a display math group.
displaymath :: TeXParser TeXAtom
displaymath = MathGroup MathDisplay <$> (charCC Mathshift *> mathInner)
<* count 2 (charCC Mathshift) <?> "end of display math"
-- Parse the body of a math group.
-- Like 'atom' but without 'mathgroup'.
mathInner :: TeXParser [TeXAtom]
mathInner = many $ choice [plain, group, command, white, alignMark,
subscript, supscript]
-- Use this parser if you know the control sequence requires an argument.
-- (Like 'argbody' but wrapped in 'Arg'.)
-- | Parse an obligatory argument: the content of a group or a single atom.
arg :: TeXParser Arg
arg = OblArg <$> argbody
-- Note: This parser will fail on certain unexpected atoms
-- that are not allowed as bare (ungrouped) arguments to a command
-- (e.g. whitespace, align marks, math groups, superscripts, subscripts).
-- | Parse the content of an obligatory argument:
-- the content of a group or a single atom.
argbody :: TeXParser TeX
argbody = choice
[ groupbody
, count 1 anyPlainChar
, count 1 command
]
-- Use this parser as a heuristic to eat up possible obligatory
-- arguments of unknown control sequences.
-- | Parse an obligatory group argument: the content of a group.
oblarg :: TeXParser Arg
oblarg = OblArg <$> groupbody
-- | Parse a traditional-style optional argument in square brackets.
optarg :: TeXParser Arg
optarg = optargBetween '[' ']'
-- | Parse an optional argument between parentheses.
optargParens :: TeXParser Arg
optargParens = optargBetween '(' ')'
-- | Parse an optional argument between custom delimiter characters.
optargBetween :: Char -> Char -> TeXParser Arg
optargBetween open close = OptArg <$> balanced open close
-- | Try to parse a 'StarArg'.
maybeStar :: TeXParser (Maybe Arg)
maybeStar = optionMaybe (StarArg <$ token (mkOther '*'))
-- | Parse a control sequence or an active character.
command :: TeXParser TeXAtom
command = commandCtrlseq <|> commandActiveChar
-- | Parse an active character.
commandActiveChar :: TeXParser TeXAtom
commandActiveChar = activechar >>= processActiveChar
-- Interpret an active character.
processActiveChar :: String -> TeXParser TeXAtom
processActiveChar name = case name of
"~" -> return (Plain "\x00A0") -- NO-BREAK SPACE
_ -> parserFail ("Encountered unknown active character: " ++ name)
-- | Parse a control sequence.
commandCtrlseq :: TeXParser TeXAtom
commandCtrlseq = ctrlseq >>= processCtrlseq
-- Interpret a control sequence.
processCtrlseq :: String -> TeXParser TeXAtom
processCtrlseq name = case name of
"par" -> return Par
" " -> return White -- control space
"\n" -> return White -- control newline
"\\" -> optional optarg *> return Newline
"begin" -> env
_ -> do
args <- maybe parseUnknownArgSpec parseArgSpec (M.lookup name commandDB)
return (Command name args)
-- Lookup table for the 'ArgSpec' of known commands.
commandDB :: Map String ArgSpec
commandDB = M.unions [ M.map toArgSpec argspecsSyntactic
, M.map toArgSpec argspecsSemantic
, argspecsCitation
, argspecsSectioning]
where
argspecsSemantic = M.fromList
[ -- Plain TeX
("rm", (0,0))
, ("it", (0,0))
-- LaTeX
, ("item", (1,0))
, ("textrm", (0,1))
, ("textit", (0,1))
, ("label", (0,1))
, ("caption", (0,1))
, ("centering", (0,0))
, ("multicolumn", (0,3))
, ("frontmatter", (0,0))
, ("mainmatter", (0,0))
, ("appendix", (0,0))
, ("backmatter", (0,0))
-- hyperref
, ("href", (0,2))
, ("url", (0,1))
-- graphicx
, ("includegraphics", (1,1))
]
argspecsCitation = M.fromList $ zip
[ -- biblatex
"cite"
, "parencite"
, "textcite"
, "citeauthor"
, "citeyear"
, "nocite"
-- natbib
, "citet"
, "citep"
, "citealt"
, "citealp"
] (repeat [OptionalStar, Optional, Optional, Mandatory])
argspecsSectioning = M.fromList $ zip
[ -- LaTeX
"part"
, "chapter"
, "section"
, "subsection"
, "subsubsection"
, "paragraph"
, "subparagraph"
-- KOMA-script
, "addpart"
, "addchap"
, "addsec"
] (repeat [OptionalStar, Optional, Mandatory])
-- Lookup table for the 'ArgSpec' of known environments.
envDB :: Map String ArgSpec
envDB = M.map toArgSpec $ M.fromList
[ -- LaTeX
("document", (0,0))
, ("quotation", (0,0))
, ("center", (0,0))
, ("figure", (1,0))
, ("table", (1,0))
, ("tabular", (1,1))
]
-- | Parse a given 'ArgSpec'.
parseArgSpec :: ArgSpec -> TeXParser Args
parseArgSpec = fmap catMaybes . mapM parseArgType
-- Parse a given 'ArgType'.
parseArgType :: ArgType -> TeXParser (Maybe Arg)
parseArgType Mandatory = Just <$> arg
parseArgType Optional =
parseArgType (OptionalGroup '[' ']')
parseArgType (OptionalGroup open close) =
optionMaybe (optargBetween open close)
parseArgType OptionalStar = maybeStar
-- | Parse a balanced group of tokens between the
-- provided opening and closing characters.
-- The (outermost) delimiters are not included in the result.
balanced :: Char -> Char -> TeXParser TeX
balanced open close = plainChar open *> balancedEnd
where
-- Keeps delimiters.
balancedInner :: TeXParser TeX
balancedInner = (:) <$> plainChar open <*> balancedInnerEnd
-- Skips delimiters.
balancedEnd :: TeXParser TeX
balancedEnd = ([] <$ plainChar close) <|>
((++) <$> (balancedInner <|>
count 1 (atomExcept [open,close]))
<*> balancedEnd)
-- Keeps delimiters.
balancedInnerEnd :: TeXParser TeX
balancedInnerEnd = count 1 (plainChar close) <|>
((++) <$> (balancedInner <|>
count 1 (atomExcept [open,close]))
<*> balancedInnerEnd)
-- Heuristic for arguments of unknown control sequences: consume any
-- number of subsequent tokens that look like optional or obligatory
-- arguments, optionally prefixed by a star, think: @\\*([...])*({...})*@.
parseUnknownArgSpec :: TeXParser Args
parseUnknownArgSpec = do
star <- maybeStar
opt <- many optarg
obl <- many oblarg
return $ maybe id (:) star (opt ++ obl)
-- | Parse the name of an environment.
envName :: TeXParser String
envName = map getRawChar <$> between bgroup egroup
(many1 (charCC Letter <|> charCC Other))
-- | Parse an environment.
env :: TeXParser TeXAtom
env = do
name <- envName
args <- maybe parseUnknownArgSpec parseArgSpec (M.lookup name envDB)
body <- envInner name
return (Group name args body)
-- Parse the body of an environment.
envInner :: String -> TeXParser [TeXAtom]
envInner name = commandEnvInner name <|> ((:) <$>
-- like 'atom' but without 'commandCtrlseq' (in 'command')
choice [plain, group, commandActiveChar, white, alignMark,
mathgroup, subscript, supscript] <*>
envInner name)
-- Parse a command (control sequence) inside the body of an environment.
commandEnvInner :: String -> TeXParser [TeXAtom]
commandEnvInner name = do
cname <- ctrlseq
if cname == "end"
then between bgroup egroup
(mapM_ char name <?> "\\end{" ++ name ++ "}")
*> return []
else (:) <$> processCtrlseq cname <*> envInner name
|
synsem/texhs
|
src/Text/TeX/Parser/Basic.hs
|
gpl-3.0
| 11,781 | 0 | 16 | 2,566 | 2,704 | 1,514 | 1,190 | 237 | 6 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Logging.Folders.Locations.Buckets.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists buckets.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.folders.locations.buckets.list@.
module Network.Google.Resource.Logging.Folders.Locations.Buckets.List
(
-- * REST Resource
FoldersLocationsBucketsListResource
-- * Creating a Request
, foldersLocationsBucketsList
, FoldersLocationsBucketsList
-- * Request Lenses
, flblParent
, flblXgafv
, flblUploadProtocol
, flblAccessToken
, flblUploadType
, flblPageToken
, flblPageSize
, flblCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.folders.locations.buckets.list@ method which the
-- 'FoldersLocationsBucketsList' request conforms to.
type FoldersLocationsBucketsListResource =
"v2" :>
Capture "parent" Text :>
"buckets" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListBucketsResponse
-- | Lists buckets.
--
-- /See:/ 'foldersLocationsBucketsList' smart constructor.
data FoldersLocationsBucketsList =
FoldersLocationsBucketsList'
{ _flblParent :: !Text
, _flblXgafv :: !(Maybe Xgafv)
, _flblUploadProtocol :: !(Maybe Text)
, _flblAccessToken :: !(Maybe Text)
, _flblUploadType :: !(Maybe Text)
, _flblPageToken :: !(Maybe Text)
, _flblPageSize :: !(Maybe (Textual Int32))
, _flblCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FoldersLocationsBucketsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'flblParent'
--
-- * 'flblXgafv'
--
-- * 'flblUploadProtocol'
--
-- * 'flblAccessToken'
--
-- * 'flblUploadType'
--
-- * 'flblPageToken'
--
-- * 'flblPageSize'
--
-- * 'flblCallback'
foldersLocationsBucketsList
:: Text -- ^ 'flblParent'
-> FoldersLocationsBucketsList
foldersLocationsBucketsList pFlblParent_ =
FoldersLocationsBucketsList'
{ _flblParent = pFlblParent_
, _flblXgafv = Nothing
, _flblUploadProtocol = Nothing
, _flblAccessToken = Nothing
, _flblUploadType = Nothing
, _flblPageToken = Nothing
, _flblPageSize = Nothing
, _flblCallback = Nothing
}
-- | Required. The parent resource whose buckets are to be listed:
-- \"projects\/[PROJECT_ID]\/locations\/[LOCATION_ID]\"
-- \"organizations\/[ORGANIZATION_ID]\/locations\/[LOCATION_ID]\"
-- \"billingAccounts\/[BILLING_ACCOUNT_ID]\/locations\/[LOCATION_ID]\"
-- \"folders\/[FOLDER_ID]\/locations\/[LOCATION_ID]\" Note: The locations
-- portion of the resource must be specified, but supplying the character -
-- in place of LOCATION_ID will return all buckets.
flblParent :: Lens' FoldersLocationsBucketsList Text
flblParent
= lens _flblParent (\ s a -> s{_flblParent = a})
-- | V1 error format.
flblXgafv :: Lens' FoldersLocationsBucketsList (Maybe Xgafv)
flblXgafv
= lens _flblXgafv (\ s a -> s{_flblXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
flblUploadProtocol :: Lens' FoldersLocationsBucketsList (Maybe Text)
flblUploadProtocol
= lens _flblUploadProtocol
(\ s a -> s{_flblUploadProtocol = a})
-- | OAuth access token.
flblAccessToken :: Lens' FoldersLocationsBucketsList (Maybe Text)
flblAccessToken
= lens _flblAccessToken
(\ s a -> s{_flblAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
flblUploadType :: Lens' FoldersLocationsBucketsList (Maybe Text)
flblUploadType
= lens _flblUploadType
(\ s a -> s{_flblUploadType = a})
-- | Optional. If present, then retrieve the next batch of results from the
-- preceding call to this method. pageToken must be the value of
-- nextPageToken from the previous response. The values of other method
-- parameters should be identical to those in the previous call.
flblPageToken :: Lens' FoldersLocationsBucketsList (Maybe Text)
flblPageToken
= lens _flblPageToken
(\ s a -> s{_flblPageToken = a})
-- | Optional. The maximum number of results to return from this request.
-- Non-positive values are ignored. The presence of nextPageToken in the
-- response indicates that more results might be available.
flblPageSize :: Lens' FoldersLocationsBucketsList (Maybe Int32)
flblPageSize
= lens _flblPageSize (\ s a -> s{_flblPageSize = a})
. mapping _Coerce
-- | JSONP
flblCallback :: Lens' FoldersLocationsBucketsList (Maybe Text)
flblCallback
= lens _flblCallback (\ s a -> s{_flblCallback = a})
instance GoogleRequest FoldersLocationsBucketsList
where
type Rs FoldersLocationsBucketsList =
ListBucketsResponse
type Scopes FoldersLocationsBucketsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient FoldersLocationsBucketsList'{..}
= go _flblParent _flblXgafv _flblUploadProtocol
_flblAccessToken
_flblUploadType
_flblPageToken
_flblPageSize
_flblCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy FoldersLocationsBucketsListResource)
mempty
|
brendanhay/gogol
|
gogol-logging/gen/Network/Google/Resource/Logging/Folders/Locations/Buckets/List.hs
|
mpl-2.0
| 6,652 | 0 | 18 | 1,455 | 899 | 525 | 374 | 130 | 1 |
-- TODO: Refactor Betty.Signup, make it testable, and actually test
-- that piece of code instead of this isolated code.
module SESSpec (spec) where
import TestImport
#if USE_AWS_SES
import Betty.SESCreds (access, ender, secret, sender)
import Control.Monad.Trans.Resource (runResourceT)
import Network.HTTP.Conduit (newManager, tlsManagerSettings)
import Network.Mail.Mime
import Network.Mail.Mime.SES
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Yesod
-- TODO: refactor to correctly use Betty.Signup.SES
spec :: Spec
spec = withApp $ do
describe "SES Email test" $ do
-- TODO: this is not particularly useful when SES credentials
-- aren't available; fix.
it "Trying to send email using SES" $ do
runResourceT $ do
manager <- liftIO $ newManager tlsManagerSettings
renderSendMailSES manager ses mail
ses :: SES
ses = SES { sesFrom = sender
, sesTo = [ender]
, sesAccessKey = access
, sesSecretKey = secret
, sesRegion = "us-east-1"
}
mail :: Mail
mail = Mail { mailHeaders = [("Subject", "Testing SES")]
, mailFrom = Address Nothing sender
, mailTo = [Address Nothing ender]
, mailCc = []
, mailBcc = []
, mailParts = return [textpart, htmlpart]
}
textpart :: Part
textpart = Part "text/plain" None Nothing [] $
"This is the text part."
htmlpart :: Part
htmlpart = Part "text/html" None Nothing [] $
renderHtml $ toHtml ("This is the HTML part." :: String)
#else
spec :: Spec
spec = withApp $
describe "SES Email test" $
it "Not configured to use SES, skipping test" $
assertEq "Nothing" True True
#endif
|
sajith/betty-web
|
test/SESSpec.hs
|
agpl-3.0
| 1,834 | 0 | 19 | 552 | 350 | 206 | 144 | 7 | 1 |
module ViperVM.Library.OpenCL.FloatMatrixMul where
import ViperVM.Backends.OpenCL.Program
import ViperVM.Backends.OpenCL.Kernel
import ViperVM.Common.Util (roundTo)
import Paths_ViperVM
program :: IO Program
program = do
fileName <- getDataFileName "lib/ViperVM/Library/OpenCL/FloatMatrixMul.cl"
src <- readFile fileName
initProgram src
kernel :: IO Kernel
kernel = do
prog <- program
initKernel prog "floatMatrixMul" [] config
-- | Configure kernel execution
config :: [CLKernelParameter] -> KernelConfiguration
config pms = KernelConfiguration gDim lDim pms
where
[CLUIntParam width, CLUIntParam height,_,_,_,_,_,_,_,_,_,_] = pms
gDim = [roundTo 16 width, roundTo 16 height,1]
lDim = [16,16,1]
|
hsyl20/HViperVM
|
lib/ViperVM/Library/OpenCL/FloatMatrixMul.hs
|
lgpl-3.0
| 736 | 0 | 8 | 119 | 225 | 125 | 100 | 19 | 1 |
{-# LANGUAGE TemplateHaskell, KindSignatures, DataKinds, PolyKinds, TypeFamilies, UndecidableInstances, GADTs, AllowAmbiguousTypes #-}
module BackwardsStateMonad where
import Data.Singletons.TH
import Data.Singletons.Prelude
$(promote [d|
data Nat = Zero | Succ Nat
bind :: (Nat -> (Foo, Nat)) -> (Foo -> Nat -> (Foo, Nat)) -> (Nat -> (Foo, Nat))
bind m k s2 = let r1 :: (Foo, Nat)
r1 = m (snd r2)
r2 :: (Foo, Nat)
r2 = k (fst r1) s2
in ((fst r2), (snd r1))
{-
bind m k s2 = let (a,s0) = m s1
(b,s1) = k a s2
in (b, s0)
-}
-- m `bind` k = \s2 -> let (a,s0) = m s1
-- (b,s1) = k a s2
-- in (b,s0)
data Foo = Foo
m :: Nat -> (Foo, Nat)
m n = (Foo, Succ n)
k :: Foo -> Nat -> (Foo, Nat)
k a n = (a, Succ n)
bar :: Nat -> (Foo, Nat)
bar p = (bind m k) p
|])
instance Show Nat where
show Zero = "Zero"
show (Succ n) = "Succ (" ++ show n ++ ")"
instance Show Foo where
show _ = "Foo"
baz1a :: Proxy (Bar Zero)
baz1a = Proxy
baz1b :: Proxy '( 'Foo, Succ (Succ Zero))
baz1b = baz1a
|
jstolarek/sandbox
|
haskell/singletons/BackwardsStateMonad.hs
|
unlicense
| 1,161 | 0 | 10 | 394 | 139 | 75 | 64 | 28 | 1 |
module P9x.P00.P00_ (
myLast', myLast'', myLast''', myLast'''', myLast''''',
myButLast, myButLast', myButLast'', myButLast''', myButLast'''', lastbut1, lastbut1safe,
elementAt, elementAt', elementAt'', elementAt''', elementAt_w'pf,
myLength, myLength1', myLength2', myLength3', myLength4', myLength5', myLength6', myLength1'', myLength2'', myLength3'',
reverse', reverse'', reverse''', reverse'''',
isPalindrome, isPalindrome'1, isPalindrome'2, isPalindrome'3, isPalindrome'4, isPalindrome'5, isPalindrome'6, isPalindrome'7,
NestedList(..), nestedList, flatten, flatten', flatten'2, flatten'3, flatten'4, flatten'5, flatten'6,
compress, compress', compress'2, compress'3, compress'4, compress'5, compress'6, compress'7,
pack, pack', pack'2, pack'3, pack'4, pack'5,
encode, encode', encode'2, encode'3, encode'4, encode'5, encode'6, encode'7,
ListItem(..), encodeModified, encodeModified',
decode, decode', decode'2,
decodeModified, decodeModified', decodeModified'2, decodeModified'3,
encodeDirect, encodeDirect',
dupli, dupli', dupli'2, dupli'3, dupli'4, dupli'5, dupli'6, dupli'7, dupli'8, dupli'9,
repli, repli', repli'2, repli'3,
dropEvery, dropEvery', dropEvery'2, dropEvery'3, dropEvery'4, dropEvery'5, dropEvery'6, dropEvery'7, dropEvery'8, dropEvery'9, dropEvery'10,
split, split', split'2, split'3, split'4, split'5, split'6, split'7,
slice, slice'2, slice'3, slice'4, slice'5, slice'6,
rotate, rotate', rotate'2, rotate'3, rotate'4, rotate'5, rotate'6, rotate'7,
removeAt, removeAt', removeAt'2, removeAt'3, removeAt'4,
insertAt, insertAt', insertAt'', insertAt''',
range, range2, range3, range4, range5, range6,
rnd_select, rnd_select2, rnd_select3, rnd_select4, rnd_select5,
diff_select, diff_select2, diff_select3, diff_select4, diff_select5,
rnd_perm2, rnd_perm3, rnd_perm4,
combinations, combinations2, combinations3, combinations4, combinations5, combinations6, combinations7,
groupSubsets, groupSubsets2, groupSubsets3,
lsort, lsort2, lsort3, lsort4, lfsort, lfsort2, lfsort3, lfsort4, lfsort5,
isPrime, isPrime2,
myGCD, myGCD2, coprime,
totient, totient2, totient3
) where
import Data.Foldable(Foldable, foldMap)
import Data.Function(on)
import Control.Monad(liftM2)
import Control.Applicative((<*>), (<$>), (<**>))
import Control.Arrow((&&&))
import Data.List(group, findIndex, nub, permutations, tails, subsequences, sort, sortBy, sortOn, groupBy, union)
import Data.Ord (comparing)
import GHC.Exts(build)
import System.Random(RandomGen, StdGen, getStdRandom, randomR, randomRIO, randomRs, getStdGen)
import Control.Monad(replicateM)
import Control.Arrow ((>>>), (&&&), second)
import GHC.Exts (sortWith)
import Data.Ratio
-- solutions from https://wiki.haskell.org/99_questions
-- P01
myLast' :: [a] -> a
myLast' = foldr1 (const id)
myLast'' :: [a] -> a
myLast'' = foldr1 (flip const)
myLast''' = head . reverse
myLast'''' :: [a] -> a
myLast'''' = foldl1 (curry snd)
myLast''''' [] = error "No end for empty lists!"
myLast''''' x = x !! (length x - 1)
-- P02
myButLast :: [a] -> a
myButLast = last . init
myButLast' x = reverse x !! 1
myButLast'' [x,_] = x
myButLast'' (_:xs) = myButLast'' xs
myButLast''' (x:(_:[])) = x
myButLast''' (_:xs) = myButLast''' xs
myButLast'''' = head . tail . reverse
lastbut1 :: Foldable f => f a -> a
lastbut1 = fst . foldl (\(_,b) x -> (b,x)) (err1,err2)
where
err1 = error "lastbut1: Empty list"
err2 = error "lastbut1: Singleton"
lastbut1safe :: Foldable f => f a -> Maybe a
lastbut1safe = fst . foldl (\(_,b) x -> (b,Just x)) (Nothing,Nothing)
-- P03
elementAt :: Int -> [a] -> a
elementAt i list = list !! i
elementAt' :: Int -> [a] -> a
elementAt' 0 (x:_) = x
elementAt' i (_:xs) = elementAt' (i - 1) xs
elementAt' _ _ = error "Index out of bounds"
elementAt'' n xs
| length xs < n = error "Index out of bounds"
| otherwise = fst . last $ zip xs [0..n]
elementAt''' n xs = head $ foldr ($) xs $ replicate n tail
elementAt_w'pf = (last .) . take . (+ 1)
-- P04
myLength :: [a] -> Int
myLength list = myLength_acc list 0
where
myLength_acc [] n = n
myLength_acc (_:xs) n = myLength_acc xs (n + 1)
myLength1' = foldl (\n _ -> n + 1) 0 :: [a] -> Int
myLength2' = foldr (\_ n -> n + 1) 0 :: [a] -> Int
myLength3' = foldr (\_ -> (+1)) 0 :: [a] -> Int
myLength4' = foldr ((+) . (const 1)) 0 :: [a] -> Int
myLength5' = foldr (const (+1)) 0 :: [a] -> Int
myLength6' = foldl (const . (+1)) 0 :: [a] -> Int
myLength1'' xs = snd $ last $ zip xs [1..] -- Just for fun
myLength2'' = snd . last . (flip zip [1..]) :: [a] -> Int -- Because point-free is also fun
myLength3'' = fst . last . zip [1..] :: [a] -> Int -- same, but easier
-- P05
reverse' :: [a] -> [a]
reverse' = foldl (flip (:)) []
reverse'' :: [a] -> [a]
reverse'' [] = []
reverse'' (x:xs) = reverse'' xs ++ [x]
reverse''' :: [a] -> [a]
reverse''' list = reverse_ list []
where
reverse_ [] reversed = reversed
reverse_ (x:xs) reversed = reverse_ xs (x:reversed)
reverse'''' :: [a] -> [a]
reverse'''' xs = foldr (\x fId empty -> fId (x : empty)) id xs []
-- P06
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = xs == (reverse xs)
isPalindrome'1 :: (Eq a) => [a] -> Bool
isPalindrome'1 [] = True
isPalindrome'1 [_] = True
isPalindrome'1 xs = (head xs) == (last xs) && (isPalindrome'1 $ init $ tail xs)
isPalindrome'2 :: (Eq a) => [a] -> Bool -- this seems to be just more vebose version of isPalindrome
isPalindrome'2 xs = foldl (\acc (a,b) -> if a == b then acc else False) True input
where input = zip xs (reverse xs)
isPalindrome'3 :: (Eq a) => [a] -> Bool
isPalindrome'3 = Control.Monad.liftM2 (==) id reverse
isPalindrome'4 :: (Eq a) => [a] -> Bool
isPalindrome'4 = (==) Control.Applicative.<*> reverse
isPalindrome'5 :: (Eq a) => [a] -> Bool
isPalindrome'5 xs = p [] xs xs
where p rev (x:xs) (_:_:ys) = p (x:rev) xs ys
p rev (_:xs) [_] = rev == xs
p rev xs [] = rev == xs
isPalindrome'6 :: (Eq a) => [a] -> Bool
isPalindrome'6 xs = and $ zipWith (==) xs (reverse xs)
isPalindrome'7 :: (Eq a) => [a] -> Bool
isPalindrome'7 xs = (uncurry (==) . (id &&& reverse)) xs
-- P07
data NestedList a = Elem a | List[NestedList a] deriving (Show, Eq)
nestedList :: [a] -> NestedList a
nestedList xs = List $ (\it -> Elem it) `map` xs
flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List x) = concatMap flatten x
flatten' :: NestedList a -> [a]
flatten' (Elem a) = [a]
flatten' (List (x:xs)) = flatten' x ++ flatten' (List xs)
flatten' (List []) = []
flatten'2 :: NestedList a -> [a]
flatten'2 (Elem x) = return x
flatten'2 (List x) = flatten'2 =<< x
flatten'3 :: NestedList a -> [a]
flatten'3 (Elem x) = [x]
flatten'3 (List x) = foldMap flatten'3 x
flatten'4 :: NestedList a -> [a]
flatten'4 a = flt' a []
where flt' (Elem x) xs = x:xs
flt' (List (x:ls)) xs = flt' x (flt' (List ls) xs)
flt' (List []) xs = xs
flatten'5 :: NestedList a -> [a] -- same as version with concatMap above
flatten'5 (Elem x ) = [x]
flatten'5 (List xs) = foldr (++) [] $ map flatten'5 xs
flatten'6 :: NestedList a -> [a]
flatten'6 = reverse . rec []
where rec acc (List []) = acc
rec acc (Elem x) = x:acc
rec acc (List (x:xs)) = rec (rec acc x) (List xs)
-- P08
compress :: Eq a => [a] -> [a]
compress = map head . group
compress' :: Eq a => [a] -> [a]
compress' (x:ys@(y:_))
| x == y = compress' ys
| otherwise = x : compress' ys
compress' ys = ys
compress'2 xs = (foldr f (const []) xs) Nothing
where
f x r a@(Just q) | x == q = r a
f x r _ = x : r (Just x)
compress'3 :: Eq a => [a] -> [a]
compress'3 = foldr skipDups []
where skipDups x [] = [x]
skipDups x acc
| x == head acc = acc
| otherwise = x : acc
compress'4 [] = []
compress'4 (x:xs) = x : (compress'4 $ dropWhile (== x) xs)
compress'5 xs = foldr (\a b -> if a == (head b) then b else a:b) [last xs] xs
compress'6 x = foldl (\a b -> if (last a) == b then a else a ++ [b]) [head x] x
compress'7 x = reverse $ foldl (\a b -> if (head a) == b then a else b:a) [head x] x
-- P09
pack :: Eq a => [a] -> [[a]]
pack [] = []
pack (x:xs) = let (first,rest) = span (==x) xs
in (x:first) : pack rest
pack' :: Eq a => [a] -> [[a]]
pack' [] = []
pack' (x:xs) = (x:first) : pack' rest
where
getReps [] = ([], [])
getReps (y:ys)
| y == x = let (f,r) = getReps ys in (y:f, r)
| otherwise = ([], (y:ys))
(first, rest) = getReps xs
pack'2 :: Eq a => [a] -> [[a]]
pack'2 [] = []
pack'2 (x:xs) = (x:reps) : (pack'2 rest)
where
(reps, rest) = maybe (xs,[]) (\i -> splitAt i xs)
(findIndex (/=x) xs)
pack'3 :: (Eq a) => [a] -> [[a]]
pack'3 [] = []
pack'3 (x:xs) = (x : takeWhile (==x) xs) : pack (dropWhile (==x) xs)
pack'4 :: (Eq a) => [a] -> [[a]]
pack'4 [] = []
pack'4 [x] = [[x]]
pack'4 (x:xs) = if x `elem` (head (pack'4 xs))
then (x:(head (pack'4 xs))):(tail (pack'4 xs))
else [x]:(pack'4 xs)
pack'5 :: (Eq a) => [a] -> [[a]]
pack'5 [] = []
pack'5 (y:ys) = reverse $ impl ys [[y]]
where
impl [] packed = packed
impl (x:xs) p@(z:zs)
| x == (head z) = impl xs ((x:z):zs)
| otherwise = impl xs ([x]:p)
-- P10
encode :: Eq a => [a] -> [(Int, a)]
encode xs = map (\x -> (length x, head x)) (group xs)
encode' :: Eq a => [a] -> [(Int, a)]
encode' = map (\x -> (length x, head x)) . group
encode'2 :: Eq a => [a] -> [(Int, a)]
encode'2 xs = map (length &&& head) $ group xs
encode'3 :: Eq a => [a] -> [(Int, a)]
encode'3 = map ((,) <$> length <*> head) . pack
encode'4 :: Eq a => [a] -> [(Int, a)]
encode'4 xs = (enc . pack) xs
where enc = foldr (\x acc -> (length x, head x) : acc) []
encode'5 :: Eq a => [a] -> [(Int, a)]
encode'5 [] = []
encode'5 (x:xs) = (length $ x : takeWhile (==x) xs, x)
: encode'5 (dropWhile (==x) xs)
encode'6 :: Eq a => [a] -> [(Int, a)]
encode'6 [] = []
encode'6 (x:xs) = encode'' 1 x xs
where encode'' n x [] = [(n, x)]
encode'' n x (y:ys)
| x == y = encode'' (n + 1) x ys
| otherwise = (n, x) : encode'' 1 y ys
encode'7 :: Eq a => [a] -> [(Int, a)]
encode'7 xs = zip (map length l) h
where l = group xs
h = map head l
-- P11
data ListItem a = Single a | Multiple Int a deriving (Show, Eq)
encodeModified :: Eq a => [a] -> [ListItem a]
encodeModified = map encodeHelper . encode
where
encodeHelper (1,x) = Single x
encodeHelper (n,x) = Multiple n x
encodeModified' :: Eq a => [a] -> [ListItem a]
encodeModified' xs = [y | x <- group xs,
let y = if (length x) == 1 then
Single (head x) else
Multiple (length x) (head x)]
-- P12
decodeModified :: [ListItem a] -> [a]
decodeModified = concatMap decodeHelper
where
decodeHelper (Single x) = [x]
decodeHelper (Multiple n x) = replicate n x
decode :: Eq a => [(Int, a)] -> [a]
decode = concatMap (uncurry replicate)
toTuple :: ListItem a -> (Int, a)
toTuple (Single x) = (1, x)
toTuple (Multiple n x) = (n, x)
decodeModified' :: [ListItem a] -> [a]
decodeModified' = concatMap (uncurry replicate . toTuple)
decodeModified'2 :: [ListItem a]-> [a]
decodeModified'2 = foldl (\x y -> x ++ decodeHelper y) []
where decodeHelper :: ListItem a -> [a]
decodeHelper (Single x) = [x]
decodeHelper (Multiple n x) = replicate n x
decodeModified'3 :: [ListItem a] -> [a]
decodeModified'3 = (\acc e ->
case e of
Single x -> acc ++ [x]
Multiple n x -> acc ++ replicate n x
) `foldl` []
decode' :: Eq a => [(Int,a)] -> [a]
decode' xs = foldr f [] xs
where f (1, x) r = x : r
f (k, x) r = x : f (k-1, x) r
{-# INLINE decode #-}
decode'2 :: Eq a => [(Int,a)] -> [a]
decode'2 xs = build (\c n ->
let
f (1, x) r = x `c` r
f (k, x) r = x `c` f (k-1, x) r
in
foldr f n xs)
-- P13
encodeDirect :: (Eq a) => [a] -> [ListItem a]
encodeDirect [] = []
encodeDirect (x:xs) = encodeDirect_ 1 x xs
encodeDirect_ n y [] = [encodeElement n y]
encodeDirect_ n y (x:xs) | y == x = encodeDirect_ (n+1) y xs
| otherwise = encodeElement n y : (encodeDirect_ 1 x xs)
encodeElement 1 y = Single y
encodeElement n y = Multiple n y
encodeDirect' :: (Eq a)=> [a] -> [ListItem a]
encodeDirect' [] = []
encodeDirect' (x:xs)
| count == 1 = (Single x) : (encodeDirect' xs)
| otherwise = (Multiple count x) : (encodeDirect' rest)
where
(matched, rest) = span (==x) xs
count = 1 + (length matched)
-- P14
dupli :: [a] -> [a]
dupli [] = []
dupli (x:xs) = x:x:dupli xs
dupli' list = concat [[x,x] | x <- list]
dupli'2 xs = xs >>= (\x -> [x,x])
dupli'3 = (<**> [id,id])
dupli'4 :: [a] -> [a]
dupli'4 = concatMap (\x -> [x,x])
dupli'5 :: [a] -> [a]
dupli'5 = concatMap (replicate 2)
dupli'6 :: [a] -> [a]
dupli'6 = foldl (\acc x -> acc ++ [x,x]) []
dupli'7 :: [a] -> [a]
dupli'7 = foldr (\ x xs -> x : x : xs) []
dupli'8 :: [a] -> [a]
dupli'8 = foldr (\x -> (x:) . (x:)) []
dupli'9 :: [a] -> [a]
dupli'9 = foldr ((.) <$> (:) <*> (:)) []
-- P15
repli :: [a] -> Int -> [a]
repli xs n = concatMap (replicate n) xs
repli' :: [a] -> Int -> [a]
repli' = flip $ concatMap . replicate
repli'2 :: [a] -> Int -> [a]
repli'2 xs n = concatMap (take n . repeat) xs
repli'3 :: [a] -> Int -> [a]
repli'3 xs n = xs >>= replicate n
-- P16
dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery (x:xs) n = dropEvery' (x:xs) n 1
where dropEvery' (x:xs) n i =
(if (n `divides` i) then [] else [x]) ++ (dropEvery' xs n (i+1))
dropEvery' [] _ _ = []
divides x y = y `mod` x == 0
dropEvery' :: [a] -> Int -> [a]
dropEvery' list count = helper list count count
where helper [] _ _ = []
helper (x:xs) count 1 = helper xs count count
helper (x:xs) count n = x : (helper xs count (n - 1))
dropEvery'2 :: [a] -> Int -> [a]
dropEvery'2 xs n = helper xs n
where helper [] _ = []
helper (x:xs) 1 = helper xs n
helper (x:xs) k = x : helper xs (k-1)
dropEvery'3 :: [a] -> Int -> [a]
dropEvery'3 [] _ = []
dropEvery'3 list count = (take (count-1) list) ++ dropEvery'3 (drop count list) count
dropEvery'4 :: [a] -> Int -> [a]
dropEvery'4 xs n
| length xs < n = xs
| otherwise = take (n-1) xs ++ dropEvery'4 (drop n xs) n
dropEvery'5 :: [a] -> Int -> [a]
dropEvery'5 = flip $ \n -> map snd . filter ((n/=) . fst) . zip (cycle [1..n])
dropEvery'6 :: [a] -> Int -> [a]
dropEvery'6 xs n = [i | (i,c) <- (zip xs [1,2..]), (mod c n) /= 0]
dropEvery'7 :: [a] -> Int -> [a]
dropEvery'7 xs n = map fst $ filter (\(_,i) -> i `mod` n /= 0) $ zip xs [1..]
dropEvery'8 :: [a] -> Int -> [a]
dropEvery'8 xs n = map fst $ filter ((n/=) . snd) $ zip xs (cycle [1..n])
dropEvery'9 :: [a] -> Int -> [a]
dropEvery'9 xs n = snd $
foldl (\acc e -> if fst acc > 1
then (fst acc - 1, snd acc ++ [e])
else (n, snd acc))
(n, []) xs
dropEvery'10 :: [a] -> Int -> [a]
dropEvery'10 xs n = fst $ foldr
(\x (xs, i) -> (if mod i n == 0 then xs else x:xs, i - 1))
([], length xs) xs
-- P17
split :: [a] -> Int -> ([a], [a])
split xs n = (take n xs, drop n xs)
split' = flip splitAt
split'2 :: [a] -> Int -> ([a], [a])
split'2 [] _ = ([], [])
split'2 list@(x : xs) n
| n > 0 = (x : ys, zs)
| otherwise = ([], list)
where (ys, zs) = split'2 xs (n - 1)
split'3 :: [a] -> Int -> ([a], [a])
split'3 (x:xs) n | n > 0 = (:) x . fst &&& snd $ split'3 xs (n - 1)
split'3 xs _ = ([], xs)
split'4 :: [a] -> Int -> ([a], [a])
split'4 [] _ = ([], [])
split'4 list n
| n < 0 = (list, [])
| otherwise = (first output, second output)
where output = foldl (\acc e -> if third acc > 0
then (first acc ++ [e], second acc, third acc - 1)
else (first acc, second acc ++ [e], third acc)) ([], [], n) list
first (x, _, _) = x
second (_, y, _) = y
third (_, _, z) = z
split'5 :: [a] -> Int -> ([a],[a])
split'5 lst n = snd $ foldl helper (0,([],[])) lst
where helper (i, (left, right)) x = if i >= n
then (i + 1, (left, right ++ [x]))
else (i + 1, (left ++ [x], right))
split'6 :: [a] -> Int -> ([a], [a])
split'6 xs n = let (a, b) = helper [] xs n in (reverse a, b)
where helper left right@(r:rs) n
| n == 0 = (left, right)
| otherwise = helper (r:left) rs (n - 1)
split'7 :: [a] -> Int -> ([a], [a])
split'7 [] _ = ([], [])
split'7 (x:xs) n
| n > 0 = (x : (fst (split xs (n-1))), snd (split xs (n-1)))
| n <= 0 = (fst (split xs 0), x : (snd (split xs 0)))
-- P18
slice :: [a] -> Int -> Int -> [a]
slice xs i k | i > 0 = take (k - i + 1) $ drop (i - 1) xs
slice'2 :: [a] -> Int -> Int -> [a]
slice'2 lst 1 m = slice_ lst m []
where slice_ _ 0 acc = reverse acc
slice_ (x:xs) n acc = slice_ xs (n - 1) (x:acc)
slice_ [] _ _ = []
slice'2 (_:xs) n m = slice xs (n - 1) (m - 1)
slice'2 [] _ _ = []
slice'3 :: [a] -> Int -> Int -> [a]
slice'3 [] _ _ = []
slice'3 (x:xs) i k
| i > 1 = slice'3 xs (i - 1) (k - 1)
| k < 1 = []
| otherwise = x:slice'3 xs (i - 1) (k - 1)
slice'4 :: [a] -> Int -> Int -> [a]
slice'4 xs i j = map snd
$ filter (\(x,_) -> x >= i && x <= j)
$ zip [1..] xs
slice'5 :: [a] -> Int -> Int -> [a]
slice'5 xs i k = [x | (x,j) <- zip xs [1..k], i <= j]
slice'6 :: [a] -> Int -> Int -> [a]
slice'6 xs a b = fst $ unzip $ filter ((>=a) . snd) $ zip xs [1..b]
-- P19
rotate :: [a] -> Int -> [a]
rotate xs n = take len . drop (n `mod` len) . cycle $ xs
where len = length xs
rotate' :: [a] -> Int -> [a]
rotate' xs n = take (length xs) $ drop (length xs + n) $ cycle xs
rotate'2 :: [a] -> Int -> [a]
rotate'2 xs n = if n >= 0 then
drop n xs ++ take n xs
else let l = ((length xs) + n) in
drop l xs ++ take l xs
rotate'3 :: [a] -> Int -> [a]
rotate'3 xs n | n >= 0 = drop n xs ++ take n xs
| n < 0 = drop len xs ++ take len xs
where len = n+length xs
rotate'4 :: [a] -> Int -> [a]
rotate'4 xs n = drop nn xs ++ take nn xs
where
nn = n `mod` length xs
rotate'5 :: [a] -> Int -> [a]
rotate'5 xs n
| n < 0 = rotate xs (n+len)
| n > len = rotate xs (n-len)
| otherwise = let (f,s) = splitAt n xs in s ++ f
where len = length xs
-- original version rotates right for positive number what is incosistent with other functions
rotate'6 :: [a] -> Int -> [a]
rotate'6 xs n
| n > 0 = (drop n xs) ++ (take n xs)
| n <= 0 = (reverse . take (negate n) . reverse $ xs) ++ (reverse . drop (negate n) . reverse $ xs)
rotate'7 :: [a] -> Int -> [a]
rotate'7 [] _ = []
rotate'7 x 0 = x
rotate'7 x y
| y > 0 = rotate'7 (tail x ++ [head x]) (y-1)
| otherwise = rotate'7 (last x : init x) (y+1)
-- P20 (modified to be zero-indexed)
removeAt :: Int -> [a] -> (a, [a])
removeAt k xs = case back of
[] -> error "removeAt: index too large"
x:rest -> (x, front ++ rest)
where (front, back) = splitAt k xs
removeAt' :: Int -> [a] -> (a, [a])
removeAt' n xs = (xs !! n, take n xs ++ drop (n + 1) xs)
removeAt'2 :: Int -> [a] -> (a, [a])
removeAt'2 n xs = let (front, back) = splitAt n xs in
(head back, front ++ tail back)
removeAt'3 :: Int -> [a] -> (a, [a])
removeAt'3 n = (\(a, b) -> (head b, a ++ tail b)) . splitAt n
removeAt'4 :: Int -> [a] -> (a, [a])
removeAt'4 0 (x:xs) = (x, xs)
removeAt'4 n (x:xs) = (l, x:r)
where (l, r) = removeAt (n - 1) xs
-- P21
insertAt :: a -> [a] -> Int -> [a]
insertAt x ys 0 = x:ys
insertAt x (y:ys) n = y:insertAt x ys (n-1)
insertAt' x xs n = take n xs ++ [x] ++ drop n xs
insertAt'' el lst n = fst $ foldl helper ([],0) lst
where helper (acc,i) x = if i == n then (acc++[el,x],i+1) else (acc++[x],i+1)
insertAt''' :: a -> [a] -> Int -> [a]
insertAt''' elt lst pos = foldr concat' [] $ zip [0..] lst
where concat' (i, x) xs
| i == pos = elt:x:xs
| otherwise = x:xs
-- P22
range :: Int -> Int -> [Int]
range x y = [x..y]
range2 :: Int -> Int -> [Int]
range2 = enumFromTo
range3 x y = take (y-x+1) $ iterate (+1) x
range4 start stop
| start > stop = []
| start == stop = [stop]
| start < stop = start:range4 (start+1) stop
-- modified original solution so that it doesn't do reverse ranges
range5 :: (Ord a, Enum a) => a -> a -> [a]
range5 a b | (a > b) = []
range5 a b = a:range5 ((if a <= b then succ else const b) a) b
range6 l r = if (l > r) then [] else scanl (+) l (replicate (r - l) 1)
-- P23
rnd_select :: [a] -> Int -> IO [a]
rnd_select [] _ = return []
rnd_select l n
| n < 0 = error "N must be greater than zero."
| otherwise = do pos <- replicateM n $ getStdRandom $ randomR (0, (length l)-1)
return [l!!p | p <- pos]
rnd_select2 :: [a] -> Int -> IO [a]
rnd_select2 xs n = do
gen <- getStdGen
return $ take n [ xs !! x | x <- randomRs (0, (length xs) - 1) gen]
rnd_select3 :: [a] -> Int -> IO [a]
rnd_select3 xs n
| n < 0 = error "N must be greater than zero."
| otherwise = replicateM n rand
where rand = do r <- randomRIO (0, (length xs) - 1)
return (xs!!r)
-- An O(N) algorithm
rnd_select4 :: [a] -> Int -> IO [a]
rnd_select4 _ 0 = return []
rnd_select4 (x:xs) n =
do r <- randomRIO (0, (length xs))
if r < n
then do
rest <- rnd_select4 xs (n-1)
return (x : rest)
else rnd_select4 xs n
-- A solution returns random results even when the number of items we want is the same as the number of items in the list
rnd_select5 :: [a] -> Int -> IO [a]
rnd_select5 _ 0 = return []
rnd_select5 [] _ = return []
rnd_select5 xs count =
do r <- randomRIO (0, (length xs)-1)
rest <- rnd_select5 (snd $ removeAt r xs) (count-1)
return ((xs!!r) : rest)
-- P24
diff_select :: Int -> Int -> IO [Int]
diff_select n to = diff_select' n [1..to]
diff_select' 0 _ = return []
diff_select' _ [] = error "too few elements to choose from"
diff_select' n xs = do r <- randomRIO (0, (length xs)-1)
let remaining = take r xs ++ drop (r+1) xs
rest <- diff_select' (n-1) remaining
return ((xs!!r) : rest)
diff_select2 :: Int -> Int -> IO [Int]
diff_select2 n to = rnd_select [1..to] n
diff_select3 :: Int -> Int -> IO [Int]
diff_select3 n m = do
gen <- getStdGen
return . take n $ randomRs (1, m) gen
diff_select4 :: Int -> Int -> StdGen -> [Int]
diff_select4 n m = take n . nub . randomRs (1, m)
diff_select5 :: Int -> Int -> IO [Int]
diff_select5 n m = take n . nub . randomRs (1, m) <$> getStdGen
-- P25
-- The solution below assumes that rnd_select returns unique elements which is not true
--rnd_perm :: [a] -> IO [a]
--rnd_perm xs = rnd_select xs (length xs)
rnd_perm2 :: [a] -> IO [a]
rnd_perm2 [] = return []
rnd_perm2 (x:xs) = do
index <- randomRIO (0, (length xs))
rest <- rnd_perm2 xs
return $ let (ys,zs) = splitAt index rest
in ys ++ (x:zs)
rnd_perm3 :: [a] -> IO [a]
rnd_perm3 [] = return []
rnd_perm3 xs = do
index <- randomRIO (0, (length xs)-1)
rest <- let (ys,(_:zs)) = splitAt index xs
in rnd_perm3 $ ys ++ zs
return $ (xs !! index):rest
rnd_perm4 :: [a] -> IO [a]
rnd_perm4 xs = rndElem . permutations $ xs
where rndElem :: [a] -> IO a
rndElem xs = do
index <- randomRIO (0, length xs - 1)
return $ xs !! index
-- P26
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [ [] ]
combinations n xs = [y:ys | y:xs' <- tails xs, ys <- combinations (n-1) xs']
combinations2 :: Int -> [a] -> [[a]]
combinations2 0 _ = return []
combinations2 n xs = do y:xs' <- tails xs
ys <- combinations2 (n-1) xs'
return (y:ys)
combinations3 :: Int -> [a] -> [[a]]
combinations3 0 _ = [[]]
combinations3 n xs = [ xs !! i : x | i <- [0..(length xs)-1]
, x <- combinations3 (n-1) (drop (i+1) xs) ]
combinations4 :: Int -> [a] -> [[a]]
combinations4 _ [] = [[]]
combinations4 0 _ = [[]]
combinations4 k (x:xs) = x_start ++ others
where x_start = [ x : rest | rest <- combinations4 (k-1) xs ]
others = if k <= length xs then combinations4 k xs else []
combinations5 :: Int -> [a] -> [[a]]
combinations5 0 _ = [[]]
combinations5 _ [] = []
combinations5 n (x:xs) = (map (x:) (combinations5 (n-1) xs)) ++ (combinations5 n xs)
combinations6 :: Int -> [a] -> [[a]]
combinations6 k ns = filter ((k==).length) (subsequences ns)
-- let's try it with combinations 2 [1,2,3]
combinations7 :: (Ord a) => Int -> [a] -> [[a]]
combinations7 n xs = compressed
where
-- create all combinations (multiple instances, permutations allowed)
-- answer : [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
combinations' n _ | n <= 0 = [[]]
combinations' 1 xs = map (:[]) xs
combinations' n xs = (:) <$> xs <*> combinations (n-1) xs
-- sort every sublist and the list itself after that
-- [[1,1],[1,2],[1,2],[1,3],[1,3],[2,2],[2,3],[2,3],[3,3]]
sorted = sort . map sort $ combinations' n xs
-- for each sublist, eliminate duplicates (see Problem 8)
-- [[1],[1,2],[1,2],[1,3],[1,3],[2],[2,3],[2,3],[3]]
grouped = map (map head . group) sorted
-- filter all sublist with length < n,
-- this means that they had at least two times the same value in it
-- [[1,2],[1,2],[1,3],[1,3],[2,3],[2,3]]
filtered = filter (\xs -> length xs == n) grouped
-- eliminate duplicates a second time, this time in the list itself
-- [[1,2],[1,3],[2,3]]
compressed = map head . group $ filtered
-- P27
groupSubsets :: [Int] -> [a] -> [[[a]]]
groupSubsets [] _ = [[]]
groupSubsets (n:ns) xs =
[ g:gs | (g,rs) <- combination_ n xs
, gs <- groupSubsets ns rs ]
groupSubsets2 :: [Int] -> [a] -> [[[a]]]
groupSubsets2 [] = const [[]]
groupSubsets2 (n:ns) = concatMap (uncurry $ (. groupSubsets2 ns) . map . (:)) . combination_ n
groupSubsets3 :: [Int] -> [a] -> [[[a]]]
groupSubsets3 [] xs = [[]]
groupSubsets3 (g:gs) xs = concatMap helper $ combination_ g xs
where helper (as, bs) = map (as:) (groupSubsets3 gs bs)
combination_ :: Int -> [a] -> [([a],[a])]
combination_ 0 xs = [([],xs)]
combination_ n [] = []
combination_ n (x:xs) = ts ++ ds
where
ts = [ (x:ys,zs) | (ys,zs) <- combination_ (n-1) xs ]
ds = [ (ys,x:zs) | (ys,zs) <- combination_ n xs ]
-- P28a
lsort :: [[a]] -> [[a]]
lsort = sortBy (comparing length)
lsort2 :: [[a]] -> [[a]]
lsort2 = sortBy (\xs ys -> compare (length xs) (length ys))
lsort3 :: [[a]] -> [[a]]
lsort3 = sortBy (compare `on` length)
lsort4 :: [[a]] -> [[a]]
lsort4 = sortOn length
-- P28b
lfsort :: [[a]] -> [[a]]
lfsort lists = concat groups
where groups = lsort $ groupBy equalLength $ lsort lists
equalLength xs ys = length xs == length ys
lfsort2 :: [[a]] -> [[a]]
lfsort2 = concat . lsort . groupBy ((==) `on` length) . lsort
lfsort3 :: [[a]] -> [[a]]
lfsort3 l = sortBy (\xs ys -> compare (frequency (length xs) l) (frequency (length ys) l)) l
where frequency len l = length (filter (\x -> length x == len) l)
lfsort4 :: [[a]] -> [[a]]
lfsort4 = map snd . concat . sortOn length . groupBy ((==) `on` fst) . sortOn fst . map (\x -> (length x, x))
-- https://en.wikibooks.org/wiki/Haskell/Understanding_arrows
lfsort5 :: [[a]] -> [[a]]
lfsort5 = zip [1..] >>> map (second (length &&& id)) >>> sortWith (snd>>>fst)
>>> cntDupLength undefined [] >>> sortWith (snd>>>fst) >>> sortWith fst
>>> map (\(_,(_,(_,a))) -> a)
where cntDupLength :: Int -> [(Int,(Int,a))] -> [(Int,(Int,a))] -> [(Int,(Int,(Int,a)))]
cntDupLength _ lls [] = map ((,) (length lls)) $ reverse lls
cntDupLength _ [] (x@(_,(l,_)):xs) = cntDupLength l [x] xs
cntDupLength l lls ys@(x@(_,(l1,_)):xs)
| l == l1 = cntDupLength l (x:lls) xs
| otherwise = (map ((,) (length lls)) $ reverse lls) ++ cntDupLength undefined [] ys
-- P31
-- see http://stackoverflow.com/questions/3082324/foldl-versus-foldr-behavior-with-infinite-lists
isPrime :: Integer -> Bool
isPrime k = k > 1 &&
foldr (\p r -> p*p > k || (k `rem` p /= 0 && r)) True primesTME
-- tree-merging Eratosthenes sieve producing infinite list of all prime numbers
primesTME :: [Integer]
primesTME = 2 : gaps 3 (join [[p*p,p*p+2*p..] | p <- primes'])
where
primes' = 3 : gaps 5 (join [[p*p,p*p+2*p..] | p <- primes'])
join ((x:xs):t) = x : union xs (join (pairs t))
pairs ((x:xs):ys:t) = (x : union xs ys) : pairs t
gaps k xs@(x:t) | k==x = gaps (k+2) t
| True = k : gaps (k+2) xs
isPrime2 :: (Integral a) => a -> Bool
isPrime2 n | n < 4 = n > 1
isPrime2 n = all ((/=0).mod n) $ 2:3:[x + i | x <- [6,12..s], i <- [-1,1]]
where s = floor $ sqrt $ fromIntegral n
-- P32
myGCD :: Integer -> Integer -> Integer
myGCD x y | x < 0 = myGCD (-x) y
| y < 0 = myGCD x (-y)
| y < x = gcd' y x
| otherwise = gcd' x y
where gcd' 0 y = y
gcd' x y = gcd' (y `mod` x) x
myGCD2 :: Integer -> Integer -> Integer
myGCD2 a b
| b == 0 = abs a
| otherwise = myGCD2 b (a `mod` b)
-- P33
coprime :: Integer -> Integer -> Bool
coprime a b = myGCD a b == 1
-- P34
totient :: Integer -> Integer
totient 1 = 1
totient a = toInteger $ length $ filter (coprime a) [1..a-1]
totient2 :: Integer -> Integer
totient2 n = toInteger $ length [x | x <- [1..n], coprime x n]
-- https://en.wikipedia.org/wiki/Euler%27s_totient_function
totient3 :: Integer -> Integer
totient3 1 = 1
totient3 n = numerator ratio `div` denominator ratio
where ratio = foldl (\acc x -> acc * (1 - (1 % x))) (n % 1) $ nub (primeFactors n)
-- P35
primeFactors :: Integer -> [Integer]
primeFactors a = let (f, f1) = factorPairOf a
f' = if prime f then [f] else primeFactors f
f1' = if prime f1 then [f1] else primeFactors f1
in f' ++ f1'
where
factorPairOf a = let f = head $ factors a
in (f, a `div` f)
factors a = filter (isFactor a) [2..a-1]
isFactor a b = a `mod` b == 0
prime a = null $ factors a
-- P36
prime_factors_mult :: Integer -> [(Integer, Int)]
prime_factors_mult n = map swap $ encode $ primeFactors n
where swap (x,y) = (y,x)
prime_factors_mult2 :: Integer -> [(Integer, Int)]
prime_factors_mult2 = map encode . group . primeFactors
where encode xs = (head xs, length xs)
|
dkandalov/katas
|
haskell/p99/src/p9x/p00/P00_.hs
|
unlicense
| 31,138 | 0 | 16 | 8,375 | 15,828 | 8,487 | 7,341 | -1 | -1 |
-- Copyright (c) 2015 Bart Massey
-- [This program is licensed under the "2-clause ('new') BSD License"]
-- Please see the file COPYING in the source
-- distribution of this software for license terms.
import Text.SSV
tsvFormat :: SSVFormat
tsvFormat = csvFormat { ssvFormatSeparator = '\t' }
main :: IO ()
main = interact (showCSV . readSSV tsvFormat)
|
BartMassey/haskell-basic-examples
|
tabcomma2.hs
|
bsd-2-clause
| 356 | 0 | 8 | 61 | 56 | 32 | 24 | 5 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE Unsafe #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Copyright : (C) 2015, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <[email protected]>
= Initialising a ROM with a data file #usingromfiles#
ROMs initialised with a data file. The BNF grammar for this data file is simple:
@
FILE = LINE+
LINE = BIT+
BIT = '0'
| '1'
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example, a data file @memory.bin@ containing the 9-bit unsigned number
@7@ to @13@ looks like:
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
We can instantiate a synchronous ROM using the content of the above file like
so:
@
topEntity :: Signal (Unsigned 3) -> Signal (Unsigned 9)
topEntity rd = 'CLaSH.Class.BitPack.unpack' '<$>' 'romFile' d7 \"memory.bin\" rd
@
And see that it works as expected:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ topEntity (fromList [3..5])__
[10,11,12]
@
However, we can also interpret the same data as a tuple of a 6-bit unsigned
number, and a 3-bit signed number:
@
topEntity2 :: Signal (Unsigned 3) -> Signal (Unsigned 6,Signed 3)
topEntity2 rd = 'CLaSH.Class.BitPack.unpack' '<$>' 'romFile' d7 \"memory.bin\" rd
@
And then we would see:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ topEntity2 (fromList [3..5])__
[(1,2),(1,3)(1,-4)]
@
-}
module CLaSH.Prelude.ROM.File
( -- * Asynchronous ROM
asyncRomFile
, asyncRomFilePow2
-- * Synchronous ROM synchronised to the system clock
, romFile
, romFilePow2
-- * Synchronous ROM synchronised to an arbitrary clock
, romFile'
, romFilePow2'
-- * Internal
, asyncRomFile#
, romFile#
)
where
import Data.Array (listArray,(!))
import GHC.TypeLits (KnownNat, type (^))
import CLaSH.Prelude.BlockRam.File (initMem)
import CLaSH.Promoted.Nat (SNat,snat,snatToInteger)
import CLaSH.Sized.BitVector (BitVector)
import CLaSH.Signal (Signal)
import CLaSH.Signal.Explicit (Signal', SClock, register', systemClock)
import CLaSH.Sized.Unsigned (Unsigned)
{-# INLINE asyncRomFile #-}
-- | An asynchronous/combinational ROM with space for @n@ elements
--
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.ROM.File#usingromfiles" for more information on how
-- to instantiate a ROM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
asyncRomFile :: (KnownNat m, Enum addr)
=> SNat n -- ^ Size of the ROM
-> FilePath -- ^ File describing the content of the ROM
-> addr -- ^ Read address @rd@
-> BitVector m -- ^ The value of the ROM at address @rd@
asyncRomFile sz file rd = asyncRomFile# sz file (fromEnum rd)
{-# INLINE asyncRomFilePow2 #-}
-- | An asynchronous/combinational ROM with space for 2^@n@ elements
--
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.ROM.File#usingromfiles" for more information on how
-- to instantiate a ROM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
asyncRomFilePow2 :: forall n m . (KnownNat m, KnownNat n, KnownNat (2^n))
=> FilePath -- ^ File describing the content of the ROM
-> Unsigned n -- ^ Read address @rd@
-> BitVector m -- ^ The value of the ROM at address @rd@
asyncRomFilePow2 = asyncRomFile (snat :: SNat (2^n))
{-# NOINLINE asyncRomFile# #-}
-- | asyncROMFile primitive
asyncRomFile# :: KnownNat m
=> SNat n -- ^ Size of the ROM
-> FilePath -- ^ File describing the content of the ROM
-> Int -- ^ Read address @rd@
-> BitVector m -- ^ The value of the ROM at address @rd@
asyncRomFile# sz file rd = content ! rd
where
content = listArray (0,szI-1) (initMem file)
szI = fromInteger (snatToInteger sz)
{-# INLINE romFile #-}
-- | A ROM with a synchronous read port, with space for @n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.ROM.File#usingromfiles" for more information on how
-- to instantiate a ROM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
romFile :: (KnownNat m, KnownNat k)
=> SNat n -- ^ Size of the ROM
-> FilePath -- ^ File describing the content of the ROM
-> Signal (Unsigned k) -- ^ Read address @rd@
-> Signal (BitVector m)
-- ^ The value of the ROM at address @rd@ from the previous clock cycle
romFile = romFile' systemClock
{-# INLINE romFilePow2 #-}
-- | A ROM with a synchronous read port, with space for 2^@n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.ROM.File#usingromfiles" for more information on how
-- to instantiate a ROM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
romFilePow2 :: forall n m . (KnownNat m, KnownNat n, KnownNat (2^n))
=> FilePath -- ^ File describing the content of the ROM
-> Signal (Unsigned n) -- ^ Read address @rd@
-> Signal (BitVector m)
-- ^ The value of the ROM at address @rd@ from the previous clock cycle
romFilePow2 = romFile' systemClock (snat :: SNat (2^n))
{-# INLINE romFilePow2' #-}
-- | A ROM with a synchronous read port, with space for 2^@n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.ROM.File#usingromfiles" for more information on how
-- to instantiate a ROM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
romFilePow2' :: forall clk n m . (KnownNat m, KnownNat n, KnownNat (2^n))
=> SClock clk -- ^ 'Clock' to synchronize to
-> FilePath -- ^ File describing the content of
-- the ROM
-> Signal' clk (Unsigned n) -- ^ Read address @rd@
-> Signal' clk (BitVector m)
-- ^ The value of the ROM at address @rd@ from the previous clock
-- cycle
romFilePow2' clk = romFile' clk (snat :: SNat (2^n))
{-# INLINE romFile' #-}
-- | A ROM with a synchronous read port, with space for @n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.ROM.File#usingromfiles" for more information on how
-- to instantiate a ROM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
romFile' :: (KnownNat m, Enum addr)
=> SClock clk -- ^ 'Clock' to synchronize to
-> SNat n -- ^ Size of the ROM
-> FilePath -- ^ File describing the content of the
-- ROM
-> Signal' clk addr -- ^ Read address @rd@
-> Signal' clk (BitVector m)
-- ^ The value of the ROM at address @rd@ from the previous clock cycle
romFile' clk sz file rd = romFile# clk sz file (fromEnum <$> rd)
{-# NOINLINE romFile# #-}
-- | romFile primitive
romFile# :: KnownNat m
=> SClock clk -- ^ 'Clock' to synchronize to
-> SNat n -- ^ Size of the ROM
-> FilePath -- ^ File describing the content of the
-- ROM
-> Signal' clk Int -- ^ Read address @rd@
-> Signal' clk (BitVector m)
-- ^ The value of the ROM at address @rd@ from the previous clock cycle
romFile# clk sz file rd = register' clk undefined ((content !) <$> rd)
where
content = listArray (0,szI-1) (initMem file)
szI = fromInteger (snatToInteger sz)
|
Ericson2314/clash-prelude
|
src/CLaSH/Prelude/ROM/File.hs
|
bsd-2-clause
| 11,995 | 0 | 12 | 3,285 | 1,037 | 642 | 395 | -1 | -1 |
module TestTypes (run) where
{-
Everything below this comment can be copy-pasted into: https://repl.it/languages/haskell
The on-line Haskell REPL doesn't seem to support selective imports of Prelude, so (+) has been replaced with (~+).
-}
infixl 6 ~+
class Additive a where
(~+) :: a -> a -> a
zero :: a
instance Additive Integer where
(~+) = (Prelude.+)
zero = 0
-- A data structure for Polynomials of the form a * x ^ n + r(x)
data Polynomial a = Const !a
| Term !a !Integer !(Polynomial a)
deriving (Eq, Read)
-- Constructor (with checks)
polynomial :: (Eq a, Additive a) => a -> Integer -> Polynomial a -> Polynomial a
polynomial a n r
| a == zero = r
| n == 0 = Const a
| otherwise = Term a n r
instance (Show a) => Show (Polynomial a) where
show (Const a) = "Const " ++ show a
show (Term a n r) = show a ++ "x" ++ show n ++ " + " ++ show r
instance (Eq a, Additive a) => Additive (Polynomial a) where
Const a1 ~+ Const a2 = Const (a1 ~+ a2)
Const a1 ~+ Term a2 n2 r2 = Term a2 n2 (Const a1 ~+ r2)
Term a1 n1 r1 ~+ Const a2 = Term a1 n1 (r1 ~+ Const a2)
p1@(Term a1 n1 r1) ~+ p2@(Term a2 n2 r2) | n1 > n2 = Term a1 n1 (r1 ~+ p2)
| n1 < n2 = Term a2 n2 (p1 ~+ r2)
| otherwise = polynomial (a1 ~+ a2) n1 (r1 ~+ r2)
zero = Const zero
foo0 :: (Additive a) => a -> a
foo0 _ = zero
foo1 :: (Additive a) => Polynomial a -> a
foo1 _ = zero
foo2 :: (Additive a) => Polynomial (Polynomial a) -> a
foo2 _ = zero
{-
Output:
0
Const 0
Const Const 0
Const Const 0
Const 0
0
-}
run :: IO ()
run = do
print (foo0 (undefined :: Integer))
print (foo0 (undefined :: Polynomial Integer))
print (foo0 (undefined :: Polynomial (Polynomial Integer)))
print (foo1 (undefined :: Polynomial (Polynomial Integer)))
print (foo2 (undefined :: Polynomial (Polynomial Integer)))
main :: IO ()
main = run
|
pmilne/algebra
|
test/TestTypes.hs
|
bsd-3-clause
| 2,068 | 0 | 13 | 659 | 788 | 393 | 395 | 50 | 1 |
#!/usr/local/bin/runghc
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE Trustworthy,ScopedTypeVariables #-}
module Main
(
main
) where
import MaintainData
import System.Environment
import System.Process
import System.Directory
import System.Exit
import System.IO.Extra(writeFileUTF8)
import Data.Time
import Data.Char
import Control.Monad
import Text.Blaze.Svg.Shields
import Text.Blaze.Svg.Renderer.String
main :: IO ()
main = do
(args) <- getArgs
if null args || map toLower $ head args == "help" then help else do
case map toLower $ head args of
"start" ->
"restart" ->
"stop" ->
"test" ->
return ()
help :: IO ()
help = return ()
getMTData :: IO MTData
getMTData = do
text <- readFile "./info"
return $ read $ head $ lines x ::IO MTData
start :: IO
start = do
os <- getMTData
(_,_,_,cabalInstall) <- createProcess
|
Xidian-Haskell-Server-Keeper/XHSK-Home
|
maintain/Main.hs
|
bsd-3-clause
| 1,061 | 2 | 12 | 372 | 277 | 148 | 129 | -1 | -1 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
#if __GLASGOW_HASKELL__ >= 708
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE TypeFamilies #-}
#endif
#include "containers.h"
-----------------------------------------------------------------------------
-- |
-- Module : Data.Map.Base
-- Copyright : (c) Daan Leijen 2002
-- (c) Andriy Palamarchuk 2008
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- An efficient implementation of maps from keys to values (dictionaries).
--
-- Since many function names (but not the type name) clash with
-- "Prelude" names, this module is usually imported @qualified@, e.g.
--
-- > import Data.Map (Map)
-- > import qualified Data.Map as Map
--
-- The implementation of 'Map' is based on /size balanced/ binary trees (or
-- trees of /bounded balance/) as described by:
--
-- * Stephen Adams, \"/Efficient sets: a balancing act/\",
-- Journal of Functional Programming 3(4):553-562, October 1993,
-- <http://www.swiss.ai.mit.edu/~adams/BB/>.
--
-- * J. Nievergelt and E.M. Reingold,
-- \"/Binary search trees of bounded balance/\",
-- SIAM journal of computing 2(1), March 1973.
--
-- Note that the implementation is /left-biased/ -- the elements of a
-- first argument are always preferred to the second, for example in
-- 'union' or 'insert'.
--
-- Operation comments contain the operation time complexity in
-- the Big-O notation <http://en.wikipedia.org/wiki/Big_O_notation>.
-----------------------------------------------------------------------------
-- [Note: Using INLINABLE]
-- ~~~~~~~~~~~~~~~~~~~~~~~
-- It is crucial to the performance that the functions specialize on the Ord
-- type when possible. GHC 7.0 and higher does this by itself when it sees th
-- unfolding of a function -- that is why all public functions are marked
-- INLINABLE (that exposes the unfolding).
-- [Note: Using INLINE]
-- ~~~~~~~~~~~~~~~~~~~~
-- For other compilers and GHC pre 7.0, we mark some of the functions INLINE.
-- We mark the functions that just navigate down the tree (lookup, insert,
-- delete and similar). That navigation code gets inlined and thus specialized
-- when possible. There is a price to pay -- code growth. The code INLINED is
-- therefore only the tree navigation, all the real work (rebalancing) is not
-- INLINED by using a NOINLINE.
--
-- All methods marked INLINE have to be nonrecursive -- a 'go' function doing
-- the real work is provided.
-- [Note: Type of local 'go' function]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- If the local 'go' function uses an Ord class, it sometimes heap-allocates
-- the Ord dictionary when the 'go' function does not have explicit type.
-- In that case we give 'go' explicit type. But this slightly decrease
-- performance, as the resulting 'go' function can float out to top level.
-- [Note: Local 'go' functions and capturing]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- As opposed to IntMap, when 'go' function captures an argument, increased
-- heap-allocation can occur: sometimes in a polymorphic function, the 'go'
-- floats out of its enclosing function and then it heap-allocates the
-- dictionary and the argument. Maybe it floats out too late and strictness
-- analyzer cannot see that these could be passed on stack.
--
-- For example, change 'member' so that its local 'go' function is not passing
-- argument k and then look at the resulting code for hedgeInt.
-- [Note: Order of constructors]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The order of constructors of Map matters when considering performance.
-- Currently in GHC 7.0, when type has 2 constructors, a forward conditional
-- jump is made when successfully matching second constructor. Successful match
-- of first constructor results in the forward jump not taken.
-- On GHC 7.0, reordering constructors from Tip | Bin to Bin | Tip
-- improves the benchmark by up to 10% on x86.
module Data.Map.Base (
-- * Map type
Map(..) -- instance Eq,Show,Read
-- * Operators
, (!), (\\)
-- * Query
, null
, size
, member
, notMember
, lookup
, findWithDefault
, lookupLT
, lookupGT
, lookupLE
, lookupGE
-- * Construction
, empty
, singleton
-- ** Insertion
, insert
, insertWith
, insertWithKey
, insertLookupWithKey
-- ** Delete\/Update
, delete
, adjust
, adjustWithKey
, update
, updateWithKey
, updateLookupWithKey
, alter
-- * Combine
-- ** Union
, union
, unionWith
, unionWithKey
, unions
, unionsWith
-- ** Difference
, difference
, differenceWith
, differenceWithKey
-- ** Intersection
, intersection
, intersectionWith
, intersectionWithKey
-- ** Universal combining function
, mergeWithKey
-- * Traversal
-- ** Map
, map
, mapWithKey
, traverseWithKey
, mapAccum
, mapAccumWithKey
, mapAccumRWithKey
, mapKeys
, mapKeysWith
, mapKeysMonotonic
-- * Folds
, foldr
, foldl
, foldrWithKey
, foldlWithKey
, foldMapWithKey
-- ** Strict folds
, foldr'
, foldl'
, foldrWithKey'
, foldlWithKey'
-- * Conversion
, elems
, keys
, assocs
, keysSet
, fromSet
-- ** Lists
, toList
, fromList
, fromListWith
, fromListWithKey
-- ** Ordered lists
, toAscList
, toDescList
, fromAscList
, fromAscListWith
, fromAscListWithKey
, fromDistinctAscList
-- * Filter
, filter
, filterWithKey
, partition
, partitionWithKey
, mapMaybe
, mapMaybeWithKey
, mapEither
, mapEitherWithKey
, split
, splitLookup
, splitRoot
-- * Submap
, isSubmapOf, isSubmapOfBy
, isProperSubmapOf, isProperSubmapOfBy
-- * Indexed
, lookupIndex
, findIndex
, elemAt
, updateAt
, deleteAt
-- * Min\/Max
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, updateMin
, updateMax
, updateMinWithKey
, updateMaxWithKey
, minView
, maxView
, minViewWithKey
, maxViewWithKey
-- * Debugging
, showTree
, showTreeWith
, valid
-- Used by the strict version
, bin
, balance
, balanced
, balanceL
, balanceR
, delta
, link
, insertMax
, merge
, glue
, trim
, trimLookupLo
, MaybeS(..)
, filterGt
, filterLt
) where
import Control.Applicative (Applicative(..), (<$>))
import Control.DeepSeq (NFData(rnf))
import Data.Bits (shiftL, shiftR)
import qualified Data.Foldable as Foldable
import Data.Monoid (Monoid(..))
import Data.Traversable (Traversable(traverse))
import Data.Typeable
import Prelude hiding (lookup, map, filter, foldr, foldl, null)
import qualified Data.Set.Base as Set
import Data.Utils.StrictFold
import Data.Utils.StrictPair
#if __GLASGOW_HASKELL__
import GHC.Exts ( build )
#if __GLASGOW_HASKELL__ >= 708
import qualified GHC.Exts as GHCExts
#endif
import Text.Read
import Data.Data
#endif
#if __GLASGOW_HASKELL__ >= 709
import Data.Coerce
#endif
{--------------------------------------------------------------------
Operators
--------------------------------------------------------------------}
infixl 9 !,\\ --
-- | /O(log n)/. Find the value at a key.
-- Calls 'error' when the element can not be found.
--
-- > fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map
-- > fromList [(5,'a'), (3,'b')] ! 5 == 'a'
(!) :: Ord k => Map k a -> k -> a
m ! k = find k m
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE (!) #-}
#endif
-- | Same as 'difference'.
(\\) :: Ord k => Map k a -> Map k b -> Map k a
m1 \\ m2 = difference m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE (\\) #-}
#endif
{--------------------------------------------------------------------
Size balanced trees.
--------------------------------------------------------------------}
-- | A Map from keys @k@ to values @a@.
-- See Note: Order of constructors
data Map k a = Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
| Tip
type Size = Int
#if __GLASGOW_HASKELL__ >= 708
type role Map nominal representational
#endif
instance (Ord k) => Monoid (Map k v) where
mempty = empty
mappend = union
mconcat = unions
#if __GLASGOW_HASKELL__
{--------------------------------------------------------------------
A Data instance
--------------------------------------------------------------------}
-- This instance preserves data abstraction at the cost of inefficiency.
-- We provide limited reflection services for the sake of data abstraction.
instance (Data k, Data a, Ord k) => Data (Map k a) where
gfoldl f z m = z fromList `f` toList m
toConstr _ = fromListConstr
gunfold k z c = case constrIndex c of
1 -> k (z fromList)
_ -> error "gunfold"
dataTypeOf _ = mapDataType
dataCast2 f = gcast2 f
fromListConstr :: Constr
fromListConstr = mkConstr mapDataType "fromList" [] Prefix
mapDataType :: DataType
mapDataType = mkDataType "Data.Map.Base.Map" [fromListConstr]
#endif
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(1)/. Is the map empty?
--
-- > Data.Map.null (empty) == True
-- > Data.Map.null (singleton 1 'a') == False
null :: Map k a -> Bool
null Tip = True
null (Bin {}) = False
{-# INLINE null #-}
-- | /O(1)/. The number of elements in the map.
--
-- > size empty == 0
-- > size (singleton 1 'a') == 1
-- > size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3
size :: Map k a -> Int
size Tip = 0
size (Bin sz _ _ _ _) = sz
{-# INLINE size #-}
-- | /O(log n)/. Lookup the value at a key in the map.
--
-- The function will return the corresponding value as @('Just' value)@,
-- or 'Nothing' if the key isn't in the map.
--
-- An example of using @lookup@:
--
-- > import Prelude hiding (lookup)
-- > import Data.Map
-- >
-- > employeeDept = fromList([("John","Sales"), ("Bob","IT")])
-- > deptCountry = fromList([("IT","USA"), ("Sales","France")])
-- > countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")])
-- >
-- > employeeCurrency :: String -> Maybe String
-- > employeeCurrency name = do
-- > dept <- lookup name employeeDept
-- > country <- lookup dept deptCountry
-- > lookup country countryCurrency
-- >
-- > main = do
-- > putStrLn $ "John's currency: " ++ (show (employeeCurrency "John"))
-- > putStrLn $ "Pete's currency: " ++ (show (employeeCurrency "Pete"))
--
-- The output of this program:
--
-- > John's currency: Just "Euro"
-- > Pete's currency: Nothing
lookup :: Ord k => k -> Map k a -> Maybe a
lookup = go
where
STRICT_1_OF_2(go)
go _ Tip = Nothing
go k (Bin _ kx x l r) = case compare k kx of
LT -> go k l
GT -> go k r
EQ -> Just x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookup #-}
#else
{-# INLINE lookup #-}
#endif
-- | /O(log n)/. Is the key a member of the map? See also 'notMember'.
--
-- > member 5 (fromList [(5,'a'), (3,'b')]) == True
-- > member 1 (fromList [(5,'a'), (3,'b')]) == False
member :: Ord k => k -> Map k a -> Bool
member = go
where
STRICT_1_OF_2(go)
go _ Tip = False
go k (Bin _ kx _ l r) = case compare k kx of
LT -> go k l
GT -> go k r
EQ -> True
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE member #-}
#else
{-# INLINE member #-}
#endif
-- | /O(log n)/. Is the key not a member of the map? See also 'member'.
--
-- > notMember 5 (fromList [(5,'a'), (3,'b')]) == False
-- > notMember 1 (fromList [(5,'a'), (3,'b')]) == True
notMember :: Ord k => k -> Map k a -> Bool
notMember k m = not $ member k m
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE notMember #-}
#else
{-# INLINE notMember #-}
#endif
-- | /O(log n)/. Find the value at a key.
-- Calls 'error' when the element can not be found.
find :: Ord k => k -> Map k a -> a
find = go
where
STRICT_1_OF_2(go)
go _ Tip = error "Map.!: given key is not an element in the map"
go k (Bin _ kx x l r) = case compare k kx of
LT -> go k l
GT -> go k r
EQ -> x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE find #-}
#else
{-# INLINE find #-}
#endif
-- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
-- the value at key @k@ or returns default value @def@
-- when the key is not in the map.
--
-- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
-- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
findWithDefault :: Ord k => a -> k -> Map k a -> a
findWithDefault = go
where
STRICT_2_OF_3(go)
go def _ Tip = def
go def k (Bin _ kx x l r) = case compare k kx of
LT -> go def k l
GT -> go def k r
EQ -> x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE findWithDefault #-}
#else
{-# INLINE findWithDefault #-}
#endif
-- | /O(log n)/. Find largest key smaller than the given one and return the
-- corresponding (key, value) pair.
--
-- > lookupLT 3 (fromList [(3,'a'), (5,'b')]) == Nothing
-- > lookupLT 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
lookupLT :: Ord k => k -> Map k v -> Maybe (k, v)
lookupLT = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing k (Bin _ kx x l r) | k <= kx = goNothing k l
| otherwise = goJust k kx x r
STRICT_1_OF_4(goJust)
goJust _ kx' x' Tip = Just (kx', x')
goJust k kx' x' (Bin _ kx x l r) | k <= kx = goJust k kx' x' l
| otherwise = goJust k kx x r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupLT #-}
#else
{-# INLINE lookupLT #-}
#endif
-- | /O(log n)/. Find smallest key greater than the given one and return the
-- corresponding (key, value) pair.
--
-- > lookupGT 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
-- > lookupGT 5 (fromList [(3,'a'), (5,'b')]) == Nothing
lookupGT :: Ord k => k -> Map k v -> Maybe (k, v)
lookupGT = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing k (Bin _ kx x l r) | k < kx = goJust k kx x l
| otherwise = goNothing k r
STRICT_1_OF_4(goJust)
goJust _ kx' x' Tip = Just (kx', x')
goJust k kx' x' (Bin _ kx x l r) | k < kx = goJust k kx x l
| otherwise = goJust k kx' x' r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupGT #-}
#else
{-# INLINE lookupGT #-}
#endif
-- | /O(log n)/. Find largest key smaller or equal to the given one and return
-- the corresponding (key, value) pair.
--
-- > lookupLE 2 (fromList [(3,'a'), (5,'b')]) == Nothing
-- > lookupLE 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
-- > lookupLE 5 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
lookupLE :: Ord k => k -> Map k v -> Maybe (k, v)
lookupLE = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing k (Bin _ kx x l r) = case compare k kx of LT -> goNothing k l
EQ -> Just (kx, x)
GT -> goJust k kx x r
STRICT_1_OF_4(goJust)
goJust _ kx' x' Tip = Just (kx', x')
goJust k kx' x' (Bin _ kx x l r) = case compare k kx of LT -> goJust k kx' x' l
EQ -> Just (kx, x)
GT -> goJust k kx x r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupLE #-}
#else
{-# INLINE lookupLE #-}
#endif
-- | /O(log n)/. Find smallest key greater or equal to the given one and return
-- the corresponding (key, value) pair.
--
-- > lookupGE 3 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
-- > lookupGE 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
-- > lookupGE 6 (fromList [(3,'a'), (5,'b')]) == Nothing
lookupGE :: Ord k => k -> Map k v -> Maybe (k, v)
lookupGE = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing k (Bin _ kx x l r) = case compare k kx of LT -> goJust k kx x l
EQ -> Just (kx, x)
GT -> goNothing k r
STRICT_1_OF_4(goJust)
goJust _ kx' x' Tip = Just (kx', x')
goJust k kx' x' (Bin _ kx x l r) = case compare k kx of LT -> goJust k kx x l
EQ -> Just (kx, x)
GT -> goJust k kx' x' r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupGE #-}
#else
{-# INLINE lookupGE #-}
#endif
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. The empty map.
--
-- > empty == fromList []
-- > size empty == 0
empty :: Map k a
empty = Tip
{-# INLINE empty #-}
-- | /O(1)/. A map with a single element.
--
-- > singleton 1 'a' == fromList [(1, 'a')]
-- > size (singleton 1 'a') == 1
singleton :: k -> a -> Map k a
singleton k x = Bin 1 k x Tip Tip
{-# INLINE singleton #-}
{--------------------------------------------------------------------
Insertion
--------------------------------------------------------------------}
-- | /O(log n)/. Insert a new key and value in the map.
-- If the key is already present in the map, the associated value is
-- replaced with the supplied value. 'insert' is equivalent to
-- @'insertWith' 'const'@.
--
-- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
-- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
-- > insert 5 'x' empty == singleton 5 'x'
-- See Note: Type of local 'go' function
insert :: Ord k => k -> a -> Map k a -> Map k a
insert = go
where
go :: Ord k => k -> a -> Map k a -> Map k a
STRICT_1_OF_3(go)
go kx x Tip = singleton kx x
go kx x (Bin sz ky y l r) =
case compare kx ky of
LT -> balanceL ky y (go kx x l) r
GT -> balanceR ky y l (go kx x r)
EQ -> Bin sz kx x l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insert #-}
#else
{-# INLINE insert #-}
#endif
-- Insert a new key and value in the map if it is not already present.
-- Used by `union`.
-- See Note: Type of local 'go' function
insertR :: Ord k => k -> a -> Map k a -> Map k a
insertR = go
where
go :: Ord k => k -> a -> Map k a -> Map k a
STRICT_1_OF_3(go)
go kx x Tip = singleton kx x
go kx x t@(Bin _ ky y l r) =
case compare kx ky of
LT -> balanceL ky y (go kx x l) r
GT -> balanceR ky y l (go kx x r)
EQ -> t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertR #-}
#else
{-# INLINE insertR #-}
#endif
-- | /O(log n)/. Insert with a function, combining new value and old value.
-- @'insertWith' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key, f new_value old_value)@.
--
-- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
-- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWith f = insertWithKey (\_ x' y' -> f x' y')
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertWith #-}
#else
{-# INLINE insertWith #-}
#endif
-- | /O(log n)/. Insert with a function, combining key, new value and old value.
-- @'insertWithKey' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key,f key new_value old_value)@.
-- Note that the key passed to f is the same key passed to 'insertWithKey'.
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
-- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
-- See Note: Type of local 'go' function
insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWithKey = go
where
go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
STRICT_2_OF_4(go)
go _ kx x Tip = singleton kx x
go f kx x (Bin sy ky y l r) =
case compare kx ky of
LT -> balanceL ky y (go f kx x l) r
GT -> balanceR ky y l (go f kx x r)
EQ -> Bin sy kx (f kx x y) l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertWithKey #-}
#else
{-# INLINE insertWithKey #-}
#endif
-- | /O(log n)/. Combines insert operation with old value retrieval.
-- The expression (@'insertLookupWithKey' f k x map@)
-- is a pair where the first element is equal to (@'lookup' k map@)
-- and the second element equal to (@'insertWithKey' f k x map@).
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
-- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
-- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
--
-- This is how to define @insertLookup@ using @insertLookupWithKey@:
--
-- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
-- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
-- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
-- See Note: Type of local 'go' function
insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
-> (Maybe a, Map k a)
insertLookupWithKey = go
where
go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a, Map k a)
STRICT_2_OF_4(go)
go _ kx x Tip = (Nothing, singleton kx x)
go f kx x (Bin sy ky y l r) =
case compare kx ky of
LT -> let (found, l') = go f kx x l
in (found, balanceL ky y l' r)
GT -> let (found, r') = go f kx x r
in (found, balanceR ky y l r')
EQ -> (Just y, Bin sy kx (f kx x y) l r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertLookupWithKey #-}
#else
{-# INLINE insertLookupWithKey #-}
#endif
{--------------------------------------------------------------------
Deletion
--------------------------------------------------------------------}
-- | /O(log n)/. Delete a key and its value from the map. When the key is not
-- a member of the map, the original map is returned.
--
-- > delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > delete 5 empty == empty
-- See Note: Type of local 'go' function
delete :: Ord k => k -> Map k a -> Map k a
delete = go
where
go :: Ord k => k -> Map k a -> Map k a
STRICT_1_OF_2(go)
go _ Tip = Tip
go k (Bin _ kx x l r) =
case compare k kx of
LT -> balanceR kx x (go k l) r
GT -> balanceL kx x l (go k r)
EQ -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE delete #-}
#else
{-# INLINE delete #-}
#endif
-- | /O(log n)/. Update a value at a specific key with the result of the provided function.
-- When the key is not
-- a member of the map, the original map is returned.
--
-- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjust ("new " ++) 7 empty == empty
adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
adjust f = adjustWithKey (\_ x -> f x)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE adjust #-}
#else
{-# INLINE adjust #-}
#endif
-- | /O(log n)/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
--
-- > let f key x = (show key) ++ ":new " ++ x
-- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjustWithKey f 7 empty == empty
adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE adjustWithKey #-}
#else
{-# INLINE adjustWithKey #-}
#endif
-- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
-- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
update f = updateWithKey (\_ x -> f x)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE update #-}
#else
{-# INLINE update #-}
#endif
-- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
-- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
-- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
-- to the new value @y@.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
-- See Note: Type of local 'go' function
updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
updateWithKey = go
where
go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
STRICT_2_OF_3(go)
go _ _ Tip = Tip
go f k(Bin sx kx x l r) =
case compare k kx of
LT -> balanceR kx x (go f k l) r
GT -> balanceL kx x l (go f k r)
EQ -> case f kx x of
Just x' -> Bin sx kx x' l r
Nothing -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE updateWithKey #-}
#else
{-# INLINE updateWithKey #-}
#endif
-- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
-- The function returns changed value, if it is updated.
-- Returns the original key value if the map entry is deleted.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
-- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
-- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
-- See Note: Type of local 'go' function
updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
updateLookupWithKey = go
where
go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
STRICT_2_OF_3(go)
go _ _ Tip = (Nothing,Tip)
go f k (Bin sx kx x l r) =
case compare k kx of
LT -> let (found,l') = go f k l in (found,balanceR kx x l' r)
GT -> let (found,r') = go f k r in (found,balanceL kx x l r')
EQ -> case f kx x of
Just x' -> (Just x',Bin sx kx x' l r)
Nothing -> (Just x,glue l r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE updateLookupWithKey #-}
#else
{-# INLINE updateLookupWithKey #-}
#endif
-- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
-- 'alter' can be used to insert, delete, or update a value in a 'Map'.
-- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
--
-- > let f _ = Nothing
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- >
-- > let f _ = Just "c"
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
-- See Note: Type of local 'go' function
alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
alter = go
where
go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
STRICT_2_OF_3(go)
go f k Tip = case f Nothing of
Nothing -> Tip
Just x -> singleton k x
go f k (Bin sx kx x l r) = case compare k kx of
LT -> balance kx x (go f k l) r
GT -> balance kx x l (go f k r)
EQ -> case f (Just x) of
Just x' -> Bin sx kx x' l r
Nothing -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE alter #-}
#else
{-# INLINE alter #-}
#endif
{--------------------------------------------------------------------
Indexing
--------------------------------------------------------------------}
-- | /O(log n)/. Return the /index/ of a key, which is its zero-based index in
-- the sequence sorted by keys. The index is a number from /0/ up to, but not
-- including, the 'size' of the map. Calls 'error' when the key is not
-- a 'member' of the map.
--
-- > findIndex 2 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map
-- > findIndex 3 (fromList [(5,"a"), (3,"b")]) == 0
-- > findIndex 5 (fromList [(5,"a"), (3,"b")]) == 1
-- > findIndex 6 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map
-- See Note: Type of local 'go' function
findIndex :: Ord k => k -> Map k a -> Int
findIndex = go 0
where
go :: Ord k => Int -> k -> Map k a -> Int
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go _ _ Tip = error "Map.findIndex: element is not in the map"
go idx k (Bin _ kx _ l r) = case compare k kx of
LT -> go idx k l
GT -> go (idx + size l + 1) k r
EQ -> idx + size l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE findIndex #-}
#endif
-- | /O(log n)/. Lookup the /index/ of a key, which is its zero-based index in
-- the sequence sorted by keys. The index is a number from /0/ up to, but not
-- including, the 'size' of the map.
--
-- > isJust (lookupIndex 2 (fromList [(5,"a"), (3,"b")])) == False
-- > fromJust (lookupIndex 3 (fromList [(5,"a"), (3,"b")])) == 0
-- > fromJust (lookupIndex 5 (fromList [(5,"a"), (3,"b")])) == 1
-- > isJust (lookupIndex 6 (fromList [(5,"a"), (3,"b")])) == False
-- See Note: Type of local 'go' function
lookupIndex :: Ord k => k -> Map k a -> Maybe Int
lookupIndex = go 0
where
go :: Ord k => Int -> k -> Map k a -> Maybe Int
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go _ _ Tip = Nothing
go idx k (Bin _ kx _ l r) = case compare k kx of
LT -> go idx k l
GT -> go (idx + size l + 1) k r
EQ -> Just $! idx + size l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupIndex #-}
#endif
-- | /O(log n)/. Retrieve an element by its /index/, i.e. by its zero-based
-- index in the sequence sorted by keys. If the /index/ is out of range (less
-- than zero, greater or equal to 'size' of the map), 'error' is called.
--
-- > elemAt 0 (fromList [(5,"a"), (3,"b")]) == (3,"b")
-- > elemAt 1 (fromList [(5,"a"), (3,"b")]) == (5, "a")
-- > elemAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
elemAt :: Int -> Map k a -> (k,a)
STRICT_1_OF_2(elemAt)
elemAt _ Tip = error "Map.elemAt: index out of range"
elemAt i (Bin _ kx x l r)
= case compare i sizeL of
LT -> elemAt i l
GT -> elemAt (i-sizeL-1) r
EQ -> (kx,x)
where
sizeL = size l
-- | /O(log n)/. Update the element at /index/, i.e. by its zero-based index in
-- the sequence sorted by keys. If the /index/ is out of range (less than zero,
-- greater or equal to 'size' of the map), 'error' is called.
--
-- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
-- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
-- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
-- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
updateAt f i t = i `seq`
case t of
Tip -> error "Map.updateAt: index out of range"
Bin sx kx x l r -> case compare i sizeL of
LT -> balanceR kx x (updateAt f i l) r
GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
EQ -> case f kx x of
Just x' -> Bin sx kx x' l r
Nothing -> glue l r
where
sizeL = size l
-- | /O(log n)/. Delete the element at /index/, i.e. by its zero-based index in
-- the sequence sorted by keys. If the /index/ is out of range (less than zero,
-- greater or equal to 'size' of the map), 'error' is called.
--
-- > deleteAt 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
-- > deleteAt 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > deleteAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > deleteAt (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
deleteAt :: Int -> Map k a -> Map k a
deleteAt i t = i `seq`
case t of
Tip -> error "Map.deleteAt: index out of range"
Bin _ kx x l r -> case compare i sizeL of
LT -> balanceR kx x (deleteAt i l) r
GT -> balanceL kx x l (deleteAt (i-sizeL-1) r)
EQ -> glue l r
where
sizeL = size l
{--------------------------------------------------------------------
Minimal, Maximal
--------------------------------------------------------------------}
-- | /O(log n)/. The minimal key of the map. Calls 'error' if the map is empty.
--
-- > findMin (fromList [(5,"a"), (3,"b")]) == (3,"b")
-- > findMin empty Error: empty map has no minimal element
findMin :: Map k a -> (k,a)
findMin (Bin _ kx x Tip _) = (kx,x)
findMin (Bin _ _ _ l _) = findMin l
findMin Tip = error "Map.findMin: empty map has no minimal element"
-- | /O(log n)/. The maximal key of the map. Calls 'error' if the map is empty.
--
-- > findMax (fromList [(5,"a"), (3,"b")]) == (5,"a")
-- > findMax empty Error: empty map has no maximal element
findMax :: Map k a -> (k,a)
findMax (Bin _ kx x _ Tip) = (kx,x)
findMax (Bin _ _ _ _ r) = findMax r
findMax Tip = error "Map.findMax: empty map has no maximal element"
-- | /O(log n)/. Delete the minimal key. Returns an empty map if the map is empty.
--
-- > deleteMin (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(5,"a"), (7,"c")]
-- > deleteMin empty == empty
deleteMin :: Map k a -> Map k a
deleteMin (Bin _ _ _ Tip r) = r
deleteMin (Bin _ kx x l r) = balanceR kx x (deleteMin l) r
deleteMin Tip = Tip
-- | /O(log n)/. Delete the maximal key. Returns an empty map if the map is empty.
--
-- > deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")]
-- > deleteMax empty == empty
deleteMax :: Map k a -> Map k a
deleteMax (Bin _ _ _ l Tip) = l
deleteMax (Bin _ kx x l r) = balanceL kx x l (deleteMax r)
deleteMax Tip = Tip
-- | /O(log n)/. Update the value at the minimal key.
--
-- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
-- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMin :: (a -> Maybe a) -> Map k a -> Map k a
updateMin f m
= updateMinWithKey (\_ x -> f x) m
-- | /O(log n)/. Update the value at the maximal key.
--
-- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
-- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMax :: (a -> Maybe a) -> Map k a -> Map k a
updateMax f m
= updateMaxWithKey (\_ x -> f x) m
-- | /O(log n)/. Update the value at the minimal key.
--
-- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
-- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
updateMinWithKey _ Tip = Tip
updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
Nothing -> r
Just x' -> Bin sx kx x' Tip r
updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
-- | /O(log n)/. Update the value at the maximal key.
--
-- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
-- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
updateMaxWithKey _ Tip = Tip
updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
Nothing -> l
Just x' -> Bin sx kx x' l Tip
updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
-- | /O(log n)/. Retrieves the minimal (key,value) pair of the map, and
-- the map stripped of that element, or 'Nothing' if passed an empty map.
--
-- > minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a")
-- > minViewWithKey empty == Nothing
minViewWithKey :: Map k a -> Maybe ((k,a), Map k a)
minViewWithKey Tip = Nothing
minViewWithKey x = Just (deleteFindMin x)
-- | /O(log n)/. Retrieves the maximal (key,value) pair of the map, and
-- the map stripped of that element, or 'Nothing' if passed an empty map.
--
-- > maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b")
-- > maxViewWithKey empty == Nothing
maxViewWithKey :: Map k a -> Maybe ((k,a), Map k a)
maxViewWithKey Tip = Nothing
maxViewWithKey x = Just (deleteFindMax x)
-- | /O(log n)/. Retrieves the value associated with minimal key of the
-- map, and the map stripped of that element, or 'Nothing' if passed an
-- empty map.
--
-- > minView (fromList [(5,"a"), (3,"b")]) == Just ("b", singleton 5 "a")
-- > minView empty == Nothing
minView :: Map k a -> Maybe (a, Map k a)
minView Tip = Nothing
minView x = Just (first snd $ deleteFindMin x)
-- | /O(log n)/. Retrieves the value associated with maximal key of the
-- map, and the map stripped of that element, or 'Nothing' if passed an
-- empty map.
--
-- > maxView (fromList [(5,"a"), (3,"b")]) == Just ("a", singleton 3 "b")
-- > maxView empty == Nothing
maxView :: Map k a -> Maybe (a, Map k a)
maxView Tip = Nothing
maxView x = Just (first snd $ deleteFindMax x)
-- Update the 1st component of a tuple (special case of Control.Arrow.first)
first :: (a -> b) -> (a,c) -> (b,c)
first f (x,y) = (f x, y)
{--------------------------------------------------------------------
Union.
--------------------------------------------------------------------}
-- | The union of a list of maps:
-- (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
--
-- > unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "b"), (5, "a"), (7, "C")]
-- > unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])]
-- > == fromList [(3, "B3"), (5, "A3"), (7, "C")]
unions :: Ord k => [Map k a] -> Map k a
unions ts
= foldlStrict union empty ts
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unions #-}
#endif
-- | The union of a list of maps, with a combining operation:
-- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
--
-- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
unionsWith f ts
= foldlStrict (unionWith f) empty ts
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionsWith #-}
#endif
-- | /O(n+m)/.
-- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
-- It prefers @t1@ when duplicate keys are encountered,
-- i.e. (@'union' == 'unionWith' 'const'@).
-- The implementation uses the efficient /hedge-union/ algorithm.
--
-- > union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]
union :: Ord k => Map k a -> Map k a -> Map k a
union Tip t2 = t2
union t1 Tip = t1
union t1 t2 = hedgeUnion NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE union #-}
#endif
-- left-biased hedge union
hedgeUnion :: Ord a => MaybeS a -> MaybeS a -> Map a b -> Map a b -> Map a b
hedgeUnion _ _ t1 Tip = t1
hedgeUnion blo bhi Tip (Bin _ kx x l r) = link kx x (filterGt blo l) (filterLt bhi r)
hedgeUnion _ _ t1 (Bin _ kx x Tip Tip) = insertR kx x t1 -- According to benchmarks, this special case increases
-- performance up to 30%. It does not help in difference or intersection.
hedgeUnion blo bhi (Bin _ kx x l r) t2 = link kx x (hedgeUnion blo bmi l (trim blo bmi t2))
(hedgeUnion bmi bhi r (trim bmi bhi t2))
where bmi = JustS kx
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeUnion #-}
#endif
{--------------------------------------------------------------------
Union with a combining function
--------------------------------------------------------------------}
-- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
--
-- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWith f m1 m2
= unionWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionWith #-}
#endif
-- | /O(n+m)/.
-- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
--
-- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
-- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionWithKey #-}
#endif
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
-- | /O(n+m)/. Difference of two maps.
-- Return elements of the first map not existing in the second map.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"
difference :: Ord k => Map k a -> Map k b -> Map k a
difference Tip _ = Tip
difference t1 Tip = t1
difference t1 t2 = hedgeDiff NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE difference #-}
#endif
hedgeDiff :: Ord a => MaybeS a -> MaybeS a -> Map a b -> Map a c -> Map a b
hedgeDiff _ _ Tip _ = Tip
hedgeDiff blo bhi (Bin _ kx x l r) Tip = link kx x (filterGt blo l) (filterLt bhi r)
hedgeDiff blo bhi t (Bin _ kx _ l r) = merge (hedgeDiff blo bmi (trim blo bmi t) l)
(hedgeDiff bmi bhi (trim bmi bhi t) r)
where bmi = JustS kx
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeDiff #-}
#endif
-- | /O(n+m)/. Difference with a combining function.
-- When two equal keys are
-- encountered, the combining function is applied to the values of these keys.
-- If it returns 'Nothing', the element is discarded (proper set difference). If
-- it returns (@'Just' y@), the element is updated with a new value @y@.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
-- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
-- > == singleton 3 "b:B"
differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
differenceWith f m1 m2
= differenceWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE differenceWith #-}
#endif
-- | /O(n+m)/. Difference with a combining function. When two equal keys are
-- encountered, the combining function is applied to the key and both values.
-- If it returns 'Nothing', the element is discarded (proper set difference). If
-- it returns (@'Just' y@), the element is updated with a new value @y@.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
-- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
-- > == singleton 3 "3:b|B"
differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE differenceWithKey #-}
#endif
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
-- | /O(n+m)/. Intersection of two maps.
-- Return data in the first map for the keys existing in both maps.
-- (@'intersection' m1 m2 == 'intersectionWith' 'const' m1 m2@).
-- The implementation uses an efficient /hedge/ algorithm comparable with
-- /hedge-union/.
--
-- > intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a"
intersection :: Ord k => Map k a -> Map k b -> Map k a
intersection Tip _ = Tip
intersection _ Tip = Tip
intersection t1 t2 = hedgeInt NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersection #-}
#endif
hedgeInt :: Ord k => MaybeS k -> MaybeS k -> Map k a -> Map k b -> Map k a
hedgeInt _ _ _ Tip = Tip
hedgeInt _ _ Tip _ = Tip
hedgeInt blo bhi (Bin _ kx x l r) t2 = let l' = hedgeInt blo bmi l (trim blo bmi t2)
r' = hedgeInt bmi bhi r (trim bmi bhi t2)
in if kx `member` t2 then link kx x l' r' else merge l' r'
where bmi = JustS kx
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeInt #-}
#endif
-- | /O(n+m)/. Intersection with a combining function. The implementation uses
-- an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
intersectionWith f m1 m2
= intersectionWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersectionWith #-}
#endif
-- | /O(n+m)/. Intersection with a combining function. The implementation uses
-- an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
-- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersectionWithKey #-}
#endif
{--------------------------------------------------------------------
MergeWithKey
--------------------------------------------------------------------}
-- | /O(n+m)/. A high-performance universal combining function. This function
-- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
-- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
-- used to define other custom combine functions.
--
-- Please make sure you know what is going on when using 'mergeWithKey',
-- otherwise you can be surprised by unexpected code growth or even
-- corruption of the data structure.
--
-- When 'mergeWithKey' is given three arguments, it is inlined to the call
-- site. You should therefore use 'mergeWithKey' only to define your custom
-- combining functions. For example, you could define 'unionWithKey',
-- 'differenceWithKey' and 'intersectionWithKey' as
--
-- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
-- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
-- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
--
-- When calling @'mergeWithKey' combine only1 only2@, a function combining two
-- 'IntMap's is created, such that
--
-- * if a key is present in both maps, it is passed with both corresponding
-- values to the @combine@ function. Depending on the result, the key is either
-- present in the result with specified value, or is left out;
--
-- * a nonempty subtree present only in the first map is passed to @only1@ and
-- the output is added to the result;
--
-- * a nonempty subtree present only in the second map is passed to @only2@ and
-- the output is added to the result.
--
-- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
-- The values can be modified arbitrarily. Most common variants of @only1@ and
-- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
-- @'filterWithKey' f@ could be used for any @f@.
mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
-> Map k a -> Map k b -> Map k c
mergeWithKey f g1 g2 = go
where
go Tip t2 = g2 t2
go t1 Tip = g1 t1
go t1 t2 = hedgeMerge NothingS NothingS t1 t2
hedgeMerge _ _ t1 Tip = g1 t1
hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r)
hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
(found, trim_t2) = trimLookupLo kx bhi t2
r' = hedgeMerge bmi bhi r trim_t2
in case found of
Nothing -> case g1 (singleton kx x) of
Tip -> merge l' r'
(Bin _ _ x' Tip Tip) -> link kx x' l' r'
_ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
Just x2 -> case f kx x x2 of
Nothing -> merge l' r'
Just x' -> link kx x' l' r'
where bmi = JustS kx
{-# INLINE mergeWithKey #-}
{--------------------------------------------------------------------
Submap
--------------------------------------------------------------------}
-- | /O(n+m)/.
-- This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
--
isSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
isSubmapOf m1 m2 = isSubmapOfBy (==) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isSubmapOf #-}
#endif
{- | /O(n+m)/.
The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if
all keys in @t1@ are in tree @t2@, and when @f@ returns 'True' when
applied to their respective values. For example, the following
expressions are all 'True':
> isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
> isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
> isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
But the following are all 'False':
> isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
> isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
> isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
-}
isSubmapOfBy :: Ord k => (a->b->Bool) -> Map k a -> Map k b -> Bool
isSubmapOfBy f t1 t2
= (size t1 <= size t2) && (submap' f t1 t2)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isSubmapOfBy #-}
#endif
submap' :: Ord a => (b -> c -> Bool) -> Map a b -> Map a c -> Bool
submap' _ Tip _ = True
submap' _ _ Tip = False
submap' f (Bin _ kx x l r) t
= case found of
Nothing -> False
Just y -> f x y && submap' f l lt && submap' f r gt
where
(lt,found,gt) = splitLookup kx t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE submap' #-}
#endif
-- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
-- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
isProperSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
isProperSubmapOf m1 m2
= isProperSubmapOfBy (==) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isProperSubmapOf #-}
#endif
{- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
@m1@ and @m2@ are not equal,
all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
applied to their respective values. For example, the following
expressions are all 'True':
> isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
> isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
But the following are all 'False':
> isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
> isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
> isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
-}
isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool
isProperSubmapOfBy f t1 t2
= (size t1 < size t2) && (submap' f t1 t2)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isProperSubmapOfBy #-}
#endif
{--------------------------------------------------------------------
Filter and partition
--------------------------------------------------------------------}
-- | /O(n)/. Filter all values that satisfy the predicate.
--
-- > filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty
-- > filter (< "a") (fromList [(5,"a"), (3,"b")]) == empty
filter :: (a -> Bool) -> Map k a -> Map k a
filter p m
= filterWithKey (\_ x -> p x) m
-- | /O(n)/. Filter all keys\/values that satisfy the predicate.
--
-- > filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
filterWithKey :: (k -> a -> Bool) -> Map k a -> Map k a
filterWithKey _ Tip = Tip
filterWithKey p (Bin _ kx x l r)
| p kx x = link kx x (filterWithKey p l) (filterWithKey p r)
| otherwise = merge (filterWithKey p l) (filterWithKey p r)
-- | /O(n)/. Partition the map according to a predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
--
-- > partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
-- > partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
-- > partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
partition :: (a -> Bool) -> Map k a -> (Map k a,Map k a)
partition p m
= partitionWithKey (\_ x -> p x) m
-- | /O(n)/. Partition the map according to a predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
--
-- > partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b")
-- > partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
-- > partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
partitionWithKey :: (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
partitionWithKey p0 t0 = toPair $ go p0 t0
where
go _ Tip = (Tip :*: Tip)
go p (Bin _ kx x l r)
| p kx x = link kx x l1 r1 :*: merge l2 r2
| otherwise = merge l1 r1 :*: link kx x l2 r2
where
(l1 :*: l2) = go p l
(r1 :*: r2) = go p r
-- | /O(n)/. Map values and collect the 'Just' results.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
mapMaybe f = mapMaybeWithKey (\_ x -> f x)
-- | /O(n)/. Map keys\/values and collect the 'Just' results.
--
-- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
-- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
mapMaybeWithKey _ Tip = Tip
mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
Just y -> link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
-- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
--
-- > let f a = if a < "c" then Left a else Right a
-- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
-- >
-- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEither f m
= mapEitherWithKey (\_ x -> f x) m
-- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
--
-- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
-- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
-- >
-- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEitherWithKey f0 t0 = toPair $ go f0 t0
where
go _ Tip = (Tip :*: Tip)
go f (Bin _ kx x l r) = case f kx x of
Left y -> link kx y l1 r1 :*: merge l2 r2
Right z -> merge l1 r1 :*: link kx z l2 r2
where
(l1 :*: l2) = go f l
(r1 :*: r2) = go f r
{--------------------------------------------------------------------
Mapping
--------------------------------------------------------------------}
-- | /O(n)/. Map a function over all values in the map.
--
-- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
map :: (a -> b) -> Map k a -> Map k b
map _ Tip = Tip
map f (Bin sx kx x l r) = Bin sx kx (f x) (map f l) (map f r)
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] map #-}
{-# RULES
"map/map" forall f g xs . map f (map g xs) = map (f . g) xs
#-}
#endif
#if __GLASGOW_HASKELL__ >= 709
-- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
{-# RULES
"map/coerce" map coerce = coerce
#-}
#endif
-- | /O(n)/. Map a function over all values in the map.
--
-- > let f key x = (show key) ++ ":" ++ x
-- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
mapWithKey _ Tip = Tip
mapWithKey f (Bin sx kx x l r) = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] mapWithKey #-}
{-# RULES
"mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
mapWithKey (\k a -> f k (g k a)) xs
"mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
mapWithKey (\k a -> f k (g a)) xs
"map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
mapWithKey (\k a -> f (g k a)) xs
#-}
#endif
-- | /O(n)/.
-- @'traverseWithKey' f s == 'fromList' <$> 'traverse' (\(k, v) -> (,) k <$> f k v) ('toList' m)@
-- That is, behaves exactly like a regular 'traverse' except that the traversing
-- function also has access to the key associated with a value.
--
-- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')])
-- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == Nothing
traverseWithKey :: Applicative t => (k -> a -> t b) -> Map k a -> t (Map k b)
traverseWithKey f = go
where
go Tip = pure Tip
go (Bin 1 k v _ _) = (\v' -> Bin 1 k v' Tip Tip) <$> f k v
go (Bin s k v l r) = flip (Bin s k) <$> go l <*> f k v <*> go r
{-# INLINE traverseWithKey #-}
-- | /O(n)/. The function 'mapAccum' threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a b = (a ++ b, b ++ "X")
-- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccum f a m
= mapAccumWithKey (\a' _ x' -> f a' x') a m
-- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
-- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumWithKey f a t
= mapAccumL f a t
-- | /O(n)/. The function 'mapAccumL' threads an accumulating
-- argument through the map in ascending order of keys.
mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumL _ a Tip = (a,Tip)
mapAccumL f a (Bin sx kx x l r) =
let (a1,l') = mapAccumL f a l
(a2,x') = f a1 kx x
(a3,r') = mapAccumL f a2 r
in (a3,Bin sx kx x' l' r')
-- | /O(n)/. The function 'mapAccumR' threads an accumulating
-- argument through the map in descending order of keys.
mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumRWithKey _ a Tip = (a,Tip)
mapAccumRWithKey f a (Bin sx kx x l r) =
let (a1,r') = mapAccumRWithKey f a r
(a2,x') = f a1 kx x
(a3,l') = mapAccumRWithKey f a2 l
in (a3,Bin sx kx x' l' r')
-- | /O(n*log n)/.
-- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the value at the greatest of the
-- original keys is retained.
--
-- > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")]
-- > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
-- > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"
mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
mapKeys f = fromList . foldrWithKey (\k x xs -> (f k, x) : xs) []
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE mapKeys #-}
#endif
-- | /O(n*log n)/.
-- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the associated values will be
-- combined using @c@.
--
-- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
-- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE mapKeysWith #-}
#endif
-- | /O(n)/.
-- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
-- is strictly monotonic.
-- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@.
-- /The precondition is not checked./
-- Semi-formally, we have:
--
-- > and [x < y ==> f x < f y | x <- ls, y <- ls]
-- > ==> mapKeysMonotonic f s == mapKeys f s
-- > where ls = keys s
--
-- This means that @f@ maps distinct original keys to distinct resulting keys.
-- This function has better performance than 'mapKeys'.
--
-- > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]
-- > valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True
-- > valid (mapKeysMonotonic (\ _ -> 1) (fromList [(5,"a"), (3,"b")])) == False
mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
mapKeysMonotonic _ Tip = Tip
mapKeysMonotonic f (Bin sz k x l r) =
Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
{--------------------------------------------------------------------
Folds
--------------------------------------------------------------------}
-- | /O(n)/. Fold the values in the map using the given right-associative
-- binary operator, such that @'foldr' f z == 'Prelude.foldr' f z . 'elems'@.
--
-- For example,
--
-- > elems map = foldr (:) [] map
--
-- > let f a len = len + (length a)
-- > foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
foldr :: (a -> b -> b) -> b -> Map k a -> b
foldr f z = go z
where
go z' Tip = z'
go z' (Bin _ _ x l r) = go (f x (go z' r)) l
{-# INLINE foldr #-}
-- | /O(n)/. A strict version of 'foldr'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldr' :: (a -> b -> b) -> b -> Map k a -> b
foldr' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ _ x l r) = go (f x (go z' r)) l
{-# INLINE foldr' #-}
-- | /O(n)/. Fold the values in the map using the given left-associative
-- binary operator, such that @'foldl' f z == 'Prelude.foldl' f z . 'elems'@.
--
-- For example,
--
-- > elems = reverse . foldl (flip (:)) []
--
-- > let f len a = len + (length a)
-- > foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
foldl :: (a -> b -> a) -> a -> Map k b -> a
foldl f z = go z
where
go z' Tip = z'
go z' (Bin _ _ x l r) = go (f (go z' l) x) r
{-# INLINE foldl #-}
-- | /O(n)/. A strict version of 'foldl'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldl' :: (a -> b -> a) -> a -> Map k b -> a
foldl' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ _ x l r) = go (f (go z' l) x) r
{-# INLINE foldl' #-}
-- | /O(n)/. Fold the keys and values in the map using the given right-associative
-- binary operator, such that
-- @'foldrWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
--
-- For example,
--
-- > keys map = foldrWithKey (\k x ks -> k:ks) [] map
--
-- > let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
-- > foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"
foldrWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
foldrWithKey f z = go z
where
go z' Tip = z'
go z' (Bin _ kx x l r) = go (f kx x (go z' r)) l
{-# INLINE foldrWithKey #-}
-- | /O(n)/. A strict version of 'foldrWithKey'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldrWithKey' :: (k -> a -> b -> b) -> b -> Map k a -> b
foldrWithKey' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ kx x l r) = go (f kx x (go z' r)) l
{-# INLINE foldrWithKey' #-}
-- | /O(n)/. Fold the keys and values in the map using the given left-associative
-- binary operator, such that
-- @'foldlWithKey' f z == 'Prelude.foldl' (\\z' (kx, x) -> f z' kx x) z . 'toAscList'@.
--
-- For example,
--
-- > keys = reverse . foldlWithKey (\ks k x -> k:ks) []
--
-- > let f result k a = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
-- > foldlWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (3:b)(5:a)"
foldlWithKey :: (a -> k -> b -> a) -> a -> Map k b -> a
foldlWithKey f z = go z
where
go z' Tip = z'
go z' (Bin _ kx x l r) = go (f (go z' l) kx x) r
{-# INLINE foldlWithKey #-}
-- | /O(n)/. A strict version of 'foldlWithKey'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldlWithKey' :: (a -> k -> b -> a) -> a -> Map k b -> a
foldlWithKey' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ kx x l r) = go (f (go z' l) kx x) r
{-# INLINE foldlWithKey' #-}
-- | /O(n)/. Fold the keys and values in the map using the given monoid, such that
--
-- @'foldMapWithKey' f = 'Prelude.fold' . 'mapWithKey' f@
--
-- This can be an asymptotically faster than 'foldrWithKey' or 'foldlWithKey' for some monoids.
foldMapWithKey :: Monoid m => (k -> a -> m) -> Map k a -> m
foldMapWithKey f = go
where
go Tip = mempty
go (Bin 1 k v _ _) = f k v
go (Bin _ k v l r) = go l `mappend` (f k v `mappend` go r)
{-# INLINE foldMapWithKey #-}
{--------------------------------------------------------------------
List variations
--------------------------------------------------------------------}
-- | /O(n)/.
-- Return all elements of the map in the ascending order of their keys.
-- Subject to list fusion.
--
-- > elems (fromList [(5,"a"), (3,"b")]) == ["b","a"]
-- > elems empty == []
elems :: Map k a -> [a]
elems = foldr (:) []
-- | /O(n)/. Return all keys of the map in ascending order. Subject to list
-- fusion.
--
-- > keys (fromList [(5,"a"), (3,"b")]) == [3,5]
-- > keys empty == []
keys :: Map k a -> [k]
keys = foldrWithKey (\k _ ks -> k : ks) []
-- | /O(n)/. An alias for 'toAscList'. Return all key\/value pairs in the map
-- in ascending key order. Subject to list fusion.
--
-- > assocs (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
-- > assocs empty == []
assocs :: Map k a -> [(k,a)]
assocs m
= toAscList m
-- | /O(n)/. The set of all keys of the map.
--
-- > keysSet (fromList [(5,"a"), (3,"b")]) == Data.Set.fromList [3,5]
-- > keysSet empty == Data.Set.empty
keysSet :: Map k a -> Set.Set k
keysSet Tip = Set.Tip
keysSet (Bin sz kx _ l r) = Set.Bin sz kx (keysSet l) (keysSet r)
-- | /O(n)/. Build a map from a set of keys and a function which for each key
-- computes its value.
--
-- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
-- > fromSet undefined Data.Set.empty == empty
fromSet :: (k -> a) -> Set.Set k -> Map k a
fromSet _ Set.Tip = Tip
fromSet f (Set.Bin sz x l r) = Bin sz x (f x) (fromSet f l) (fromSet f r)
{--------------------------------------------------------------------
Lists
use [foldlStrict] to reduce demand on the control-stack
--------------------------------------------------------------------}
#if __GLASGOW_HASKELL__ >= 708
instance (Ord k) => GHCExts.IsList (Map k v) where
type Item (Map k v) = (k,v)
fromList = fromList
toList = toList
#endif
-- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
-- If the list contains more than one value for the same key, the last value
-- for the key is retained.
--
-- If the keys of the list are ordered, linear-time implementation is used,
-- with the performance equal to 'fromDistinctAscList'.
--
-- > fromList [] == empty
-- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
-- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
-- For some reason, when 'singleton' is used in fromList or in
-- create, it is not inlined, so we inline it manually.
fromList :: Ord k => [(k,a)] -> Map k a
fromList [] = Tip
fromList [(kx, x)] = Bin 1 kx x Tip Tip
fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = fromList' (Bin 1 kx0 x0 Tip Tip) xs0
| otherwise = go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
where
not_ordered _ [] = False
not_ordered kx ((ky,_) : _) = kx >= ky
{-# INLINE not_ordered #-}
fromList' t0 xs = foldlStrict ins t0 xs
where ins t (k,x) = insert k x t
STRICT_1_OF_3(go)
go _ t [] = t
go _ t [(kx, x)] = insertMax kx x t
go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
| otherwise = case create s xss of
(r, ys, []) -> go (s `shiftL` 1) (link kx x l r) ys
(r, _, ys) -> fromList' (link kx x l r) ys
-- The create is returning a triple (tree, xs, ys). Both xs and ys
-- represent not yet processed elements and only one of them can be nonempty.
-- If ys is nonempty, the keys in ys are not ordered with respect to tree
-- and must be inserted using fromList'. Otherwise the keys have been
-- ordered so far.
STRICT_1_OF_2(create)
create _ [] = (Tip, [], [])
create s xs@(xp : xss)
| s == 1 = case xp of (kx, x) | not_ordered kx xss -> (Bin 1 kx x Tip Tip, [], xss)
| otherwise -> (Bin 1 kx x Tip Tip, xss, [])
| otherwise = case create (s `shiftR` 1) xs of
res@(_, [], _) -> res
(l, [(ky, y)], zs) -> (insertMax ky y l, [], zs)
(l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
| otherwise -> case create (s `shiftR` 1) yss of
(r, zs, ws) -> (link ky y l r, zs, ws)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromList #-}
#endif
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
--
-- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
-- > fromListWith (++) [] == empty
fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
fromListWith f xs
= fromListWithKey (\_ x y -> f x y) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromListWith #-}
#endif
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
--
-- > let f k a1 a2 = (show k) ++ a1 ++ a2
-- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
-- > fromListWithKey f [] == empty
fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromListWithKey f xs
= foldlStrict ins empty xs
where
ins t (k,x) = insertWithKey f k x t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromListWithKey #-}
#endif
-- | /O(n)/. Convert the map to a list of key\/value pairs. Subject to list fusion.
--
-- > toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
-- > toList empty == []
toList :: Map k a -> [(k,a)]
toList = toAscList
-- | /O(n)/. Convert the map to a list of key\/value pairs where the keys are
-- in ascending order. Subject to list fusion.
--
-- > toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
toAscList :: Map k a -> [(k,a)]
toAscList = foldrWithKey (\k x xs -> (k,x):xs) []
-- | /O(n)/. Convert the map to a list of key\/value pairs where the keys
-- are in descending order. Subject to list fusion.
--
-- > toDescList (fromList [(5,"a"), (3,"b")]) == [(5,"a"), (3,"b")]
toDescList :: Map k a -> [(k,a)]
toDescList = foldlWithKey (\xs k x -> (k,x):xs) []
-- List fusion for the list generating functions.
#if __GLASGOW_HASKELL__
-- The foldrFB and foldlFB are fold{r,l}WithKey equivalents, used for list fusion.
-- They are important to convert unfused methods back, see mapFB in prelude.
foldrFB :: (k -> a -> b -> b) -> b -> Map k a -> b
foldrFB = foldrWithKey
{-# INLINE[0] foldrFB #-}
foldlFB :: (a -> k -> b -> a) -> a -> Map k b -> a
foldlFB = foldlWithKey
{-# INLINE[0] foldlFB #-}
-- Inline assocs and toList, so that we need to fuse only toAscList.
{-# INLINE assocs #-}
{-# INLINE toList #-}
-- The fusion is enabled up to phase 2 included. If it does not succeed,
-- convert in phase 1 the expanded elems,keys,to{Asc,Desc}List calls back to
-- elems,keys,to{Asc,Desc}List. In phase 0, we inline fold{lr}FB (which were
-- used in a list fusion, otherwise it would go away in phase 1), and let compiler
-- do whatever it wants with elems,keys,to{Asc,Desc}List -- it was forbidden to
-- inline it before phase 0, otherwise the fusion rules would not fire at all.
{-# NOINLINE[0] elems #-}
{-# NOINLINE[0] keys #-}
{-# NOINLINE[0] toAscList #-}
{-# NOINLINE[0] toDescList #-}
{-# RULES "Map.elems" [~1] forall m . elems m = build (\c n -> foldrFB (\_ x xs -> c x xs) n m) #-}
{-# RULES "Map.elemsBack" [1] foldrFB (\_ x xs -> x : xs) [] = elems #-}
{-# RULES "Map.keys" [~1] forall m . keys m = build (\c n -> foldrFB (\k _ xs -> c k xs) n m) #-}
{-# RULES "Map.keysBack" [1] foldrFB (\k _ xs -> k : xs) [] = keys #-}
{-# RULES "Map.toAscList" [~1] forall m . toAscList m = build (\c n -> foldrFB (\k x xs -> c (k,x) xs) n m) #-}
{-# RULES "Map.toAscListBack" [1] foldrFB (\k x xs -> (k, x) : xs) [] = toAscList #-}
{-# RULES "Map.toDescList" [~1] forall m . toDescList m = build (\c n -> foldlFB (\xs k x -> c (k,x) xs) n m) #-}
{-# RULES "Map.toDescListBack" [1] foldlFB (\xs k x -> (k, x) : xs) [] = toDescList #-}
#endif
{--------------------------------------------------------------------
Building trees from ascending/descending lists can be done in linear time.
Note that if [xs] is ascending that:
fromAscList xs == fromList xs
fromAscListWith f xs == fromListWith f xs
--------------------------------------------------------------------}
-- | /O(n)/. Build a map from an ascending list in linear time.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
-- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscList :: Eq k => [(k,a)] -> Map k a
fromAscList xs
= fromAscListWithKey (\_ x _ -> x) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscList #-}
#endif
-- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
-- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWith f xs
= fromAscListWithKey (\_ x y -> f x y) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscListWith #-}
#endif
-- | /O(n)/. Build a map from an ascending list in linear time with a
-- combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
-- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
-- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
-- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWithKey f xs
= fromDistinctAscList (combineEq f xs)
where
-- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
combineEq _ xs'
= case xs' of
[] -> []
[x] -> [x]
(x:xx) -> combineEq' x xx
combineEq' z [] = [z]
combineEq' z@(kz,zz) (x@(kx,xx):xs')
| kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs'
| otherwise = z:combineEq' x xs'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscListWithKey #-}
#endif
-- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
-- /The precondition is not checked./
--
-- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
-- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
-- For some reason, when 'singleton' is used in fromDistinctAscList or in
-- create, it is not inlined, so we inline it manually.
fromDistinctAscList :: [(k,a)] -> Map k a
fromDistinctAscList [] = Tip
fromDistinctAscList ((kx0, x0) : xs0) = go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
where
STRICT_1_OF_3(go)
go _ t [] = t
go s l ((kx, x) : xs) = case create s xs of
(r, ys) -> go (s `shiftL` 1) (link kx x l r) ys
STRICT_1_OF_2(create)
create _ [] = (Tip, [])
create s xs@(x' : xs')
| s == 1 = case x' of (kx, x) -> (Bin 1 kx x Tip Tip, xs')
| otherwise = case create (s `shiftR` 1) xs of
res@(_, []) -> res
(l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
(r, zs) -> (link ky y l r, zs)
{--------------------------------------------------------------------
Utility functions that return sub-ranges of the original
tree. Some functions take a `Maybe value` as an argument to
allow comparisons against infinite values. These are called `blow`
(Nothing is -\infty) and `bhigh` (here Nothing is +\infty).
We use MaybeS value, which is a Maybe strict in the Just case.
[trim blow bhigh t] A tree that is either empty or where [x > blow]
and [x < bhigh] for the value [x] of the root.
[filterGt blow t] A tree where for all values [k]. [k > blow]
[filterLt bhigh t] A tree where for all values [k]. [k < bhigh]
[split k t] Returns two trees [l] and [r] where all keys
in [l] are <[k] and all keys in [r] are >[k].
[splitLookup k t] Just like [split] but also returns whether [k]
was found in the tree.
--------------------------------------------------------------------}
data MaybeS a = NothingS | JustS !a
{--------------------------------------------------------------------
[trim blo bhi t] trims away all subtrees that surely contain no
values between the range [blo] to [bhi]. The returned tree is either
empty or the key of the root is between @blo@ and @bhi@.
--------------------------------------------------------------------}
trim :: Ord k => MaybeS k -> MaybeS k -> Map k a -> Map k a
trim NothingS NothingS t = t
trim (JustS lk) NothingS t = greater lk t where greater lo (Bin _ k _ _ r) | k <= lo = greater lo r
greater _ t' = t'
trim NothingS (JustS hk) t = lesser hk t where lesser hi (Bin _ k _ l _) | k >= hi = lesser hi l
lesser _ t' = t'
trim (JustS lk) (JustS hk) t = middle lk hk t where middle lo hi (Bin _ k _ _ r) | k <= lo = middle lo hi r
middle lo hi (Bin _ k _ l _) | k >= hi = middle lo hi l
middle _ _ t' = t'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE trim #-}
#endif
-- Helper function for 'mergeWithKey'. The @'trimLookupLo' lk hk t@ performs both
-- @'trim' (JustS lk) hk t@ and @'lookup' lk t@.
-- See Note: Type of local 'go' function
trimLookupLo :: Ord k => k -> MaybeS k -> Map k a -> (Maybe a, Map k a)
trimLookupLo lk0 mhk0 t0 = toPair $ go lk0 mhk0 t0
where
go lk NothingS t = greater lk t
where greater :: Ord k => k -> Map k a -> StrictPair (Maybe a) (Map k a)
greater lo t'@(Bin _ kx x l r) = case compare lo kx of
LT -> lookup lo l :*: t'
EQ -> (Just x :*: r)
GT -> greater lo r
greater _ Tip = (Nothing :*: Tip)
go lk (JustS hk) t = middle lk hk t
where middle :: Ord k => k -> k -> Map k a -> StrictPair (Maybe a) (Map k a)
middle lo hi t'@(Bin _ kx x l r) = case compare lo kx of
LT | kx < hi -> lookup lo l :*: t'
| otherwise -> middle lo hi l
EQ -> Just x :*: lesser hi r
GT -> middle lo hi r
middle _ _ Tip = (Nothing :*: Tip)
lesser :: Ord k => k -> Map k a -> Map k a
lesser hi (Bin _ k _ l _) | k >= hi = lesser hi l
lesser _ t' = t'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE trimLookupLo #-}
#endif
{--------------------------------------------------------------------
[filterGt b t] filter all keys >[b] from tree [t]
[filterLt b t] filter all keys <[b] from tree [t]
--------------------------------------------------------------------}
filterGt :: Ord k => MaybeS k -> Map k v -> Map k v
filterGt NothingS t = t
filterGt (JustS b) t = filter' b t
where filter' _ Tip = Tip
filter' b' (Bin _ kx x l r) =
case compare b' kx of LT -> link kx x (filter' b' l) r
EQ -> r
GT -> filter' b' r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE filterGt #-}
#endif
filterLt :: Ord k => MaybeS k -> Map k v -> Map k v
filterLt NothingS t = t
filterLt (JustS b) t = filter' b t
where filter' _ Tip = Tip
filter' b' (Bin _ kx x l r) =
case compare kx b' of LT -> link kx x l (filter' b' r)
EQ -> l
GT -> filter' b' l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE filterLt #-}
#endif
{--------------------------------------------------------------------
Split
--------------------------------------------------------------------}
-- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@ where
-- the keys in @map1@ are smaller than @k@ and the keys in @map2@ larger than @k@.
-- Any key equal to @k@ is found in neither @map1@ nor @map2@.
--
-- > split 2 (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3,"b"), (5,"a")])
-- > split 3 (fromList [(5,"a"), (3,"b")]) == (empty, singleton 5 "a")
-- > split 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
-- > split 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", empty)
-- > split 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], empty)
split :: Ord k => k -> Map k a -> (Map k a,Map k a)
split k0 t0 = k0 `seq` toPair $ go k0 t0
where
go k t =
case t of
Tip -> (Tip :*: Tip)
Bin _ kx x l r -> case compare k kx of
LT -> let (lt :*: gt) = go k l in lt :*: link kx x gt r
GT -> let (lt :*: gt) = go k r in link kx x l lt :*: gt
EQ -> (l :*: r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE split #-}
#endif
-- | /O(log n)/. The expression (@'splitLookup' k map@) splits a map just
-- like 'split' but also returns @'lookup' k map@.
--
-- > splitLookup 2 (fromList [(5,"a"), (3,"b")]) == (empty, Nothing, fromList [(3,"b"), (5,"a")])
-- > splitLookup 3 (fromList [(5,"a"), (3,"b")]) == (empty, Just "b", singleton 5 "a")
-- > splitLookup 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Nothing, singleton 5 "a")
-- > splitLookup 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Just "a", empty)
-- > splitLookup 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], Nothing, empty)
splitLookup :: Ord k => k -> Map k a -> (Map k a,Maybe a,Map k a)
splitLookup k t = k `seq`
case t of
Tip -> (Tip,Nothing,Tip)
Bin _ kx x l r -> case compare k kx of
LT -> let (lt,z,gt) = splitLookup k l
gt' = link kx x gt r
in gt' `seq` (lt,z,gt')
GT -> let (lt,z,gt) = splitLookup k r
lt' = link kx x l lt
in lt' `seq` (lt',z,gt)
EQ -> (l,Just x,r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE splitLookup #-}
#endif
{--------------------------------------------------------------------
Utility functions that maintain the balance properties of the tree.
All constructors assume that all values in [l] < [k] and all values
in [r] > [k], and that [l] and [r] are valid trees.
In order of sophistication:
[Bin sz k x l r] The type constructor.
[bin k x l r] Maintains the correct size, assumes that both [l]
and [r] are balanced with respect to each other.
[balance k x l r] Restores the balance and size.
Assumes that the original tree was balanced and
that [l] or [r] has changed by at most one element.
[link k x l r] Restores balance and size.
Furthermore, we can construct a new tree from two trees. Both operations
assume that all values in [l] < all values in [r] and that [l] and [r]
are valid:
[glue l r] Glues [l] and [r] together. Assumes that [l] and
[r] are already balanced with respect to each other.
[merge l r] Merges two trees and restores balance.
Note: in contrast to Adam's paper, we use (<=) comparisons instead
of (<) comparisons in [link], [merge] and [balance].
Quickcheck (on [difference]) showed that this was necessary in order
to maintain the invariants. It is quite unsatisfactory that I haven't
been able to find out why this is actually the case! Fortunately, it
doesn't hurt to be a bit more conservative.
--------------------------------------------------------------------}
{--------------------------------------------------------------------
Link
--------------------------------------------------------------------}
link :: k -> a -> Map k a -> Map k a -> Map k a
link kx x Tip r = insertMin kx x r
link kx x l Tip = insertMax kx x l
link kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
| delta*sizeL < sizeR = balanceL kz z (link kx x l lz) rz
| delta*sizeR < sizeL = balanceR ky y ly (link kx x ry r)
| otherwise = bin kx x l r
-- insertMin and insertMax don't perform potentially expensive comparisons.
insertMax,insertMin :: k -> a -> Map k a -> Map k a
insertMax kx x t
= case t of
Tip -> singleton kx x
Bin _ ky y l r
-> balanceR ky y l (insertMax kx x r)
insertMin kx x t
= case t of
Tip -> singleton kx x
Bin _ ky y l r
-> balanceL ky y (insertMin kx x l) r
{--------------------------------------------------------------------
[merge l r]: merges two trees.
--------------------------------------------------------------------}
merge :: Map k a -> Map k a -> Map k a
merge Tip r = r
merge l Tip = l
merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
| delta*sizeL < sizeR = balanceL ky y (merge l ly) ry
| delta*sizeR < sizeL = balanceR kx x lx (merge rx r)
| otherwise = glue l r
{--------------------------------------------------------------------
[glue l r]: glues two trees together.
Assumes that [l] and [r] are already balanced with respect to each other.
--------------------------------------------------------------------}
glue :: Map k a -> Map k a -> Map k a
glue Tip r = r
glue l Tip = l
glue l r
| size l > size r = let ((km,m),l') = deleteFindMax l in balanceR km m l' r
| otherwise = let ((km,m),r') = deleteFindMin r in balanceL km m l r'
-- | /O(log n)/. Delete and find the minimal element.
--
-- > deleteFindMin (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((3,"b"), fromList[(5,"a"), (10,"c")])
-- > deleteFindMin Error: can not return the minimal element of an empty map
deleteFindMin :: Map k a -> ((k,a),Map k a)
deleteFindMin t
= case t of
Bin _ k x Tip r -> ((k,x),r)
Bin _ k x l r -> let (km,l') = deleteFindMin l in (km,balanceR k x l' r)
Tip -> (error "Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
-- | /O(log n)/. Delete and find the maximal element.
--
-- > deleteFindMax (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((10,"c"), fromList [(3,"b"), (5,"a")])
-- > deleteFindMax empty Error: can not return the maximal element of an empty map
deleteFindMax :: Map k a -> ((k,a),Map k a)
deleteFindMax t
= case t of
Bin _ k x l Tip -> ((k,x),l)
Bin _ k x l r -> let (km,r') = deleteFindMax r in (km,balanceL k x l r')
Tip -> (error "Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
{--------------------------------------------------------------------
[balance l x r] balances two trees with value x.
The sizes of the trees should balance after decreasing the
size of one of them. (a rotation).
[delta] is the maximal relative difference between the sizes of
two trees, it corresponds with the [w] in Adams' paper.
[ratio] is the ratio between an outer and inner sibling of the
heavier subtree in an unbalanced setting. It determines
whether a double or single rotation should be performed
to restore balance. It is corresponds with the inverse
of $\alpha$ in Adam's article.
Note that according to the Adam's paper:
- [delta] should be larger than 4.646 with a [ratio] of 2.
- [delta] should be larger than 3.745 with a [ratio] of 1.534.
But the Adam's paper is erroneous:
- It can be proved that for delta=2 and delta>=5 there does
not exist any ratio that would work.
- Delta=4.5 and ratio=2 does not work.
That leaves two reasonable variants, delta=3 and delta=4,
both with ratio=2.
- A lower [delta] leads to a more 'perfectly' balanced tree.
- A higher [delta] performs less rebalancing.
In the benchmarks, delta=3 is faster on insert operations,
and delta=4 has slightly better deletes. As the insert speedup
is larger, we currently use delta=3.
--------------------------------------------------------------------}
delta,ratio :: Int
delta = 3
ratio = 2
-- The balance function is equivalent to the following:
--
-- balance :: k -> a -> Map k a -> Map k a -> Map k a
-- balance k x l r
-- | sizeL + sizeR <= 1 = Bin sizeX k x l r
-- | sizeR > delta*sizeL = rotateL k x l r
-- | sizeL > delta*sizeR = rotateR k x l r
-- | otherwise = Bin sizeX k x l r
-- where
-- sizeL = size l
-- sizeR = size r
-- sizeX = sizeL + sizeR + 1
--
-- rotateL :: a -> b -> Map a b -> Map a b -> Map a b
-- rotateL k x l r@(Bin _ _ _ ly ry) | size ly < ratio*size ry = singleL k x l r
-- | otherwise = doubleL k x l r
--
-- rotateR :: a -> b -> Map a b -> Map a b -> Map a b
-- rotateR k x l@(Bin _ _ _ ly ry) r | size ry < ratio*size ly = singleR k x l r
-- | otherwise = doubleR k x l r
--
-- singleL, singleR :: a -> b -> Map a b -> Map a b -> Map a b
-- singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
-- singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
--
-- doubleL, doubleR :: a -> b -> Map a b -> Map a b -> Map a b
-- doubleL k1 x1 t1 (Bin _ k2 x2 (Bin _ k3 x3 t2 t3) t4) = bin k3 x3 (bin k1 x1 t1 t2) (bin k2 x2 t3 t4)
-- doubleR k1 x1 (Bin _ k2 x2 t1 (Bin _ k3 x3 t2 t3)) t4 = bin k3 x3 (bin k2 x2 t1 t2) (bin k1 x1 t3 t4)
--
-- It is only written in such a way that every node is pattern-matched only once.
balance :: k -> a -> Map k a -> Map k a -> Map k a
balance k x l r = case l of
Tip -> case r of
Tip -> Bin 1 k x Tip Tip
(Bin _ _ _ Tip Tip) -> Bin 2 k x Tip r
(Bin _ rk rx Tip rr@(Bin _ _ _ _ _)) -> Bin 3 rk rx (Bin 1 k x Tip Tip) rr
(Bin _ rk rx (Bin _ rlk rlx _ _) Tip) -> Bin 3 rlk rlx (Bin 1 k x Tip Tip) (Bin 1 rk rx Tip Tip)
(Bin rs rk rx rl@(Bin rls rlk rlx rll rlr) rr@(Bin rrs _ _ _ _))
| rls < ratio*rrs -> Bin (1+rs) rk rx (Bin (1+rls) k x Tip rl) rr
| otherwise -> Bin (1+rs) rlk rlx (Bin (1+size rll) k x Tip rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
(Bin ls lk lx ll lr) -> case r of
Tip -> case (ll, lr) of
(Tip, Tip) -> Bin 2 k x l Tip
(Tip, (Bin _ lrk lrx _ _)) -> Bin 3 lrk lrx (Bin 1 lk lx Tip Tip) (Bin 1 k x Tip Tip)
((Bin _ _ _ _ _), Tip) -> Bin 3 lk lx ll (Bin 1 k x Tip Tip)
((Bin lls _ _ _ _), (Bin lrs lrk lrx lrl lrr))
| lrs < ratio*lls -> Bin (1+ls) lk lx ll (Bin (1+lrs) k x lr Tip)
| otherwise -> Bin (1+ls) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+size lrr) k x lrr Tip)
(Bin rs rk rx rl rr)
| rs > delta*ls -> case (rl, rr) of
(Bin rls rlk rlx rll rlr, Bin rrs _ _ _ _)
| rls < ratio*rrs -> Bin (1+ls+rs) rk rx (Bin (1+ls+rls) k x l rl) rr
| otherwise -> Bin (1+ls+rs) rlk rlx (Bin (1+ls+size rll) k x l rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
(_, _) -> error "Failure in Data.Map.balance"
| ls > delta*rs -> case (ll, lr) of
(Bin lls _ _ _ _, Bin lrs lrk lrx lrl lrr)
| lrs < ratio*lls -> Bin (1+ls+rs) lk lx ll (Bin (1+rs+lrs) k x lr r)
| otherwise -> Bin (1+ls+rs) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+rs+size lrr) k x lrr r)
(_, _) -> error "Failure in Data.Map.balance"
| otherwise -> Bin (1+ls+rs) k x l r
{-# NOINLINE balance #-}
-- Functions balanceL and balanceR are specialised versions of balance.
-- balanceL only checks whether the left subtree is too big,
-- balanceR only checks whether the right subtree is too big.
-- balanceL is called when left subtree might have been inserted to or when
-- right subtree might have been deleted from.
balanceL :: k -> a -> Map k a -> Map k a -> Map k a
balanceL k x l r = case r of
Tip -> case l of
Tip -> Bin 1 k x Tip Tip
(Bin _ _ _ Tip Tip) -> Bin 2 k x l Tip
(Bin _ lk lx Tip (Bin _ lrk lrx _ _)) -> Bin 3 lrk lrx (Bin 1 lk lx Tip Tip) (Bin 1 k x Tip Tip)
(Bin _ lk lx ll@(Bin _ _ _ _ _) Tip) -> Bin 3 lk lx ll (Bin 1 k x Tip Tip)
(Bin ls lk lx ll@(Bin lls _ _ _ _) lr@(Bin lrs lrk lrx lrl lrr))
| lrs < ratio*lls -> Bin (1+ls) lk lx ll (Bin (1+lrs) k x lr Tip)
| otherwise -> Bin (1+ls) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+size lrr) k x lrr Tip)
(Bin rs _ _ _ _) -> case l of
Tip -> Bin (1+rs) k x Tip r
(Bin ls lk lx ll lr)
| ls > delta*rs -> case (ll, lr) of
(Bin lls _ _ _ _, Bin lrs lrk lrx lrl lrr)
| lrs < ratio*lls -> Bin (1+ls+rs) lk lx ll (Bin (1+rs+lrs) k x lr r)
| otherwise -> Bin (1+ls+rs) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+rs+size lrr) k x lrr r)
(_, _) -> error "Failure in Data.Map.balanceL"
| otherwise -> Bin (1+ls+rs) k x l r
{-# NOINLINE balanceL #-}
-- balanceR is called when right subtree might have been inserted to or when
-- left subtree might have been deleted from.
balanceR :: k -> a -> Map k a -> Map k a -> Map k a
balanceR k x l r = case l of
Tip -> case r of
Tip -> Bin 1 k x Tip Tip
(Bin _ _ _ Tip Tip) -> Bin 2 k x Tip r
(Bin _ rk rx Tip rr@(Bin _ _ _ _ _)) -> Bin 3 rk rx (Bin 1 k x Tip Tip) rr
(Bin _ rk rx (Bin _ rlk rlx _ _) Tip) -> Bin 3 rlk rlx (Bin 1 k x Tip Tip) (Bin 1 rk rx Tip Tip)
(Bin rs rk rx rl@(Bin rls rlk rlx rll rlr) rr@(Bin rrs _ _ _ _))
| rls < ratio*rrs -> Bin (1+rs) rk rx (Bin (1+rls) k x Tip rl) rr
| otherwise -> Bin (1+rs) rlk rlx (Bin (1+size rll) k x Tip rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
(Bin ls _ _ _ _) -> case r of
Tip -> Bin (1+ls) k x l Tip
(Bin rs rk rx rl rr)
| rs > delta*ls -> case (rl, rr) of
(Bin rls rlk rlx rll rlr, Bin rrs _ _ _ _)
| rls < ratio*rrs -> Bin (1+ls+rs) rk rx (Bin (1+ls+rls) k x l rl) rr
| otherwise -> Bin (1+ls+rs) rlk rlx (Bin (1+ls+size rll) k x l rll) (Bin (1+rrs+size rlr) rk rx rlr rr)
(_, _) -> error "Failure in Data.Map.balanceR"
| otherwise -> Bin (1+ls+rs) k x l r
{-# NOINLINE balanceR #-}
{--------------------------------------------------------------------
The bin constructor maintains the size of the tree
--------------------------------------------------------------------}
bin :: k -> a -> Map k a -> Map k a -> Map k a
bin k x l r
= Bin (size l + size r + 1) k x l r
{-# INLINE bin #-}
{--------------------------------------------------------------------
Eq converts the tree to a list. In a lazy setting, this
actually seems one of the faster methods to compare two trees
and it is certainly the simplest :-)
--------------------------------------------------------------------}
instance (Eq k,Eq a) => Eq (Map k a) where
t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
{--------------------------------------------------------------------
Ord
--------------------------------------------------------------------}
instance (Ord k, Ord v) => Ord (Map k v) where
compare m1 m2 = compare (toAscList m1) (toAscList m2)
{--------------------------------------------------------------------
Functor
--------------------------------------------------------------------}
instance Functor (Map k) where
fmap f m = map f m
instance Traversable (Map k) where
traverse f = traverseWithKey (\_ -> f)
{-# INLINE traverse #-}
instance Foldable.Foldable (Map k) where
fold = go
where go Tip = mempty
go (Bin 1 _ v _ _) = v
go (Bin _ _ v l r) = go l `mappend` (v `mappend` go r)
{-# INLINABLE fold #-}
foldr = foldr
{-# INLINE foldr #-}
foldl = foldl
{-# INLINE foldl #-}
foldMap f t = go t
where go Tip = mempty
go (Bin 1 _ v _ _) = f v
go (Bin _ _ v l r) = go l `mappend` (f v `mappend` go r)
{-# INLINE foldMap #-}
#if MIN_VERSION_base(4,6,0)
foldl' = foldl'
{-# INLINE foldl' #-}
foldr' = foldr'
{-# INLINE foldr' #-}
#endif
#if MIN_VERSION_base(4,8,0)
length = size
{-# INLINE length #-}
null = null
{-# INLINE null #-}
toList = elems -- NB: Foldable.toList /= Map.toList
{-# INLINE toList #-}
elem = go
where STRICT_1_OF_2(go)
go _ Tip = False
go x (Bin _ _ v l r) = x == v || go x l || go x r
{-# INLINABLE elem #-}
maximum = start
where start Tip = error "Map.Foldable.maximum: called with empty map"
start (Bin _ _ v l r) = go (go v l) r
STRICT_1_OF_2(go)
go m Tip = m
go m (Bin _ _ v l r) = go (go (max m v) l) r
{-# INLINABLE maximum #-}
minimum = start
where start Tip = error "Map.Foldable.minumum: called with empty map"
start (Bin _ _ v l r) = go (go v l) r
STRICT_1_OF_2(go)
go m Tip = m
go m (Bin _ _ v l r) = go (go (min m v) l) r
{-# INLINABLE minimum #-}
sum = foldl' (+) 0
{-# INLINABLE sum #-}
product = foldl' (*) 1
{-# INLINABLE product #-}
#endif
instance (NFData k, NFData a) => NFData (Map k a) where
rnf Tip = ()
rnf (Bin _ kx x l r) = rnf kx `seq` rnf x `seq` rnf l `seq` rnf r
{--------------------------------------------------------------------
Read
--------------------------------------------------------------------}
instance (Ord k, Read k, Read e) => Read (Map k e) where
#ifdef __GLASGOW_HASKELL__
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
#else
readsPrec p = readParen (p > 10) $ \ r -> do
("fromList",s) <- lex r
(xs,t) <- reads s
return (fromList xs,t)
#endif
{--------------------------------------------------------------------
Show
--------------------------------------------------------------------}
instance (Show k, Show a) => Show (Map k a) where
showsPrec d m = showParen (d > 10) $
showString "fromList " . shows (toList m)
-- | /O(n)/. Show the tree that implements the map. The tree is shown
-- in a compressed, hanging format. See 'showTreeWith'.
showTree :: (Show k,Show a) => Map k a -> String
showTree m
= showTreeWith showElem True False m
where
showElem k x = show k ++ ":=" ++ show x
{- | /O(n)/. The expression (@'showTreeWith' showelem hang wide map@) shows
the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
@wide@ is 'True', an extra wide version is shown.
> Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]]
> Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t
> (4,())
> +--(2,())
> | +--(1,())
> | +--(3,())
> +--(5,())
>
> Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t
> (4,())
> |
> +--(2,())
> | |
> | +--(1,())
> | |
> | +--(3,())
> |
> +--(5,())
>
> Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t
> +--(5,())
> |
> (4,())
> |
> | +--(3,())
> | |
> +--(2,())
> |
> +--(1,())
-}
showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
showTreeWith showelem hang wide t
| hang = (showsTreeHang showelem wide [] t) ""
| otherwise = (showsTree showelem wide [] [] t) ""
showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
showsTree showelem wide lbars rbars t
= case t of
Tip -> showsBars lbars . showString "|\n"
Bin _ kx x Tip Tip
-> showsBars lbars . showString (showelem kx x) . showString "\n"
Bin _ kx x l r
-> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
showWide wide rbars .
showsBars lbars . showString (showelem kx x) . showString "\n" .
showWide wide lbars .
showsTree showelem wide (withEmpty lbars) (withBar lbars) l
showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
showsTreeHang showelem wide bars t
= case t of
Tip -> showsBars bars . showString "|\n"
Bin _ kx x Tip Tip
-> showsBars bars . showString (showelem kx x) . showString "\n"
Bin _ kx x l r
-> showsBars bars . showString (showelem kx x) . showString "\n" .
showWide wide bars .
showsTreeHang showelem wide (withBar bars) l .
showWide wide bars .
showsTreeHang showelem wide (withEmpty bars) r
showWide :: Bool -> [String] -> String -> String
showWide wide bars
| wide = showString (concat (reverse bars)) . showString "|\n"
| otherwise = id
showsBars :: [String] -> ShowS
showsBars bars
= case bars of
[] -> id
_ -> showString (concat (reverse (tail bars))) . showString node
node :: String
node = "+--"
withBar, withEmpty :: [String] -> [String]
withBar bars = "| ":bars
withEmpty bars = " ":bars
{--------------------------------------------------------------------
Typeable
--------------------------------------------------------------------}
INSTANCE_TYPEABLE2(Map,mapTc,"Map")
{--------------------------------------------------------------------
Assertions
--------------------------------------------------------------------}
-- | /O(n)/. Test if the internal map structure is valid.
--
-- > valid (fromAscList [(3,"b"), (5,"a")]) == True
-- > valid (fromAscList [(5,"a"), (3,"b")]) == False
valid :: Ord k => Map k a -> Bool
valid t
= balanced t && ordered t && validsize t
ordered :: Ord a => Map a b -> Bool
ordered t
= bounded (const True) (const True) t
where
bounded lo hi t'
= case t' of
Tip -> True
Bin _ kx _ l r -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
-- | Exported only for "Debug.QuickCheck"
balanced :: Map k a -> Bool
balanced t
= case t of
Tip -> True
Bin _ _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
balanced l && balanced r
validsize :: Map a b -> Bool
validsize t
= (realsize t == Just (size t))
where
realsize t'
= case t' of
Tip -> Just 0
Bin sz _ _ l r -> case (realsize l,realsize r) of
(Just n,Just m) | n+m+1 == sz -> Just sz
_ -> Nothing
{--------------------------------------------------------------------
Utilities
--------------------------------------------------------------------}
-- | /O(1)/. Decompose a map into pieces based on the structure of the underlying
-- tree. This function is useful for consuming a map in parallel.
--
-- No guarantee is made as to the sizes of the pieces; an internal, but
-- deterministic process determines this. However, it is guaranteed that the pieces
-- returned will be in ascending order (all elements in the first submap less than all
-- elements in the second, and so on).
--
-- Examples:
--
-- > splitRoot (fromList (zip [1..6] ['a'..])) ==
-- > [fromList [(1,'a'),(2,'b'),(3,'c')],fromList [(4,'d')],fromList [(5,'e'),(6,'f')]]
--
-- > splitRoot empty == []
--
-- Note that the current implementation does not return more than three submaps,
-- but you should not depend on this behaviour because it can change in the
-- future without notice.
splitRoot :: Map k b -> [Map k b]
splitRoot orig =
case orig of
Tip -> []
Bin _ k v l r -> [l, singleton k v, r]
{-# INLINE splitRoot #-}
|
DavidAlphaFox/ghc
|
libraries/containers/Data/Map/Base.hs
|
bsd-3-clause
| 111,520 | 0 | 21 | 28,710 | 23,586 | 12,396 | 11,190 | -1 | -1 |
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, DataKinds, ViewPatterns,GADTs #-}
import GL
import OpenGlDigits
import Control.Concurrent.STM
import Control.Concurrent
import Graphics.UI.Gtk hiding (Point,Signal, Object)
import Graphics.UI.Gtk.OpenGL
import Graphics.Rendering.OpenGL hiding (Projection)
import qualified Data.Map as M
import Control.Monad
import Sprite.Logic
import Sprite.Widget
import Control.Lens hiding (set)
import Haskell
import Data.Monoid
import Data.List.Zipper (insert,empty)
data Synth = Pattern Int (M.Map Int GLfloat) | Projection Int (M.Map Int GLfloat) | Synth String | Bus Int | Viewer
type instance SocketName Synth = String
newtype N = N Int deriving (Eq, Show, Num, Integral, Real, Enum, Ord)
instance Monoid N where
mempty = N 1
mappend = (+)
mb :: [N] -> Synth -> N
mb [] _ = mempty
mb xs (Pattern n ma) = N . (*z) . maximum . map (\(N x) -> x) $ xs where
z = sum . map floor . map (*128) $ M.elems ma
type instance Signal Synth = N
basePattern o = Object
(M.singleton 0 (SInput (-0.1,0.5) (0.5,0.5) ["patternOut"]))
(M.singleton 0 (SOutput (1.1,0.5) (0.5,0.5) "patternOut" (mb,N o)))
(Pattern 3 $ M.fromList $ zip [0..2] $ repeat 0)
baseProjection = Object
(M.singleton 0 (SInput (-0.1,0.5) (0.5,0.5) ["patternOut"]))
(M.singleton 0 (SOutput (1.1,0.5) (0.5,0.5) "projectionOut" (mb,N 3)))
(Projection 6 $ M.fromList $ zip [0..5] $ repeat 0)
baseSynth n x = Object
(M.fromList $ [(fromIntegral i,SInput (-0.1,fromIntegral j / fromIntegral n) (0.5,0.5) ["projectionOut","busOut"]) | (i,j) <- zip [0..n-1] [0..n-1]])
M.empty
(Synth x)
baseBus n = Object
(M.singleton 0 (SInput (-0.1,0.5) (0.5,0.5) ["projectionOut"]))
M.empty -- (M.singleton 0 (SOutput (1.1,0.5) (0.5,0.5) "busOut" (mb,mempty)))
(Bus n)
baseViewer = Object
(M.singleton 0 (SInput (-0.1,0.5) (0.5,0.5) ["projectionOut", "patternOut"]))
(M.singleton 0 (SOutput (1.1,0.5) (0.5,0.5) "viewerOut" (mb,N 4)))
Viewer
scrollSynth :: ScrollDirection -> Point -> Synth -> STM Synth
scrollSynth s (x,_) e@(Pattern n y)
| x >=0 && x < 1 = let m = floor $ x * fromIntegral n
in return . Pattern n $ at m %~ fmap f $ y
| otherwise = return e
where f x = case s of
ScrollUp -> min 1 $ x + 1/128
ScrollDown -> max 0 $ x - 1/128
_ -> x
scrollSynth s (x,_) e@(Projection n y)
| x >=0 && x < 1 = let m = floor $ x * fromIntegral n
in return . Projection n $ at m %~ fmap f $ y
| otherwise = return e
where f x = case s of
ScrollUp -> min 1 $ x + 1/128
ScrollDown -> max 0 $ x - 1/128
_ -> x
scrollSynth s (_,_) (Bus y) = return . Bus $ case s of
ScrollUp -> min 127 $ y + 1
ScrollDown -> max 0 $ y - 1
scrollSynth s (x,_) y = return y
setSynth :: Point -> Synth -> STM Synth
setSynth (x,y) e@(Pattern n q)
| x >=0 && x < 1 && y >= 0 && y < 1 = let m = floor $ x * fromIntegral n
in return . Pattern n $ at m .~ Just (realToFrac y) $ q
| otherwise = return e
setSynth (x,y) e@(Projection n q)
| x >=0 && x < 1 && y >= 0 && y < 1 = let m = floor $ x * fromIntegral n
in return . Projection n $ at m .~ Just (realToFrac y) $ q
| otherwise = return e
setSynth _ x = return x
graph :: Graph Synth
graph = Graph (M.fromList $
[ (0,(Affine (0.5,0.5) (0.06,0.1),basePattern 4))
, (1,(Affine (0.5,0.5) (0.12,0.1),baseProjection))
, (2, (Affine (0.5,0.5) (0.1,0.1),baseSynth 5 "SAMPLER"))
, (3,(Affine (0.5,0.5) (0.06,0.1),baseBus 0))
, (4,(Affine (0.5,0.5) (0.06,0.1),basePattern 6))
-- , (4,(Affine (0.5,0.5) (0.06,0.1),baseViewer))
]) M.empty M.empty
rbe (SInput (realToFrac -> x,realToFrac -> y) c _) = renderPrimitive LineLoop $ do
vertex (Vertex2 (x - 0.05) (y - 0.05) :: Vertex2 GLfloat)
vertex (Vertex2 (x + 0.05) (y - 0.05) :: Vertex2 GLfloat)
vertex (Vertex2 (x + 0.05) (y + 0.05) :: Vertex2 GLfloat)
vertex (Vertex2 (x - 0.05) (y + 0.05) :: Vertex2 GLfloat)
rbe (SOutput (realToFrac -> x,realToFrac -> y) c _ (_,N n) ) = do
renderPrimitive LineLoop $ do
vertex (Vertex2 (x - 0.05) (y - 0.05) :: Vertex2 GLfloat)
vertex (Vertex2 (x + 0.05) (y - 0.05) :: Vertex2 GLfloat)
vertex (Vertex2 (x + 0.05) (y + 0.05) :: Vertex2 GLfloat)
vertex (Vertex2 (x - 0.05) (y + 0.05) :: Vertex2 GLfloat)
renderNumberPosWH 0.5 0.5 (x) (0.8) (y) (0.1) $ n
renderSynth :: Object Synth -> IO ()
renderSynth (Object is os (Pattern n y)) = do
let d = 1 / fromIntegral n
polygonSmooth $= Enabled
forM_ (M.assocs y) $ \(i,v') -> do
let x1 = d * fromIntegral i + d/4
x2 = d * (fromIntegral i + 1) - d/4
v = v'*0.7
color (Color4 0.3 0.4 0.5 0.3:: Color4 GLfloat)
renderNumberPosWH 0.5 0.5 (x2 - 2*d/10) (0.8) (1/8/fromIntegral n) (0.1) $ floor $ v' * 128
color (Color4 0.6 0.7 0.8 0.1:: Color4 GLfloat)
renderPrimitive Quads $ do
-- mcolor p 2 3 4 1
vertex (Vertex2 x1 0.05 :: Vertex2 GLfloat)
vertex (Vertex2 x2 0.05 :: Vertex2 GLfloat)
-- mcolor p 4 3 2 1
vertex (Vertex2 x2 (0.05 + v) :: Vertex2 GLfloat)
vertex (Vertex2 x1 (0.05 + v) :: Vertex2 GLfloat)
color (Color4 0.8 0.9 1 0.1:: Color4 GLfloat)
forM_ [(0.1,0.1), (0.9,0.1),(0.9,0.9),(0.1,0.9)] $ \(xc,yc) ->
renderPrimitive Polygon $ forM_ [0,0.1.. 2*pi] $ \a -> do
let x = xc + 0.1*cos a
y = yc + 0.1*sin a
vertex (Vertex2 x y:: Vertex2 GLfloat)
color (Color4 0.8 0.9 1 0.1:: Color4 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0.1 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 1 :: Vertex2 GLfloat)
vertex (Vertex2 0.1 1 :: Vertex2 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.9 :: Vertex2 GLfloat)
vertex (Vertex2 0 0.9 :: Vertex2 GLfloat)
forM_ (M.elems is) rbe
forM_ (M.elems os) rbe
renderSynth (Object is os (Projection n y)) = do
let d = 1 / fromIntegral n
polygonSmooth $= Enabled
forM_ (M.assocs y) $ \(i,v') -> do
let x1 = d * fromIntegral i + d/4
x2 = d * (fromIntegral i + 1) - d/4
v = v'*0.7
color (Color4 0.3 0.4 0.5 0.3:: Color4 GLfloat)
renderNumberPosWH 0.5 0.5 (x2 - 2*d/10) (0.8) (1/8/fromIntegral n) (0.1) $ floor $ v' * 128
color (Color4 0.6 0.7 0.8 0.1:: Color4 GLfloat)
renderPrimitive Quads $ do
-- mcolor p 2 3 4 1
vertex (Vertex2 x1 0.05 :: Vertex2 GLfloat)
vertex (Vertex2 x2 0.05 :: Vertex2 GLfloat)
-- mcolor p 4 3 2 1
vertex (Vertex2 x2 (0.05 + v) :: Vertex2 GLfloat)
vertex (Vertex2 x1 (0.05 + v) :: Vertex2 GLfloat)
color (Color4 0.9 1 0.8 0.1:: Color4 GLfloat)
forM_ [(0.1,0.1), (0.9,0.1),(0.9,0.9),(0.1,0.9)] $ \(xc,yc) ->
renderPrimitive Polygon $ forM_ [0,0.1.. 2*pi] $ \a -> do
let x = xc + 0.1*cos a
y = yc + 0.1*sin a
vertex (Vertex2 x y:: Vertex2 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0.1 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 1 :: Vertex2 GLfloat)
vertex (Vertex2 0.1 1 :: Vertex2 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.9 :: Vertex2 GLfloat)
vertex (Vertex2 0 0.9 :: Vertex2 GLfloat)
forM_ (M.elems is) rbe
forM_ (M.elems os) rbe
renderSynth (Object is os (Synth n)) = do
polygonSmooth $= Enabled
lineSmooth $= Enabled
color (Color4 0.6 0.7 0.8 0.1:: Color4 GLfloat)
renderWordPOSWH 0.5 0.5 (0.3) (0.5) (1/20) (1/10) $ n
color (Color4 1 0.9 0.8 0.1:: Color4 GLfloat)
forM_ [(0.1,0.1), (0.9,0.1),(0.9,0.9),(0.1,0.9)] $ \(xc,yc) ->
renderPrimitive Polygon $ forM_ [0,0.1.. 2*pi] $ \a -> do
let x = xc + 0.1*cos a
y = yc + 0.1*sin a
vertex (Vertex2 x y:: Vertex2 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0.1 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 1 :: Vertex2 GLfloat)
vertex (Vertex2 0.1 1 :: Vertex2 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.9 :: Vertex2 GLfloat)
vertex (Vertex2 0 0.9 :: Vertex2 GLfloat)
forM_ (M.elems is) rbe
forM_ (M.elems os) rbe
renderSynth (Object is os (Bus n)) = do
polygonSmooth $= Enabled
lineSmooth $= Enabled
color (Color4 0.6 0.7 0.8 0.1:: Color4 GLfloat)
renderNumberPosWH 0.5 0.5 (0.9) (0.5) (1/20) (1/10) $ n
-- renderNumberPosWH 0.5 0.5 0.1 0.5 (1/20) (1/10) $ fromIntegral (v M.! 0)
color (Color4 0.4 0.9 0.9 0.1:: Color4 GLfloat)
forM_ [(0.1,0.1), (0.9,0.1),(0.9,0.9),(0.1,0.9)] $ \(xc,yc) ->
renderPrimitive Polygon $ forM_ [0,0.1.. 2*pi] $ \a -> do
let x = xc + 0.1*cos a
y = yc + 0.1*sin a
vertex (Vertex2 x y:: Vertex2 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0.1 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 0 :: Vertex2 GLfloat)
vertex (Vertex2 0.9 1 :: Vertex2 GLfloat)
vertex (Vertex2 0.1 1 :: Vertex2 GLfloat)
renderPrimitive Quads $ do
vertex (Vertex2 0 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.1 :: Vertex2 GLfloat)
vertex (Vertex2 1 0.9 :: Vertex2 GLfloat)
vertex (Vertex2 0 0.9 :: Vertex2 GLfloat)
forM_ (M.elems is) rbe
forM_ (M.elems os) rbe
{-
let h = 1/(fromIntegral $ length ps + 1)
pn n = (p + n) / (n+1)
forM_ (zip [0,h..] [n]) $ \(d,n) -> do
mcolor p 1 1 2 1
renderWordPOSWH 0.5 0.5 (1/5) (d + h/4) (1/20) (h/2) $ take 15 n
renderPrimitive Quads $ do
mcolor p 5 20 30 0.1
vertex (Vertex2 0 d :: Vertex2 GLfloat)
vertex (Vertex2 1 d :: Vertex2 GLfloat)
mcolor p 15 20 30 0.1
vertex (Vertex2 1 (d + h) :: Vertex2 GLfloat)
vertex (Vertex2 0 (d + h) :: Vertex2 GLfloat)
forM_ (zip [h,2*h..] (ps)) $ \(d,n) -> do
color $ Color4 (pn 2) (pn 2) (pn 2) 1
renderWordPOSWH 0.5 0.5 (1/5) (d + h/4) (1/20) (h/2) $ take 15 n
renderPrimitive Quads $ do
mcolor p 20 30 5 0.1
vertex (Vertex2 0 d :: Vertex2 GLfloat)
vertex (Vertex2 1 d :: Vertex2 GLfloat)
mcolor p 20 30 15 0.1
vertex (Vertex2 1 (d + h) :: Vertex2 GLfloat)
vertex (Vertex2 0 (d + h) :: Vertex2 GLfloat)
color $ Color4 1 (pn 1) (pn 1) 1
forM_ (map socketPoint $ connections c) $ \(x,y) -> renderPrimitive LineLoop $ do
let x0 = x + 0.03
x1 = x - 0.03
y1 = y - 0.03
y0 = y + 0.03
mcolor p 4 3 2 1
vertex (Vertex2 x0 y0 :: Vertex2 GLfloat)
vertex (Vertex2 x1 y0 :: Vertex2 GLfloat)
mcolor p 5 3 1 1
vertex (Vertex2 x1 y1 :: Vertex2 GLfloat)
vertex (Vertex2 x0 y1 :: Vertex2 GLfloat)
-}
main = do
initGUI
bootGL
window <- windowNew
onDestroy window mainQuit
set window [ containerBorderWidth := 8,
windowTitle := "tracks widget" ]
hb <- hBoxNew False 1
ref <- newTVarIO $ insert graph empty
connects <- graphing setSynth scrollSynth renderSynth ref
set window [containerChild := connects]
widgetShowAll window
dat <- widgetGetDrawWindow $ window
cursorNew Tcross >>= drawWindowSetCursor dat . Just
mainGUI
|
paolino/sprites
|
ConnectsMain.hs
|
bsd-3-clause
| 12,387 | 64 | 18 | 3,909 | 4,900 | 2,443 | 2,457 | 227 | 6 |
{-# LANGUAGE MagicHash, NoImplicitPrelude, TypeFamilies, UnboxedTuples,
RoleAnnotations #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Types
-- Copyright : (c) The University of Glasgow 2009
-- License : see libraries/ghc-prim/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- GHC type definitions.
-- Use GHC.Exts from the base package instead of importing this
-- module directly.
--
-----------------------------------------------------------------------------
module GHC.Types (
Bool(..), Char(..), Int(..), Word(..),
Float(..), Double(..),
Ordering(..), IO(..),
Java(..), Object(..), JString(..),
Object#,
isTrue#,
SPEC(..),
Coercible,
) where
import GHC.Prim
infixr 5 :
data [] a = [] | a : [a]
data {-# CTYPE "HsBool" #-} Bool = False | True
{- | The character type 'Char' is an enumeration whose values represent
Unicode (or equivalently ISO\/IEC 10646) characters (see
<http://www.unicode.org/> for details). This set extends the ISO 8859-1
(Latin-1) character set (the first 256 characters), which is itself an extension
of the ASCII character set (the first 128 characters). A character literal in
Haskell has type 'Char'.
To convert a 'Char' to or from the corresponding 'Int' value defined
by Unicode, use 'Prelude.toEnum' and 'Prelude.fromEnum' from the
'Prelude.Enum' class respectively (or equivalently 'ord' and 'chr').
-}
data {-# CTYPE "HsChar" #-} Char = C# Char#
-- | A fixed-precision integer type with at least the range @[-2^29 .. 2^29-1]@.
-- The exact range for a given implementation can be determined by using
-- 'Prelude.minBound' and 'Prelude.maxBound' from the 'Prelude.Bounded' class.
data {-# CTYPE "HsInt" #-} Int = I# Int#
-- |A 'Word' is an unsigned integral type, with the same size as 'Int'.
data {-# CTYPE "HsWord" #-} Word = W# Word#
-- | Single-precision floating point numbers.
-- It is desirable that this type be at least equal in range and precision
-- to the IEEE single-precision type.
data {-# CTYPE "HsFloat" #-} Float = F# Float#
-- | Double-precision floating point numbers.
-- It is desirable that this type be at least equal in range and precision
-- to the IEEE double-precision type.
data {-# CTYPE "HsDouble" #-} Double = D# Double#
data Ordering = LT | EQ | GT
{- |
A value of type @'IO' a@ is a computation which, when performed,
does some I\/O before returning a value of type @a@.
There is really only one way to \"perform\" an I\/O action: bind it to
@Main.main@ in your program. When your program is run, the I\/O will
be performed. It isn't possible to perform I\/O from an arbitrary
function, unless that function is itself in the 'IO' monad and called
at some point, directly or indirectly, from @Main.main@.
'IO' is a monad, so 'IO' actions can be combined using either the do-notation
or the '>>' and '>>=' operations from the 'Monad' class.
-}
newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
type role IO representational
{-
The above role annotation is redundant but is included because this role
is significant in the normalisation of FFI types. Specifically, if this
role were to become nominal (which would be very strange, indeed!), changes
elsewhere in GHC would be necessary. See [FFI type roles] in TcForeign.
-}
{-
Note [Kind-changing of (~) and Coercible]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(~) and Coercible are tricky to define. To the user, they must appear as
constraints, but we cannot define them as such in Haskell. But we also cannot
just define them only in GHC.Prim (like (->)), because we need a real module
for them, e.g. to compile the constructor's info table.
Furthermore the type of MkCoercible cannot be written in Haskell
(no syntax for ~#R).
So we define them as regular data types in GHC.Types, and do magic in TysWiredIn,
inside GHC, to change the kind and type.
-}
-- | A data constructor used to box up all unlifted equalities
--
-- The type constructor is special in that GHC pretends that it
-- has kind (? -> ? -> Fact) rather than (* -> * -> *)
data (~) a b = Eq# ((~#) a b)
-- | This two-parameter class has instances for types @a@ and @b@ if
-- the compiler can infer that they have the same representation. This class
-- does not have regular instances; instead they are created on-the-fly during
-- type-checking. Trying to manually declare an instance of @Coercible@
-- is an error.
--
-- Nevertheless one can pretend that the following three kinds of instances
-- exist. First, as a trivial base-case:
--
-- @instance a a@
--
-- Furthermore, for every type constructor there is
-- an instance that allows to coerce under the type constructor. For
-- example, let @D@ be a prototypical type constructor (@data@ or
-- @newtype@) with three type arguments, which have roles @nominal@,
-- @representational@ resp. @phantom@. Then there is an instance of
-- the form
--
-- @instance Coercible b b\' => Coercible (D a b c) (D a b\' c\')@
--
-- Note that the @nominal@ type arguments are equal, the
-- @representational@ type arguments can differ, but need to have a
-- @Coercible@ instance themself, and the @phantom@ type arguments can be
-- changed arbitrarily.
--
-- The third kind of instance exists for every @newtype NT = MkNT T@ and
-- comes in two variants, namely
--
-- @instance Coercible a T => Coercible a NT@
--
-- @instance Coercible T b => Coercible NT b@
--
-- This instance is only usable if the constructor @MkNT@ is in scope.
--
-- If, as a library author of a type constructor like @Set a@, you
-- want to prevent a user of your module to write
-- @coerce :: Set T -> Set NT@,
-- you need to set the role of @Set@\'s type parameter to @nominal@,
-- by writing
--
-- @type role Set nominal@
--
-- For more details about this feature, please refer to
-- <http://www.cis.upenn.edu/~eir/papers/2014/coercible/coercible.pdf Safe Coercions>
-- by Joachim Breitner, Richard A. Eisenberg, Simon Peyton Jones and Stephanie Weirich.
--
-- @since 4.7.0.0
data Coercible a b = MkCoercible ((~#) a b)
-- It's really ~R# (representational equality), not ~#,
-- but * we don't yet have syntax for ~R#,
-- * the compiled code is the same either way
-- * TysWiredIn has the truthful types
-- Also see Note [Kind-changing of (~) and Coercible]
-- | Alias for 'tagToEnum#'. Returns True if its parameter is 1# and False
-- if it is 0#.
{-# INLINE isTrue# #-}
isTrue# :: Int# -> Bool -- See Note [Optimizing isTrue#]
isTrue# x = tagToEnum# x
-- Note [Optimizing isTrue#]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Current definition of isTrue# is a temporary workaround. We would like to
-- have functions isTrue# and isFalse# defined like this:
--
-- isTrue# :: Int# -> Bool
-- isTrue# 1# = True
-- isTrue# _ = False
--
-- isFalse# :: Int# -> Bool
-- isFalse# 0# = True
-- isFalse# _ = False
--
-- These functions would allow us to safely check if a tag can represent True
-- or False. Using isTrue# and isFalse# as defined above will not introduce
-- additional case into the code. When we scrutinize return value of isTrue#
-- or isFalse#, either explicitly in a case expression or implicitly in a guard,
-- the result will always be a single case expression (given that optimizations
-- are turned on). This results from case-of-case transformation. Consider this
-- code (this is both valid Haskell and Core):
--
-- case isTrue# (a ># b) of
-- True -> e1
-- False -> e2
--
-- Inlining isTrue# gives:
--
-- case (case (a ># b) of { 1# -> True; _ -> False } ) of
-- True -> e1
-- False -> e2
--
-- Case-of-case transforms that to:
--
-- case (a ># b) of
-- 1# -> case True of
-- True -> e1
-- False -> e2
-- _ -> case False of
-- True -> e1
-- False -> e2
--
-- Which is then simplified by case-of-known-constructor:
--
-- case (a ># b) of
-- 1# -> e1
-- _ -> e2
--
-- While we get good Core here, the code generator will generate very bad Cmm
-- if e1 or e2 do allocation. It will push heap checks into case alternatives
-- which results in about 2.5% increase in code size. Until this is improved we
-- just make isTrue# an alias to tagToEnum#. This is a temporary solution (if
-- you're reading this in 2023 then things went wrong). See #8326.
--
-- | 'SPEC' is used by GHC in the @SpecConstr@ pass in order to inform
-- the compiler when to be particularly aggressive. In particular, it
-- tells GHC to specialize regardless of size or the number of
-- specializations. However, not all loops fall into this category.
--
-- Libraries can specify this by using 'SPEC' data type to inform which
-- loops should be aggressively specialized.
data SPEC = SPEC | SPEC2
-- The Java Monad
newtype Java c a = Java (Object# c -> (# Object# c, a #))
type role Java nominal representational
data {-# CLASS "java.lang.Object" #-} Object = O# (Object# Object)
data {-# CLASS "java.lang.String" #-} JString = JS# (Object# JString)
|
alexander-at-github/eta
|
libraries/ghc-prim/GHC/Types.hs
|
bsd-3-clause
| 9,300 | 3 | 10 | 1,953 | 542 | 390 | 152 | -1 | -1 |
module Day13 (part1, part2, test1, getTile, showMap, testMap, part2Solution, part1Solution) where
import Data.Bits
import Data.Graph.AStar
import qualified Data.HashSet as H
import Data.List
import Data.Graph.Inductive.Query.BFS
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.PatriciaTree
import Data.Hashable
import Data.Maybe
type Coord = (Integer, Integer)
data Tile = Wall | Open
deriving (Eq,Ord,Show)
getWalkableAdjacents :: Integer -> Coord -> [Coord]
getWalkableAdjacents o (x,y)
| getTile o (x,y) == Just Open = map fst $ filter (walkable . snd) $ map (\c -> (c,getTile o c)) [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]
| otherwise = []
where
walkable Nothing = False
walkable (Just Wall) = False
walkable (Just Open) = True
getTile :: Integer -> Coord -> Maybe Tile
getTile o (x,y)
| x < 0 || y < 0 = Nothing
| even calc = Just Open
| otherwise = Just Wall
where
calc = popCount $ x*x + 3*x + 2*x*y + y + y*y + o
getNode :: Coord -> Int
getNode = hash
getGraph :: Integer -> Integer -> Coord -> Gr Coord (Coord,Coord)
getGraph o d c@(xg,yg) = mkGraph
[(getNode (x,y), (x,y)) | x <- [xg-d..xg+d], y <- [yg-d..yg+d], withinRange o d (x,y) c]
[(getNode (x,y), getNode (x',y'),((x,y),(x',y')))
| x <- [xg-d..xg+d]
, y <- [yg-d..yg+d]
, x' <- [xg-d..xg+d]
, y' <- [yg-d..yg+d]
, (x',y') `elem` getWalkableAdjacents o (x,y)
, withinRange o d (x,y) c
, withinRange o d (x',y') c
]
integralDist :: Coord -> Coord -> Integer
integralDist (x,y) (x',y') = floor $ sqrt (fromIntegral $ (x'-x)^2 + (y' - y)^2)
withinRange :: Integer -> Integer -> Coord -> Coord -> Bool
withinRange o m c1 c2 = case a of
Nothing -> False
(Just d) -> d <= m
where
a = part1 o c1 c2
part1 :: Integer -> Coord -> Coord -> Maybe Integer
part1 o s g = genericLength <$> aStar (H.fromList . getWalkableAdjacents o) (const . const 1) (integralDist g) (g ==) s
part2 :: Integer -> Integer -> [Coord]
part2 o d = mapMaybe (lab g) $ bfs (getNode (1,1)) g
where g = getGraph o d (1,1)
part1Solution :: Maybe Integer
part1Solution = part1 input (1,1) (31,39)
part2Solution :: Integer
part2Solution = genericLength $ part2 input 50
showMap :: [[Maybe Tile]] -> [String]
showMap = map (map f)
where
f (Just Wall) = '#'
f (Just Open) = '.'
f Nothing = 'x'
testMap :: [String]
testMap = [".#.####.##","..#..#...#","#....##...","###.#.###.",".##..#..#.","..##....#.","#...##.###"]
test1 :: Integer
test1 = 10
input :: Integer
input = 1350
|
z0isch/aoc2016
|
src/Day13.hs
|
bsd-3-clause
| 2,741 | 0 | 17 | 736 | 1,286 | 703 | 583 | 66 | 3 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
-- | This module defines the representation of Subtyping and WF Constraints, and
-- the code for syntax-directed constraint generation.
module Language.Haskell.Liquid.Constraint.Generate (
generateConstraints
) where
import CoreUtils (exprType)
import MkCore
import Coercion
import DataCon
import Pair
import CoreSyn
import SrcLoc
import Type
import TyCon
import PrelNames
import TypeRep
import Class (Class, className)
import Var
import Id
import Name
import NameSet
import Text.PrettyPrint.HughesPJ hiding (first)
import Control.Monad.State
import Control.Applicative ((<$>))
import Data.Monoid (mconcat, mempty, mappend)
import Data.Maybe (fromMaybe, catMaybes, fromJust, isJust)
import qualified Data.HashMap.Strict as M
import qualified Data.HashSet as S
import qualified Data.List as L
import qualified Data.Text as T
import Data.Bifunctor
import Data.List (foldl')
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Text.Printf
import qualified Language.Haskell.Liquid.CTags as Tg
import Language.Fixpoint.Sort (pruneUnsortedReft)
import Language.Fixpoint.Visitor
import Language.Haskell.Liquid.Fresh
import qualified Language.Fixpoint.Types as F
import Language.Haskell.Liquid.Dictionaries
import Language.Haskell.Liquid.Variance
import Language.Haskell.Liquid.Types hiding (binds, Loc, loc, freeTyVars, Def)
import Language.Haskell.Liquid.Strata
import Language.Haskell.Liquid.Bounds
import Language.Haskell.Liquid.RefType
import Language.Haskell.Liquid.Visitors
import Language.Haskell.Liquid.PredType hiding (freeTyVars)
import Language.Haskell.Liquid.GhcMisc ( isInternal, collectArguments, tickSrcSpan
, hasBaseTypeVar, showPpr, isDataConId)
import Language.Haskell.Liquid.Misc
import Language.Fixpoint.Misc
import Language.Haskell.Liquid.Literals
import Language.Haskell.Liquid.RefSplit
import Control.DeepSeq
import Language.Haskell.Liquid.Constraint.Types
import Language.Haskell.Liquid.Constraint.Constraint
-----------------------------------------------------------------------
------------- Constraint Generation: Toplevel -------------------------
-----------------------------------------------------------------------
generateConstraints :: GhcInfo -> CGInfo
generateConstraints info = {-# SCC "ConsGen" #-} execState act $ initCGI cfg info
where
act = consAct info
cfg = config $ spec info
consAct info
= do γ <- initEnv info
sflag <- scheck <$> get
tflag <- trustghc <$> get
let trustBinding x = if tflag
then (x `elem` (derVars info) || isInternal x)
else False
foldM_ (consCBTop trustBinding) γ (cbs info)
hcs <- hsCs <$> get
hws <- hsWfs <$> get
scss <- sCs <$> get
annot <- annotMap <$> get
scs <- if sflag then concat <$> mapM splitS (hcs ++ scss)
else return []
let smap = if sflag then solveStrata scs else []
let hcs' = if sflag then subsS smap hcs else hcs
fcs <- concat <$> mapM splitC (subsS smap hcs')
fws <- concat <$> mapM splitW hws
let annot' = if sflag then (\t -> subsS smap t) <$> annot else annot
modify $ \st -> st { fixCs = fcs } { fixWfs = fws } {annotMap = annot'}
------------------------------------------------------------------------------------
initEnv :: GhcInfo -> CG CGEnv
------------------------------------------------------------------------------------
initEnv info
= do let tce = tcEmbeds sp
let fVars = impVars info
let dcs = filter isConLikeId (snd <$> freeSyms sp)
defaults <- forM fVars $ \x -> liftM (x,) (trueTy $ varType x)
dcsty <- forM dcs $ \x -> liftM (x,) (trueTy $ varType x)
(hs,f0) <- refreshHoles $ grty info -- asserted refinements (for defined vars)
f0'' <- refreshArgs' =<< grtyTop info -- default TOP reftype (for exported vars without spec)
let f0' = if notruetypes $ config sp then [] else f0''
f1 <- refreshArgs' $ defaults -- default TOP reftype (for all vars)
f1' <- refreshArgs' $ makedcs dcsty -- default TOP reftype (for data cons)
f2 <- refreshArgs' $ assm info -- assumed refinements (for imported vars)
f3 <- refreshArgs' $ vals asmSigs sp -- assumed refinedments (with `assume`)
f4 <- refreshArgs' $ makedcs $ vals ctors sp -- constructor refinements (for measures)
sflag <- scheck <$> get
let senv = if sflag then f2 else []
let tx = mapFst F.symbol . addRInv ialias . strataUnify senv . predsUnify sp
let bs = (tx <$> ) <$> [f0 ++ f0', f1 ++ f1', f2, f3, f4]
lts <- lits <$> get
let tcb = mapSnd (rTypeSort tce) <$> concat bs
let γ0 = measEnv sp (head bs) (cbs info) (tcb ++ lts) (bs!!3) hs
foldM (++=) γ0 [("initEnv", x, y) | (x, y) <- concat $ tail bs]
where
sp = spec info
ialias = mkRTyConIAl $ ialiases sp
vals f = map (mapSnd val) . f
makedcs = map strengthenDataConType
refreshHoles vts = first catMaybes . unzip . map extract <$> mapM refreshHoles' vts
refreshHoles' (x,t)
| noHoles t = return (Nothing,x,t)
| otherwise = (Just $ F.symbol x,x,) <$> mapReftM tx t
where
tx r | hasHole r = refresh r
| otherwise = return r
extract (a,b,c) = (a,(b,c))
refreshArgs' = mapM (mapSndM refreshArgs)
strataUnify :: [(Var, SpecType)] -> (Var, SpecType) -> (Var, SpecType)
strataUnify senv (x, t) = (x, maybe t (mappend t) pt)
where
pt = (fmap (\(U _ _ l) -> U mempty mempty l)) <$> L.lookup x senv
-- | TODO: All this *should* happen inside @Bare@ but appears
-- to happen after certain are signatures are @fresh@-ed,
-- which is why they are here.
-- NV : still some sigs do not get TyConInfo
predsUnify :: GhcSpec -> (Var, RRType RReft) -> (Var, RRType RReft)
predsUnify sp = second (addTyConInfo tce tyi) -- needed to eliminate some @RPropH@
where
tce = tcEmbeds sp
tyi = tyconEnv sp
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
measEnv sp xts cbs lts asms hs
= CGE { loc = noSrcSpan
, renv = fromListREnv $ second val <$> meas sp
, syenv = F.fromListSEnv $ freeSyms sp
, fenv = initFEnv $ lts ++ (second (rTypeSort tce . val) <$> meas sp)
, denv = dicts sp
, recs = S.empty
, invs = mkRTyConInv $ invariants sp
, ial = mkRTyConIAl $ ialiases sp
, grtys = fromListREnv xts
, assms = fromListREnv asms
, emb = tce
, tgEnv = Tg.makeTagEnv cbs
, tgKey = Nothing
, trec = Nothing
, lcb = M.empty
, holes = fromListHEnv hs
, lcs = mempty
}
where
tce = tcEmbeds sp
assm = assm_grty impVars
grty = assm_grty defVars
assm_grty f info = [ (x, val t) | (x, t) <- sigs, x `S.member` xs ]
where
xs = S.fromList $ f info
sigs = tySigs $ spec info
grtyTop info = forM topVs $ \v -> (v,) <$> (trueTy $ varType v) -- val $ varSpecType v) | v <- defVars info, isTop v]
where
topVs = filter isTop $ defVars info
isTop v = isExportedId v && not (v `S.member` sigVs)
isExportedId = flip elemNameSet (exports $ spec info) . getName
sigVs = S.fromList $ [v | (v,_) <- (tySigs $ spec info)
++ (asmSigs $ spec info)]
------------------------------------------------------------------------
-- | Helpers: Reading/Extending Environment Bindings -------------------
------------------------------------------------------------------------
getTag :: CGEnv -> F.Tag
getTag γ = maybe Tg.defaultTag (`Tg.getTag` (tgEnv γ)) (tgKey γ)
setLoc :: CGEnv -> SrcSpan -> CGEnv
γ `setLoc` src
| isGoodSrcSpan src = γ { loc = src }
| otherwise = γ
withRecs :: CGEnv -> [Var] -> CGEnv
withRecs γ xs = γ { recs = foldl' (flip S.insert) (recs γ) xs }
withTRec γ xts = γ' {trec = Just $ M.fromList xts' `M.union` trec'}
where γ' = γ `withRecs` (fst <$> xts)
trec' = fromMaybe M.empty $ trec γ
xts' = mapFst F.symbol <$> xts
setBind :: CGEnv -> Tg.TagKey -> CGEnv
setBind γ k
| Tg.memTagEnv k (tgEnv γ) = γ { tgKey = Just k }
| otherwise = γ
isGeneric :: RTyVar -> SpecType -> Bool
isGeneric α t = all (\(c, α') -> (α'/=α) || isOrd c || isEq c ) (classConstrs t)
where classConstrs t = [(c, α') | (c, ts) <- tyClasses t
, t' <- ts
, α' <- freeTyVars t']
isOrd = (ordClassName ==) . className
isEq = (eqClassName ==) . className
------------------------------------------------------------
------------------- Constraint Splitting -------------------
------------------------------------------------------------
splitW :: WfC -> CG [FixWfC]
splitW (WfC γ t@(RFun x t1 t2 _))
= do ws <- bsplitW γ t
ws' <- splitW (WfC γ t1)
γ' <- (γ, "splitW") += (x, t1)
ws'' <- splitW (WfC γ' t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ t@(RAppTy t1 t2 _))
= do ws <- bsplitW γ t
ws' <- splitW (WfC γ t1)
ws'' <- splitW (WfC γ t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ (RAllT _ r))
= splitW (WfC γ r)
splitW (WfC γ (RAllP _ r))
= splitW (WfC γ r)
splitW (WfC γ t@(RVar _ _))
= bsplitW γ t
splitW (WfC γ t@(RApp _ ts rs _))
= do ws <- bsplitW γ t
γ' <- γ `extendEnvWithVV` t
ws' <- concat <$> mapM splitW (map (WfC γ') ts)
ws'' <- concat <$> mapM (rsplitW γ) rs
return $ ws ++ ws' ++ ws''
splitW (WfC γ (RAllE x tx t))
= do ws <- splitW (WfC γ tx)
γ' <- (γ, "splitW") += (x, tx)
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC γ (REx x tx t))
= do ws <- splitW (WfC γ tx)
γ' <- (γ, "splitW") += (x, tx)
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC _ t)
= errorstar $ "splitW cannot handle: " ++ showpp t
rsplitW _ (RPropP _ _)
= errorstar "Constrains: rsplitW for RPropP"
rsplitW γ (RProp ss t0)
= do γ' <- foldM (++=) γ [("rsplitC", x, ofRSort s) | (x, s) <- ss]
splitW $ WfC γ' t0
rsplitW _ (RHProp _ _)
= errorstar "TODO: EFFECTS"
bsplitW :: CGEnv -> SpecType -> CG [FixWfC]
bsplitW γ t = pruneRefs <$> get >>= return . bsplitW' γ t
bsplitW' γ t pflag
| F.isNonTrivial r' = [F.wfC (fe_binds $ fenv γ) r' Nothing ci]
| otherwise = []
where
r' = rTypeSortedReft' pflag γ t
ci = Ci (loc γ) Nothing
------------------------------------------------------------
splitS :: SubC -> CG [([Stratum], [Stratum])]
bsplitS :: SpecType -> SpecType -> CG [([Stratum], [Stratum])]
------------------------------------------------------------
splitS (SubC γ (REx x _ t1) (REx x2 _ t2) exprs) | x == x2
= splitS (SubC γ t1 t2 exprs)
{-
<<<<<<< HEAD
splitS (SubC γ t1 (REx _ _ t2) exprs)
= splitS (SubC γ t1 t2 exprs)
splitS (SubC γ (REx _ _ t1) t2 exprs)
= splitS (SubC γ t1 t2 exprs)
=======
splitS (SubC γ t1 (REx _ _ t2))
= splitS (SubC γ t1 t2)
splitS (SubC γ (REx _ _ t1) t2)
= splitS (SubC γ t1 t2)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
-}
splitS (SubC γ (RAllE x _ t1) (RAllE x2 _ t2) exprs) | x == x2
= splitS (SubC γ t1 t2 exprs)
splitS (SubC γ (RAllE _ _ t1) t2 exprs)
= splitS (SubC γ t1 t2 exprs)
splitS (SubC γ t1 (RAllE _ _ t2) exprs)
= splitS (SubC γ t1 t2 exprs)
-- <<<<<<< HEAD
splitS (SubC γ (RRTy _ _ _ t1) t2 exprs)
= splitS (SubC γ t1 t2 exprs)
splitS (SubC γ t1 (RRTy _ _ _ t2) exprs)
= splitS (SubC γ t1 t2 exprs)
splitS (SubC γ t1@(RFun x1 r1 r1' _) t2@(RFun x2 r2 r2' _) exprs)
= do cs <- bsplitS t1 t2
cs' <- splitS (SubC γ r2 r1 exprs)
γ' <- (γ, "splitC") += (x2, r2)
let r1x2' = r1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitS (SubC γ' r1x2' r2' exprs)
return $ cs ++ cs' ++ cs''
splitS (SubC γ t1@(RAppTy r1 r1' _) t2@(RAppTy r2 r2' _) exprs)
= do cs <- bsplitS t1 t2
cs' <- splitS (SubC γ r1 r2 exprs)
cs'' <- splitS (SubC γ r1' r2' exprs)
cs''' <- splitS (SubC γ r2' r1' exprs)
return $ cs ++ cs' ++ cs'' ++ cs'''
splitS (SubC γ t1 (RAllP p t) exprs)
= splitS $ SubC γ t1 t' exprs
where t' = fmap (replacePredsWithRefs su) t
su = (uPVar p, pVartoRConc p)
splitS (SubC _ t1@(RAllP _ _) t2 _)
= errorstar $ "Predicate in lhs of constrain:" ++ showpp t1 ++ "\n<:\n" ++ showpp t2
splitS (SubC γ (RAllT α1 t1) (RAllT α2 t2) exprs)
| α1 == α2
= splitS $ SubC γ t1 t2 exprs
| otherwise
= splitS $ SubC γ t1 t2' exprs
where t2' = subsTyVar_meet' (α2, RVar α1 mempty) t2
splitS (SubC _ (RApp c1 _ _ _) (RApp c2 _ _ _) _) | isClass c1 && c1 == c2
=======
splitS (SubC γ (RRTy _ _ _ t1) t2)
= splitS (SubC γ t1 t2)
splitS (SubC γ t1 (RRTy _ _ _ t2))
= splitS (SubC γ t1 t2)
splitS (SubC γ t1@(RFun x1 r1 r1' _) t2@(RFun x2 r2 r2' _))
= do cs <- bsplitS t1 t2
cs' <- splitS (SubC γ r2 r1)
γ' <- (γ, "splitC") += (x2, r2)
let r1x2' = r1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitS (SubC γ' r1x2' r2')
return $ cs ++ cs' ++ cs''
splitS (SubC γ t1@(RAppTy r1 r1' _) t2@(RAppTy r2 r2' _))
= do cs <- bsplitS t1 t2
cs' <- splitS (SubC γ r1 r2)
cs'' <- splitS (SubC γ r1' r2')
cs''' <- splitS (SubC γ r2' r1')
return $ cs ++ cs' ++ cs'' ++ cs'''
splitS (SubC γ t1 (RAllP p t))
= splitS $ SubC γ t1 t'
where
t' = fmap (replacePredsWithRefs su) t
su = (uPVar p, pVartoRConc p)
splitS (SubC _ t1@(RAllP _ _) t2)
= errorstar $ "Predicate in lhs of constrain:" ++ showpp t1 ++ "\n<:\n" ++ showpp t2
splitS (SubC γ (RAllT α1 t1) (RAllT α2 t2))
| α1 == α2
= splitS $ SubC γ t1 t2
| otherwise
= splitS $ SubC γ t1 t2'
where t2' = subsTyVar_meet' (α2, RVar α1 mempty) t2
splitS (SubC _ (RApp c1 _ _ _) (RApp c2 _ _ _)) | isClass c1 && c1 == c2
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= return []
splitS (SubC γ t1@(RApp _ _ _ _) t2@(RApp _ _ _ _) exprs)
= do (t1',t2') <- unifyVV t1 t2
cs <- bsplitS t1' t2'
γ' <- γ `extendEnvWithVV` t1'
let RApp c t1s r1s _ = t1'
let RApp _ t2s r2s _ = t2'
let tyInfo = rtc_info c
csvar <- splitsSWithVariance γ' t1s t2s exprs $ varianceTyArgs tyInfo
csvar' <- rsplitsSWithVariance γ' r1s r2s exprs $ variancePsArgs tyInfo
return $ cs ++ csvar ++ csvar'
<<<<<<< HEAD
splitS (SubC _ t1@(RVar a1 _) t2@(RVar a2 _) _)
| a1 == a2
= bsplitS t1 t2
splitS (SubC _ t1 t2 _)
=======
splitS (SubC _ t1@(RVar a1 _) t2@(RVar a2 _))
| a1 == a2
= bsplitS t1 t2
splitS (SubC _ t1 t2)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= errorstar $ "(Another Broken Test!!!) splitS unexpected: " ++ showpp t1 ++ "\n\n" ++ showpp t2
splitS (SubR _ _ _ _)
= return []
<<<<<<< HEAD
splitsSWithVariance γ t1s t2s exprs variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (\s1 s2 -> splitS (SubC γ s1 s2 exprs)) t1 t2 v) (zip3 t1s t2s variants)
rsplitsSWithVariance γ t1s t2s exprs variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (rsplitS γ exprs) t1 t2 v) (zip3 t1s t2s variants)
=======
splitsSWithVariance γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (\s1 s2 -> splitS (SubC γ s1 s2)) t1 t2 v) (zip3 t1s t2s variants)
rsplitsSWithVariance γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (rsplitS γ) t1 t2 v) (zip3 t1s t2s variants)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
bsplitS t1 t2
= return $ [(s1, s2)]
where [s1, s2] = getStrata <$> [t1, t2]
rsplitS γ exprs (RProp s1 r1) (RProp s2 r2)
= splitS (SubC γ (F.subst su r1) r2 exprs)
where su = F.mkSubst [(x, F.EVar y) | ((x,_), (y,_)) <- zip s1 s2]
rsplitS _ _ _ _
= errorstar "rspliS Rpoly - RPropP"
splitfWithVariance f t1 t2 Invariant = liftM2 (++) (f t1 t2) (f t2 t1) -- return []
splitfWithVariance f t1 t2 Bivariant = liftM2 (++) (f t1 t2) (f t2 t1)
splitfWithVariance f t1 t2 Covariant = f t1 t2
splitfWithVariance f t1 t2 Contravariant = f t2 t1
------------------------------------------------------------
splitC :: SubC -> CG [FixSubC]
------------------------------------------------------------
splitC (SubC γ (REx x tx t1) (REx x2 _ t2) exprs) | x == x2
= do γ' <- (γ, "addExBind 0") += (x, forallExprRefType γ tx)
splitC (SubC γ' t1 t2 exprs)
<<<<<<< HEAD
splitC (SubC γ t1 (REx x tx t2) exprs)
= do γ' <- (γ, "addExBind 1") += (x, forallExprRefType γ tx)
let xs = grapBindsWithType tx γ
let t2' = splitExistsCases x xs tx t2
splitC (SubC γ' t1 t2' exprs)
-- existential at the left hand side is treated like forall
splitC (SubC γ (REx x tx t1) t2 exprs)
= do -- let tx' = traceShow ("splitC: " ++ showpp z) tx
=======
splitC (SubC γ t1 (REx x tx t2))
= do γ' <- (γ, "addExBind 1") += (x, forallExprRefType γ tx)
splitC (SubC γ' t1 t2)
-- existential at the left hand side is treated like forall
splitC (SubC γ (REx x tx t1) t2)
= do -- let tx' = traceShow ("splitC: " ++ showpp z) tx
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
γ' <- (γ, "addExBind 1") += (x, forallExprRefType γ tx)
splitC (SubC γ' t1 t2 exprs)
splitC (SubC γ (RAllE x tx t1) (RAllE x2 _ t2) exprs) | x == x2
= do γ' <- (γ, "addExBind 0") += (x, forallExprRefType γ tx)
splitC (SubC γ' t1 t2 exprs)
<<<<<<< HEAD
splitC (SubC γ (RAllE x tx t1) t2 exprs)
=======
splitC (SubC γ (RAllE x tx t1) t2)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= do γ' <- (γ, "addExBind 2") += (x, forallExprRefType γ tx)
splitC (SubC γ' t1 t2 exprs)
splitC (SubC γ t1 (RAllE x tx t2) exprs)
= do γ' <- (γ, "addExBind 2") += (x, forallExprRefType γ tx)
splitC (SubC γ' t1 t2 exprs)
<<<<<<< HEAD
splitC (SubC γ (RRTy [(_, t)] _ OCons t1) t2 exprs)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) γ (zip xs ts)
c1 <- splitC (SubC γ' t1' t2' exprs)
c2 <- splitC (SubC γ t1 t2 exprs)
=======
splitC (SubC γ (RRTy env _ OCons t1) t2)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) γ xts
c1 <- splitC (SubC γ' t1' t2')
c2 <- splitC (SubC γ t1 t2 )
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
return $ c1 ++ c2
where
(xts, t1', t2') = envToSub env
<<<<<<< HEAD
splitC (SubC γ (RRTy e r o t1) t2 exprs)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) γ e
c1 <- splitC (SubR γ' o r exprs)
c2 <- splitC (SubC γ t1 t2 exprs)
return $ c1 ++ c2
splitC (SubC γ t1@(RFun x1 r1 r1' _) t2@(RFun x2 r2 r2' _) exprs)
= do cs <- bsplitC γ t1 t2
cs' <- splitC (SubC γ r2 r1 exprs)
γ' <- (γ, "splitC") += (x2, r2)
let r1x2' = r1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitC (SubC γ' r1x2' r2' exprs)
return $ cs ++ cs' ++ cs''
splitC (SubC γ t1@(RAppTy r1 r1' _) t2@(RAppTy r2 r2' _) exprs)
= do cs <- bsplitC γ t1 t2
cs' <- splitC (SubC γ r1 r2 exprs)
cs'' <- splitC (SubC γ r1' r2' exprs)
cs''' <- splitC (SubC γ r2' r1' exprs)
return $ cs ++ cs' ++ cs'' ++ cs'''
splitC (SubC γ t1 (RAllP p t) exprs)
= splitC $ SubC γ t1 t' exprs
where t' = fmap (replacePredsWithRefs su) t
su = (uPVar p, pVartoRConc p)
splitC (SubC _ t1@(RAllP _ _) t2 _)
= errorstar $ "Predicate in lhs of constraint:" ++ showpp t1 ++ "\n<:\n" ++ showpp t2
splitC (SubC γ (RAllT α1 t1) (RAllT α2 t2) exprs)
| α1 == α2
= splitC $ SubC γ t1 t2 exprs
| otherwise
= splitC $ SubC γ t1 t2' exprs
=======
splitC (SubC γ (RRTy e r o t1) t2)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) γ e
c1 <- splitC (SubR γ' o r )
c2 <- splitC (SubC γ t1 t2)
return $ c1 ++ c2
splitC (SubC γ t1@(RFun x1 r1 r1' _) t2@(RFun x2 r2 r2' _))
= do cs <- bsplitC γ t1 t2
cs' <- splitC (SubC γ r2 r1)
γ' <- (γ, "splitC") += (x2, r2)
let r1x2' = r1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitC (SubC γ' r1x2' r2')
return $ cs ++ cs' ++ cs''
splitC (SubC γ t1@(RAppTy r1 r1' _) t2@(RAppTy r2 r2' _))
= do cs <- bsplitC γ t1 t2
cs' <- splitC (SubC γ r1 r2)
cs'' <- splitC (SubC γ r1' r2')
cs''' <- splitC (SubC γ r2' r1')
return $ cs ++ cs' ++ cs'' ++ cs'''
splitC (SubC γ t1 (RAllP p t))
= splitC $ SubC γ t1 t'
where
t' = fmap (replacePredsWithRefs su) t
su = (uPVar p, pVartoRConc p)
splitC (SubC _ t1@(RAllP _ _) t2)
= errorstar $ "Predicate in lhs of constraint:" ++ showpp t1 ++ "\n<:\n" ++ showpp t2
splitC (SubC γ (RAllT α1 t1) (RAllT α2 t2))
| α1 == α2
= splitC $ SubC γ t1 t2
| otherwise
= splitC $ SubC γ t1 t2'
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
where t2' = subsTyVar_meet' (α2, RVar α1 mempty) t2
splitC (SubC _ (RApp c1 _ _ _) (RApp c2 _ _ _) _) | isClass c1 && c1 == c2
= return []
splitC (SubC γ t1@(RApp _ _ _ _) t2@(RApp _ _ _ _) exprs)
= do (t1',t2') <- unifyVV t1 t2
cs <- bsplitC γ t1' t2'
γ' <- γ `extendEnvWithVV` t1'
let RApp c t1s r1s _ = t1'
let RApp _ t2s r2s _ = t2'
let tyInfo = rtc_info c
csvar <- splitsCWithVariance γ' t1s t2s exprs $ varianceTyArgs tyInfo
csvar' <- rsplitsCWithVariance γ' r1s r2s exprs $ variancePsArgs tyInfo
return $ cs ++ csvar ++ csvar'
<<<<<<< HEAD
splitC (SubC γ t1@(RVar a1 _) t2@(RVar a2 _) _)
| a1 == a2
= bsplitC γ t1 t2
splitC (SubC _ t1 t2 _)
= errorstar $ "(Another Broken Test!!!) splitc unexpected: " ++ showpp t1 ++ "\n\n" ++ showpp t2
splitC (SubR γ o r _)
= do fg <- pruneRefs <$> get
=======
splitC (SubC γ t1@(RVar a1 _) t2@(RVar a2 _))
| a1 == a2
= bsplitC γ t1 t2
splitC (SubC _ t1 t2)
= errorstar $ "(Another Broken Test!!!) splitc unexpected:\n" ++ showpp t1 ++ "\n\n" ++ showpp t2
splitC (SubR γ o r)
= do fg <- pruneRefs <$> get
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
let r1' = if fg then pruneUnsortedReft γ'' r1 else r1
return $ F.subC γ' F.PTrue r1' r2 Nothing tag ci
where
γ'' = fe_env $ fenv γ
γ' = fe_binds $ fenv γ
r1 = F.RR F.boolSort $ F.toReft r
r2 = F.RR F.boolSort $ F.Reft (vv, F.Refa $ F.PBexp $ F.EVar vv)
vv = "vvRec"
-- s = boolSort -- F.FApp F.boolFTyCon []
ci = Ci src err
err = Just $ ErrAssType src o (text $ show o ++ "type error") r
tag = getTag γ
src = loc γ
<<<<<<< HEAD
splitsCWithVariance γ t1s t2s exprs variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (\s1 s2 -> (splitC (SubC γ s1 s2 exprs))) t1 t2 v) (zip3 t1s t2s variants)
rsplitsCWithVariance γ t1s t2s exprs variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (rsplitC γ exprs) t1 t2 v) (zip3 t1s t2s variants)
=======
splitsCWithVariance γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (\s1 s2 -> (splitC (SubC γ s1 s2))) t1 t2 v) (zip3 t1s t2s variants)
rsplitsCWithVariance γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (rsplitC γ) t1 t2 v) (zip3 t1s t2s variants)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
bsplitC γ t1 t2
= do checkStratum γ t1 t2
pflag <- pruneRefs <$> get
γ' <- γ ++= ("bsplitC", v, t1)
let r = (mempty :: UReft F.Reft){ur_reft = F.Reft (F.dummySymbol, F.Refa $ constraintToLogic γ' (lcs γ'))}
let t1' = addRTyConInv (invs γ') t1 `strengthen` r
return $ bsplitC' γ' t1' t2 pflag
where
F.Reft(v, _) = ur_reft (fromMaybe mempty (stripRTypeBase t1))
checkStratum γ t1 t2
| s1 <:= s2 = return ()
| otherwise = addWarning wrn
where
[s1, s2] = getStrata <$> [t1, t2]
wrn = ErrOther (loc γ) (text $ "Stratum Error : " ++ show s1 ++ " > " ++ show s2)
bsplitC' γ t1 t2 pflag
| F.isFunctionSortedReft r1' && F.isNonTrivial r2'
= F.subC γ' grd (r1' {F.sr_reft = mempty}) r2' Nothing tag ci
| F.isNonTrivial r2'
= F.subC γ' grd r1' r2' Nothing tag ci
| otherwise
= []
where
γ' = fe_binds $ fenv γ
r1' = rTypeSortedReft' pflag γ t1
r2' = rTypeSortedReft' pflag γ t2
ci = Ci src err
tag = getTag γ
err = Just $ ErrSubType src (text "subtype") g t1 t2
src = loc γ
REnv g = renv γ
grd = F.PTrue
unifyVV t1@(RApp _ _ _ _) t2@(RApp _ _ _ _)
= do vv <- (F.vv . Just) <$> fresh
return $ (shiftVV t1 vv, (shiftVV t2 vv) ) -- {rt_pargs = r2s'})
unifyVV _ _
= errorstar $ "Constraint.Generate.unifyVV called on invalid inputs"
<<<<<<< HEAD
rsplitC _ _ (RPropP _ _) (RPropP _ _)
=======
rsplitC _ (RPropP _ _) (RPropP _ _)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= errorstar "RefTypes.rsplitC on RPropP"
rsplitC γ exprs (RProp s1 r1) (RProp s2 r2)
= do γ' <- foldM (++=) γ [("rsplitC1", x, ofRSort s) | (x, s) <- s2]
splitC (SubC γ' (F.subst su r1) r2 exprs)
where su = F.mkSubst [(x, F.EVar y) | ((x,_), (y,_)) <- zip s1 s2]
<<<<<<< HEAD
rsplitC _ _ _ _
=======
rsplitC _ _ _
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= errorstar "rsplit Rpoly - RPropP"
type CG = State CGInfo
initCGI cfg info = CGInfo {
hsCs = []
, sCs = []
, hsWfs = []
, fixCs = []
, isBind = []
, fixWfs = []
, freshIndex = 0
, binds = F.emptyBindEnv
, annotMap = AI M.empty
, tyConInfo = tyi
, tyConEmbed = tce
, kuts = F.ksEmpty
, lits = coreBindLits tce info
, termExprs = M.fromList $ texprs spc
, specDecr = decr spc
, specLVars = lvars spc
, specLazy = lazy spc
, tcheck = not $ notermination cfg
, scheck = strata cfg
, trustghc = trustinternals cfg
, pruneRefs = not $ noPrune cfg
, logErrors = []
, kvProf = emptyKVProf
, recCount = 0
}
where
tce = tcEmbeds spc
spc = spec info
tyi = tyconEnv spc -- EFFECTS HEREHEREHERE makeTyConInfo (tconsP spc)
coreBindLits tce info
= sortNub $ [ (val x, so) | (_, Just (F.ELit x so)) <- lconsts ]
++ [(F.symbol x, F.strSort) | (_, Just (F.ESym x)) <- lconsts ]
++ [ (dconToSym dc, dconToSort dc) | dc <- dcons ]
where
lconsts = literalConst tce <$> literals (cbs info)
dcons = filter isDCon $ impVars info -- ++ (snd <$> freeSyms (spec info))
dconToSort = typeSort tce . expandTypeSynonyms . varType
dconToSym = dataConSymbol . idDataCon
isDCon x = isDataConId x && not (hasBaseTypeVar x)
extendEnvWithVV γ t
| F.isNontrivialVV vv
= (γ, "extVV") += (vv, t)
| otherwise
= return γ
where vv = rTypeValueVar t
{- see tests/pos/polyfun for why you need everything in fixenv -}
addCGEnv :: (SpecType -> SpecType) -> CGEnv -> (String, F.Symbol, SpecType) -> CG CGEnv
addCGEnv tx γ (msg, x, REx y tyy tyx)
= do y' <- fresh
γ' <- addCGEnv tx γ (msg, y', tyy)
addCGEnv tx γ' (msg, x, tyx `F.subst1` (y, F.EVar y'))
addCGEnv tx γ (msg, x, RAllE yy tyy tyx)
= addCGEnv tx γ (msg, x, t)
where
xs = grapBindsWithType tyy γ
t = foldl (\t1 t2 -> t1 `F.meet` t2) ttrue [ tyx' `F.subst1` (yy, F.EVar x) | x <- xs]
(tyx', ttrue) = splitXRelatedRefs yy tyx
addCGEnv tx γ (_, x, t')
= do idx <- fresh
let t = tx $ normalize {-x-} idx t'
let γ' = γ { renv = insertREnv x t (renv γ) }
pflag <- pruneRefs <$> get
is <- if isBase t
then liftM2 (++) (liftM single $ addBind x $ rTypeSortedReft' pflag γ' t) (addClassBind t)
else return [] -- addClassBind t
return $ γ' { fenv = insertsFEnv (fenv γ) is }
(++=) :: CGEnv -> (String, F.Symbol, SpecType) -> CG CGEnv
(++=) γ = addCGEnv (addRTyConInv (M.unionWith mappend (invs γ) (ial γ))) γ
addSEnv :: CGEnv -> (String, F.Symbol, SpecType) -> CG CGEnv
addSEnv γ = addCGEnv (addRTyConInv (invs γ)) γ
rTypeSortedReft' pflag γ
| pflag
= pruneUnsortedReft (fe_env $ fenv γ) . f
| otherwise
= f
where
f = rTypeSortedReft (emb γ)
(+++=) :: (CGEnv, String) -> (F.Symbol, CoreExpr, SpecType) -> CG CGEnv
(γ, _) +++= (x, e, t) = (γ{lcb = M.insert x e (lcb γ)}, "+++=") += (x, t)
(+=) :: (CGEnv, String) -> (F.Symbol, SpecType) -> CG CGEnv
(γ, msg) += (x, r)
| x == F.dummySymbol
= return γ
| x `memberREnv` (renv γ)
= err
| otherwise
= γ ++= (msg, x, r)
where err = errorstar $ msg ++ " Duplicate binding for "
++ F.symbolString x
++ "\n New: " ++ showpp r
++ "\n Old: " ++ showpp (x `lookupREnv` (renv γ))
γ -= x = γ {renv = deleteREnv x (renv γ), lcb = M.delete x (lcb γ)}
(??=) :: CGEnv -> F.Symbol -> CG SpecType
γ ??= x
= case M.lookup x (lcb γ) of
Just e -> consE (γ-=x) e
Nothing -> refreshTy $ γ ?= x
(?=) :: CGEnv -> F.Symbol -> SpecType
γ ?= x = fromMaybe err $ lookupREnv x (renv γ)
where err = errorstar $ "EnvLookup: unknown "
++ showpp x
++ " in renv\n"
++ showpp (renv γ)
normalize idx
= normalizeVV idx
. normalizePds
normalizeVV idx t@(RApp _ _ _ _)
| not (F.isNontrivialVV (rTypeValueVar t))
= shiftVV t (F.vv $ Just idx)
normalizeVV _ t
= t
addBind :: F.Symbol -> F.SortedReft -> CG ((F.Symbol, F.Sort), F.BindId)
addBind x r
= do st <- get
let (i, bs') = F.insertBindEnv x r (binds st)
put $ st { binds = bs' }
return ((x, F.sr_sort r), i) -- traceShow ("addBind: " ++ showpp x) i
addClassBind :: SpecType -> CG [((F.Symbol, F.Sort), F.BindId)]
addClassBind = mapM (uncurry addBind) . classBinds
-- RJ: What is this `isBind` business?
pushConsBind act
= do modify $ \s -> s { isBind = False : isBind s }
z <- act
modify $ \s -> s { isBind = tail (isBind s) }
return z
<<<<<<< HEAD
addC :: SubC -> String -> CG ()
addC !c@(SubC γ t1 t2 exprs) _msg
=======
addC :: SubC -> String -> CG ()
addC !c@(SubC γ t1 t2) _msg
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= do -- trace ("addC at " ++ show (loc γ) ++ _msg++ showpp t1 ++ "\n <: \n" ++ showpp t2 ) $
modify $ \s -> s { hsCs = c : (hsCs s) }
bflag <- headDefault True . isBind <$> get
sflag <- scheck <$> get
if bflag && sflag
then modify $ \s -> s {sCs = (SubC γ t2 t1 exprs) : (sCs s) }
else return ()
where
headDefault a [] = a
headDefault _ (x:_) = x
addC !c _msg
= modify $ \s -> s { hsCs = c : (hsCs s) }
<<<<<<< HEAD
addPost γ expr (RRTy e r OInv t)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("addPost", x,t)) γ e
addC (SubR γ' OInv r [(γ',expr)]) "precondition" >> return t
addPost γ expr (RRTy e r OTerm t)
= do γ' <- foldM (\γ (x, t) -> γ ++= ("addPost", x,t)) γ e
addC (SubR γ' OTerm r [(γ',expr)]) "precondition" >> return t
addPost _ _ (RRTy _ _ OCons t)
= return t
addPost _ _ t
=======
addPost γ (RRTy e r OInv t)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("addPost", x,t)) γ e
addC (SubR γ' OInv r) "precondition" >> return t
addPost γ (RRTy e r OTerm t)
= do γ' <- foldM (\γ (x, t) -> γ ++= ("addPost", x,t)) γ e
addC (SubR γ' OTerm r) "precondition" >> return t
addPost _ (RRTy _ _ OCons t)
= return t
addPost _ t
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= return t
addW :: WfC -> CG ()
addW !w = modify $ \s -> s { hsWfs = w : (hsWfs s) }
addWarning :: TError SpecType -> CG ()
addWarning w = modify $ \s -> s { logErrors = w : (logErrors s) }
-- | Used for annotation binders (i.e. at binder sites)
addIdA :: Var -> Annot SpecType -> CG ()
addIdA !x !t = modify $ \s -> s { annotMap = upd $ annotMap s }
where
loc = getSrcSpan x
upd m@(AI _) = if boundRecVar loc m then m else addA loc (Just x) t m
boundRecVar l (AI m) = not $ null [t | (_, AnnRDf t) <- M.lookupDefault [] l m]
-- | Used for annotating reads (i.e. at Var x sites)
addLocA :: Maybe Var -> SrcSpan -> Annot SpecType -> CG ()
addLocA !xo !l !t
= modify $ \s -> s { annotMap = addA l xo t $ annotMap s }
-- | Used to update annotations for a location, due to (ghost) predicate applications
updateLocA (_:_) (Just l) t = addLocA Nothing l (AnnUse t)
updateLocA _ _ _ = return ()
addA !l xo@(Just _) !t (AI m)
| isGoodSrcSpan l
= AI $ inserts l (T.pack . showPpr <$> xo, t) m
addA !l xo@Nothing !t (AI m)
| l `M.member` m -- only spans known to be variables
= AI $ inserts l (T.pack . showPpr <$> xo, t) m
addA _ _ _ !a
= a
-------------------------------------------------------------------
------------------------ Generation: Freshness --------------------
-------------------------------------------------------------------
-- | Right now, we generate NO new pvars. Rather than clutter code
-- with `uRType` calls, put it in one place where the above
-- invariant is /obviously/ enforced.
-- Constraint generation should ONLY use @freshTy_type@ and @freshTy_expr@
freshTy_type :: KVKind -> CoreExpr -> Type -> CG SpecType
freshTy_type k _ τ = freshTy_reftype k $ ofType τ
freshTy_expr :: KVKind -> CoreExpr -> Type -> CG SpecType
freshTy_expr k e _ = freshTy_reftype k $ exprRefType e
freshTy_reftype :: KVKind -> SpecType -> CG SpecType
-- freshTy_reftype k t = do t <- refresh =<< fixTy t
-- addKVars k t
-- return t
freshTy_reftype k t = (fixTy t >>= refresh) =>> addKVars k
-- | Used to generate "cut" kvars for fixpoint. Typically, KVars for recursive
-- definitions, and also to update the KVar profile.
addKVars :: KVKind -> SpecType -> CG ()
addKVars !k !t = do when (True) $ modify $ \s -> s { kvProf = updKVProf k kvars (kvProf s) }
when (isKut k) $ modify $ \s -> s { kuts = F.ksUnion kvars (kuts s) }
where
kvars = sortNub $ specTypeKVars t
isKut :: KVKind -> Bool
isKut RecBindE = True
isKut _ = False
specTypeKVars :: SpecType -> [F.KVar]
specTypeKVars = foldReft ((++) . (kvars . ur_reft)) []
trueTy :: Type -> CG SpecType
trueTy = ofType' >=> true
ofType' :: Type -> CG SpecType
ofType' = fixTy . ofType
fixTy :: SpecType -> CG SpecType
fixTy t = do tyi <- tyConInfo <$> get
tce <- tyConEmbed <$> get
return $ addTyConInfo tce tyi t
refreshArgsTop :: (Var, SpecType) -> CG SpecType
refreshArgsTop (x, t)
= do (t', su) <- refreshArgsSub t
modify $ \s -> s {termExprs = M.adjust (F.subst su <$>) x $ termExprs s}
return t'
refreshArgs :: SpecType -> CG SpecType
refreshArgs t
= fst <$> refreshArgsSub t
-- NV TODO: this does not refreshes args if they are wrapped in an RRTy
refreshArgsSub :: SpecType -> CG (SpecType, F.Subst)
refreshArgsSub t
= do ts <- mapM refreshArgs ts_u
xs' <- mapM (\_ -> fresh) xs
let sus = F.mkSubst <$> (L.inits $ zip xs (F.EVar <$> xs'))
let su = last sus
let ts' = zipWith F.subst sus ts
let t' = fromRTypeRep $ trep {ty_binds = xs', ty_args = ts', ty_res = F.subst su tbd}
return (t', su)
where
trep = toRTypeRep t
xs = ty_binds trep
ts_u = ty_args trep
tbd = ty_res trep
instance Freshable CG Integer where
fresh = do s <- get
let n = freshIndex s
put $ s { freshIndex = n + 1 }
return n
-------------------------------------------------------------------------------
----------------------- TERMINATION TYPE --------------------------------------
-------------------------------------------------------------------------------
makeDecrIndex :: (Var, Template SpecType)-> CG [Int]
makeDecrIndex (x, Assumed t)
= do dindex <- makeDecrIndexTy x t
case dindex of
Left _ -> return []
Right i -> return i
makeDecrIndex (x, Asserted t)
= do dindex <- makeDecrIndexTy x t
case dindex of
Left msg -> addWarning msg >> return []
Right i -> return i
makeDecrIndex _ = return []
makeDecrIndexTy x t
= do spDecr <- specDecr <$> get
hint <- checkHint' (L.lookup x $ spDecr)
case dindex of
Nothing -> return $ Left msg -- addWarning msg >> return []
Just i -> return $ Right $ fromMaybe [i] hint
where
ts = ty_args trep
checkHint' = checkHint x ts (isDecreasing cenv)
dindex = L.findIndex (isDecreasing cenv) ts
msg = ErrTermin [x] (getSrcSpan x) (text "No decreasing parameter")
cenv = makeNumEnv ts
trep = toRTypeRep $ unOCons t
recType ((_, []), (_, [], t))
= t
recType ((vs, indexc), (_, index, t))
= makeRecType t v dxt index
where v = (vs !!) <$> indexc
dxt = (xts !!) <$> index
xts = zip (ty_binds trep) (ty_args trep)
trep = toRTypeRep $ unOCons t
checkIndex (x, vs, t, index)
= do mapM_ (safeLogIndex msg' vs) index
mapM (safeLogIndex msg ts) index
where
loc = getSrcSpan x
ts = ty_args $ toRTypeRep $ unOCons $ unTemplate t
msg' = ErrTermin [x] loc (text $ "No decreasing " ++ show index ++ "-th argument on " ++ (showPpr x) ++ " with " ++ (showPpr vs))
msg = ErrTermin [x] loc (text "No decreasing parameter")
makeRecType t vs dxs is
= mergecondition t $ fromRTypeRep $ trep {ty_binds = xs', ty_args = ts'}
where
(xs', ts') = unzip $ replaceN (last is) (makeDecrType vdxs) xts
vdxs = zip vs dxs
xts = zip (ty_binds trep) (ty_args trep)
trep = toRTypeRep $ unOCons t
unOCons (RAllT v t) = RAllT v $ unOCons t
unOCons (RAllP p t) = RAllP p $ unOCons t
unOCons (RFun x tx t r) = RFun x (unOCons tx) (unOCons t) r
unOCons (RRTy _ _ OCons t) = unOCons t
unOCons t = t
mergecondition (RAllT _ t1) (RAllT v t2)
= RAllT v $ mergecondition t1 t2
mergecondition (RAllP _ t1) (RAllP p t2)
= RAllP p $ mergecondition t1 t2
mergecondition (RRTy xts r OCons t1) t2
= RRTy xts r OCons (mergecondition t1 t2)
mergecondition (RFun _ t11 t12 _) (RFun x2 t21 t22 r2)
= RFun x2 (mergecondition t11 t21) (mergecondition t12 t22) r2
mergecondition _ t
= t
safeLogIndex err ls n
| n >= length ls = addWarning err >> return Nothing
| otherwise = return $ Just $ ls !! n
checkHint _ _ _ Nothing
= return Nothing
checkHint x _ _ (Just ns) | L.sort ns /= ns
= addWarning (ErrTermin [x] loc (text "The hints should be increasing")) >> return Nothing
where loc = getSrcSpan x
checkHint x ts f (Just ns)
= (mapM (checkValidHint x ts f) ns) >>= (return . Just . catMaybes)
checkValidHint x ts f n
| n < 0 || n >= length ts = addWarning err >> return Nothing
| f (ts L.!! n) = return $ Just n
| otherwise = addWarning err >> return Nothing
where err = ErrTermin [x] loc (text $ "Invalid Hint " ++ show (n+1) ++ " for " ++ (showPpr x) ++ "\nin\n" ++ show (ts))
loc = getSrcSpan x
-------------------------------------------------------------------
-------------------- Generation: Corebind -------------------------
-------------------------------------------------------------------
consCBTop :: (Var -> Bool) -> CGEnv -> CoreBind -> CG CGEnv
consCBLet :: CGEnv -> CoreBind -> CG CGEnv
-------------------------------------------------------------------
consCBLet γ cb
= do oldtcheck <- tcheck <$> get
strict <- specLazy <$> get
let tflag = oldtcheck
let isStr = tcond cb strict
modify $ \s -> s{tcheck = tflag && isStr}
γ' <- consCB (tflag && isStr) isStr γ cb
modify $ \s -> s{tcheck = oldtcheck}
return γ'
consCBTop trustBinding γ cb | all trustBinding xs
= do ts <- mapM trueTy (varType <$> xs)
foldM (\γ xt -> (γ, "derived") += xt) γ (zip xs' ts)
where xs = bindersOf cb
xs' = F.symbol <$> xs
consCBTop _ γ cb
= do oldtcheck <- tcheck <$> get
strict <- specLazy <$> get
let tflag = oldtcheck
let isStr = tcond cb strict
modify $ \s -> s{tcheck = tflag && isStr}
γ' <- consCB (tflag && isStr) isStr γ cb
modify $ \s -> s{tcheck = oldtcheck}
return γ'
tcond cb strict
= not $ any (\x -> S.member x strict || isInternal x) (binds cb)
where binds (NonRec x _) = [x]
binds (Rec xes) = fst $ unzip xes
-------------------------------------------------------------------
consCB :: Bool -> Bool -> CGEnv -> CoreBind -> CG CGEnv
-------------------------------------------------------------------
consCBSizedTys γ xes
= do xets'' <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e))
sflag <- scheck <$> get
let cmakeFinType = if sflag then makeFinType else id
let cmakeFinTy = if sflag then makeFinTy else snd
let xets = mapThd3 (fmap cmakeFinType) <$> xets''
ts' <- mapM (T.mapM refreshArgs) $ (thd3 <$> xets)
let vs = zipWith collectArgs ts' es
is <- mapM makeDecrIndex (zip xs ts') >>= checkSameLens
let ts = cmakeFinTy <$> zip is ts'
let xeets = (\vis -> [(vis, x) | x <- zip3 xs is $ map unTemplate ts]) <$> (zip vs is)
(L.transpose <$> mapM checkIndex (zip4 xs vs ts is)) >>= checkEqTypes
let rts = (recType <$>) <$> xeets
let xts = zip xs ts
γ' <- foldM extender γ xts
let γs = [γ' `withTRec` (zip xs rts') | rts' <- rts]
let xets' = zip3 xs es ts
mapM_ (uncurry $ consBind True) (zip γs xets')
return γ'
where
(xs, es) = unzip xes
collectArgs = collectArguments . length . ty_binds . toRTypeRep . unOCons . unTemplate
checkEqTypes :: [[Maybe SpecType]] -> CG [[SpecType]]
checkEqTypes x = mapM (checkAll err1 toRSort) (catMaybes <$> x)
checkSameLens = checkAll err2 length
err1 = ErrTermin xs loc $ text "The decreasing parameters should be of same type"
err2 = ErrTermin xs loc $ text "All Recursive functions should have the same number of decreasing parameters"
loc = getSrcSpan (head xs)
checkAll _ _ [] = return []
checkAll err f (x:xs)
| all (==(f x)) (f <$> xs) = return (x:xs)
| otherwise = addWarning err >> return []
consCBWithExprs γ xes
= do xets' <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e))
texprs <- termExprs <$> get
let xtes = catMaybes $ (`lookup` texprs) <$> xs
sflag <- scheck <$> get
let cmakeFinType = if sflag then makeFinType else id
let xets = mapThd3 (fmap cmakeFinType) <$> xets'
let ts = safeFromAsserted err . thd3 <$> xets
ts' <- mapM refreshArgs ts
let xts = zip xs (Asserted <$> ts')
γ' <- foldM extender γ xts
let γs = makeTermEnvs γ' xtes xes ts ts'
let xets' = zip3 xs es (Asserted <$> ts')
mapM_ (uncurry $ consBind True) (zip γs xets')
return γ'
where (xs, es) = unzip xes
lookup k m | Just x <- M.lookup k m = Just (k, x)
| otherwise = Nothing
err = "Constant: consCBWithExprs"
makeFinTy (ns, t) = fmap go t
where
go t = fromRTypeRep $ trep {ty_args = args'}
where
trep = toRTypeRep t
args' = mapNs ns makeFinType $ ty_args trep
makeTermEnvs γ xtes xes ts ts' = withTRec γ . zip xs <$> rts
where
vs = zipWith collectArgs ts es
ys = (fst4 . bkArrowDeep) <$> ts
ys' = (fst4 . bkArrowDeep) <$> ts'
sus' = zipWith mkSub ys ys'
sus = zipWith mkSub ys ((F.symbol <$>) <$> vs)
ess = (\x -> (safeFromJust (err x) $ (x `L.lookup` xtes))) <$> xs
tes = zipWith (\su es -> F.subst su <$> es) sus ess
tes' = zipWith (\su es -> F.subst su <$> es) sus' ess
rss = zipWith makeLexRefa tes' <$> (repeat <$> tes)
rts = zipWith addTermCond ts' <$> rss
(xs, es) = unzip xes
mkSub ys ys' = F.mkSubst [(x, F.EVar y) | (x, y) <- zip ys ys']
collectArgs = collectArguments . length . ty_binds . toRTypeRep
err x = "Constant: makeTermEnvs: no terminating expression for " ++ showPpr x
consCB tflag _ γ (Rec xes) | tflag
= do texprs <- termExprs <$> get
modify $ \i -> i { recCount = recCount i + length xes }
let xxes = catMaybes $ (`lookup` texprs) <$> xs
if null xxes
then consCBSizedTys γ xes
else check xxes <$> consCBWithExprs γ xes
where xs = fst $ unzip xes
check ys r | length ys == length xs = r
| otherwise = errorstar err
err = printf "%s: Termination expressions should be provided for ALL mutual recursive functions" loc
loc = showPpr $ getSrcSpan (head xs)
lookup k m | Just x <- M.lookup k m = Just (k, x)
| otherwise = Nothing
consCB _ str γ (Rec xes) | not str
= do xets' <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e))
sflag <- scheck <$> get
let cmakeDivType = if sflag then makeDivType else id
let xets = mapThd3 (fmap cmakeDivType) <$> xets'
modify $ \i -> i { recCount = recCount i + length xes }
let xts = [(x, to) | (x, _, to) <- xets]
γ' <- foldM extender (γ `withRecs` (fst <$> xts)) xts
mapM_ (consBind True γ') xets
return γ'
consCB _ _ γ (Rec xes)
= do xets <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e))
modify $ \i -> i { recCount = recCount i + length xes }
let xts = [(x, to) | (x, _, to) <- xets]
γ' <- foldM extender (γ `withRecs` (fst <$> xts)) xts
mapM_ (consBind True γ') xets
return γ'
-- | NV: Dictionaries are not checked, because
-- | class methods' preconditions are not satisfied
consCB _ _ γ (NonRec x _) | isDictionary x
= do t <- trueTy (varType x)
extender γ (x, Assumed t)
where
isDictionary = isJust . dlookup (denv γ)
consCB _ _ γ (NonRec x (App (Var w) (Type τ))) | isDictionary w
= do t <- trueTy τ
addW $ WfC γ t
let xts = dmap (f t) $ safeFromJust (show w ++ "Not a dictionary" ) $ dlookup (denv γ) w
let γ' = γ{denv = dinsert (denv γ) x xts }
t <- trueTy (varType x)
extender γ' (x, Assumed t)
where f t' (RAllT α te) = subsTyVar_meet' (α, t') te
f _ _ = error "consCB on Dictionary: this should not happen"
isDictionary = isJust . dlookup (denv γ)
consCB _ _ γ (NonRec x e)
<<<<<<< HEAD
= do to <- varTemplate γ (x, Nothing)
to' <- consBind False γ (x, e, to) >>= (addPostTemplate γ e)
extender γ (x, to')
-- consBind :: Bool -> CGEnv -> (CoreBndr, Expr CoreBndr, Template SpecType) -> CG (Template SpecType)
consBind isRec γ (x, e, Asserted spect)
=======
= do to <- varTemplate γ (x, Nothing)
to' <- consBind False γ (x, e, to) >>= (addPostTemplate γ)
extender γ (x, to')
consBind isRec γ (x, e, Asserted spect)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= do let γ' = (γ `setLoc` getSrcSpan x) `setBind` x
(_,πs,_,_) = bkUniv spect
γπ <- foldM addPToEnv γ' πs
cconsE γπ e spect
when (F.symbol x `elemHEnv` holes γ) $
-- have to add the wf constraint here for HOLEs so we have the proper env
addW $ WfC γπ $ fmap killSubst spect
addIdA x (defAnn isRec spect)
return $ Asserted spect -- Nothing
consBind isRec γ (x, e, Assumed spect)
= do let γ' = (γ `setLoc` getSrcSpan x) `setBind` x
γπ <- foldM addPToEnv γ' πs
cconsE γπ e =<< true spect
addIdA x (defAnn isRec spect)
return $ Asserted spect -- Nothing
where πs = ty_preds $ toRTypeRep spect
consBind isRec γ (x, e, Unknown)
= do t <- consE (γ `setBind` x) e
addIdA x (defAnn isRec t)
return $ Asserted t
noHoles = and . foldReft (\r bs -> not (hasHole r) : bs) []
killSubst :: RReft -> RReft
killSubst = fmap killSubstReft
killSubstReft :: F.Reft -> F.Reft
killSubstReft = trans kv () ()
where
<<<<<<< HEAD
tx (F.Reft (s, rs)) = F.Reft (s, map f rs)
f (F.RKvar k _) = F.RKvar k mempty
-- have to add next line to make pattern matching exhaustive
f r = r
=======
kv = defaultVisitor { txPred = ks }
ks _ (F.PKVar k _) = F.PKVar k mempty
ks _ p = p
-- tx (F.Reft (s, rs)) = F.Reft (s, map f rs)
-- f (F.RKvar k _) = F.RKvar k mempty
-- f (F.RConc p) = F.RConc p
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
defAnn True = AnnRDf
defAnn False = AnnDef
addPToEnv γ π
= do γπ <- γ ++= ("addSpec1", pname π, pvarRType π)
foldM (++=) γπ [("addSpec2", x, ofRSort t) | (t, x, _) <- pargs π]
extender γ (x, Asserted t) = γ ++= ("extender", F.symbol x, t)
extender γ (x, Assumed t) = γ ++= ("extender", F.symbol x, t)
extender γ _ = return γ
addBinders γ0 x' cbs = foldM (++=) (γ0 -= x') [("addBinders", x, t) | (x, t) <- cbs]
data Template a = Asserted a | Assumed a | Unknown deriving (Functor, F.Foldable, T.Traversable)
deriving instance (Show a) => (Show (Template a))
unTemplate (Asserted t) = t
unTemplate (Assumed t) = t
unTemplate _ = errorstar "Constraint.Generate.unTemplate called on `Unknown`"
<<<<<<< HEAD
addPostTemplate γ expr (Asserted t) = Asserted <$> addPost γ expr t
addPostTemplate γ expr (Assumed t) = Assumed <$> addPost γ expr t
addPostTemplate _ _ Unknown = return Unknown
=======
addPostTemplate γ (Asserted t) = Asserted <$> addPost γ t
addPostTemplate γ (Assumed t) = Assumed <$> addPost γ t
addPostTemplate _ Unknown = return Unknown
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
safeFromAsserted _ (Asserted t) = t
safeFromAsserted msg _ = errorstar $ "safeFromAsserted:" ++ msg
-- | @varTemplate@ is only called with a `Just e` argument when the `e`
-- corresponds to the body of a @Rec@ binder.
varTemplate :: CGEnv -> (Var, Maybe CoreExpr) -> CG (Template SpecType)
varTemplate γ (x, eo)
= case (eo, lookupREnv (F.symbol x) (grtys γ), lookupREnv (F.symbol x) (assms γ)) of
(_, Just t, _) -> Asserted <$> refreshArgsTop (x, t)
(_, _, Just t) -> Assumed <$> refreshArgsTop (x, t)
(Just e, _, _) -> do t <- freshTy_expr RecBindE e (exprType e)
addW (WfC γ t)
Asserted <$> refreshArgsTop (x, t)
(_, _, _) -> return Unknown
-------------------------------------------------------------------
-------------------- Generation: Expression -----------------------
-------------------------------------------------------------------
----------------------- Type Checking -----------------------------
cconsE :: CGEnv -> Expr Var -> SpecType -> CG ()
-------------------------------------------------------------------
cconsE γ e@(Let b@(NonRec x _) ee) t
= do sp <- specLVars <$> get
if (x `S.member` sp) || isDefLazyVar x
then cconsLazyLet γ e t
else do γ' <- consCBLet γ b
cconsE γ' ee t
where
isDefLazyVar = L.isPrefixOf "fail" . showPpr
cconsE γ e (RAllP p t)
= cconsE γ' e t''
where
t' = replacePredsWithRefs su <$> t
su = (uPVar p, pVartoRConc p)
(css, t'') = splitConstraints t'
γ' = foldl (flip addConstraints) γ css
cconsE γ (Let b e) t
= do γ' <- consCBLet γ b
cconsE γ' e t
cconsE γ (Case e x _ cases) t
= do γ' <- consCBLet γ (NonRec x e)
forM_ cases $ cconsCase γ' x t nonDefAlts
where
nonDefAlts = [a | (a, _, _) <- cases, a /= DEFAULT]
cconsE γ (Lam α e) (RAllT α' t) | isTyVar α
= cconsE γ e $ subsTyVar_meet' (α', rVar α) t
cconsE γ (Lam x e) (RFun y ty t _)
| not (isTyVar x)
= do γ' <- (γ, "cconsE") += (F.symbol x, ty)
cconsE γ' e (t `F.subst1` (y, F.EVar $ F.symbol x))
addIdA x (AnnDef ty)
cconsE γ (Tick tt e) t
= cconsE (γ `setLoc` tickSrcSpan tt) e t
-- GHC 7.10 encodes type classes with a single method as newtypes and
-- `cast`s between the method and class type instead of applying the
-- class constructor. Just rewrite the core to what we're used to
-- seeing..
cconsE γ (Cast e co) t
| Pair _t1 t2 <- coercionKind co
, isClassPred t2
, (tc,ts) <- splitTyConApp t2
, [dc] <- tyConDataCons tc
= cconsE γ (mkCoreConApps dc $ map Type ts ++ [e]) t
cconsE γ e@(Cast e' _) t
= do t' <- castTy γ (exprType e) e'
<<<<<<< HEAD
addC (SubC γ t' t [(γ,e)]) ("cconsE Cast" ++ showPpr e)
=======
addC (SubC γ t' t) ("cconsE Cast" ++ showPpr e)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
cconsE γ e t
= do te <- consE γ e
te' <- instantiatePreds γ e te >>= addPost γ e
addC (SubC γ te' t [(γ,e)]) ("cconsE" ++ showPpr e)
splitConstraints (RRTy cs _ OCons t)
= let (css, t') = splitConstraints t in (cs:css, t')
splitConstraints (RFun x tx@(RApp c _ _ _) t r) | isClass c
= let (css, t') = splitConstraints t in (css, RFun x tx t' r)
splitConstraints t
= ([], t)
-------------------------------------------------------------------
-- | @instantiatePreds@ peels away the universally quantified @PVars@
-- of a @RType@, generates fresh @Ref@ for them and substitutes them
-- in the body.
instantiatePreds γ e (RAllP π t)
= do r <- freshPredRef γ e π
instantiatePreds γ e $ replacePreds "consE" t [(π, r)]
instantiatePreds _ _ t0
= return t0
-------------------------------------------------------------------
-- | @instantiateStrata@ generates fresh @Strata@ vars and substitutes
-- them inside the body of the type.
instantiateStrata ls t = substStrata t ls <$> mapM (\_ -> fresh) ls
substStrata t ls ls' = F.substa f t
where
f x = fromMaybe x $ L.lookup x su
su = zip ls ls'
-------------------------------------------------------------------
cconsLazyLet γ (Let (NonRec x ex) e) t
= do tx <- trueTy (varType x)
γ' <- (γ, "Let NonRec") +++= (x', ex, tx)
cconsE γ' e t
where
x' = F.symbol x
cconsLazyLet _ _ _
= errorstar "Constraint.Generate.cconsLazyLet called on invalid inputs"
-------------------------------------------------------------------
-- | Type Synthesis -----------------------------------------------
-------------------------------------------------------------------
consE :: CGEnv -> Expr Var -> CG SpecType
-------------------------------------------------------------------
consE γ (Var x)
= do t <- varRefType γ x
addLocA (Just x) (loc γ) (varAnn γ x t)
return t
consE γ (Lit c)
= refreshVV $ uRType $ literalFRefType (emb γ) c
consE γ e'@(App e (Type τ))
= do RAllT α te <- checkAll ("Non-all TyApp with expr", e) <$> consE γ e
t <- if isGeneric α te then freshTy_type TypeInstE e τ else trueTy τ
addW $ WfC γ t
t' <- refreshVV t
instantiatePreds γ e' $ subsTyVar_meet' (α, t') te
consE γ e'@(App e a) | isDictionary a
= if isJust tt
then return $ fromJust tt
else do ([], πs, ls, te) <- bkUniv <$> consE γ e
te0 <- instantiatePreds γ e' $ foldr RAllP te πs
te' <- instantiateStrata ls te0
(γ', te''') <- dropExists γ te'
te'' <- dropConstraints γ te'''
updateLocA πs (exprLoc e) te''
let RFun x tx t _ = checkFun ("Non-fun App with caller ", e') te''
<<<<<<< HEAD
pushConsBind $ cconsE γ' a tx
addPost γ' e' $ maybe (checkUnbound γ' e' x t) (F.subst1 t . (x,)) (argExpr γ a)
=======
pushConsBind $ cconsE γ' a tx
addPost γ' $ maybe (checkUnbound γ' e' x t) (F.subst1 t . (x,)) (argExpr γ a)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
where
grepfunname (App x (Type _)) = grepfunname x
grepfunname (Var x) = x
grepfunname e = errorstar $ "grepfunname on \t" ++ showPpr e
mdict w = case w of
Var x -> case dlookup (denv γ) x of {Just _ -> Just x; Nothing -> Nothing}
Tick _ e -> mdict e
_ -> Nothing
isDictionary _ = isJust (mdict a)
d = fromJust (mdict a)
dinfo = dlookup (denv γ) d
tt = dhasinfo dinfo $ grepfunname e
consE γ e'@(App e a)
= do ([], πs, ls, te) <- bkUniv <$> consE γ e
te0 <- instantiatePreds γ e' $ foldr RAllP te πs
te' <- instantiateStrata ls te0
(γ', te''') <- dropExists γ te'
te'' <- dropConstraints γ te'''
updateLocA πs (exprLoc e) te''
let RFun x tx t _ = checkFun ("Non-fun App with caller ", e') te''
<<<<<<< HEAD
pushConsBind $ cconsE γ' a tx
addPost γ' e' $ maybe (checkUnbound γ' e' x t) (F.subst1 t . (x,)) (argExpr γ a)
=======
pushConsBind $ cconsE γ' a tx
addPost γ' $ maybe (checkUnbound γ' e' x t) (F.subst1 t . (x,)) (argExpr γ a)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
consE γ (Lam α e) | isTyVar α
= liftM (RAllT (rTyVar α)) (consE γ e)
consE γ e@(Lam x e1)
= do tx <- freshTy_type LamE (Var x) τx
γ' <- ((γ, "consE") += (F.symbol x, tx))
t1 <- consE γ' e1
addIdA x $ AnnDef tx
addW $ WfC γ tx
return $ rFun (F.symbol x) tx t1
where
FunTy τx _ = exprType e
-- EXISTS-BASED CONSTRAINTS HEREHEREHEREHERE
-- Currently suppressed because they break all sorts of invariants,
-- e.g. for `unfoldR`...
-- consE γ e@(Let b@(NonRec x _) e')
-- = do γ' <- consCBLet γ b
-- consElimE γ' [F.symbol x] e'
--
-- consE γ (Case e x _ [(ac, ys, ce)])
-- = do γ' <- consCBLet γ (NonRec x e)
-- γ'' <- caseEnv γ' x [] ac ys
-- consElimE γ'' (F.symbol <$> (x:ys)) ce
consE γ e@(Let _ _)
= cconsFreshE LetE γ e
consE γ e@(Case _ _ _ _)
= cconsFreshE CaseE γ e
consE γ (Tick tt e)
= do t <- consE (γ `setLoc` l) e
addLocA Nothing l (AnnUse t)
return t
where l = tickSrcSpan tt
-- GHC 7.10 encodes type classes with a single method as newtypes and
-- `cast`s between the method and class type instead of applying the
-- class constructor. Just rewrite the core to what we're used to
-- seeing..
consE γ (Cast e co)
| Pair _t1 t2 <- coercionKind co
, isClassPred t2
, (tc,ts) <- splitTyConApp t2
, [dc] <- tyConDataCons tc
= consE γ (mkCoreConApps dc $ map Type ts ++ [e])
consE γ e@(Cast e' _)
= castTy γ (exprType e) e'
consE _ e@(Coercion _)
= trueTy $ exprType e
consE _ e@(Type t)
= errorstar $ "consE cannot handle type " ++ showPpr (e, t)
castTy _ τ (Var x)
= do t <- trueTy τ
return $ t `strengthen` (uTop $ F.uexprReft $ F.expr x)
castTy g t (Tick _ e)
= castTy g t e
castTy _ _ e
= errorstar $ "castTy cannot handle expr " ++ showPpr e
-- castTy γ τ e
-- = do t <- trueTy (exprType e)
-- cconsE γ e t
-- trueTy τ
singletonReft = uTop . F.symbolReft . F.symbol
-- | @consElimE@ is used to *synthesize* types by **existential elimination**
-- instead of *checking* via a fresh template. That is, assuming
-- γ |- e1 ~> t1
-- we have
-- γ |- let x = e1 in e2 ~> Ex x t1 t2
-- where
-- γ, x:t1 |- e2 ~> t2
-- instead of the earlier case where we generate a fresh template `t` and check
-- γ, x:t1 |- e <~ t
-- consElimE γ xs e
-- = do t <- consE γ e
-- xts <- forM xs $ \x -> (x,) <$> (γ ??= x)
-- return $ rEx xts t
-- | @consFreshE@ is used to *synthesize* types with a **fresh template** when
-- the above existential elimination is not easy (e.g. at joins, recursive binders)
cconsFreshE kvkind γ e
= do t <- freshTy_type kvkind e $ exprType e
addW $ WfC γ t
cconsE γ e t
return t
checkUnbound γ e x t
| x `notElem` (F.syms t)
= t
| otherwise
= errorstar $ "checkUnbound: " ++ show x ++ " is elem of syms of " ++ show t
++ "\nIn\t" ++ showPpr e ++ " at " ++ showPpr (loc γ)
dropExists γ (REx x tx t) = liftM (, t) $ (γ, "dropExists") += (x, tx)
dropExists γ t = return (γ, t)
dropConstraints :: CGEnv -> SpecType -> CG SpecType
<<<<<<< HEAD
dropConstraints γ (RRTy [(_, ct)] _ OCons t)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) γ (zip xs ts)
addC (SubC γ' t1 t2 []) "dropConstraints"
=======
dropConstraints γ (RFun x tx@(RApp c _ _ _) t r) | isClass c
= (flip (RFun x tx)) r <$> dropConstraints γ t
dropConstraints γ (RRTy cts _ OCons t)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) γ xts
addC (SubC γ' t1 t2) "dropConstraints"
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
dropConstraints γ t
where
(xts, t1, t2) = envToSub cts
dropConstraints _ t = return t
-------------------------------------------------------------------------------------
cconsCase :: CGEnv -> Var -> SpecType -> [AltCon] -> (AltCon, [Var], CoreExpr) -> CG ()
-------------------------------------------------------------------------------------
cconsCase γ x t acs (ac, ys, ce)
= do cγ <- caseEnv γ x acs ac ys
cconsE cγ ce t
refreshTy t = refreshVV t >>= refreshArgs
refreshVV (RAllT a t) = liftM (RAllT a) (refreshVV t)
refreshVV (RAllP p t) = liftM (RAllP p) (refreshVV t)
refreshVV (REx x t1 t2)
= do [t1', t2'] <- mapM refreshVV [t1, t2]
liftM (shiftVV (REx x t1' t2')) fresh
refreshVV (RFun x t1 t2 r)
= do [t1', t2'] <- mapM refreshVV [t1, t2]
liftM (shiftVV (RFun x t1' t2' r)) fresh
refreshVV (RAppTy t1 t2 r)
= do [t1', t2'] <- mapM refreshVV [t1, t2]
liftM (shiftVV (RAppTy t1' t2' r)) fresh
refreshVV (RApp c ts rs r)
= do ts' <- mapM refreshVV ts
rs' <- mapM refreshVVRef rs
liftM (shiftVV (RApp c ts' rs' r)) fresh
refreshVV t
= return t
refreshVVRef (RProp ss t)
= do xs <- mapM (\_ -> fresh) (fst <$> ss)
let su = F.mkSubst $ zip (fst <$> ss) (F.EVar <$> xs)
liftM (RProp (zip xs (snd <$> ss)) . F.subst su) (refreshVV t)
refreshVVRef (RPropP ss r)
= return $ RPropP ss r
refreshVVRef (RHProp _ _)
= errorstar "TODO: EFFECTS refreshVVRef"
-------------------------------------------------------------------------------------
caseEnv :: CGEnv -> Var -> [AltCon] -> AltCon -> [Var] -> CG CGEnv
-------------------------------------------------------------------------------------
caseEnv γ x _ (DataAlt c) ys
= do let (x' : ys') = F.symbol <$> (x:ys)
xt0 <- checkTyCon ("checkTycon cconsCase", x) <$> γ ??= x'
tdc <- γ ??= (dataConSymbol c) >>= refreshVV
let (rtd, yts, _) = unfoldR tdc (shiftVV xt0 x') ys
let r1 = dataConReft c ys'
let r2 = dataConMsReft rtd ys'
let xt = (xt0 `F.meet` rtd) `strengthen` (uTop (r1 `F.meet` r2))
let cbs = safeZip "cconsCase" (x':ys') (xt0:yts)
cγ' <- addBinders γ x' cbs
cγ <- addBinders cγ' x' [(x', xt)]
return cγ
caseEnv γ x acs a _
= do let x' = F.symbol x
xt' <- (`strengthen` uTop (altReft γ acs a)) <$> (γ ??= x')
cγ <- addBinders γ x' [(x', xt')]
return cγ
altReft γ _ (LitAlt l) = literalFReft (emb γ) l
altReft γ acs DEFAULT = mconcat [notLiteralReft l | LitAlt l <- acs]
where notLiteralReft = maybe mempty F.notExprReft . snd . literalConst (emb γ)
altReft _ _ _ = error "Constraint : altReft"
unfoldR td (RApp _ ts rs _) ys = (t3, tvys ++ yts, ignoreOblig rt)
where
tbody = instantiatePvs (instantiateTys td ts) $ reverse rs
(ys0, yts', _, rt) = safeBkArrow $ instantiateTys tbody tvs'
yts'' = zipWith F.subst sus (yts'++[rt])
(t3,yts) = (last yts'', init yts'')
sus = F.mkSubst <$> (L.inits [(x, F.EVar y) | (x, y) <- zip ys0 ys'])
(αs, ys') = mapSnd (F.symbol <$>) $ L.partition isTyVar ys
tvs' = rVar <$> αs
tvys = ofType . varType <$> αs
unfoldR _ _ _ = error "Constraint.hs : unfoldR"
instantiateTys = foldl' go
where go (RAllT α tbody) t = subsTyVar_meet' (α, t) tbody
go _ _ = errorstar "Constraint.instanctiateTy"
instantiatePvs = foldl' go
where go (RAllP p tbody) r = replacePreds "instantiatePv" tbody [(p, r)]
go _ _ = errorstar "Constraint.instanctiatePv"
checkTyCon _ t@(RApp _ _ _ _) = t
checkTyCon x t = checkErr x t --errorstar $ showPpr x ++ "type: " ++ showPpr t
checkFun _ t@(RFun _ _ _ _) = t
checkFun x t = checkErr x t
checkAll _ t@(RAllT _ _) = t
checkAll x t = checkErr x t
checkErr (msg, e) t = errorstar $ msg ++ showPpr e ++ ", type: " ++ showpp t
varAnn γ x t
| x `S.member` recs γ
= AnnLoc (getSrcSpan' x)
| otherwise
= AnnUse t
getSrcSpan' x
| loc == noSrcSpan
= loc
| otherwise
= loc
where loc = getSrcSpan x
-----------------------------------------------------------------------
-- | Helpers: Creating Fresh Refinement -------------------------------
-----------------------------------------------------------------------
freshPredRef :: CGEnv -> CoreExpr -> PVar RSort -> CG SpecProp
freshPredRef γ e (PV _ (PVProp τ) _ as)
= do t <- freshTy_type PredInstE e (toType τ)
args <- mapM (\_ -> fresh) as
let targs = [(x, s) | (x, (s, y, z)) <- zip args as, (F.EVar y) == z ]
γ' <- foldM (++=) γ [("freshPredRef", x, ofRSort τ) | (x, τ) <- targs]
addW $ WfC γ' t
return $ RProp targs t
freshPredRef _ _ (PV _ PVHProp _ _)
= errorstar "TODO:EFFECTS:freshPredRef"
-----------------------------------------------------------------------
---------- Helpers: Creating Refinement Types For Various Things ------
-----------------------------------------------------------------------
argExpr :: CGEnv -> CoreExpr -> Maybe F.Expr
argExpr _ (Var vy) = Just $ F.eVar vy
argExpr γ (Lit c) = snd $ literalConst (emb γ) c
argExpr γ (Tick _ e) = argExpr γ e
argExpr _ e = errorstar $ "argExpr: " ++ showPpr e
varRefType γ x = liftM (varRefType' γ x) (γ ??= F.symbol x)
varRefType' γ x t'
| Just tys <- trec γ, Just tr <- M.lookup x' tys
= tr `strengthen` xr
| otherwise
= t
where t = t' `strengthen` xr
xr = singletonReft x -- uTop $ F.symbolReft $ F.symbol x
x' = F.symbol x
-- TODO: should only expose/use subt. Not subsTyVar_meet
subsTyVar_meet' (α, t) = subsTyVar_meet (α, toRSort t, t)
-----------------------------------------------------------------------
--------------- Forcing Strictness ------------------------------------
-----------------------------------------------------------------------
instance NFData CGEnv where
rnf (CGE x1 x2 x3 _ x5 x6 x7 x8 x9 _ _ x10 _ _ _ _ _)
= x1 `seq` rnf x2 `seq` seq x3 `seq` rnf x5 `seq`
rnf x6 `seq` x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10
instance NFData FEnv where
rnf (FE x1 _) = rnf x1
instance NFData SubC where
<<<<<<< HEAD
rnf (SubC x1 x2 x3 _)
= rnf x1 `seq` rnf x2 `seq` rnf x3
rnf (SubR x1 _ x2 _)
=======
rnf (SubC x1 x2 x3)
= rnf x1 `seq` rnf x2 `seq` rnf x3
rnf (SubR x1 _ x2)
>>>>>>> 93075f43817e7d040b120142466af0e7b7e292a7
= rnf x1 `seq` rnf x2
instance NFData Class where
rnf _ = ()
instance NFData RTyCon where
rnf _ = ()
instance NFData Type where
rnf _ = ()
instance NFData WfC where
rnf (WfC x1 x2)
= rnf x1 `seq` rnf x2
instance NFData CGInfo where
rnf x = ({-# SCC "CGIrnf1" #-} rnf (hsCs x)) `seq`
({-# SCC "CGIrnf2" #-} rnf (hsWfs x)) `seq`
({-# SCC "CGIrnf3" #-} rnf (fixCs x)) `seq`
({-# SCC "CGIrnf4" #-} rnf (fixWfs x)) `seq`
({-# SCC "CGIrnf6" #-} rnf (freshIndex x)) `seq`
({-# SCC "CGIrnf7" #-} rnf (binds x)) `seq`
({-# SCC "CGIrnf8" #-} rnf (annotMap x)) `seq`
({-# SCC "CGIrnf10" #-} rnf (kuts x)) `seq`
({-# SCC "CGIrnf10" #-} rnf (lits x)) `seq`
({-# SCC "CGIrnf10" #-} rnf (kvProf x))
-------------------------------------------------------------------------------
--------------------- Reftypes from F.Fixpoint Expressions ----------------------
-------------------------------------------------------------------------------
forallExprRefType :: CGEnv -> SpecType -> SpecType
forallExprRefType γ t = t `strengthen` (uTop r')
where
r' = fromMaybe mempty $ forallExprReft γ r
r = F.sr_reft $ rTypeSortedReft (emb γ) t
forallExprReft :: CGEnv -> F.Reft -> Maybe F.Reft
forallExprReft γ r = F.isSingletonReft r >>= forallExprReft_ γ
-- = do e <- F.isSingletonReft r
-- r' <- forallExprReft_ γ e
-- return r'
forallExprReft_ :: CGEnv -> F.Expr -> Maybe F.Reft
forallExprReft_ γ (F.EApp f es)
= case forallExprReftLookup γ (val f) of
Just (xs,_,_,t) -> let su = F.mkSubst $ safeZip "fExprRefType" xs es in
Just $ F.subst su $ F.sr_reft $ rTypeSortedReft (emb γ) t
Nothing -> Nothing -- F.exprReft e
forallExprReft_ γ (F.EVar x)
= case forallExprReftLookup γ x of
Just (_,_,_,t) -> Just $ F.sr_reft $ rTypeSortedReft (emb γ) t
Nothing -> Nothing -- F.exprReft e
forallExprReft_ _ _ = Nothing -- F.exprReft e
forallExprReftLookup γ x = snap <$> F.lookupSEnv x (syenv γ)
where
snap = mapFourth4 ignoreOblig . bkArrow . fourth4 . bkUniv . (γ ?=) . F.symbol
{-
splitExistsCases z xs tx
= fmap $ fmap (exrefAddEq z xs tx)
exrefAddEq z xs t (F.Reft (s, F.Refa rs))
= F.Reft(s, F.Refa (F.POr [ pand x | x <- xs]))
where
tref = fromMaybe mempty $ stripRTypeBase t
pand x = substzx x rs `mappend` exrefToPred x tref
substzx x = F.subst (F.mkSubst [(z, F.EVar x)])
exrefToPred x u = F.subst (F.mkSubst [(v, F.EVar x)]) p
where
F.Reft (v, F.Refa p) = ur_reft u
-}
-------------------------------------------------------------------------------
-------------------- Cleaner Signatures For Rec-bindings ----------------------
-------------------------------------------------------------------------------
exprLoc :: CoreExpr -> Maybe SrcSpan
exprLoc (Tick tt _) = Just $ tickSrcSpan tt
exprLoc (App e a) | isType a = exprLoc e
exprLoc _ = Nothing
isType (Type _) = True
isType a = eqType (exprType a) predType
exprRefType :: CoreExpr -> SpecType
exprRefType = exprRefType_ M.empty
exprRefType_ :: M.HashMap Var SpecType -> CoreExpr -> SpecType
exprRefType_ γ (Let b e)
= exprRefType_ (bindRefType_ γ b) e
exprRefType_ γ (Lam α e) | isTyVar α
= RAllT (rTyVar α) (exprRefType_ γ e)
exprRefType_ γ (Lam x e)
= rFun (F.symbol x) (ofType $ varType x) (exprRefType_ γ e)
exprRefType_ γ (Tick _ e)
= exprRefType_ γ e
exprRefType_ γ (Var x)
= M.lookupDefault (ofType $ varType x) x γ
exprRefType_ _ e
= ofType $ exprType e
bindRefType_ γ (Rec xes)
= extendγ γ [(x, exprRefType_ γ e) | (x,e) <- xes]
bindRefType_ γ (NonRec x e)
= extendγ γ [(x, exprRefType_ γ e)]
extendγ γ xts
= foldr (\(x,t) m -> M.insert x t m) γ xts
instance NFData REnv where
rnf (REnv _) = () -- rnf m
|
rolph-recto/liquidhaskell
|
src/Language/Haskell/Liquid/Constraint/Generate2.hs
|
bsd-3-clause
| 73,935 | 695 | 17 | 20,775 | 27,250 | 14,042 | 13,208 | -1 | -1 |
{-# LANGUAGE
OverloadedStrings
#-}
module Storage.Object.Aws where
import qualified Aws
import qualified Aws.Core as Aws
import qualified Aws.S3 as S3
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Network.HTTP.Conduit (Manager, RequestBody(..))
import System.IO
import System.Posix.Files
import qualified Storage.Object as Obj
data Config = Config
{ awsConfig :: !Aws.Configuration
, awsDomain :: !T.Text -- Need a good URL lib
, manager :: !Manager
}
-- | Aws implementation of Storage.Object.
withHandle :: Config -> Obj.Handle
withHandle cfg = Obj.Handle
{ Obj.store = store cfg
}
store :: Config -> Obj.Object -> IO Obj.StoreResponse
store cfg obj = do
let awscfg = awsConfig cfg
let s3cfg = S3.s3 Aws.HTTP (T.encodeUtf8 $ awsDomain cfg) False
let mgr = manager cfg
runResourceT $ do
let file = Obj.objData obj
let streamer sink = withFile file ReadMode $ \h -> sink $ S.hGet h 10240
size <- liftIO (fromIntegral . fileSize <$> getFileStatus file :: IO Integer)
let body = RequestBodyStream (fromInteger size) streamer
rsp <- Aws.pureAws awscfg s3cfg mgr $ S3.putObject "riverd" (T.pack file) body
return $ Obj.Success "Success!" -- Just return success always for now
{-
createFolder :: IO ()
createFolder = do
cfg <- Aws.dbgConfiguration
let s3cfg = S3.s3 Aws.HTTP "s3-eu-west-1.amazonaws.com" False
{- Set up a ResourceT region with an available HTTP manager. -}
withManager $ \mgr -> do
rsp <- Aws.pureAws cfg s3cfg mgr $
(S3.putObject "riverd" "testFolder/" mempty)
liftIO $ print rsp
-}
|
wayofthepie/collect
|
src/Storage/Object/Aws.hs
|
bsd-3-clause
| 1,807 | 0 | 17 | 404 | 424 | 230 | 194 | 40 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main
where
import Prelude hiding ((.), id)
import Control.Category
import Data.Monoid
import Data.Maybe
import Control.Applicative
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BS
import qualified Network.IRC.Message as I
import qualified Network.IRC.Message.Encode as I
import qualified Data.Attoparsec as A
import Data.Word (Word8)
import System.Random (RandomGen, Random(..))
import Data.Attoparsec.Char8 (char8)
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck hiding (property)
-- message = [ ":" prefix SPACE ] command [ params ] crlf
genMessage :: Gen B.ByteString
-- promote
-- sequenceA
genMessage = BS.concat <$> sequence [pre , genCommandStr, ps, pure "\r\n"]
where pre = oneof [ pure mempty
, B.append ":" <$> (B.append <$> genPrefix <*> pure " ")]
ps = oneof [ pure mempty, genParamsStr]
-- prefix = servername / ( nickname [ [ "!" user ] "@" host ] )
genPrefix :: Gen B.ByteString
genPrefix = frequency [(1,genServername), (3, genNickPrefix)]
where genNickPrefix = B.append <$> genNickname <*> genH
genH = oneof [ pure mempty
, B.append <$> genU <*> (B.cons 64 <$> genServername)]
genU = oneof [ pure mempty, B.append "!" <$> genUser]
-- command = 1*letter / 3digit
-- params = *14( SPACE middle ) [ SPACE ":" trailing ]
-- =/ 14( SPACE middle ) [ SPACE [ ":" ] trailing ]
genParamsStr :: Gen B.ByteString
genParamsStr = B.append <$> genHead <*> genTail
where
genHead = B.append " " <$> genMiddle
genTail = oneof [pure mempty, B.append <$> (pure " :") <*> genTrailing]
-- nospcrlfcl = %x01-09 / %x0B-0C / %x0E-1F / %x21-39 / %x3B-FF
genNospcrlfcl :: Gen Word8
genNospcrlfcl = elements $
[0x01..0x09]++[0x0B..0x0C]++[0x0E..0x1F]++[0x21..0x39]++[0x3B..0xFF]
-- middle = nospcrlfcl *( ":" / nospcrlfcl )
genMiddle :: Gen B.ByteString
genMiddle = B.pack <$> ( (:) <$>
genNospcrlfcl <*> listOf (frequency [(1, pure 58), (9, genNospcrlfcl)]))
-- trailing = *( ":" / " " / nospcrlfcl )
genTrailing :: Gen B.ByteString
genTrailing = B.pack <$>
listOf (frequency [(1,pure 58), (3,pure 32), (9, genNospcrlfcl)])
type Servername = Hostname
genServername :: Gen B.ByteString
genServername = genHostname
-- host = hostname / hostaddr
newtype Host = Host { unHost :: B.ByteString } deriving (Show, Eq)
instance Arbitrary Host where
arbitrary = undefined
-- hostname = shortname *( "." shortname )
newtype Hostname = Hostname { unHostname :: B.ByteString } deriving (Show, Eq)
instance Arbitrary Hostname where
arbitrary = Hostname <$> genHostname
genHostname = B.append <$>
genShortname <*> (B.concat <$> listOf g)
where g :: Gen B.ByteString
g = B.cons 0x2E <$> genShortname
-- shortname = ( letter / digit ) *( letter / digit / "-" )
-- *( letter / digit )
-- ; as specified in RFC 1123 [HNAME]
newtype Shortname = Shortname { unShortname :: B.ByteString }
deriving (Show, Eq)
instance Arbitrary Shortname where
arbitrary = Shortname <$> genShortname
genShortname :: Gen B.ByteString
genShortname = B.pack <$> ((:) <$> oneof [genLetter,genDigit] <*> listOf (oneof [genLetter, genDigit, pure 0x2D]))
-- hostaddr = ip4addr / ip6addr
newtype Hostaddr = Hostaddr { unHostaddr :: B.ByteString } deriving (Show, Eq)
instance Arbitrary Hostaddr where
arbitrary = undefined
-- ip4addr = 1*3digit "." 1*3digit "." 1*3digit "." 1*3digit
newtype Ip4addr = Ip4addr { unIp4addr :: B.ByteString } deriving (Show, Eq)
instance Arbitrary Ip4addr where
arbitrary = undefined
-- ip6addr = 1*hexdigit 7( ":" 1*hexdigit )
newtype Ip6addr = Ip6addr { unIp6addr :: B.ByteString } deriving (Show, Eq)
instance Arbitrary Ip6addr where
arbitrary = undefined
-- ip6addr =/ "0:0:0:0:0:" ( "0" / "FFFF" ) ":" ip4addr
-- nickname = ( letter / special ) *8( letter / digit / special / "-" )
newtype Nickname = Nickname { unNickname :: B.ByteString } deriving (Show, Eq)
instance Arbitrary Nickname where
arbitrary = Nickname <$> genNickname
-- old RFC says
-- <nick> ::= <letter> { <letter> | <number> | <special> }
genNickname :: Gen B.ByteString
--genNickname = B.pack <$> ((:) <$> oneof [genLetter,genSpecial] <*> listOf (oneof [genLetter, genDigit, genSpecial, pure 0x2D]))
genNickname = B.pack <$> ((:) <$> genLetter <*> listOf (oneof [genLetter, genDigit, genSpecial, pure 0x2D]))
newtype PrefixString = PrefixString { unPrefixString :: B.ByteString }
deriving (Show, Eq, Ord)
instance Arbitrary PrefixString where
arbitrary = PrefixString <$> genPrefix
newtype CommandString = CommandString { unCommandString :: B.ByteString }
deriving (Show, Eq, Ord)
instance Arbitrary CommandString where
arbitrary = CommandString <$> genCommandStr
genCommandStr :: Gen B.ByteString
genCommandStr = oneof [getCommandStr, gen3DigitNrStr]
instance Arbitrary B.ByteString where
arbitrary = B.pack <$> arbitrary
-- user = 1*( %x01-09 / %x0B-0C / %x0E-1F / %x21-3F / %x41-FF )
-- ; any octet except NUL, CR, LF, " " and "@"
genUser :: Gen B.ByteString
genUser = B.pack <$> listOf1 g
where g :: Gen Word8
g = elements $
[0x01..0x09]++[0x0B..0x0C]++[0x0E..0x1F]++[0x21..0x3F]++[0x41..0xFF]
-- letter = %x41-5A / %x61-7A ; A-Z / a-z
genLetter :: Gen Word8
genLetter = elements $ [0x41..0x5A] ++ [0x61..0x7A]
-- special = %x5B-60 / %x7B-7D
-- ; "[", "]", "\", "`", "_", "^", "{", "|", "}"
genSpecial :: Gen Word8
genSpecial = elements $ [0x5B..0x60] ++ [0x7B..0x7D]
-- digit = %x30-39 ; 0-9
genDigit :: Gen Word8
genDigit = elements $ [0x30..0x39]
prop_idempotent_message :: Property
prop_idempotent_message = forAll genMessage (\ms -> (e =<< e ms) == e ms)
where e = fmap I.encode . maybeP I.message
getCommandStr :: Gen B.ByteString
getCommandStr = elements $
[ "ADMIN", "AWAY", "CONNECT", "DIE", "ERROR", "INFO", "INVITE", "ISON"
, "JOIN", "KICK", "KILL", "LINKS", "LIST", "LUSERS", "MODE", "MOTD"
, "NAMES", "NICK", "NOTICE", "OPER", "PART", "PASS", "PING", "PONG"
, "PRIVMSG", "QUIT", "REHASH", "RESTART", "SERVICE", "SERVLIST", "SQUERY"
, "SQUIT", "STATS", "SUMMON", "TIME", "TOPIC", "TRACE", "USER", "USERHOST"
, "USERS", "VERSION", "WALLOPS", "WHO", "WHOIS", "WHOWAS"
]
gen3DigitNrStr :: Gen B.ByteString
gen3DigitNrStr = elements . map BS.pack $
[concatMap show [x,y,z] | x <- [0..9], y <- [0..9], z <- [0..9]]
maybeP :: A.Parser r -> BS.ByteString -> Maybe r
maybeP p s = A.maybeResult $ A.feed (A.parse p s) mempty
successfullyParsed p = isJust . maybeP p
prop_parsed = forAll genMessage (successfullyParsed I.message)
{-
idempotent :: Eq a => (a -> a) -> a -> Bool
idempotent e a = e (e a) == e a
-}
-- I.prefix expects an whitespace after the prefix !!!
main :: IO ()
main = do
-- hspec specs
quickCheckWith stdArgs { maxSuccess = 20000, maxSize = 512 } (
(label "prop_idempotent_message" prop_idempotent_message)
.&. (label "prop_idempotent_message" prop_idempotent_message))
|
bernstein/ircfs
|
tests/TestEncode.hs
|
bsd-3-clause
| 7,347 | 0 | 13 | 1,631 | 1,888 | 1,079 | 809 | 121 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
module Spec.Wordpress (tests) where
import qualified Data.Text as T
import qualified Data.XML.Types as XML
import Hakyll.Convert.Common (DistilledPost (..))
import Hakyll.Convert.Wordpress
import Spec.SpecHelpers
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit
import qualified Text.RSS.Syntax as RSS
deriving instance Eq DistilledPost
deriving instance Show DistilledPost
tests :: TestTree
tests =
testGroup
"Wordpress.distill"
[ extractsPostUri,
extractsPostBody,
combinesMultipleContentTags,
extractsPostTitle,
canSkipComments,
canExtractComments,
usesTheFirstCommentAuthorTag,
turnsIncorrectDatesIntoEpochStart,
parsesDates,
extractsPostTags,
extractsPostCategories
]
extractsPostUri :: TestTree
extractsPostUri =
testGroup
"extracts post's item link"
[ testCase (T.unpack uri) (dpUri (distill False (createInput uri)) @?= uri)
| uri <-
[ "https://example.com/testing-post-uris",
"http://www.example.com/~joe/posts.atom"
]
]
where
createInput uri =
(RSS.nullItem "First post")
{ RSS.rssItemLink = Just uri
}
contentTag :: XML.Name
contentTag =
XML.Name
{ XML.nameLocalName = "encoded",
XML.nameNamespace = Just "http://purl.org/rss/1.0/modules/content/",
XML.namePrefix = Just "content"
}
namedElement :: XML.Name -> [XML.Node] -> XML.Element
namedElement name nodes =
XML.Element
{ XML.elementName = name,
XML.elementAttributes = [],
XML.elementNodes = nodes
}
extractsPostBody :: TestTree
extractsPostBody =
testGroup
"extracts post's body"
[ testCase (T.unpack body) (dpBody (distill False (createInput body)) @?= T.append body "\n")
| body <-
[ "<p>Today was a snowy day, and I decided to...</p>",
"<h3>My opinion on current affairs</h3><p>So you see, I...</p>"
]
]
where
createInput body =
(RSS.nullItem "Test post")
{ RSS.rssItemOther =
[ namedElement contentTag [XML.NodeContent $ XML.ContentText body]
]
}
combinesMultipleContentTags :: TestTree
combinesMultipleContentTags =
testCase
"combines multiple content:encoded tags into the post body"
(dpBody (distill False input) @?= T.unlines [body1, body2])
where
body1 = "<h3>Welcome!</h3>"
body2 = "<p>Hope you like my blog</p>"
input =
(RSS.nullItem "Just testing")
{ RSS.rssItemOther =
[ createElement body1,
createElement body2
]
}
createElement body = namedElement contentTag [XML.NodeContent $ XML.ContentText body]
extractsPostTitle :: TestTree
extractsPostTitle =
testGroup
"extracts post's title"
[ testCase (T.unpack title) (dpTitle (distill False (RSS.nullItem title)) @?= Just title)
| title <-
[ "First post",
"You won't believe what happened to me today",
"Trying out <i>things</i>…"
]
]
commentTag :: XML.Name
commentTag =
XML.Name
{ XML.nameLocalName = "comment",
XML.nameNamespace = Just "http://wordpress.org/export/1.2/",
XML.namePrefix = Just "wp"
}
commentContentTag :: XML.Name
commentContentTag =
XML.Name
{ XML.nameLocalName = "comment_content",
XML.nameNamespace = Just "http://wordpress.org/export/1.2/",
XML.namePrefix = Just "wp"
}
commentDateTag :: XML.Name
commentDateTag =
XML.Name
{ XML.nameLocalName = "comment_date",
XML.nameNamespace = Just "http://wordpress.org/export/1.2/",
XML.namePrefix = Just "wp"
}
commentAuthorTag :: XML.Name
commentAuthorTag =
XML.Name
{ XML.nameLocalName = "comment_author",
XML.nameNamespace = Just "http://wordpress.org/export/1.2/",
XML.namePrefix = Just "wp"
}
canSkipComments :: TestTree
canSkipComments =
testCase
"does not extract comments if first argument is False"
(dpBody (distill False input) @?= "<p>Hello, world!</p>\n")
where
input =
(RSS.nullItem "Testing...")
{ RSS.rssItemOther =
[ namedElement contentTag [XML.NodeContent $ XML.ContentText "<p>Hello, world!</p>"],
namedElement
commentTag
[ XML.NodeContent $ XML.ContentText "<p>I'd like to point out that...</p>"
]
]
}
canExtractComments :: TestTree
canExtractComments =
testGroup
"extracts comments if first argument is True"
[ noDateNoAuthor,
dateNoAuthor,
noDateAuthor,
dateAuthor
]
where
createInput comment =
(RSS.nullItem "Testing...")
{ RSS.rssItemOther =
[ namedElement contentTag [XML.NodeContent $ XML.ContentText "<p>Is this thing on?</p>"],
comment
]
}
noDateNoAuthor =
testCase
"comments with no \"published\" date and no author"
(dpBody (distill True (createInput noDateNoAuthorComment)) @?= expectedNoDateNoAuthor)
noDateNoAuthorComment =
namedElement
commentTag
[ XML.NodeElement $
namedElement commentContentTag [XML.NodeContent $ XML.ContentText "<p>hi</p>"]
]
expectedNoDateNoAuthor =
"<p>Is this thing on?</p>\n\n\n\
\<h3 id='hakyll-convert-comments-title'>Comments</h3>\n\
\<div class='hakyll-convert-comment'>\n\
\<p class='hakyll-convert-comment-date'>On unknown date, unknown author wrote:</p>\n\
\<div class='hakyll-convert-comment-body'>\n\
\<p>hi</p>\n\
\</div>\n\
\</div>"
dateNoAuthor =
testCase
"comments with a \"published\" date but no author"
(dpBody (distill True (createInput dateNoAuthorComment)) @?= expectedDateNoAuthor)
dateNoAuthorComment =
namedElement
commentTag
[ XML.NodeElement $ namedElement commentContentTag [XML.NodeContent $ XML.ContentText "<p>hi</p>"],
XML.NodeElement $ namedElement commentDateTag [XML.NodeContent $ XML.ContentText "2017-09-02 21:28:46"]
]
expectedDateNoAuthor =
"<p>Is this thing on?</p>\n\n\n\
\<h3 id='hakyll-convert-comments-title'>Comments</h3>\n\
\<div class='hakyll-convert-comment'>\n\
\<p class='hakyll-convert-comment-date'>On 2017-09-02 21:28:46, unknown author wrote:</p>\n\
\<div class='hakyll-convert-comment-body'>\n\
\<p>hi</p>\n\
\</div>\n\
\</div>"
noDateAuthor =
testCase
"comments with no \"published\" date but with an author"
(dpBody (distill True (createInput commentNoDateAuthor)) @?= expectedNoDateAuthor)
commentNoDateAuthor =
namedElement
commentTag
[ XML.NodeElement $
namedElement
commentContentTag
[XML.NodeContent $ XML.ContentText "<p>Here's the thing: …</p>"],
XML.NodeElement $
namedElement commentAuthorTag [XML.NodeContent $ XML.ContentText "Terry Jones"]
]
expectedNoDateAuthor =
"<p>Is this thing on?</p>\n\n\n\
\<h3 id='hakyll-convert-comments-title'>Comments</h3>\n\
\<div class='hakyll-convert-comment'>\n\
\<p class='hakyll-convert-comment-date'>On unknown date, Terry Jones wrote:</p>\n\
\<div class='hakyll-convert-comment-body'>\n\
\<p>Here's the thing: …</p>\n\
\</div>\n\
\</div>"
dateAuthor =
testCase
"comments with a \"published\" date and an author"
(dpBody (distill True (createInput commentDateAuthor)) @?= expectedDateAuthor)
commentDateAuthor =
namedElement
commentTag
[ XML.NodeElement $
namedElement
commentContentTag
[XML.NodeContent $ XML.ContentText "<p>It sure is!</p>"],
XML.NodeElement $
namedElement
commentDateTag
[XML.NodeContent $ XML.ContentText "2017-09-02 21:28:46"],
XML.NodeElement $
namedElement
commentAuthorTag
[XML.NodeContent $ XML.ContentText "Elizabeth Keyes"]
]
expectedDateAuthor =
"<p>Is this thing on?</p>\n\n\n\
\<h3 id='hakyll-convert-comments-title'>Comments</h3>\n\
\<div class='hakyll-convert-comment'>\n\
\<p class='hakyll-convert-comment-date'>On 2017-09-02 21:28:46, Elizabeth Keyes wrote:</p>\n\
\<div class='hakyll-convert-comment-body'>\n\
\<p>It sure is!</p>\n\
\</div>\n\
\</div>"
usesTheFirstCommentAuthorTag :: TestTree
usesTheFirstCommentAuthorTag =
testCase
"uses the first wp:comment_author tag"
(dpBody (distill True input) @?= expected)
where
input =
(RSS.nullItem "Testing...")
{ RSS.rssItemOther =
[ namedElement
contentTag
[XML.NodeContent $ XML.ContentText "<p>Check this out!</p>"],
namedElement
commentTag
[ XML.NodeElement $ namedElement commentContentTag [XML.NodeContent $ XML.ContentText "<p>Cool!</p>"],
XML.NodeElement $ namedElement commentAuthorTag [XML.NodeContent $ XML.ContentText "Alexander Batischev"],
XML.NodeElement $ namedElement commentAuthorTag [XML.NodeContent $ XML.ContentText "John Doe"]
]
]
}
expected =
"<p>Check this out!</p>\n\n\n\
\<h3 id='hakyll-convert-comments-title'>Comments</h3>\n\
\<div class='hakyll-convert-comment'>\n\
\<p class='hakyll-convert-comment-date'>On unknown date, Alexander Batischev wrote:</p>\n\
\<div class='hakyll-convert-comment-body'>\n\
\<p>Cool!</p>\n\
\</div>\n\
\</div>"
turnsIncorrectDatesIntoEpochStart :: TestTree
turnsIncorrectDatesIntoEpochStart =
testGroup
"turns incorrect \"published\" dates into Unix epoch start date"
[ testCase (T.unpack date) (dpDate (distill False (createInput date)) @?= expected)
| date <-
[ "First of April",
"2020.07.30",
"2020.07.30 00:01",
"2020-07-30 00:01",
"2020-07-30T00:01",
"2020-07-30T00:01Z",
"Sun, 31st July, 2020"
]
]
where
createInput date =
(RSS.nullItem "Testing...")
{ RSS.rssItemPubDate = Just date
}
expected = fromGregorian 1970 1 1 0 0 0
parsesDates :: TestTree
parsesDates =
testGroup
"parses \"published\" dates"
[ testCase (T.unpack dateStr) (dpDate (distill False (createInput dateStr)) @?= expected)
| (dateStr, expected) <-
[ ("Sun, 06 Nov 1994 08:49:37 GMT", fromGregorian 1994 11 6 8 49 37),
("Fri, 31 Jul 2020 22:21:59 EST", fromGregorian 2020 8 1 3 21 59)
]
]
where
createInput date =
(RSS.nullItem "Testing...")
{ RSS.rssItemPubDate = Just date
}
extractsPostTags :: TestTree
extractsPostTags =
testCase
"extracts post's tags"
(dpTags (distill False input) @?= expected)
where
input =
(RSS.nullItem "Testing tags here")
{ RSS.rssItemCategories =
[ (RSS.newCategory "first tag") {RSS.rssCategoryDomain = Just "post_tag"},
(RSS.newCategory "a non-tag") {RSS.rssCategoryDomain = Just "wrong domain"},
(RSS.newCategory "second tag") {RSS.rssCategoryDomain = Just "post_tag"},
(RSS.newCategory "another non-tag") {RSS.rssCategoryDomain = Nothing},
(RSS.newCategory "third tag") {RSS.rssCategoryDomain = Just "post_tag"}
]
}
expected = ["first tag", "second tag", "third tag"]
extractsPostCategories :: TestTree
extractsPostCategories =
testCase
"extracts post's categories"
(dpCategories (distill False input) @?= expected)
where
input =
(RSS.nullItem "Testing categories here")
{ RSS.rssItemCategories =
[ (RSS.newCategory "essays") {RSS.rssCategoryDomain = Just "category"},
(RSS.newCategory "a non-category") {RSS.rssCategoryDomain = Just "wrong domain"},
(RSS.newCategory "traveling") {RSS.rssCategoryDomain = Just "category"},
(RSS.newCategory "another non-category") {RSS.rssCategoryDomain = Nothing}
]
}
expected = ["essays", "traveling"]
|
kowey/hakyll-convert
|
test/spec/Spec/Wordpress.hs
|
bsd-3-clause
| 12,402 | 0 | 17 | 3,260 | 2,268 | 1,220 | 1,048 | 265 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
-- |
-- Module : Network.Socks5.Types
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
module Network.Socks5.Types
( SocksVersion(..)
, SocksCommand(..)
, SocksMethod(..)
, SocksHostAddress(..)
, SocksAddress(..)
, SocksReply(..)
, SocksVersionNotSupported(..)
, SocksError(..)
) where
import Data.ByteString (ByteString)
import Data.Word
import Data.Data
import Network.Socket (HostAddress, HostAddress6, PortNumber)
import Control.Exception
import qualified Data.ByteString.Char8 as BC
import Numeric (showHex)
import Data.List (intersperse)
-- | Socks Version
data SocksVersion = SocksVer5
deriving (Show,Eq,Ord)
-- | Command that can be send and receive on the SOCKS protocol
data SocksCommand =
SocksCommandConnect
| SocksCommandBind
| SocksCommandUdpAssociate
| SocksCommandOther !Word8
deriving (Show,Eq,Ord)
-- | Authentication methods available on the SOCKS protocol.
--
-- Only SocksMethodNone is effectively implemented, but
-- other value are enumerated for completeness.
data SocksMethod =
SocksMethodNone
| SocksMethodGSSAPI
| SocksMethodUsernamePassword
| SocksMethodOther !Word8
| SocksMethodNotAcceptable
deriving (Show,Eq,Ord)
-- | A Host address on the SOCKS protocol.
data SocksHostAddress =
SocksAddrIPV4 !HostAddress
| SocksAddrDomainName !ByteString
| SocksAddrIPV6 !HostAddress6
deriving (Eq,Ord)
instance Show SocksHostAddress where
show (SocksAddrIPV4 ha) = "SocksAddrIPV4(" ++ showHostAddress ha ++ ")"
show (SocksAddrIPV6 ha6) = "SocksAddrIPV6(" ++ showHostAddress6 ha6 ++ ")"
show (SocksAddrDomainName dn) = "SocksAddrDomainName(" ++ BC.unpack dn ++ ")"
-- | 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
-- | Describe a Socket address on the SOCKS protocol
data SocksAddress = SocksAddress !SocksHostAddress !PortNumber
deriving (Show,Eq,Ord)
-- | Type of reply on the SOCKS protocol
data SocksReply =
SocksReplySuccess
| SocksReplyError SocksError
deriving (Show,Eq,Ord,Data,Typeable)
-- | SOCKS error that can be received or sent
data SocksError =
SocksErrorGeneralServerFailure
| SocksErrorConnectionNotAllowedByRule
| SocksErrorNetworkUnreachable
| SocksErrorHostUnreachable
| SocksErrorConnectionRefused
| SocksErrorTTLExpired
| SocksErrorCommandNotSupported
| SocksErrorAddrTypeNotSupported
| SocksErrorOther Word8
deriving (Show,Eq,Ord,Data,Typeable)
-- | Exception returned when using a SOCKS version that is not supported.
--
-- This package only implement version 5.
data SocksVersionNotSupported = SocksVersionNotSupported
deriving (Show,Data,Typeable)
instance Exception SocksError
instance Exception SocksVersionNotSupported
instance Enum SocksCommand where
toEnum 1 = SocksCommandConnect
toEnum 2 = SocksCommandBind
toEnum 3 = SocksCommandUdpAssociate
toEnum w
| w < 256 = SocksCommandOther $ fromIntegral w
| otherwise = error "socks command is only 8 bits"
fromEnum SocksCommandConnect = 1
fromEnum SocksCommandBind = 2
fromEnum SocksCommandUdpAssociate = 3
fromEnum (SocksCommandOther w) = fromIntegral w
instance Enum SocksMethod where
toEnum 0 = SocksMethodNone
toEnum 1 = SocksMethodGSSAPI
toEnum 2 = SocksMethodUsernamePassword
toEnum 0xff = SocksMethodNotAcceptable
toEnum w
| w < 256 = SocksMethodOther $ fromIntegral w
| otherwise = error "socks method is only 8 bits"
fromEnum SocksMethodNone = 0
fromEnum SocksMethodGSSAPI = 1
fromEnum SocksMethodUsernamePassword = 2
fromEnum (SocksMethodOther w) = fromIntegral w
fromEnum SocksMethodNotAcceptable = 0xff
instance Enum SocksError where
fromEnum SocksErrorGeneralServerFailure = 1
fromEnum SocksErrorConnectionNotAllowedByRule = 2
fromEnum SocksErrorNetworkUnreachable = 3
fromEnum SocksErrorHostUnreachable = 4
fromEnum SocksErrorConnectionRefused = 5
fromEnum SocksErrorTTLExpired = 6
fromEnum SocksErrorCommandNotSupported = 7
fromEnum SocksErrorAddrTypeNotSupported = 8
fromEnum (SocksErrorOther w) = fromIntegral w
toEnum 1 = SocksErrorGeneralServerFailure
toEnum 2 = SocksErrorConnectionNotAllowedByRule
toEnum 3 = SocksErrorNetworkUnreachable
toEnum 4 = SocksErrorHostUnreachable
toEnum 5 = SocksErrorConnectionRefused
toEnum 6 = SocksErrorTTLExpired
toEnum 7 = SocksErrorCommandNotSupported
toEnum 8 = SocksErrorAddrTypeNotSupported
toEnum w = SocksErrorOther $ fromIntegral w
instance Enum SocksReply where
fromEnum SocksReplySuccess = 0
fromEnum (SocksReplyError e) = fromEnum e
toEnum 0 = SocksReplySuccess
toEnum n = SocksReplyError (toEnum n)
|
erikd/hs-socks
|
Network/Socks5/Types.hs
|
bsd-3-clause
| 5,911 | 0 | 10 | 1,379 | 1,337 | 736 | 601 | 143 | 1 |
module SSH.Sender where
import Control.Concurrent.Chan
import Control.Monad (replicateM)
import Data.Word
import System.IO
import System.Random
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import SSH.Debug
import SSH.Crypto
import SSH.Packet
import SSH.Util
data SenderState
= NoKeys
{ senderThem :: Handle
, senderOutSeq :: Word32
}
| GotKeys
{ senderThem :: Handle
, senderOutSeq :: Word32
, senderEncrypting :: Bool
, senderCipher :: Cipher
, senderKey :: BS.ByteString
, senderVector :: BS.ByteString
, senderHMAC :: HMAC
}
data SenderMessage
= Prepare Cipher BS.ByteString BS.ByteString HMAC
| StartEncrypting
| Send LBS.ByteString
| Stop
class Sender a where
send :: SenderMessage -> a ()
sendPacket :: Packet () -> a ()
sendPacket = send . Send . doPacket
sender :: Chan SenderMessage -> SenderState -> IO ()
sender ms ss = do
m <- readChan ms
case m of
Stop -> return ()
Prepare cipher key iv hmac -> do
dump ("initiating encryption", key, iv)
sender ms (GotKeys (senderThem ss) (senderOutSeq ss) False cipher key iv hmac)
StartEncrypting -> do
dump ("starting encryption")
sender ms (ss { senderEncrypting = True })
Send msg -> do
pad <- fmap (LBS.pack . map fromIntegral) $
replicateM (fromIntegral $ paddingLen msg) (randomRIO (0, 255 :: Int))
let f = full msg pad
case ss of
GotKeys h os True cipher key iv (HMAC _ mac) -> do
dump ("sending encrypted", os, f)
let (encrypted, newVector) = encrypt cipher key iv f
LBS.hPut h . LBS.concat $
[ encrypted
, mac . doPacket $ long os >> raw f
]
hFlush h
sender ms $ ss
{ senderOutSeq = senderOutSeq ss + 1
, senderVector = newVector
}
_ -> do
dump ("sending unencrypted", senderOutSeq ss, f)
LBS.hPut (senderThem ss) f
hFlush (senderThem ss)
sender ms (ss { senderOutSeq = senderOutSeq ss + 1 })
where
blockSize =
case ss of
GotKeys { senderCipher = Cipher _ _ bs _ }
| bs > 8 -> bs
_ -> 8
full msg pad = doPacket $ do
long (len msg)
byte (paddingLen msg)
raw msg
raw pad
len :: LBS.ByteString -> Word32
len msg = 1 + fromIntegral (LBS.length msg) + fromIntegral (paddingLen msg)
paddingNeeded :: LBS.ByteString -> Word8
paddingNeeded msg = fromIntegral blockSize - (fromIntegral $ (5 + LBS.length msg) `mod` fromIntegral blockSize)
paddingLen :: LBS.ByteString -> Word8
paddingLen msg =
if paddingNeeded msg < 4
then paddingNeeded msg + fromIntegral blockSize
else paddingNeeded msg
encrypt :: Cipher -> BS.ByteString -> BS.ByteString -> LBS.ByteString -> (LBS.ByteString, BS.ByteString)
encrypt (Cipher AES CBC bs _) key vector m =
( fromBlocks encrypted
, case encrypted of
(_:_) -> strictLBS (last encrypted)
[] -> error ("encrypted data empty for `" ++ show m ++ "' in encrypt") vector
)
where
encrypted = toBlocks bs $ aes128cbcEncrypt key vector m
|
alexbiehl/hs-ssh
|
src/SSH/Sender.hs
|
bsd-3-clause
| 3,569 | 0 | 22 | 1,279 | 1,101 | 560 | 541 | 90 | 7 |
{-#LANGUAGE DeriveDataTypeable
, DeriveFunctor
, DeriveFoldable
, DeriveTraversable #-}
module Language.Asdf.AST where
import Data.Data
import Data.Foldable
import Data.Traversable
import qualified Data.Map as Map
import Text.Parsec
data Prec = None
| In Rational
| InL Rational
| InR Rational
| Pre Rational
| Post Rational
deriving (Eq, Ord, Show, Data, Typeable)
data Identifier = VarId String
| TypeId String
| OpId Prec String
deriving (Eq, Ord, Show, Data, Typeable)
data Statement = ExprStmt ParsedExpr
| VarDef String
| ConstDef String ParsedExpr
| Foreign String
| Assign String ParsedExpr
| FuncDef String [ParsedStatement] Bool ParsedStatement
| Scope [ParsedStatement]
| For ParsedStatement ParsedStatement ParsedStatement ParsedStatement
| While ParsedExpr ParsedStatement
| DoWhile ParsedExpr ParsedStatement
| If ParsedExpr [ParsedStatement] (Maybe [ParsedStatement])
| Return ParsedExpr
deriving (Show, Eq, Ord, Data, Typeable)
data ParsedStatement = ParsedStatement SourcePos Statement
deriving (Show, Eq, Ord, Data, Typeable)
data Expr = Call ParsedExpr [ParsedExpr]
{- This is more complex because we want to be able tell (when pretty printing) the difference between a
regular identifier and an operator identifier. For example a + b, or zipWith((+), a, b)
-}
| Id Identifier
| Cast ParsedType ParsedExpr
| Dot ParsedExpr String
| StringLiteral String
| CharLiteral Char
| IntegerLiteral Integer
| FloatLiteral Double
deriving (Show, Eq, Ord, Data, Typeable)
data ParsedExpr = ParsedExpr SourcePos Expr
deriving (Show, Eq, Ord, Data, Typeable)
data Type a = TypeName String
| Pointer a
| Array (Maybe Integer) a
| TCall a [a]
| Struct (Map.Map String a)
| Union (Map.Map String a)
| NType Int
| Func [a] Bool a -- bool indicates variable number of arguments
| DefaultInt
| DefaultFloat
| Var (Maybe String)
deriving (Show, Eq, Ord, Data, Typeable, Functor, Foldable, Traversable)
data ParsedType = ParsedType SourcePos (Type ParsedType)
deriving (Show, Eq, Ord, Data, Typeable)
|
sw17ch/Asdf
|
src/Language/Asdf/AST.hs
|
bsd-3-clause
| 2,563 | 0 | 9 | 857 | 587 | 330 | 257 | 61 | 0 |
{-# LANGUAGE OverloadedStrings, PackageImports #-}
import Control.Applicative
import Control.Monad
import "monads-tf" Control.Monad.Trans
import Data.HandleLike
import System.Environment
import Network
import Network.PeyoTLS.ReadFile
import Network.PeyoTLS.Client
import "crypto-random" Crypto.Random
import qualified Data.ByteString.Char8 as BSC
main :: IO ()
main = do
d : _ <- getArgs
ca <- readCertificateStore [
d ++ "/cacert.pem",
d ++ "/geotrust_global_ca.pem" ]
-- h <- connectTo "localhost" $ PortNumber 443
h <- connectTo "skami3.iocikun.jp" $ PortNumber 443
g <- cprgCreate <$> createEntropyPool :: IO SystemRNG
(`run` g) $ do
p <- open h ["TLS_RSA_WITH_AES_128_CBC_SHA"] [] ca
nms <- getNames p
unless ("skami3.iocikun.jp" `elem` nms) . error $
"certificate name mismatch: " ++ show nms
hlPut p "GET / HTTP/1.1 \r\n"
hlPut p "Host: localhost\r\n\r\n"
doUntil BSC.null (hlGetLine p) >>= liftIO . mapM_ BSC.putStrLn
hlClose p
doUntil :: Monad m => (a -> Bool) -> m a -> m [a]
doUntil p rd = rd >>= \x ->
(if p x then return . (: []) else (`liftM` doUntil p rd) . (:)) x
|
YoshikuniJujo/peyotls
|
peyotls/examples/checkMyServer.hs
|
bsd-3-clause
| 1,111 | 8 | 15 | 195 | 376 | 196 | 180 | 31 | 2 |
module Day5.DoesntHeHaveInternElvesForThis
( countNiceStrings
) where
import Data.List as L
import Data.List.Split as S
countNiceStrings :: String -> Int
countNiceStrings = undefined -- filter doesNotContainDisallowedStrings . filter containsAtLeastOneLetterThatAppearsTwiceInARow . filter hasAtLeastThreeVowels $ S.splitOn "\n" input
isNice :: String -> Bool
isNice = undefined -- filter doesNotContainDisallowedStrings . containsAtLeastOneLetterThatAppearsTwiceInARow . hasAtLeastThreeVowels
hasAtLeastThreeVowels :: String -> Bool
hasAtLeastThreeVowels s = (L.length . filter isVowel $ s) >= 3
isVowel :: Char -> Bool
isVowel c
| c == 'a' = True
| c == 'e' = True
| c == 'i' = True
| c == 'o' = True
| c == 'u' = True
| otherwise = False
containsAtLeastOneLetterThatAppearsTwiceInARow :: String -> Bool
containsAtLeastOneLetterThatAppearsTwiceInARow [] = False
containsAtLeastOneLetterThatAppearsTwiceInARow [_] = False
containsAtLeastOneLetterThatAppearsTwiceInARow (x:y:ys)
| x == y = True
| otherwise = containsAtLeastOneLetterThatAppearsTwiceInARow (y:ys)
doesNotContainDisallowedStrings :: String -> Bool
doesNotContainDisallowedStrings s
| "ab" `isInfixOf` s = False
| "cd" `isInfixOf` s = False
| "pq" `isInfixOf` s = False
| "xy" `isInfixOf` s = False
| otherwise = True
|
fboyer/adventofcode-haskell
|
src/Day5/DoesntHeHaveInternElvesForThis.hs
|
bsd-3-clause
| 1,335 | 0 | 9 | 221 | 342 | 178 | 164 | 31 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Diagrams.Backend.HsQML.Tutorial (
-- * DiagramCanvas QML script
-- $diagramcanvas
-- * Context object
-- $contextobject
-- * Main window
-- $mainwindow
-- * Rendering diagrams
-- $rendering
) where
import Graphics.QML
import Diagrams.Backend.HsQML
import Diagrams.Backend.HsQML.DiagramObj.Type
{- $diagramcanvas
To use this backend you first need a custom Canvas object to handle signals coming from Haskell.
Example script to place in your QML search path (can be next to your main QML document):
> -- DiagramCanvas.qml
>import QtQuick 2.4
>
>Canvas {
> id: canvas;
> property variant diagram;
> renderStrategy: Canvas.Threaded;
> renderTarget: Canvas.FramebufferObject;
>
> onDiagramChanged: {
> var context = canvas.getContext('2d');
> if(canvas.diagram && context) {
> console.log("reconnect");
> canvas.diagram.save.connect(function() {canvas.context.save()})
> canvas.diagram.restore.connect(function () {canvas.context.restore()});
> canvas.diagram.text.connect(function (text,x,y) {canvas.context.strokeText(text,x,y)});
> canvas.diagram.beginPath.connect(function () {canvas.context.beginPath()});
> canvas.diagram.closePath.connect(function () {canvas.context.closePath()});
> canvas.diagram.stroke.connect(function () {canvas.context.stroke()});
> canvas.diagram.fill.connect(function() {canvas.context.fill()});
> canvas.diagram.moveTo.connect(function (x,y) {canvas.context.moveTo(x,y)});
> canvas.diagram.lineTo.connect(function (x,y) {canvas.context.lineTo(x,y)});
> canvas.diagram.bezierCurveTo.connect(function(cp1x,cp1y,cp2x,cp2y,x,y)
> {canvas.context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)});
> canvas.diagram.connectLinearGradient.connect(connectLG);
> canvas.diagram.connectRadialGradient.connect(connectRG);
>
> canvas.diagram.setStrokeColour.connect(function(r,g,b,a)
> {canvas.context.strokeStyle = Qt.rgba(r,g,b,a).toString();});
> canvas.diagram.setFillColour.connect(function(r,g,b,a)
> {canvas.context.fillStyle = Qt.rgba(r,g,b,a)});
> canvas.diagram.setFont.connect(function(f) {canvas.context.font = f});
> canvas.diagram.setLineWidth.connect(function(w) {canvas.context.lineWidth = w});
> canvas.diagram.oddEvenFill.connect(function() {canvas.context.fillRule = Qt.OddEvenFill});
> canvas.diagram.windingFill.connect(function() {canvas.context.fillRule = Qt.WindingFill});
> } else {
> console.log("warning! no diagram or context object to connect");
> }
> }
>
> onPaint: {
> if(canvas.diagram) {
> canvas.diagram.reload();
> }
> }
>
> function connectLG(gradient, x0, y0, x1, y1) {
> var grad = canvas.context.createLinearGradient(x0, y0, x1, y1);
> gradient.addStop.connect( function(r,g,b,a, off) {grad.addColorStop(off, Qt.rgba(r,g,b,a))});
> canvas.diagram.setLineGradient.connect(function() {canvas.context.strokeStyle = grad;});
> canvas.diagram.setFillGradient.connect(function() {canvas.context.fillStyle = grad;});
>
> }
>
> function connectRG(gradient, x0, y0, r0, x1, y1, r1) {
> var grad = canvas.context.createRadialGradient(x0, y0, r0, x1, y1, r1);
> gradient.addStop.connect(function(r,g,b,a, off) {grad.addColorStop(off, Qt.rgba(r,g,b,a))});
> canvas.diagram.setLineGradient.connect(function() {canvas.context.strokeStyle = grad;});
> canvas.diagram.setFillGradient.connect(function() {canvas.context.fillStyle = grad;});
> }
>}
-}
{- $contextobject
You can make an 'ObjRef' to a 'DiagramObj' available to the QML script by placing it in a property of your context object:
> -- Main.hs
> module Main where
> import Control.Applicative
> import Control.Concurrent
> import Control.Concurrent.MVar
> import Data.Typeable
> import Diagrams.Prelude
> import Diagrams.Backend.HsQML
> import Graphics.QML
>
>data Repaint deriving Typeable
>
>repaint :: Proxy Repaint
>repaint = Proxy
>
>instance SignalKeyClass Repaint where
> type SignalParams Repaint = IO ()
>
>data MainObj = MainObj
> { diagramObj :: MVar (ObjRef (DiagramObj ()))
> }
> deriving Typeable
>
>instance DefaultClass MainObj where
> classMembers =
> [ defPropertySigRO' "mainDiagram" diagramChanged $ \this ->
> case fromObjRef this of
> MainObj mvar -> readMVar mvar
> , defPropertyConst' "self" return
> , defSignal "repaint" repaint
> ]
-}
{- $mainwindow
Then, place a DiagramCanvas somewhere in your application, and connect it to the controller object:
> -- main.qml
>import QtQuick 2.0
>import QtQuick.Controls 1.3
>import QtQuick.Window 2.2
>
>ApplicationWindow {
> title: "test";
> width: 800;
> height: 800;
> visible: true;
>
> toolBar: ToolBar {
> ToolButton {
> onClicked: canvas.repaint();
> }
> }
>
> DiagramCanvas {
> id: canvas;
> anchors.fill: parent;
>
> function repaint() {
> canvas.diagram = self.mainDiagram;
> canvas.paint(canvas.canvasWindow);
> }
>
> Connections {
> target: self;
> onRepaint: canvas.repaint();
> }
> }
>
>}
-}
{- $rendering
The 'renderHsQML' function creates an 'ObjRef' to the controller object.
> -- Main.hs
>diagram :: Diagram B R2
>diagram = circle 1
>
>main :: IO ()
>main = do
> diag <- renderHsQML (mkSizeSpec (Just 800) (Just 800)) diagram
> mainObj <- MainObj <$> newMVar diag
> ctx <- newObjectDC mainObj
> runEngineLoop defaultEngineConfig
> { initialDocument = fileDocument "qml/main.qml"
> , contextObject = Just $ anyObjRef ctx
> }
-}
|
marcinmrotek/diagrams-hsqml
|
src/Diagrams/Backend/HsQML/Tutorial.hs
|
bsd-3-clause
| 5,634 | 0 | 4 | 984 | 43 | 34 | 9 | 5 | 0 |
{-# LANGUAGE PatternGuards #-}
import System.Exit (exitSuccess)
import qualified Debug.Trace as T
import Control.Monad (forM_, when)
import Control.Monad.ST (runST)
import Control.Applicative ((<$>))
import qualified Data.Vector as Vec
import qualified Data.Vector.Mutable as VM
import Data.Vector ((!), (//))
import qualified Graphics.UI.GLFW as GLFW
import qualified Graphics.Rendering.OpenGL.Raw as GL
import qualified Gamgine.Gfx as GFX
import qualified Gamgine.Math.Vect as V
import qualified Gamgine.Math.Matrix as M
import qualified Gamgine.Math.Utils as MU
import Gamgine.Math.Vect
import Gamgine.Gfx ((<<<))
type Point = V.Vect
type Points = Vec.Vector Point
gridWidth = 20 :: Int
gridHeight = 20 :: Int
dGridWidth = fromIntegral gridWidth
dGridHeight = fromIntegral gridHeight
borderWidth = (fromIntegral $ max gridWidth gridHeight)
edgeLength = 1 :: Double
fixedPoint :: Int -> Bool
fixedPoint i =
i == gridWidth * (gridHeight - 1)
|| i == (gridWidth * gridHeight) - 1
makeGrid :: Int -> Int -> Double -> Points
makeGrid width length edgeLength =
Vec.generate (width * length) $ \i ->
let (quot, rem) = i `quotRem` width
x = fromIntegral rem * edgeLength
y = fromIntegral quot * edgeLength
in (x:.y:.0)
main :: IO ()
main = do
GLFW.init
GLFW.windowHint $ GLFW.WindowHint'Resizable True
GLFW.swapInterval 1
Just win <- GLFW.createWindow 800 800 "" Nothing Nothing
initCallbacks win
GLFW.makeContextCurrent (Just win)
appLoop win Nothing $ makeGrid gridWidth gridHeight edgeLength
appLoop :: GLFW.Window -> Maybe Int -> Points -> IO ()
appLoop win currIdx points = do
GLFW.pollEvents
GL.glClearColor 0 0 0 0
GL.glClear (fromIntegral GL.gl_COLOR_BUFFER_BIT)
renderLines points
let pts' = applyGravity . applyConstraints $ points
mworld <- mousePosInWorldCoords win
gridTrans <- gridTranslation win
let mgrid = mworld - gridTrans
pressed <- isButtonPressed win GLFW.MouseButton'1
let currIdx' | not pressed = Nothing
| Nothing <- currIdx = findClosestPoint mgrid pts'
| otherwise = currIdx
case currIdx' of
Just idx -> do
GL.glPointSize 10
GL.glColor3f <<< ((1,0,0) :: GFX.RGB)
GFX.withPrimitive GL.gl_POINTS $
GL.glVertex3f <<< (pts' ! idx)
let pts'' | pressed = pts' // [(idx, mgrid)]
| otherwise = pts'
GLFW.swapBuffers win
appLoop win currIdx' pts''
_ -> do
GLFW.swapBuffers win
appLoop win currIdx' pts'
where
isButtonPressed win button = (== GLFW.MouseButtonState'Pressed) <$> GLFW.getMouseButton win button
renderLines :: Points -> IO ()
renderLines points = do
GL.glColor3f <<< ((1,1,1) :: GFX.RGB)
-- verticals
forM_ [0 .. gridWidth - 1] $ \x ->
GFX.withPrimitive GL.gl_LINE_STRIP $
forM_ [0 .. gridHeight - 1] $ \y ->
GL.glVertex3f <<< (points ! (y * gridWidth + x))
-- horizontals
forM_ [0 .. gridHeight - 1] $ \y ->
GFX.withPrimitive GL.gl_LINE_STRIP $
forM_ [0 .. gridWidth - 1] $ \x ->
GL.glVertex3f <<< (points ! (y * gridWidth + x))
findClosestPoint :: V.Vect -> Points -> Maybe Int
findClosestPoint pos points =
let (_, idx, _) = Vec.foldl' compDist (0, -1, edgeLength) points
in if idx == -1 then Nothing else Just idx
where
compDist (i, idx, dist) p =
let dist' = V.len $ pos - p
in if dist' < dist
then (i + 1, i, dist')
else (i + 1, idx, dist)
applyGravity :: Points -> Points
applyGravity points = runST (apply points)
where
apply points = do
mutPts <- Vec.thaw points
forM_ [0 .. (gridWidth * gridHeight - 1)] $ \i -> do
when (not $ fixedPoint i) $ do
pt <- VM.read mutPts i
VM.write mutPts i (pt - gravity)
Vec.freeze mutPts
gravity = (0:. (edgeLength * 0.02) :.0:.())
applyConstraints :: Points -> Points
applyConstraints points = runST (apply points)
where
apply points = do
mutPts <- Vec.thaw points
forM_ [0 .. (gridWidth * gridHeight - 1)] $ \i -> do
let (y, x) = i `quotRem` gridWidth
when (x > 0) $ constrain i (i - 1) mutPts
when (x < (gridWidth - 1)) $ constrain i (i + 1) mutPts
when (y > 0) $ constrain i (i - gridWidth) mutPts
when (y < (gridHeight - 1)) $ constrain i (i + gridWidth) mutPts
Vec.freeze mutPts
constrain i j pts = do
iPt <- VM.read pts i
jPt <- VM.read pts j
let diff = iPt - jPt
norm = V.normalize diff
len = V.len diff
iFix = fixedPoint i
jFix = fixedPoint j
ptsAway = len >= edgeLength
disp = abs (len - edgeLength)
iT | iFix = 0
| jFix = disp
| otherwise = disp * 0.5
jT | jFix = 0
| iFix = disp
| otherwise = disp * 0.5
iVec = norm * V.v3 iT iT iT
jVec = norm * V.v3 jT jT jT
VM.write pts i (if ptsAway then iPt - iVec else iPt + iVec)
VM.write pts j (if ptsAway then jPt + jVec else jPt - jVec)
initCallbacks :: GLFW.Window -> IO ()
initCallbacks win = do
GLFW.setWindowSizeCallback win (Just resize)
GLFW.setWindowCloseCallback win (Just quit)
where
resize win width height = do
let M.Frustum {M.right = right, M.top = top} = frustum (width, height)
GL.glViewport 0 0 (fromIntegral width) (fromIntegral height)
GL.glMatrixMode GL.gl_PROJECTION
GL.glLoadIdentity
GL.glOrtho 0 (GFX.floatToFloat right) 0 (GFX.floatToFloat top) (-1) 1
GL.glMatrixMode GL.gl_MODELVIEW
GL.glLoadIdentity
gridTrans <- gridTranslation win
GL.glTranslatef <<< gridTrans
quit win = GLFW.destroyWindow win >> GLFW.terminate >> exitSuccess
mousePosInWorldCoords :: GLFW.Window -> IO V.Vect
mousePosInWorldCoords win = do
winDims <- GLFW.getWindowSize win
(cx, cy) <- GLFW.getCursorPos win
let winToWorldMtx = M.mkWinToWorldMatrix winDims (frustum winDims)
return $ V.setElem 2 0 $ M.winToWorld winToWorldMtx (floor cx, floor cy)
gridTranslation :: GLFW.Window -> IO V.Vect
gridTranslation win = do
M.Frustum {M.right = r, M.top = t} <- frustum <$> GLFW.getWindowSize win
let transX = (r - dGridWidth) / 2
transY = (t - dGridHeight) / 2
return (transX:.transY:.0)
frustum :: (Int, Int) -> M.Frustum
frustum (width, height) =
let dWidth = fromIntegral width :: Double
dHeight = fromIntegral height :: Double
maxSide = max dGridWidth dGridHeight + (2 * borderWidth)
(right, top) | dWidth < dHeight = (maxSide, maxSide * (dHeight / dWidth))
| otherwise = (maxSide * (dWidth / dHeight), maxSide)
in M.Frustum 0 right 0 top (-1) 1
|
dan-t/clothsim
|
Main.hs
|
bsd-3-clause
| 7,158 | 7 | 19 | 2,168 | 2,585 | 1,320 | 1,265 | -1 | -1 |
module Main
where
import Data.Monoid ()
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.HUnit
import Test.QuickCheck
import qualified TestDigram
import qualified TestEnnGramMap
import qualified TestCandSel
import qualified Properties
main :: IO ()
main = defaultMainWithOpts
[ testCase "unittests.Digram" testDigram
, testCase "unittests.EnnGramList" testMakeEnnGramList
, testCase "unittests.EnnGramMap" testMakeEnnGramMap
, testCase "unittests.CandSelMkCnd" testMakeCandidates
, testCase "unittests.CandSelDropSafeOverlap" testDropSafeOverlap
, testCase "unittests.CandSelOverlaps" testOverlaps
, testCase "unittests.CandSelGetNextCnd" testGetNextCandidates
, testCase "unittests.CandSelMakeThenGet"
$ assertRightTrue TestCandSel.testMakeThenGetCandidates
, testProperty "prop.compressDecompressId" propCompressDecompressId
, testProperty "prop.compressionSavesSpaceOrId" propCompressSavesSpaceOrId
, testProperty "prop.allCompressionsUsed" propAllCompressionsUsed
, testProperty "prop.overlapEquivalence" propOverlapEquivalence
, testProperty "prop.getNextCandidateEquivalence" propGetNextCandidateEquivalence
] mempty
assertRightTrue :: Show a => Either a Bool -> Assertion
assertRightTrue z@(Left _) = assertFailure $ "Expected Right True, got " ++ show z
assertRightTrue (Right z) = assertBool (show z ++ "is not True") z
testDigram :: Assertion
testDigram = assertRightTrue TestDigram.testDigramTable
testMakeEnnGramMap :: Assertion
testMakeEnnGramMap = assertRightTrue TestEnnGramMap.testMakeEnnGramMap
testMakeEnnGramList :: Assertion
testMakeEnnGramList = assertRightTrue TestEnnGramMap.testMakeEnnGramList
testMakeCandidates :: Assertion
testMakeCandidates = assertRightTrue TestCandSel.testMakeCandidates
testDropSafeOverlap :: Assertion
testDropSafeOverlap = assertRightTrue TestCandSel.testDropSafeOverlap
testOverlaps :: Assertion
testOverlaps = assertRightTrue TestCandSel.testOverlaps
testGetNextCandidates :: Assertion
testGetNextCandidates = assertRightTrue TestCandSel.testGetNextCandidates
propCompressDecompressId :: Property
propCompressDecompressId = property $ Properties.propertyCompressionIsReversible
propCompressSavesSpaceOrId :: Property
propCompressSavesSpaceOrId = property $ Properties.propertyCompressionSavesSpaceOrId
propAllCompressionsUsed :: Property
propAllCompressionsUsed = property $ Properties.propertyAllCompressionsUsed
propOverlapEquivalence :: Property
propOverlapEquivalence = property $ Properties.propertyOverlapEquivalence
propGetNextCandidateEquivalence :: Property
propGetNextCandidateEquivalence = property $ Properties.propertyGetNextCandidatesEquivalence
|
pcrama/message-compiler
|
test/Suite.hs
|
bsd-3-clause
| 2,810 | 0 | 9 | 347 | 451 | 243 | 208 | 55 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : RefacAsPatterns
-- Copyright : (c) Christopher Brown 2007
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module contains a transformation for HaRe.
-- Convert all patterns into AS patterns and
-- change all reference to the pattern on the RHS to references
-- to the AS name.
--
-----------------------------------------------------------------------------
module RefacAsPatterns where
import System.IO.Unsafe
import PrettyPrint
import RefacTypeSyn
import RefacLocUtils
import Data.Char
import GHC.Unicode
import AbstractIO
import Maybe
import List
import RefacUtils
data Patt = Match HsMatchP | MyAlt HsAltP | MyDo HsStmtP | MyListComp HsExpP
deriving (Show)
refacAsPatterns args
= do let
fileName = args!!0
name = args!!1
beginRow = read (args!!2)::Int
beginCol = read (args!!3)::Int
endRow = read (args!!4)::Int
endCol = read (args!!5)::Int
AbstractIO.putStrLn "refacAsPatterns"
unless (isVarId name)
$ error "The new name is invalid!\n"
-- Parse the input file.
modInfo@(inscps, exps, mod, tokList) <- parseSourceFile fileName
-- there are two modes to this refactoring:
-- either one selects a pattern, or, one selects an expression (referring to a pattern).
let exp = locToExp (beginRow, beginCol) (endRow, endCol) tokList mod
case exp of
Exp (HsId (HsVar (PNT (PN (UnQual "unknown") (G (PlainModule "unknown") "--" (N Nothing))) Value (N Nothing)) ))
-> do
let (pnt, pat, match) = findPattern tokList (beginRow, beginCol) (endRow, endCol) mod
((_,m), (newToks, newMod)) <- applyRefac (changePattern name pat match) (Just (inscps, exps, mod, tokList)) fileName
unless (newMod /= mod) $ AbstractIO.putStrLn "Pattern does not occur on the rhs!"
writeRefactoredFiles False [((fileName, m), (newToks, newMod))]
AbstractIO.putStrLn "Completed.\n"
_
-> do
-- all we need is the expression and the pattern to which it is imitating...
let pat = getPat exp mod
((_,m), (newToks, newMod)) <- applyRefac (changePatternSimple name pat exp) (Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName, m), (newToks, newMod))]
AbstractIO.putStrLn "Completed.\n"
getPat exp t
= fromMaybe (error "No Pattern is associated with the highlighted expression!")
(applyTU (once_tdTU (failTU `adhocTU` worker)) t)
where
worker (p :: HsPatP)
| rewritePats p == exp = Just p
| otherwise = Nothing
convertPat :: String -> HsPatP -> HsPatP
convertPat _ (Pat (HsPAsPat n p)) = error "The selected pattern is already an as-pattern!"
convertPat _ (Pat (HsPId _)) = error "Cannot perform to-as-patterns on a simple variable!"
convertPat _ (Pat (HsPLit _ _)) = error "Cannot perform to-as-patterns on a constant value!"
convertPat name (Pat (HsPParen p)) = convertPat name p
convertPat name p = (Pat (HsPAsPat (nameToPNT name) p))
changePatternSimple name pat exp (_, _, t)
= do
inscopeNames <- hsVisibleNames exp t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
-- let newPats = checkPats name pat [p]
let convertedPat = convertPat name pat
newExp <- checkExpr convertedPat exp
newT <- update exp newExp t
newT2 <- update pat convertedPat newT
return newT2
changePattern name pat (Match match) (_, _,t)
= do
newDecl <- lookInMatches t name pat [match]
newT <- update match (newDecl !! 0) t
return newT
changePattern name pat (MyAlt alt) (_, _, t)
= do
newAlt <- lookInAlt t name pat alt
newT <- update alt newAlt t
return newT
changePattern name pat (MyDo inDo) (_,_, t)
= do
newDo <- lookInDo t name pat inDo
newT <- update inDo newDo t
return newT
changePattern name pat (MyListComp inList) (_,_,t)
= do
newList <- lookInList t name pat inList
newT <- update inList newList t
return newT
-- sconvertPatterns :: (Term t, MonadPlus m,Monad m) => t -> String -> HsPatP -> HsDeclP -> m HsDeclP
convertPatterns t name pat dec@(Dec (HsPatBind a b (HsBody e) ds))
= do
newExp <- checkExpr (Pat (HsPAsPat (nameToPNT name) pat)) e
return (Dec (HsPatBind a b (HsBody newExp) ds))
convertPatterns t name pat (Dec (HsFunBind loc matches))
=
do
rest <- lookInMatches t name pat matches
return (Dec (HsFunBind loc rest ))
lookInMatches _ _ _ [] = return []
lookInMatches t name pat (match@(HsMatch s pnt (p:ps) (HsGuard g@((_,_,e):gs)) ds):ms)
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let newPats = checkPats name pat (p:ps)
let convertedPat = convertPat name pat
newGuard <- checkGuards convertedPat g
newDS <- mapM (convertPatterns t name pat) ds
rest <- lookInMatches t name pat ms
if newGuard == g && newDS == ds
then do
return (HsMatch s pnt (p:ps) (HsGuard g) ds : rest)
else do
return (HsMatch s pnt newPats (HsGuard newGuard) newDS : rest)
lookInMatches t name pat (match@(HsMatch s pnt (p:ps) (HsBody e) ds):ms)
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let newPats = checkPats name pat (p:ps)
let convertedPat = convertPat name pat
newExp <- checkExpr convertedPat e
newDS <- mapM (convertPatterns t name pat) ds
rest <- lookInMatches t name pat ms
if newExp == e && newDS == ds
then do
return (HsMatch s pnt (p:ps) (HsBody e) ds : rest)
else do
return (HsMatch s pnt newPats (HsBody newExp) newDS : rest)
lookInAlt t name pat (alt@(HsAlt s p (HsGuard g@((_,_,e):gs)) ds)::HsAltP)
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let newPats = checkPats name pat [p]
let convertedPat = convertPat name pat
newGuard <- checkGuards convertedPat g
newDS <- mapM (convertPatterns t name pat) ds
-- rest <- lookInMatches t name pat ms
if newGuard == g && newDS == ds
then do
return (HsAlt s p (HsGuard g) ds)
else do
return (HsAlt s (ghead "lookInAlt" newPats) (HsGuard newGuard) newDS)
lookInAlt t name pat (alt@(HsAlt s p (HsBody e) ds)::HsAltP)
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let newPats = checkPats name pat [p]
let convertedPat = convertPat name pat
newExp <- checkExpr convertedPat e
newDS <- mapM (convertPatterns t name pat) ds
-- rest <- lookInMatches t name pat ms
if newExp == e && newDS == ds
then do
return (HsAlt s p (HsBody e) ds)
else do
return (HsAlt s (ghead "lookInAlt" newPats) (HsBody newExp) newDS)
lookInDo t name pat (inDo@(HsGenerator s p e rest))
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let newPats = checkPats name pat [p]
let convertedPat = convertPat name pat
newExp <- checkExpr convertedPat e
newDS <- lookInExps t name pat rest
-- rest <- lookInMatches t name pat ms
if newExp == e && newDS == rest
then do
return (HsGenerator s p e rest)
else do
return (HsGenerator s (ghead "lookInDo" newPats) newExp newDS)
lookInList t name pat (inList@(Exp (HsListComp d)))
= do
res <- lookInDo t name pat d
return (Exp (HsListComp res))
lookInExps t name pat (HsLast e)
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let convertedPat = convertPat name pat
newExp <- checkExpr convertedPat e
return (HsLast newExp)
lookInExps t name pat (HsGenerator s p e rest)
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let newPats = checkPats name pat [p]
let convertedPat = convertPat name pat
newExp <- checkExpr convertedPat e
newDS <- lookInExps t name pat rest
-- rest <- lookInMatches t name pat ms
if newExp == e && newDS == rest
then do
return (HsGenerator s p e rest)
else do
return (HsGenerator s (ghead "lookInDo" newPats) newExp newDS)
lookInExps t name pat (HsQualifier e rest)
= do
inscopeNames <- hsVisibleNames e t
unless (not (name `elem` inscopeNames))
$ error ("the use of the name: " ++ name ++ " is already in scope!")
let convertedPat = convertPat name pat
newExp <- checkExpr convertedPat e
newDS <- lookInExps t name pat rest
return (HsQualifier newExp newDS)
lookInExps t name pat (HsLetStmt ds rest)
= do
let convertedPat = convertPat name pat
newRest <- lookInExps t name pat rest
newDS <- mapM (convertPatterns t name pat) ds
-- rest <- lookInMatches t name pat ms
if newDS == ds && rest == newRest
then do
return (HsLetStmt ds rest)
else do
return (HsLetStmt newDS newRest)
checkPats :: String -> HsPatP -> [ HsPatP ] -> [ HsPatP ]
checkPats _ _ [] = []
checkPats name pat (pat2@(Pat (HsPParen p)): ps)
| pat == pat2 = (Pat (HsPParen (Pat (HsPAsPat (nameToPNT name) p)))) : checkPats name pat ps
| otherwise = (Pat (HsPParen res)) : (checkPats name pat ps)
where
res = ghead "checkPats HsPParen res" $ checkPats name pat [p]
checkPats name pat (pat2@(Pat (HsPApp i ps)):pss)
| pat == pat2 = (Pat (HsPAsPat (nameToPNT name) pat2)) : checkPats name pat pss
| otherwise = (Pat (HsPApp i (checkPats name pat ps))) : checkPats name pat pss
checkPats name pat (pat2@(Pat (HsPTuple s ps)):pss)
| pat == pat2 = (Pat (HsPAsPat (nameToPNT name) pat2)) : checkPats name pat pss
| otherwise = (Pat (HsPTuple s (checkPats name pat ps))) : checkPats name pat pss
checkPats name pat (pat2@(Pat (HsPList s ps)) : pss)
| pat == pat2 = (Pat (HsPAsPat (nameToPNT name) pat2)) : checkPats name pat pss
| otherwise = (Pat (HsPList s (checkPats name pat ps))) : checkPats name pat pss
checkPats name pat ((Pat (HsPInfixApp p1 i p2)) : pss)
= (Pat (HsPInfixApp res1 i res2)) : checkPats name pat pss
where
res1 = ghead "checkPats HsPInFixApp res1" $ checkPats name pat [p1]
res2 = ghead "checkPats HsPInfixApp res2" $ checkPats name pat [p2]
checkPats name pat (p:ps)
| pat == p = (Pat (HsPAsPat (nameToPNT name) p)) : checkPats name pat ps
| otherwise = p : (checkPats name pat ps)
-- checkGuards [] g = return g
checkGuards _ [] = return []
checkGuards pat@(Pat (HsPAsPat s p)) ((s1, e1, e2):gs)
= do
-- rewrite the guard
newGuard <- rewriteExp s (rewritePats p) e1 pat
-- newGuard' <- checkExpr ps newGuard
-- rewrite the RHS of the guard
rhs <- rewriteExp s (rewritePats p) e2 pat
-- rhs' <- checkExpr ps rhs
rest <- checkGuards pat gs
return ((s1, newGuard, rhs):rest)
-- checkExpr :: [ HsPatP ] -> HsExpP -> m HsExpP
-- checkExpr [] e = return e
checkExpr pat@(Pat (HsPAsPat s p)) e
= do
newExp <- rewriteExp s (rewritePats p) e pat -- error $ show (rewritePats p)
-- newExp' <- checkExpr ps newExp
return newExp
checkExpr _ e = return e
-- rewrite exp checks to see whether the given expression occurs within
-- the second exp. If it does, the expression is replaced with the name of the 'as'
-- pattern.
-- rewriteExp :: String -> HsExpP -> HsExpP -> HsExpP
rewriteExp name e1 e2 t
= applyTP (full_tdTP (idTP `adhocTP` (inExp e1))) e2
where
-- inExp :: HsExpP -> HsExpP -> HsExpP
inExp (Exp (HsParen e1)::HsExpP) (e2::HsExpP)
= do
-- error $ show e2
allDef <- allDefined e2 t
if (rmLocs e1) == (rmLocs e2) && (and allDef)
then do
return (nameToExp (pNTtoName name))
else do
return e2
inExp (e1::HsExpP) (e2::HsExpP)
| (rmLocs e1) == (rmLocs e2) = return (nameToExp (pNTtoName name))
| otherwise = return e2
allDefined e t
= applyTU (full_tdTU (constTU [] `adhocTU` inPNT)) e
where
inPNT (p@(PNT pname ty _)::PNT)
= return [findPN pname t]
rewritePats :: HsPatP -> HsExpP
rewritePats (pat1@(Pat (HsPRec x y)))
= Exp (HsRecConstr loc0 x (map sortField y))
where
sortField :: HsFieldI a HsPatP -> HsFieldI a HsExpP
sortField (HsField i e) = (HsField i (rewritePats e))
rewritePats (pat1@(Pat (HsPLit x y)))
= Exp (HsLit x y)
rewritePats (pat1@(Pat (HsPAsPat i p1)))
= Exp (HsAsPat i (rewritePats p1))
rewritePats (pat1@(Pat (HsPIrrPat p1)))
= Exp (HsIrrPat (rewritePats p1))
rewritePats (pat1@(Pat (HsPWildCard)))
= nameToExp "undefined"
rewritePats (pat1@(Pat (HsPApp i p1)))
= createFuncFromPat i (map rewritePats p1)
rewritePats (pat1@(Pat (HsPList _ p1)))
= Exp (HsList (map rewritePats p1))
rewritePats (pat1@(Pat (HsPTuple _ p1)))
= Exp (HsTuple (map rewritePats p1))
rewritePats (pat1@(Pat (HsPInfixApp p1 x p2)))
= Exp (HsInfixApp (rewritePats p1)
(HsCon x)
(rewritePats p2))
rewritePats (pat@(Pat (HsPParen p1)))
= Exp (HsParen (rewritePats p1))
rewritePats (pat1@(Pat (HsPId (HsVar (PNT (PN (UnQual (i:is)) a) b c)))))
| isUpper i = (Exp (HsId (HsCon (PNT (PN (UnQual (i:is)) a) b c))))
| otherwise = (Exp (HsId (HsVar (PNT (PN (UnQual (i:is)) a) b c))))
rewritePats (pat1@(Pat (HsPId (HsCon (PNT (PN (UnQual (i:is)) a) b c)))))
= (Exp (HsId (HsCon (PNT (PN (UnQual (i:is)) a) b c))))
-- rewritePats p = error $ show p
-- strip removes whitespace and '\n' from a given string
strip :: String -> String
strip [] = []
strip (' ':xs) = strip xs
strip ('\n':xs) = strip xs
strip (x:xs) = x : strip xs
isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
--check whether the cursor points to the beginning of the datatype declaration
--taken from RefacADT.hs
checkCursor :: String -> Int -> Int -> HsModuleP -> Either String HsDeclP
checkCursor fileName row col mod
= case locToTypeDecl of
Nothing -> Left ("Invalid cursor position. Please place cursor at the beginning of the definition!")
Just decl -> Right decl
where
locToTypeDecl = find (definesPNT (locToPNT fileName (row, col) mod)) (hsModDecls mod)
definesPNT pnt d@(Dec (HsPatBind loc p e ds))
= findPNT pnt d
definesPNT pnt d@(Dec (HsFunBind loc ms)) = findPNT pnt d
definesPNT pnt _ = False
{-|
Takes the position of the highlighted code and returns
the function name, the list of arguments, the expression that has been
highlighted by the user, and any where\/let clauses associated with the
function.
-}
{-findPattern :: Term t => [PosToken] -- ^ The token stream for the
-- file to be
-- refactored.
-> (Int, Int) -- ^ The beginning position of the highlighting.
-> (Int, Int) -- ^ The end position of the highlighting.
-> t -- ^ The abstract syntax tree.
-> (SrcLoc, PNT, FunctionPats, HsExpP, WhereDecls) -- ^ A tuple of,
-- (the function name, the list of arguments,
-- the expression highlighted, any where\/let clauses
-- associated with the function).
-}
findPattern toks beginPos endPos t
= fromMaybe (defaultPNT, defaultPat, error "Invalid pattern selected!")
(applyTU (once_tdTU (failTU `adhocTU` inMatch
`adhocTU` inCase
`adhocTU` inDo
`adhocTU` inList )) t)
where
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 pnt pats rhs ds)::HsMatchP)
-- is the highlighted region selecting a pattern?
| inPat pats == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat pats)
Just (pnt, pat, Match match)
inCase (alt@(HsAlt s p rhs ds)::HsAltP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (defaultPNT, pat, MyAlt alt)
inDo (inDo@(HsGenerator s p e rest)::HsStmtP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (defaultPNT, pat, MyDo inDo)
inDo x = Nothing
inList (inlist@(Exp (HsListComp (HsGenerator s p e rest)))::HsExpP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (defaultPNT, pat, MyListComp inlist)
inList x = Nothing
inPat :: [HsPatP] -> Maybe HsPatP
inPat [] = Nothing
inPat (p:ps)
= if p1 /= defaultPat
then Just p1
else inPat ps
where
p1 = locToLocalPat beginPos endPos toks p
-- inPat _ = Nothing
|
forste/haReFork
|
refactorer/RefacAsPatterns.hs
|
bsd-3-clause
| 18,714 | 0 | 22 | 5,798 | 6,274 | 3,133 | 3,141 | -1 | -1 |
module WSC.Util where
import Control.Applicative
import Data.ByteString.UTF8 as UTF8
import Data.HashSet as HashSet
tupleA :: Applicative f => f a -> f b -> f (a, b)
tupleA = liftA2 (,)
set :: [String] -> HashSet ByteString
set = HashSet.fromList . fmap UTF8.fromString
|
DylanLukes/Winchester-STG-Compiler
|
WSC/Util.hs
|
bsd-3-clause
| 272 | 0 | 9 | 45 | 103 | 57 | 46 | 8 | 1 |
{-# LANGUAGE PatternGuards, DeriveFunctor, TypeSynonymInstances #-}
module Idris.Core.CaseTree(CaseDef(..), SC, SC'(..), CaseAlt, CaseAlt'(..),
Phase(..), CaseTree,
simpleCase, small, namesUsed, findCalls, findUsedArgs) where
import Idris.Core.TT
import Control.Monad.State
import Data.Maybe
import Data.List hiding (partition)
import Debug.Trace
data CaseDef = CaseDef [Name] !SC [Term]
deriving Show
data SC' t = Case Name [CaseAlt' t] -- ^ invariant: lowest tags first
| ProjCase t [CaseAlt' t] -- ^ special case for projections
| STerm !t
| UnmatchedCase String -- ^ error message
| ImpossibleCase -- ^ already checked to be impossible
deriving (Eq, Ord, Functor)
{-!
deriving instance Binary SC'
deriving instance NFData SC'
!-}
type SC = SC' Term
data CaseAlt' t = ConCase Name Int [Name] !(SC' t)
| FnCase Name [Name] !(SC' t) -- ^ reflection function
| ConstCase Const !(SC' t)
| SucCase Name !(SC' t)
| DefaultCase !(SC' t)
deriving (Show, Eq, Ord, Functor)
{-!
deriving instance Binary CaseAlt'
deriving instance NFData CaseAlt'
!-}
type CaseAlt = CaseAlt' Term
instance Show t => Show (SC' t) where
show sc = show' 1 sc
where
show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
showSep ("\n" ++ indent i) (map (showA i) alts)
show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
showSep ("\n" ++ indent i) (map (showA i) alts)
show' i (STerm tm) = show tm
show' i (UnmatchedCase str) = "error " ++ show str
show' i ImpossibleCase = "impossible"
indent i = concat $ take i (repeat " ")
showA i (ConCase n t args sc)
= show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
++ show' (i+1) sc
showA i (FnCase n args sc)
= "FN " ++ show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
++ show' (i+1) sc
showA i (ConstCase t sc)
= show t ++ " => " ++ show' (i+1) sc
showA i (SucCase n sc)
= show n ++ "+1 => " ++ show' (i+1) sc
showA i (DefaultCase sc)
= "_ => " ++ show' (i+1) sc
type CaseTree = SC
type Clause = ([Pat], (Term, Term))
type CS = ([Term], Int, [(Name, Type)])
instance TermSize SC where
termsize n (Case n' as) = termsize n as
termsize n (ProjCase n' as) = termsize n as
termsize n (STerm t) = termsize n t
termsize n _ = 1
instance TermSize CaseAlt where
termsize n (ConCase _ _ _ s) = termsize n s
termsize n (FnCase _ _ s) = termsize n s
termsize n (ConstCase _ s) = termsize n s
termsize n (SucCase _ s) = termsize n s
termsize n (DefaultCase s) = termsize n s
-- simple terms can be inlined trivially - good for primitives in particular
-- To avoid duplicating work, don't inline something which uses one
-- of its arguments in more than one place
small :: Name -> [Name] -> SC -> Bool
small n args t = let as = findAllUsedArgs t args in
length as == length (nub as) &&
termsize n t < 10
namesUsed :: SC -> [Name]
namesUsed sc = nub $ nu' [] sc where
nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
nu' ps (ProjCase t alts) = nub $ (nut ps t ++
(concatMap (nua ps) alts))
nu' ps (STerm t) = nub $ nut ps t
nu' ps _ = []
nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc) \\ args
nua ps (ConstCase _ sc) = nu' ps sc
nua ps (SucCase _ sc) = nu' ps sc
nua ps (DefaultCase sc) = nu' ps sc
nut ps (P _ n _) | n `elem` ps = []
| otherwise = [n]
nut ps (App f a) = nut ps f ++ nut ps a
nut ps (Proj t _) = nut ps t
nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
nut ps (Bind n b sc) = nut (n:ps) sc
nut ps _ = []
-- Return all called functions, and which arguments are used in each argument position
-- for the call, in order to help reduce compilation time, and trace all unused
-- arguments
findCalls :: SC -> [Name] -> [(Name, [[Name]])]
findCalls sc topargs = nub $ nu' topargs sc where
nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
nu' ps (STerm t) = nub $ nut ps t
nu' ps _ = []
nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc)
nua ps (ConstCase _ sc) = nu' ps sc
nua ps (SucCase _ sc) = nu' ps sc
nua ps (DefaultCase sc) = nu' ps sc
nut ps (P Ref n _) | n `elem` ps = []
| otherwise = [(n, [])] -- tmp
nut ps fn@(App f a)
| (P Ref n _, args) <- unApply fn
= if n `elem` ps then nut ps f ++ nut ps a
else [(n, map argNames args)] ++ concatMap (nut ps) args
| (P (TCon _ _) n _, _) <- unApply fn = []
| otherwise = nut ps f ++ nut ps a
nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
nut ps (Proj t _) = nut ps t
nut ps (Bind n b sc) = nut (n:ps) sc
nut ps _ = []
argNames tm = let ns = directUse tm in
filter (\x -> x `elem` ns) topargs
-- Find names which are used directly (i.e. not in a function call) in a term
directUse :: Eq n => TT n -> [n]
directUse (P _ n _) = [n]
directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
++ directUse t
directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
directUse fn@(App f a)
| (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
| (P (TCon _ _) n _, args) <- unApply fn = [] -- type constructors not used at runtime
| otherwise = nub $ directUse f ++ directUse a
directUse (Proj x i) = nub $ directUse x
directUse _ = []
-- Find all directly used arguments (i.e. used but not in function calls)
findUsedArgs :: SC -> [Name] -> [Name]
findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
nu' (Case n alts) = n : concatMap nua alts
nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
nu' (STerm t) = directUse t
nu' _ = []
nua (ConCase n i args sc) = nu' sc
nua (FnCase n args sc) = nu' sc
nua (ConstCase _ sc) = nu' sc
nua (SucCase _ sc) = nu' sc
nua (DefaultCase sc) = nu' sc
data Phase = CompileTime | RunTime
deriving (Show, Eq)
-- Generate a simple case tree
-- Work Right to Left
simpleCase :: Bool -> Bool -> Bool ->
Phase -> FC -> [Type] ->
[([Name], Term, Term)] ->
TC CaseDef
simpleCase tc cover reflect phase fc argtys cs
= sc' tc cover phase fc (filter (\(_, _, r) ->
case r of
Impossible -> False
_ -> True) cs)
where
sc' tc cover phase fc []
= return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
sc' tc cover phase fc cs
= let proj = phase == RunTime
vnames = fstT (head cs)
pats = map (\ (avs, l, r) ->
(avs, toPats reflect tc l, (l, r))) cs
chkPats = mapM chkAccessible pats in
case chkPats of
OK pats ->
let numargs = length (fst (head pats))
ns = take numargs args
(ns', ps') = order ns pats
(tree, st) = runState
(match ns' ps' (defaultCase cover))
([], numargs, [])
t = CaseDef ns (prune proj (depatt ns' tree)) (fstT st) in
if proj then return (stripLambdas t)
else return t
-- FIXME: This check is not quite right in some cases, and is breaking
-- perfectly valid code!
-- if checkSameTypes (lstT st) tree
-- then return t
-- else Error (At fc (Msg "Typecase is not allowed"))
Error err -> Error (At fc err)
where args = map (\i -> sMN i "e") [0..]
defaultCase True = STerm Erased
defaultCase False = UnmatchedCase "Error"
fstT (x, _, _) = x
lstT (_, _, x) = x
chkAccessible (avs, l, c)
| phase == RunTime || reflect = return (l, c)
| otherwise = do mapM_ (acc l) avs
return (l, c)
acc [] n = Error (Inaccessible n)
acc (PV x t : xs) n | x == n = OK ()
acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
acc (PSuc p : xs) n = acc (p : xs) n
acc (_ : xs) n = acc xs n
-- For each 'Case', make sure every choice is in the same type family,
-- as directed by the variable type (i.e. there is no implicit type casing
-- going on).
checkSameTypes :: [(Name, Type)] -> SC -> Bool
checkSameTypes tys (Case n alts)
= case lookup n tys of
Just t -> and (map (checkAlts t) alts)
_ -> and (map ((checkSameTypes tys).getSC) alts)
where
checkAlts t (ConCase n _ _ sc) = isType n t && checkSameTypes tys sc
checkAlts (Constant t) (ConstCase c sc) = isConstType c t && checkSameTypes tys sc
checkAlts _ (ConstCase c sc) = False
checkAlts _ _ = True
getSC (ConCase _ _ _ sc) = sc
getSC (FnCase _ _ sc) = sc
getSC (ConstCase _ sc) = sc
getSC (SucCase _ sc) = sc
getSC (DefaultCase sc) = sc
checkSameTypes _ _ = True
-- FIXME: All we're actually doing here is checking that we haven't arrived
-- at a specific constructor for a polymorphic argument. I *think* this
-- is sufficient, but if it turns out not to be, fix it!
isType n t | (P (TCon _ _) _ _, _) <- unApply t = True
isType n t | (P Ref _ _, _) <- unApply t = True
isType n t = False
isConstType (I _) (AType (ATInt ITNative)) = True
isConstType (BI _) (AType (ATInt ITBig)) = True
isConstType (Fl _) (AType ATFloat) = True
isConstType (Ch _) (AType (ATInt ITChar)) = True
isConstType (Str _) StrType = True
isConstType (B8 _) (AType (ATInt _)) = True
isConstType (B16 _) (AType (ATInt _)) = True
isConstType (B32 _) (AType (ATInt _)) = True
isConstType (B64 _) (AType (ATInt _)) = True
isConstType (B8V _) (AType (ATInt _)) = True
isConstType (B16V _) (AType (ATInt _)) = True
isConstType (B32V _) (AType (ATInt _)) = True
isConstType (B64V _) (AType (ATInt _)) = True
isConstType _ _ = False
data Pat = PCon Name Int [Pat]
| PConst Const
| PV Name Type
| PSuc Pat -- special case for n+1 on Integer
| PReflected Name [Pat]
| PAny
| PTyPat -- typecase, not allowed, inspect last
deriving Show
-- If there are repeated variables, take the *last* one (could be name shadowing
-- in a where clause, so take the most recent).
toPats :: Bool -> Bool -> Term -> [Pat]
toPats reflect tc f = reverse (toPat reflect tc (getArgs f)) where
getArgs (App f a) = a : getArgs f
getArgs _ = []
toPat :: Bool -> Bool -> [Term] -> [Pat]
toPat reflect tc tms = evalState (mapM (\x -> toPat' x []) tms) []
where
toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
return $ PCon n t args'
-- n + 1
toPat' (P _ (UN pabi) _)
[p, Constant (BI 1)] | pabi == txt "prim__addBigInt"
= do p' <- toPat' p []
return $ PSuc p'
-- Typecase
-- toPat' (P (TCon t a) n _) args | tc
-- = do args' <- mapM (\x -> toPat' x []) args
-- return $ PCon n t args'
-- toPat' (Constant (AType (ATInt ITNative))) []
-- | tc = return $ PCon (UN "Int") 1 []
-- toPat' (Constant (AType ATFloat)) [] | tc = return $ PCon (UN "Float") 2 []
-- toPat' (Constant (AType (ATInt ITChar))) [] | tc = return $ PCon (UN "Char") 3 []
-- toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
-- toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
-- toPat' (Constant (AType (ATInt ITBig))) []
-- | tc = return $ PCon (UN "Integer") 6 []
-- toPat' (Constant (AType (ATInt (ITFixed n)))) []
-- | tc = return $ PCon (UN (fixedN n)) (7 + fromEnum n) [] -- 7-10 inclusive
toPat' (P Bound n ty) [] = -- trace (show (n, ty)) $
do ns <- get
if n `elem` ns
then return PAny
else do put (n : ns)
return (PV n ty)
toPat' (App f a) args = toPat' f (a : args)
toPat' (Constant (AType _)) [] = return PTyPat
toPat' (Constant StrType) [] = return PTyPat
toPat' (Constant PtrType) [] = return PTyPat
toPat' (Constant VoidType) [] = return PTyPat
toPat' (Constant x) [] = return $ PConst x
toPat' (Bind n (Pi t) sc) [] | reflect && noOccurrence n sc
= do t' <- toPat' t []
sc' <- toPat' sc []
return $ PReflected (sUN "->") (t':sc':[])
toPat' (P _ n _) args | reflect
= do args' <- mapM (\x -> toPat' x []) args
return $ PReflected n args'
toPat' t _ = return PAny
fixedN IT8 = "Bits8"
fixedN IT16 = "Bits16"
fixedN IT32 = "Bits32"
fixedN IT64 = "Bits64"
data Partition = Cons [Clause]
| Vars [Clause]
deriving Show
isVarPat (PV _ _ : ps , _) = True
isVarPat (PAny : ps , _) = True
isVarPat (PTyPat : ps , _) = True
isVarPat _ = False
isConPat (PCon _ _ _ : ps, _) = True
isConPat (PReflected _ _ : ps, _) = True
isConPat (PSuc _ : ps, _) = True
isConPat (PConst _ : ps, _) = True
isConPat _ = False
partition :: [Clause] -> [Partition]
partition [] = []
partition ms@(m : _)
| isVarPat m = let (vars, rest) = span isVarPat ms in
Vars vars : partition rest
| isConPat m = let (cons, rest) = span isConPat ms in
Cons cons : partition rest
partition xs = error $ "Partition " ++ show xs
-- reorder the patterns so that the one with most distinct names
-- comes next. Take rightmost first, otherwise (i.e. pick value rather
-- than dependency)
order :: [Name] -> [Clause] -> ([Name], [Clause])
order [] cs = ([], cs)
order ns [] = (ns, [])
order ns cs = let patnames = transpose (map (zip ns) (map fst cs))
pats' = transpose (sortBy moreDistinct (reverse patnames)) in
(getNOrder pats', zipWith rebuild pats' cs)
where
getNOrder [] = error $ "Failed order on " ++ show (ns, cs)
getNOrder (c : _) = map fst c
rebuild patnames clause = (map snd patnames, snd clause)
moreDistinct xs ys = compare (numNames [] (map snd ys))
(numNames [] (map snd xs))
numNames xs (PCon n _ _ : ps)
| not (Left n `elem` xs) = numNames (Left n : xs) ps
numNames xs (PConst c : ps)
| not (Right c `elem` xs) = numNames (Right c : xs) ps
numNames xs (_ : ps) = numNames xs ps
numNames xs [] = length xs
match :: [Name] -> [Clause] -> SC -- error case
-> State CS SC
match [] (([], ret) : xs) err
= do (ts, v, ntys) <- get
put (ts ++ (map (fst.snd) xs), v, ntys)
case snd ret of
Impossible -> return ImpossibleCase
tm -> return $ STerm tm -- run out of arguments
match vs cs err = do let ps = partition cs
mixture vs ps err
mixture :: [Name] -> [Partition] -> SC -> State CS SC
mixture vs [] err = return err
mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
conRule vs ms fallthrough
mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
varRule vs ms fallthrough
data ConType = CName Name Int -- named constructor
| CFn Name -- reflected function name
| CSuc -- n+1
| CConst Const -- constant, not implemented yet
deriving (Show, Eq)
data Group = ConGroup ConType -- Constructor
[([Pat], Clause)] -- arguments and rest of alternative
deriving Show
conRule :: [Name] -> [Clause] -> SC -> State CS SC
conRule (v:vs) cs err = do groups <- groupCons cs
caseGroups (v:vs) groups err
caseGroups :: [Name] -> [Group] -> SC -> State CS SC
caseGroups (v:vs) gs err = do g <- altGroups gs
return $ Case v (sort g)
where
altGroups [] = return [DefaultCase err]
altGroups (ConGroup (CName n i) args : cs)
= do g <- altGroup n i args
rest <- altGroups cs
return (g : rest)
altGroups (ConGroup (CFn n) args : cs)
= do g <- altFnGroup n args
rest <- altGroups cs
return (g : rest)
altGroups (ConGroup CSuc args : cs)
= do g <- altSucGroup args
rest <- altGroups cs
return (g : rest)
altGroups (ConGroup (CConst c) args : cs)
= do g <- altConstGroup c args
rest <- altGroups cs
return (g : rest)
altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
matchCs <- match (newArgs ++ vs) nextCs err
return $ ConCase n i newArgs matchCs
altFnGroup n gs = do (newArgs, nextCs) <- argsToAlt gs
matchCs <- match (newArgs ++ vs) nextCs err
return $ FnCase n newArgs matchCs
altSucGroup gs = do ([newArg], nextCs) <- argsToAlt gs
matchCs <- match (newArg:vs) nextCs err
return $ SucCase newArg matchCs
altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
matchCs <- match vs nextCs err
return $ ConstCase n matchCs
argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
argsToAlt [] = return ([], [])
argsToAlt rs@((r, m) : rest)
= do newArgs <- getNewVars r
return (newArgs, addRs rs)
where
getNewVars [] = return []
getNewVars ((PV n t) : ns) = do v <- getVar "e"
(cs, i, ntys) <- get
put (cs, i, (v, t) : ntys)
nsv <- getNewVars ns
return (v : nsv)
getNewVars (PAny : ns) = do v <- getVar "i"
nsv <- getNewVars ns
return (v : nsv)
getNewVars (PTyPat : ns) = do v <- getVar "t"
nsv <- getNewVars ns
return (v : nsv)
getNewVars (_ : ns) = do v <- getVar "e"
nsv <- getNewVars ns
return (v : nsv)
addRs [] = []
addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
uniq i (UN n) = MN i n
uniq i n = n
getVar :: String -> State CS Name
getVar b = do (t, v, ntys) <- get; put (t, v+1, ntys); return (sMN v b)
groupCons :: [Clause] -> State CS [Group]
groupCons cs = gc [] cs
where
gc acc [] = return acc
gc acc ((p : ps, res) : cs) =
do acc' <- addGroup p ps res acc
gc acc' cs
addGroup p ps res acc = case p of
PCon con i args -> return $ addg (CName con i) args (ps, res) acc
PConst cval -> return $ addConG cval (ps, res) acc
PSuc n -> return $ addg CSuc [n] (ps, res) acc
PReflected fn args -> return $ addg (CFn fn) args (ps, res) acc
pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
addg c conargs res []
= [ConGroup c [(conargs, res)]]
addg c conargs res (g@(ConGroup c' cs):gs)
| c == c' = ConGroup c (cs ++ [(conargs, res)]) : gs
| otherwise = g : addg c conargs res gs
addConG con res [] = [ConGroup (CConst con) [([], res)]]
addConG con res (g@(ConGroup (CConst n) cs) : gs)
| con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
-- | otherwise = g : addConG con res gs
addConG con res (g : gs) = g : addConG con res gs
varRule :: [Name] -> [Clause] -> SC -> State CS SC
varRule (v : vs) alts err =
do alts' <- mapM (repVar v) alts
match vs alts' err
where
repVar v (PV p ty : ps , (lhs, res))
= do (cs, i, ntys) <- get
put (cs, i, (v, ty) : ntys)
return (ps, (lhs, subst p (P Bound v ty) res))
repVar v (PAny : ps , res) = return (ps, res)
repVar v (PTyPat : ps , res) = return (ps, res)
-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
depatt :: [Name] -> SC -> SC
depatt ns tm = dp [] tm
where
dp ms (STerm tm) = STerm (applyMaps ms tm)
dp ms (Case x alts) = Case x (map (dpa ms x) alts)
dp ms sc = sc
dpa ms x (ConCase n i args sc)
= ConCase n i args (dp ((x, (n, args)) : ms) sc)
dpa ms x (FnCase n args sc)
= FnCase n args (dp ((x, (n, args)) : ms) sc)
dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
dpa ms x (SucCase n sc) = SucCase n (dp ms sc)
dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
applyMaps ms f@(App _ _)
| (P nt cn pty, args) <- unApply f
= let args' = map (applyMaps ms) args in
applyMap ms nt cn pty args'
where
applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
applyMap ((x, (n, args)) : ms) nt cn pty args'
| and ((length args == length args') :
(n == cn) : zipWith same args args') = P Ref x Erased
| otherwise = applyMap ms nt cn pty args'
same n (P _ n' _) = n == n'
same _ _ = False
applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
applyMaps ms t = t
-- FIXME: Do this for SucCase too
prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
-> SC -> SC
prune proj (Case n alts)
= let alts' = filter notErased (map pruneAlt alts) in
case alts' of
[] -> ImpossibleCase
as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
else Case n as
as@[SucCase cn sc] -> if proj then mkProj n (-1) [cn] sc
else Case n as
as@[ConstCase _ sc] -> prune proj sc
-- Bit of a hack here! The default case will always be 0, make sure
-- it gets caught first.
[s@(SucCase _ _), DefaultCase dc]
-> Case n [ConstCase (BI 0) dc, s]
as -> Case n as
where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
pruneAlt (FnCase cn ns sc) = FnCase cn ns (prune proj sc)
pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
pruneAlt (SucCase n sc) = SucCase n (prune proj sc)
pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
notErased (DefaultCase (STerm Erased)) = False
notErased (DefaultCase ImpossibleCase) = False
notErased _ = True
mkProj n i [] sc = prune proj sc
mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
-- Change every 'n' in sc to 'n-1'
-- mkProjS n cn sc = prune proj (fmap projn sc) where
-- projn pn@(P _ n' _)
-- | cn == n' = App (App (P Ref (UN "prim__subBigInt") Erased)
-- (P Bound n Erased)) (Constant (BI 1))
-- projn t = t
projRep :: Name -> Name -> Int -> SC -> SC
projRep arg n i (Case x alts)
| x == arg = ProjCase (Proj (P Bound n Erased) i)
(map (projRepAlt arg n i) alts)
| otherwise = Case x (map (projRepAlt arg n i) alts)
projRep arg n i (ProjCase t alts)
= ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
projRep arg n i c = c -- unmatched
projRepAlt arg n i (ConCase cn t args rhs)
= ConCase cn t args (projRep arg n i rhs)
projRepAlt arg n i (FnCase cn args rhs)
= FnCase cn args (projRep arg n i rhs)
projRepAlt arg n i (ConstCase t rhs)
= ConstCase t (projRep arg n i rhs)
projRepAlt arg n i (SucCase sn rhs)
= SucCase sn (projRep arg n i rhs)
projRepAlt arg n i (DefaultCase rhs)
= DefaultCase (projRep arg n i rhs)
projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
prune _ t = t
stripLambdas :: CaseDef -> CaseDef
stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
= stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
stripLambdas x = x
|
ctford/Idris-Elba-dev
|
src/Idris/Core/CaseTree.hs
|
bsd-3-clause
| 25,707 | 0 | 20 | 9,460 | 10,105 | 5,099 | 5,006 | 494 | 22 |
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-|
Plot traces to html using lucid
Example code:
@
plotHtml :: Html ()
plotHtml = toHtml $ plotly "myDiv" [trace] & layout . title ?~ "my plot"
& layout . width ?~ 300
@
where `trace` is a value of type `Trace`
-}
module Graphics.Plotly.Lucid where
import Lucid
import Graphics.Plotly.Base
import Data.Monoid ((<>))
import Data.Text.Encoding (decodeUtf8)
import Data.ByteString.Lazy (toStrict)
import Data.Aeson
-- |`script` tag to go in the header to import the plotly.js javascript from the official CDN
plotlyCDN :: Monad m => HtmlT m ()
plotlyCDN = script_ [src_ "https://cdn.plot.ly/plotly-latest.min.js"] $ toHtml (""::String)
-- |Activate a plot defined by a `Plotly` value
plotlyJS :: Monad m => Plotly -> HtmlT m ()
plotlyJS (Plotly divNm trs lay) =
let trJSON = decodeUtf8 $ toStrict $ encode trs
layoutJSON = decodeUtf8 $ toStrict $ encode lay
in script_ ("Plotly.newPlot('"<>divNm<>"', "<>trJSON<>","<>layoutJSON<>", {displayModeBar: false});")
-- |Create a div for a Plotly value
plotlyDiv :: Monad m => Plotly -> HtmlT m ()
plotlyDiv (Plotly divNm _ _) =
div_ [id_ divNm]
""
instance ToHtml Plotly where
toHtml pl = plotlyDiv pl >> plotlyJS pl
toHtmlRaw = toHtml
|
filopodia/open
|
plotlyhs/src/Graphics/Plotly/Lucid.hs
|
mit
| 1,351 | 0 | 14 | 273 | 299 | 158 | 141 | 23 | 1 |
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell #-}
module Rewriting.Derive.Instance where
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data ( Reader system, ToDoc system
, Reader object, ToDoc object
)
=> Instance system object = Instance
{ system :: system
, from :: object
, to :: object
}
deriving ( Typeable
)
$(derives [makeReader, makeToDoc] [''Instance])
-- local variables:
-- mode: haskell
-- end:
|
florianpilz/autotool
|
src/Rewriting/Derive/Instance.hs
|
gpl-2.0
| 503 | 2 | 9 | 136 | 114 | 68 | 46 | 13 | 0 |
-- Copyright (c) 2013 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts, UndecidableInstances #-}
-- | This module contains extra instances of Hashable, which are not
-- found in the data-hash library, but are useful.
module Data.Hashable.ExtraInstances where
import Data.Array(Array)
import Data.Hashable
--import Data.Hashable.Extras
import Data.Map(Map)
import qualified Data.Array as Array
import qualified Data.Map as Map
--instance Hashable2 Map
--instance Hashable k => Hashable1 (Map k)
instance (Hashable k, Hashable v) => Hashable (Map k v) where
hashWithSalt =
Map.foldWithKey (\k' v' s' -> s' `hashWithSalt` k' `hashWithSalt` v')
instance (Hashable i, Hashable e, Array.Ix i) => Hashable (Array i e) where
hashWithSalt s = hashWithSalt s . Array.assocs
--instance (Hashable i, Array.Ix i) => Hashable1 (Array i)
|
emc2/compiler-misc
|
src/Data/Hashable/ExtraInstances.hs
|
bsd-3-clause
| 2,424 | 0 | 10 | 398 | 206 | 133 | 73 | 13 | 0 |
{-# LANGUAGE ForeignFunctionInterface, CPP, FlexibleContexts, RankNTypes #-}
{-| Bindings to the CUDD BDD library
This is a straightforward wrapper around the C library. See <http://vlsi.colorado.edu/~fabio/CUDD/> for documentation.
Exampe usage:
> import Cudd.Cudd
>
> main = do
> let manager = cuddInit
> v1 = ithVar manager 0
> v2 = ithVar manager 1
> conj = bAnd manager v1 v2
> implies = lEq manager conj v1
> print implies
-}
module Cudd.Cudd (
DDManager(..),
DDNode(..),
deref,
cuddInit,
cuddInitOrder,
readOne,
readLogicZero,
ithVar,
bAnd,
bOr,
bNand,
bNor,
bXor,
bXnor,
bNot,
dumpDot',
dumpDot,
cudd_cache_slots,
cudd_unique_slots,
eval,
printMinterm,
allSat,
oneSat,
onePrime,
supportIndex,
bExists,
bForall,
bIte,
permute,
swapVariables,
nodeReadIndex,
dagSize,
indicesToCube,
liCompaction,
minimize,
readSize,
xEqY,
xGtY,
interval,
disequality,
inequality,
ddNodeToInt,
pickOneMinterm,
readPerm,
readInvPerm,
readPerms,
readInvPerms,
readTree,
countLeaves,
countMinterm,
countPath,
countPathsToNonZero,
printDebug,
andAbstract,
xorExistAbstract,
transfer,
makePrime,
constrain,
restrict,
squeeze,
SatBit(..),
largestCube,
lEq,
printInfo
) where
import Foreign.Storable
import Foreign.Ptr
import Foreign.C.Types
import Foreign.C.String
import Foreign.ForeignPtr
import Foreign.ForeignPtr.Unsafe
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import System.IO.Unsafe
import Control.Monad
import Data.List
import Cudd.ForeignHelpers
import Cudd.MTR
import Cudd.C
import Cudd.Common
newtype DDManager = DDManager (Ptr CDDManager)
newtype DDNode = DDNode {unDDNode :: ForeignPtr CDDNode} deriving (Ord, Eq, Show)
deref = c_cuddIterDerefBddPtr
cuddInit :: DDManager
cuddInit = DDManager $ unsafePerformIO $ c_cuddInit 0 0 (fromIntegral cudd_unique_slots) (fromIntegral cudd_cache_slots) 0
cuddInitOrder :: [Int] -> DDManager
cuddInitOrder order = DDManager $ unsafePerformIO $ withArrayLen (map fromIntegral order) $ \size ptr -> do
when (sort order /= [0..size-1]) (error "cuddInitOrder: order does not contain each variable once")
m <- c_cuddInit (fromIntegral size) 0 (fromIntegral cudd_unique_slots) (fromIntegral cudd_cache_slots) 0
res <- c_cuddShuffleHeap m ptr
when (res /= 1) (error "shuffleHeap failed")
return m
cuddArg0 :: (Ptr CDDManager -> IO (Ptr CDDNode)) -> DDManager -> DDNode
cuddArg0 f (DDManager m) = DDNode $ unsafePerformIO $ do
node <- f m
newForeignPtrEnv deref m node
cuddArg1 :: (Ptr CDDManager -> Ptr CDDNode -> IO (Ptr CDDNode)) -> DDManager -> DDNode -> DDNode
cuddArg1 f (DDManager m) (DDNode x) = DDNode $ unsafePerformIO $
withForeignPtr x $ \xp -> do
node <- f m xp
newForeignPtrEnv deref m node
cuddArg2 :: (Ptr CDDManager -> Ptr CDDNode -> Ptr CDDNode -> IO (Ptr CDDNode)) -> DDManager -> DDNode -> DDNode -> DDNode
cuddArg2 f (DDManager m) (DDNode l) (DDNode r) = DDNode $ unsafePerformIO $
withForeignPtr l $ \lp ->
withForeignPtr r $ \rp -> do
node <- f m lp rp
newForeignPtrEnv deref m node
cuddArg3 :: (Ptr CDDManager -> Ptr CDDNode -> Ptr CDDNode -> Ptr CDDNode -> IO (Ptr CDDNode)) -> DDManager -> DDNode -> DDNode-> DDNode -> DDNode
cuddArg3 f (DDManager m) (DDNode l) (DDNode r) (DDNode x) = DDNode $ unsafePerformIO $
withForeignPtr l $ \lp ->
withForeignPtr r $ \rp ->
withForeignPtr x $ \xp -> do
node <- f m lp rp xp
newForeignPtrEnv deref m node
readOne :: DDManager -> DDNode
readOne = cuddArg0 c_cuddReadOneWithRef
readLogicZero :: DDManager -> DDNode
readLogicZero = cuddArg0 c_cuddReadLogicZeroWithRef
ithVar :: DDManager -> Int -> DDNode
ithVar m i = cuddArg0 (flip c_cuddBddIthVar (fromIntegral i)) m
bAnd :: DDManager -> DDNode -> DDNode -> DDNode
bAnd = cuddArg2 c_cuddBddAnd
bOr :: DDManager -> DDNode -> DDNode -> DDNode
bOr = cuddArg2 c_cuddBddOr
bNand :: DDManager -> DDNode -> DDNode -> DDNode
bNand = cuddArg2 c_cuddBddNand
bNor :: DDManager -> DDNode -> DDNode -> DDNode
bNor = cuddArg2 c_cuddBddNor
bXor :: DDManager -> DDNode -> DDNode -> DDNode
bXor = cuddArg2 c_cuddBddXor
bXnor :: DDManager -> DDNode -> DDNode -> DDNode
bXnor = cuddArg2 c_cuddBddXnor
bNot :: DDManager -> DDNode -> DDNode
bNot = cuddArg1 (const c_cuddNot)
dumpDot' :: DDManager -> [DDNode] -> Maybe [String] -> Maybe [String] -> Ptr CFile -> IO Int
dumpDot' (DDManager m) nodes iNames oNames file = liftM fromIntegral $
withForeignArrayPtrLen (map unDDNode nodes) $ \nn np ->
maybe ($ nullPtr) withStringArrayPtr iNames $ \iNamesP ->
maybe ($ nullPtr) withStringArrayPtr oNames $ \oNamesP -> do
c_cuddDumpDot m (fromIntegral nn) np iNamesP oNamesP file
foreign import ccall safe "fopen"
c_fopen :: CString -> CString -> IO (Ptr CFile)
foreign import ccall safe "fclose"
c_fclose :: (Ptr CFile) -> IO ()
dumpDot :: DDManager -> DDNode -> String -> IO Int
dumpDot m n fName =
withCAString fName $ \fNameP ->
withCAString "w" $ \md -> do
file <- c_fopen fNameP md
res <- dumpDot' m [n] Nothing Nothing file
c_fclose file
return res
eval :: DDManager -> DDNode -> [Int] -> Bool
eval (DDManager m) (DDNode n) a = unsafePerformIO $ do
res <- withArray (map fromIntegral a) $ \ap ->
withForeignPtr n $ \np ->
c_cuddEval m np ap
return $ (==0) $ c_cuddIsComplement res
printMinterm :: DDManager -> DDNode -> IO ()
printMinterm (DDManager m) (DDNode n) =
withForeignPtr n $ c_cuddPrintMinterm m
foreign import ccall safe "allSat"
c_allSat :: Ptr CDDManager -> Ptr CDDNode -> Ptr CInt -> Ptr CInt -> IO (Ptr (Ptr CInt))
foreign import ccall safe "oneSat"
c_oneSat :: Ptr CDDManager -> Ptr CDDNode -> Ptr CInt -> IO (Ptr CInt)
allSat :: DDManager -> DDNode -> [[SatBit]]
allSat (DDManager m) (DDNode n) = unsafePerformIO $
alloca $ \nvarsptr ->
alloca $ \ntermsptr ->
withForeignPtr n $ \np -> do
res <- c_allSat m np ntermsptr nvarsptr
nterms <- liftM fromIntegral $ peek ntermsptr
res <- peekArray nterms res
nvars <- liftM fromIntegral $ peek nvarsptr
res <- mapM (peekArray nvars) res
return $ map (map (toSatBit . fromIntegral)) res
oneSat :: DDManager -> DDNode -> Maybe [SatBit]
oneSat (DDManager m) (DDNode n) = unsafePerformIO $
alloca $ \nvarsptr ->
withForeignPtr n $ \np -> do
res <- c_oneSat m np nvarsptr
if res==nullPtr then return Nothing else do
nvars <- liftM fromIntegral $ peek nvarsptr
res <- peekArray nvars res
return $ Just $ map (toSatBit . fromIntegral) res
foreign import ccall safe "onePrime"
c_onePrime :: Ptr CDDManager -> Ptr CDDNode -> Ptr CDDNode -> Ptr CInt -> IO (Ptr CInt)
onePrime :: DDManager -> DDNode -> DDNode -> Maybe [Int]
onePrime (DDManager m) (DDNode l) (DDNode u) = unsafePerformIO $
alloca $ \nvarsptr ->
withForeignPtr l $ \lp ->
withForeignPtr u $ \up -> do
res <- c_onePrime m lp up nvarsptr
if res==nullPtr then return Nothing else do
nvars <- liftM fromIntegral $ peek nvarsptr
res <- peekArray nvars res
return $ Just $ map fromIntegral res
readSize :: DDManager -> Int
readSize (DDManager m) = fromIntegral $ unsafePerformIO $ c_cuddReadSize m
supportIndex :: DDManager -> DDNode -> [Bool]
supportIndex (DDManager m) (DDNode n) = unsafePerformIO $
withForeignPtr n $ \np -> do
res <- c_cuddSupportIndex m np
size <- c_cuddReadSize m
res <- peekArray (fromIntegral size) res
return $ map toBool res
bExists :: DDManager -> DDNode -> DDNode -> DDNode
bExists = cuddArg2 c_cuddBddExistAbstract
bForall :: DDManager -> DDNode -> DDNode -> DDNode
bForall = cuddArg2 c_cuddBddUnivAbstract
bIte :: DDManager -> DDNode -> DDNode -> DDNode -> DDNode
bIte = cuddArg3 c_cuddBddIte
swapVariables :: DDManager -> DDNode -> [DDNode] -> [DDNode] -> DDNode
swapVariables (DDManager m) (DDNode d) s1 s2 = DDNode $ unsafePerformIO $
withForeignPtr d $ \dp ->
withForeignArrayPtrLen (map unDDNode s1) $ \s1 s1ps ->
withForeignArrayPtrLen (map unDDNode s2) $ \s2 s2ps -> do
when (s1 /= s2) (error "cuddBddSwapVariables: variable lists have different sizes")
node <- c_cuddBddSwapVariables m dp s1ps s2ps (fromIntegral s1)
newForeignPtrEnv deref m node
permute :: DDManager -> DDNode -> [Int] -> DDNode
permute (DDManager m) (DDNode d) indexes = DDNode $ unsafePerformIO $
withForeignPtr d $ \dp ->
withArray (map fromIntegral indexes) $ \ip -> do
node <- c_cuddBddPermute m dp ip
newForeignPtrEnv deref m node
xGtY :: DDManager -> [DDNode] -> [DDNode] -> DDNode
xGtY (DDManager m) x y = DDNode $ unsafePerformIO $
withForeignArrayPtrLen (map unDDNode x) $ \xl xp ->
withForeignArrayPtrLen (map unDDNode y) $ \yl yp -> do
when (xl /= yl) (error "cuddXgty: variable lists have different sizes")
node <- c_cuddXgty m (fromIntegral xl) nullPtr xp yp
newForeignPtrEnv deref m node
xEqY :: DDManager -> [DDNode] -> [DDNode] -> DDNode
xEqY (DDManager m) x y = DDNode $ unsafePerformIO $
withForeignArrayPtrLen (map unDDNode x) $ \xl xp ->
withForeignArrayPtrLen (map unDDNode y) $ \yl yp -> do
when (xl /= yl) (error "cuddXeqy: variable lists have different sizes")
node <- c_cuddXeqy m (fromIntegral xl) xp yp
newForeignPtrEnv deref m node
inequality :: DDManager -> Int -> Int -> [DDNode] -> [DDNode] -> DDNode
inequality (DDManager m) n c x y = DDNode $ unsafePerformIO $
withForeignArrayPtr (map unDDNode x) $ \xp ->
withForeignArrayPtr (map unDDNode y) $ \yp -> do
node <- c_cuddInequality m (fromIntegral n) (fromIntegral c) xp yp
newForeignPtrEnv deref m node
disequality :: DDManager -> Int -> Int -> [DDNode] -> [DDNode] -> DDNode
disequality (DDManager m) n c x y = DDNode $ unsafePerformIO $
withForeignArrayPtr (map unDDNode x) $ \xp ->
withForeignArrayPtr (map unDDNode y) $ \yp -> do
node <- c_cuddDisequality m (fromIntegral n) (fromIntegral c) xp yp
newForeignPtrEnv deref m node
interval :: DDManager -> [DDNode] -> Int -> Int -> DDNode
interval (DDManager m) vararr lower upper = DDNode $ unsafePerformIO $
withForeignArrayPtrLen (map unDDNode vararr) $ \sz vp -> do
node <- c_cuddBddInterval m (fromIntegral sz) vp (fromIntegral lower) (fromIntegral upper)
newForeignPtrEnv deref m node
nodeReadIndex :: DDNode -> Int
nodeReadIndex (DDNode d) = fromIntegral $ unsafePerformIO $ withForeignPtr d c_cuddNodeReadIndex
dagSize :: DDNode -> Int
dagSize (DDNode d) = fromIntegral $ unsafePerformIO $ withForeignPtr d c_cuddDagSize
indicesToCube :: DDManager -> [Int] -> DDNode
indicesToCube (DDManager m) indices = DDNode $ unsafePerformIO $
withArrayLen (map fromIntegral indices) $ \size ip -> do
node <- c_cuddIndicesToCube m ip (fromIntegral size)
newForeignPtrEnv deref m node
liCompaction :: DDManager -> DDNode -> DDNode -> DDNode
liCompaction = cuddArg2 c_cuddBddLICompaction
minimize :: DDManager -> DDNode -> DDNode -> DDNode
minimize = cuddArg2 c_cuddBddMinimize
pickOneMinterm :: DDManager -> DDNode -> [DDNode] -> Maybe DDNode
pickOneMinterm (DDManager m) (DDNode d) vars = unsafePerformIO $
withForeignPtr d $ \dp ->
withForeignArrayPtrLen (map unDDNode vars) $ \vs vp -> do
node <- c_cuddBddPickOneMinterm m dp vp (fromIntegral vs)
if node == nullPtr then return Nothing else do
nd <- newForeignPtrEnv deref m node
return $ Just $ DDNode nd
printInfo :: DDManager -> Ptr CFile -> IO Int
printInfo (DDManager m) cf = liftM fromIntegral $ c_cuddPrintInfo m cf
readPerm :: DDManager -> Int -> Int
readPerm (DDManager m) i = fromIntegral $ unsafePerformIO $ c_cuddReadPerm m (fromIntegral i)
readInvPerm :: DDManager -> Int -> Int
readInvPerm (DDManager m) i = fromIntegral $ unsafePerformIO $ c_cuddReadInvPerm m (fromIntegral i)
readPerms :: DDManager -> [Int]
readPerms m = map (readPerm m) [0..(readSize m - 1)]
readInvPerms :: DDManager -> [Int]
readInvPerms m = map (readInvPerm m) [0..(readSize m -1)]
readTree :: DDManager -> IO (Ptr CMtrNode)
readTree (DDManager m) = c_cuddReadTree m
countLeaves :: DDNode -> Int
countLeaves (DDNode d) = fromIntegral $ unsafePerformIO $
withForeignPtr d $ \dp ->
c_cuddCountLeaves dp
countMinterm :: DDManager -> DDNode -> Int -> Double
countMinterm (DDManager m) (DDNode d) n = realToFrac $ unsafePerformIO $
withForeignPtr d $ \dp ->
c_cuddCountMinterm m dp (fromIntegral n)
countPathsToNonZero :: DDNode -> Double
countPathsToNonZero (DDNode d) = realToFrac $ unsafePerformIO $
withForeignPtr d $ \dp ->
c_cuddCountPathsToNonZero dp
countPath :: DDNode -> Double
countPath (DDNode d) = realToFrac $ unsafePerformIO $
withForeignPtr d $ \dp ->
c_cuddCountPath dp
printDebug :: DDManager -> DDNode -> Int -> Int -> IO Int
printDebug (DDManager m) (DDNode d) n pr = liftM fromIntegral $
withForeignPtr d $ \dp ->
c_cuddPrintDebug m dp (fromIntegral n) (fromIntegral pr)
andAbstract :: DDManager -> DDNode -> DDNode -> DDNode -> DDNode
andAbstract = cuddArg3 c_cuddBddAndAbstract
xorExistAbstract :: DDManager -> DDNode -> DDNode -> DDNode -> DDNode
xorExistAbstract = cuddArg3 c_cuddBddXorExistAbstract
transfer :: DDManager -> DDManager -> DDNode -> DDNode
transfer (DDManager m1) (DDManager m2) (DDNode x) = DDNode $ unsafePerformIO $
withForeignPtr x $ \xp -> do
node <- c_cuddBddTransfer m1 m2 xp
newForeignPtrEnv deref m2 node
makePrime :: DDManager -> DDNode -> DDNode -> DDNode
makePrime = cuddArg2 c_cuddBddMakePrime
constrain :: DDManager -> DDNode -> DDNode -> DDNode
constrain = cuddArg2 c_cuddBddConstrain
restrict :: DDManager -> DDNode -> DDNode -> DDNode
restrict = cuddArg2 c_cuddBddRestrict
squeeze :: DDManager -> DDNode -> DDNode -> DDNode
squeeze = cuddArg2 c_cuddBddSqueeze
largestCube :: DDManager -> DDNode -> (Int, DDNode)
largestCube (DDManager m) (DDNode n) = unsafePerformIO $
alloca $ \lp ->
withForeignPtr n $ \np -> do
node <- c_cuddLargestCube m np lp
res <- newForeignPtrEnv deref m node
l <- peek lp
return (fromIntegral l, DDNode res)
lEq :: DDManager -> DDNode -> DDNode -> Bool
lEq (DDManager m) (DDNode l) (DDNode r) = (==1) $ unsafePerformIO $
withForeignPtr l $ \lp ->
withForeignPtr r $ \rp ->
c_cuddBddLeq m lp rp
ddNodeToInt :: Integral i => DDNode -> i
ddNodeToInt = fromIntegral . ptrToIntPtr . unsafeForeignPtrToPtr . unDDNode
|
maweki/haskell_cudd
|
Cudd/Cudd.hs
|
bsd-3-clause
| 14,778 | 18 | 18 | 3,166 | 5,084 | 2,558 | 2,526 | 344 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveDataTypeable #-}
module VSim.VIR.Monad (
ParserState(..)
, Parser(..)
, ParserError(..)
, runParser
, newState
, formatErr
, lexer
, parseError
, getLoc
) where
import Data.ByteString.Char8 as B
import Data.List
import Data.Ord
import Data.IORef
import Data.IORefEx
import Data.Maybe
import Data.Typeable
import Data.Time.Clock
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
import Control.Monad.Reader
import Control.Monad.Error
import Control.Monad.State
import Control.Exception as E
import System.FilePath
import System.IO.Error
import System.IO
import Text.Printf
import VSim.Data.Loc
import VSim.Data.Line
import VSim.VIR.Types
import VSim.VIR.Lexer as L
data ParserState = ParserState {
psFileName :: FilePath
, psInput :: IORef L.AlexInput
, psTokenStart :: IORef Int
, psPrevTokenEnd :: IORef Int
, psLocationStack :: IORef [Line]
}
newtype Parser a = Parser { unParser :: ReaderT ParserState IO a }
deriving (
Functor,
MonadReader ParserState,
MonadIO,
MonadFix,
Monad )
runParser :: ParserState -> Parser a -> IO a
runParser ps p = runReaderT (unParser p) ps
data ParserError = ParserError String
deriving (Show, Typeable)
instance E.Exception ParserError
instance MonadError ParserError Parser where
throwError e = Parser $ E.throw e
catchError p f =
Parser $ ReaderT $ \ps -> do
e <- tryS $ runReaderT (unParser p) ps
either (\e -> runReaderT (unParser $ f $ ParserError e) ps)
return e
tryS :: IO a -> IO (Either String a)
tryS act =
E.handle (\(e :: E.SomeException) -> retE $ show e) $
E.handle (\(ParserError e) -> return $ Left e) $
E.handle (\(e) -> retE $ ioeGetErrorString e) $
fmap Right act
where retE = return . Left . formatErr unknownLoc
getLoc :: Parser Loc
getLoc = do
(l, ec) <- fmap L.irScanLineColumn (readRef psInput)
sc <- readRef psTokenStart
ls <- readRef psLocationStack
fn <- asks psFileName
let r = Loc (case ls of [] -> Nothing; (x:_) -> x `seq` Just x)
l sc ec fn
r `seq` return r
lexer :: (L.Token -> Parser b) -> Parser b
lexer f = do
writeRef psPrevTokenEnd =<< fmap (snd . L.irScanLineColumn) (readRef psInput)
(startColumn, tok) <- L.irScanM (readRef psInput) (writeRef psInput)
writeRef psTokenStart startColumn
f tok
newState :: String -> B.ByteString -> IO ParserState
newState fn inp = do
let psFileName = fn
psInput <- newIORef (L.newIrScanInput inp)
psTokenStart <- newIORef 0
psPrevTokenEnd <- newIORef 0
psLocationStack <- newIORef []
return $ ParserState {..}
parseError :: (Show t) => t -> Parser a
parseError token = do
loc <- getLoc
fail $ formatErr loc $ "Parse error on token " ++ (show token)
formatErr :: Loc -> String -> String
formatErr (Loc sl l sc ec fn) err =
printf "File %s, line %s, characters %s-%s:%s %s\n"
(show fn) (show l) (show sc) (show $ ec-1) (unl sl) err
where
unl (Just l) = showLine l
unl Nothing = "_:0:0:"
|
ierton/vsim
|
src/VSim/VIR/Monad.hs
|
bsd-3-clause
| 3,322 | 0 | 16 | 802 | 1,129 | 591 | 538 | 103 | 2 |
{-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types, UnboxedTuples #-}
{-# OPTIONS_GHC -fno-full-laziness -funbox-strict-fields #-}
-- | Zero based arrays.
--
-- Note that no bounds checking are performed.
module Data.HashMap.Array
( Array
, MArray
-- * Creation
, new
, new_
, singleton
, singletonM
, pair
-- * Basic interface
, length
, lengthM
, read
, write
, index
, indexM
, update
, updateWith'
, unsafeUpdateM
, insert
, insertM
, delete
, unsafeFreeze
, unsafeThaw
, run
, run2
, copy
, copyM
-- * Folds
, foldl'
, foldr
, thaw
, map
, map'
, traverse
, filter
, toList
) where
import qualified Data.Traversable as Traversable
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative (Applicative)
#endif
import Control.DeepSeq
-- GHC 7.7 exports toList/fromList from GHC.Exts
-- In order to avoid warnings on previous GHC versions, we provide
-- an explicit import list instead of only hiding the offending symbols
import GHC.Exts (Array#, Int(..), newArray#, readArray#, writeArray#,
indexArray#, unsafeFreezeArray#, unsafeThawArray#,
MutableArray#)
import GHC.ST (ST(..))
#if __GLASGOW_HASKELL__ >= 709
import Prelude hiding (filter, foldr, length, map, read, traverse)
#else
import Prelude hiding (filter, foldr, length, map, read)
#endif
#if __GLASGOW_HASKELL__ >= 702
import GHC.Exts (sizeofArray#, copyArray#, thawArray#, sizeofMutableArray#,
copyMutableArray#)
#endif
#if defined(ASSERTS)
import qualified Prelude
#endif
import Data.HashMap.Unsafe (runST)
------------------------------------------------------------------------
#if defined(ASSERTS)
-- This fugly hack is brought by GHC's apparent reluctance to deal
-- with MagicHash and UnboxedTuples when inferring types. Eek!
# define CHECK_BOUNDS(_func_,_len_,_k_) \
if (_k_) < 0 || (_k_) >= (_len_) then error ("Data.HashMap.Array." ++ (_func_) ++ ": bounds error, offset " ++ show (_k_) ++ ", length " ++ show (_len_)) else
# define CHECK_OP(_func_,_op_,_lhs_,_rhs_) \
if not ((_lhs_) _op_ (_rhs_)) then error ("Data.HashMap.Array." ++ (_func_) ++ ": Check failed: _lhs_ _op_ _rhs_ (" ++ show (_lhs_) ++ " vs. " ++ show (_rhs_) ++ ")") else
# define CHECK_GT(_func_,_lhs_,_rhs_) CHECK_OP(_func_,>,_lhs_,_rhs_)
# define CHECK_LE(_func_,_lhs_,_rhs_) CHECK_OP(_func_,<=,_lhs_,_rhs_)
# define CHECK_EQ(_func_,_lhs_,_rhs_) CHECK_OP(_func_,==,_lhs_,_rhs_)
#else
# define CHECK_BOUNDS(_func_,_len_,_k_)
# define CHECK_OP(_func_,_op_,_lhs_,_rhs_)
# define CHECK_GT(_func_,_lhs_,_rhs_)
# define CHECK_LE(_func_,_lhs_,_rhs_)
# define CHECK_EQ(_func_,_lhs_,_rhs_)
#endif
data Array a = Array {
unArray :: !(Array# a)
#if __GLASGOW_HASKELL__ < 702
, length :: !Int
#endif
}
instance Show a => Show (Array a) where
show = show . toList
#if __GLASGOW_HASKELL__ >= 702
length :: Array a -> Int
length ary = I# (sizeofArray# (unArray ary))
{-# INLINE length #-}
#endif
-- | Smart constructor
array :: Array# a -> Int -> Array a
#if __GLASGOW_HASKELL__ >= 702
array ary _n = Array ary
#else
array = Array
#endif
{-# INLINE array #-}
data MArray s a = MArray {
unMArray :: !(MutableArray# s a)
#if __GLASGOW_HASKELL__ < 702
, lengthM :: !Int
#endif
}
#if __GLASGOW_HASKELL__ >= 702
lengthM :: MArray s a -> Int
lengthM mary = I# (sizeofMutableArray# (unMArray mary))
{-# INLINE lengthM #-}
#endif
-- | Smart constructor
marray :: MutableArray# s a -> Int -> MArray s a
#if __GLASGOW_HASKELL__ >= 702
marray mary _n = MArray mary
#else
marray = MArray
#endif
{-# INLINE marray #-}
------------------------------------------------------------------------
instance NFData a => NFData (Array a) where
rnf = rnfArray
rnfArray :: NFData a => Array a -> ()
rnfArray ary0 = go ary0 n0 0
where
n0 = length ary0
go !ary !n !i
| i >= n = ()
| otherwise = rnf (index ary i) `seq` go ary n (i+1)
{-# INLINE rnfArray #-}
-- | Create a new mutable array of specified size, in the specified
-- state thread, with each element containing the specified initial
-- value.
new :: Int -> a -> ST s (MArray s a)
new n@(I# n#) b =
CHECK_GT("new",n,(0 :: Int))
ST $ \s ->
case newArray# n# b s of
(# s', ary #) -> (# s', marray ary n #)
{-# INLINE new #-}
new_ :: Int -> ST s (MArray s a)
new_ n = new n undefinedElem
singleton :: a -> Array a
singleton x = runST (singletonM x)
{-# INLINE singleton #-}
singletonM :: a -> ST s (Array a)
singletonM x = new 1 x >>= unsafeFreeze
{-# INLINE singletonM #-}
pair :: a -> a -> Array a
pair x y = run $ do
ary <- new 2 x
write ary 1 y
return ary
{-# INLINE pair #-}
read :: MArray s a -> Int -> ST s a
read ary _i@(I# i#) = ST $ \ s ->
CHECK_BOUNDS("read", lengthM ary, _i)
readArray# (unMArray ary) i# s
{-# INLINE read #-}
write :: MArray s a -> Int -> a -> ST s ()
write ary _i@(I# i#) b = ST $ \ s ->
CHECK_BOUNDS("write", lengthM ary, _i)
case writeArray# (unMArray ary) i# b s of
s' -> (# s' , () #)
{-# INLINE write #-}
index :: Array a -> Int -> a
index ary _i@(I# i#) =
CHECK_BOUNDS("index", length ary, _i)
case indexArray# (unArray ary) i# of (# b #) -> b
{-# INLINE index #-}
indexM :: Array a -> Int -> ST s a
indexM ary _i@(I# i#) =
CHECK_BOUNDS("indexM", length ary, _i)
case indexArray# (unArray ary) i# of (# b #) -> return b
{-# INLINE indexM #-}
unsafeFreeze :: MArray s a -> ST s (Array a)
unsafeFreeze mary
= ST $ \s -> case unsafeFreezeArray# (unMArray mary) s of
(# s', ary #) -> (# s', array ary (lengthM mary) #)
{-# INLINE unsafeFreeze #-}
unsafeThaw :: Array a -> ST s (MArray s a)
unsafeThaw ary
= ST $ \s -> case unsafeThawArray# (unArray ary) s of
(# s', mary #) -> (# s', marray mary (length ary) #)
{-# INLINE unsafeThaw #-}
run :: (forall s . ST s (MArray s e)) -> Array e
run act = runST $ act >>= unsafeFreeze
{-# INLINE run #-}
run2 :: (forall s. ST s (MArray s e, a)) -> (Array e, a)
run2 k = runST (do
(marr,b) <- k
arr <- unsafeFreeze marr
return (arr,b))
-- | Unsafely copy the elements of an array. Array bounds are not checked.
copy :: Array e -> Int -> MArray s e -> Int -> Int -> ST s ()
#if __GLASGOW_HASKELL__ >= 702
copy !src !_sidx@(I# sidx#) !dst !_didx@(I# didx#) _n@(I# n#) =
CHECK_LE("copy", _sidx + _n, length src)
CHECK_LE("copy", _didx + _n, lengthM dst)
ST $ \ s# ->
case copyArray# (unArray src) sidx# (unMArray dst) didx# n# s# of
s2 -> (# s2, () #)
#else
copy !src !sidx !dst !didx n =
CHECK_LE("copy", sidx + n, length src)
CHECK_LE("copy", didx + n, lengthM dst)
copy_loop sidx didx 0
where
copy_loop !i !j !c
| c >= n = return ()
| otherwise = do b <- indexM src i
write dst j b
copy_loop (i+1) (j+1) (c+1)
#endif
-- | Unsafely copy the elements of an array. Array bounds are not checked.
copyM :: MArray s e -> Int -> MArray s e -> Int -> Int -> ST s ()
#if __GLASGOW_HASKELL__ >= 702
copyM !src !_sidx@(I# sidx#) !dst !_didx@(I# didx#) _n@(I# n#) =
CHECK_BOUNDS("copyM: src", lengthM src, _sidx + _n - 1)
CHECK_BOUNDS("copyM: dst", lengthM dst, _didx + _n - 1)
ST $ \ s# ->
case copyMutableArray# (unMArray src) sidx# (unMArray dst) didx# n# s# of
s2 -> (# s2, () #)
#else
copyM !src !sidx !dst !didx n =
CHECK_BOUNDS("copyM: src", lengthM src, sidx + n - 1)
CHECK_BOUNDS("copyM: dst", lengthM dst, didx + n - 1)
copy_loop sidx didx 0
where
copy_loop !i !j !c
| c >= n = return ()
| otherwise = do b <- read src i
write dst j b
copy_loop (i+1) (j+1) (c+1)
#endif
-- | /O(n)/ Insert an element at the given position in this array,
-- increasing its size by one.
insert :: Array e -> Int -> e -> Array e
insert ary idx b = runST (insertM ary idx b)
{-# INLINE insert #-}
-- | /O(n)/ Insert an element at the given position in this array,
-- increasing its size by one.
insertM :: Array e -> Int -> e -> ST s (Array e)
insertM ary idx b =
CHECK_BOUNDS("insertM", count + 1, idx)
do mary <- new_ (count+1)
copy ary 0 mary 0 idx
write mary idx b
copy ary idx mary (idx+1) (count-idx)
unsafeFreeze mary
where !count = length ary
{-# INLINE insertM #-}
-- | /O(n)/ Update the element at the given position in this array.
update :: Array e -> Int -> e -> Array e
update ary idx b = runST (updateM ary idx b)
{-# INLINE update #-}
-- | /O(n)/ Update the element at the given position in this array.
updateM :: Array e -> Int -> e -> ST s (Array e)
updateM ary idx b =
CHECK_BOUNDS("updateM", count, idx)
do mary <- thaw ary 0 count
write mary idx b
unsafeFreeze mary
where !count = length ary
{-# INLINE updateM #-}
-- | /O(n)/ Update the element at the given positio in this array, by
-- applying a function to it. Evaluates the element to WHNF before
-- inserting it into the array.
updateWith' :: Array e -> Int -> (e -> e) -> Array e
updateWith' ary idx f = update ary idx $! f (index ary idx)
{-# INLINE updateWith' #-}
-- | /O(1)/ Update the element at the given position in this array,
-- without copying.
unsafeUpdateM :: Array e -> Int -> e -> ST s ()
unsafeUpdateM ary idx b =
CHECK_BOUNDS("unsafeUpdateM", length ary, idx)
do mary <- unsafeThaw ary
write mary idx b
_ <- unsafeFreeze mary
return ()
{-# INLINE unsafeUpdateM #-}
foldl' :: (b -> a -> b) -> b -> Array a -> b
foldl' f = \ z0 ary0 -> go ary0 (length ary0) 0 z0
where
go ary n i !z
| i >= n = z
| otherwise = go ary n (i+1) (f z (index ary i))
{-# INLINE foldl' #-}
foldr :: (a -> b -> b) -> b -> Array a -> b
foldr f = \ z0 ary0 -> go ary0 (length ary0) 0 z0
where
go ary n i z
| i >= n = z
| otherwise = f (index ary i) (go ary n (i+1) z)
{-# INLINE foldr #-}
undefinedElem :: a
undefinedElem = error "Data.HashMap.Array: Undefined element"
{-# NOINLINE undefinedElem #-}
thaw :: Array e -> Int -> Int -> ST s (MArray s e)
#if __GLASGOW_HASKELL__ >= 702
thaw !ary !_o@(I# o#) !n@(I# n#) =
CHECK_LE("thaw", _o + n, length ary)
ST $ \ s -> case thawArray# (unArray ary) o# n# s of
(# s2, mary# #) -> (# s2, marray mary# n #)
#else
thaw !ary !o !n =
CHECK_LE("thaw", o + n, length ary)
do mary <- new_ n
copy ary o mary 0 n
return mary
#endif
{-# INLINE thaw #-}
-- | /O(n)/ Delete an element at the given position in this array,
-- decreasing its size by one.
delete :: Array e -> Int -> Array e
delete ary idx = runST (deleteM ary idx)
{-# INLINE delete #-}
-- | /O(n)/ Delete an element at the given position in this array,
-- decreasing its size by one.
deleteM :: Array e -> Int -> ST s (Array e)
deleteM ary idx = do
CHECK_BOUNDS("deleteM", count, idx)
do mary <- new_ (count-1)
copy ary 0 mary 0 idx
copy ary (idx+1) mary idx (count-(idx+1))
unsafeFreeze mary
where !count = length ary
{-# INLINE deleteM #-}
map :: (a -> b) -> Array a -> Array b
map f = \ ary ->
let !n = length ary
in run $ do
mary <- new_ n
go ary mary 0 n
where
go ary mary i n
| i >= n = return mary
| otherwise = do
write mary i $ f (index ary i)
go ary mary (i+1) n
{-# INLINE map #-}
-- | Strict version of 'map'.
map' :: (a -> b) -> Array a -> Array b
map' f = \ ary ->
let !n = length ary
in run $ do
mary <- new_ n
go ary mary 0 n
where
go ary mary i n
| i >= n = return mary
| otherwise = do
write mary i $! f (index ary i)
go ary mary (i+1) n
{-# INLINE map' #-}
fromList :: Int -> [a] -> Array a
fromList n xs0 =
CHECK_EQ("fromList", n, Prelude.length xs0)
run $ do
mary <- new_ n
go xs0 mary 0
where
go [] !mary !_ = return mary
go (x:xs) mary i = do write mary i x
go xs mary (i+1)
toList :: Array a -> [a]
toList = foldr (:) []
traverse :: Applicative f => (a -> f b) -> Array a -> f (Array b)
traverse f = \ ary -> fromList (length ary) `fmap`
Traversable.traverse f (toList ary)
{-# INLINE traverse #-}
filter :: (a -> Bool) -> Array a -> Array a
filter p = \ ary ->
let !n = length ary
in run $ do
mary <- new_ n
go ary mary 0 0 n
where
go ary mary i j n
| i >= n = if i == j
then return mary
else do mary2 <- new_ j
copyM mary 0 mary2 0 j
return mary2
| p el = write mary j el >> go ary mary (i+1) (j+1) n
| otherwise = go ary mary (i+1) j n
where el = index ary i
{-# INLINE filter #-}
|
bgamari/unordered-containers
|
Data/HashMap/Array.hs
|
bsd-3-clause
| 13,153 | 0 | 14 | 3,718 | 3,912 | 2,005 | 1,907 | -1 | -1 |
module Dotnet.System.Xml.XmlAttributeTy where
import Dotnet
import Dotnet.System.Xml.XmlNodeTy
data XmlAttribute_ a
type XmlAttribute a = Dotnet.System.Xml.XmlNodeTy.XmlNode (XmlAttribute_ a)
|
alekar/hugs
|
dotnet/lib/Dotnet/System/Xml/XmlAttributeTy.hs
|
bsd-3-clause
| 195 | 0 | 7 | 20 | 43 | 29 | 14 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Type.Equality
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : not portable
--
-- Definition of propositional equality @(:~:)@. Pattern-matching on a variable
-- of type @(a :~: b)@ produces a proof that @a ~ b@.
--
-- @since 4.7.0.0
-----------------------------------------------------------------------------
module Data.Type.Equality (
-- * The equality types
(:~:)(..), type (~~),
-- * Working with equality
sym, trans, castWith, gcastWith, apply, inner, outer,
-- * Inferring equality from other types
TestEquality(..),
-- * Boolean type-level equality
type (==)
) where
import Data.Maybe
import GHC.Enum
import GHC.Show
import GHC.Read
import GHC.Base
import Data.Type.Bool
-- | Lifted, homogeneous equality. By lifted, we mean that it can be
-- bogus (deferred type error). By homogeneous, the two types @a@
-- and @b@ must have the same kind.
class a ~~ b => (a :: k) ~ (b :: k) | a -> b, b -> a
-- See Note [The equality types story] in TysPrim
-- NB: All this class does is to wrap its superclass, which is
-- the "real", inhomogeneous equality; this is needed when
-- we have a Given (a~b), and we want to prove things from it
-- NB: Not exported, as (~) is magical syntax. That's also why there's
-- no fixity.
instance {-# INCOHERENT #-} a ~~ b => a ~ b
-- See Note [The equality types story] in TysPrim
-- If we have a Wanted (t1 ~ t2), we want to immediately
-- simplify it to (t1 ~~ t2) and solve that instead
--
-- INCOHERENT because we want to use this instance eagerly, even when
-- the tyvars are partially unknown.
infix 4 :~:
-- | Propositional equality. If @a :~: b@ is inhabited by some terminating
-- value, then the type @a@ is the same as the type @b@. To use this equality
-- in practice, pattern-match on the @a :~: b@ to get out the @Refl@ constructor;
-- in the body of the pattern-match, the compiler knows that @a ~ b@.
--
-- @since 4.7.0.0
data a :~: b where -- See Note [The equality types story] in TysPrim
Refl :: a :~: a
-- with credit to Conal Elliott for 'ty', Erik Hesselink & Martijn van
-- Steenbergen for 'type-equality', Edward Kmett for 'eq', and Gabor Greif
-- for 'type-eq'
-- | Symmetry of equality
sym :: (a :~: b) -> (b :~: a)
sym Refl = Refl
-- | Transitivity of equality
trans :: (a :~: b) -> (b :~: c) -> (a :~: c)
trans Refl Refl = Refl
-- | Type-safe cast, using propositional equality
castWith :: (a :~: b) -> a -> b
castWith Refl x = x
-- | Generalized form of type-safe cast using propositional equality
gcastWith :: (a :~: b) -> ((a ~ b) => r) -> r
gcastWith Refl x = x
-- | Apply one equality to another, respectively
apply :: (f :~: g) -> (a :~: b) -> (f a :~: g b)
apply Refl Refl = Refl
-- | Extract equality of the arguments from an equality of a applied types
inner :: (f a :~: g b) -> (a :~: b)
inner Refl = Refl
-- | Extract equality of type constructors from an equality of applied types
outer :: (f a :~: g b) -> (f :~: g)
outer Refl = Refl
deriving instance Eq (a :~: b)
deriving instance Show (a :~: b)
deriving instance Ord (a :~: b)
instance a ~ b => Read (a :~: b) where
readsPrec d = readParen (d > 10) (\r -> [(Refl, s) | ("Refl",s) <- lex r ])
instance a ~ b => Enum (a :~: b) where
toEnum 0 = Refl
toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument"
fromEnum Refl = 0
instance a ~ b => Bounded (a :~: b) where
minBound = Refl
maxBound = Refl
-- | This class contains types where you can learn the equality of two types
-- from information contained in /terms/. Typically, only singleton types should
-- inhabit this class.
class TestEquality f where
-- | Conditionally prove the equality of @a@ and @b@.
testEquality :: f a -> f b -> Maybe (a :~: b)
instance TestEquality ((:~:) a) where
testEquality Refl Refl = Just Refl
-- | A type family to compute Boolean equality. Instances are provided
-- only for /open/ kinds, such as @*@ and function kinds. Instances are
-- also provided for datatypes exported from base. A poly-kinded instance
-- is /not/ provided, as a recursive definition for algebraic kinds is
-- generally more useful.
type family (a :: k) == (b :: k) :: Bool
infix 4 ==
{-
This comment explains more about why a poly-kinded instance for (==) is
not provided. To be concrete, here would be the poly-kinded instance:
type family EqPoly (a :: k) (b :: k) where
EqPoly a a = True
EqPoly a b = False
type instance (a :: k) == (b :: k) = EqPoly a b
Note that this overlaps with every other instance -- if this were defined,
it would be the only instance for (==).
Now, consider
data Nat = Zero | Succ Nat
Suppose I want
foo :: (Succ n == Succ m) ~ True => ((n == m) :~: True)
foo = Refl
This would not type-check with the poly-kinded instance. `Succ n == Succ m`
quickly becomes `EqPoly (Succ n) (Succ m)` but then is stuck. We don't know
enough about `n` and `m` to reduce further.
On the other hand, consider this:
type family EqNat (a :: Nat) (b :: Nat) where
EqNat Zero Zero = True
EqNat (Succ n) (Succ m) = EqNat n m
EqNat n m = False
type instance (a :: Nat) == (b :: Nat) = EqNat a b
With this instance, `foo` type-checks fine. `Succ n == Succ m` becomes `EqNat
(Succ n) (Succ m)` which becomes `EqNat n m`. Thus, we can conclude `(n == m)
~ True` as desired.
So, the Nat-specific instance allows strictly more reductions, and is thus
preferable to the poly-kinded instance. But, if we introduce the poly-kinded
instance, we are barred from writing the Nat-specific instance, due to
overlap.
Even better than the current instance for * would be one that does this sort
of recursion for all datatypes, something like this:
type family EqStar (a :: *) (b :: *) where
EqStar Bool Bool = True
EqStar (a,b) (c,d) = a == c && b == d
EqStar (Maybe a) (Maybe b) = a == b
...
EqStar a b = False
The problem is the (...) is extensible -- we would want to add new cases for
all datatypes in scope. This is not currently possible for closed type
families.
-}
-- all of the following closed type families are local to this module
type family EqStar (a :: *) (b :: *) where
EqStar a a = 'True
EqStar a b = 'False
-- This looks dangerous, but it isn't. This allows == to be defined
-- over arbitrary type constructors.
type family EqArrow (a :: k1 -> k2) (b :: k1 -> k2) where
EqArrow a a = 'True
EqArrow a b = 'False
type family EqBool a b where
EqBool 'True 'True = 'True
EqBool 'False 'False = 'True
EqBool a b = 'False
type family EqOrdering a b where
EqOrdering 'LT 'LT = 'True
EqOrdering 'EQ 'EQ = 'True
EqOrdering 'GT 'GT = 'True
EqOrdering a b = 'False
type EqUnit (a :: ()) (b :: ()) = 'True
type family EqList a b where
EqList '[] '[] = 'True
EqList (h1 ': t1) (h2 ': t2) = (h1 == h2) && (t1 == t2)
EqList a b = 'False
type family EqMaybe a b where
EqMaybe 'Nothing 'Nothing = 'True
EqMaybe ('Just x) ('Just y) = x == y
EqMaybe a b = 'False
type family Eq2 a b where
Eq2 '(a1, b1) '(a2, b2) = a1 == a2 && b1 == b2
type family Eq3 a b where
Eq3 '(a1, b1, c1) '(a2, b2, c2) = a1 == a2 && b1 == b2 && c1 == c2
type family Eq4 a b where
Eq4 '(a1, b1, c1, d1) '(a2, b2, c2, d2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2
type family Eq5 a b where
Eq5 '(a1, b1, c1, d1, e1) '(a2, b2, c2, d2, e2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2
type family Eq6 a b where
Eq6 '(a1, b1, c1, d1, e1, f1) '(a2, b2, c2, d2, e2, f2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2
type family Eq7 a b where
Eq7 '(a1, b1, c1, d1, e1, f1, g1) '(a2, b2, c2, d2, e2, f2, g2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2
type family Eq8 a b where
Eq8 '(a1, b1, c1, d1, e1, f1, g1, h1) '(a2, b2, c2, d2, e2, f2, g2, h2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2
type family Eq9 a b where
Eq9 '(a1, b1, c1, d1, e1, f1, g1, h1, i1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2
type family Eq10 a b where
Eq10 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2
type family Eq11 a b where
Eq11 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2
type family Eq12 a b where
Eq12 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2
type family Eq13 a b where
Eq13 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2
type family Eq14 a b where
Eq14 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2 && n1 == n2
type family Eq15 a b where
Eq15 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1, o1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2 && n1 == n2 && o1 == o2
-- these all look to be overlapping, but they are differentiated by their kinds
type instance a == b = EqStar a b
type instance a == b = EqArrow a b
type instance a == b = EqBool a b
type instance a == b = EqOrdering a b
type instance a == b = EqUnit a b
type instance a == b = EqList a b
type instance a == b = EqMaybe a b
type instance a == b = Eq2 a b
type instance a == b = Eq3 a b
type instance a == b = Eq4 a b
type instance a == b = Eq5 a b
type instance a == b = Eq6 a b
type instance a == b = Eq7 a b
type instance a == b = Eq8 a b
type instance a == b = Eq9 a b
type instance a == b = Eq10 a b
type instance a == b = Eq11 a b
type instance a == b = Eq12 a b
type instance a == b = Eq13 a b
type instance a == b = Eq14 a b
type instance a == b = Eq15 a b
|
tolysz/prepare-ghcjs
|
spec-lts8/base/Data/Type/Equality.hs
|
bsd-3-clause
| 11,498 | 21 | 34 | 2,841 | 3,516 | 2,026 | 1,490 | -1 | -1 |
module ImportifyUsed (doCache) where
import Importify.Main (doCache)
|
serokell/importify
|
test/test-data/importify@project/01-ImportifyUsed.hs
|
mit
| 80 | 0 | 5 | 18 | 19 | 12 | 7 | 2 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RecordWildCards #-}
-- | Functionality for downloading packages securely for cabal's usage.
module Stack.Fetch
( unpackPackages
, unpackPackageIdent
, unpackPackageIdents
, fetchPackages
, untar
, resolvePackages
, resolvePackagesAllowMissing
, ResolvedPackage (..)
, withCabalFiles
, loadFromIndex
) where
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Check as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import Codec.Compression.GZip (decompress)
import Stack.Prelude
import Crypto.Hash (SHA256 (..))
import qualified Data.ByteString as S
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as HashMap
import qualified Data.HashSet as HashSet
import Data.List (intercalate, maximum)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import Data.Text.Metrics
import Lens.Micro (to)
import Network.HTTP.Download
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import Stack.PackageIndex
import Stack.Types.BuildPlan
import Stack.Types.PackageIdentifier
import Stack.Types.PackageIndex
import Stack.Types.PackageName
import Stack.Types.Version
import qualified System.FilePath as FP
import System.IO (SeekMode (AbsoluteSeek))
import System.PosixCompat (setFileMode)
data FetchException
= Couldn'tReadIndexTarball FilePath Tar.FormatError
| Couldn'tReadPackageTarball FilePath SomeException
| UnpackDirectoryAlreadyExists (Set FilePath)
| CouldNotParsePackageSelectors [String]
| UnknownPackageNames (Set PackageName)
| UnknownPackageIdentifiers (HashSet PackageIdentifierRevision) String
Bool -- Do we use any 00-index.tar.gz indices? Just used for more informative error messages
deriving Typeable
instance Exception FetchException
instance Show FetchException where
show (Couldn'tReadIndexTarball fp err) = concat
[ "There was an error reading the index tarball "
, fp
, ": "
, show err
]
show (Couldn'tReadPackageTarball fp err) = concat
[ "There was an error reading the package tarball "
, fp
, ": "
, show err
]
show (UnpackDirectoryAlreadyExists dirs) = unlines
$ "Unable to unpack due to already present directories:"
: map (" " ++) (Set.toList dirs)
show (CouldNotParsePackageSelectors strs) =
"The following package selectors are not valid package names or identifiers: " ++
intercalate ", " strs
show (UnknownPackageNames names) =
"The following packages were not found in your indices: " ++
intercalate ", " (map packageNameString $ Set.toList names)
show (UnknownPackageIdentifiers idents suggestions uses00Index) =
"The following package identifiers were not found in your indices: " ++
intercalate ", " (map packageIdentifierRevisionString $ HashSet.toList idents) ++
(if null suggestions then "" else "\n" ++ suggestions) ++
(if uses00Index then "\n\nYou seem to be using a legacy 00-index.tar.gz tarball.\nConsider changing your configuration to use a 01-index.tar.gz file.\nAlternatively, you can set the ignore-revision-mismatch setting to true.\nFor more information, see: https://github.com/commercialhaskell/stack/issues/3520" else "")
-- | Fetch packages into the cache without unpacking
fetchPackages :: HasCabalLoader env => Set PackageIdentifier -> RIO env ()
fetchPackages idents' = do
resolved <- resolvePackages Nothing idents Set.empty
ToFetchResult toFetch alreadyUnpacked <- getToFetch Nothing resolved
assert (Map.null alreadyUnpacked) (return ())
nowUnpacked <- fetchPackages' Nothing toFetch
assert (Map.null nowUnpacked) (return ())
where
-- Since we're just fetching tarballs and not unpacking cabal files, we can
-- always provide a CFILatest cabal file info
idents = map (flip PackageIdentifierRevision CFILatest) $ Set.toList idents'
-- | Intended to work for the command line command.
unpackPackages :: HasCabalLoader env
=> Maybe SnapshotDef -- ^ when looking up by name, take from this build plan
-> FilePath -- ^ destination
-> [String] -- ^ names or identifiers
-> RIO env ()
unpackPackages mSnapshotDef dest input = do
dest' <- resolveDir' dest
(names, idents) <- case partitionEithers $ map parse input of
([], x) -> return $ partitionEithers x
(errs, _) -> throwM $ CouldNotParsePackageSelectors errs
resolved <- resolvePackages mSnapshotDef idents (Set.fromList names)
ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just dest') resolved
unless (Map.null alreadyUnpacked) $
throwM $ UnpackDirectoryAlreadyExists $ Set.fromList $ map toFilePath $ Map.elems alreadyUnpacked
unpacked <- fetchPackages' Nothing toFetch
F.forM_ (Map.toList unpacked) $ \(ident, dest'') -> logInfo $ T.pack $ concat
[ "Unpacked "
, packageIdentifierString ident
, " to "
, toFilePath dest''
]
where
-- Possible future enhancement: parse names as name + version range
parse s =
case parsePackageName t of
Right x -> Right $ Left x
Left _ ->
case parsePackageIdentifierRevision t of
Right x -> Right $ Right x
Left _ -> Left s
where
t = T.pack s
-- | Same as 'unpackPackageIdents', but for a single package.
unpackPackageIdent
:: HasCabalLoader env
=> Path Abs Dir -- ^ unpack directory
-> Path Rel Dir -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157
-> PackageIdentifierRevision
-> RIO env (Path Abs Dir)
unpackPackageIdent unpackDir distDir (PackageIdentifierRevision ident mcfi) = do
-- FIXME make this more direct in the future
m <- unpackPackageIdents unpackDir (Just distDir) [PackageIdentifierRevision ident mcfi]
case Map.toList m of
[(ident', dir)]
| ident /= ident' -> error "unpackPackageIdent: ident mismatch"
| otherwise -> return dir
[] -> error "unpackPackageIdent: empty list"
_ -> error "unpackPackageIdent: multiple results"
-- | Ensure that all of the given package idents are unpacked into the build
-- unpack directory, and return the paths to all of the subdirectories.
unpackPackageIdents
:: HasCabalLoader env
=> Path Abs Dir -- ^ unpack directory
-> Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157
-> [PackageIdentifierRevision]
-> RIO env (Map PackageIdentifier (Path Abs Dir))
unpackPackageIdents unpackDir mdistDir idents = do
resolved <- resolvePackages Nothing idents Set.empty
ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just unpackDir) resolved
nowUnpacked <- fetchPackages' mdistDir toFetch
return $ alreadyUnpacked <> nowUnpacked
data ResolvedPackage = ResolvedPackage
{ rpIdent :: !PackageIdentifier
, rpDownload :: !(Maybe PackageDownload)
, rpOffsetSize :: !OffsetSize
, rpIndex :: !PackageIndex
}
deriving Show
-- | Resolve a set of package names and identifiers into @FetchPackage@ values.
resolvePackages :: HasCabalLoader env
=> Maybe SnapshotDef -- ^ when looking up by name, take from this build plan
-> [PackageIdentifierRevision]
-> Set PackageName
-> RIO env [ResolvedPackage]
resolvePackages mSnapshotDef idents0 names0 = do
eres <- go
case eres of
Left _ -> do
updateAllIndices
go >>= either throwM return
Right x -> return x
where
go = r <$> getUses00Index <*> resolvePackagesAllowMissing mSnapshotDef idents0 names0
r uses00Index (missingNames, missingIdents, idents)
| not $ Set.null missingNames = Left $ UnknownPackageNames missingNames
| not $ HashSet.null missingIdents = Left $ UnknownPackageIdentifiers missingIdents "" uses00Index
| otherwise = Right idents
-- | Does the configuration use a 00-index.tar.gz file for indices?
-- See <https://github.com/commercialhaskell/stack/issues/3520>
getUses00Index :: HasCabalLoader env => RIO env Bool
getUses00Index =
any is00 <$> view (cabalLoaderL.to clIndices)
where
is00 :: PackageIndex -> Bool
is00 index = "00-index.tar.gz" `T.isInfixOf` indexLocation index
-- | Turn package identifiers and package names into a list of
-- @ResolvedPackage@s. Returns any unresolved names and
-- identifier. These are considered unresolved even if the only
-- mismatch is in the cabal file info (MSS 2017-07-17: old versions of
-- this code had special handling to treat missing cabal file info as
-- a warning, that's no longer necessary or desirable since all info
-- should be present and checked).
resolvePackagesAllowMissing
:: forall env. HasCabalLoader env
=> Maybe SnapshotDef -- ^ when looking up by name, take from this build plan
-> [PackageIdentifierRevision]
-> Set PackageName
-> RIO env (Set PackageName, HashSet PackageIdentifierRevision, [ResolvedPackage])
resolvePackagesAllowMissing mSnapshotDef idents0 names0 = do
cache@(PackageCache cache') <- getPackageCaches
-- Find out the latest versions of all packages in the cache
let versions = fmap (maximum . HashMap.keys) cache'
-- Determines the identifier for a given name, either from
-- snapshot information or by taking the latest version
-- available
getNamed :: PackageName -> Maybe PackageIdentifierRevision
getNamed =
case mSnapshotDef of
Nothing -> getNamedFromIndex
Just sd -> getNamedFromSnapshotDef sd
-- Use whatever is specified in the snapshot. TODO this does not
-- handle the case where a snapshot defines a package outside of
-- the index, we'd need a LoadedSnapshot for that.
getNamedFromSnapshotDef sd name = do
loop $ sdLocations sd
where
loop [] = Nothing
loop (PLIndex ident@(PackageIdentifierRevision (PackageIdentifier name' _) _):rest)
| name == name' = Just ident
| otherwise = loop rest
loop (_:rest) = loop rest
-- Take latest version available, including latest cabal file information
getNamedFromIndex name = fmap
(\ver -> PackageIdentifierRevision (PackageIdentifier name ver) CFILatest)
(HashMap.lookup name versions)
(missingNames, idents1) = partitionEithers $ map
(\name -> maybe (Left name) Right (getNamed name))
(Set.toList names0)
cl <- view cabalLoaderL
let (missingIdents, resolved) =
partitionEithers
$ map (\pir -> maybe (Left pir) Right (lookupResolvedPackage cl pir cache))
$ idents0 <> idents1
return (Set.fromList missingNames, HashSet.fromList missingIdents, resolved)
lookupResolvedPackage
:: CabalLoader
-> PackageIdentifierRevision
-> PackageCache PackageIndex
-> Maybe ResolvedPackage
lookupResolvedPackage cl (PackageIdentifierRevision ident@(PackageIdentifier name version) cfi) (PackageCache cache) = do
(index, mdownload, files) <- HashMap.lookup name cache >>= HashMap.lookup version
let moffsetSize =
case cfi of
CFILatest -> Just $ snd $ NE.last files
CFIHash _msize hash' -> -- TODO check size?
lookup hash'
$ concatMap (\(hashes, x) -> map (, x) hashes)
$ NE.toList files
CFIRevision rev -> fmap snd $ listToMaybe $ drop (fromIntegral rev) $ NE.toList files
offsetSize <-
case moffsetSize of
Just x -> Just x
Nothing
| clIgnoreRevisionMismatch cl -> Just $ snd $ NE.last files
| otherwise -> Nothing
Just ResolvedPackage
{ rpIdent = ident
, rpDownload = mdownload
, rpOffsetSize = offsetSize
, rpIndex = index
}
data ToFetch = ToFetch
{ tfTarball :: !(Path Abs File)
, tfDestDir :: !(Maybe (Path Abs Dir))
, tfUrl :: !T.Text
, tfSize :: !(Maybe Word64)
, tfSHA256 :: !(Maybe StaticSHA256)
, tfCabal :: !ByteString
-- ^ Contents of the .cabal file
}
data ToFetchResult = ToFetchResult
{ tfrToFetch :: !(Map PackageIdentifier ToFetch)
, tfrAlreadyUnpacked :: !(Map PackageIdentifier (Path Abs Dir))
}
-- | Add the cabal files to a list of idents with their caches.
withCabalFiles
:: HasCabalLoader env
=> IndexName
-> [(ResolvedPackage, a)]
-> (PackageIdentifier -> a -> ByteString -> IO b)
-> RIO env [b]
withCabalFiles name pkgs f = do
indexPath <- configPackageIndex name
withBinaryFile (toFilePath indexPath) ReadMode
$ \h -> mapM (goPkg h) pkgs
where
goPkg h (ResolvedPackage { rpIdent = ident, rpOffsetSize = OffsetSize offset size }, tf) = do
-- Did not find warning for tarballs is handled above
liftIO $ do
hSeek h AbsoluteSeek $ fromIntegral offset
cabalBS <- S.hGet h $ fromIntegral size
f ident tf cabalBS
loadFromIndex :: HasCabalLoader env => PackageIdentifierRevision -> RIO env ByteString
loadFromIndex ident = do
-- TODO in the future, keep all of the necessary @Handle@s open
bothCaches <- getPackageCaches
mres <- lookupPackageIdentifierExact ident bothCaches
case mres of
Just bs -> return bs
-- Update the cache and try again
Nothing -> do
let fuzzy = fuzzyLookupCandidates ident bothCaches
suggestions = case fuzzy of
FRNameNotFound Nothing -> ""
FRNameNotFound (Just cs) ->
"Perhaps you meant " <> orSeparated cs <> "?"
FRVersionNotFound cs -> "Possible candidates: " <>
commaSeparated (NE.map packageIdentifierText cs)
<> "."
FRRevisionNotFound cs ->
"The specified revision was not found.\nPossible candidates: " <>
commaSeparated (NE.map (T.pack . packageIdentifierRevisionString) cs)
<> "."
cl <- view cabalLoaderL
join $ modifyMVar (clUpdateRef cl) $ \toUpdate ->
if toUpdate then do
logInfo $ T.concat
[ "Didn't see "
, T.pack $ packageIdentifierRevisionString ident
, " in your package indices.\n"
, "Updating and trying again."
]
updateAllIndices
_ <- getPackageCaches
return (False, loadFromIndex ident)
else do
uses00Index <- getUses00Index
return (toUpdate, throwIO $ UnknownPackageIdentifiers
(HashSet.singleton ident) (T.unpack suggestions) uses00Index)
lookupPackageIdentifierExact
:: HasCabalLoader env
=> PackageIdentifierRevision
-> PackageCache PackageIndex
-> RIO env (Maybe ByteString)
lookupPackageIdentifierExact identRev cache = do
cl <- view cabalLoaderL
forM (lookupResolvedPackage cl identRev cache) $ \rp -> do
[bs] <- withCabalFiles (indexName (rpIndex rp)) [(rp, ())] $ \_ _ bs -> return bs
return bs
data FuzzyResults
= FRNameNotFound !(Maybe (NonEmpty T.Text))
| FRVersionNotFound !(NonEmpty PackageIdentifier)
| FRRevisionNotFound !(NonEmpty PackageIdentifierRevision)
-- | Given package identifier and package caches, return list of packages
-- with the same name and the same two first version number components found
-- in the caches.
fuzzyLookupCandidates
:: PackageIdentifierRevision
-> PackageCache index
-> FuzzyResults
fuzzyLookupCandidates (PackageIdentifierRevision (PackageIdentifier name ver) _rev) (PackageCache caches) =
case HashMap.lookup name caches of
Nothing -> FRNameNotFound $ typoCorrectionCandidates name (PackageCache caches)
Just m ->
case HashMap.lookup ver m of
Nothing ->
case NE.nonEmpty $ filter sameMajor $ HashMap.keys m of
Just vers -> FRVersionNotFound $ NE.map (PackageIdentifier name) vers
Nothing ->
case NE.nonEmpty $ HashMap.keys m of
Nothing -> error "fuzzyLookupCandidates: no versions"
Just vers -> FRVersionNotFound $ NE.map (PackageIdentifier name) vers
Just (_index, _mpd, revisions) ->
let hashes = concatMap fst $ NE.toList revisions
pirs = map (PackageIdentifierRevision (PackageIdentifier name ver) . CFIHash Nothing) hashes
in case NE.nonEmpty pirs of
Nothing -> error "fuzzyLookupCandidates: no revisions"
Just pirs' -> FRRevisionNotFound pirs'
where
sameMajor v = toMajorVersion v == toMajorVersion ver
-- | Try to come up with typo corrections for given package identifier using
-- package caches. This should be called before giving up, i.e. when
-- 'fuzzyLookupCandidates' cannot return anything.
typoCorrectionCandidates
:: PackageName
-> PackageCache index
-> Maybe (NonEmpty T.Text)
typoCorrectionCandidates name' (PackageCache cache) =
let name = packageNameText name'
in NE.nonEmpty
. take 10
. map snd
. filter (\(distance, _) -> distance < 4)
. map (\k -> (damerauLevenshtein name (packageNameText k), packageNameText k))
. HashMap.keys
$ cache
-- | Figure out where to fetch from.
getToFetch :: HasCabalLoader env
=> Maybe (Path Abs Dir) -- ^ directory to unpack into, @Nothing@ means no unpack
-> [ResolvedPackage]
-> RIO env ToFetchResult
getToFetch mdest resolvedAll = do
(toFetch0, unpacked) <- liftM partitionEithers $ mapM checkUnpacked resolvedAll
toFetch1 <- mapM goIndex $ Map.toList $ Map.fromListWith (++) toFetch0
return ToFetchResult
{ tfrToFetch = Map.unions toFetch1
, tfrAlreadyUnpacked = Map.fromList unpacked
}
where
checkUnpacked resolved = do
let ident = rpIdent resolved
dirRel <- parseRelDir $ packageIdentifierString ident
let mdestDir = (</> dirRel) <$> mdest
mexists <-
case mdestDir of
Nothing -> return Nothing
Just destDir -> do
exists <- doesDirExist destDir
return $ if exists then Just destDir else Nothing
case mexists of
Just destDir -> return $ Right (ident, destDir)
Nothing -> do
let index = rpIndex resolved
d = rpDownload resolved
targz = T.pack $ packageIdentifierString ident ++ ".tar.gz"
tarball <- configPackageTarball (indexName index) ident
return $ Left (indexName index, [(resolved, ToFetch
{ tfTarball = tarball
, tfDestDir = mdestDir
, tfUrl = case fmap pdUrl d of
Just url | not (S.null url) -> decodeUtf8 url
_ -> indexDownloadPrefix index <> targz
, tfSize = fmap pdSize d
, tfSHA256 = fmap pdSHA256 d
, tfCabal = S.empty -- filled in by goIndex
})])
goIndex (name, pkgs) =
liftM Map.fromList $
withCabalFiles name pkgs $ \ident tf cabalBS ->
return (ident, tf { tfCabal = cabalBS })
-- | Download the given name,version pairs into the directory expected by cabal.
--
-- For each package it downloads, it will optionally unpack it to the given
-- @Path@ (if present). Note that unpacking is not simply a matter of
-- untarring, but also of grabbing the cabal file from the package index. The
-- destinations should not include package identifiers.
--
-- Returns the list of paths unpacked, including package identifiers. E.g.:
--
-- @
-- fetchPackages [("foo-1.2.3", Just "/some/dest")] ==> ["/some/dest/foo-1.2.3"]
-- @
--
-- Since 0.1.0.0
fetchPackages' :: forall env. HasCabalLoader env
=> Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157
-> Map PackageIdentifier ToFetch
-> RIO env (Map PackageIdentifier (Path Abs Dir))
fetchPackages' mdistDir toFetchAll = do
connCount <- view $ cabalLoaderL.to clConnectionCount
outputVar <- newTVarIO Map.empty
parMapM_
connCount
(go outputVar)
(Map.toList toFetchAll)
readTVarIO outputVar
where
go :: TVar (Map PackageIdentifier (Path Abs Dir))
-> (PackageIdentifier, ToFetch)
-> RIO env ()
go outputVar (ident, toFetch) = do
req <- parseUrlThrow $ T.unpack $ tfUrl toFetch
let destpath = tfTarball toFetch
let toHashCheck bs = HashCheck SHA256 (CheckHexDigestByteString bs)
let downloadReq = DownloadRequest
{ drRequest = req
, drHashChecks = map (toHashCheck . staticSHA256ToBase16) $ maybeToList (tfSHA256 toFetch)
, drLengthCheck = fromIntegral <$> tfSize toFetch
, drRetryPolicy = drRetryPolicyDefault
}
let progressSink _ =
logInfo $ packageIdentifierText ident <> ": download"
_ <- verifiedDownload downloadReq destpath progressSink
identStrP <- parseRelDir $ packageIdentifierString ident
F.forM_ (tfDestDir toFetch) $ \destDir -> do
let innerDest = toFilePath destDir
unexpectedEntries <- liftIO $ untar destpath identStrP (parent destDir)
liftIO $ do
case mdistDir of
Nothing -> return ()
-- See: https://github.com/fpco/stack/issues/157
Just distDir -> do
let inner = parent destDir </> identStrP
oldDist = inner </> $(mkRelDir "dist")
newDist = inner </> distDir
exists <- doesDirExist oldDist
when exists $ do
-- Previously used takeDirectory, but that got confused
-- by trailing slashes, see:
-- https://github.com/commercialhaskell/stack/issues/216
--
-- Instead, use Path which is a bit more resilient
ensureDir $ parent newDist
renameDir oldDist newDist
let cabalFP =
innerDest FP.</>
packageNameString (packageIdentifierName ident)
FP.<.> "cabal"
S.writeFile cabalFP $ tfCabal toFetch
atomically $ modifyTVar outputVar $ Map.insert ident destDir
F.forM_ unexpectedEntries $ \(path, entryType) ->
logWarn $ "Unexpected entry type " <> entryType <> " for entry " <> T.pack path
-- | Internal function used to unpack tarball.
--
-- Takes a path to a .tar.gz file, the name of the directory it should contain,
-- and a destination folder to extract the tarball into. Returns unexpected
-- entries, as pairs of paths and descriptions.
untar :: forall b1 b2. Path b1 File -> Path Rel Dir -> Path b2 Dir -> IO [(FilePath, T.Text)]
untar tarPath expectedTarFolder destDirParent = do
ensureDir destDirParent
withLazyFile (toFilePath tarPath) $ \lbs -> do
let rawEntries = fmap (either wrap wrap)
$ Tar.checkTarbomb (toFilePathNoTrailingSep expectedTarFolder)
$ Tar.read $ decompress lbs
filterEntries
:: Monoid w => (Tar.Entry -> (Bool, w))
-> Tar.Entries b -> (Tar.Entries b, w)
-- Allow collecting warnings, Writer-monad style.
filterEntries f =
Tar.foldEntries
(\e -> let (res, w) = f e in
\(rest, wOld) -> ((if res then Tar.Next e else id) rest, wOld <> w))
(Tar.Done, mempty)
(\err -> (Tar.Fail err, mempty))
extractableEntry e =
case Tar.entryContent e of
Tar.NormalFile _ _ -> (True, [])
Tar.Directory -> (True, [])
Tar.SymbolicLink _ -> (True, [])
Tar.HardLink _ -> (True, [])
Tar.OtherEntryType 'g' _ _ -> (False, [])
Tar.OtherEntryType 'x' _ _ -> (False, [])
Tar.CharacterDevice _ _ -> (False, [(path, "character device")])
Tar.BlockDevice _ _ -> (False, [(path, "block device")])
Tar.NamedPipe -> (False, [(path, "named pipe")])
Tar.OtherEntryType code _ _ -> (False, [(path, "other entry type with code " <> T.pack (show code))])
where
path = Tar.fromTarPath $ Tar.entryTarPath e
(entries, unexpectedEntries) = filterEntries extractableEntry rawEntries
wrap :: Exception e => e -> FetchException
wrap = Couldn'tReadPackageTarball (toFilePath tarPath) . toException
getPerms :: Tar.Entry -> (FilePath, Tar.Permissions)
getPerms e = (toFilePath destDirParent FP.</> Tar.fromTarPath (Tar.entryTarPath e),
Tar.entryPermissions e)
filePerms :: [(FilePath, Tar.Permissions)]
filePerms = catMaybes $ Tar.foldEntries (\e -> (:) (Just $ getPerms e))
[] (const []) entries
Tar.unpack (toFilePath destDirParent) entries
-- Reset file permissions as they were in the tarball, but only
-- for extracted entries (whence filterEntries extractableEntry above).
-- See https://github.com/commercialhaskell/stack/issues/2361
mapM_ (\(fp, perm) -> setFileMode
(FP.dropTrailingPathSeparator fp)
perm) filePerms
return unexpectedEntries
parMapM_ :: (F.Foldable f,MonadUnliftIO m)
=> Int
-> (a -> m ())
-> f a
-> m ()
parMapM_ (max 1 -> 1) f xs = F.mapM_ f xs
parMapM_ cnt f xs0 = withRunInIO $ \run -> do
var <- newTVarIO $ F.toList xs0
replicateConcurrently_ cnt $ fix $ \loop -> join $ atomically $ do
xs <- readTVar var
case xs of
[] -> return $ return ()
x:xs' -> do
writeTVar var xs'
return $ do
run $ f x
loop
orSeparated :: NonEmpty T.Text -> T.Text
orSeparated xs
| NE.length xs == 1 = NE.head xs
| NE.length xs == 2 = NE.head xs <> " or " <> NE.last xs
| otherwise = T.intercalate ", " (NE.init xs) <> ", or " <> NE.last xs
commaSeparated :: NonEmpty T.Text -> T.Text
commaSeparated = F.fold . NE.intersperse ", "
-- | Location of a package tarball
configPackageTarball :: HasCabalLoader env => IndexName -> PackageIdentifier -> RIO env (Path Abs File)
configPackageTarball iname ident = do
root <- configPackageIndexRoot iname
name <- parseRelDir $ packageNameString $ packageIdentifierName ident
ver <- parseRelDir $ versionString $ packageIdentifierVersion ident
base <- parseRelFile $ packageIdentifierString ident ++ ".tar.gz"
return (root </> $(mkRelDir "packages") </> name </> ver </> base)
|
anton-dessiatov/stack
|
src/Stack/Fetch.hs
|
bsd-3-clause
| 28,789 | 0 | 30 | 8,578 | 6,506 | 3,283 | 3,223 | 545 | 11 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
module Bug where
import Data.Kind
data family Sing (a :: k)
data HR (a :: j) (b :: k) where
HRefl :: HR a a
data instance Sing (z :: HR a b) where
SHRefl :: Sing HRefl
foo :: forall (j :: Type) (k :: Type) (a :: j)
(b :: k) (r :: HR a b)
(p :: forall (z :: Type) (y :: z). HR a y -> Type).
Sing r
-> App p HRefl
-> HRApp p r
foo SHRefl pHRefl = pHRefl
type App f x = f x
type HRApp (f :: forall (z :: Type) (y :: z). HR a y -> Type)
(x :: HR a b) = f x
|
ezyang/ghc
|
testsuite/tests/typecheck/should_compile/T13879.hs
|
bsd-3-clause
| 703 | 0 | 10 | 215 | 262 | 160 | 102 | -1 | -1 |
module A6 where
--Any type/data constructor name declared in this module can be renamed.
--Any type variable can be renamed.
--Rename type Constructor 'BTree' to 'MyBTree'
data BTree a = Empty | T a (BTree a) (BTree a)
deriving Show
buildtree :: Ord a => [a] -> BTree a
buildtree [] = Empty
buildtree (x:xs) = insert x (buildtree xs)
insert :: Ord a => a -> [BTree a] -> BTree a
insert val (((Empty : t@(T val Empty Empty)) : xs))
= T val Empty (result Empty) where result Empty = (T val Empty Empty)
insert val (T tval left right)
| val > tval = T tval left (insert val right)
| otherwise = T tval (insert val left) right
newPat_1 = Empty
f :: String -> String
f newPat_2@((x : xs)) = newPat_2
main :: BTree Int
main = buildtree [3,1,2]
|
kmate/HaRe
|
old/testing/unfoldAsPatterns/A6_TokOut.hs
|
bsd-3-clause
| 780 | 0 | 13 | 186 | 328 | 171 | 157 | 17 | 1 |
module Opaleye.SQLite.Operators (module Opaleye.SQLite.Operators) where
import qualified Data.Foldable as F
import Opaleye.SQLite.Internal.Column (Column(Column), unsafeCase_,
unsafeIfThenElse, unsafeGt, unsafeEq)
import qualified Opaleye.SQLite.Internal.Column as C
import Opaleye.SQLite.Internal.QueryArr (QueryArr(QueryArr))
import qualified Opaleye.SQLite.Internal.PrimQuery as PQ
import qualified Opaleye.SQLite.Order as Ord
import qualified Opaleye.SQLite.PGTypes as T
import qualified Opaleye.SQLite.Internal.HaskellDB.PrimQuery as HPQ
{-| Restrict query results to a particular condition. Corresponds to
the guard method of the MonadPlus class.
-}
restrict :: QueryArr (Column T.PGBool) ()
restrict = QueryArr f where
f (Column predicate, primQ, t0) = ((), PQ.restrict predicate primQ, t0)
doubleOfInt :: Column T.PGInt4 -> Column T.PGFloat8
doubleOfInt (Column e) = Column (HPQ.CastExpr "float8" e)
infix 4 .==
(.==) :: Column a -> Column a -> Column T.PGBool
(.==) = unsafeEq
infix 4 ./=
(./=) :: Column a -> Column a -> Column T.PGBool
(./=) = C.binOp HPQ.OpNotEq
infix 4 .>
(.>) :: Ord.PGOrd a => Column a -> Column a -> Column T.PGBool
(.>) = unsafeGt
infix 4 .<
(.<) :: Ord.PGOrd a => Column a -> Column a -> Column T.PGBool
(.<) = C.binOp HPQ.OpLt
infix 4 .<=
(.<=) :: Ord.PGOrd a => Column a -> Column a -> Column T.PGBool
(.<=) = C.binOp HPQ.OpLtEq
infix 4 .>=
(.>=) :: Ord.PGOrd a => Column a -> Column a -> Column T.PGBool
(.>=) = C.binOp HPQ.OpGtEq
case_ :: [(Column T.PGBool, Column a)] -> Column a -> Column a
case_ = unsafeCase_
ifThenElse :: Column T.PGBool -> Column a -> Column a -> Column a
ifThenElse = unsafeIfThenElse
infixr 3 .&&
(.&&) :: Column T.PGBool -> Column T.PGBool -> Column T.PGBool
(.&&) = C.binOp HPQ.OpAnd
infixr 2 .||
(.||) :: Column T.PGBool -> Column T.PGBool -> Column T.PGBool
(.||) = C.binOp HPQ.OpOr
not :: Column T.PGBool -> Column T.PGBool
not = C.unOp HPQ.OpNot
(.++) :: Column T.PGText -> Column T.PGText -> Column T.PGText
(.++) = C.binOp HPQ.OpCat
lower :: Column T.PGText -> Column T.PGText
lower = C.unOp HPQ.OpLower
upper :: Column T.PGText -> Column T.PGText
upper = C.unOp HPQ.OpUpper
like :: Column T.PGText -> Column T.PGText -> Column T.PGBool
like = C.binOp HPQ.OpLike
ors :: F.Foldable f => f (Column T.PGBool) -> Column T.PGBool
ors = F.foldl' (.||) (T.pgBool False)
in_ :: (Functor f, F.Foldable f) => f (Column a) -> Column a -> Column T.PGBool
in_ hs w = ors . fmap (w .==) $ hs
|
bergmark/haskell-opaleye
|
opaleye-sqlite/src/Opaleye/SQLite/Operators.hs
|
bsd-3-clause
| 2,541 | 0 | 10 | 473 | 1,004 | 540 | 464 | 57 | 1 |
module Lib
( someFunc
) where
someFunc :: IO ()
someFunc = print "some func"
|
juhp/stack
|
test/integration/tests/3396-package-indices/files/src/Lib.hs
|
bsd-3-clause
| 88 | 0 | 6 | 26 | 27 | 15 | 12 | 4 | 1 |
------------------------------------------------------------------------------
-- |
-- Module: Plugins.Utils
-- Copyright: (c) 2010 Jose Antonio Ortega Ruiz
-- License: BSD3-style (see LICENSE)
--
-- Maintainer: Jose A Ortega Ruiz <[email protected]>
-- Stability: unstable
-- Portability: unportable
-- Created: Sat Dec 11, 2010 20:55
--
--
-- Miscellaneous utility functions
--
------------------------------------------------------------------------------
module Plugins.Utils (expandHome, changeLoop, safeHead) where
import Control.Monad
import Control.Concurrent.STM
import System.Environment
import System.FilePath
expandHome :: FilePath -> IO FilePath
expandHome ('~':'/':path) = fmap (</> path) (getEnv "HOME")
expandHome p = return p
changeLoop :: Eq a => STM a -> (a -> IO ()) -> IO ()
changeLoop s f = atomically s >>= go
where
go old = do
f old
go =<< atomically (do
new <- s
guard (new /= old)
return new)
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:_) = Just x
|
tsiliakis/xmobar
|
src/Plugins/Utils.hs
|
bsd-3-clause
| 1,067 | 0 | 16 | 220 | 265 | 141 | 124 | 19 | 1 |
{-# OPTIONS -fwarn-tabs #-}
-- Check we get a warning for multiple tabs, with the correct number of tabs
-- mentioned
module ShouldCompile where
-- tab in middle of line
tab1 = 'a'
-- tab at end of line
tab2 = 'b'
-- two tabs in middle of line
tab3 = 'c'
tab4 = if True
-- tab at start of line
then 'd'
-- tab at start of line
else 'e'
-- tab before a comment starts
|
urbanslug/ghc
|
testsuite/tests/parser/should_compile/T9723b.hs
|
bsd-3-clause
| 378 | 8 | 5 | 89 | 49 | 33 | 16 | 8 | 2 |
module Pet.Pipeline where
import Pet.Commands
|
fredmorcos/attic
|
projects/pet/archive/pet_haskell_modular_1/Pet/Pipeline.hs
|
isc
| 47 | 0 | 4 | 6 | 11 | 7 | 4 | 2 | 0 |
module Graphics.Urho3D.Input.InputConstants(
MouseButton(..)
, MouseButtonFlags
, Qualifier(..)
, QualifierFlags
, Key(..)
, Scancode(..)
, HatPosition(..)
, ControllerButton(..)
, ControllerAxis(..)
) where
import GHC.Generics
import Graphics.Urho3D.Container.FlagSet
import Data.Word
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
C.context (C.cppCtx)
C.include "<Urho3D/Input/InputConstants.h>"
C.using "namespace Urho3D"
data MouseButton =
MouseButtonNone
| MouseButtonLeft
| MouseButtonMiddle
| MouseButtonRight
| MouseButtonX1
| MouseButtonX2
| MouseButtonAny
deriving (Eq, Ord, Show, Read, Bounded, Generic)
instance Enum MouseButton where
toEnum = fromUrhoMouseButton
{-# INLINE toEnum #-}
fromEnum = toUrhoMouseButton
{-# INLINE fromEnum #-}
fromUrhoMouseButton :: Int -> MouseButton
fromUrhoMouseButton i
| i == mouseButtonNone = MouseButtonNone
| i == mouseButtonLeft = MouseButtonLeft
| i == mouseButtonMiddle = MouseButtonMiddle
| i == mouseButtonRight = MouseButtonRight
| i == mouseButtonX1 = MouseButtonX1
| i == mouseButtonX2 = MouseButtonX2
| i == mouseButtonAny = MouseButtonAny
| otherwise = MouseButtonNone
toUrhoMouseButton :: MouseButton -> Int
toUrhoMouseButton i = case i of
MouseButtonNone -> mouseButtonNone
MouseButtonLeft -> mouseButtonLeft
MouseButtonMiddle -> mouseButtonMiddle
MouseButtonRight -> mouseButtonRight
MouseButtonX1 -> mouseButtonX1
MouseButtonX2 -> mouseButtonX2
MouseButtonAny -> mouseButtonAny
type MouseButtonFlags = FlagSet Word32 MouseButton
mouseButtonNone :: Int
mouseButtonNone = fromIntegral $ [C.pure| int { MOUSEB_NONE } |]
mouseButtonLeft :: Int
mouseButtonLeft = fromIntegral $ [C.pure| int { MOUSEB_LEFT } |]
mouseButtonMiddle :: Int
mouseButtonMiddle = fromIntegral $ [C.pure| int { MOUSEB_MIDDLE } |]
mouseButtonRight :: Int
mouseButtonRight = fromIntegral $ [C.pure| int { MOUSEB_RIGHT } |]
mouseButtonX1 :: Int
mouseButtonX1 = fromIntegral $ [C.pure| int { MOUSEB_X1 } |]
mouseButtonX2 :: Int
mouseButtonX2 = fromIntegral $ [C.pure| int { MOUSEB_X2 } |]
mouseButtonAny :: Int
mouseButtonAny = fromIntegral $ [C.pure| int { MOUSEB_ANY } |]
data Qualifier =
QualNone
| QualShift
| QualCtrl
| QualAlt
| QualAny
deriving (Eq, Ord, Show, Read, Bounded, Generic)
instance Enum Qualifier where
toEnum i = case i of
0 -> QualNone
1 -> QualShift
2 -> QualCtrl
4 -> QualAlt
8 -> QualAny
_ -> QualNone
{-# INLINE toEnum #-}
fromEnum i = case i of
QualNone -> 0
QualShift -> 1
QualCtrl -> 2
QualAlt -> 4
QualAny -> 8
{-# INLINE fromEnum #-}
type QualifierFlags = FlagSet Word32 Qualifier
data Key =
KeyA
| KeyB
| KeyC
| KeyD
| KeyE
| KeyF
| KeyG
| KeyH
| KeyI
| KeyJ
| KeyK
| KeyL
| KeyM
| KeyN
| KeyO
| KeyP
| KeyQ
| KeyR
| KeyS
| KeyT
| KeyU
| KeyV
| KeyW
| KeyX
| KeyY
| KeyZ
| Key0
| Key1
| Key2
| Key3
| Key4
| Key5
| Key6
| Key7
| Key8
| Key9
| KeyBackspace
| KeyTab
| KeyReturn
| KeyReturn2
| KeyKPEnter
| KeyShift
| KeyCtrl
| KeyAlt
| KeyGui
| KeyPause
| KeyCapsLock
| KeyEsc
| KeySpace
| KeyPageUp
| KeyPageDown
| KeyEnd
| KeyHome
| KeyLeft
| KeyUp
| KeyRight
| KeyDown
| KeySelect
| KeyPrintScreen
| KeyInsert
| KeyDelete
| KeyLGUI
| KeyRGUI
| KeyApplication
| KeyKP0
| KeyKP1
| KeyKP2
| KeyKP3
| KeyKP4
| KeyKP5
| KeyKP6
| KeyKP7
| KeyKP8
| KeyKP9
| KeyKPMultiply
| KeyKPPlus
| KeyKPMinus
| KeyKPPeriod
| KeyKPDivide
| KeyF1
| KeyF2
| KeyF3
| KeyF4
| KeyF5
| KeyF6
| KeyF7
| KeyF8
| KeyF9
| KeyF10
| KeyF11
| KeyF12
| KeyF13
| KeyF14
| KeyF15
| KeyF16
| KeyF17
| KeyF18
| KeyF19
| KeyF20
| KeyF21
| KeyF22
| KeyF23
| KeyF24
| KeyNumLockClear
| KeyScrollLock
| KeyLShift
| KeyRShift
| KeyLCtrl
| KeyRCtrl
| KeyLAlt
| KeyRAlt
| KeyACBack
| KeyACBookMarks
| KeyACForward
| KeyACHome
| KeyACRefresh
| KeyACSearch
| KeyACStop
| KeyAgain
| KeyAltErase
| KeyAmpersand
| KeyAT
| KeyAudioMute
| KeyAudioNext
| KeyAudioPlay
| KeyAudioPrev
| KeyAudioStop
| KeyBackQuote
| KeyBackSlash
| KeyBrightnessDown
| KeyBrightnessUp
| KeyCalculator
| KeyCancel
| KeyCaret
| KeyClear
| KeyClearAgain
| KeyColon
| KeyComma
| KeyComputer
| KeyCopy
| KeyCRSel
| KeyCurrencySubUnit
| KeyCurrencyUnit
| KeyCut
| KeyDecimalSeparator
| KeyDisplaySwitch
| KeyDollar
| KeyEject
| KeyEquals
| KeyExclaim
| KeyExsel
| KeyFind
| KeyGreater
| KeyHash
| KeyHelp
| KeyKBDillumDown
| KeyKBDillumToggle
| KeyKBDillumUp
| KeyKP00
| KeyKP000
| KeyKPA
| KeyKPAmpersand
| KeyKPAT
| KeyKPB
| KeyKPBackspace
| KeyKPBinary
| KeyKPC
| KeyKPClear
| KeyKPClearEntry
| KeyKPColon
| KeyKPComma
| KeyKPD
| KeyKPDBLAmpersand
| KeyKPDBLVerticalBar
| KeyKPDecimal
| KeyKPE
| KeyKPEquals
| KeyKPEqualsAS400
| KeyKPExclaim
| KeyKPF
| KeyKPGreater
| KeyKPHash
| KeyKPHexadecimal
| KeyKPLeftBrace
| KeyKPLeftParen
| KeyKPLess
| KeyKPMemAdd
| KeyKPMemClear
| KeyKPMemDivide
| KeyKPMemMultiply
| KeyKPMemRecall
| KeyKPMemStore
| KeyKPMemSubtract
| KeyKPOctal
| KeyKPPercent
| KeyKPPlusMinus
| KeyKPPower
| KeyKPRightBrace
| KeyKPRightParen
| KeyKPSpace
| KeyKPTab
| KeyKPVerticalBar
| KeyKPXor
| KeyLeftBracket
| KeyLeftParen
| KeyLess
| KeyMail
| KeyMediaSelect
| KeyMenu
| KeyMinus
| KeyMode
| KeyMute
| KeyOper
| KeyOut
| KeyPaste
| KeyPercent
| KeyPeriod
| KeyPlus
| KeyPower
| KeyPrior
| KeyQuestion
| KeyQuote
| KeyQuoteDbl
| KeyRightBracket
| KeyRightParen
| KeySemicolon
| KeySeparator
| KeySlash
| KeySleep
| KeyStop
| KeySysReq
| KeyThousandsSeparator
| KeyUnderscore
| KeyUndo
| KeyVolumeDown
| KeyVolumeUp
| KeyWWW
| KeyUnknown
deriving (Eq, Ord, Show, Read, Bounded, Generic)
instance Enum Key where
fromEnum = toUrhoKey
{-# INLINE fromEnum #-}
toEnum = fromUrhoKey
{-# INLINE toEnum #-}
fromUrhoKey :: Int -> Key
fromUrhoKey i
| i == keyA = KeyA
| i == keyB = KeyB
| i == keyC = KeyC
| i == keyD = KeyD
| i == keyE = KeyE
| i == keyF = KeyF
| i == keyG = KeyG
| i == keyH = KeyH
| i == keyI = KeyI
| i == keyJ = KeyJ
| i == keyK = KeyK
| i == keyL = KeyL
| i == keyM = KeyM
| i == keyN = KeyN
| i == keyO = KeyO
| i == keyP = KeyP
| i == keyQ = KeyQ
| i == keyR = KeyR
| i == keyS = KeyS
| i == keyT = KeyT
| i == keyU = KeyU
| i == keyV = KeyV
| i == keyW = KeyW
| i == keyX = KeyX
| i == keyY = KeyY
| i == keyZ = KeyZ
| i == key0 = Key0
| i == key1 = Key1
| i == key2 = Key2
| i == key3 = Key3
| i == key4 = Key4
| i == key5 = Key5
| i == key6 = Key6
| i == key7 = Key7
| i == key8 = Key8
| i == key9 = Key9
| i == keyBackspace = KeyBackspace
| i == keyTab = KeyTab
| i == keyReturn = KeyReturn
| i == keyReturn2 = KeyReturn2
| i == keyKPEnter = KeyKPEnter
| i == keyShift = KeyShift
| i == keyCtrl = KeyCtrl
| i == keyAlt = KeyAlt
| i == keyGui = KeyGui
| i == keyPause = KeyPause
| i == keyCapsLock = KeyCapsLock
| i == keyEsc = KeyEsc
| i == keySpace = KeySpace
| i == keyPageUp = KeyPageUp
| i == keyPageDown = KeyPageDown
| i == keyEnd = KeyEnd
| i == keyHome = KeyHome
| i == keyLeft = KeyLeft
| i == keyUp = KeyUp
| i == keyRight = KeyRight
| i == keyDown = KeyDown
| i == keySelect = KeySelect
| i == keyPrintScreen = KeyPrintScreen
| i == keyInsert = KeyInsert
| i == keyDelete = KeyDelete
| i == keyLGUI = KeyLGUI
| i == keyRGUI = KeyRGUI
| i == keyApplication = KeyApplication
| i == keyKP0 = KeyKP0
| i == keyKP1 = KeyKP1
| i == keyKP2 = KeyKP2
| i == keyKP3 = KeyKP3
| i == keyKP4 = KeyKP4
| i == keyKP5 = KeyKP5
| i == keyKP6 = KeyKP6
| i == keyKP7 = KeyKP7
| i == keyKP8 = KeyKP8
| i == keyKP9 = KeyKP9
| i == keyKPMultiply = KeyKPMultiply
| i == keyKPPlus = KeyKPPlus
| i == keyKPMinus = KeyKPMinus
| i == keyKPPeriod = KeyKPPeriod
| i == keyKPDivide = KeyKPDivide
| i == keyF1 = KeyF1
| i == keyF2 = KeyF2
| i == keyF3 = KeyF3
| i == keyF4 = KeyF4
| i == keyF5 = KeyF5
| i == keyF6 = KeyF6
| i == keyF7 = KeyF7
| i == keyF8 = KeyF8
| i == keyF9 = KeyF9
| i == keyF10 = KeyF10
| i == keyF11 = KeyF11
| i == keyF12 = KeyF12
| i == keyF13 = KeyF13
| i == keyF14 = KeyF14
| i == keyF15 = KeyF15
| i == keyF16 = KeyF16
| i == keyF17 = KeyF17
| i == keyF18 = KeyF18
| i == keyF19 = KeyF19
| i == keyF20 = KeyF20
| i == keyF21 = KeyF21
| i == keyF22 = KeyF22
| i == keyF23 = KeyF23
| i == keyF24 = KeyF24
| i == keyNumLockClear = KeyNumLockClear
| i == keyScrollLock = KeyScrollLock
| i == keyLShift = KeyLShift
| i == keyRShift = KeyRShift
| i == keyLCtrl = KeyLCtrl
| i == keyRCtrl = KeyRCtrl
| i == keyLAlt = KeyLAlt
| i == keyRAlt = KeyRAlt
| i == keyACBack = KeyACBack
| i == keyACBookMarks = KeyACBookMarks
| i == keyACForward = KeyACForward
| i == keyACHome = KeyACHome
| i == keyACRefresh = KeyACRefresh
| i == keyACSearch = KeyACSearch
| i == keyACStop = KeyACStop
| i == keyAgain = KeyAgain
| i == keyAltErase = KeyAltErase
| i == keyAmpersand = KeyAmpersand
| i == keyAT = KeyAT
| i == keyAudioMute = KeyAudioMute
| i == keyAudioNext = KeyAudioNext
| i == keyAudioPlay = KeyAudioPlay
| i == keyAudioPrev = KeyAudioPrev
| i == keyAudioStop = KeyAudioStop
| i == keyBackQuote = KeyBackQuote
| i == keyBackSlash = KeyBackSlash
| i == keyBrightnessDown = KeyBrightnessDown
| i == keyBrightnessUp = KeyBrightnessUp
| i == keyCalculator = KeyCalculator
| i == keyCancel = KeyCancel
| i == keyCaret = KeyCaret
| i == keyClear = KeyClear
| i == keyClearAgain = KeyClearAgain
| i == keyColon = KeyColon
| i == keyComma = KeyComma
| i == keyComputer = KeyComputer
| i == keyCopy = KeyCopy
| i == keyCRSel = KeyCRSel
| i == keyCurrencySubUnit = KeyCurrencySubUnit
| i == keyCurrencyUnit = KeyCurrencyUnit
| i == keyCut = KeyCut
| i == keyDecimalSeparator = KeyDecimalSeparator
| i == keyDisplaySwitch = KeyDisplaySwitch
| i == keyDollar = KeyDollar
| i == keyEject = KeyEject
| i == keyEquals = KeyEquals
| i == keyExclaim = KeyExclaim
| i == keyExsel = KeyExsel
| i == keyFind = KeyFind
| i == keyGreater = KeyGreater
| i == keyHash = KeyHash
| i == keyHelp = KeyHelp
| i == keyKBDillumDown = KeyKBDillumDown
| i == keyKBDillumToggle = KeyKBDillumToggle
| i == keyKBDillumUp = KeyKBDillumUp
| i == keyKP00 = KeyKP00
| i == keyKP000 = KeyKP000
| i == keyKPA = KeyKPA
| i == keyKPAmpersand = KeyKPAmpersand
| i == keyKPAT = KeyKPAT
| i == keyKPB = KeyKPB
| i == keyKPBackspace = KeyKPBackspace
| i == keyKPBinary = KeyKPBinary
| i == keyKPC = KeyKPC
| i == keyKPClear = KeyKPClear
| i == keyKPClearEntry = KeyKPClearEntry
| i == keyKPColon = KeyKPColon
| i == keyKPComma = KeyKPComma
| i == keyKPD = KeyKPD
| i == keyKPDBLAmpersand = KeyKPDBLAmpersand
| i == keyKPDBLVerticalBar = KeyKPDBLVerticalBar
| i == keyKPDecimal = KeyKPDecimal
| i == keyKPE = KeyKPE
| i == keyKPEquals = KeyKPEquals
| i == keyKPEqualsAS400 = KeyKPEqualsAS400
| i == keyKPExclaim = KeyKPExclaim
| i == keyKPF = KeyKPF
| i == keyKPGreater = KeyKPGreater
| i == keyKPHash = KeyKPHash
| i == keyKPHexadecimal = KeyKPHexadecimal
| i == keyKPLeftBrace = KeyKPLeftBrace
| i == keyKPLeftParen = KeyKPLeftParen
| i == keyKPLess = KeyKPLess
| i == keyKPMemAdd = KeyKPMemAdd
| i == keyKPMemClear = KeyKPMemClear
| i == keyKPMemDivide = KeyKPMemDivide
| i == keyKPMemMultiply = KeyKPMemMultiply
| i == keyKPMemRecall = KeyKPMemRecall
| i == keyKPMemStore = KeyKPMemStore
| i == keyKPMemSubtract = KeyKPMemSubtract
| i == keyKPOctal = KeyKPOctal
| i == keyKPPercent = KeyKPPercent
| i == keyKPPlusMinus = KeyKPPlusMinus
| i == keyKPPower = KeyKPPower
| i == keyKPRightBrace = KeyKPRightBrace
| i == keyKPRightParen = KeyKPRightParen
| i == keyKPSpace = KeyKPSpace
| i == keyKPTab = KeyKPTab
| i == keyKPVerticalBar = KeyKPVerticalBar
| i == keyKPXor = KeyKPXor
| i == keyLeftBracket = KeyLeftBracket
| i == keyLeftParen = KeyLeftParen
| i == keyLess = KeyLess
| i == keyMail = KeyMail
| i == keyMediaSelect = KeyMediaSelect
| i == keyMenu = KeyMenu
| i == keyMinus = KeyMinus
| i == keyMode = KeyMode
| i == keyMute = KeyMute
| i == keyOper = KeyOper
| i == keyOut = KeyOut
| i == keyPaste = KeyPaste
| i == keyPercent = KeyPercent
| i == keyPeriod = KeyPeriod
| i == keyPlus = KeyPlus
| i == keyPower = KeyPower
| i == keyPrior = KeyPrior
| i == keyQuestion = KeyQuestion
| i == keyQuote = KeyQuote
| i == keyQuoteDbl = KeyQuoteDbl
| i == keyRightBracket = KeyRightBracket
| i == keyRightParen = KeyRightParen
| i == keySemicolon = KeySemicolon
| i == keySeparator = KeySeparator
| i == keySlash = KeySlash
| i == keySleep = KeySleep
| i == keyStop = KeyStop
| i == keySysReq = KeySysReq
| i == keyThousandsSeparator = KeyThousandsSeparator
| i == keyUnderscore = KeyUnderscore
| i == keyUndo = KeyUndo
| i == keyVolumeDown = KeyVolumeDown
| i == keyVolumeUp = KeyVolumeUp
| i == keyWWW = KeyWWW
| otherwise = KeyUnknown
toUrhoKey :: Key -> Int
toUrhoKey i = case i of
KeyA -> keyA
KeyB -> keyB
KeyC -> keyC
KeyD -> keyD
KeyE -> keyE
KeyF -> keyF
KeyG -> keyG
KeyH -> keyH
KeyI -> keyI
KeyJ -> keyJ
KeyK -> keyK
KeyL -> keyL
KeyM -> keyM
KeyN -> keyN
KeyO -> keyO
KeyP -> keyP
KeyQ -> keyQ
KeyR -> keyR
KeyS -> keyS
KeyT -> keyT
KeyU -> keyU
KeyV -> keyV
KeyW -> keyW
KeyX -> keyX
KeyY -> keyY
KeyZ -> keyZ
Key0 -> key0
Key1 -> key1
Key2 -> key2
Key3 -> key3
Key4 -> key4
Key5 -> key5
Key6 -> key6
Key7 -> key7
Key8 -> key8
Key9 -> key9
KeyBackspace -> keyBackspace
KeyTab -> keyTab
KeyReturn -> keyReturn
KeyReturn2 -> keyReturn2
KeyKPEnter -> keyKPEnter
KeyShift -> keyShift
KeyCtrl -> keyCtrl
KeyAlt -> keyAlt
KeyGui -> keyGui
KeyPause -> keyPause
KeyCapsLock -> keyCapsLock
KeyEsc -> keyEsc
KeySpace -> keySpace
KeyPageUp -> keyPageUp
KeyPageDown -> keyPageDown
KeyEnd -> keyEnd
KeyHome -> keyHome
KeyLeft -> keyLeft
KeyUp -> keyUp
KeyRight -> keyRight
KeyDown -> keyDown
KeySelect -> keySelect
KeyPrintScreen -> keyPrintScreen
KeyInsert -> keyInsert
KeyDelete -> keyDelete
KeyLGUI -> keyLGUI
KeyRGUI -> keyRGUI
KeyApplication -> keyApplication
KeyKP0 -> keyKP0
KeyKP1 -> keyKP1
KeyKP2 -> keyKP2
KeyKP3 -> keyKP3
KeyKP4 -> keyKP4
KeyKP5 -> keyKP5
KeyKP6 -> keyKP6
KeyKP7 -> keyKP7
KeyKP8 -> keyKP8
KeyKP9 -> keyKP9
KeyKPMultiply -> keyKPMultiply
KeyKPPlus -> keyKPPlus
KeyKPMinus -> keyKPMinus
KeyKPPeriod -> keyKPPeriod
KeyKPDivide -> keyKPDivide
KeyF1 -> keyF1
KeyF2 -> keyF2
KeyF3 -> keyF3
KeyF4 -> keyF4
KeyF5 -> keyF5
KeyF6 -> keyF6
KeyF7 -> keyF7
KeyF8 -> keyF8
KeyF9 -> keyF9
KeyF10 -> keyF10
KeyF11 -> keyF11
KeyF12 -> keyF12
KeyF13 -> keyF13
KeyF14 -> keyF14
KeyF15 -> keyF15
KeyF16 -> keyF16
KeyF17 -> keyF17
KeyF18 -> keyF18
KeyF19 -> keyF19
KeyF20 -> keyF20
KeyF21 -> keyF21
KeyF22 -> keyF22
KeyF23 -> keyF23
KeyF24 -> keyF24
KeyNumLockClear -> keyNumLockClear
KeyScrollLock -> keyScrollLock
KeyLShift -> keyLShift
KeyRShift -> keyRShift
KeyLCtrl -> keyLCtrl
KeyRCtrl -> keyRCtrl
KeyLAlt -> keyLAlt
KeyRAlt -> keyRAlt
KeyACBack -> keyACBack
KeyACBookMarks -> keyACBookMarks
KeyACForward -> keyACForward
KeyACHome -> keyACHome
KeyACRefresh -> keyACRefresh
KeyACSearch -> keyACSearch
KeyACStop -> keyACStop
KeyAgain -> keyAgain
KeyAltErase -> keyAltErase
KeyAmpersand -> keyAmpersand
KeyAT -> keyAT
KeyAudioMute -> keyAudioMute
KeyAudioNext -> keyAudioNext
KeyAudioPlay -> keyAudioPlay
KeyAudioPrev -> keyAudioPrev
KeyAudioStop -> keyAudioStop
KeyBackQuote -> keyBackQuote
KeyBackSlash -> keyBackSlash
KeyBrightnessDown -> keyBrightnessDown
KeyBrightnessUp -> keyBrightnessUp
KeyCalculator -> keyCalculator
KeyCancel -> keyCancel
KeyCaret -> keyCaret
KeyClear -> keyClear
KeyClearAgain -> keyClearAgain
KeyColon -> keyColon
KeyComma -> keyComma
KeyComputer -> keyComputer
KeyCopy -> keyCopy
KeyCRSel -> keyCRSel
KeyCurrencySubUnit -> keyCurrencySubUnit
KeyCurrencyUnit -> keyCurrencyUnit
KeyCut -> keyCut
KeyDecimalSeparator -> keyDecimalSeparator
KeyDisplaySwitch -> keyDisplaySwitch
KeyDollar -> keyDollar
KeyEject -> keyEject
KeyEquals -> keyEquals
KeyExclaim -> keyExclaim
KeyExsel -> keyExsel
KeyFind -> keyFind
KeyGreater -> keyGreater
KeyHash -> keyHash
KeyHelp -> keyHelp
KeyKBDillumDown -> keyKBDillumDown
KeyKBDillumToggle -> keyKBDillumToggle
KeyKBDillumUp -> keyKBDillumUp
KeyKP00 -> keyKP00
KeyKP000 -> keyKP000
KeyKPA -> keyKPA
KeyKPAmpersand -> keyKPAmpersand
KeyKPAT -> keyKPAT
KeyKPB -> keyKPB
KeyKPBackspace -> keyKPBackspace
KeyKPBinary -> keyKPBinary
KeyKPC -> keyKPC
KeyKPClear -> keyKPClear
KeyKPClearEntry -> keyKPClearEntry
KeyKPColon -> keyKPColon
KeyKPComma -> keyKPComma
KeyKPD -> keyKPD
KeyKPDBLAmpersand -> keyKPDBLAmpersand
KeyKPDBLVerticalBar -> keyKPDBLVerticalBar
KeyKPDecimal -> keyKPDecimal
KeyKPE -> keyKPE
KeyKPEquals -> keyKPEquals
KeyKPEqualsAS400 -> keyKPEqualsAS400
KeyKPExclaim -> keyKPExclaim
KeyKPF -> keyKPF
KeyKPGreater -> keyKPGreater
KeyKPHash -> keyKPHash
KeyKPHexadecimal -> keyKPHexadecimal
KeyKPLeftBrace -> keyKPLeftBrace
KeyKPLeftParen -> keyKPLeftParen
KeyKPLess -> keyKPLess
KeyKPMemAdd -> keyKPMemAdd
KeyKPMemClear -> keyKPMemClear
KeyKPMemDivide -> keyKPMemDivide
KeyKPMemMultiply -> keyKPMemMultiply
KeyKPMemRecall -> keyKPMemRecall
KeyKPMemStore -> keyKPMemStore
KeyKPMemSubtract -> keyKPMemSubtract
KeyKPOctal -> keyKPOctal
KeyKPPercent -> keyKPPercent
KeyKPPlusMinus -> keyKPPlusMinus
KeyKPPower -> keyKPPower
KeyKPRightBrace -> keyKPRightBrace
KeyKPRightParen -> keyKPRightParen
KeyKPSpace -> keyKPSpace
KeyKPTab -> keyKPTab
KeyKPVerticalBar -> keyKPVerticalBar
KeyKPXor -> keyKPXor
KeyLeftBracket -> keyLeftBracket
KeyLeftParen -> keyLeftParen
KeyLess -> keyLess
KeyMail -> keyMail
KeyMediaSelect -> keyMediaSelect
KeyMenu -> keyMenu
KeyMinus -> keyMinus
KeyMode -> keyMode
KeyMute -> keyMute
KeyOper -> keyOper
KeyOut -> keyOut
KeyPaste -> keyPaste
KeyPercent -> keyPercent
KeyPeriod -> keyPeriod
KeyPlus -> keyPlus
KeyPower -> keyPower
KeyPrior -> keyPrior
KeyQuestion -> keyQuestion
KeyQuote -> keyQuote
KeyQuoteDbl -> keyQuoteDbl
KeyRightBracket -> keyRightBracket
KeyRightParen -> keyRightParen
KeySemicolon -> keySemicolon
KeySeparator -> keySeparator
KeySlash -> keySlash
KeySleep -> keySleep
KeyStop -> keyStop
KeySysReq -> keySysReq
KeyThousandsSeparator -> keyThousandsSeparator
KeyUnderscore -> keyUnderscore
KeyUndo -> keyUndo
KeyVolumeDown -> keyVolumeDown
KeyVolumeUp -> keyVolumeUp
KeyWWW -> keyWWW
KeyUnknown -> keyUnknown
keyA :: Int
keyA = fromIntegral $ [C.pure| int {KEY_A} |]
keyB :: Int
keyB = fromIntegral $ [C.pure| int {KEY_B} |]
keyC :: Int
keyC = fromIntegral $ [C.pure| int {KEY_C} |]
keyD :: Int
keyD = fromIntegral $ [C.pure| int {KEY_D} |]
keyE :: Int
keyE = fromIntegral $ [C.pure| int {KEY_E} |]
keyF :: Int
keyF = fromIntegral $ [C.pure| int {KEY_F} |]
keyG :: Int
keyG = fromIntegral $ [C.pure| int {KEY_G} |]
keyH :: Int
keyH = fromIntegral $ [C.pure| int {KEY_H} |]
keyI :: Int
keyI = fromIntegral $ [C.pure| int {KEY_I} |]
keyJ :: Int
keyJ = fromIntegral $ [C.pure| int {KEY_J} |]
keyK :: Int
keyK = fromIntegral $ [C.pure| int {KEY_K} |]
keyL :: Int
keyL = fromIntegral $ [C.pure| int {KEY_L} |]
keyM :: Int
keyM = fromIntegral $ [C.pure| int {KEY_M} |]
keyN :: Int
keyN = fromIntegral $ [C.pure| int {KEY_N} |]
keyO :: Int
keyO = fromIntegral $ [C.pure| int {KEY_O} |]
keyP :: Int
keyP = fromIntegral $ [C.pure| int {KEY_P} |]
keyQ :: Int
keyQ = fromIntegral $ [C.pure| int {KEY_Q} |]
keyR :: Int
keyR = fromIntegral $ [C.pure| int {KEY_R} |]
keyS :: Int
keyS = fromIntegral $ [C.pure| int {KEY_S} |]
keyT :: Int
keyT = fromIntegral $ [C.pure| int {KEY_T} |]
keyU :: Int
keyU = fromIntegral $ [C.pure| int {KEY_U} |]
keyV :: Int
keyV = fromIntegral $ [C.pure| int {KEY_V} |]
keyW :: Int
keyW = fromIntegral $ [C.pure| int {KEY_W} |]
keyX :: Int
keyX = fromIntegral $ [C.pure| int {KEY_X} |]
keyY :: Int
keyY = fromIntegral $ [C.pure| int {KEY_Y} |]
keyZ :: Int
keyZ = fromIntegral $ [C.pure| int {KEY_Z} |]
key0 :: Int
key0 = fromIntegral $ [C.pure| int {KEY_0} |]
key1 :: Int
key1 = fromIntegral $ [C.pure| int {KEY_1} |]
key2 :: Int
key2 = fromIntegral $ [C.pure| int {KEY_2} |]
key3 :: Int
key3 = fromIntegral $ [C.pure| int {KEY_3} |]
key4 :: Int
key4 = fromIntegral $ [C.pure| int {KEY_4} |]
key5 :: Int
key5 = fromIntegral $ [C.pure| int {KEY_5} |]
key6 :: Int
key6 = fromIntegral $ [C.pure| int {KEY_6} |]
key7 :: Int
key7 = fromIntegral $ [C.pure| int {KEY_7} |]
key8 :: Int
key8 = fromIntegral $ [C.pure| int {KEY_8} |]
key9 :: Int
key9 = fromIntegral $ [C.pure| int {KEY_9} |]
keyBackspace :: Int
keyBackspace = fromIntegral $ [C.pure| int {KEY_BACKSPACE} |]
keyTab :: Int
keyTab = fromIntegral $ [C.pure| int {KEY_TAB} |]
keyReturn :: Int
keyReturn = fromIntegral $ [C.pure| int {KEY_RETURN} |]
keyReturn2 :: Int
keyReturn2 = fromIntegral $ [C.pure| int {KEY_RETURN2} |]
keyKPEnter :: Int
keyKPEnter = fromIntegral $ [C.pure| int {KEY_KP_ENTER} |]
keyShift :: Int
keyShift = fromIntegral $ [C.pure| int {KEY_SHIFT} |]
keyCtrl :: Int
keyCtrl = fromIntegral $ [C.pure| int {KEY_CTRL} |]
keyAlt :: Int
keyAlt = fromIntegral $ [C.pure| int {KEY_ALT} |]
keyGui :: Int
keyGui = fromIntegral $ [C.pure| int {KEY_GUI} |]
keyPause :: Int
keyPause = fromIntegral $ [C.pure| int {KEY_PAUSE} |]
keyCapsLock :: Int
keyCapsLock = fromIntegral $ [C.pure| int {KEY_CAPSLOCK} |]
keyEsc :: Int
keyEsc = fromIntegral $ [C.pure| int {KEY_ESCAPE} |]
keySpace :: Int
keySpace = fromIntegral $ [C.pure| int {KEY_SPACE} |]
keyPageUp :: Int
keyPageUp = fromIntegral $ [C.pure| int {KEY_PAGEUP} |]
keyPageDown :: Int
keyPageDown = fromIntegral $ [C.pure| int {KEY_PAGEDOWN} |]
keyEnd :: Int
keyEnd = fromIntegral $ [C.pure| int {KEY_END} |]
keyHome :: Int
keyHome = fromIntegral $ [C.pure| int {KEY_HOME} |]
keyLeft :: Int
keyLeft = fromIntegral $ [C.pure| int {KEY_LEFT} |]
keyUp :: Int
keyUp = fromIntegral $ [C.pure| int {KEY_UP} |]
keyRight :: Int
keyRight = fromIntegral $ [C.pure| int {KEY_RIGHT} |]
keyDown :: Int
keyDown = fromIntegral $ [C.pure| int {KEY_DOWN} |]
keySelect :: Int
keySelect = fromIntegral $ [C.pure| int {KEY_SELECT} |]
keyPrintScreen :: Int
keyPrintScreen = fromIntegral $ [C.pure| int {KEY_PRINTSCREEN} |]
keyInsert :: Int
keyInsert = fromIntegral $ [C.pure| int {KEY_INSERT} |]
keyDelete :: Int
keyDelete = fromIntegral $ [C.pure| int {KEY_DELETE} |]
keyLGUI :: Int
keyLGUI = fromIntegral $ [C.pure| int {KEY_LGUI} |]
keyRGUI :: Int
keyRGUI = fromIntegral $ [C.pure| int {KEY_RGUI} |]
keyApplication :: Int
keyApplication = fromIntegral $ [C.pure| int {KEY_APPLICATION} |]
keyKP0 :: Int
keyKP0 = fromIntegral $ [C.pure| int {KEY_KP_0} |]
keyKP1 :: Int
keyKP1 = fromIntegral $ [C.pure| int {KEY_KP_1} |]
keyKP2 :: Int
keyKP2 = fromIntegral $ [C.pure| int {KEY_KP_2} |]
keyKP3 :: Int
keyKP3 = fromIntegral $ [C.pure| int {KEY_KP_3} |]
keyKP4 :: Int
keyKP4 = fromIntegral $ [C.pure| int {KEY_KP_4} |]
keyKP5 :: Int
keyKP5 = fromIntegral $ [C.pure| int {KEY_KP_5} |]
keyKP6 :: Int
keyKP6 = fromIntegral $ [C.pure| int {KEY_KP_6} |]
keyKP7 :: Int
keyKP7 = fromIntegral $ [C.pure| int {KEY_KP_7} |]
keyKP8 :: Int
keyKP8 = fromIntegral $ [C.pure| int {KEY_KP_8} |]
keyKP9 :: Int
keyKP9 = fromIntegral $ [C.pure| int {KEY_KP_9} |]
keyKPMultiply :: Int
keyKPMultiply = fromIntegral $ [C.pure| int {KEY_KP_MULTIPLY} |]
keyKPPlus :: Int
keyKPPlus = fromIntegral $ [C.pure| int {KEY_KP_PLUS} |]
keyKPMinus :: Int
keyKPMinus = fromIntegral $ [C.pure| int {KEY_KP_MINUS} |]
keyKPPeriod :: Int
keyKPPeriod = fromIntegral $ [C.pure| int {KEY_KP_PERIOD} |]
keyKPDivide :: Int
keyKPDivide = fromIntegral $ [C.pure| int {KEY_KP_DIVIDE} |]
keyF1 :: Int
keyF1 = fromIntegral $ [C.pure| int {KEY_F1} |]
keyF2 :: Int
keyF2 = fromIntegral $ [C.pure| int {KEY_F2} |]
keyF3 :: Int
keyF3 = fromIntegral $ [C.pure| int {KEY_F3} |]
keyF4 :: Int
keyF4 = fromIntegral $ [C.pure| int {KEY_F4} |]
keyF5 :: Int
keyF5 = fromIntegral $ [C.pure| int {KEY_F5} |]
keyF6 :: Int
keyF6 = fromIntegral $ [C.pure| int {KEY_F6} |]
keyF7 :: Int
keyF7 = fromIntegral $ [C.pure| int {KEY_F7} |]
keyF8 :: Int
keyF8 = fromIntegral $ [C.pure| int {KEY_F8} |]
keyF9 :: Int
keyF9 = fromIntegral $ [C.pure| int {KEY_F9} |]
keyF10 :: Int
keyF10 = fromIntegral $ [C.pure| int {KEY_F10} |]
keyF11 :: Int
keyF11 = fromIntegral $ [C.pure| int {KEY_F11} |]
keyF12 :: Int
keyF12 = fromIntegral $ [C.pure| int {KEY_F12} |]
keyF13 :: Int
keyF13 = fromIntegral $ [C.pure| int {KEY_F13} |]
keyF14 :: Int
keyF14 = fromIntegral $ [C.pure| int {KEY_F14} |]
keyF15 :: Int
keyF15 = fromIntegral $ [C.pure| int {KEY_F15} |]
keyF16 :: Int
keyF16 = fromIntegral $ [C.pure| int {KEY_F16} |]
keyF17 :: Int
keyF17 = fromIntegral $ [C.pure| int {KEY_F17} |]
keyF18 :: Int
keyF18 = fromIntegral $ [C.pure| int {KEY_F18} |]
keyF19 :: Int
keyF19 = fromIntegral $ [C.pure| int {KEY_F19} |]
keyF20 :: Int
keyF20 = fromIntegral $ [C.pure| int {KEY_F20} |]
keyF21 :: Int
keyF21 = fromIntegral $ [C.pure| int {KEY_F21} |]
keyF22 :: Int
keyF22 = fromIntegral $ [C.pure| int {KEY_F22} |]
keyF23 :: Int
keyF23 = fromIntegral $ [C.pure| int {KEY_F23} |]
keyF24 :: Int
keyF24 = fromIntegral $ [C.pure| int {KEY_F24} |]
keyNumLockClear :: Int
keyNumLockClear = fromIntegral $ [C.pure| int {KEY_NUMLOCKCLEAR} |]
keyScrollLock :: Int
keyScrollLock = fromIntegral $ [C.pure| int {KEY_SCROLLLOCK} |]
keyLShift :: Int
keyLShift = fromIntegral $ [C.pure| int {KEY_LSHIFT} |]
keyRShift :: Int
keyRShift = fromIntegral $ [C.pure| int {KEY_RSHIFT} |]
keyLCtrl :: Int
keyLCtrl = fromIntegral $ [C.pure| int {KEY_LCTRL} |]
keyRCtrl :: Int
keyRCtrl = fromIntegral $ [C.pure| int {KEY_RCTRL} |]
keyLAlt :: Int
keyLAlt = fromIntegral $ [C.pure| int {KEY_LALT} |]
keyRAlt :: Int
keyRAlt = fromIntegral $ [C.pure| int {KEY_RALT} |]
keyACBack :: Int
keyACBack = fromIntegral $ [C.pure| int {KEY_AC_BACK} |]
keyACBookMarks :: Int
keyACBookMarks = fromIntegral $ [C.pure| int {KEY_AC_BOOKMARKS} |]
keyACForward :: Int
keyACForward = fromIntegral $ [C.pure| int {KEY_AC_FORWARD}|]
keyACHome :: Int
keyACHome = fromIntegral $ [C.pure| int {KEY_AC_HOME} |]
keyACRefresh :: Int
keyACRefresh = fromIntegral $ [C.pure| int {KEY_AC_REFRESH} |]
keyACSearch :: Int
keyACSearch = fromIntegral $ [C.pure| int {KEY_AC_SEARCH} |]
keyACStop :: Int
keyACStop = fromIntegral $ [C.pure| int {KEY_AC_STOP} |]
keyAgain :: Int
keyAgain = fromIntegral $ [C.pure| int {KEY_AGAIN} |]
keyAltErase :: Int
keyAltErase = fromIntegral $ [C.pure| int {KEY_ALTERASE} |]
keyAmpersand :: Int
keyAmpersand = fromIntegral $ [C.pure| int {KEY_AMPERSAND} |]
keyAT :: Int
keyAT = fromIntegral $ [C.pure| int {KEY_AT} |]
keyAudioMute :: Int
keyAudioMute = fromIntegral $ [C.pure| int {KEY_AUDIOMUTE} |]
keyAudioNext :: Int
keyAudioNext = fromIntegral $ [C.pure| int {KEY_AUDIONEXT} |]
keyAudioPlay :: Int
keyAudioPlay = fromIntegral $ [C.pure| int {KEY_AUDIOPLAY} |]
keyAudioPrev :: Int
keyAudioPrev = fromIntegral $ [C.pure| int {KEY_AUDIOPREV} |]
keyAudioStop :: Int
keyAudioStop = fromIntegral $ [C.pure| int {KEY_AUDIOSTOP} |]
keyBackQuote :: Int
keyBackQuote = fromIntegral $ [C.pure| int {KEY_BACKQUOTE} |]
keyBackSlash :: Int
keyBackSlash = fromIntegral $ [C.pure| int {KEY_BACKSLASH} |]
keyBrightnessDown :: Int
keyBrightnessDown = fromIntegral $ [C.pure| int {KEY_BRIGHTNESSDOWN} |]
keyBrightnessUp :: Int
keyBrightnessUp = fromIntegral $ [C.pure| int {KEY_BRIGHTNESSUP} |]
keyCalculator :: Int
keyCalculator = fromIntegral $ [C.pure| int {KEY_CALCULATOR} |]
keyCancel :: Int
keyCancel = fromIntegral $ [C.pure| int {KEY_CANCEL} |]
keyCaret :: Int
keyCaret = fromIntegral $ [C.pure| int {KEY_CARET} |]
keyClear :: Int
keyClear = fromIntegral $ [C.pure| int {KEY_CLEAR} |]
keyClearAgain :: Int
keyClearAgain = fromIntegral $ [C.pure| int {KEY_CLEARAGAIN} |]
keyColon :: Int
keyColon = fromIntegral $ [C.pure| int {KEY_COLON} |]
keyComma :: Int
keyComma = fromIntegral $ [C.pure| int {KEY_COMMA} |]
keyComputer :: Int
keyComputer = fromIntegral $ [C.pure| int {KEY_COMPUTER} |]
keyCopy :: Int
keyCopy = fromIntegral $ [C.pure| int {KEY_COPY} |]
keyCRSel :: Int
keyCRSel = fromIntegral $ [C.pure| int {KEY_CRSEL} |]
keyCurrencySubUnit :: Int
keyCurrencySubUnit = fromIntegral $ [C.pure| int {KEY_CURRENCYSUBUNIT} |]
keyCurrencyUnit :: Int
keyCurrencyUnit = fromIntegral $ [C.pure| int {KEY_CURRENCYUNIT} |]
keyCut :: Int
keyCut = fromIntegral $ [C.pure| int {KEY_CUT} |]
keyDecimalSeparator :: Int
keyDecimalSeparator = fromIntegral $ [C.pure| int {KEY_DECIMALSEPARATOR} |]
keyDisplaySwitch :: Int
keyDisplaySwitch = fromIntegral $ [C.pure| int {KEY_DISPLAYSWITCH} |]
keyDollar :: Int
keyDollar = fromIntegral $ [C.pure| int {KEY_DOLLAR} |]
keyEject :: Int
keyEject = fromIntegral $ [C.pure| int {KEY_EJECT} |]
keyEquals :: Int
keyEquals = fromIntegral $ [C.pure| int {KEY_EQUALS} |]
keyExclaim :: Int
keyExclaim = fromIntegral $ [C.pure| int {KEY_EXCLAIM} |]
keyExsel :: Int
keyExsel = fromIntegral $ [C.pure| int {KEY_EXSEL} |]
keyFind :: Int
keyFind = fromIntegral $ [C.pure| int {KEY_FIND} |]
keyGreater :: Int
keyGreater = fromIntegral $ [C.pure| int {KEY_GREATER} |]
keyHash :: Int
keyHash = fromIntegral $ [C.pure| int {KEY_HASH} |]
keyHelp :: Int
keyHelp = fromIntegral $ [C.pure| int {KEY_HELP} |]
keyKBDillumDown :: Int
keyKBDillumDown = fromIntegral $ [C.pure| int {KEY_KBDILLUMDOWN} |]
keyKBDillumToggle :: Int
keyKBDillumToggle = fromIntegral $ [C.pure| int {KEY_KBDILLUMTOGGLE} |]
keyKBDillumUp :: Int
keyKBDillumUp = fromIntegral $ [C.pure| int {KEY_KBDILLUMUP} |]
keyKP00 :: Int
keyKP00 = fromIntegral $ [C.pure| int {KEY_KP_00} |]
keyKP000 :: Int
keyKP000 = fromIntegral $ [C.pure| int {KEY_KP_000} |]
keyKPA :: Int
keyKPA = fromIntegral $ [C.pure| int {KEY_KP_A} |]
keyKPAmpersand :: Int
keyKPAmpersand = fromIntegral $ [C.pure| int {KEY_KP_AMPERSAND} |]
keyKPAT :: Int
keyKPAT = fromIntegral $ [C.pure| int {KEY_KP_AT} |]
keyKPB :: Int
keyKPB = fromIntegral $ [C.pure| int {KEY_KP_B} |]
keyKPBackspace :: Int
keyKPBackspace = fromIntegral $ [C.pure| int {KEY_KP_BACKSPACE} |]
keyKPBinary :: Int
keyKPBinary = fromIntegral $ [C.pure| int {KEY_KP_BINARY} |]
keyKPC :: Int
keyKPC = fromIntegral $ [C.pure| int {KEY_KP_C} |]
keyKPClear :: Int
keyKPClear = fromIntegral $ [C.pure| int {KEY_KP_CLEAR} |]
keyKPClearEntry :: Int
keyKPClearEntry = fromIntegral $ [C.pure| int {KEY_KP_CLEARENTRY} |]
keyKPColon :: Int
keyKPColon = fromIntegral $ [C.pure| int {KEY_KP_COLON} |]
keyKPComma :: Int
keyKPComma = fromIntegral $ [C.pure| int {KEY_KP_COMMA} |]
keyKPD :: Int
keyKPD = fromIntegral $ [C.pure| int {KEY_KP_D} |]
keyKPDBLAmpersand :: Int
keyKPDBLAmpersand = fromIntegral $ [C.pure| int {KEY_KP_DBLAMPERSAND} |]
keyKPDBLVerticalBar :: Int
keyKPDBLVerticalBar = fromIntegral $ [C.pure| int {KEY_KP_DBLVERTICALBAR} |]
keyKPDecimal :: Int
keyKPDecimal = fromIntegral $ [C.pure| int {KEY_KP_DECIMAL} |]
keyKPE :: Int
keyKPE = fromIntegral $ [C.pure| int {KEY_KP_E} |]
keyKPEquals :: Int
keyKPEquals = fromIntegral $ [C.pure| int {KEY_KP_EQUALS} |]
keyKPEqualsAS400 :: Int
keyKPEqualsAS400 = fromIntegral $ [C.pure| int {KEY_KP_EQUALSAS400} |]
keyKPExclaim :: Int
keyKPExclaim = fromIntegral $ [C.pure| int {KEY_KP_EXCLAM} |]
keyKPF :: Int
keyKPF = fromIntegral $ [C.pure| int {KEY_KP_F} |]
keyKPGreater :: Int
keyKPGreater = fromIntegral $ [C.pure| int {KEY_KP_GREATER} |]
keyKPHash :: Int
keyKPHash = fromIntegral $ [C.pure| int {KEY_KP_HASH} |]
keyKPHexadecimal :: Int
keyKPHexadecimal = fromIntegral $ [C.pure| int {KEY_KP_HEXADECIMAL} |]
keyKPLeftBrace :: Int
keyKPLeftBrace = fromIntegral $ [C.pure| int {KEY_KP_LEFTBRACE} |]
keyKPLeftParen :: Int
keyKPLeftParen = fromIntegral $ [C.pure| int {KEY_KP_LEFTPAREN} |]
keyKPLess :: Int
keyKPLess = fromIntegral $ [C.pure| int {KEY_KP_LESS} |]
keyKPMemAdd :: Int
keyKPMemAdd = fromIntegral $ [C.pure| int {KEY_KP_MEMADD} |]
keyKPMemClear :: Int
keyKPMemClear = fromIntegral $ [C.pure| int {KEY_KP_MEMCLEAR} |]
keyKPMemDivide :: Int
keyKPMemDivide = fromIntegral $ [C.pure| int {KEY_KP_MEMDIVIDE} |]
keyKPMemMultiply :: Int
keyKPMemMultiply = fromIntegral $ [C.pure| int {KEY_KP_MEMMULTIPLY} |]
keyKPMemRecall :: Int
keyKPMemRecall = fromIntegral $ [C.pure| int {KEY_KP_MEMRECALL} |]
keyKPMemStore :: Int
keyKPMemStore = fromIntegral $ [C.pure| int {KEY_KP_MEMSTORE} |]
keyKPMemSubtract :: Int
keyKPMemSubtract = fromIntegral $ [C.pure| int {KEY_KP_MEMSUBTRACT} |]
keyKPOctal :: Int
keyKPOctal = fromIntegral $ [C.pure| int {KEY_KP_OCTAL} |]
keyKPPercent :: Int
keyKPPercent = fromIntegral $ [C.pure| int {KEY_KP_PERCENT} |]
keyKPPlusMinus :: Int
keyKPPlusMinus = fromIntegral $ [C.pure| int {KEY_KP_PLUSMINUS} |]
keyKPPower :: Int
keyKPPower = fromIntegral $ [C.pure| int {KEY_KP_POWER} |]
keyKPRightBrace :: Int
keyKPRightBrace = fromIntegral $ [C.pure| int {KEY_KP_RIGHTBRACE} |]
keyKPRightParen :: Int
keyKPRightParen = fromIntegral $ [C.pure| int {KEY_KP_RIGHTPAREN} |]
keyKPSpace :: Int
keyKPSpace = fromIntegral $ [C.pure| int {KEY_KP_SPACE} |]
keyKPTab :: Int
keyKPTab = fromIntegral $ [C.pure| int {KEY_KP_TAB} |]
keyKPVerticalBar :: Int
keyKPVerticalBar = fromIntegral $ [C.pure| int {KEY_KP_VERTICALBAR} |]
keyKPXor :: Int
keyKPXor = fromIntegral $ [C.pure| int {KEY_KP_XOR} |]
keyLeftBracket :: Int
keyLeftBracket = fromIntegral $ [C.pure| int {KEY_LEFTBRACKET} |]
keyLeftParen :: Int
keyLeftParen = fromIntegral $ [C.pure| int {KEY_LEFTPAREN} |]
keyLess :: Int
keyLess = fromIntegral $ [C.pure| int {KEY_LESS} |]
keyMail :: Int
keyMail = fromIntegral $ [C.pure| int {KEY_MAIL} |]
keyMediaSelect :: Int
keyMediaSelect = fromIntegral $ [C.pure| int {KEY_MEDIASELECT} |]
keyMenu :: Int
keyMenu = fromIntegral $ [C.pure| int {KEY_MENU} |]
keyMinus :: Int
keyMinus = fromIntegral $ [C.pure| int {KEY_MINUS} |]
keyMode :: Int
keyMode = fromIntegral $ [C.pure| int {KEY_MODE} |]
keyMute :: Int
keyMute = fromIntegral $ [C.pure| int {KEY_MUTE} |]
keyOper :: Int
keyOper = fromIntegral $ [C.pure| int {KEY_OPER} |]
keyOut :: Int
keyOut = fromIntegral $ [C.pure| int {KEY_OUT} |]
keyPaste :: Int
keyPaste = fromIntegral $ [C.pure| int {KEY_PASTE} |]
keyPercent :: Int
keyPercent = fromIntegral $ [C.pure| int {KEY_PERCENT} |]
keyPeriod :: Int
keyPeriod = fromIntegral $ [C.pure| int {KEY_PERIOD} |]
keyPlus :: Int
keyPlus = fromIntegral $ [C.pure| int {KEY_PLUS} |]
keyPower :: Int
keyPower = fromIntegral $ [C.pure| int {KEY_POWER} |]
keyPrior :: Int
keyPrior = fromIntegral $ [C.pure| int {KEY_PRIOR} |]
keyQuestion :: Int
keyQuestion = fromIntegral $ [C.pure| int {KEY_QUESTION} |]
keyQuote :: Int
keyQuote = fromIntegral $ [C.pure| int {KEY_QUOTE} |]
keyQuoteDbl :: Int
keyQuoteDbl = fromIntegral $ [C.pure| int {KEY_QUOTEDBL} |]
keyRightBracket :: Int
keyRightBracket = fromIntegral $ [C.pure| int {KEY_RIGHTBRACKET} |]
keyRightParen :: Int
keyRightParen = fromIntegral $ [C.pure| int {KEY_RIGHTPAREN} |]
keySemicolon :: Int
keySemicolon = fromIntegral $ [C.pure| int {KEY_SEMICOLON} |]
keySeparator :: Int
keySeparator = fromIntegral $ [C.pure| int {KEY_SEPARATOR} |]
keySlash :: Int
keySlash = fromIntegral $ [C.pure| int {KEY_SLASH} |]
keySleep :: Int
keySleep = fromIntegral $ [C.pure| int {KEY_SLEEP} |]
keyStop :: Int
keyStop = fromIntegral $ [C.pure| int {KEY_STOP} |]
keySysReq :: Int
keySysReq = fromIntegral $ [C.pure| int {KEY_SYSREQ} |]
keyThousandsSeparator :: Int
keyThousandsSeparator = fromIntegral $ [C.pure| int {KEY_THOUSANDSSEPARATOR} |]
keyUnderscore :: Int
keyUnderscore = fromIntegral $ [C.pure| int {KEY_UNDERSCORE} |]
keyUndo :: Int
keyUndo = fromIntegral $ [C.pure| int {KEY_UNDO} |]
keyVolumeDown :: Int
keyVolumeDown = fromIntegral $ [C.pure| int {KEY_VOLUMEDOWN} |]
keyVolumeUp :: Int
keyVolumeUp = fromIntegral $ [C.pure| int {KEY_VOLUMEUP} |]
keyWWW :: Int
keyWWW = fromIntegral $ [C.pure| int {KEY_WWW} |]
keyUnknown :: Int
keyUnknown = fromIntegral $ [C.pure| int {KEY_UNKNOWN}|]
data Scancode =
ScancodeUnknown
| ScancodeCtrl
| ScancodeShift
| ScancodeAlt
| ScancodeGui
| ScancodeA
| ScancodeB
| ScancodeC
| ScancodeD
| ScancodeE
| ScancodeF
| ScancodeG
| ScancodeH
| ScancodeI
| ScancodeJ
| ScancodeK
| ScancodeL
| ScancodeM
| ScancodeN
| ScancodeO
| ScancodeP
| ScancodeQ
| ScancodeR
| ScancodeS
| ScancodeT
| ScancodeU
| ScancodeV
| ScancodeW
| ScancodeX
| ScancodeY
| ScancodeZ
| Scancode1
| Scancode2
| Scancode3
| Scancode4
| Scancode5
| Scancode6
| Scancode7
| Scancode8
| Scancode9
| Scancode0
| ScancodeReturn
| ScancodeEscape
| ScancodeBackspace
| ScancodeTab
| ScancodeSpace
| ScancodeMinus
| ScancodeEquals
| ScancodeLeftBracket
| ScancodeRightBracket
| ScancodeBackslash
| ScancodeNonushash
| ScancodeSemicolon
| ScancodeApostrophe
| ScancodeGrave
| ScancodeComma
| ScancodePeriod
| ScancodeSlash
| ScancodeCapslock
| ScancodeF1
| ScancodeF2
| ScancodeF3
| ScancodeF4
| ScancodeF5
| ScancodeF6
| ScancodeF7
| ScancodeF8
| ScancodeF9
| ScancodeF10
| ScancodeF11
| ScancodeF12
| ScancodePrintScreen
| ScancodeScrolLlock
| ScancodePause
| ScancodeInsert
| ScancodeHome
| ScancodePageUp
| ScancodeDelete
| ScancodeEnd
| ScancodePageDown
| ScancodeRight
| ScancodeLeft
| ScancodeDown
| ScancodeUp
| ScancodeNumLockClear
| ScancodeKpDivide
| ScancodeKpMultiply
| ScancodeKpMinus
| ScancodeKpPlus
| ScancodeKpEnter
| ScancodeKp1
| ScancodeKp2
| ScancodeKp3
| ScancodeKp4
| ScancodeKp5
| ScancodeKp6
| ScancodeKp7
| ScancodeKp8
| ScancodeKp9
| ScancodeKp0
| ScancodeKpPeriod
| ScancodeNonusbackslash
| ScancodeApplication
| ScancodePower
| ScancodeKpEquals
| ScancodeF13
| ScancodeF14
| ScancodeF15
| ScancodeF16
| ScancodeF17
| ScancodeF18
| ScancodeF19
| ScancodeF20
| ScancodeF21
| ScancodeF22
| ScancodeF23
| ScancodeF24
| ScancodeExecute
| ScancodeHelp
| ScancodeMenu
| ScancodeSelect
| ScancodeStop
| ScancodeAgain
| ScancodeUndo
| ScancodeCut
| ScancodeCopy
| ScancodePaste
| ScancodeFind
| ScancodeMute
| ScancodeVolumeUp
| ScancodeVolumeDown
| ScancodeKpComma
| ScancodeKpEqualsAs400
| ScancodeInternational1
| ScancodeInternational2
| ScancodeInternational3
| ScancodeInternational4
| ScancodeInternational5
| ScancodeInternational6
| ScancodeInternational7
| ScancodeInternational8
| ScancodeInternational9
| ScancodeLang1
| ScancodeLang2
| ScancodeLang3
| ScancodeLang4
| ScancodeLang5
| ScancodeLang6
| ScancodeLang7
| ScancodeLang8
| ScancodeLang9
| ScancodeAltErase
| ScancodeSysReq
| ScancodeCancel
| ScancodeClear
| ScancodePrior
| ScancodeReturn2
| ScancodeSeparator
| ScancodeOut
| ScancodeOper
| ScancodeClearAgain
| ScancodeCrsel
| ScancodeExsel
| ScancodeKp00
| ScancodeKp000
| ScancodeThousandsSeparator
| ScancodeDecimalSeparator
| ScancodeCurrencyUnit
| ScancodeCurrencySubUnit
| ScancodeKpLeftParen
| ScancodeKpRightParen
| ScancodeKpLeftBrace
| ScancodeKpRightBrace
| ScancodeKpTab
| ScancodeKpBackspace
| ScancodeKpA
| ScancodeKpB
| ScancodeKpC
| ScancodeKpD
| ScancodeKpE
| ScancodeKpF
| ScancodeKpXor
| ScancodeKpPower
| ScancodeKpPercent
| ScancodeKpLess
| ScancodeKpGreater
| ScancodeKpAmpersand
| ScancodeKpDblAmpersand
| ScancodeKpVerticalBar
| ScancodeKpDblverticalBar
| ScancodeKpColon
| ScancodeKpHash
| ScancodeKpSpace
| ScancodeKpAt
| ScancodeKpExclam
| ScancodeKpMemStore
| ScancodeKpMemRecall
| ScancodeKpMemClear
| ScancodeKpMemAdd
| ScancodeKpMemSubtract
| ScancodeKpMemMultiply
| ScancodeKpMemDivide
| ScancodeKpPlusMinus
| ScancodeKpClear
| ScancodeKpClearEntry
| ScancodeKpBinary
| ScancodeKpOctal
| ScancodeKpDecimal
| ScancodeKpHexadecimal
| ScancodeLCtrl
| ScancodeLShift
| ScancodeLAlt
| ScancodeLGui
| ScancodeRCtrl
| ScancodeRShift
| ScancodeRAlt
| ScancodeRGui
| ScancodeMode
| ScancodeAudioNext
| ScancodeAudioPrev
| ScancodeAudioStop
| ScancodeAudioPlay
| ScancodeAudioMute
| ScancodeMediaSelect
| ScancodeWww
| ScancodeMail
| ScancodeCalculator
| ScancodeComputer
| ScancodeAcSearch
| ScancodeAcHome
| ScancodeAcBack
| ScancodeAcForward
| ScancodeAcStop
| ScancodeAcRefresh
| ScancodeAcBookmarks
| ScancodeBrightnessDown
| ScancodeBrightnessUp
| ScancodeDisplaySwitch
| ScancodeKbdillumToggle
| ScancodeKbdillumDown
| ScancodeKbdillumUp
| ScancodeEject
| ScancodeSleep
| ScancodeApp1
| ScancodeApp2
deriving (Eq, Ord, Show, Read, Bounded, Generic)
instance Enum Scancode where
fromEnum = toUrhoScancode
{-# INLINE fromEnum #-}
toEnum = fromUrhoScancode
{-# INLINE toEnum #-}
fromUrhoScancode :: Int -> Scancode
fromUrhoScancode i
| i == scancodeUnknown = ScancodeUnknown
| i == scancodeCtrl = ScancodeCtrl
| i == scancodeShift = ScancodeShift
| i == scancodeAlt = ScancodeAlt
| i == scancodeGui = ScancodeGui
| i == scancodeA = ScancodeA
| i == scancodeB = ScancodeB
| i == scancodeC = ScancodeC
| i == scancodeD = ScancodeD
| i == scancodeE = ScancodeE
| i == scancodeF = ScancodeF
| i == scancodeG = ScancodeG
| i == scancodeH = ScancodeH
| i == scancodeI = ScancodeI
| i == scancodeJ = ScancodeJ
| i == scancodeK = ScancodeK
| i == scancodeL = ScancodeL
| i == scancodeM = ScancodeM
| i == scancodeN = ScancodeN
| i == scancodeO = ScancodeO
| i == scancodeP = ScancodeP
| i == scancodeQ = ScancodeQ
| i == scancodeR = ScancodeR
| i == scancodeS = ScancodeS
| i == scancodeT = ScancodeT
| i == scancodeU = ScancodeU
| i == scancodeV = ScancodeV
| i == scancodeW = ScancodeW
| i == scancodeX = ScancodeX
| i == scancodeY = ScancodeY
| i == scancodeZ = ScancodeZ
| i == scancode1 = Scancode1
| i == scancode2 = Scancode2
| i == scancode3 = Scancode3
| i == scancode4 = Scancode4
| i == scancode5 = Scancode5
| i == scancode6 = Scancode6
| i == scancode7 = Scancode7
| i == scancode8 = Scancode8
| i == scancode9 = Scancode9
| i == scancode0 = Scancode0
| i == scancodeReturn = ScancodeReturn
| i == scancodeEscape = ScancodeEscape
| i == scancodeBackspace = ScancodeBackspace
| i == scancodeTab = ScancodeTab
| i == scancodeSpace = ScancodeSpace
| i == scancodeMinus = ScancodeMinus
| i == scancodeEquals = ScancodeEquals
| i == scancodeLeftBracket = ScancodeLeftBracket
| i == scancodeRightBracket = ScancodeRightBracket
| i == scancodeBackslash = ScancodeBackslash
| i == scancodeNonushash = ScancodeNonushash
| i == scancodeSemicolon = ScancodeSemicolon
| i == scancodeApostrophe = ScancodeApostrophe
| i == scancodeGrave = ScancodeGrave
| i == scancodeComma = ScancodeComma
| i == scancodePeriod = ScancodePeriod
| i == scancodeSlash = ScancodeSlash
| i == scancodeCapslock = ScancodeCapslock
| i == scancodeF1 = ScancodeF1
| i == scancodeF2 = ScancodeF2
| i == scancodeF3 = ScancodeF3
| i == scancodeF4 = ScancodeF4
| i == scancodeF5 = ScancodeF5
| i == scancodeF6 = ScancodeF6
| i == scancodeF7 = ScancodeF7
| i == scancodeF8 = ScancodeF8
| i == scancodeF9 = ScancodeF9
| i == scancodeF10 = ScancodeF10
| i == scancodeF11 = ScancodeF11
| i == scancodeF12 = ScancodeF12
| i == scancodePrintScreen = ScancodePrintScreen
| i == scancodeScrolLlock = ScancodeScrolLlock
| i == scancodePause = ScancodePause
| i == scancodeInsert = ScancodeInsert
| i == scancodeHome = ScancodeHome
| i == scancodePageUp = ScancodePageUp
| i == scancodeDelete = ScancodeDelete
| i == scancodeEnd = ScancodeEnd
| i == scancodePageDown = ScancodePageDown
| i == scancodeRight = ScancodeRight
| i == scancodeLeft = ScancodeLeft
| i == scancodeDown = ScancodeDown
| i == scancodeUp = ScancodeUp
| i == scancodeNumLockClear = ScancodeNumLockClear
| i == scancodeKpDivide = ScancodeKpDivide
| i == scancodeKpMultiply = ScancodeKpMultiply
| i == scancodeKpMinus = ScancodeKpMinus
| i == scancodeKpPlus = ScancodeKpPlus
| i == scancodeKpEnter = ScancodeKpEnter
| i == scancodeKp1 = ScancodeKp1
| i == scancodeKp2 = ScancodeKp2
| i == scancodeKp3 = ScancodeKp3
| i == scancodeKp4 = ScancodeKp4
| i == scancodeKp5 = ScancodeKp5
| i == scancodeKp6 = ScancodeKp6
| i == scancodeKp7 = ScancodeKp7
| i == scancodeKp8 = ScancodeKp8
| i == scancodeKp9 = ScancodeKp9
| i == scancodeKp0 = ScancodeKp0
| i == scancodeKpPeriod = ScancodeKpPeriod
| i == scancodeNonusbackslash = ScancodeNonusbackslash
| i == scancodeApplication = ScancodeApplication
| i == scancodePower = ScancodePower
| i == scancodeKpEquals = ScancodeKpEquals
| i == scancodeF13 = ScancodeF13
| i == scancodeF14 = ScancodeF14
| i == scancodeF15 = ScancodeF15
| i == scancodeF16 = ScancodeF16
| i == scancodeF17 = ScancodeF17
| i == scancodeF18 = ScancodeF18
| i == scancodeF19 = ScancodeF19
| i == scancodeF20 = ScancodeF20
| i == scancodeF21 = ScancodeF21
| i == scancodeF22 = ScancodeF22
| i == scancodeF23 = ScancodeF23
| i == scancodeF24 = ScancodeF24
| i == scancodeExecute = ScancodeExecute
| i == scancodeHelp = ScancodeHelp
| i == scancodeMenu = ScancodeMenu
| i == scancodeSelect = ScancodeSelect
| i == scancodeStop = ScancodeStop
| i == scancodeAgain = ScancodeAgain
| i == scancodeUndo = ScancodeUndo
| i == scancodeCut = ScancodeCut
| i == scancodeCopy = ScancodeCopy
| i == scancodePaste = ScancodePaste
| i == scancodeFind = ScancodeFind
| i == scancodeMute = ScancodeMute
| i == scancodeVolumeUp = ScancodeVolumeUp
| i == scancodeVolumeDown = ScancodeVolumeDown
| i == scancodeKpComma = ScancodeKpComma
| i == scancodeKpEqualsAs400 = ScancodeKpEqualsAs400
| i == scancodeInternational1 = ScancodeInternational1
| i == scancodeInternational2 = ScancodeInternational2
| i == scancodeInternational3 = ScancodeInternational3
| i == scancodeInternational4 = ScancodeInternational4
| i == scancodeInternational5 = ScancodeInternational5
| i == scancodeInternational6 = ScancodeInternational6
| i == scancodeInternational7 = ScancodeInternational7
| i == scancodeInternational8 = ScancodeInternational8
| i == scancodeInternational9 = ScancodeInternational9
| i == scancodeLang1 = ScancodeLang1
| i == scancodeLang2 = ScancodeLang2
| i == scancodeLang3 = ScancodeLang3
| i == scancodeLang4 = ScancodeLang4
| i == scancodeLang5 = ScancodeLang5
| i == scancodeLang6 = ScancodeLang6
| i == scancodeLang7 = ScancodeLang7
| i == scancodeLang8 = ScancodeLang8
| i == scancodeLang9 = ScancodeLang9
| i == scancodeAltErase = ScancodeAltErase
| i == scancodeSysReq = ScancodeSysReq
| i == scancodeCancel = ScancodeCancel
| i == scancodeClear = ScancodeClear
| i == scancodePrior = ScancodePrior
| i == scancodeReturn2 = ScancodeReturn2
| i == scancodeSeparator = ScancodeSeparator
| i == scancodeOut = ScancodeOut
| i == scancodeOper = ScancodeOper
| i == scancodeClearAgain = ScancodeClearAgain
| i == scancodeCrsel = ScancodeCrsel
| i == scancodeExsel = ScancodeExsel
| i == scancodeKp00 = ScancodeKp00
| i == scancodeKp000 = ScancodeKp000
| i == scancodeThousandsSeparator = ScancodeThousandsSeparator
| i == scancodeDecimalSeparator = ScancodeDecimalSeparator
| i == scancodeCurrencyUnit = ScancodeCurrencyUnit
| i == scancodeCurrencySubUnit = ScancodeCurrencySubUnit
| i == scancodeKpLeftParen = ScancodeKpLeftParen
| i == scancodeKpRightParen = ScancodeKpRightParen
| i == scancodeKpLeftBrace = ScancodeKpLeftBrace
| i == scancodeKpRightBrace = ScancodeKpRightBrace
| i == scancodeKpTab = ScancodeKpTab
| i == scancodeKpBackspace = ScancodeKpBackspace
| i == scancodeKpA = ScancodeKpA
| i == scancodeKpB = ScancodeKpB
| i == scancodeKpC = ScancodeKpC
| i == scancodeKpD = ScancodeKpD
| i == scancodeKpE = ScancodeKpE
| i == scancodeKpF = ScancodeKpF
| i == scancodeKpXor = ScancodeKpXor
| i == scancodeKpPower = ScancodeKpPower
| i == scancodeKpPercent = ScancodeKpPercent
| i == scancodeKpLess = ScancodeKpLess
| i == scancodeKpGreater = ScancodeKpGreater
| i == scancodeKpAmpersand = ScancodeKpAmpersand
| i == scancodeKpDblAmpersand = ScancodeKpDblAmpersand
| i == scancodeKpVerticalBar = ScancodeKpVerticalBar
| i == scancodeKpDblverticalBar = ScancodeKpDblverticalBar
| i == scancodeKpColon = ScancodeKpColon
| i == scancodeKpHash = ScancodeKpHash
| i == scancodeKpSpace = ScancodeKpSpace
| i == scancodeKpAt = ScancodeKpAt
| i == scancodeKpExclam = ScancodeKpExclam
| i == scancodeKpMemStore = ScancodeKpMemStore
| i == scancodeKpMemRecall = ScancodeKpMemRecall
| i == scancodeKpMemClear = ScancodeKpMemClear
| i == scancodeKpMemAdd = ScancodeKpMemAdd
| i == scancodeKpMemSubtract = ScancodeKpMemSubtract
| i == scancodeKpMemMultiply = ScancodeKpMemMultiply
| i == scancodeKpMemDivide = ScancodeKpMemDivide
| i == scancodeKpPlusMinus = ScancodeKpPlusMinus
| i == scancodeKpClear = ScancodeKpClear
| i == scancodeKpClearEntry = ScancodeKpClearEntry
| i == scancodeKpBinary = ScancodeKpBinary
| i == scancodeKpOctal = ScancodeKpOctal
| i == scancodeKpDecimal = ScancodeKpDecimal
| i == scancodeKpHexadecimal = ScancodeKpHexadecimal
| i == scancodeLCtrl = ScancodeLCtrl
| i == scancodeLShift = ScancodeLShift
| i == scancodeLAlt = ScancodeLAlt
| i == scancodeLGui = ScancodeLGui
| i == scancodeRCtrl = ScancodeRCtrl
| i == scancodeRShift = ScancodeRShift
| i == scancodeRAlt = ScancodeRAlt
| i == scancodeRGui = ScancodeRGui
| i == scancodeMode = ScancodeMode
| i == scancodeAudioNext = ScancodeAudioNext
| i == scancodeAudioPrev = ScancodeAudioPrev
| i == scancodeAudioStop = ScancodeAudioStop
| i == scancodeAudioPlay = ScancodeAudioPlay
| i == scancodeAudioMute = ScancodeAudioMute
| i == scancodeMediaSelect = ScancodeMediaSelect
| i == scancodeWww = ScancodeWww
| i == scancodeMail = ScancodeMail
| i == scancodeCalculator = ScancodeCalculator
| i == scancodeComputer = ScancodeComputer
| i == scancodeAcSearch = ScancodeAcSearch
| i == scancodeAcHome = ScancodeAcHome
| i == scancodeAcBack = ScancodeAcBack
| i == scancodeAcForward = ScancodeAcForward
| i == scancodeAcStop = ScancodeAcStop
| i == scancodeAcRefresh = ScancodeAcRefresh
| i == scancodeAcBookmarks = ScancodeAcBookmarks
| i == scancodeBrightnessDown = ScancodeBrightnessDown
| i == scancodeBrightnessUp = ScancodeBrightnessUp
| i == scancodeDisplaySwitch = ScancodeDisplaySwitch
| i == scancodeKbdillumToggle = ScancodeKbdillumToggle
| i == scancodeKbdillumDown = ScancodeKbdillumDown
| i == scancodeKbdillumUp = ScancodeKbdillumUp
| i == scancodeEject = ScancodeEject
| i == scancodeSleep = ScancodeSleep
| i == scancodeApp1 = ScancodeApp1
| i == scancodeApp2 = ScancodeApp2
| otherwise = ScancodeUnknown
toUrhoScancode :: Scancode -> Int
toUrhoScancode i = case i of
ScancodeUnknown -> scancodeUnknown
ScancodeCtrl -> scancodeCtrl
ScancodeShift -> scancodeShift
ScancodeAlt -> scancodeAlt
ScancodeGui -> scancodeGui
ScancodeA -> scancodeA
ScancodeB -> scancodeB
ScancodeC -> scancodeC
ScancodeD -> scancodeD
ScancodeE -> scancodeE
ScancodeF -> scancodeF
ScancodeG -> scancodeG
ScancodeH -> scancodeH
ScancodeI -> scancodeI
ScancodeJ -> scancodeJ
ScancodeK -> scancodeK
ScancodeL -> scancodeL
ScancodeM -> scancodeM
ScancodeN -> scancodeN
ScancodeO -> scancodeO
ScancodeP -> scancodeP
ScancodeQ -> scancodeQ
ScancodeR -> scancodeR
ScancodeS -> scancodeS
ScancodeT -> scancodeT
ScancodeU -> scancodeU
ScancodeV -> scancodeV
ScancodeW -> scancodeW
ScancodeX -> scancodeX
ScancodeY -> scancodeY
ScancodeZ -> scancodeZ
Scancode1 -> scancode1
Scancode2 -> scancode2
Scancode3 -> scancode3
Scancode4 -> scancode4
Scancode5 -> scancode5
Scancode6 -> scancode6
Scancode7 -> scancode7
Scancode8 -> scancode8
Scancode9 -> scancode9
Scancode0 -> scancode0
ScancodeReturn -> scancodeReturn
ScancodeEscape -> scancodeEscape
ScancodeBackspace -> scancodeBackspace
ScancodeTab -> scancodeTab
ScancodeSpace -> scancodeSpace
ScancodeMinus -> scancodeMinus
ScancodeEquals -> scancodeEquals
ScancodeLeftBracket -> scancodeLeftBracket
ScancodeRightBracket -> scancodeRightBracket
ScancodeBackslash -> scancodeBackslash
ScancodeNonushash -> scancodeNonushash
ScancodeSemicolon -> scancodeSemicolon
ScancodeApostrophe -> scancodeApostrophe
ScancodeGrave -> scancodeGrave
ScancodeComma -> scancodeComma
ScancodePeriod -> scancodePeriod
ScancodeSlash -> scancodeSlash
ScancodeCapslock -> scancodeCapslock
ScancodeF1 -> scancodeF1
ScancodeF2 -> scancodeF2
ScancodeF3 -> scancodeF3
ScancodeF4 -> scancodeF4
ScancodeF5 -> scancodeF5
ScancodeF6 -> scancodeF6
ScancodeF7 -> scancodeF7
ScancodeF8 -> scancodeF8
ScancodeF9 -> scancodeF9
ScancodeF10 -> scancodeF10
ScancodeF11 -> scancodeF11
ScancodeF12 -> scancodeF12
ScancodePrintScreen -> scancodePrintScreen
ScancodeScrolLlock -> scancodeScrolLlock
ScancodePause -> scancodePause
ScancodeInsert -> scancodeInsert
ScancodeHome -> scancodeHome
ScancodePageUp -> scancodePageUp
ScancodeDelete -> scancodeDelete
ScancodeEnd -> scancodeEnd
ScancodePageDown -> scancodePageDown
ScancodeRight -> scancodeRight
ScancodeLeft -> scancodeLeft
ScancodeDown -> scancodeDown
ScancodeUp -> scancodeUp
ScancodeNumLockClear -> scancodeNumLockClear
ScancodeKpDivide -> scancodeKpDivide
ScancodeKpMultiply -> scancodeKpMultiply
ScancodeKpMinus -> scancodeKpMinus
ScancodeKpPlus -> scancodeKpPlus
ScancodeKpEnter -> scancodeKpEnter
ScancodeKp1 -> scancodeKp1
ScancodeKp2 -> scancodeKp2
ScancodeKp3 -> scancodeKp3
ScancodeKp4 -> scancodeKp4
ScancodeKp5 -> scancodeKp5
ScancodeKp6 -> scancodeKp6
ScancodeKp7 -> scancodeKp7
ScancodeKp8 -> scancodeKp8
ScancodeKp9 -> scancodeKp9
ScancodeKp0 -> scancodeKp0
ScancodeKpPeriod -> scancodeKpPeriod
ScancodeNonusbackslash -> scancodeNonusbackslash
ScancodeApplication -> scancodeApplication
ScancodePower -> scancodePower
ScancodeKpEquals -> scancodeKpEquals
ScancodeF13 -> scancodeF13
ScancodeF14 -> scancodeF14
ScancodeF15 -> scancodeF15
ScancodeF16 -> scancodeF16
ScancodeF17 -> scancodeF17
ScancodeF18 -> scancodeF18
ScancodeF19 -> scancodeF19
ScancodeF20 -> scancodeF20
ScancodeF21 -> scancodeF21
ScancodeF22 -> scancodeF22
ScancodeF23 -> scancodeF23
ScancodeF24 -> scancodeF24
ScancodeExecute -> scancodeExecute
ScancodeHelp -> scancodeHelp
ScancodeMenu -> scancodeMenu
ScancodeSelect -> scancodeSelect
ScancodeStop -> scancodeStop
ScancodeAgain -> scancodeAgain
ScancodeUndo -> scancodeUndo
ScancodeCut -> scancodeCut
ScancodeCopy -> scancodeCopy
ScancodePaste -> scancodePaste
ScancodeFind -> scancodeFind
ScancodeMute -> scancodeMute
ScancodeVolumeUp -> scancodeVolumeUp
ScancodeVolumeDown -> scancodeVolumeDown
ScancodeKpComma -> scancodeKpComma
ScancodeKpEqualsAs400 -> scancodeKpEqualsAs400
ScancodeInternational1 -> scancodeInternational1
ScancodeInternational2 -> scancodeInternational2
ScancodeInternational3 -> scancodeInternational3
ScancodeInternational4 -> scancodeInternational4
ScancodeInternational5 -> scancodeInternational5
ScancodeInternational6 -> scancodeInternational6
ScancodeInternational7 -> scancodeInternational7
ScancodeInternational8 -> scancodeInternational8
ScancodeInternational9 -> scancodeInternational9
ScancodeLang1 -> scancodeLang1
ScancodeLang2 -> scancodeLang2
ScancodeLang3 -> scancodeLang3
ScancodeLang4 -> scancodeLang4
ScancodeLang5 -> scancodeLang5
ScancodeLang6 -> scancodeLang6
ScancodeLang7 -> scancodeLang7
ScancodeLang8 -> scancodeLang8
ScancodeLang9 -> scancodeLang9
ScancodeAltErase -> scancodeAltErase
ScancodeSysReq -> scancodeSysReq
ScancodeCancel -> scancodeCancel
ScancodeClear -> scancodeClear
ScancodePrior -> scancodePrior
ScancodeReturn2 -> scancodeReturn2
ScancodeSeparator -> scancodeSeparator
ScancodeOut -> scancodeOut
ScancodeOper -> scancodeOper
ScancodeClearAgain -> scancodeClearAgain
ScancodeCrsel -> scancodeCrsel
ScancodeExsel -> scancodeExsel
ScancodeKp00 -> scancodeKp00
ScancodeKp000 -> scancodeKp000
ScancodeThousandsSeparator -> scancodeThousandsSeparator
ScancodeDecimalSeparator -> scancodeDecimalSeparator
ScancodeCurrencyUnit -> scancodeCurrencyUnit
ScancodeCurrencySubUnit -> scancodeCurrencySubUnit
ScancodeKpLeftParen -> scancodeKpLeftParen
ScancodeKpRightParen -> scancodeKpRightParen
ScancodeKpLeftBrace -> scancodeKpLeftBrace
ScancodeKpRightBrace -> scancodeKpRightBrace
ScancodeKpTab -> scancodeKpTab
ScancodeKpBackspace -> scancodeKpBackspace
ScancodeKpA -> scancodeKpA
ScancodeKpB -> scancodeKpB
ScancodeKpC -> scancodeKpC
ScancodeKpD -> scancodeKpD
ScancodeKpE -> scancodeKpE
ScancodeKpF -> scancodeKpF
ScancodeKpXor -> scancodeKpXor
ScancodeKpPower -> scancodeKpPower
ScancodeKpPercent -> scancodeKpPercent
ScancodeKpLess -> scancodeKpLess
ScancodeKpGreater -> scancodeKpGreater
ScancodeKpAmpersand -> scancodeKpAmpersand
ScancodeKpDblAmpersand -> scancodeKpDblAmpersand
ScancodeKpVerticalBar -> scancodeKpVerticalBar
ScancodeKpDblverticalBar -> scancodeKpDblverticalBar
ScancodeKpColon -> scancodeKpColon
ScancodeKpHash -> scancodeKpHash
ScancodeKpSpace -> scancodeKpSpace
ScancodeKpAt -> scancodeKpAt
ScancodeKpExclam -> scancodeKpExclam
ScancodeKpMemStore -> scancodeKpMemStore
ScancodeKpMemRecall -> scancodeKpMemRecall
ScancodeKpMemClear -> scancodeKpMemClear
ScancodeKpMemAdd -> scancodeKpMemAdd
ScancodeKpMemSubtract -> scancodeKpMemSubtract
ScancodeKpMemMultiply -> scancodeKpMemMultiply
ScancodeKpMemDivide -> scancodeKpMemDivide
ScancodeKpPlusMinus -> scancodeKpPlusMinus
ScancodeKpClear -> scancodeKpClear
ScancodeKpClearEntry -> scancodeKpClearEntry
ScancodeKpBinary -> scancodeKpBinary
ScancodeKpOctal -> scancodeKpOctal
ScancodeKpDecimal -> scancodeKpDecimal
ScancodeKpHexadecimal -> scancodeKpHexadecimal
ScancodeLCtrl -> scancodeLCtrl
ScancodeLShift -> scancodeLShift
ScancodeLAlt -> scancodeLAlt
ScancodeLGui -> scancodeLGui
ScancodeRCtrl -> scancodeRCtrl
ScancodeRShift -> scancodeRShift
ScancodeRAlt -> scancodeRAlt
ScancodeRGui -> scancodeRGui
ScancodeMode -> scancodeMode
ScancodeAudioNext -> scancodeAudioNext
ScancodeAudioPrev -> scancodeAudioPrev
ScancodeAudioStop -> scancodeAudioStop
ScancodeAudioPlay -> scancodeAudioPlay
ScancodeAudioMute -> scancodeAudioMute
ScancodeMediaSelect -> scancodeMediaSelect
ScancodeWww -> scancodeWww
ScancodeMail -> scancodeMail
ScancodeCalculator -> scancodeCalculator
ScancodeComputer -> scancodeComputer
ScancodeAcSearch -> scancodeAcSearch
ScancodeAcHome -> scancodeAcHome
ScancodeAcBack -> scancodeAcBack
ScancodeAcForward -> scancodeAcForward
ScancodeAcStop -> scancodeAcStop
ScancodeAcRefresh -> scancodeAcRefresh
ScancodeAcBookmarks -> scancodeAcBookmarks
ScancodeBrightnessDown -> scancodeBrightnessDown
ScancodeBrightnessUp -> scancodeBrightnessUp
ScancodeDisplaySwitch -> scancodeDisplaySwitch
ScancodeKbdillumToggle -> scancodeKbdillumToggle
ScancodeKbdillumDown -> scancodeKbdillumDown
ScancodeKbdillumUp -> scancodeKbdillumUp
ScancodeEject -> scancodeEject
ScancodeSleep -> scancodeSleep
ScancodeApp1 -> scancodeApp1
ScancodeApp2 -> scancodeApp2
scancodeUnknown :: Int
scancodeUnknown = fromIntegral $ [C.pure| int {SCANCODE_UNKNOWN} |]
scancodeCtrl :: Int
scancodeCtrl = fromIntegral $ [C.pure| int {SCANCODE_CTRL} |]
scancodeShift :: Int
scancodeShift = fromIntegral $ [C.pure| int {SCANCODE_SHIFT} |]
scancodeAlt :: Int
scancodeAlt = fromIntegral $ [C.pure| int {SCANCODE_ALT} |]
scancodeGui :: Int
scancodeGui = fromIntegral $ [C.pure| int {SCANCODE_GUI} |]
scancodeA :: Int
scancodeA = fromIntegral $ [C.pure| int {SCANCODE_A} |]
scancodeB :: Int
scancodeB = fromIntegral $ [C.pure| int {SCANCODE_B} |]
scancodeC :: Int
scancodeC = fromIntegral $ [C.pure| int {SCANCODE_C} |]
scancodeD :: Int
scancodeD = fromIntegral $ [C.pure| int {SCANCODE_D} |]
scancodeE :: Int
scancodeE = fromIntegral $ [C.pure| int {SCANCODE_E} |]
scancodeF :: Int
scancodeF = fromIntegral $ [C.pure| int {SCANCODE_F} |]
scancodeG :: Int
scancodeG = fromIntegral $ [C.pure| int {SCANCODE_G} |]
scancodeH :: Int
scancodeH = fromIntegral $ [C.pure| int {SCANCODE_H} |]
scancodeI :: Int
scancodeI = fromIntegral $ [C.pure| int {SCANCODE_I} |]
scancodeJ :: Int
scancodeJ = fromIntegral $ [C.pure| int {SCANCODE_J} |]
scancodeK :: Int
scancodeK = fromIntegral $ [C.pure| int {SCANCODE_K} |]
scancodeL :: Int
scancodeL = fromIntegral $ [C.pure| int {SCANCODE_L} |]
scancodeM :: Int
scancodeM = fromIntegral $ [C.pure| int {SCANCODE_M} |]
scancodeN :: Int
scancodeN = fromIntegral $ [C.pure| int {SCANCODE_N} |]
scancodeO :: Int
scancodeO = fromIntegral $ [C.pure| int {SCANCODE_O} |]
scancodeP :: Int
scancodeP = fromIntegral $ [C.pure| int {SCANCODE_P} |]
scancodeQ :: Int
scancodeQ = fromIntegral $ [C.pure| int {SCANCODE_Q} |]
scancodeR :: Int
scancodeR = fromIntegral $ [C.pure| int {SCANCODE_R} |]
scancodeS :: Int
scancodeS = fromIntegral $ [C.pure| int {SCANCODE_S} |]
scancodeT :: Int
scancodeT = fromIntegral $ [C.pure| int {SCANCODE_T} |]
scancodeU :: Int
scancodeU = fromIntegral $ [C.pure| int {SCANCODE_U} |]
scancodeV :: Int
scancodeV = fromIntegral $ [C.pure| int {SCANCODE_V} |]
scancodeW :: Int
scancodeW = fromIntegral $ [C.pure| int {SCANCODE_W} |]
scancodeX :: Int
scancodeX = fromIntegral $ [C.pure| int {SCANCODE_X} |]
scancodeY :: Int
scancodeY = fromIntegral $ [C.pure| int {SCANCODE_Y} |]
scancodeZ :: Int
scancodeZ = fromIntegral $ [C.pure| int {SCANCODE_Z} |]
scancode1 :: Int
scancode1 = fromIntegral $ [C.pure| int {SCANCODE_1} |]
scancode2 :: Int
scancode2 = fromIntegral $ [C.pure| int {SCANCODE_2} |]
scancode3 :: Int
scancode3 = fromIntegral $ [C.pure| int {SCANCODE_3} |]
scancode4 :: Int
scancode4 = fromIntegral $ [C.pure| int {SCANCODE_4} |]
scancode5 :: Int
scancode5 = fromIntegral $ [C.pure| int {SCANCODE_5} |]
scancode6 :: Int
scancode6 = fromIntegral $ [C.pure| int {SCANCODE_6} |]
scancode7 :: Int
scancode7 = fromIntegral $ [C.pure| int {SCANCODE_7} |]
scancode8 :: Int
scancode8 = fromIntegral $ [C.pure| int {SCANCODE_8} |]
scancode9 :: Int
scancode9 = fromIntegral $ [C.pure| int {SCANCODE_9} |]
scancode0 :: Int
scancode0 = fromIntegral $ [C.pure| int {SCANCODE_0} |]
scancodeReturn :: Int
scancodeReturn = fromIntegral $ [C.pure| int {SCANCODE_RETURN} |]
scancodeEscape :: Int
scancodeEscape = fromIntegral $ [C.pure| int {SCANCODE_ESCAPE} |]
scancodeBackspace :: Int
scancodeBackspace = fromIntegral $ [C.pure| int {SCANCODE_BACKSPACE} |]
scancodeTab :: Int
scancodeTab = fromIntegral $ [C.pure| int {SCANCODE_TAB} |]
scancodeSpace :: Int
scancodeSpace = fromIntegral $ [C.pure| int {SCANCODE_SPACE} |]
scancodeMinus :: Int
scancodeMinus = fromIntegral $ [C.pure| int {SCANCODE_MINUS} |]
scancodeEquals :: Int
scancodeEquals = fromIntegral $ [C.pure| int {SCANCODE_EQUALS} |]
scancodeLeftBracket :: Int
scancodeLeftBracket = fromIntegral $ [C.pure| int {SCANCODE_LEFTBRACKET} |]
scancodeRightBracket :: Int
scancodeRightBracket = fromIntegral $ [C.pure| int {SCANCODE_RIGHTBRACKET} |]
scancodeBackslash :: Int
scancodeBackslash = fromIntegral $ [C.pure| int {SCANCODE_BACKSLASH} |]
scancodeNonushash :: Int
scancodeNonushash = fromIntegral $ [C.pure| int {SCANCODE_NONUSHASH} |]
scancodeSemicolon :: Int
scancodeSemicolon = fromIntegral $ [C.pure| int {SCANCODE_SEMICOLON} |]
scancodeApostrophe :: Int
scancodeApostrophe = fromIntegral $ [C.pure| int {SCANCODE_APOSTROPHE} |]
scancodeGrave :: Int
scancodeGrave = fromIntegral $ [C.pure| int {SCANCODE_GRAVE} |]
scancodeComma :: Int
scancodeComma = fromIntegral $ [C.pure| int {SCANCODE_COMMA} |]
scancodePeriod :: Int
scancodePeriod = fromIntegral $ [C.pure| int {SCANCODE_PERIOD} |]
scancodeSlash :: Int
scancodeSlash = fromIntegral $ [C.pure| int {SCANCODE_SLASH} |]
scancodeCapslock :: Int
scancodeCapslock = fromIntegral $ [C.pure| int {SCANCODE_CAPSLOCK} |]
scancodeF1 :: Int
scancodeF1 = fromIntegral $ [C.pure| int {SCANCODE_F1} |]
scancodeF2 :: Int
scancodeF2 = fromIntegral $ [C.pure| int {SCANCODE_F2} |]
scancodeF3 :: Int
scancodeF3 = fromIntegral $ [C.pure| int {SCANCODE_F3} |]
scancodeF4 :: Int
scancodeF4 = fromIntegral $ [C.pure| int {SCANCODE_F4} |]
scancodeF5 :: Int
scancodeF5 = fromIntegral $ [C.pure| int {SCANCODE_F5} |]
scancodeF6 :: Int
scancodeF6 = fromIntegral $ [C.pure| int {SCANCODE_F6} |]
scancodeF7 :: Int
scancodeF7 = fromIntegral $ [C.pure| int {SCANCODE_F7} |]
scancodeF8 :: Int
scancodeF8 = fromIntegral $ [C.pure| int {SCANCODE_F8} |]
scancodeF9 :: Int
scancodeF9 = fromIntegral $ [C.pure| int {SCANCODE_F9} |]
scancodeF10 :: Int
scancodeF10 = fromIntegral $ [C.pure| int {SCANCODE_F10} |]
scancodeF11 :: Int
scancodeF11 = fromIntegral $ [C.pure| int {SCANCODE_F11} |]
scancodeF12 :: Int
scancodeF12 = fromIntegral $ [C.pure| int {SCANCODE_F12} |]
scancodePrintScreen :: Int
scancodePrintScreen = fromIntegral $ [C.pure| int {SCANCODE_PRINTSCREEN} |]
scancodeScrolLlock :: Int
scancodeScrolLlock = fromIntegral $ [C.pure| int {SCANCODE_SCROLLLOCK} |]
scancodePause :: Int
scancodePause = fromIntegral $ [C.pure| int {SCANCODE_PAUSE} |]
scancodeInsert :: Int
scancodeInsert = fromIntegral $ [C.pure| int {SCANCODE_INSERT} |]
scancodeHome :: Int
scancodeHome = fromIntegral $ [C.pure| int {SCANCODE_HOME} |]
scancodePageUp :: Int
scancodePageUp = fromIntegral $ [C.pure| int {SCANCODE_PAGEUP} |]
scancodeDelete :: Int
scancodeDelete = fromIntegral $ [C.pure| int {SCANCODE_DELETE} |]
scancodeEnd :: Int
scancodeEnd = fromIntegral $ [C.pure| int {SCANCODE_END} |]
scancodePageDown :: Int
scancodePageDown = fromIntegral $ [C.pure| int {SCANCODE_PAGEDOWN} |]
scancodeRight :: Int
scancodeRight = fromIntegral $ [C.pure| int {SCANCODE_RIGHT} |]
scancodeLeft :: Int
scancodeLeft = fromIntegral $ [C.pure| int {SCANCODE_LEFT} |]
scancodeDown :: Int
scancodeDown = fromIntegral $ [C.pure| int {SCANCODE_DOWN} |]
scancodeUp :: Int
scancodeUp = fromIntegral $ [C.pure| int {SCANCODE_UP} |]
scancodeNumLockClear :: Int
scancodeNumLockClear = fromIntegral $ [C.pure| int {SCANCODE_NUMLOCKCLEAR} |]
scancodeKpDivide :: Int
scancodeKpDivide = fromIntegral $ [C.pure| int {SCANCODE_KP_DIVIDE} |]
scancodeKpMultiply :: Int
scancodeKpMultiply = fromIntegral $ [C.pure| int {SCANCODE_KP_MULTIPLY} |]
scancodeKpMinus :: Int
scancodeKpMinus = fromIntegral $ [C.pure| int {SCANCODE_KP_MINUS} |]
scancodeKpPlus :: Int
scancodeKpPlus = fromIntegral $ [C.pure| int {SCANCODE_KP_PLUS} |]
scancodeKpEnter :: Int
scancodeKpEnter = fromIntegral $ [C.pure| int {SCANCODE_KP_ENTER} |]
scancodeKp1 :: Int
scancodeKp1 = fromIntegral $ [C.pure| int {SCANCODE_KP_1} |]
scancodeKp2 :: Int
scancodeKp2 = fromIntegral $ [C.pure| int {SCANCODE_KP_2} |]
scancodeKp3 :: Int
scancodeKp3 = fromIntegral $ [C.pure| int {SCANCODE_KP_3} |]
scancodeKp4 :: Int
scancodeKp4 = fromIntegral $ [C.pure| int {SCANCODE_KP_4} |]
scancodeKp5 :: Int
scancodeKp5 = fromIntegral $ [C.pure| int {SCANCODE_KP_5} |]
scancodeKp6 :: Int
scancodeKp6 = fromIntegral $ [C.pure| int {SCANCODE_KP_6} |]
scancodeKp7 :: Int
scancodeKp7 = fromIntegral $ [C.pure| int {SCANCODE_KP_7} |]
scancodeKp8 :: Int
scancodeKp8 = fromIntegral $ [C.pure| int {SCANCODE_KP_8} |]
scancodeKp9 :: Int
scancodeKp9 = fromIntegral $ [C.pure| int {SCANCODE_KP_9} |]
scancodeKp0 :: Int
scancodeKp0 = fromIntegral $ [C.pure| int {SCANCODE_KP_0} |]
scancodeKpPeriod :: Int
scancodeKpPeriod = fromIntegral $ [C.pure| int {SCANCODE_KP_PERIOD} |]
scancodeNonusbackslash :: Int
scancodeNonusbackslash = fromIntegral $ [C.pure| int {SCANCODE_NONUSBACKSLASH} |]
scancodeApplication :: Int
scancodeApplication = fromIntegral $ [C.pure| int {SCANCODE_APPLICATION} |]
scancodePower :: Int
scancodePower = fromIntegral $ [C.pure| int {SCANCODE_POWER} |]
scancodeKpEquals :: Int
scancodeKpEquals = fromIntegral $ [C.pure| int {SCANCODE_KP_EQUALS} |]
scancodeF13 :: Int
scancodeF13 = fromIntegral $ [C.pure| int {SCANCODE_F13} |]
scancodeF14 :: Int
scancodeF14 = fromIntegral $ [C.pure| int {SCANCODE_F14} |]
scancodeF15 :: Int
scancodeF15 = fromIntegral $ [C.pure| int {SCANCODE_F15} |]
scancodeF16 :: Int
scancodeF16 = fromIntegral $ [C.pure| int {SCANCODE_F16} |]
scancodeF17 :: Int
scancodeF17 = fromIntegral $ [C.pure| int {SCANCODE_F17} |]
scancodeF18 :: Int
scancodeF18 = fromIntegral $ [C.pure| int {SCANCODE_F18} |]
scancodeF19 :: Int
scancodeF19 = fromIntegral $ [C.pure| int {SCANCODE_F19} |]
scancodeF20 :: Int
scancodeF20 = fromIntegral $ [C.pure| int {SCANCODE_F20} |]
scancodeF21 :: Int
scancodeF21 = fromIntegral $ [C.pure| int {SCANCODE_F21} |]
scancodeF22 :: Int
scancodeF22 = fromIntegral $ [C.pure| int {SCANCODE_F22} |]
scancodeF23 :: Int
scancodeF23 = fromIntegral $ [C.pure| int {SCANCODE_F23} |]
scancodeF24 :: Int
scancodeF24 = fromIntegral $ [C.pure| int {SCANCODE_F24} |]
scancodeExecute :: Int
scancodeExecute = fromIntegral $ [C.pure| int {SCANCODE_EXECUTE} |]
scancodeHelp :: Int
scancodeHelp = fromIntegral $ [C.pure| int {SCANCODE_HELP} |]
scancodeMenu :: Int
scancodeMenu = fromIntegral $ [C.pure| int {SCANCODE_MENU} |]
scancodeSelect :: Int
scancodeSelect = fromIntegral $ [C.pure| int {SCANCODE_SELECT} |]
scancodeStop :: Int
scancodeStop = fromIntegral $ [C.pure| int {SCANCODE_STOP} |]
scancodeAgain :: Int
scancodeAgain = fromIntegral $ [C.pure| int {SCANCODE_AGAIN} |]
scancodeUndo :: Int
scancodeUndo = fromIntegral $ [C.pure| int {SCANCODE_UNDO} |]
scancodeCut :: Int
scancodeCut = fromIntegral $ [C.pure| int {SCANCODE_CUT} |]
scancodeCopy :: Int
scancodeCopy = fromIntegral $ [C.pure| int {SCANCODE_COPY} |]
scancodePaste :: Int
scancodePaste = fromIntegral $ [C.pure| int {SCANCODE_PASTE} |]
scancodeFind :: Int
scancodeFind = fromIntegral $ [C.pure| int {SCANCODE_FIND} |]
scancodeMute :: Int
scancodeMute = fromIntegral $ [C.pure| int {SCANCODE_MUTE} |]
scancodeVolumeUp :: Int
scancodeVolumeUp = fromIntegral $ [C.pure| int {SCANCODE_VOLUMEUP} |]
scancodeVolumeDown :: Int
scancodeVolumeDown = fromIntegral $ [C.pure| int {SCANCODE_VOLUMEDOWN} |]
scancodeKpComma :: Int
scancodeKpComma = fromIntegral $ [C.pure| int {SCANCODE_KP_COMMA} |]
scancodeKpEqualsAs400 :: Int
scancodeKpEqualsAs400 = fromIntegral $ [C.pure| int {SCANCODE_KP_EQUALSAS400} |]
scancodeInternational1 :: Int
scancodeInternational1 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL1} |]
scancodeInternational2 :: Int
scancodeInternational2 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL2} |]
scancodeInternational3 :: Int
scancodeInternational3 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL3} |]
scancodeInternational4 :: Int
scancodeInternational4 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL4} |]
scancodeInternational5 :: Int
scancodeInternational5 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL5} |]
scancodeInternational6 :: Int
scancodeInternational6 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL6} |]
scancodeInternational7 :: Int
scancodeInternational7 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL7} |]
scancodeInternational8 :: Int
scancodeInternational8 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL8} |]
scancodeInternational9 :: Int
scancodeInternational9 = fromIntegral $ [C.pure| int {SCANCODE_INTERNATIONAL9} |]
scancodeLang1 :: Int
scancodeLang1 = fromIntegral $ [C.pure| int {SCANCODE_LANG1} |]
scancodeLang2 :: Int
scancodeLang2 = fromIntegral $ [C.pure| int {SCANCODE_LANG2} |]
scancodeLang3 :: Int
scancodeLang3 = fromIntegral $ [C.pure| int {SCANCODE_LANG3} |]
scancodeLang4 :: Int
scancodeLang4 = fromIntegral $ [C.pure| int {SCANCODE_LANG4} |]
scancodeLang5 :: Int
scancodeLang5 = fromIntegral $ [C.pure| int {SCANCODE_LANG5} |]
scancodeLang6 :: Int
scancodeLang6 = fromIntegral $ [C.pure| int {SCANCODE_LANG6} |]
scancodeLang7 :: Int
scancodeLang7 = fromIntegral $ [C.pure| int {SCANCODE_LANG7} |]
scancodeLang8 :: Int
scancodeLang8 = fromIntegral $ [C.pure| int {SCANCODE_LANG8} |]
scancodeLang9 :: Int
scancodeLang9 = fromIntegral $ [C.pure| int {SCANCODE_LANG9} |]
scancodeAltErase :: Int
scancodeAltErase = fromIntegral $ [C.pure| int {SCANCODE_ALTERASE} |]
scancodeSysReq :: Int
scancodeSysReq = fromIntegral $ [C.pure| int {SCANCODE_SYSREQ} |]
scancodeCancel :: Int
scancodeCancel = fromIntegral $ [C.pure| int {SCANCODE_CANCEL} |]
scancodeClear :: Int
scancodeClear = fromIntegral $ [C.pure| int {SCANCODE_CLEAR} |]
scancodePrior :: Int
scancodePrior = fromIntegral $ [C.pure| int {SCANCODE_PRIOR} |]
scancodeReturn2 :: Int
scancodeReturn2 = fromIntegral $ [C.pure| int {SCANCODE_RETURN2} |]
scancodeSeparator :: Int
scancodeSeparator = fromIntegral $ [C.pure| int {SCANCODE_SEPARATOR} |]
scancodeOut :: Int
scancodeOut = fromIntegral $ [C.pure| int {SCANCODE_OUT} |]
scancodeOper :: Int
scancodeOper = fromIntegral $ [C.pure| int {SCANCODE_OPER} |]
scancodeClearAgain :: Int
scancodeClearAgain = fromIntegral $ [C.pure| int {SCANCODE_CLEARAGAIN} |]
scancodeCrsel :: Int
scancodeCrsel = fromIntegral $ [C.pure| int {SCANCODE_CRSEL} |]
scancodeExsel :: Int
scancodeExsel = fromIntegral $ [C.pure| int {SCANCODE_EXSEL} |]
scancodeKp00 :: Int
scancodeKp00 = fromIntegral $ [C.pure| int {SCANCODE_KP_00} |]
scancodeKp000 :: Int
scancodeKp000 = fromIntegral $ [C.pure| int {SCANCODE_KP_000} |]
scancodeThousandsSeparator :: Int
scancodeThousandsSeparator = fromIntegral $ [C.pure| int {SCANCODE_THOUSANDSSEPARATOR} |]
scancodeDecimalSeparator :: Int
scancodeDecimalSeparator = fromIntegral $ [C.pure| int {SCANCODE_DECIMALSEPARATOR} |]
scancodeCurrencyUnit :: Int
scancodeCurrencyUnit = fromIntegral $ [C.pure| int {SCANCODE_CURRENCYUNIT} |]
scancodeCurrencySubUnit :: Int
scancodeCurrencySubUnit = fromIntegral $ [C.pure| int {SCANCODE_CURRENCYSUBUNIT} |]
scancodeKpLeftParen :: Int
scancodeKpLeftParen = fromIntegral $ [C.pure| int {SCANCODE_KP_LEFTPAREN} |]
scancodeKpRightParen :: Int
scancodeKpRightParen = fromIntegral $ [C.pure| int {SCANCODE_KP_RIGHTPAREN} |]
scancodeKpLeftBrace :: Int
scancodeKpLeftBrace = fromIntegral $ [C.pure| int {SCANCODE_KP_LEFTBRACE} |]
scancodeKpRightBrace :: Int
scancodeKpRightBrace = fromIntegral $ [C.pure| int {SCANCODE_KP_RIGHTBRACE} |]
scancodeKpTab :: Int
scancodeKpTab = fromIntegral $ [C.pure| int {SCANCODE_KP_TAB} |]
scancodeKpBackspace :: Int
scancodeKpBackspace = fromIntegral $ [C.pure| int {SCANCODE_KP_BACKSPACE} |]
scancodeKpA :: Int
scancodeKpA = fromIntegral $ [C.pure| int {SCANCODE_KP_A} |]
scancodeKpB :: Int
scancodeKpB = fromIntegral $ [C.pure| int {SCANCODE_KP_B} |]
scancodeKpC :: Int
scancodeKpC = fromIntegral $ [C.pure| int {SCANCODE_KP_C} |]
scancodeKpD :: Int
scancodeKpD = fromIntegral $ [C.pure| int {SCANCODE_KP_D} |]
scancodeKpE :: Int
scancodeKpE = fromIntegral $ [C.pure| int {SCANCODE_KP_E} |]
scancodeKpF :: Int
scancodeKpF = fromIntegral $ [C.pure| int {SCANCODE_KP_F} |]
scancodeKpXor :: Int
scancodeKpXor = fromIntegral $ [C.pure| int {SCANCODE_KP_XOR} |]
scancodeKpPower :: Int
scancodeKpPower = fromIntegral $ [C.pure| int {SCANCODE_KP_POWER} |]
scancodeKpPercent :: Int
scancodeKpPercent = fromIntegral $ [C.pure| int {SCANCODE_KP_PERCENT} |]
scancodeKpLess :: Int
scancodeKpLess = fromIntegral $ [C.pure| int {SCANCODE_KP_LESS} |]
scancodeKpGreater :: Int
scancodeKpGreater = fromIntegral $ [C.pure| int {SCANCODE_KP_GREATER} |]
scancodeKpAmpersand :: Int
scancodeKpAmpersand = fromIntegral $ [C.pure| int {SCANCODE_KP_AMPERSAND} |]
scancodeKpDblAmpersand :: Int
scancodeKpDblAmpersand = fromIntegral $ [C.pure| int {SCANCODE_KP_DBLAMPERSAND} |]
scancodeKpVerticalBar :: Int
scancodeKpVerticalBar = fromIntegral $ [C.pure| int {SCANCODE_KP_VERTICALBAR} |]
scancodeKpDblverticalBar :: Int
scancodeKpDblverticalBar = fromIntegral $ [C.pure| int {SCANCODE_KP_DBLVERTICALBAR} |]
scancodeKpColon :: Int
scancodeKpColon = fromIntegral $ [C.pure| int {SCANCODE_KP_COLON} |]
scancodeKpHash :: Int
scancodeKpHash = fromIntegral $ [C.pure| int {SCANCODE_KP_HASH} |]
scancodeKpSpace :: Int
scancodeKpSpace = fromIntegral $ [C.pure| int {SCANCODE_KP_SPACE} |]
scancodeKpAt :: Int
scancodeKpAt = fromIntegral $ [C.pure| int {SCANCODE_KP_AT} |]
scancodeKpExclam :: Int
scancodeKpExclam = fromIntegral $ [C.pure| int {SCANCODE_KP_EXCLAM} |]
scancodeKpMemStore :: Int
scancodeKpMemStore = fromIntegral $ [C.pure| int {SCANCODE_KP_MEMSTORE} |]
scancodeKpMemRecall :: Int
scancodeKpMemRecall = fromIntegral $ [C.pure| int {SCANCODE_KP_MEMRECALL} |]
scancodeKpMemClear :: Int
scancodeKpMemClear = fromIntegral $ [C.pure| int {SCANCODE_KP_MEMCLEAR} |]
scancodeKpMemAdd :: Int
scancodeKpMemAdd = fromIntegral $ [C.pure| int {SCANCODE_KP_MEMADD} |]
scancodeKpMemSubtract :: Int
scancodeKpMemSubtract = fromIntegral $ [C.pure| int {SCANCODE_KP_MEMSUBTRACT} |]
scancodeKpMemMultiply :: Int
scancodeKpMemMultiply = fromIntegral $ [C.pure| int {SCANCODE_KP_MEMMULTIPLY} |]
scancodeKpMemDivide :: Int
scancodeKpMemDivide = fromIntegral $ [C.pure| int {SCANCODE_KP_MEMDIVIDE} |]
scancodeKpPlusMinus :: Int
scancodeKpPlusMinus = fromIntegral $ [C.pure| int {SCANCODE_KP_PLUSMINUS} |]
scancodeKpClear :: Int
scancodeKpClear = fromIntegral $ [C.pure| int {SCANCODE_KP_CLEAR} |]
scancodeKpClearEntry :: Int
scancodeKpClearEntry = fromIntegral $ [C.pure| int {SCANCODE_KP_CLEARENTRY} |]
scancodeKpBinary :: Int
scancodeKpBinary = fromIntegral $ [C.pure| int {SCANCODE_KP_BINARY} |]
scancodeKpOctal :: Int
scancodeKpOctal = fromIntegral $ [C.pure| int {SCANCODE_KP_OCTAL} |]
scancodeKpDecimal :: Int
scancodeKpDecimal = fromIntegral $ [C.pure| int {SCANCODE_KP_DECIMAL} |]
scancodeKpHexadecimal :: Int
scancodeKpHexadecimal = fromIntegral $ [C.pure| int {SCANCODE_KP_HEXADECIMAL} |]
scancodeLCtrl :: Int
scancodeLCtrl = fromIntegral $ [C.pure| int {SCANCODE_LCTRL} |]
scancodeLShift :: Int
scancodeLShift = fromIntegral $ [C.pure| int {SCANCODE_LSHIFT} |]
scancodeLAlt :: Int
scancodeLAlt = fromIntegral $ [C.pure| int {SCANCODE_LALT} |]
scancodeLGui :: Int
scancodeLGui = fromIntegral $ [C.pure| int {SCANCODE_LGUI} |]
scancodeRCtrl :: Int
scancodeRCtrl = fromIntegral $ [C.pure| int {SCANCODE_RCTRL} |]
scancodeRShift :: Int
scancodeRShift = fromIntegral $ [C.pure| int {SCANCODE_RSHIFT} |]
scancodeRAlt :: Int
scancodeRAlt = fromIntegral $ [C.pure| int {SCANCODE_RALT} |]
scancodeRGui :: Int
scancodeRGui = fromIntegral $ [C.pure| int {SCANCODE_RGUI} |]
scancodeMode :: Int
scancodeMode = fromIntegral $ [C.pure| int {SCANCODE_MODE} |]
scancodeAudioNext :: Int
scancodeAudioNext = fromIntegral $ [C.pure| int {SCANCODE_AUDIONEXT} |]
scancodeAudioPrev :: Int
scancodeAudioPrev = fromIntegral $ [C.pure| int {SCANCODE_AUDIOPREV} |]
scancodeAudioStop :: Int
scancodeAudioStop = fromIntegral $ [C.pure| int {SCANCODE_AUDIOSTOP} |]
scancodeAudioPlay :: Int
scancodeAudioPlay = fromIntegral $ [C.pure| int {SCANCODE_AUDIOPLAY} |]
scancodeAudioMute :: Int
scancodeAudioMute = fromIntegral $ [C.pure| int {SCANCODE_AUDIOMUTE} |]
scancodeMediaSelect :: Int
scancodeMediaSelect = fromIntegral $ [C.pure| int {SCANCODE_MEDIASELECT} |]
scancodeWww :: Int
scancodeWww = fromIntegral $ [C.pure| int {SCANCODE_WWW} |]
scancodeMail :: Int
scancodeMail = fromIntegral $ [C.pure| int {SCANCODE_MAIL} |]
scancodeCalculator :: Int
scancodeCalculator = fromIntegral $ [C.pure| int {SCANCODE_CALCULATOR} |]
scancodeComputer :: Int
scancodeComputer = fromIntegral $ [C.pure| int {SCANCODE_COMPUTER} |]
scancodeAcSearch :: Int
scancodeAcSearch = fromIntegral $ [C.pure| int {SCANCODE_AC_SEARCH} |]
scancodeAcHome :: Int
scancodeAcHome = fromIntegral $ [C.pure| int {SCANCODE_AC_HOME} |]
scancodeAcBack :: Int
scancodeAcBack = fromIntegral $ [C.pure| int {SCANCODE_AC_BACK} |]
scancodeAcForward :: Int
scancodeAcForward = fromIntegral $ [C.pure| int {SCANCODE_AC_FORWARD} |]
scancodeAcStop :: Int
scancodeAcStop = fromIntegral $ [C.pure| int {SCANCODE_AC_STOP} |]
scancodeAcRefresh :: Int
scancodeAcRefresh = fromIntegral $ [C.pure| int {SCANCODE_AC_REFRESH} |]
scancodeAcBookmarks :: Int
scancodeAcBookmarks = fromIntegral $ [C.pure| int {SCANCODE_AC_BOOKMARKS} |]
scancodeBrightnessDown :: Int
scancodeBrightnessDown = fromIntegral $ [C.pure| int {SCANCODE_BRIGHTNESSDOWN} |]
scancodeBrightnessUp :: Int
scancodeBrightnessUp = fromIntegral $ [C.pure| int {SCANCODE_BRIGHTNESSUP} |]
scancodeDisplaySwitch :: Int
scancodeDisplaySwitch = fromIntegral $ [C.pure| int {SCANCODE_DISPLAYSWITCH} |]
scancodeKbdillumToggle :: Int
scancodeKbdillumToggle = fromIntegral $ [C.pure| int {SCANCODE_KBDILLUMTOGGLE} |]
scancodeKbdillumDown :: Int
scancodeKbdillumDown = fromIntegral $ [C.pure| int {SCANCODE_KBDILLUMDOWN} |]
scancodeKbdillumUp :: Int
scancodeKbdillumUp = fromIntegral $ [C.pure| int {SCANCODE_KBDILLUMUP} |]
scancodeEject :: Int
scancodeEject = fromIntegral $ [C.pure| int {SCANCODE_EJECT} |]
scancodeSleep :: Int
scancodeSleep = fromIntegral $ [C.pure| int {SCANCODE_SLEEP} |]
scancodeApp1 :: Int
scancodeApp1 = fromIntegral $ [C.pure| int {SCANCODE_APP1} |]
scancodeApp2 :: Int
scancodeApp2 = fromIntegral $ [C.pure| int {SCANCODE_APP2} |]
data HatPosition =
HatCenter
| HatUp
| HatRight
| HatDown
| HatLeft
deriving (Eq, Ord, Show, Read, Bounded, Generic)
instance Enum HatPosition where
fromEnum = fromUrhoHatPosition
{-# INLINE fromEnum #-}
toEnum = toUrhoHatPosition
{-# INLINE toEnum #-}
toUrhoHatPosition :: Int -> HatPosition
toUrhoHatPosition i
| i == hatCenter = HatCenter
| i == hatUp = HatUp
| i == hatRight = HatRight
| i == hatDown = HatDown
| i == hatLeft = HatLeft
| otherwise = HatCenter
fromUrhoHatPosition :: HatPosition -> Int
fromUrhoHatPosition i = case i of
HatCenter -> hatCenter
HatUp -> hatUp
HatRight -> hatRight
HatDown -> hatDown
HatLeft -> hatLeft
hatCenter :: Int
hatCenter = fromIntegral $ [C.pure| int {HAT_CENTER} |]
hatUp :: Int
hatUp = fromIntegral $ [C.pure| int {HAT_UP} |]
hatRight :: Int
hatRight = fromIntegral $ [C.pure| int {HAT_RIGHT} |]
hatDown :: Int
hatDown = fromIntegral $ [C.pure| int {HAT_DOWN} |]
hatLeft :: Int
hatLeft = fromIntegral $ [C.pure| int {HAT_LEFT} |]
data ControllerButton =
ControllerButtonA
| ControllerButtonB
| ControllerButtonX
| ControllerButtonY
| ControllerButtonBack
| ControllerButtonGuide
| ControllerButtonStart
| ControllerButtonLeftStick
| ControllerButtonRightStick
| ControllerButtonLeftShoulder
| ControllerButtonRightShoulder
| ControllerButtonDpadUp
| ControllerButtonDpadDown
| ControllerButtonDpadLeft
| ControllerButtonDpadRight
deriving (Eq, Ord, Show, Read, Bounded, Generic)
instance Enum ControllerButton where
fromEnum = fromUrhoControllerButton
{-# INLINE fromEnum #-}
toEnum = toUrhoControllerButton
{-# INLINE toEnum #-}
toUrhoControllerButton :: Int -> ControllerButton
toUrhoControllerButton i
| i == controllerButtonA = ControllerButtonA
| i == controllerButtonB = ControllerButtonB
| i == controllerButtonX = ControllerButtonX
| i == controllerButtonY = ControllerButtonY
| i == controllerButtonBack = ControllerButtonBack
| i == controllerButtonGuide = ControllerButtonGuide
| i == controllerButtonStart = ControllerButtonStart
| i == controllerButtonLeftstick = ControllerButtonLeftStick
| i == controllerButtonRightstick = ControllerButtonRightStick
| i == controllerButtonLeftshoulder = ControllerButtonLeftShoulder
| i == controllerButtonRightshoulder = ControllerButtonRightShoulder
| i == controllerButtonDpadUp = ControllerButtonDpadUp
| i == controllerButtonDpadDown = ControllerButtonDpadDown
| i == controllerButtonDpadLeft = ControllerButtonDpadLeft
| i == controllerButtonDpadRight = ControllerButtonDpadRight
| otherwise = ControllerButtonA
fromUrhoControllerButton :: ControllerButton -> Int
fromUrhoControllerButton i = case i of
ControllerButtonA -> controllerButtonA
ControllerButtonB -> controllerButtonB
ControllerButtonX -> controllerButtonX
ControllerButtonY -> controllerButtonY
ControllerButtonBack -> controllerButtonBack
ControllerButtonGuide -> controllerButtonGuide
ControllerButtonStart -> controllerButtonStart
ControllerButtonLeftStick -> controllerButtonLeftstick
ControllerButtonRightStick -> controllerButtonRightstick
ControllerButtonLeftShoulder -> controllerButtonLeftshoulder
ControllerButtonRightShoulder -> controllerButtonRightshoulder
ControllerButtonDpadUp -> controllerButtonDpadUp
ControllerButtonDpadDown -> controllerButtonDpadDown
ControllerButtonDpadLeft -> controllerButtonDpadLeft
ControllerButtonDpadRight -> controllerButtonDpadRight
controllerButtonA :: Int
controllerButtonA = fromIntegral [C.pure| int { CONTROLLER_BUTTON_A } |]
controllerButtonB :: Int
controllerButtonB = fromIntegral [C.pure| int { CONTROLLER_BUTTON_B } |]
controllerButtonX :: Int
controllerButtonX = fromIntegral [C.pure| int { CONTROLLER_BUTTON_X } |]
controllerButtonY :: Int
controllerButtonY = fromIntegral [C.pure| int { CONTROLLER_BUTTON_Y } |]
controllerButtonBack :: Int
controllerButtonBack = fromIntegral [C.pure| int { CONTROLLER_BUTTON_BACK } |]
controllerButtonGuide :: Int
controllerButtonGuide = fromIntegral [C.pure| int { CONTROLLER_BUTTON_GUIDE } |]
controllerButtonStart :: Int
controllerButtonStart = fromIntegral [C.pure| int { CONTROLLER_BUTTON_START } |]
controllerButtonLeftstick :: Int
controllerButtonLeftstick = fromIntegral [C.pure| int { CONTROLLER_BUTTON_LEFTSTICK } |]
controllerButtonRightstick :: Int
controllerButtonRightstick = fromIntegral [C.pure| int { CONTROLLER_BUTTON_RIGHTSTICK } |]
controllerButtonLeftshoulder :: Int
controllerButtonLeftshoulder = fromIntegral [C.pure| int { CONTROLLER_BUTTON_LEFTSHOULDER } |]
controllerButtonRightshoulder :: Int
controllerButtonRightshoulder = fromIntegral [C.pure| int { CONTROLLER_BUTTON_RIGHTSHOULDER } |]
controllerButtonDpadUp :: Int
controllerButtonDpadUp = fromIntegral [C.pure| int { CONTROLLER_BUTTON_DPAD_UP } |]
controllerButtonDpadDown :: Int
controllerButtonDpadDown = fromIntegral [C.pure| int { CONTROLLER_BUTTON_DPAD_DOWN } |]
controllerButtonDpadLeft :: Int
controllerButtonDpadLeft = fromIntegral [C.pure| int { CONTROLLER_BUTTON_DPAD_LEFT } |]
controllerButtonDpadRight :: Int
controllerButtonDpadRight = fromIntegral [C.pure| int { CONTROLLER_BUTTON_DPAD_RIGHT } |]
data ControllerAxis =
ControllerAxisLeftX
| ControllerAxisLeftY
| ControllerAxisRightX
| ControllerAxisRightY
| ControllerAxisTriggerLeft
| ControllerAxisTriggerRight
deriving (Eq, Ord, Show, Read, Bounded, Generic)
instance Enum ControllerAxis where
fromEnum = fromUrhoControllerAxis
{-# INLINE fromEnum #-}
toEnum = toUrhoControllerAxis
{-# INLINE toEnum #-}
toUrhoControllerAxis :: Int -> ControllerAxis
toUrhoControllerAxis i
| i == controllerAxisLeftx = ControllerAxisLeftX
| i == controllerAxisLefty = ControllerAxisLeftY
| i == controllerAxisRightx = ControllerAxisRightX
| i == controllerAxisRighty = ControllerAxisRightY
| i == controllerAxisTriggerleft = ControllerAxisTriggerLeft
| i == controllerAxisTriggerright = ControllerAxisTriggerRight
| otherwise = ControllerAxisLeftX
fromUrhoControllerAxis :: ControllerAxis -> Int
fromUrhoControllerAxis i = case i of
ControllerAxisLeftX -> controllerAxisLeftx
ControllerAxisLeftY -> controllerAxisLefty
ControllerAxisRightX -> controllerAxisRightx
ControllerAxisRightY -> controllerAxisRighty
ControllerAxisTriggerLeft -> controllerAxisTriggerleft
ControllerAxisTriggerRight -> controllerAxisTriggerright
controllerAxisLeftx :: Int
controllerAxisLeftx = fromIntegral [C.pure| int {CONTROLLER_AXIS_LEFTX} |]
controllerAxisLefty :: Int
controllerAxisLefty = fromIntegral [C.pure| int {CONTROLLER_AXIS_LEFTY} |]
controllerAxisRightx :: Int
controllerAxisRightx = fromIntegral [C.pure| int {CONTROLLER_AXIS_RIGHTX} |]
controllerAxisRighty :: Int
controllerAxisRighty = fromIntegral [C.pure| int {CONTROLLER_AXIS_RIGHTY} |]
controllerAxisTriggerleft :: Int
controllerAxisTriggerleft = fromIntegral [C.pure| int {CONTROLLER_AXIS_TRIGGERLEFT} |]
controllerAxisTriggerright :: Int
controllerAxisTriggerright = fromIntegral [C.pure| int {CONTROLLER_AXIS_TRIGGERRIGHT} |]
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Input/InputConstants.hs
|
mit
| 89,469 | 0 | 8 | 15,606 | 22,506 | 12,830 | 9,676 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.