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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{- |
Module : $Header$
Description : sublogic analysis for CoCASL
Copyright : (c) Till Mossakowski, C.Maeder and Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
This module provides the sublogic functions (as required by Logic.hs)
for CoCASL. It is based on the respective functions for CASL.
-}
module CoCASL.Sublogic
( CoCASL_Sublogics
, minFormSublogic
, minCSigItem
, minCBaseItem
, hasCoFeature
, setCoFeature
) where
import Common.AS_Annotation
import CASL.Sublogic
import CoCASL.AS_CoCASL
-- | type for CoCASL sublogics
type CoCASL_Sublogics = CASL_SL Bool
hasCoFeature :: CoCASL_Sublogics -> Bool
hasCoFeature = ext_features
setCoFeature :: Bool -> CoCASL_Sublogics -> CoCASL_Sublogics
setCoFeature b s = s { ext_features = b }
theCoFeature :: CoCASL_Sublogics
theCoFeature = setCoFeature True bottom
minFormSublogic :: C_FORMULA -> CoCASL_Sublogics
minFormSublogic cf = case cf of
BoxOrDiamond _ _ f _ ->
sublogics_max theCoFeature $ sl_sentence minFormSublogic f
CoSort_gen_ax _ _ _ -> theCoFeature
-- may be changed to Constraints with mappings
-- may be ops need to be checked for partiality?
minCSigItem :: C_SIG_ITEM -> CoCASL_Sublogics
minCSigItem (CoDatatype_items l _) =
foldl sublogics_max theCoFeature $ map (minCoDatatype . item) l
minCoDatatype :: CODATATYPE_DECL -> CoCASL_Sublogics
minCoDatatype (CoDatatype_decl _ l _) =
foldl sublogics_max theCoFeature $ map (minCoAlternative . item) l
minCoAlternative :: COALTERNATIVE -> CoCASL_Sublogics
minCoAlternative a = case a of
Co_construct fk _ l _ ->
foldl sublogics_max (sl_opkind fk) $ map minCoComponents l
CoSubsorts _ _ -> need_sub
minCoComponents :: COCOMPONENTS -> CoCASL_Sublogics
minCoComponents (CoSelect _ t _) = sl_op_type t
minCBaseItem :: C_BASIC_ITEM -> CoCASL_Sublogics
minCBaseItem bi = case bi of
CoFree_datatype l _ ->
foldl sublogics_max theCoFeature $ map minCoDatatype $ map item l
CoSort_gen l _ -> foldl sublogics_max theCoFeature $
map (sl_sig_items minCSigItem minFormSublogic . item) l
|
nevrenato/Hets_Fork
|
CoCASL/Sublogic.hs
|
gpl-2.0
| 2,234 | 0 | 12 | 442 | 456 | 233 | 223 | 41 | 2 |
-- A collection of Themes.
module Yi.Style.Library where
import Yi.Style
import Data.Prototype
import Data.Monoid
type Theme = Proto UIStyle
-- | Abstract theme that provides useful defaults.
defaultTheme :: Theme
defaultTheme = Proto $ const $ UIStyle
{ modelineAttributes = error "modeline attributes must be redefined!"
, modelineFocusStyle = withFg brightwhite
, tabBarAttributes = error "tabbar attributes must be redefined!"
, tabInFocusStyle = withFg black `mappend` withBg brightwhite
, tabNotFocusedStyle = withFg grey `mappend` withBg white
, baseAttributes = error "base attributes must be redefined!"
, selectedStyle = withFg black `mappend` withBg cyan
, eofStyle = withFg blue
, errorStyle = withBg red
, hintStyle = withFg black `mappend` withBg cyan
, strongHintStyle = withFg black `mappend` withBg magenta
, commentStyle = withFg purple
, blockCommentStyle = withFg purple
, keywordStyle = withFg darkblue
, numberStyle = withFg darkred
, preprocessorStyle = withFg red
, stringStyle = withFg darkcyan
, longStringStyle = mempty
, typeStyle = withFg darkgreen
, dataConstructorStyle
= withBd True `mappend` withFg darkgreen
, importStyle = withFg grey
, builtinStyle = withFg blue
, regexStyle = withFg red
, variableStyle = mempty
, operatorStyle = withFg brown
, makeFileRuleHead = withFg blue
, makeFileAction = withFg grey
, quoteStyle = withFg grey
}
-- | The default Theme
defaultLightTheme :: Theme
defaultLightTheme = defaultTheme `override` \super _ -> super
{ modelineAttributes = emptyAttributes { foreground = black, background = darkcyan }
, tabBarAttributes = emptyAttributes { foreground = white, background = black }
, baseAttributes = emptyAttributes
}
-- | A Theme inspired by the darkblue colorscheme of Vim.
darkBlueTheme :: Theme
darkBlueTheme = defaultTheme `override` \super _ -> super
{ modelineAttributes = emptyAttributes { foreground = darkblue, background = white }
, modelineFocusStyle = withBg brightwhite
, tabBarAttributes = emptyAttributes { foreground = darkblue, background = brightwhite }
, tabInFocusStyle = withFg grey `mappend` withBg white
, tabNotFocusedStyle = withFg lightGrey `mappend` withBg white
, baseAttributes = emptyAttributes { foreground = white, background = black }
, selectedStyle = withFg white `mappend` withBg blue
, eofStyle = withFg red
, hintStyle = withBg darkblue
, strongHintStyle = withBg blue
, commentStyle = withFg darkred
, keywordStyle = withFg brown
, stringStyle = withFg purple
, variableStyle = withFg cyan
, operatorStyle = withFg brown
}
-- TextMate themes are available on the TM wiki:
-- http://wiki.macromates.com/Themes/UserSubmittedThemes
-- | Theme originally designed by Joseph Andrew Magnani for TextMate, and
-- redistributed with explicit permission. It is not usable in the vty UI.
happyDeluxe :: Theme
happyDeluxe = defaultTheme `override` \super _ -> super
{ modelineAttributes = emptyAttributes
, tabBarAttributes = emptyAttributes { foreground = RGB 255 255 255 }
, baseAttributes = emptyAttributes { foreground = RGB 255 255 255, background = RGB 14 19 30 }
, selectedStyle = withBg (RGB 21 40 90)
, commentStyle = withFg (RGB 53 73 124)
, keywordStyle = withFg (RGB 254 144 6)
, numberStyle = withFg (RGB 20 222 209)
, stringStyle = withFg (RGB 253 102 249)
, typeStyle = mempty
, operatorStyle = mempty
, errorStyle = withFg (RGB 252 45 7)
}
-- | Theme originally developed by Matthew Ratzloff for TextMate, and
-- redistributed with explicit permission. It is not usable in the vty UI.
textExMachina :: Theme
textExMachina = defaultTheme `override` \super _ -> super
{ modelineAttributes = emptyAttributes { foreground = black }
, tabBarAttributes = emptyAttributes { foreground = black }
, baseAttributes = emptyAttributes { foreground = RGB 230 230 230, background = RGB 21 21 21 }
, selectedStyle = withBg (RGB 102 102 102)
, commentStyle = withFg (RGB 51 51 51)
, keywordStyle = withFg (RGB 119 124 178)
, numberStyle = withFg (RGB 174 129 255)
, stringStyle = withFg (RGB 102 204 255)
, typeStyle = withFg (RGB 174 129 255)
, variableStyle = withFg (RGB 255 255 255)
, operatorStyle = withFg (RGB 151 255 127)
}
|
codemac/yi-editor
|
src/Yi/Style/Library.hs
|
gpl-2.0
| 4,647 | 0 | 11 | 1,169 | 1,103 | 632 | 471 | 84 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module Lib.FSHook
( getLdPreloadPath
, FSHook
, with
, OutputEffect(..), OutputBehavior(..)
, Input(..)
, DelayedOutput(..), UndelayedOutput
, Protocol.OutFilePath(..), Protocol.OutEffect(..)
, FSAccessHandlers(..)
, AccessType(..), AccessDoc
, runCommand, timedRunCommand
) where
import Prelude.Compat hiding (FilePath)
import Control.Concurrent (ThreadId, myThreadId, killThread)
import Control.Concurrent.MVar
import Control.Monad (forever, void, unless, (<=<))
import Data.ByteString (ByteString)
import Data.IORef
import Data.Map.Strict (Map)
import Data.Maybe (maybeToList)
import Data.Monoid ((<>))
import Data.String (IsString(..))
import Data.Time (NominalDiffTime)
import Data.Typeable (Typeable)
import Lib.Argv0 (getArgv0)
import Lib.ByteString (unprefixed)
import Lib.ColorText (ColorText)
import Lib.Exception (finally, bracket_, onException, handleSync)
import Lib.FSHook.AccessType (AccessType(..))
import Lib.FSHook.OutputBehavior (OutputEffect(..), OutputBehavior(..))
import Lib.FSHook.Protocol (IsDelayed(..))
import Lib.FilePath (FilePath, (</>), takeDirectory, canonicalizePath)
import Lib.Fresh (Fresh)
import Lib.IORef (atomicModifyIORef'_, atomicModifyIORef_)
import Lib.Printer (Printer)
import Lib.Sock (recvFrame, recvLoop_, withUnixStreamListener)
import Lib.TimeIt (timeIt)
import Network.Socket (Socket)
import Paths_buildsome (getDataFileName)
import System.IO (hPutStrLn, stderr)
import qualified Control.Exception as E
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Map.Strict as M
import qualified Lib.AsyncContext as AsyncContext
import qualified Lib.FSHook.OutputBehavior as OutputBehavior
import qualified Lib.FSHook.Protocol as Protocol
import qualified Lib.FilePath as FilePath
import qualified Lib.Fresh as Fresh
import qualified Lib.Printer as Printer
import qualified Lib.Process as Process
import qualified Lib.Timeout as Timeout
import qualified Network.Socket as Sock
import qualified Network.Socket.ByteString as SockBS
import qualified System.Posix.ByteString as Posix
type AccessDoc = ColorText
type JobId = ByteString
data Input = Input
{ inputAccessType :: AccessType
, inputPath :: FilePath
} deriving (Eq, Ord, Show)
data DelayedOutput = DelayedOutput
-- TODO: Rename to delayedOutput...
{ outputBehavior :: OutputBehavior
, outputPath :: FilePath
} deriving (Eq, Ord, Show)
type UndelayedOutput = Protocol.OutFilePath
data FSAccessHandlers = FSAccessHandlers
{ delayedFSAccessHandler :: AccessDoc -> [Input] -> [DelayedOutput] -> IO ()
, undelayedFSAccessHandler :: AccessDoc -> [Input] -> [UndelayedOutput] -> IO ()
}
type JobLabel = ColorText
data RunningJob = RunningJob
{ jobLabel :: JobLabel
, jobActiveConnections :: IORef (Map Int (ThreadId, IO ()))
, jobFreshConnIds :: Fresh Int
, jobThreadId :: ThreadId
, jobFSAccessHandlers :: FSAccessHandlers
, jobRootFilter :: FilePath
}
data Job = KillingJob JobLabel | CompletedJob JobLabel | LiveJob RunningJob
data FSHook = FSHook
{ fsHookRunningJobs :: IORef (Map JobId Job)
, fsHookFreshJobIds :: Fresh Int
, fsHookLdPreloadPath :: FilePath
, fsHookServerAddress :: FilePath
, fsHookPrinter :: Printer
}
data ProtocolError = ProtocolError String deriving (Typeable)
instance E.Exception ProtocolError
instance Show ProtocolError where
show (ProtocolError msg) = "ProtocolError: " ++ msg
data Need = HOOK | HINT
fromNeedStr :: ByteString -> Need
fromNeedStr "HOOK" = HOOK
fromNeedStr "HINT" = HINT
fromNeedStr x = error $ "Invalid hello message need str: " ++ show x
serve :: Printer -> FSHook -> Socket -> IO ()
serve printer fsHook conn = do
mHelloLine <- recvFrame conn
case mHelloLine of
Nothing -> E.throwIO $ ProtocolError "Unexpected EOF"
Just helloLine ->
case unprefixed Protocol.helloPrefix helloLine of
Nothing ->
E.throwIO $ ProtocolError $ concat
[ "Bad hello message from connection: ", show helloLine, " expected: "
, show Protocol.helloPrefix, " (check your fs_override.so installation)" ]
Just pidJobId -> do
runningJobs <- readIORef (fsHookRunningJobs fsHook)
case M.lookup jobId runningJobs of
Nothing -> do
let jobIds = M.keys runningJobs
E.throwIO $ ProtocolError $ concat ["Bad slave id: ", show jobId, " mismatches all: ", show jobIds]
Just (KillingJob _label) ->
-- New connection created in the process of killing connections, ignore it
return ()
Just (LiveJob job) ->
(handleJobConnection fullTidStr conn job $ fromNeedStr needStr)
Just (CompletedJob label) ->
E.throwIO $ ProtocolError $ concat
-- Main/parent process completed, and leaked some subprocess
-- which connected again!
[ "Job: ", BS8.unpack jobId, "(", BS8.unpack (Printer.render printer label)
, ") received new connections after formal completion!"]
where
fullTidStr = concat [BS8.unpack pidStr, ":", BS8.unpack tidStr]
[pidStr, tidStr, jobId, needStr] = BS8.split ':' pidJobId
-- Except thread killed
printRethrowExceptions :: String -> IO a -> IO a
printRethrowExceptions msg =
E.handle $ \e -> do
case E.fromException e of
Just E.ThreadKilled -> return ()
_ -> E.uninterruptibleMask_ $ hPutStrLn stderr $ msg ++ show (e :: E.SomeException)
E.throwIO e
with :: Printer -> FilePath -> (FSHook -> IO a) -> IO a
with printer ldPreloadPath body = do
pid <- Posix.getProcessID
freshJobIds <- Fresh.new 0
let serverFilename = "/tmp/fshook-" <> BS8.pack (show pid)
withUnixStreamListener serverFilename $ \listener -> do
runningJobsRef <- newIORef M.empty
let
fsHook = FSHook
{ fsHookRunningJobs = runningJobsRef
, fsHookFreshJobIds = freshJobIds
, fsHookLdPreloadPath = ldPreloadPath
, fsHookServerAddress = serverFilename
, fsHookPrinter = printer
}
AsyncContext.new $ \ctx -> do
_ <-
AsyncContext.spawn ctx $ printRethrowExceptions "BUG: Listener loop threw exception: " $ forever $
do
(conn, _srcAddr) <- Sock.accept listener
AsyncContext.spawn ctx $
-- Job connection may fail when the process is killed
-- during a send-message, which may cause a protocol error
printRethrowExceptions "Job connection failed: " $
serve printer fsHook conn
`finally` Sock.close conn
body fsHook
{-# INLINE sendGo #-}
sendGo :: Socket -> IO ()
sendGo conn = void $ SockBS.send conn (BS8.pack "GO")
{-# INLINE handleJobMsg #-}
handleJobMsg :: String -> Socket -> RunningJob -> Protocol.Msg -> IO ()
handleJobMsg _tidStr conn job (Protocol.Msg isDelayed func) =
case func of
-- TODO: If any of these outputs are NOT also mode-only inputs on
-- their file paths, don't use handleOutputs so that we don't
-- report them as inputs
-- outputs
-- TODO: Handle truncation flag
Protocol.OpenW outPath _openWMode _create Protocol.OpenNoTruncate
-> handleOutputs [(OutputBehavior.fileChanger, outPath)]
Protocol.OpenW outPath _openWMode _create Protocol.OpenTruncate
-> handleOutputs [(OutputBehavior.fileChanger, outPath)]
Protocol.Creat outPath _ -> handleOutputs [(OutputBehavior.fileChanger, outPath)]
Protocol.Rename a b -> handleOutputs [ (OutputBehavior.existingFileChanger, a)
, (OutputBehavior.fileChanger, b) ]
Protocol.Unlink outPath -> handleOutputs [(OutputBehavior.existingFileChanger, outPath)]
Protocol.Truncate outPath _ -> handleOutputs [(OutputBehavior.existingFileChanger, outPath)]
Protocol.Chmod outPath _ -> handleOutputs [(OutputBehavior.existingFileChanger, outPath)]
Protocol.Chown outPath _ _ -> handleOutputs [(OutputBehavior.existingFileChanger, outPath)]
Protocol.MkNod outPath _ _ -> handleOutputs [(OutputBehavior.nonExistingFileChanger, outPath)] -- TODO: Special mkNod handling?
Protocol.MkDir outPath _ -> handleOutputs [(OutputBehavior.nonExistingFileChanger, outPath)]
Protocol.RmDir outPath -> handleOutputs [(OutputBehavior.existingFileChanger, outPath)]
-- I/O
Protocol.SymLink target linkPath ->
-- TODO: We don't actually read the input here, but we don't
-- handle symlinks correctly yet, so better be false-positive
-- than false-negative
handle
[ Input AccessTypeFull target ]
[ (OutputBehavior.nonExistingFileChanger, linkPath) ]
Protocol.Link src dest -> error $ unwords ["Hard links not supported:", show src, "->", show dest]
-- inputs
Protocol.OpenR path -> handleInput AccessTypeFull path
Protocol.Access path _mode -> handleInput AccessTypeModeOnly path
Protocol.Stat path -> handleInput AccessTypeStat path
Protocol.LStat path -> handleInput AccessTypeStat path
Protocol.OpenDir path -> handleInput AccessTypeFull path
Protocol.ReadLink path -> handleInput AccessTypeFull path
Protocol.Exec path -> handleInput AccessTypeFull path
Protocol.ExecP mPath attempted ->
handleInputs $
map (Input AccessTypeFull) (maybeToList mPath) ++
map (Input AccessTypeModeOnly) attempted
Protocol.RealPath path -> handleInput AccessTypeModeOnly path
where
handlers = jobFSAccessHandlers job
handleDelayed inputs outputs = wrap $ delayedFSAccessHandler handlers actDesc inputs outputs
handleUndelayed inputs outputs = wrap $ undelayedFSAccessHandler handlers actDesc inputs outputs
wrap = wrapHandler job conn isDelayed
actDesc = fromString (Protocol.showFunc func) <> " done by " <> jobLabel job
handleInput accessType path = handleInputs [Input accessType path]
handleInputs inputs =
case isDelayed of
NotDelayed -> handleUndelayed inputs []
Delayed -> handleDelayed inputs []
inputOfOutputPair (_behavior, Protocol.OutFilePath path _effect) =
Input AccessTypeModeOnly path
mkDelayedOutput ( behavior, Protocol.OutFilePath path _effect) =
DelayedOutput behavior path
handleOutputs = handle []
handle inputs outputPairs =
case isDelayed of
NotDelayed -> handleUndelayed allInputs $ map snd outputPairs
Delayed -> handleDelayed allInputs $ map mkDelayedOutput outputPairs
where
allInputs = inputs ++ map inputOfOutputPair outputPairs
wrapHandler :: RunningJob -> Socket -> IsDelayed -> IO () -> IO ()
wrapHandler job conn isDelayed handler =
forwardExceptions $ do
handler
-- Intentionally avoid sendGo if jobFSAccessHandler failed. It
-- means we disallow the effect.
case isDelayed of
Delayed -> sendGo conn
NotDelayed -> return ()
where
forwardExceptions =
handleSync $ \[email protected] {} ->
E.throwTo (jobThreadId job) e
withRegistered :: Ord k => IORef (Map k a) -> k -> a -> IO r -> IO r
withRegistered registry key val =
bracket_ register unregister
where
register = atomicModifyIORef_ registry $ M.insert key val
unregister = atomicModifyIORef_ registry $ M.delete key
handleJobConnection :: String -> Socket -> RunningJob -> Need -> IO ()
handleJobConnection tidStr conn job _need = do
-- This lets us know for sure that by the time the slave dies,
-- we've seen its connection
connId <- Fresh.next $ jobFreshConnIds job
tid <- myThreadId
connFinishedMVar <- newEmptyMVar
(`finally` putMVar connFinishedMVar ()) $
withRegistered (jobActiveConnections job) connId (tid, readMVar connFinishedMVar) $ do
sendGo conn
recvLoop_ (handleJobMsg tidStr conn job <=< Protocol.parseMsg) conn
mkEnvVars :: FSHook -> FilePath -> JobId -> Process.Env
mkEnvVars fsHook rootFilter jobId =
(map . fmap) BS8.unpack
[ ("LD_PRELOAD", fsHookLdPreloadPath fsHook)
, ("DYLD_FORCE_FLAT_NAMESPACE", "1")
, ("DYLD_INSERT_LIBRARIES", fsHookLdPreloadPath fsHook)
, ("BUILDSOME_MASTER_UNIX_SOCKADDR", fsHookServerAddress fsHook)
, ("BUILDSOME_JOB_ID", jobId)
, ("BUILDSOME_ROOT_FILTER", rootFilter)
]
timedRunCommand ::
FSHook -> FilePath -> (Process.Env -> IO r) -> ColorText ->
FSAccessHandlers -> IO (NominalDiffTime, r)
timedRunCommand fsHook rootFilter cmd label fsAccessHandlers = do
pauseTimeRef <- newIORef 0
let
addPauseTime delta = atomicModifyIORef'_ pauseTimeRef (+delta)
measurePauseTime act = do
(time, res) <- timeIt act
addPauseTime time
return res
wrappedFsAccessHandler isDelayed handler accessDoc inputs outputs = do
let act = handler accessDoc inputs outputs
case isDelayed of
Delayed -> measurePauseTime act
NotDelayed -> act
wrappedFsAccessHandlers =
FSAccessHandlers
(wrappedFsAccessHandler Delayed delayed)
(wrappedFsAccessHandler NotDelayed undelayed)
(time, res) <-
runCommand fsHook rootFilter (timeIt . cmd) label wrappedFsAccessHandlers
subtractedTime <- (time-) <$> readIORef pauseTimeRef
return (subtractedTime, res)
where
FSAccessHandlers delayed undelayed = fsAccessHandlers
withRunningJob :: FSHook -> JobId -> RunningJob -> IO r -> IO r
withRunningJob fsHook jobId job body = do
setJob (LiveJob job)
(body <* setJob (CompletedJob (jobLabel job)))
`onException` setJob (KillingJob (jobLabel job))
where
registry = fsHookRunningJobs fsHook
setJob = atomicModifyIORef_ registry . M.insert jobId
runCommand ::
FSHook -> FilePath -> (Process.Env -> IO r) -> ColorText ->
FSAccessHandlers -> IO r
runCommand fsHook rootFilter cmd label fsAccessHandlers = do
activeConnections <- newIORef M.empty
freshConnIds <- Fresh.new 0
jobIdNum <- Fresh.next $ fsHookFreshJobIds fsHook
tid <- myThreadId
let jobId = BS8.pack ("cmd" ++ show jobIdNum)
job = RunningJob
{ jobLabel = label
, jobActiveConnections = activeConnections
, jobFreshConnIds = freshConnIds
, jobThreadId = tid
, jobRootFilter = rootFilter
, jobFSAccessHandlers = fsAccessHandlers
}
-- Don't leak connections still running our handlers once we leave!
let onActiveConnections f = mapM_ f . M.elems =<< readIORef activeConnections
(`onException` onActiveConnections killConnection) $
do
res <-
withRunningJob fsHook jobId job $ cmd $ mkEnvVars fsHook rootFilter jobId
let timeoutMsg =
Printer.render (fsHookPrinter fsHook)
(label <> ": Process completed, but still has likely-leaked " <>
"children connected to FS hooks")
Timeout.warning (Timeout.seconds 5) timeoutMsg $
onActiveConnections awaitConnection
return res
where
killConnection (tid, awaitConn) = killThread tid >> awaitConn
awaitConnection (_tid, awaitConn) = awaitConn
data CannotFindOverrideSharedObject = CannotFindOverrideSharedObject deriving (Show, Typeable)
instance E.Exception CannotFindOverrideSharedObject
assertLdPreloadPathExists :: FilePath -> IO ()
assertLdPreloadPathExists path = do
e <- FilePath.exists path
unless e $ E.throwIO CannotFindOverrideSharedObject
getLdPreloadPath :: Maybe FilePath -> IO FilePath
getLdPreloadPath (Just path) = do
ldPreloadPath <- canonicalizePath path
assertLdPreloadPathExists ldPreloadPath
return ldPreloadPath
getLdPreloadPath Nothing = do
installedFilePath <- BS8.pack <$> (getDataFileName . BS8.unpack) fileName
installedExists <- FilePath.exists installedFilePath
if installedExists
then return installedFilePath
else do
argv0 <- getArgv0
let nearExecPath = takeDirectory argv0 </> fileName
assertLdPreloadPathExists nearExecPath
return nearExecPath
where
fileName = "cbits/fs_override.so"
|
da-x/buildsome
|
src/Lib/FSHook.hs
|
gpl-2.0
| 16,102 | 0 | 24 | 3,443 | 4,154 | 2,174 | 1,980 | 326 | 24 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
import Control.Monad.Free
import Data.List
import qualified GHC.Generics as GHC
import Reflex
import Reflex.Dom
----------
type Name = String
type Info = String
data Vocab a where
GetName :: (Name -> a) -> Vocab a
PutInfo :: Info -> a -> Vocab a
deriving (GHC.Generic)
instance Functor Vocab where
fmap f = \case
GetName g -> GetName (f . g)
PutInfo s a -> PutInfo s (f a)
getName :: MonadFree Vocab m => m Name
getName = liftF $ GetName id
putInfo :: MonadFree Vocab m => Info -> m ()
putInfo s = liftF $ PutInfo s ()
----------
type Req = (Name -> Free Vocab ())
dissociate :: Free Vocab () -> ([Info], Maybe Req)
dissociate s0 = case s0 of
Pure () -> ([], Nothing)
Free w -> case w of
GetName g -> ([], Just g)
PutInfo x s1 -> dissociate s1 & _1 %~ (x :)
step :: Name -> ([Info], Maybe Req) -> ([Info], Maybe Req)
step n (xs, r) = case r of
Nothing -> (xs, Nothing)
Just g -> dissociate $ g n
----------
mySession :: MonadFree Vocab m => m ()
mySession = putInfo "Welcome to Reflex." >> go
where
go :: MonadFree Vocab m => m ()
go = do
xs <- getName
mapM_ putInfo $ fmap ($ xs) [id, reverse, show . length]
go
----------
submitName :: MonadWidget t m => m (Event t String)
submitName = do
rec t <- textInput $ def & setValue .~ fmap (\_ -> "") e
e <- button "Submit"
return $ ffilter (/= "") $ tag (current (value t)) e
sayHello :: MonadWidget t m => Event t String -> m ()
sayHello e = do
let h = fmap (\xs -> "Hello, " ++ xs ++ ".") e
d <- holdDyn ((intercalate ", ") . fst $ dissociate mySession) h
dynText d
----------
main :: IO ()
main = mainWidget $
el "div" $ do
e <- submitName
e1 <- el "div" $ do
d <- foldDyn step (dissociate mySession) e
d1 <- mapDyn ((intercalate ", ") . fst) d
return $ updated d1
el "div" $ do
sayHello $ e1
----------
|
artuuge/free-running
|
helloFreeReflex.hs
|
gpl-2.0
| 2,090 | 0 | 17 | 525 | 891 | 452 | 439 | 64 | 3 |
{- |
Module : Engine
Description : The engine playing a game on a `Playfield`
Copyright : (c) Frédéric BISSON, 2015
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
The engine handles the rules of the game:
- apply `Action`
- manage out of bounds elements
- designate the winner
-}
module Tank.Game.Engine
( Winner (..)
, playActionS
) where
import Control.Lens
import Control.Monad.State.Lazy
import Tank.Units
import Tank.Elements
import Tank.Game.Playfield
import Tank.Game.Action
{-|
Designates who is the winner, if any.
-}
data Winner = NoWinner -- ^ No winner, the game may go on
| DrawGame -- ^ No winner but it’s a draw game
| Winner TankID -- ^ Someone won!
deriving (Eq, Show)
{-|
Play couples of `Action` on a `Playfield` and look for a `Winner` (or no winner
if the list is exhausted).
-}
playActionS :: Monad m => [(Action, Action)] -> StateT Playfield m Winner
playActionS [] = return NoWinner
playActionS ((action1, action2):actions) = do
moveMissilesS
runActionS action1
runActionS action2
clearOutOfBoundS
winner <- findWinner
if winner == NoWinner then playActionS actions
else return winner
{-|
Find which `Tank` is the `Winner`.
-}
findWinner :: Monad m => StateT Playfield m Winner
findWinner = do
(t1, t2) <- use pTanks
missiles <- use pMissiles
let findHit tank = missiles^..folded.missilePos.filtered (cover tank)
return $ case (findHit t1, findHit t2) of
([], []) -> NoWinner
([], _) -> Winner TankA
(_, []) -> Winner TankB
_ -> DrawGame
{-|
Clear out of bounds elements (`Missile`) from the `Playfield` since they can
no longer interact with the rest of the game.
-}
clearOutOfBoundS :: Monad m => StateT Playfield m ()
clearOutOfBoundS = do
bounds <- use pConstraint
pMissiles %= filter (isInside bounds . view missilePos)
{-|
Apply an `Action` to the `Playfield`.
-}
runActionS :: Monad m => Action -> StateT Playfield m ()
runActionS DoNothing = return ()
runActionS (Forward tid) = zoom (toTank tid) tankForwardS
runActionS (Backward tid) = zoom (toTank tid) tankBackwardS
runActionS (TurnCat tid a) = zoom (toTank tid) (tankCatTurnS a)
runActionS (TurnTur tid a) = zoom (toTank tid) (tankTurTurnS a)
runActionS (Fire tid) = do
mMissile <- zoom (toTank tid) tankFireS
pMissiles %= maybeInsert mMissile
runActionS (DropMine tid) = do
mMine <- zoom (toTank tid) tankDropMineS
pMines %= maybeInsert mMine
|
Zigazou/Tank
|
src/Tank/Game/Engine.hs
|
gpl-3.0
| 2,565 | 0 | 13 | 567 | 655 | 330 | 325 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Git
( module Git
, Text
) where
import Control.DeepSeq
import Control.Monad
import Data.Function
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import GHC.IO.Encoding (utf8, setLocaleEncoding, getLocaleEncoding, textEncodingName)
import Prelude hiding (FilePath)
import Shelly
type GitRef = Text
type CommitId = Text
-- | Run @git@ operation
runGit :: FilePath -> Text -> [Text] -> Sh Text
runGit d op args = do
d' <- toTextWarn d
out <- withUtf8 $ silently $ run "git" ("--git-dir=" <> d' : op : args)
return out
-- | WARNING: non-reentrant Hack!
withUtf8 :: Sh a -> Sh a
withUtf8 act = do
oldloc <- liftIO getLocaleEncoding
if (textEncodingName oldloc == textEncodingName utf8)
then act
else do
liftIO $ setLocaleEncoding utf8
r <- act
liftIO $ setLocaleEncoding oldloc
return r
-- | wrapper around @git cat-file commit@
--
-- Returns (commit-header, commit-body)
gitCatCommit :: FilePath -> GitRef -> Sh (Text,Text)
gitCatCommit d ref = do
tmp <- runGit d "cat-file" ["commit", ref ]
return (fmap (T.drop 2) $ T.breakOn "\n\n" tmp)
-- | wrapper around @git cat-file commit@
gitCatBlob :: FilePath -> GitRef -> Sh Text
gitCatBlob d ref = do
tmpl <- liftM tread $ runGit d "cat-file" ["-s", ref] -- workaround shelly adding EOLs
tmp <- runGit d "cat-file" ["blob", ref]
return (T.take tmpl tmp)
where
tread = read . T.unpack
-- | Wrapper around @git rev-parse --verify@
--
-- Normalise git ref to commit sha1
gitNormCid :: FilePath -> GitRef -> Sh CommitId
gitNormCid d ref = do
tmp <- runGit d "rev-parse" ["-q", "--verify", ref <> "^{commit}" ]
return (T.strip tmp)
-- | wrapper around @git branch --contains@
gitBranchesContain :: FilePath -> GitRef -> Sh [Text]
gitBranchesContain d ref = do
tmp <- liftM T.lines $
errExit False $ print_stderr False $
runGit d "branch" ["--contains", ref]
unless (all (\s -> T.take 2 s `elem` [" ","* "]) tmp) $
fail "gitBranchesContain: internal error"
return $!! map (T.drop 2) tmp
-- | returns @[(path, (url, key))]@
--
-- may throw exception
getModules :: FilePath -> GitRef -> Sh [(Text, (Text, Text))]
getModules d ref = do
tmp <- runGit d "show" [ref <> ":.gitmodules"]
setStdin tmp
res <- liftM T.lines $ runGit d "config" [ "--file", "/dev/stdin", "-l" ]
let ms = [ (T.tail key1,(key2, T.tail val))
| r <- res, "submodule." `T.isPrefixOf` r
, let (key,val) = T.break (=='=') r
, let (key',key2) = T.breakOnEnd "." key
, let (_,key1) = T.break (=='.') (T.init key')
]
ms' = [ (path', (url, k))
| es@((k,_):_) <- groupBy ((==) `on` fst) ms
, let props = map snd es
, let url = fromMaybe (error "getModules1") (lookup "url" props)
, let path' = fromMaybe (error "getModules2") (lookup "path" props)
]
return $!! ms'
-- | The state of a file in the parent of a git commit and the changes
-- thereof.
data CommitParent
= CommitParent { srcFileType :: !GitType
, changeType :: !ChangeType
, srcHash :: !Text
}
deriving (Show)
instance NFData CommitParent where rnf !_ = ()
-- | The changes to a file in a git commit
data ChangedFile = ChangedFile { parents :: [CommitParent]
, dstType :: !GitType
, dstHash :: !Text
, dstPath :: !Text
}
deriving (Show)
instance NFData ChangedFile where
rnf !a = rnf (parents a) `seq` ()
data ChangeType
= FileAdded
| FileCopied
| FileDeleted
| FileModified
| FileRenamed
| FileTypeChanged
-- ^ e.g. changed between regular file, symlink, submodule, ...
| FileUnmerged
| FileUnknown
| FilePairingBroken
deriving (Show)
instance NFData ChangeType where rnf !_ = ()
gitDiffTree :: FilePath -> GitRef -> Sh (CommitId, [ChangedFile])
gitDiffTree d ref = do
tmp <- liftM T.lines $ runGit d "diff-tree" ["--root","-c", "-r", ref]
case tmp of
cid:deltas -> return $!! (cid, map parseDtLine deltas)
[] -> return ("", [])
where
parseStatus :: Char -> ChangeType
parseStatus c =
case c of
'A' -> FileAdded
'C' -> FileCopied
'D' -> FileDeleted
'M' -> FileModified
'R' -> FileRenamed
'T' -> FileTypeChanged
'U' -> FileUnmerged
'X' -> FileUnknown
'B' -> FilePairingBroken
_ -> error $ "parseDtLine: unknown file status "++[c]
parseDtLine :: Text -> ChangedFile
parseDtLine l
= ChangedFile { parents = _parents
, dstType = cvtMode _dstMode
, dstHash = _dstHash
, dstPath = _dstPath
}
where
(modes, _dstMode:rest) = splitAt nParents $ T.split (==' ') l''
(hashes, [_dstHash, _status]) = splitAt nParents rest
_parents = zipWith3 CommitParent (map cvtMode modes) (map parseStatus $ T.unpack _status) hashes
[l'', _dstPath] = T.split (=='\t') l'
(colons, l') = T.span (==':') l
nParents = T.length colons
gitDiffTreePatch :: FilePath -> GitRef -> Text -> Sh Text
gitDiffTreePatch d ref fname = runGit d "diff-tree" ["--root", "--cc", "-r", ref, "--", fname]
z40 :: GitRef
z40 = T.pack (replicate 40 '0')
data GitType
= GitTypeVoid
| GitTypeRegFile
| GitTypeExeFile
| GitTypeTree
| GitTypeSymLink
| GitTypeGitLink
deriving (Show,Eq,Ord,Enum)
instance NFData GitType where rnf !_ = ()
cvtMode :: Text -> GitType
cvtMode "000000" = GitTypeVoid
cvtMode "040000" = GitTypeSymLink
cvtMode "100644" = GitTypeRegFile
cvtMode "100755" = GitTypeExeFile
cvtMode "120000" = GitTypeSymLink
cvtMode "160000" = GitTypeGitLink
cvtMode x = error ("cvtMode: " ++ show x)
|
bgamari/git-haskell-org-hooks
|
src/Git.hs
|
gpl-3.0
| 6,276 | 0 | 18 | 1,888 | 1,899 | 1,004 | 895 | 160 | 11 |
import qualified Data.ByteString.Char8 as B
import System.Fuse
import System.Environment
import System.Posix.Types
import Shiny.FS.Internal
import Shiny.Hardware (Hardware)
--import Shiny.Hardware.Dummy (mkDummyHardware)
import Shiny.Hardware.Serial (mkSerialHardware)
import Control.Applicative
import Control.Monad
import Control.Concurrent.MVar
type HT = ()
ledFSOps :: Hardware -> IO (FuseOperations HT)
ledFSOps hw = do
tree <- mkFileTree hw
mvar <- newMVar (FSState hw tree)
return defaultFuseOps { fuseGetFileStat = ledGetFileStat mvar
, fuseOpen = ledOpen mvar
, fuseRead = ledRead mvar
, fuseWrite = ledWrite mvar
, fuseSetFileSize = ledTruncate mvar
, fuseOpenDirectory = ledOpenDirectory mvar
, fuseReadDirectory = ledReadDirectory mvar
, fuseGetFileSystemStats = ledGetFileSystemStats mvar
}
ledGetFileStat :: MVar FSState -> FilePath -> IO (Either Errno FileStat)
ledGetFileStat mvar path = withMVar mvar $ \FSState{fileTree=tree} ->
case (lookupPath path tree) of
Just t -> Right <$> (stat t)
Nothing -> return (Left eNOENT)
ledOpenDirectory :: MVar FSState -> FilePath -> IO (Errno)
ledOpenDirectory mvar path = withMVar mvar $ \FSState{fileTree=tree} ->
case (lookupPath path tree) of
Just Dir{} -> return eOK
_ -> return eNOENT
ledReadDirectory :: MVar FSState -> FilePath -> IO (Either Errno [(FilePath, FileStat)])
ledReadDirectory mvar path = withMVar mvar $ \FSState{fileTree=tree} ->
case (lookupPath path tree) of
Just (Dir _ children) -> liftM Right $ mapM pathStat children
_ -> return (Left eNOENT)
where pathStat child = do
st <- stat child
return (treeName child, st)
ledOpen :: MVar FSState -> FilePath -> OpenMode -> OpenFileFlags -> IO (Either Errno HT)
ledOpen mvar path _ _ = withMVar mvar $ \FSState{fileTree=tree} ->
case (lookupPath path tree) of
Just File {} -> return (Right ())
_ -> return (Left eNOENT)
ledRead :: MVar FSState -> FilePath -> HT -> ByteCount -> FileOffset -> IO (Either Errno B.ByteString)
ledRead mvar path _ count offset = withMVar mvar $ \FSState{fileTree=tree} ->
case (lookupPath path tree) of
Just f@File{} -> fileRead f count offset
_ -> return (Left eNOENT)
ledWrite :: MVar FSState -> FilePath -> HT -> B.ByteString -> FileOffset -> IO (Either Errno ByteCount)
ledWrite mvar path _ dataIn offset = withMVar mvar $ \FSState{fileTree=tree} ->
case (lookupPath path tree) of
Just f@File{} -> fileWrite f dataIn offset
_ -> return (Left eNOENT)
ledTruncate :: MVar FSState -> FilePath -> FileOffset -> IO Errno
ledTruncate _ _ _ = return eOK
ledGetFileSystemStats :: MVar FSState -> FilePath -> IO (Either Errno FileSystemStats)
ledGetFileSystemStats _ _ =
return $ Right $ FileSystemStats
{ fsStatBlockSize = 512
, fsStatBlockCount = 1
, fsStatBlocksFree = 1
, fsStatBlocksAvailable = 1
, fsStatFileCount = 5
, fsStatFilesFree = 10
, fsStatMaxNameLength = 255
}
main :: IO()
main = do
progName <- getProgName
args <- getArgs
hw <- mkSerialHardware "/dev/ttyACM0" (8*40)
fs <- ledFSOps hw
fuseRun progName args fs defaultExceptionHandler
|
dhrosa/shinyfs
|
Shiny/FS.hs
|
gpl-3.0
| 3,500 | 0 | 13 | 949 | 1,138 | 576 | 562 | 75 | 2 |
module EightPuzzle
(
) where
import EightPuzzle.Internal
|
cdepillabout/coursera
|
algorithms1/week4/src/EightPuzzle.hs
|
gpl-3.0
| 66 | 0 | 4 | 16 | 12 | 8 | 4 | 3 | 0 |
{-
Pandoc filter that cleans up internal references to figures and tables (tables soon!).
Compile with:
ghc --make pandoc-internalref.hs
and use in pandoc with
--filter [PATH]/pandoc-internalref
-}
module Main where
import System.Environment
import Text.Pandoc.JSON
import Text.Pandoc.Walk (walk, walkM)
import Data.List (stripPrefix, delete)
import Control.Monad ((>=>))
main = toJSONFilter pandocSeq
{-main = putStrLn "a"-}
pandocSeq :: (Maybe Format) -> (Pandoc -> IO Pandoc)
pandocSeq (Just (Format "latex")) = (walkM fixlink) >=> baseSeq >=> (walkM latexRef)
pandocSeq (Just (Format "native")) = (walkM fixlink) >=> baseSeq >=> (walkM latexRef)
{-pandocSeq _ = return -}
pandocSeq _ = baseSeq
baseSeq :: Pandoc -> IO Pandoc
baseSeq = (walkM floatAttribute)
{-baseSeq = (walkM fixlink) >=> (walkM floatAttribute)-}
-- fix latex internal ref's
fixlink :: Inline -> IO Inline
fixlink (Link txt ('#':ident, x))
| Just subident <- stripPrefix "fig:" ident = return reflink
| Just subident <- stripPrefix "tab:" ident = return reflink
where reflink = Link [RawInline (Format "latex") ("\\ref*{" ++ ident ++ "}")] ("#" ++ ident, x)
fixlink x = return x
-- read attributes into a div
floatAttribute:: Block -> IO Block
floatAttribute (Para ((Image caps (src,_)):(Str ('{':'#':label)):rest)) =
return (Div ((delete '}' label), classes, []) [Para [Image caps' (src, "fig:")]])
where
caps' = caps
classes = [delete '}' str | Str str <- rest]
floatAttribute (Table caps aligns widths headers rows)
| attribCaps /= [] = return (Div (ident, classes', []) [Table goodCaps aligns widths headers rows])
where
(goodCaps, attribCaps) = break capStartsAttribs caps
capStartsAttribs (Str capcontent) = head capcontent == '{'
capStartsAttribs x = False
classes = [delete '{' (delete '}' str) | Str str <- attribCaps]
ident | (head $ head classes) == '#' = tail $ head classes
| otherwise = ""
classes' | (head $ head classes) == '#' = tail classes
| otherwise = classes
{-goodCaps = takeWhile (\a -> ) caps-}
{-Str lastCap = last caps-}
{-hasTableAttribs = (head lastCap == '{') && (tail lastCap == '}')-}
floatAttribute x = return x
-- add \label to image captions
latexRef :: Block -> IO Block
latexRef (Div (ident, classes, kvs) [Para [Image caps src]]) =
return (Div (ident, classes, kvs)
[Para [Image (caps ++ [RawInline (Format "tex") ("\\label{" ++ ident ++ "}")]) src]])
latexRef (Div (ident, classes, kvs) [Table caps aligns widths headers rows]) =
return (Div (ident, classes, kvs)
[Table (caps ++ [RawInline (Format "tex") ("\\label{" ++ ident ++ "}")]) aligns widths headers rows])
latexRef x = return x
|
balachia/pandoc-filters
|
pandoc-internalref.hs
|
gpl-3.0
| 2,808 | 0 | 18 | 613 | 970 | 504 | 466 | 43 | 2 |
{-# 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.ServiceNetworking.Services.DNSZones.Add
-- 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)
--
-- Service producers can use this method to add private DNS zones in the
-- shared producer host project and matching peering zones in the consumer
-- project.
--
-- /See:/ <https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started Service Networking API Reference> for @servicenetworking.services.dnsZones.add@.
module Network.Google.Resource.ServiceNetworking.Services.DNSZones.Add
(
-- * REST Resource
ServicesDNSZonesAddResource
-- * Creating a Request
, servicesDNSZonesAdd
, ServicesDNSZonesAdd
-- * Request Lenses
, sdzaParent
, sdzaXgafv
, sdzaUploadProtocol
, sdzaAccessToken
, sdzaUploadType
, sdzaPayload
, sdzaCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceNetworking.Types
-- | A resource alias for @servicenetworking.services.dnsZones.add@ method which the
-- 'ServicesDNSZonesAdd' request conforms to.
type ServicesDNSZonesAddResource =
"v1" :>
Capture "parent" Text :>
"dnsZones:add" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AddDNSZoneRequest :>
Post '[JSON] Operation
-- | Service producers can use this method to add private DNS zones in the
-- shared producer host project and matching peering zones in the consumer
-- project.
--
-- /See:/ 'servicesDNSZonesAdd' smart constructor.
data ServicesDNSZonesAdd =
ServicesDNSZonesAdd'
{ _sdzaParent :: !Text
, _sdzaXgafv :: !(Maybe Xgafv)
, _sdzaUploadProtocol :: !(Maybe Text)
, _sdzaAccessToken :: !(Maybe Text)
, _sdzaUploadType :: !(Maybe Text)
, _sdzaPayload :: !AddDNSZoneRequest
, _sdzaCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesDNSZonesAdd' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sdzaParent'
--
-- * 'sdzaXgafv'
--
-- * 'sdzaUploadProtocol'
--
-- * 'sdzaAccessToken'
--
-- * 'sdzaUploadType'
--
-- * 'sdzaPayload'
--
-- * 'sdzaCallback'
servicesDNSZonesAdd
:: Text -- ^ 'sdzaParent'
-> AddDNSZoneRequest -- ^ 'sdzaPayload'
-> ServicesDNSZonesAdd
servicesDNSZonesAdd pSdzaParent_ pSdzaPayload_ =
ServicesDNSZonesAdd'
{ _sdzaParent = pSdzaParent_
, _sdzaXgafv = Nothing
, _sdzaUploadProtocol = Nothing
, _sdzaAccessToken = Nothing
, _sdzaUploadType = Nothing
, _sdzaPayload = pSdzaPayload_
, _sdzaCallback = Nothing
}
-- | Required. The service that is managing peering connectivity for a
-- service producer\'s organization. For Google services that support this
-- functionality, this value is
-- \`services\/servicenetworking.googleapis.com\`.
sdzaParent :: Lens' ServicesDNSZonesAdd Text
sdzaParent
= lens _sdzaParent (\ s a -> s{_sdzaParent = a})
-- | V1 error format.
sdzaXgafv :: Lens' ServicesDNSZonesAdd (Maybe Xgafv)
sdzaXgafv
= lens _sdzaXgafv (\ s a -> s{_sdzaXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sdzaUploadProtocol :: Lens' ServicesDNSZonesAdd (Maybe Text)
sdzaUploadProtocol
= lens _sdzaUploadProtocol
(\ s a -> s{_sdzaUploadProtocol = a})
-- | OAuth access token.
sdzaAccessToken :: Lens' ServicesDNSZonesAdd (Maybe Text)
sdzaAccessToken
= lens _sdzaAccessToken
(\ s a -> s{_sdzaAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sdzaUploadType :: Lens' ServicesDNSZonesAdd (Maybe Text)
sdzaUploadType
= lens _sdzaUploadType
(\ s a -> s{_sdzaUploadType = a})
-- | Multipart request metadata.
sdzaPayload :: Lens' ServicesDNSZonesAdd AddDNSZoneRequest
sdzaPayload
= lens _sdzaPayload (\ s a -> s{_sdzaPayload = a})
-- | JSONP
sdzaCallback :: Lens' ServicesDNSZonesAdd (Maybe Text)
sdzaCallback
= lens _sdzaCallback (\ s a -> s{_sdzaCallback = a})
instance GoogleRequest ServicesDNSZonesAdd where
type Rs ServicesDNSZonesAdd = Operation
type Scopes ServicesDNSZonesAdd =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient ServicesDNSZonesAdd'{..}
= go _sdzaParent _sdzaXgafv _sdzaUploadProtocol
_sdzaAccessToken
_sdzaUploadType
_sdzaCallback
(Just AltJSON)
_sdzaPayload
serviceNetworkingService
where go
= buildClient
(Proxy :: Proxy ServicesDNSZonesAddResource)
mempty
|
brendanhay/gogol
|
gogol-servicenetworking/gen/Network/Google/Resource/ServiceNetworking/Services/DNSZones/Add.hs
|
mpl-2.0
| 5,643 | 0 | 17 | 1,257 | 789 | 463 | 326 | 116 | 1 |
-- | ECDSA Signatures
module Network.Haskoin.Crypto.ECDSA
( SecretT
, Signature(..)
, withSource
, getEntropy
, signMsg
, verifySig
, genPrvKey
, isCanonicalHalfOrder
, decodeDerSig
, decodeStrictSig
) where
import Control.DeepSeq (NFData, rnf)
import Control.Monad (guard, unless, when)
import qualified Control.Monad.State as S (StateT, evalStateT, get, put)
import Control.Monad.Trans (lift)
import qualified Crypto.Secp256k1 as EC
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Short (toShort)
import Data.Maybe (fromMaybe)
import Data.Serialize (Serialize, encode, get, put)
import Data.Serialize.Get (getByteString, getWord8,
lookAhead)
import Data.Serialize.Put (putByteString)
import Network.Haskoin.Constants
import Network.Haskoin.Crypto.Hash
import Network.Haskoin.Crypto.Keys
import Numeric (showHex)
import System.Entropy (getEntropy)
-- | Internal state of the 'SecretT' monad
type SecretState m = (WorkingState, Int -> m ByteString)
-- | StateT monad stack tracking the internal state of HMAC DRBG
-- pseudo random number generator using SHA-256. The 'SecretT' monad is
-- run with the 'withSource' function by providing it a source of entropy.
type SecretT m = S.StateT (SecretState m) m
-- | Run a 'SecretT' monad by providing it a source of entropy. You can
-- use 'getEntropy' or provide your own entropy source function.
withSource :: Monad m => (Int -> m ByteString) -> SecretT m a -> m a
withSource f m = do
seed <- f 32 -- Read 256 bits from the random source
nonce <- f 16 -- Read 128 bits from the random source
let ws = hmacDRBGNew seed nonce haskoinUserAgent
S.evalStateT m (ws,f)
-- | Generate a new random 'EC.SecKey' value from the 'SecretT' monad. This
-- will invoke the HMAC DRBG routine. Of the internal entropy pool of the HMAC
-- DRBG was stretched too much, this function will reseed it.
nextSecret :: Monad m => SecretT m EC.SecKey
nextSecret = do
(ws, f) <- S.get
let (ws', randM) = hmacDRBGGen ws 32 haskoinUserAgent
case randM of
(Just rand) -> do
S.put (ws', f)
case EC.secKey rand of
Just key -> return key
Nothing -> nextSecret
Nothing -> do
seed <- lift $ f 32 -- Read 256 bits to re-seed the PRNG
let ws0 = hmacDRBGRsd ws' seed haskoinUserAgent
S.put (ws0, f)
nextSecret
-- | Produce a new 'PrvKey' randomly from the 'SecretT' monad.
genPrvKey :: Monad m => SecretT m PrvKey
genPrvKey = makePrvKey <$> nextSecret
-- | Data type representing an ECDSA signature.
newtype Signature = Signature { getSignature :: EC.Sig }
deriving (Read, Show, Eq)
instance NFData Signature where
rnf (Signature s) = s `seq` ()
hashToMsg :: Hash256 -> EC.Msg
hashToMsg =
fromMaybe e . EC.msg . encode
where
e = error "Could not convert 32-byte hash to secp256k1 message"
-- <http://www.secg.org/sec1-v2.pdf Section 4.1.3>
-- | Sign a message
signMsg :: Hash256 -> PrvKeyI c -> Signature
signMsg h d = Signature $ EC.signMsg (prvKeySecKey d) (hashToMsg h)
-- | Verify an ECDSA signature
verifySig :: Hash256 -> Signature -> PubKeyI c -> Bool
verifySig h s q =
EC.verifySig p g m
where
(g, _) = EC.normalizeSig $ getSignature s
m = hashToMsg h
p = pubKeyPoint q
instance Serialize Signature where
get = do
l <- lookAhead $ do
t <- getWord8
-- 0x30 is DER sequence type
unless (t == 0x30) $ fail $
"Bad DER identifier byte 0x" ++ showHex t ". Expecting 0x30"
l <- getWord8
when (l == 0x00) $ fail "Indeterminate form unsupported"
when (l >= 0x80) $ fail "Multi-octect length not supported"
return $ fromIntegral l
bs <- getByteString $ l + 2
case decodeDerSig bs of
Just s -> return s
Nothing -> fail "Invalid signature"
put (Signature s) = putByteString $ EC.exportSig s
isCanonicalHalfOrder :: Signature -> Bool
isCanonicalHalfOrder = not . snd . EC.normalizeSig . getSignature
decodeDerSig :: ByteString -> Maybe Signature
decodeDerSig bs = Signature <$> EC.laxImportSig bs
decodeStrictSig :: ByteString -> Maybe Signature
decodeStrictSig bs = do
g <- EC.importSig bs
let compact = EC.exportCompactSig g
-- <http://www.secg.org/sec1-v2.pdf Section 4.1.4>
-- 4.1.4.1 (r and s can not be zero)
guard $ EC.getCompactSigR compact /= zero
guard $ EC.getCompactSigS compact /= zero
return $ Signature g
where
zero = toShort $ BS.replicate 32 0
|
plaprade/haskoin
|
haskoin-core/src/Network/Haskoin/Crypto/ECDSA.hs
|
unlicense
| 4,958 | 0 | 17 | 1,418 | 1,182 | 624 | 558 | 97 | 3 |
{-# LANGUAGE OverloadedStrings, CPP #-}
module FormStructure.Chapter7 (ch7Roles) where
#ifndef __HASTE__
--import Data.Text.Lazy (pack)
#endif
import FormEngine.FormItem
import FormStructure.Common
ch7Roles :: FormItem
ch7Roles = Chapter
{ chDescriptor = defaultFIDescriptor { iLabel = Just "7.Roles " }
, chItems = [roles, remark]
}
where
roles :: FormItem
roles = SimpleGroup
{ sgDescriptor = defaultFIDescriptor
{ iLabel = Just "Employed roles"
, iMandatory = True
}
, sgLevel = 0
, sgItems = [ NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Data producer"
, iTags = [Tag "box_1"]
, iLink = Just "Haste['toRoles']()"
}
, nfiUnit = SingleUnit "Full-time equivalent"
}
, NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Data expert"
, iTags = fmap Tag ["box_2", "box_3", "box_4_1"]
, iLink = Just "Haste['toRoles']()"
}
, nfiUnit = SingleUnit "Full-time equivalent"
}
, NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Data consumer"
, iTags = [Tag "box_3"]
, iLink = Just "Haste['toRoles']()"
}
, nfiUnit = SingleUnit "Full-time equivalent"
}
, NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Data curator"
, iTags = fmap Tag ["box_2", "box_3", "box_4_1", "box_5_i", "box_5_e", "box_6"]
, iLink = Just "Haste['toRoles']()"
}
, nfiUnit = SingleUnit "Full-time equivalent"
}
, NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Data custodian"
, iTags = fmap Tag ["box_4_1", "box_5_i", "box_5_e"]
, iLink = Just "Haste['toRoles']()"
}
, nfiUnit = SingleUnit "Full-time equivalent"
}
, NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Data steward"
, iTags = fmap Tag ["box_1", "box_2", "box_3", "box_4_1", "box_5_i", "box_5_e", "box_6"]
, iLink = Just "Haste['toRoles']()"
}
, nfiUnit = SingleUnit "Full-time equivalent"
}
, NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Data manager"
, iTags = fmap Tag ["box_1", "box_2", "box_4_1", "box_5_i", "box_5_e", "box_6"]
, iLink = Just "Haste['toRoles']()"
}
, nfiUnit = SingleUnit "Full-time equivalent"
}
]
}
|
DataStewardshipPortal/ds-elixir-cz
|
FormStructure/Chapter7.hs
|
apache-2.0
| 3,323 | 0 | 15 | 1,567 | 549 | 327 | 222 | 56 | 1 |
import Data.Matrix (matrix, inverse, nrows, multStd, toList)
import Data.Ratio ((%))
recursionMatrix n integerSequence = matrix n n (\(i,j) -> integerSequence !! (i + j - 2) % 1)
solutionMatrix n integerSequence = matrix n 1 (\(i,_) -> integerSequence !! (i + n - 1) % 1)
targetInverse integerSequence = (case biggestInverse of Right m -> m) where
biggestInverse = last $ takeWhile isRight allInverses where
allInverses = map (\n -> inverse $ recursionMatrix n integerSequence) [1..]
allSolutions = map (`solutionMatrix` integerSequence) [1..]
recursion integerSequence = toList $ multStd inverseMatrix (solutionMatrix matrixSize integerSequence) where
inverseMatrix = targetInverse integerSequence
matrixSize = nrows inverseMatrix
isRight (Right _) = True
isRight (Left _) = False
-- Conjecture:
-- A320099
-- 103*a(n-1) + 1063*a(n-2) - 1873*a(n-3) - 20274*a(n-4) + 44071*a(n-5) - 10365*a(n-6) - 20208*a(n-7) + 5959*a(n-8) + 2300*a(n-9) - 500*a(n-10) # for n > 10
|
peterokagey/haskellOEIS
|
src/Sandbox/RecursionFinder.hs
|
apache-2.0
| 984 | 0 | 13 | 159 | 300 | 163 | 137 | 13 | 1 |
import Data.Char (toUpper)
main :: IO Bool
main =
putStrLn "Is green your favorite color?" >>
getLine >>=
(\input -> return ((toUpper . head $ input) == 'Y'))
|
EricYT/Haskell
|
src/real_haskell/chapter-7/return1.hs
|
apache-2.0
| 174 | 0 | 13 | 43 | 64 | 34 | 30 | 6 | 1 |
module Data.GitParser
(module Data.GitParser.Parser
,module Data.GitParser.Types
,module Data.GitParser.Repo) where
import Data.GitParser.Repo
import Data.GitParser.Types
import Data.GitParser.Parser
|
jamessanders/gitparser
|
src/Data/GitParser.hs
|
bsd-2-clause
| 212 | 0 | 5 | 27 | 47 | 32 | 15 | 7 | 0 |
--
-- Copyright (c) 2013, Carl Joachim Svenn
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module Game.Run.Iteration
(
iterationShowFont,
) where
import MyPrelude
import Game
import Game.Run.RunWorld
import Font
import OpenGL
import OpenGL.Helpers
--------------------------------------------------------------------------------
-- demonstrate Font
iterationShowFont :: Iteration' RunWorld
iterationShowFont =
makeIteration' $ \run -> do
-- output
run' <- outputShowFont run
let s = (0.5, 0.3)
iteration' (iterationShowFont' s) run'
iterationShowFont' :: (Float, Float) -> Iteration' RunWorld
iterationShowFont' s =
defaultIteration s outputShowFont' $ defaultStep noDo $ \s run b -> do
keysTouchHandlePointTouched (run, b, [iterationShowFont' s]) $ \s' ->
(run, b, [iterationShowFont' s'])
--------------------------------------------------------------------------------
-- output
outputShowFont :: RunWorld -> MEnv' RunWorld
outputShowFont run = do
io $ putStrLn "iterationShowFont"
return run
outputShowFont' :: (Float, Float) -> RunWorld -> () -> MEnv' ((Float, Float), RunWorld, ())
outputShowFont' pos@(x, y) run b = do
-- setup Scene
run' <- beginRunScene run
fontshade <- resourceFontShade
fontdata <- resourceFontData
io $ do
glDisable gl_CULL_FACE
-- draw text to Screen
let proj2D = sceneProj2D $ runScene run'
fontShade fontshade 1.0 proj2D
fontDrawDefault fontshade fontdata (valueFontSize * shapeHth (sceneShape (runScene run))) valueFontColor
fontDraw2DCentered fontshade fontdata x y valueFontText
glEnable gl_CULL_FACE
return (pos, run', b)
where
valueFontSize = 0.04
valueFontColor = makeFontColorFloat 1.0 1.0 1.0 1.0
valueFontText = "Haskell inside!"
beginRunScene :: RunWorld -> MEnv' RunWorld
beginRunScene run = do
(wth, hth) <- screenSize
fbo <- screenFBO
io $ do
-- setup GL
glBindFramebuffer gl_FRAMEBUFFER fbo
glViewport 0 0 (fI wth) (fI hth)
glClear $ gl_COLOR_BUFFER_BIT .|. gl_DEPTH_BUFFER_BIT .|. gl_STENCIL_BUFFER_BIT
-- update Scene
return run { runScene = makeScene wth hth }
|
karamellpelle/MEnv
|
source/Game/Run/Iteration.hs
|
bsd-2-clause
| 3,701 | 0 | 17 | 880 | 599 | 317 | 282 | 49 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Text (pack, strip)
import STC
main :: IO ()
main = do
token <- readFile "telegram.token"
telegramBotServer . strip $ pack token
|
EleDiaz/StoryTellerChat
|
app/Main.hs
|
bsd-3-clause
| 220 | 0 | 8 | 57 | 60 | 32 | 28 | 8 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Antialiasing
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module corresponds to section 3.2 (Antialiasing) of the OpenGL 1.5
-- specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Antialiasing (
sampleBuffers, samples, multisample, subpixelBits
) where
import Graphics.Rendering.OpenGL.GL.Capability (
EnableCap(CapMultisample), makeCapability )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLsizei, Capability )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetSampleBuffers,GetSamples,GetSubpixelBits), getSizei1 )
import Graphics.Rendering.OpenGL.GL.StateVar (
GettableStateVar, makeGettableStateVar, StateVar )
--------------------------------------------------------------------------------
sampleBuffers :: GettableStateVar GLsizei
sampleBuffers = antialiasingInfo GetSampleBuffers
samples :: GettableStateVar GLsizei
samples = antialiasingInfo GetSamples
multisample :: StateVar Capability
multisample = makeCapability CapMultisample
subpixelBits :: GettableStateVar GLsizei
subpixelBits = antialiasingInfo GetSubpixelBits
antialiasingInfo :: GetPName -> GettableStateVar GLsizei
antialiasingInfo = makeGettableStateVar . getSizei1 id
|
FranklinChen/hugs98-plus-Sep2006
|
packages/OpenGL/Graphics/Rendering/OpenGL/GL/Antialiasing.hs
|
bsd-3-clause
| 1,563 | 0 | 6 | 172 | 205 | 131 | 74 | 19 | 1 |
{-# LANGUAGE TypeOperators #-}
-- |
-- Module : Data.OI.IO
-- Copyright : (c) Nobuo Yamashita 2011-2016
-- License : BSD3
-- Author : Nobuo Yamashita
-- Maintainer : [email protected]
-- Stability : experimental
--
module Data.OI.IO
(
-- * Interaction enable to handle I/O error
(:~>)
-- * I/O oprations
,openFile
,hIsClosed
,hIsEOF
,hGetLine
,hClose
,hPutStrLn
,isEOF
,getLine
,putStrLn
) where
import Data.OI.Internal
import System.IO (IOMode(..),Handle)
import qualified System.IO as IO
import System.FilePath
import Prelude hiding (getLine,putStrLn)
type a :~> b = OI (IOResult a) -> IOResult b
infixr 0 :~>
openFile :: FilePath -> IOMode -> Handle :~> Handle
openFile = (iooi' .) . IO.openFile
hIsClosed :: IO.Handle -> Bool :~> Bool
hIsClosed = iooi' . IO.hIsClosed
hIsEOF :: IO.Handle -> Bool :~> Bool
hIsEOF = iooi' . IO.hIsEOF
hGetLine :: IO.Handle -> String :~> String
hGetLine = iooi' . IO.hGetLine
hClose :: IO.Handle -> () :~> ()
hClose = iooi' . IO.hClose
hPutStrLn :: IO.Handle -> String -> () :~> ()
hPutStrLn = (iooi' .) . IO.hPutStrLn
isEOF :: Bool :~> Bool
isEOF = iooi' IO.isEOF
getLine :: String :~> String
getLine = iooi' IO.getLine
putStrLn :: String -> () :~> ()
putStrLn = iooi' . IO.putStrLn
|
nobsun/oi
|
src/Data/OI/IO.hs
|
bsd-3-clause
| 1,278 | 0 | 8 | 260 | 373 | 219 | 154 | 38 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
module DB.Create where
import Database.HDBC (run, commit)
import DB.Base
createDb ∷ FilePath → IO ()
createDb dbName = do
conn ← connect dbName
run conn ("CREATE TABLE IF NOT EXISTS tags " ++
"(id INTEGER PRIMARY KEY," ++
" name VARCHAR NOT NULL UNIQUE)") []
-- length
-- mtime, ctime, atime
-- inode (int)
run conn ("CREATE TABLE IF NOT EXISTS files " ++
"(id INTEGER PRIMARY KEY," ++
" name VARCHAR NOT NULL UNIQUE," ++
" contents BLOB NOT NULL)") []
run conn ("CREATE TABLE IF NOT EXISTS files_tags " ++
"(id INTEGER PRIMARY KEY," ++
" file_id INTEGER NOT NULL REFERENCES files," ++
" tag_id INTEGER NOT NULL REFERENCES tags," ++
" CONSTRAINT unique_file_tag UNIQUE (file_id, tag_id))") []
commit conn
disconnect conn
{-
dbStuff ∷ String → IO ()
dbStuff dbFileName = do
createDb dbFileName
conn ← connectSqlite3 dbFileName
-- addSomeData conn
-- viewData conn
disconnect conn
-}
|
marklar/TagFS
|
src/DB/Create.hs
|
bsd-3-clause
| 1,115 | 0 | 12 | 344 | 154 | 78 | 76 | 21 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module DataAnalysis04 where
import Data.Convertible (Convertible)
import Data.List (genericIndex, genericLength, genericTake)
import Database.HDBC (SqlValue, disconnect, fromSql, quickQuery')
import Database.HDBC.Sqlite3 (connectSqlite3)
import DataAnalysis02 (average)
readSqlColumn :: Convertible SqlValue a => [[SqlValue]] -> Integer -> [a]
readSqlColumn sqlResult index = map (fromSql . (`genericIndex` index)) sqlResult
queryDatabase :: FilePath -> String -> IO [[SqlValue]]
queryDatabase databaseFile sqlQuery = do
conn <- connectSqlite3 databaseFile
result <- quickQuery' conn sqlQuery []
disconnect conn
return result
pullStockClosingPrices :: FilePath -> String -> IO [(Double, Double)]
pullStockClosingPrices databaseFile database = do
sqlResult <- queryDatabase databaseFile
("SELECT rowid, adjclose FROM " ++ database)
return $ zip (reverse $ readSqlColumn sqlResult 0)
(readSqlColumn sqlResult 1)
percentChange :: Double -> Double -> Double
percentChange value first = 100 * (value - first) / first
applyPercentChangeToData :: [(Double, Double)] -> [(Double, Double)]
applyPercentChangeToData dataset = zip indices scaledData
where (_, first) = last dataset
indices = reverse [1.0 .. genericLength dataset]
scaledData = map (\(_, value) -> percentChange value first) dataset
movingAverage :: [Double] -> Integer -> [Double]
movingAverage values window
| window >= genericLength values = [average values]
| otherwise =
average (genericTake window values) : movingAverage (tail values) window
applyMovingAverageToData :: [(Double, Double)] -> Integer -> [(Double, Double)]
applyMovingAverageToData dataset window =
zip [fromIntegral window..] (movingAverage (map snd (reverse dataset)) window)
pullLatitudeLongitude :: FilePath -> String -> IO [(Double, Double)]
pullLatitudeLongitude databaseFile database = do
sqlResult <- queryDatabase databaseFile
("SELECT latitude, longitude FROM " ++ database)
return $ zip (readSqlColumn sqlResult 1) (readSqlColumn sqlResult 0)
|
mrordinaire/data-analysis
|
src/DataAnalysis04.hs
|
bsd-3-clause
| 2,145 | 0 | 11 | 381 | 664 | 350 | 314 | 41 | 1 |
module Graphics.UI.Font
( module Graphics.UI.Font.TextureAtlas
, module Graphics.UI.Font.TextureFont
, module Graphics.UI.Font.TextureGlyph
, module Graphics.UI.Font.Markup
, module Graphics.UI.Font.FontManager
)
where
import Graphics.UI.Font.TextureAtlas
import Graphics.UI.Font.TextureFont
import Graphics.UI.Font.TextureGlyph
import Graphics.UI.Font.Markup
import Graphics.UI.Font.FontManager
|
christiaanb/glfont
|
src/Graphics/UI/Font.hs
|
bsd-3-clause
| 423 | 0 | 5 | 56 | 84 | 61 | 23 | 11 | 0 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.DirectStateAccess
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the EXT_direct_state_access extension not
-- already in the OpenGL 3.1 core, see
-- <http://www.opengl.org/registry/specs/EXT/direct_state_access.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.DirectStateAccess (
-- * Functions
glClientAttribDefault,
glPushClientAttribDefault,
glMatrixLoadf,
glMatrixLoadd,
glMatrixMultf,
glMatrixMultd,
glMatrixLoadIdentity,
glMatrixRotatef,
glMatrixRotated,
glMatrixScalef,
glMatrixScaled,
glMatrixTranslatef,
glMatrixTranslated,
glMatrixOrtho,
glMatrixFrustum,
glMatrixPush,
glMatrixPop,
glTextureParameteri,
glTextureParameteriv,
glTextureParameterf,
glTextureParameterfv,
glTextureImage1D,
glTextureImage2D,
glTextureSubImage1D,
glTextureSubImage2D,
glCopyTextureImage1D,
glCopyTextureImage2D,
glCopyTextureSubImage1D,
glCopyTextureSubImage2D,
glGetTextureImage,
glGetTextureParameterfv,
glGetTextureParameteriv,
glGetTextureLevelParameterfv,
glGetTextureLevelParameteriv,
glTextureImage3D,
glTextureSubImage3D,
glCopyTextureSubImage3D,
glBindMultiTexture,
glMultiTexCoordPointer,
glMultiTexEnvf,
glMultiTexEnvfv,
glMultiTexEnvi,
glMultiTexEnviv,
glMultiTexGend,
glMultiTexGendv,
glMultiTexGenf,
glMultiTexGenfv,
glMultiTexGeni,
glMultiTexGeniv,
glGetMultiTexEnvfv,
glGetMultiTexEnviv,
glGetMultiTexGendv,
glGetMultiTexGenfv,
glGetMultiTexGeniv,
glMultiTexParameteri,
glMultiTexParameteriv,
glMultiTexParameterf,
glMultiTexParameterfv,
glMultiTexImage1D,
glMultiTexImage2D,
glMultiTexSubImage1D,
glMultiTexSubImage2D,
glCopyMultiTexImage1D,
glCopyMultiTexImage2D,
glCopyMultiTexSubImage1D,
glCopyMultiTexSubImage2D,
glGetMultiTexImage,
glGetMultiTexParameterfv,
glGetMultiTexParameteriv,
glGetMultiTexLevelParameterfv,
glGetMultiTexLevelParameteriv,
glMultiTexImage3D,
glMultiTexSubImage3D,
glCopyMultiTexSubImage3D,
glEnableClientStateIndexed,
glDisableClientStateIndexed,
glGetFloatIndexedv,
glGetDoubleIndexedv,
glGetPointerIndexedv,
glEnableIndexed,
glDisableIndexed,
glIsEnabledIndexed,
glGetIntegerIndexedv,
glGetBooleanIndexedv,
glNamedProgramString,
glNamedProgramLocalParameter4d,
glNamedProgramLocalParameter4dv,
glNamedProgramLocalParameter4f,
glNamedProgramLocalParameter4fv,
glGetNamedProgramLocalParameterdv,
glGetNamedProgramLocalParameterfv,
glGetNamedProgramiv,
glGetNamedProgramString,
glCompressedTextureImage3D,
glCompressedTextureImage2D,
glCompressedTextureImage1D,
glCompressedTextureSubImage3D,
glCompressedTextureSubImage2D,
glCompressedTextureSubImage1D,
glGetCompressedTextureImage,
glCompressedMultiTexImage3D,
glCompressedMultiTexImage2D,
glCompressedMultiTexImage1D,
glCompressedMultiTexSubImage3D,
glCompressedMultiTexSubImage2D,
glCompressedMultiTexSubImage1D,
glGetCompressedMultiTexImage,
glMatrixLoadTransposef,
glMatrixLoadTransposed,
glMatrixMultTransposef,
glMatrixMultTransposed,
glNamedBufferData,
glNamedBufferSubData,
glMapNamedBuffer,
glUnmapNamedBuffer,
glGetNamedBufferParameteriv,
glGetNamedBufferPointerv,
glGetNamedBufferSubData,
glProgramUniform1f,
glProgramUniform2f,
glProgramUniform3f,
glProgramUniform4f,
glProgramUniform1i,
glProgramUniform2i,
glProgramUniform3i,
glProgramUniform4i,
glProgramUniform1fv,
glProgramUniform2fv,
glProgramUniform3fv,
glProgramUniform4fv,
glProgramUniform1iv,
glProgramUniform2iv,
glProgramUniform3iv,
glProgramUniform4iv,
glProgramUniformMatrix2fv,
glProgramUniformMatrix3fv,
glProgramUniformMatrix4fv,
glProgramUniformMatrix2x3fv,
glProgramUniformMatrix3x2fv,
glProgramUniformMatrix2x4fv,
glProgramUniformMatrix4x2fv,
glProgramUniformMatrix3x4fv,
glProgramUniformMatrix4x3fv,
glTextureBuffer,
glMultiTexBuffer,
glTextureParameterIiv,
glTextureParameterIuiv,
glGetTextureParameterIiv,
glGetTextureParameterIuiv,
glMultiTexParameterIiv,
glMultiTexParameterIuiv,
glGetMultiTexParameterIiv,
glGetMultiTexParameterIuiv,
glProgramUniform1ui,
glProgramUniform2ui,
glProgramUniform3ui,
glProgramUniform4ui,
glProgramUniform1uiv,
glProgramUniform2uiv,
glProgramUniform3uiv,
glProgramUniform4uiv,
glNamedProgramLocalParameters4fv,
glNamedProgramLocalParameterI4i,
glNamedProgramLocalParameterI4iv,
glNamedProgramLocalParametersI4iv,
glNamedProgramLocalParameterI4ui,
glNamedProgramLocalParameterI4uiv,
glNamedProgramLocalParametersI4uiv,
glGetNamedProgramLocalParameterIiv,
glGetNamedProgramLocalParameterIuiv,
glNamedRenderbufferStorage,
glGetNamedRenderbufferParameteriv,
glNamedRenderbufferStorageMultisample,
glNamedRenderbufferStorageMultisampleCoverage,
glCheckNamedFramebufferStatus,
glNamedFramebufferTexture1D,
glNamedFramebufferTexture2D,
glNamedFramebufferTexture3D,
glNamedFramebufferRenderbuffer,
glGetNamedFramebufferAttachmentParameteriv,
glGenerateTextureMipmap,
glGenerateMultiTexMipmap,
glFramebufferDrawBuffer,
glFramebufferDrawBuffers,
glFramebufferReadBuffer,
glGetFramebufferParameteriv,
glNamedFramebufferTexture,
glNamedFramebufferTextureLayer,
glNamedFramebufferTextureFace,
glTextureRenderbuffer,
glMultiTexRenderbuffer,
-- * Tokens
gl_PROGRAM_MATRIX,
gl_TRANSPOSE_PROGRAM_MATRIX,
gl_PROGRAM_MATRIX_STACK_DEPTH
) where
import Foreign.C.Types
import Foreign.Ptr
import Graphics.Rendering.OpenGL.Raw.ARB.FramebufferNoAttachments
import Graphics.Rendering.OpenGL.Raw.ARB.SeparateShaderObjects
import Graphics.Rendering.OpenGL.Raw.Core31.Types
import Graphics.Rendering.OpenGL.Raw.Extensions
#include "HsOpenGLRaw.h"
extensionNameString :: String
extensionNameString = "GL_EXT_direct_state_access"
EXTENSION_ENTRY(dyn_glClientAttribDefault,ptr_glClientAttribDefault,"glClientAttribDefault",glClientAttribDefault,GLbitfield -> IO ())
EXTENSION_ENTRY(dyn_glPushClientAttribDefault,ptr_glPushClientAttribDefault,"glPushClientAttribDefault",glPushClientAttribDefault,GLbitfield -> IO ())
EXTENSION_ENTRY(dyn_glMatrixLoadf,ptr_glMatrixLoadf,"glMatrixLoadf",glMatrixLoadf,GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMatrixLoadd,ptr_glMatrixLoadd,"glMatrixLoadd",glMatrixLoadd,GLenum -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixMultf,ptr_glMatrixMultf,"glMatrixMultf",glMatrixMultf,GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMatrixMultd,ptr_glMatrixMultd,"glMatrixMultd",glMatrixMultd,GLenum -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixLoadIdentity,ptr_glMatrixLoadIdentity,"glMatrixLoadIdentity",glMatrixLoadIdentity,GLenum -> IO ())
EXTENSION_ENTRY(dyn_glMatrixRotatef,ptr_glMatrixRotatef,"glMatrixRotatef",glMatrixRotatef,GLenum -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMatrixRotated,ptr_glMatrixRotated,"glMatrixRotated",glMatrixRotated,GLenum -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixScalef,ptr_glMatrixScalef,"glMatrixScalef",glMatrixScalef,GLenum -> GLfloat -> GLfloat -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMatrixScaled,ptr_glMatrixScaled,"glMatrixScaled",glMatrixScaled,GLenum -> GLdouble -> GLdouble -> GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixTranslatef,ptr_glMatrixTranslatef,"glMatrixTranslatef",glMatrixTranslatef,GLenum -> GLfloat -> GLfloat -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMatrixTranslated,ptr_glMatrixTranslated,"glMatrixTranslated",glMatrixTranslated,GLenum -> GLdouble -> GLdouble -> GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixOrtho,ptr_glMatrixOrtho,"glMatrixOrtho",glMatrixOrtho,GLenum -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixFrustum,ptr_glMatrixFrustum,"glMatrixFrustum",glMatrixFrustum,GLenum -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixPush,ptr_glMatrixPush,"glMatrixPush",glMatrixPush,GLenum -> IO ())
EXTENSION_ENTRY(dyn_glMatrixPop,ptr_glMatrixPop,"glMatrixPop",glMatrixPop,GLenum -> IO ())
EXTENSION_ENTRY(dyn_glTextureParameteri,ptr_glTextureParameteri,"glTextureParameteri",glTextureParameteri,GLuint -> GLenum -> GLenum -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glTextureParameteriv,ptr_glTextureParameteriv,"glTextureParameteriv",glTextureParameteriv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glTextureParameterf,ptr_glTextureParameterf,"glTextureParameterf",glTextureParameterf,GLuint -> GLenum -> GLenum -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glTextureParameterfv,ptr_glTextureParameterfv,"glTextureParameterfv",glTextureParameterfv,GLuint -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glTextureImage1D,ptr_glTextureImage1D,"glTextureImage1D",glTextureImage1D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glTextureImage2D,ptr_glTextureImage2D,"glTextureImage2D",glTextureImage2D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glTextureSubImage1D,ptr_glTextureSubImage1D,"glTextureSubImage1D",glTextureSubImage1D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glTextureSubImage2D,ptr_glTextureSubImage2D,"glTextureSubImage2D",glTextureSubImage2D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCopyTextureImage1D,ptr_glCopyTextureImage1D,"glCopyTextureImage1D",glCopyTextureImage1D,GLuint -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glCopyTextureImage2D,ptr_glCopyTextureImage2D,"glCopyTextureImage2D",glCopyTextureImage2D,GLuint -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glCopyTextureSubImage1D,ptr_glCopyTextureSubImage1D,"glCopyTextureSubImage1D",glCopyTextureSubImage1D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glCopyTextureSubImage2D,ptr_glCopyTextureSubImage2D,"glCopyTextureSubImage2D",glCopyTextureSubImage2D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glGetTextureImage,ptr_glGetTextureImage,"glGetTextureImage",glGetTextureImage,GLuint -> GLenum -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glGetTextureParameterfv,ptr_glGetTextureParameterfv,"glGetTextureParameterfv",glGetTextureParameterfv,GLuint -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetTextureParameteriv,ptr_glGetTextureParameteriv,"glGetTextureParameteriv",glGetTextureParameteriv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetTextureLevelParameterfv,ptr_glGetTextureLevelParameterfv,"glGetTextureLevelParameterfv",glGetTextureLevelParameterfv,GLuint -> GLenum -> GLint -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetTextureLevelParameteriv,ptr_glGetTextureLevelParameteriv,"glGetTextureLevelParameteriv",glGetTextureLevelParameteriv,GLuint -> GLenum -> GLint -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glTextureImage3D,ptr_glTextureImage3D,"glTextureImage3D",glTextureImage3D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glTextureSubImage3D,ptr_glTextureSubImage3D,"glTextureSubImage3D",glTextureSubImage3D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCopyTextureSubImage3D,ptr_glCopyTextureSubImage3D,"glCopyTextureSubImage3D",glCopyTextureSubImage3D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glBindMultiTexture,ptr_glBindMultiTexture,"glBindMultiTexture",glBindMultiTexture,GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordPointer,ptr_glMultiTexCoordPointer,"glMultiTexCoordPointer",glMultiTexCoordPointer,GLenum -> GLint -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexEnvf,ptr_glMultiTexEnvf,"glMultiTexEnvf",glMultiTexEnvf,GLenum -> GLenum -> GLenum -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexEnvfv,ptr_glMultiTexEnvfv,"glMultiTexEnvfv",glMultiTexEnvfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexEnvi,ptr_glMultiTexEnvi,"glMultiTexEnvi",glMultiTexEnvi,GLenum -> GLenum -> GLenum -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexEnviv,ptr_glMultiTexEnviv,"glMultiTexEnviv",glMultiTexEnviv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexGend,ptr_glMultiTexGend,"glMultiTexGend",glMultiTexGend,GLenum -> GLenum -> GLenum -> GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexGendv,ptr_glMultiTexGendv,"glMultiTexGendv",glMultiTexGendv,GLenum -> GLenum -> GLenum -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexGenf,ptr_glMultiTexGenf,"glMultiTexGenf",glMultiTexGenf,GLenum -> GLenum -> GLenum -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexGenfv,ptr_glMultiTexGenfv,"glMultiTexGenfv",glMultiTexGenfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexGeni,ptr_glMultiTexGeni,"glMultiTexGeni",glMultiTexGeni,GLenum -> GLenum -> GLenum -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexGeniv,ptr_glMultiTexGeniv,"glMultiTexGeniv",glMultiTexGeniv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexEnvfv,ptr_glGetMultiTexEnvfv,"glGetMultiTexEnvfv",glGetMultiTexEnvfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexEnviv,ptr_glGetMultiTexEnviv,"glGetMultiTexEnviv",glGetMultiTexEnviv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexGendv,ptr_glGetMultiTexGendv,"glGetMultiTexGendv",glGetMultiTexGendv,GLenum -> GLenum -> GLenum -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexGenfv,ptr_glGetMultiTexGenfv,"glGetMultiTexGenfv",glGetMultiTexGenfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexGeniv,ptr_glGetMultiTexGeniv,"glGetMultiTexGeniv",glGetMultiTexGeniv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexParameteri,ptr_glMultiTexParameteri,"glMultiTexParameteri",glMultiTexParameteri,GLenum -> GLenum -> GLenum -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexParameteriv,ptr_glMultiTexParameteriv,"glMultiTexParameteriv",glMultiTexParameteriv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexParameterf,ptr_glMultiTexParameterf,"glMultiTexParameterf",glMultiTexParameterf,GLenum -> GLenum -> GLenum -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexParameterfv,ptr_glMultiTexParameterfv,"glMultiTexParameterfv",glMultiTexParameterfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexImage1D,ptr_glMultiTexImage1D,"glMultiTexImage1D",glMultiTexImage1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexImage2D,ptr_glMultiTexImage2D,"glMultiTexImage2D",glMultiTexImage2D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexSubImage1D,ptr_glMultiTexSubImage1D,"glMultiTexSubImage1D",glMultiTexSubImage1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexSubImage2D,ptr_glMultiTexSubImage2D,"glMultiTexSubImage2D",glMultiTexSubImage2D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCopyMultiTexImage1D,ptr_glCopyMultiTexImage1D,"glCopyMultiTexImage1D",glCopyMultiTexImage1D,GLenum -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glCopyMultiTexImage2D,ptr_glCopyMultiTexImage2D,"glCopyMultiTexImage2D",glCopyMultiTexImage2D,GLenum -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glCopyMultiTexSubImage1D,ptr_glCopyMultiTexSubImage1D,"glCopyMultiTexSubImage1D",glCopyMultiTexSubImage1D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glCopyMultiTexSubImage2D,ptr_glCopyMultiTexSubImage2D,"glCopyMultiTexSubImage2D",glCopyMultiTexSubImage2D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexImage,ptr_glGetMultiTexImage,"glGetMultiTexImage",glGetMultiTexImage,GLenum -> GLenum -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexParameterfv,ptr_glGetMultiTexParameterfv,"glGetMultiTexParameterfv",glGetMultiTexParameterfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexParameteriv,ptr_glGetMultiTexParameteriv,"glGetMultiTexParameteriv",glGetMultiTexParameteriv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexLevelParameterfv,ptr_glGetMultiTexLevelParameterfv,"glGetMultiTexLevelParameterfv",glGetMultiTexLevelParameterfv,GLenum -> GLenum -> GLint -> GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexLevelParameteriv,ptr_glGetMultiTexLevelParameteriv,"glGetMultiTexLevelParameteriv",glGetMultiTexLevelParameteriv,GLenum -> GLenum -> GLint -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexImage3D,ptr_glMultiTexImage3D,"glMultiTexImage3D",glMultiTexImage3D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexSubImage3D,ptr_glMultiTexSubImage3D,"glMultiTexSubImage3D",glMultiTexSubImage3D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCopyMultiTexSubImage3D,ptr_glCopyMultiTexSubImage3D,"glCopyMultiTexSubImage3D",glCopyMultiTexSubImage3D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glEnableClientStateIndexed,ptr_glEnableClientStateIndexed,"glEnableClientStateIndexed",glEnableClientStateIndexed,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glDisableClientStateIndexed,ptr_glDisableClientStateIndexed,"glDisableClientStateIndexed",glDisableClientStateIndexed,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glGetFloatIndexedv,ptr_glGetFloatIndexedv,"glGetFloatIndexedv",glGetFloatIndexedv,GLenum -> GLuint -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetDoubleIndexedv,ptr_glGetDoubleIndexedv,"glGetDoubleIndexedv",glGetDoubleIndexedv,GLenum -> GLuint -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glGetPointerIndexedv,ptr_glGetPointerIndexedv,"glGetPointerIndexedv",glGetPointerIndexedv,GLenum -> GLuint -> Ptr (Ptr a) -> IO ())
EXTENSION_ENTRY(dyn_glEnableIndexed,ptr_glEnableIndexed,"glEnableIndexed",glEnableIndexed,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glDisableIndexed,ptr_glDisableIndexed,"glDisableIndexed",glDisableIndexed,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glIsEnabledIndexed,ptr_glIsEnabledIndexed,"glIsEnabledIndexed",glIsEnabledIndexed,GLenum -> GLuint -> IO GLboolean)
EXTENSION_ENTRY(dyn_glGetIntegerIndexedv,ptr_glGetIntegerIndexedv,"glGetIntegerIndexedv",glGetIntegerIndexedv,GLenum -> GLuint -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetBooleanIndexedv,ptr_glGetBooleanIndexedv,"glGetBooleanIndexedv",glGetBooleanIndexedv,GLenum -> GLuint -> Ptr GLboolean -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramString,ptr_glNamedProgramString,"glNamedProgramString",glNamedProgramString,GLuint -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4d,ptr_glNamedProgramLocalParameter4d,"glNamedProgramLocalParameter4d",glNamedProgramLocalParameter4d,GLuint -> GLenum -> GLuint -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4dv,ptr_glNamedProgramLocalParameter4dv,"glNamedProgramLocalParameter4dv",glNamedProgramLocalParameter4dv,GLuint -> GLenum -> GLuint -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4f,ptr_glNamedProgramLocalParameter4f,"glNamedProgramLocalParameter4f",glNamedProgramLocalParameter4f,GLuint -> GLenum -> GLuint -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4fv,ptr_glNamedProgramLocalParameter4fv,"glNamedProgramLocalParameter4fv",glNamedProgramLocalParameter4fv,GLuint -> GLenum -> GLuint -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterdv,ptr_glGetNamedProgramLocalParameterdv,"glGetNamedProgramLocalParameterdv",glGetNamedProgramLocalParameterdv,GLuint -> GLenum -> GLuint -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterfv,ptr_glGetNamedProgramLocalParameterfv,"glGetNamedProgramLocalParameterfv",glGetNamedProgramLocalParameterfv,GLuint -> GLenum -> GLuint -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedProgramiv,ptr_glGetNamedProgramiv,"glGetNamedProgramiv",glGetNamedProgramiv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedProgramString,ptr_glGetNamedProgramString,"glGetNamedProgramString",glGetNamedProgramString,GLuint -> GLenum -> GLenum -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedTextureImage3D,ptr_glCompressedTextureImage3D,"glCompressedTextureImage3D",glCompressedTextureImage3D,GLuint -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedTextureImage2D,ptr_glCompressedTextureImage2D,"glCompressedTextureImage2D",glCompressedTextureImage2D,GLuint -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedTextureImage1D,ptr_glCompressedTextureImage1D,"glCompressedTextureImage1D",glCompressedTextureImage1D,GLuint -> GLenum -> GLint -> GLenum -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedTextureSubImage3D,ptr_glCompressedTextureSubImage3D,"glCompressedTextureSubImage3D",glCompressedTextureSubImage3D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedTextureSubImage2D,ptr_glCompressedTextureSubImage2D,"glCompressedTextureSubImage2D",glCompressedTextureSubImage2D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedTextureSubImage1D,ptr_glCompressedTextureSubImage1D,"glCompressedTextureSubImage1D",glCompressedTextureSubImage1D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glGetCompressedTextureImage,ptr_glGetCompressedTextureImage,"glGetCompressedTextureImage",glGetCompressedTextureImage,GLuint -> GLenum -> GLint -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedMultiTexImage3D,ptr_glCompressedMultiTexImage3D,"glCompressedMultiTexImage3D",glCompressedMultiTexImage3D,GLenum -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedMultiTexImage2D,ptr_glCompressedMultiTexImage2D,"glCompressedMultiTexImage2D",glCompressedMultiTexImage2D,GLenum -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedMultiTexImage1D,ptr_glCompressedMultiTexImage1D,"glCompressedMultiTexImage1D",glCompressedMultiTexImage1D,GLenum -> GLenum -> GLint -> GLenum -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedMultiTexSubImage3D,ptr_glCompressedMultiTexSubImage3D,"glCompressedMultiTexSubImage3D",glCompressedMultiTexSubImage3D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedMultiTexSubImage2D,ptr_glCompressedMultiTexSubImage2D,"glCompressedMultiTexSubImage2D",glCompressedMultiTexSubImage2D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glCompressedMultiTexSubImage1D,ptr_glCompressedMultiTexSubImage1D,"glCompressedMultiTexSubImage1D",glCompressedMultiTexSubImage1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glGetCompressedMultiTexImage,ptr_glGetCompressedMultiTexImage,"glGetCompressedMultiTexImage",glGetCompressedMultiTexImage,GLenum -> GLenum -> GLint -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glMatrixLoadTransposef,ptr_glMatrixLoadTransposef,"glMatrixLoadTransposef",glMatrixLoadTransposef,GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMatrixLoadTransposed,ptr_glMatrixLoadTransposed,"glMatrixLoadTransposed",glMatrixLoadTransposed,GLenum -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glMatrixMultTransposef,ptr_glMatrixMultTransposef,"glMatrixMultTransposef",glMatrixMultTransposef,GLenum -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glMatrixMultTransposed,ptr_glMatrixMultTransposed,"glMatrixMultTransposed",glMatrixMultTransposed,GLenum -> Ptr GLdouble -> IO ())
EXTENSION_ENTRY(dyn_glNamedBufferData,ptr_glNamedBufferData,"glNamedBufferData",glNamedBufferData,GLuint -> GLsizeiptr -> Ptr a -> GLenum -> IO ())
EXTENSION_ENTRY(dyn_glNamedBufferSubData,ptr_glNamedBufferSubData,"glNamedBufferSubData",glNamedBufferSubData,GLuint -> GLintptr -> GLsizeiptr -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glMapNamedBuffer,ptr_glMapNamedBuffer,"glMapNamedBuffer",glMapNamedBuffer,GLuint -> GLenum -> IO ())
EXTENSION_ENTRY(dyn_glUnmapNamedBuffer,ptr_glUnmapNamedBuffer,"glUnmapNamedBuffer",glUnmapNamedBuffer,GLuint -> IO GLboolean)
EXTENSION_ENTRY(dyn_glGetNamedBufferParameteriv,ptr_glGetNamedBufferParameteriv,"glGetNamedBufferParameteriv",glGetNamedBufferParameteriv,GLuint -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedBufferPointerv,ptr_glGetNamedBufferPointerv,"glGetNamedBufferPointerv",glGetNamedBufferPointerv,GLuint -> GLenum -> Ptr (Ptr a) -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedBufferSubData,ptr_glGetNamedBufferSubData,"glGetNamedBufferSubData",glGetNamedBufferSubData,GLuint -> GLintptr -> GLsizeiptr -> Ptr a -> IO ())
EXTENSION_ENTRY(dyn_glTextureBuffer,ptr_glTextureBuffer,"glTextureBuffer",glTextureBuffer,GLuint -> GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexBuffer,ptr_glMultiTexBuffer,"glMultiTexBuffer",glMultiTexBuffer,GLenum -> GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTextureParameterIiv,ptr_glTextureParameterIiv,"glTextureParameterIiv",glTextureParameterIiv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glTextureParameterIuiv,ptr_glTextureParameterIuiv,"glTextureParameterIuiv",glTextureParameterIuiv,GLuint -> GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glGetTextureParameterIiv,ptr_glGetTextureParameterIiv,"glGetTextureParameterIiv",glGetTextureParameterIiv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetTextureParameterIuiv,ptr_glGetTextureParameterIuiv,"glGetTextureParameterIuiv",glGetTextureParameterIuiv,GLuint -> GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexParameterIiv,ptr_glMultiTexParameterIiv,"glMultiTexParameterIiv",glMultiTexParameterIiv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexParameterIuiv,ptr_glMultiTexParameterIuiv,"glMultiTexParameterIuiv",glMultiTexParameterIuiv,GLenum -> GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexParameterIiv,ptr_glGetMultiTexParameterIiv,"glGetMultiTexParameterIiv",glGetMultiTexParameterIiv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetMultiTexParameterIuiv,ptr_glGetMultiTexParameterIuiv,"glGetMultiTexParameterIuiv",glGetMultiTexParameterIuiv,GLenum -> GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameters4fv,ptr_glNamedProgramLocalParameters4fv,"glNamedProgramLocalParameters4fv",glNamedProgramLocalParameters4fv,GLuint -> GLenum -> GLuint -> GLsizei -> Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4i,ptr_glNamedProgramLocalParameterI4i,"glNamedProgramLocalParameterI4i",glNamedProgramLocalParameterI4i,GLuint -> GLenum -> GLuint -> GLint -> GLint -> GLint -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4iv,ptr_glNamedProgramLocalParameterI4iv,"glNamedProgramLocalParameterI4iv",glNamedProgramLocalParameterI4iv,GLuint -> GLenum -> GLuint -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParametersI4iv,ptr_glNamedProgramLocalParametersI4iv,"glNamedProgramLocalParametersI4iv",glNamedProgramLocalParametersI4iv,GLuint -> GLenum -> GLuint -> GLsizei -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4ui,ptr_glNamedProgramLocalParameterI4ui,"glNamedProgramLocalParameterI4ui",glNamedProgramLocalParameterI4ui,GLuint -> GLenum -> GLuint -> GLuint -> GLuint -> GLuint -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4uiv,ptr_glNamedProgramLocalParameterI4uiv,"glNamedProgramLocalParameterI4uiv",glNamedProgramLocalParameterI4uiv,GLuint -> GLenum -> GLuint -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glNamedProgramLocalParametersI4uiv,ptr_glNamedProgramLocalParametersI4uiv,"glNamedProgramLocalParametersI4uiv",glNamedProgramLocalParametersI4uiv,GLuint -> GLenum -> GLuint -> GLsizei -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterIiv,ptr_glGetNamedProgramLocalParameterIiv,"glGetNamedProgramLocalParameterIiv",glGetNamedProgramLocalParameterIiv,GLuint -> GLenum -> GLuint -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterIuiv,ptr_glGetNamedProgramLocalParameterIuiv,"glGetNamedProgramLocalParameterIuiv",glGetNamedProgramLocalParameterIuiv,GLuint -> GLenum -> GLuint -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glNamedRenderbufferStorage,ptr_glNamedRenderbufferStorage,"glNamedRenderbufferStorage",glNamedRenderbufferStorage,GLuint -> GLenum -> GLsizei -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedRenderbufferParameteriv,ptr_glGetNamedRenderbufferParameteriv,"glGetNamedRenderbufferParameteriv",glGetNamedRenderbufferParameteriv,GLuint -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedRenderbufferStorageMultisample,ptr_glNamedRenderbufferStorageMultisample,"glNamedRenderbufferStorageMultisample",glNamedRenderbufferStorageMultisample,GLuint -> GLsizei -> GLenum -> GLsizei -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glNamedRenderbufferStorageMultisampleCoverage,ptr_glNamedRenderbufferStorageMultisampleCoverage,"glNamedRenderbufferStorageMultisampleCoverage",glNamedRenderbufferStorageMultisampleCoverage,GLuint -> GLsizei -> GLsizei -> GLenum -> GLsizei -> GLsizei -> IO ())
EXTENSION_ENTRY(dyn_glCheckNamedFramebufferStatus,ptr_glCheckNamedFramebufferStatus,"glCheckNamedFramebufferStatus",glCheckNamedFramebufferStatus,GLuint -> GLenum -> IO GLenum)
EXTENSION_ENTRY(dyn_glNamedFramebufferTexture1D,ptr_glNamedFramebufferTexture1D,"glNamedFramebufferTexture1D",glNamedFramebufferTexture1D,GLuint -> GLenum -> GLenum -> GLuint -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedFramebufferTexture2D,ptr_glNamedFramebufferTexture2D,"glNamedFramebufferTexture2D",glNamedFramebufferTexture2D,GLuint -> GLenum -> GLenum -> GLuint -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedFramebufferTexture3D,ptr_glNamedFramebufferTexture3D,"glNamedFramebufferTexture3D",glNamedFramebufferTexture3D,GLuint -> GLenum -> GLenum -> GLuint -> GLint -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedFramebufferRenderbuffer,ptr_glNamedFramebufferRenderbuffer,"glNamedFramebufferRenderbuffer",glNamedFramebufferRenderbuffer,GLuint -> GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glGetNamedFramebufferAttachmentParameteriv,ptr_glGetNamedFramebufferAttachmentParameteriv,"glGetNamedFramebufferAttachmentParameteriv",glGetNamedFramebufferAttachmentParameteriv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ())
EXTENSION_ENTRY(dyn_glGenerateTextureMipmap,ptr_glGenerateTextureMipmap,"glGenerateTextureMipmap",glGenerateTextureMipmap,GLuint -> GLenum -> IO ())
EXTENSION_ENTRY(dyn_glGenerateMultiTexMipmap,ptr_glGenerateMultiTexMipmap,"glGenerateMultiTexMipmap",glGenerateMultiTexMipmap,GLenum -> GLenum -> IO ())
EXTENSION_ENTRY(dyn_glFramebufferDrawBuffer,ptr_glFramebufferDrawBuffer,"glFramebufferDrawBuffer",glFramebufferDrawBuffer,GLuint -> GLenum -> IO ())
EXTENSION_ENTRY(dyn_glFramebufferDrawBuffers,ptr_glFramebufferDrawBuffers,"glFramebufferDrawBuffers",glFramebufferDrawBuffers,GLuint -> GLsizei -> Ptr GLenum -> IO ())
EXTENSION_ENTRY(dyn_glFramebufferReadBuffer,ptr_glFramebufferReadBuffer,"glFramebufferReadBuffer",glFramebufferReadBuffer,GLuint -> GLenum -> IO ())
EXTENSION_ENTRY(dyn_glNamedFramebufferTexture,ptr_glNamedFramebufferTexture,"glNamedFramebufferTexture",glNamedFramebufferTexture,GLuint -> GLenum -> GLuint -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedFramebufferTextureLayer,ptr_glNamedFramebufferTextureLayer,"glNamedFramebufferTextureLayer",glNamedFramebufferTextureLayer,GLuint -> GLenum -> GLuint -> GLint -> GLint -> IO ())
EXTENSION_ENTRY(dyn_glNamedFramebufferTextureFace,ptr_glNamedFramebufferTextureFace,"glNamedFramebufferTextureFace",glNamedFramebufferTextureFace,GLuint -> GLenum -> GLuint -> GLint -> GLenum -> IO ())
EXTENSION_ENTRY(dyn_glTextureRenderbuffer,ptr_glTextureRenderbuffer,"glTextureRenderbuffer",glTextureRenderbuffer,GLuint -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexRenderbuffer,ptr_glMultiTexRenderbuffer,"glMultiTexRenderbuffer",glMultiTexRenderbuffer,GLenum -> GLenum -> GLuint -> IO ())
gl_PROGRAM_MATRIX :: GLenum
gl_PROGRAM_MATRIX = 0x8E2D
gl_TRANSPOSE_PROGRAM_MATRIX :: GLenum
gl_TRANSPOSE_PROGRAM_MATRIX = 0x8E2E
gl_PROGRAM_MATRIX_STACK_DEPTH :: GLenum
gl_PROGRAM_MATRIX_STACK_DEPTH = 0x8E2F
|
mfpi/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/EXT/DirectStateAccess.hs
|
bsd-3-clause
| 34,735 | 0 | 21 | 2,903 | 7,903 | 4,341 | 3,562 | -1 | -1 |
module Plots
( -- * Core Library
-- | Definitions of bounds, axis scale, orientation,
-- legend, generic plot ,plot spec and so on.
module Plots.Types
-- | Definitions of theme, plots style, common themes,
-- marker shapes, colour maps and sample maps.
, module Plots.Themes
-- * API
-- | Data types and classes, definitions of
-- plotable, bounds, axis labels, legends,
-- diagram essentials and so on.
, module Plots.API
-- * Axis Library
-- | Axis definition (r2Axis & polarAxis), aspect
-- ratio and scaling.
, module Plots.Axis
-- | Grid lines and styles.
, module Plots.Axis.Grid
-- | Axis labels and tick labels .
, module Plots.Axis.Labels
-- | Rendering system for polar and r2 axis, and system
-- for calculating bounds and scale.
, module Plots.Axis.Render
-- | Ticks properties and placement.
, module Plots.Axis.Ticks
-- | Colour bars.
, module Plots.Axis.ColourBar
-- * Plot Types
-- | Scatter and bubble.
-- Scatter and bubble plot api.
, module Plots.Types.Scatter
-- | Line, trail and path.
-- Line plot, steps plot api & api for trail and path.
, module Plots.Types.Line
-- | Ribbon and area.
-- Ribbon and area plot api.
, module Plots.Types.Ribbon
-- | Histogram.
-- API for histogram.
, module Plots.Types.Histogram
-- | Parametric functions and vectors.
-- Parametric plot and vectors api.
, module Plots.Types.Function
-- | Boxplot.
-- Boxplot api.
, module Plots.Types.Boxplot
-- | Density fucntion.
-- Density plot api.
, module Plots.Types.Density
-- | Smooth.
-- Smooth plot api.
, module Plots.Types.Smooth
-- | Text.
-- API for text plot.
, module Plots.Types.Text
-- | Wedge and annular wedge.
-- API for wedge, annular wegde and pie.
, module Plots.Types.Pie
-- | Scatter plot for polar co-ordinates.
-- API for polar scatter plot.
, module Plots.Types.Points
-- | API using multiple types.
, module Plots.Types.Others
-- , module Plots.Types.Heatmap
) where
import Plots.Axis
import Plots.Axis.Grid
import Plots.Axis.Labels
import Plots.Axis.Render
import Plots.Axis.Ticks
import Plots.Axis.ColourBar
import Plots.Types
import Plots.Themes
import Plots.API
import Plots.Types.Scatter
import Plots.Types.Line
import Plots.Types.Ribbon
import Plots.Types.Histogram
import Plots.Types.Function
import Plots.Types.Boxplot
import Plots.Types.Density
import Plots.Types.Smooth
import Plots.Types.Text
import Plots.Types.Pie
import Plots.Types.Points
import Plots.Types.Others
-- import Plots.Types.Heatmap
|
bergey/plots
|
src/Plots.hs
|
bsd-3-clause
| 2,909 | 0 | 5 | 836 | 315 | 229 | 86 | 44 | 0 |
module Diag.Util.Timer
where
import System.CPUTime
import Text.Printf
timeItMsg :: String -> IO a -> IO a
timeItMsg msg ioa = do
t1 <- getCPUTime
a <- ioa
t2 <- getCPUTime
let t :: Double
t = fromIntegral (t2-t1) * 1e-12
printf "CPU time for %s: %6.5fs\n" msg t
return a
|
marcmo/hsDiagnosis
|
src/Diag/Util/Timer.hs
|
bsd-3-clause
| 293 | 0 | 13 | 72 | 111 | 54 | 57 | 12 | 1 |
module Ivory.Language.Sint where
import Ivory.Language.BoundedInteger
import Ivory.Language.Type
import qualified Ivory.Language.Syntax as I
import Data.Int (Int8,Int16,Int32,Int64)
-- Signed Types ----------------------------------------------------------------
-- | 8-bit integers.
newtype Sint8 = Sint8 { getSint8 :: I.Expr }
deriving Show
instance IvoryType Sint8 where
ivoryType _ = I.TyInt I.Int8
instance IvoryVar Sint8 where
wrapVar = wrapVarExpr
unwrapExpr = getSint8
instance IvoryExpr Sint8 where
wrapExpr = Sint8
instance Num Sint8 where
(*) = exprBinop (*)
(+) = exprBinop (+)
(-) = exprBinop (-)
abs = exprUnary abs
signum = exprUnary signum
negate = exprUnary negate
fromInteger = boundedFromInteger Sint8 (0 :: Int8)
instance Bounded Sint8 where
minBound = wrapExpr (I.ExpMaxMin False)
maxBound = wrapExpr (I.ExpMaxMin True)
-- | 16-bit integers.
newtype Sint16 = Sint16 { getSint16 :: I.Expr }
deriving Show
instance IvoryType Sint16 where
ivoryType _ = I.TyInt I.Int16
instance IvoryVar Sint16 where
wrapVar = wrapVarExpr
unwrapExpr = getSint16
instance IvoryExpr Sint16 where
wrapExpr = Sint16
instance Num Sint16 where
(*) = exprBinop (*)
(+) = exprBinop (+)
(-) = exprBinop (-)
abs = exprUnary abs
signum = exprUnary signum
negate = exprUnary negate
fromInteger = boundedFromInteger Sint16 (0 :: Int16)
instance Bounded Sint16 where
minBound = wrapExpr (I.ExpMaxMin False)
maxBound = wrapExpr (I.ExpMaxMin True)
-- | 32-bit integers.
newtype Sint32 = Sint32 { getSint32 :: I.Expr }
deriving Show
instance IvoryType Sint32 where
ivoryType _ = I.TyInt I.Int32
instance IvoryVar Sint32 where
wrapVar = wrapVarExpr
unwrapExpr = getSint32
instance IvoryExpr Sint32 where
wrapExpr = Sint32
instance Num Sint32 where
(*) = exprBinop (*)
(+) = exprBinop (+)
(-) = exprBinop (-)
abs = exprUnary abs
signum = exprUnary signum
negate = exprUnary negate
fromInteger = boundedFromInteger Sint32 (0 :: Int32)
instance Bounded Sint32 where
minBound = wrapExpr (I.ExpMaxMin False)
maxBound = wrapExpr (I.ExpMaxMin True)
-- | 64-bit integers.
newtype Sint64 = Sint64 { getSint64 :: I.Expr }
deriving Show
instance IvoryType Sint64 where
ivoryType _ = I.TyInt I.Int64
instance IvoryVar Sint64 where
wrapVar = wrapVarExpr
unwrapExpr = getSint64
instance IvoryExpr Sint64 where
wrapExpr = Sint64
instance Num Sint64 where
(*) = exprBinop (*)
(+) = exprBinop (+)
(-) = exprBinop (-)
abs = exprUnary abs
signum = exprUnary signum
negate = exprUnary negate
fromInteger = boundedFromInteger Sint64 (0 :: Int64)
instance Bounded Sint64 where
minBound = wrapExpr (I.ExpMaxMin False)
maxBound = wrapExpr (I.ExpMaxMin True)
|
GaloisInc/ivory
|
ivory/src/Ivory/Language/Sint.hs
|
bsd-3-clause
| 2,936 | 0 | 9 | 698 | 836 | 473 | 363 | 85 | 0 |
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction,
ViewPatterns, FlexibleInstances #-}
module Language.Lisk.Parser where
import Data.List
import Data.Either
import Control.Monad.Reader
import Control.Monad.Error
import Control.Arrow
import Control.Applicative
import Control.Monad.Identity
import Data.Char
import Text.Parsec hiding ((<|>),many,token)
import Text.Parsec.Combinator
import Language.Haskell.Exts.Syntax
import Language.Haskell.Exts.Pretty
import qualified Language.Haskell.Exts.Parser as P (parseExp,parse,ParseResult(..))
data LiskExpr = LSym SrcLoc String
| LTCM SrcLoc String
| LList SrcLoc [LiskExpr]
deriving Show
type LP = Parsec String ()
printLiskToHaskell = prettyPrint
parseLisk = parse (spaces *> liskModule <* spaces)
printLiskFragment p = either (putStrLn.show) (putStrLn.prettyPrint) . parse p ""
printLisk str =
case parse liskModule "" str of
Left e -> error $ show e ++ suggest
Right ex -> putStrLn $ prettyPrint ex
liskModule = parens $ do
loc <- getLoc
symbolOf "module" <?> "module"
spaces1
name <- liskModuleName
spaces
importDecls <- liskImportDecl
spaces
decls <- sepBy liskDecl spaces
return $ Module loc name [] Nothing Nothing importDecls decls
symbolOf = string
liskDecl = try liskTypeSig <|> try liskFunBind <|> liskPatBind
liskTypeSig = parens $ do
loc <- getLoc
symbolOf "::" <?> "type signature e.g. (:: x :string)"
spaces1
idents <- pure <$> liskIdent <|>
parens (sepBy1 liskIdent spaces1)
spaces1
typ <- liskType
return $ TypeSig loc idents typ
liskType = try liskTyCon <|> try liskTyVar <|> liskTyApp
liskTyApp = parens $ do
op <- liskType
spaces1
args <- sepBy1 liskType spaces1
let op' =
case op of
TyCon (Special (TupleCon b n)) -> TyCon $ Special $ TupleCon b $ length args
_ -> op
return $ foldl TyApp op' args
liskTyCon = TyCon <$> liskQName
liskTyVar = TyVar <$> liskName
liskPatBind = parens $ do
loc <- getLoc
symbolOf "=" <?> "pattern binding e.g. (= x \"Hello, World!\")"
spaces1
pat <- liskPat
typ <- return Nothing -- liskType -- TODO
spaces1
rhs <- liskRhs
binds <- liskBinds
return $ PatBind loc pat Nothing rhs binds
liskFunBind = FunBind <$> sepBy1 liskMatch spaces1
liskMatch = parens $ do
loc <- getLoc
symbolOf "=" <?> "pattern binding e.g. (= x \"Hello, World!\")"
spaces1
name <- liskName
spaces1
pats <- (pure <$> liskPat) <|> parens (sepBy1 liskPat spaces1)
typ <- return Nothing -- liskType -- TODO
spaces1
rhs <- liskRhs
binds <- liskBinds
return $ Match loc name pats typ rhs binds
liskBinds = try liskBDecls <|> liskIPBinds
liskBDecls = BDecls <$> pure [] -- TODO
liskIPBinds = IPBinds <$> pure [] -- TODO
liskPat = liskPVar -- TODO
liskRhs = liskUnguardedRhs
liskUnguardedRhs = UnGuardedRhs <$> liskExp
-- TODO
liskExp = try liskVar
<|> try liskLit
<|> try liskApp
liskApp = try liskTupleApp <|> try liskOpApp <|> try liskIdentApp <|> liskOpPartial
liskTupleApp = parens $ do
string ","
args <- (spaces1 *> sepBy1 liskExp spaces1) <|> pure []
let op = Var $ Special $ TupleCon Boxed $ max 2 (length args)
paren | null args = id
| otherwise = Paren
return $ paren $ foldl App op $ args
liskIdentApp = parens $ do
op <- liskExp
spaces1
args <- sepBy1 liskExp spaces1
return $ Paren $ foldl App op $ args
liskOpApp = parens $ do
op <- QVarOp <$> liskOp
spaces1
args <- (:) <$> (liskExp <* spaces) <*> sepBy1 liskExp spaces1
return $ Paren $ foldl1 (flip InfixApp op) args
liskOpPartial = parens $ do
op <- Var <$> liskOp
spaces1
e <- liskExp
return $ App op e
liskOp = UnQual . Symbol <$> many1 (oneOf ".*-+/\\=<>")
liskLit = Lit <$> (liskChar <|> try liskString <|> liskInt)
liskChar = Char <$> (string "\\" *> (space <|> newline <|> noneOf "\n \t"))
where space = const ' ' <$> string "Space"
<|> const '\n' <$> string "Newline"
liskString = do
strRep <- char '\"' *> (concat <$> many liskStringSeq) <* char '\"'
case P.parseExp $ "\"" ++ strRep ++ "\"" of
P.ParseOk (Lit s@String{}) -> return s
P.ParseFailed _ msg -> parserFail msg
where liskStringSeq = ("\\"++) <$> (char '\\' *> (pure <$> noneOf "\n"))
<|> pure <$> noneOf "\n\""
liskInt = Int <$> (read <$> many1 digit)
liskPVar = PVar <$> liskName
liskQName = try liskSpecial <|> try liskQual <|> try liskUnQual
liskQual = mzero -- TODO
liskUnQual = UnQual <$> liskName
liskSpecial = Special <$> spec where
spec = string "()" *> pure UnitCon
<|> string "[]" *> pure ListCon
<|> string "->" *> pure FunCon
<|> string "," *> pure (TupleCon Boxed{-TODO:boxed-} 0)
liskName = try liskIdent <|> liskSymbol
liskVar = Var <$> liskUnQual
liskIdent = Ident . hyphenToCamelCase . colonToConsTyp <$> ident where
ident = ((++) <$> (string ":" <|> pure "")
<*> many1 liskIdentifierToken)
colonToConsTyp (':':x:xs) = toUpper x : xs
colonToConsTyp xs = xs
liskSymbol = Symbol <$> many1 liskIdentifierToken
liskList = mzero -- TODO
liskImportDecl = parens $ do
symbolOf "import" <?> "import"
spaces1
sepBy1 liskImportDeclModule spaces1
liskImportDeclModule =
liskImportDeclModuleName <|> liskImportDeclModuleSpec
liskImportDeclModuleSpec = parens $ do
imp <- liskImportDeclModuleSpec
return imp
liskImportDeclModuleName = do
loc <- getLoc
name <- liskModuleName
return $ ImportDecl {
importLoc = loc
, importModule = name
, importQualified = False
, importSrc = False
, importPkg = Nothing
, importAs = Nothing
, importSpecs = Nothing
}
liskModuleName = (<?> "module name (e.g. `:module.some-name')") $ do
parts <- sepBy1 modulePart (string ".")
return $ ModuleName $ intercalate "." parts
where modulePart = format <$> many1 liskIdentifierToken
format = hyphenToCamelCase . upperize
upperize (x:xs) = toUpper x : xs
liskDefIdentifier = do
ident <- many1 liskIdentifierToken
return $ Ident ident
liskIdentifierToken = letter <|> digit <|> oneOf "-"
hyphenToCamelCase ('-':'-':xs) = hyphenToCamelCase ('-':xs)
hyphenToCamelCase ('-':x:xs) = toUpper x : hyphenToCamelCase xs
hyphenToCamelCase ('-':xs) = hyphenToCamelCase xs
hyphenToCamelCase (x:xs) = x : hyphenToCamelCase xs
hyphenToCamelCase [] = []
getLoc = posToLoc <$> getPosition where
posToLoc pos =
SrcLoc { srcFilename = sourceName pos
, srcLine = sourceLine pos
, srcColumn = sourceColumn pos
}
parens = between (char '(') (char ')')
suggest = "\n(are you trying to use not-currently-supported syntax?)"
bi f g = f . g . f
spaces1 = many1 space
|
aculich/lisk
|
src/Language/Lisk/Parser.hs
|
bsd-3-clause
| 6,812 | 0 | 18 | 1,569 | 2,211 | 1,097 | 1,114 | 191 | 2 |
module Chap7Arith4 where
--id :: a -> a
--id x = x
roundTrip :: (Show a, Read a) => a -> a
roundTrip a = read (show a)
-- 5.
roundTrip' :: (Show a, Read a) => a -> a
roundTrip' = read . show
-- 6.
-- Probably not be what the exercise is looking for
roundTrip'' :: (Show a, Read b, Integral b) => a -> b
roundTrip'' = read . show
main = do
print (roundTrip 4)
print (id 4)
print (roundTrip' 4)
print (roundTrip'' 4)
|
tkasu/haskellbook-adventure
|
app/Chap7Arith4.hs
|
bsd-3-clause
| 431 | 0 | 9 | 105 | 175 | 91 | 84 | 12 | 1 |
import Test.Hspec
import System.Directory
import Lib
main :: IO ()
main = hspec $ do
describe "Foo" $ do
it "Return a foo file" $ do
m
res <- doesFileExist "foo"
res `shouldBe` True
|
lpaulmp/shake-ansible
|
test/Spec.hs
|
bsd-3-clause
| 208 | 0 | 15 | 60 | 75 | 36 | 39 | 10 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP #-}
module VarSet (
-- * Var, Id and TyVar set types
VarSet, IdSet, TyVarSet, CoVarSet, TyCoVarSet,
-- ** Manipulating these sets
emptyVarSet, unitVarSet, mkVarSet,
extendVarSet, extendVarSetList, extendVarSet_C,
elemVarSet, varSetElems, subVarSet,
unionVarSet, unionVarSets, mapUnionVarSet,
intersectVarSet, intersectsVarSet, disjointVarSet,
isEmptyVarSet, delVarSet, delVarSetList, delVarSetByKey,
minusVarSet, filterVarSet,
varSetAny, varSetAll,
transCloVarSet, fixVarSet,
lookupVarSet, lookupVarSetByName,
sizeVarSet, seqVarSet,
elemVarSetByKey, partitionVarSet,
pluralVarSet, pprVarSet,
-- * Deterministic Var set types
DVarSet, DIdSet, DTyVarSet, DTyCoVarSet,
-- ** Manipulating these sets
emptyDVarSet, unitDVarSet, mkDVarSet,
extendDVarSet, extendDVarSetList,
elemDVarSet, dVarSetElems, subDVarSet,
unionDVarSet, unionDVarSets, mapUnionDVarSet,
intersectDVarSet, intersectsDVarSet, disjointDVarSet,
isEmptyDVarSet, delDVarSet, delDVarSetList,
minusDVarSet, foldDVarSet, filterDVarSet,
dVarSetMinusVarSet,
transCloDVarSet,
sizeDVarSet, seqDVarSet,
partitionDVarSet,
dVarSetToVarSet,
) where
#include "HsVersions.h"
import Var ( Var, TyVar, CoVar, TyCoVar, Id )
import Unique
import Name ( Name )
import UniqSet
import UniqDSet
import UniqFM( disjointUFM, pluralUFM, pprUFM )
import UniqDFM( disjointUDFM, udfmToUfm )
import Outputable (SDoc)
-- | A non-deterministic set of variables.
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why it's not
-- deterministic and why it matters. Use DVarSet if the set eventually
-- gets converted into a list or folded over in a way where the order
-- changes the generated code, for example when abstracting variables.
type VarSet = UniqSet Var
type IdSet = UniqSet Id
type TyVarSet = UniqSet TyVar
type CoVarSet = UniqSet CoVar
type TyCoVarSet = UniqSet TyCoVar
emptyVarSet :: VarSet
intersectVarSet :: VarSet -> VarSet -> VarSet
unionVarSet :: VarSet -> VarSet -> VarSet
unionVarSets :: [VarSet] -> VarSet
mapUnionVarSet :: (a -> VarSet) -> [a] -> VarSet
-- ^ map the function over the list, and union the results
varSetElems :: VarSet -> [Var]
unitVarSet :: Var -> VarSet
extendVarSet :: VarSet -> Var -> VarSet
extendVarSetList:: VarSet -> [Var] -> VarSet
elemVarSet :: Var -> VarSet -> Bool
delVarSet :: VarSet -> Var -> VarSet
delVarSetList :: VarSet -> [Var] -> VarSet
minusVarSet :: VarSet -> VarSet -> VarSet
isEmptyVarSet :: VarSet -> Bool
mkVarSet :: [Var] -> VarSet
lookupVarSet :: VarSet -> Var -> Maybe Var
-- Returns the set element, which may be
-- (==) to the argument, but not the same as
lookupVarSetByName :: VarSet -> Name -> Maybe Var
sizeVarSet :: VarSet -> Int
filterVarSet :: (Var -> Bool) -> VarSet -> VarSet
extendVarSet_C :: (Var->Var->Var) -> VarSet -> Var -> VarSet
delVarSetByKey :: VarSet -> Unique -> VarSet
elemVarSetByKey :: Unique -> VarSet -> Bool
partitionVarSet :: (Var -> Bool) -> VarSet -> (VarSet, VarSet)
emptyVarSet = emptyUniqSet
unitVarSet = unitUniqSet
extendVarSet = addOneToUniqSet
extendVarSetList= addListToUniqSet
intersectVarSet = intersectUniqSets
intersectsVarSet:: VarSet -> VarSet -> Bool -- True if non-empty intersection
disjointVarSet :: VarSet -> VarSet -> Bool -- True if empty intersection
subVarSet :: VarSet -> VarSet -> Bool -- True if first arg is subset of second
-- (s1 `intersectsVarSet` s2) doesn't compute s2 if s1 is empty;
-- ditto disjointVarSet, subVarSet
unionVarSet = unionUniqSets
unionVarSets = unionManyUniqSets
varSetElems = uniqSetToList
elemVarSet = elementOfUniqSet
minusVarSet = minusUniqSet
delVarSet = delOneFromUniqSet
delVarSetList = delListFromUniqSet
isEmptyVarSet = isEmptyUniqSet
mkVarSet = mkUniqSet
lookupVarSet = lookupUniqSet
lookupVarSetByName = lookupUniqSet
sizeVarSet = sizeUniqSet
filterVarSet = filterUniqSet
extendVarSet_C = addOneToUniqSet_C
delVarSetByKey = delOneFromUniqSet_Directly
elemVarSetByKey = elemUniqSet_Directly
partitionVarSet = partitionUniqSet
mapUnionVarSet get_set xs = foldr (unionVarSet . get_set) emptyVarSet xs
-- See comments with type signatures
intersectsVarSet s1 s2 = not (s1 `disjointVarSet` s2)
disjointVarSet s1 s2 = disjointUFM s1 s2
subVarSet s1 s2 = isEmptyVarSet (s1 `minusVarSet` s2)
varSetAny :: (Var -> Bool) -> VarSet -> Bool
varSetAny = uniqSetAny
varSetAll :: (Var -> Bool) -> VarSet -> Bool
varSetAll = uniqSetAll
-- There used to exist mapVarSet, see Note [Unsound mapUniqSet] in UniqSet for
-- why it got removed.
fixVarSet :: (VarSet -> VarSet) -- Map the current set to a new set
-> VarSet -> VarSet
-- (fixVarSet f s) repeatedly applies f to the set s,
-- until it reaches a fixed point.
fixVarSet fn vars
| new_vars `subVarSet` vars = vars
| otherwise = fixVarSet fn new_vars
where
new_vars = fn vars
transCloVarSet :: (VarSet -> VarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> VarSet -> VarSet
-- (transCloVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
-- The function fn could be (Var -> VarSet), but we use (VarSet -> VarSet)
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
-- Use fixVarSet if the function needs to see the whole set all at once
transCloVarSet fn seeds
= go seeds seeds
where
go :: VarSet -- Accumulating result
-> VarSet -- Work-list; un-processed subset of accumulating result
-> VarSet
-- Specification: go acc vs = acc `union` transClo fn vs
go acc candidates
| isEmptyVarSet new_vs = acc
| otherwise = go (acc `unionVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusVarSet` acc
seqVarSet :: VarSet -> ()
seqVarSet s = sizeVarSet s `seq` ()
-- | Determines the pluralisation suffix appropriate for the length of a set
-- in the same way that plural from Outputable does for lists.
pluralVarSet :: VarSet -> SDoc
pluralVarSet = pluralUFM
-- | Pretty-print a non-deterministic set.
-- The order of variables is non-deterministic and for pretty-printing that
-- shouldn't be a problem.
-- Having this function helps contain the non-determinism created with
-- varSetElems.
-- Passing a list to the pretty-printing function allows the caller
-- to decide on the order of Vars (eg. toposort them) without them having
-- to use varSetElems at the call site. This prevents from let-binding
-- non-deterministically ordered lists and reusing them where determinism
-- matters.
pprVarSet :: VarSet -- ^ The things to be pretty printed
-> ([Var] -> SDoc) -- ^ The pretty printing function to use on the
-- elements
-> SDoc -- ^ 'SDoc' where the things have been pretty
-- printed
pprVarSet = pprUFM
-- Deterministic VarSet
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
-- DVarSet.
type DVarSet = UniqDSet Var
type DIdSet = UniqDSet Id
type DTyVarSet = UniqDSet TyVar
type DTyCoVarSet = UniqDSet TyCoVar
emptyDVarSet :: DVarSet
emptyDVarSet = emptyUniqDSet
unitDVarSet :: Var -> DVarSet
unitDVarSet = unitUniqDSet
mkDVarSet :: [Var] -> DVarSet
mkDVarSet = mkUniqDSet
extendDVarSet :: DVarSet -> Var -> DVarSet
extendDVarSet = addOneToUniqDSet
elemDVarSet :: Var -> DVarSet -> Bool
elemDVarSet = elementOfUniqDSet
dVarSetElems :: DVarSet -> [Var]
dVarSetElems = uniqDSetToList
subDVarSet :: DVarSet -> DVarSet -> Bool
subDVarSet s1 s2 = isEmptyDVarSet (s1 `minusDVarSet` s2)
unionDVarSet :: DVarSet -> DVarSet -> DVarSet
unionDVarSet = unionUniqDSets
unionDVarSets :: [DVarSet] -> DVarSet
unionDVarSets = unionManyUniqDSets
-- | Map the function over the list, and union the results
mapUnionDVarSet :: (a -> DVarSet) -> [a] -> DVarSet
mapUnionDVarSet get_set xs = foldr (unionDVarSet . get_set) emptyDVarSet xs
intersectDVarSet :: DVarSet -> DVarSet -> DVarSet
intersectDVarSet = intersectUniqDSets
-- | True if empty intersection
disjointDVarSet :: DVarSet -> DVarSet -> Bool
disjointDVarSet s1 s2 = disjointUDFM s1 s2
-- | True if non-empty intersection
intersectsDVarSet :: DVarSet -> DVarSet -> Bool
intersectsDVarSet s1 s2 = not (s1 `disjointDVarSet` s2)
isEmptyDVarSet :: DVarSet -> Bool
isEmptyDVarSet = isEmptyUniqDSet
delDVarSet :: DVarSet -> Var -> DVarSet
delDVarSet = delOneFromUniqDSet
minusDVarSet :: DVarSet -> DVarSet -> DVarSet
minusDVarSet = minusUniqDSet
dVarSetMinusVarSet :: DVarSet -> VarSet -> DVarSet
dVarSetMinusVarSet = uniqDSetMinusUniqSet
foldDVarSet :: (Var -> a -> a) -> a -> DVarSet -> a
foldDVarSet = foldUniqDSet
filterDVarSet :: (Var -> Bool) -> DVarSet -> DVarSet
filterDVarSet = filterUniqDSet
sizeDVarSet :: DVarSet -> Int
sizeDVarSet = sizeUniqDSet
-- | Partition DVarSet according to the predicate given
partitionDVarSet :: (Var -> Bool) -> DVarSet -> (DVarSet, DVarSet)
partitionDVarSet = partitionUniqDSet
-- | Delete a list of variables from DVarSet
delDVarSetList :: DVarSet -> [Var] -> DVarSet
delDVarSetList = delListFromUniqDSet
seqDVarSet :: DVarSet -> ()
seqDVarSet s = sizeDVarSet s `seq` ()
-- | Add a list of variables to DVarSet
extendDVarSetList :: DVarSet -> [Var] -> DVarSet
extendDVarSetList = addListToUniqDSet
-- | Convert a DVarSet to a VarSet by forgeting the order of insertion
dVarSetToVarSet :: DVarSet -> VarSet
dVarSetToVarSet = udfmToUfm
-- | transCloVarSet for DVarSet
transCloDVarSet :: (DVarSet -> DVarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> DVarSet -> DVarSet
-- (transCloDVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
-- The function fn could be (Var -> DVarSet), but we use (DVarSet -> DVarSet)
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
transCloDVarSet fn seeds
= go seeds seeds
where
go :: DVarSet -- Accumulating result
-> DVarSet -- Work-list; un-processed subset of accumulating result
-> DVarSet
-- Specification: go acc vs = acc `union` transClo fn vs
go acc candidates
| isEmptyDVarSet new_vs = acc
| otherwise = go (acc `unionDVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusDVarSet` acc
|
vikraman/ghc
|
compiler/basicTypes/VarSet.hs
|
bsd-3-clause
| 11,246 | 0 | 10 | 2,517 | 1,959 | 1,139 | 820 | 188 | 1 |
module System.Win32.DHCP.SUBNET_ELEMENT_INFO_ARRAY_V4
( SUBNET_ELEMENT_INFO_ARRAY_V4 (..)
, infoArray
) where
import System.Win32.DHCP.DhcpStructure
import System.Win32.DHCP.LengthBuffer
import System.Win32.DHCP.SUBNET_ELEMENT_DATA_V4
-- typedef struct _DHCP_SUBNET_ELEMENT_INFO_ARRAY_V4 {
-- DWORD NumElements;
-- LPDHCP_SUBNET_ELEMENT_DATA_V4 Elements;
-- } DHCP_SUBNET_ELEMENT_INFO_ARRAY_V4, *LPDHCP_SUBNET_ELEMENT_INFO_ARRAY_V4;
newtype SUBNET_ELEMENT_INFO_ARRAY_V4
= SUBNET_ELEMENT_INFO_ARRAY_V4 (LengthBuffer SUBNET_ELEMENT_DATA_V4)
unwrap :: SUBNET_ELEMENT_INFO_ARRAY_V4 -> LengthBuffer SUBNET_ELEMENT_DATA_V4
unwrap (SUBNET_ELEMENT_INFO_ARRAY_V4 ia) = ia
infoArray :: DhcpStructure SUBNET_ELEMENT_INFO_ARRAY_V4
infoArray = newtypeDhcpStructure SUBNET_ELEMENT_INFO_ARRAY_V4 unwrap
$ lengthBuffer (baseDhcpArray subnetElementData)
|
mikesteele81/Win32-dhcp-server
|
src/System/Win32/DHCP/SUBNET_ELEMENT_INFO_ARRAY_V4.hs
|
bsd-3-clause
| 883 | 0 | 8 | 106 | 116 | 69 | 47 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
module Text.Markdown
( -- * Functions
markdown
-- * Settings
, MarkdownSettings
, msXssProtect
, msStandaloneHtml
, msFencedHandlers
, msBlockCodeRenderer
, msLinkNewTab
, msBlankBeforeBlockquote
, msBlockFilter
, msAddHeadingId
-- * Newtype
, Markdown (..)
-- * Fenced handlers
, FencedHandler (..)
, codeFencedHandler
, htmlFencedHandler
-- * Convenience re-exports
, def
) where
import Control.Arrow ((&&&))
import Text.Markdown.Inline
import Text.Markdown.Block
import Text.Markdown.Types
import Prelude hiding (sequence, takeWhile)
import Data.Char (isAlphaNum)
import Data.Default (Default (..))
import Data.List (intercalate, isInfixOf)
import Data.Text (Text)
import qualified Data.Text.Lazy as TL
import Text.Blaze (toValue)
import Text.Blaze.Html (ToMarkup (..), Html)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Monoid (Monoid (mappend, mempty, mconcat))
import Data.Functor.Identity (runIdentity)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as HA
import Text.HTML.SanitizeXSS (sanitizeBalance)
import qualified Data.Map as Map
import Data.String (IsString)
-- | A newtype wrapper providing a @ToHtml@ instance.
newtype Markdown = Markdown TL.Text
deriving(Eq, Ord, Monoid, IsString, Show)
instance ToMarkup Markdown where
toMarkup (Markdown t) = markdown def t
-- | Convert the given textual markdown content to HTML.
--
-- >>> :set -XOverloadedStrings
-- >>> import Text.Blaze.Html.Renderer.Text
-- >>> renderHtml $ markdown def "# Hello World!"
-- "<h1>Hello World!</h1>"
--
-- >>> renderHtml $ markdown def { msXssProtect = False } "<script>alert('evil')</script>"
-- "<script>alert('evil')</script>"
markdown :: MarkdownSettings -> TL.Text -> Html
markdown ms tl =
sanitize
$ runIdentity
$ CL.sourceList blocksH
$= toHtmlB ms
$$ CL.fold mappend mempty
where
sanitize
| msXssProtect ms = preEscapedToMarkup . sanitizeBalance . TL.toStrict . renderHtml
| otherwise = id
blocksH :: [Block Html]
blocksH = processBlocks blocks
blocks :: [Block Text]
blocks = runIdentity
$ CL.sourceList (TL.toChunks tl)
$$ toBlocks ms
=$ CL.consume
processBlocks :: [Block Text] -> [Block Html]
processBlocks = map (fmap $ toHtmlI ms)
. msBlockFilter ms
. map (fmap $ intercalate [InlineHtml "<br>"])
. map (fmap $ map $ toInline refs)
. map toBlockLines
refs =
Map.unions $ map toRef blocks
where
toRef (BlockReference x y) = Map.singleton x y
toRef _ = Map.empty
data MState = NoState | InList ListType
toHtmlB :: Monad m => MarkdownSettings -> Conduit (Block Html) m Html
toHtmlB ms =
loop NoState
where
loop state = await >>= maybe
(closeState state)
(\x -> do
state' <- getState state x
yield $ go x
loop state')
closeState NoState = return ()
closeState (InList Unordered) = yield $ escape "</ul>"
closeState (InList Ordered) = yield $ escape "</ol>"
getState NoState (BlockList ltype _) = do
yield $ escape $
case ltype of
Unordered -> "<ul>"
Ordered -> "<ol>"
return $ InList ltype
getState NoState _ = return NoState
getState state@(InList lt1) b@(BlockList lt2 _)
| lt1 == lt2 = return state
| otherwise = closeState state >> getState NoState b
getState state@(InList _) _ = closeState state >> return NoState
go (BlockPara h) = H.p h
go (BlockPlainText h) = h
go (BlockList _ (Left h)) = H.li h
go (BlockList _ (Right bs)) = H.li $ blocksToHtml bs
go (BlockHtml t) = escape t
go (BlockCode a b) = msBlockCodeRenderer ms a (id &&& toMarkup $ b)
go (BlockQuote bs) = H.blockquote $ blocksToHtml bs
go BlockRule = H.hr
go (BlockHeading level h)
| msAddHeadingId ms = wrap level H.! HA.id (clean h) $ h
| otherwise = wrap level h
where
wrap 1 = H.h1
wrap 2 = H.h2
wrap 3 = H.h3
wrap 4 = H.h4
wrap 5 = H.h5
wrap _ = H.h6
isValidChar c = isAlphaNum c || isInfixOf [c] "-_:."
clean = toValue . TL.filter isValidChar . (TL.replace " " "-") . TL.toLower . renderHtml
go BlockReference{} = return ()
blocksToHtml bs = runIdentity $ mapM_ yield bs $$ toHtmlB ms =$ CL.fold mappend mempty
escape :: Text -> Html
escape = preEscapedToMarkup
toHtmlI :: MarkdownSettings -> [Inline] -> Html
toHtmlI ms is0
| msXssProtect ms = escape $ sanitizeBalance $ TL.toStrict $ renderHtml final
| otherwise = final
where
final = gos is0
gos = mconcat . map go
go (InlineText t) = toMarkup t
go (InlineItalic is) = H.i $ gos is
go (InlineBold is) = H.b $ gos is
go (InlineCode t) = H.code $ toMarkup t
go (InlineLink url Nothing content)
| msLinkNewTab ms = H.a H.! HA.href (H.toValue url) H.! HA.target "_blank" $ gos content
| otherwise = H.a H.! HA.href (H.toValue url) $ gos content
go (InlineLink url (Just title) content)
| msLinkNewTab ms = H.a H.! HA.href (H.toValue url) H.! HA.title (H.toValue title) H.! HA.target "_blank" $ gos content
| otherwise = H.a H.! HA.href (H.toValue url) H.! HA.title (H.toValue title) $ gos content
go (InlineImage url Nothing content) = H.img H.! HA.src (H.toValue url) H.! HA.alt (H.toValue content)
go (InlineImage url (Just title) content) = H.img H.! HA.src (H.toValue url) H.! HA.alt (H.toValue content) H.! HA.title (H.toValue title)
go (InlineHtml t) = escape t
go (InlineFootnoteRef x) = let ishown = TL.pack (show x)
(<>) = mappend
in H.a H.! HA.href (H.toValue $ "#footnote-" <> ishown)
H.! HA.id (H.toValue $ "ref-" <> ishown) $ H.toHtml $ "[" <> ishown <> "]"
go (InlineFootnote x) = let ishown = TL.pack (show x)
(<>) = mappend
in H.a H.! HA.href (H.toValue $ "#ref-" <> ishown)
H.! HA.id (H.toValue $ "footnote-" <> ishown) $ H.toHtml $ "[" <> ishown <> "]"
|
thefalconfeat/markdown
|
Text/Markdown.hs
|
bsd-3-clause
| 6,541 | 0 | 19 | 1,806 | 2,232 | 1,141 | 1,091 | 147 | 21 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad
import Data.ByteString.Char8 (ByteString)
import Foreign.C.Types
import HROOT
main :: IO ()
main = do
tcanvas <- newTCanvas ("Test" :: ByteString) ("Test" :: ByteString) 640 480
h1 <- newTH1F ("test" :: ByteString) ("test" :: ByteString) 100 (-5.0) 5.0
tRandom <- newTRandom 65535
let generator = gaus tRandom 0 2
let go n | n < 0 = return ()
| otherwise = do
histfill generator h1
go (n-1)
go 1000000
draw h1 ("" :: ByteString)
saveAs tcanvas ("random1d.pdf" :: ByteString) ("" :: ByteString)
saveAs tcanvas ("random1d.jpg" :: ByteString) ("" :: ByteString)
saveAs tcanvas ("random1d.png" :: ByteString) ("" :: ByteString)
delete h1
delete tcanvas
histfill :: IO CDouble -> TH1F -> IO ()
histfill gen hist = do
x <- gen
fill1 hist x
return ()
|
wavewave/HROOT-generate
|
HROOT-generate/template/HROOT/example/random1d.hs
|
gpl-3.0
| 910 | 0 | 15 | 225 | 343 | 170 | 173 | 28 | 1 |
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module SimpleTest.Interact
( -- * TestInteraction type and commands
TestInteraction
, runTestInteraction
, withConnection
, getSetting
-- * WebsocketInteraction type and commands
, WebsocketInteraction
, helo
, register
, unregister
, ping
, ack
, sendPushNotification
-- ** General MonadIO helpers
, wait
, randomChannelId
, randomElement
, randomNumber
, randomChoice
, randomData
, assert
-- ** WebsocketInteraction Message manipulation commands
, getEndpoint
-- * Datatypes for interactions
, Uaid
, ChannelIDs
, ChannelID
, Endpoint
, Version
, Storage
, Config
, ClientTracker(..)
, TestConfig(..)
, newStorage
, newConfig
, newClientTracker
, eatExceptions
) where
import Control.Applicative ((<$>))
import Control.Concurrent (threadDelay)
import qualified Control.Exception as E
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Reader (ReaderT, ask, runReaderT)
import Control.Monad.State.Strict (MonadState (get, put), StateT,
runStateT)
import Control.Monad.Trans (liftIO)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import Data.IORef
import qualified Data.Map.Strict as Map
import Data.Maybe (fromJust, fromMaybe)
import qualified Data.Sequence as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Network.Metric as Metric
import qualified Network.Socket as S
import qualified Network.WebSockets as WS
import qualified Network.WebSockets.Stream as WS
import Network.Wreq (FormParam ((:=)))
import qualified Network.Wreq as W
import qualified Network.Wreq.Session as Wreq
import qualified OpenSSL as SSL
import qualified OpenSSL.Session as SSL
import qualified System.IO.Streams as Streams
import qualified System.IO.Streams.SSL as Streams
import Test.QuickCheck (arbitrary, vectorOf)
import Test.QuickCheck.Gen (Gen, choose, elements, generate)
import PushClient (ChannelUpdate (..), Message (..),
mkMessage, receiveMessage,
sendMessage, sendReceiveMessage)
import SimpleTest.Types (ChannelID, ChannelIDs, Data,
Endpoint, Notification (..), Uaid,
Version)
import SimpleTest.Util (ValidChannelID (..))
----------------------------------------------------------------
type Result = String
-- | WebsocketInteraction datatypes
type VariableStorage = Map.Map String Result
data Storage = Storage !VariableStorage
data Config = IConfig
{ iconn :: !WS.Connection
, iStat :: !Metric.AnySink
, iSession :: !Wreq.Session
}
data ClientTracker = ClientTracker
{ attempting :: IORef Int
, maxClients :: !Int
}
data TestConfig = TC
{ tcHostip :: String
, tcPort :: Int
, tcSecure :: Bool
, tcTracker :: ClientTracker
, tcInitStorage :: Storage
, tcStatsd :: Metric.AnySink
, tcSession :: Wreq.Session
, tcSettings :: Map.Map String Int
}
-- | WebsocketInteraction monad transformer for a simplePush interaction
type WebsocketInteraction = ReaderT Config (StateT Storage IO)
-- | Testing monad transformer for a simplePush interaction
type TestInteraction = StateT TestConfig IO
-- | Class that allows access to a Metric Sink
class Monad m => MetricSink m where
getSink :: m Metric.AnySink
instance MetricSink WebsocketInteraction where
getSink = iStat <$> ask
instance MetricSink TestInteraction where
getSink = tcStatsd <$> get
----------------------------------------------------------------
newStorage :: Storage
newStorage = Storage Map.empty
newConfig :: WS.Connection -> Metric.AnySink -> Wreq.Session -> Config
newConfig = IConfig
newClientTracker :: Int -> IO ClientTracker
newClientTracker m = do
attempts <- newIORef 0
return $ ClientTracker attempts m
-- | Run a complete websocket client interaction
runWebsocketInteraction :: WebsocketInteraction a
-> Config
-> Storage
-> IO (a, Storage)
runWebsocketInteraction interaction config = runStateT (runReaderT interaction config)
-- | Run a test interaction
runTestInteraction :: TestInteraction a -> TestConfig -> IO (a, TestConfig)
runTestInteraction = runStateT
makeClient :: Bool -> String -> Int -> WS.ClientApp a ->IO a
makeClient True host port app = SSL.withOpenSSL $ do
ctx <- SSL.context
is <- S.getAddrInfo Nothing (Just host) (Just $ show port)
let a = S.addrAddress $ head is
f = S.addrFamily $ head is
s <- S.socket f S.Stream S.defaultProtocol
S.connect s a
ssl <- SSL.connection ctx s
SSL.connect ssl
(i,o) <- Streams.sslToStreams ssl
stream <- WS.makeStream (Streams.read i)
(\b -> Streams.write (BL.toStrict <$> b) o)
WS.runClientWithStream stream host "/" WS.defaultConnectionOptions (originHeader host port) app
where
originHeader host port = [("Origin", BC.concat ["http://", BC.pack host,
":", BC.pack $ show port])]
makeClient False host port app = WS.runClientWith host port "/"
WS.defaultConnectionOptions (originHeader host port) app
where
originHeader host port = [("Origin", BC.concat ["http://", BC.pack host,
":", BC.pack $ show port])]
----------------------------------------------------------------
{- * TestInteraction commands
-}
-- | Run an interaction in a test interaction
withConnection :: WebsocketInteraction a -> TestInteraction a
withConnection interaction = do
tc@TC{..} <- get
(resp, store) <- liftIO $ makeClient tcSecure tcHostip tcPort $ \conn -> do
let config = newConfig conn tcStatsd tcSession
runWebsocketInteraction interaction config tcInitStorage
put $ tc { tcInitStorage = store }
return resp
-- | Get an env setting from the map
getSetting :: String -> TestInteraction Int
getSetting name = do
TC{..} <- get
return (fromJust $ Map.lookup name tcSettings)
----------------------------------------------------------------
{- * Statistics helpers
-}
-- | Times an interaction and returns its result after sending the timer metric
-- recorded over the supplied metric sink.
withTimer :: (MetricSink m, MonadIO m)
=> ByteString -- ^ Metric namespace
-> ByteString -- ^ Metric bucket name
-> m a -- ^ Monad to run
-> m a
withTimer namespace bucket op = do
sink <- getSink
now <- liftIO getPOSIXTime
opVal <- op
done <- liftIO getPOSIXTime
let diff = fromIntegral $ round $ (done - now) * 1000
liftIO $ eatExceptions $ Metric.push sink $ metricTimer diff
return opVal
where
metricTimer = Metric.Timer namespace bucket
-- | Send a counter increment
incrementCounter :: (MetricSink m, MonadIO m) =>
ByteString -- ^ Metric namespace
-> ByteString -- ^ Metric bucket name
-> Integer -- ^ Count to increment by
-> m ()
incrementCounter namespace bucket count = do
sink <- getSink
liftIO $ eatExceptions $ Metric.push sink counter
return ()
where
counter = Metric.Counter namespace bucket count
----------------------------------------------------------------
{- * Utility Methods for raw message sending/recieving interactions
-}
-- | Send a message and get a message in response
sendRecieve :: Message -> WebsocketInteraction Message
sendRecieve msg = do
conn <- iconn <$> ask
liftIO $ sendReceiveMessage msg conn
-- | Send a message without a response
send :: Message -> WebsocketInteraction ()
send msg = do
conn <- iconn <$> ask
void $ liftIO $ sendMessage msg conn
-- | Get a message
getMessage :: WebsocketInteraction Message
getMessage = do
conn <- iconn <$> ask
liftIO (receiveMessage conn)
getEndpoint :: Message -> String
getEndpoint = fromJust . pushEndpoint
----------------------------------------------------------------
{- * Validity assertions to ensure operations work properly
-}
assert :: (Show a, MonadIO m, MetricSink m)
=> (Bool, a) -- ^ Condition that must be true, and an object to show
-> String -- ^ Error message to print
-> String -- ^ Counter to increment
-> m ()
assert (True, _) _ _ = return ()
assert (False, obj) msg cntr = do
liftIO $ putStrLn $ "Assert failed: " ++ msg ++ " \tObject: " ++ show obj
incrementCounter "push_test.assertfail" (BC.pack cntr) 1
fail "Abort"
assertStatus200 :: (MonadIO m, MetricSink m) => Message -> m ()
assertStatus200 msg = assert (msgStatus == 200, msg)
"message status not 200."
("not200status." ++ statusMsg)
where
statusMsg = show msgStatus
msgStatus = fromJust $ status msg
assertEndpointMatch :: (MonadIO m, MetricSink m) => ChannelID -> Message -> m ()
assertEndpointMatch cid msg = do
assert (length cids == 1, cids) "channel updates is longer than 1." "extra_updates"
assert (updateCid == cid', (updateCid, cid')) "channel ID mismatch." "chan_id_mismatch"
where
cids = fromJust $ updates msg
cid' = fromJust cid
updateCid = cu_channelID $ head cids
----------------------------------------------------------------
{- * Basic SimplePush style websocket interaction commands
-}
-- | Say helo to a remote server
helo :: Uaid -> ChannelIDs -> WebsocketInteraction Message
helo uid cids = sendRecieve heloMsg
where
heloMsg = mkMessage {messageType="hello", uaid=uid, channelIDs=cids}
-- | Register a channel ID with a remote server
register :: ChannelID -> WebsocketInteraction Message
register cid = do
msg <- sendRecieve registerMsg
assertStatus200 msg
return msg
where
registerMsg = mkMessage {messageType="register", channelID=cid}
-- | Unregister a channel ID with a remote server
unregister :: ChannelID -> WebsocketInteraction Message
unregister cid = sendRecieve unregisterMsg
where
unregisterMsg = mkMessage {messageType="unregister", channelID=cid}
-- | Ack a notification
ack :: Message -> WebsocketInteraction ()
ack msg = do
send ackMsg
incrementCounter "push_test.notification" "ack" 1
where
ackMsg = mkMessage {messageType="ack", updates=basicChans (updates msg)}
-- Strip out the data from the ack
basicChans = fmap $ map (\update -> update { cu_data=Nothing })
-- | Send a Push Notification and Receive it
sendPushNotification :: (ChannelID, Endpoint) -> Notification -> WebsocketInteraction Message
sendPushNotification (cid, endpoint) notif@Notification{..} = do
sess <- iSession <$> ask
msg <- withTimer "push_test.update" "latency" $ do
sendNotification sess endpoint notif
incrementCounter "push_test.notification" "sent" 1
getMessage
incDataCounter notifData
assertEndpointMatch cid msg
incrementCounter "push_test.notification" "received" 1
return msg
where
incDataCounter Nothing = return ()
incDataCounter (Just d) =
incrementCounter "push_test.notification.throughput" "bytes"
(msgLen d)
msgLen = toInteger . length
ping :: WebsocketInteraction Bool
ping = do
conn <- iconn <$> ask
liftIO $ WS.sendTextData conn ("{}" :: BL.ByteString)
(d :: BL.ByteString) <- liftIO $ WS.receiveData conn
return $ d == "{}"
----------------------------------------------------------------
{- * MonadIO utility methods
-}
-- | Wait for a given amount of seconds
wait :: MonadIO m => Int -> m ()
wait i = liftIO $ threadDelay (i * 1000000)
-- | Generate a random valid channelID
randomChannelId :: MonadIO m => m ChannelID
randomChannelId = do
(ValidChannelID cid) <- liftIO $ generate (arbitrary :: Gen ValidChannelID)
return cid
-- | Choose from a list randomly
randomElement :: MonadIO m => [a] -> m a
randomElement xs = liftIO $ generate (elements xs)
randomNumber :: MonadIO m => (Int, Int) -> m Int
randomNumber (l, u) = liftIO $ generate $ choose (l, u)
randomChoice :: MonadIO m => S.Seq a -> m a
randomChoice vec = do
i <- randomNumber (0, S.length vec - 1)
return $ S.index vec i
hexChar :: Gen Char
hexChar = elements (['a'..'f'] ++ ['0'..'9'])
randomData :: MonadIO m => Int -> m String
randomData len = liftIO $ generate $ vectorOf len hexChar
----------------------------------------------------------------
{- * Utility methods for parsing messages and generating components
-}
-- | Send a PUT request to a notification point
sendNotification :: MonadIO m => Wreq.Session -> String -> Notification -> m ()
sendNotification sess ep notif = liftIO $ void $ Wreq.put sess ep encNotif
where encNotif = serializeNotification notif
-- | Serialize the notification to a bytestring for sending
serializeNotification :: Notification -> [FormParam]
serializeNotification (Notification ver Nothing) = [serializeVersion ver]
serializeNotification (Notification ver dat) = [encVer, encData]
where
encVer = serializeVersion ver
encData = serializeData dat
-- | Serialize the version to a bytestring for sending
serializeVersion :: Version -> FormParam
serializeVersion Nothing = "version" := ("" :: String)
serializeVersion (Just ver) = "version" := ver
-- | Serialize the data to a bytestring
serializeData :: Data -> FormParam
serializeData dat = "data" := fromMaybe ("" :: String) dat
eatExceptions :: IO a -> IO ()
eatExceptions m = void m `E.catch` \(_ :: E.SomeException) -> return ()
|
bbangert/push-tester
|
spTester/SimpleTest/Interact.hs
|
mpl-2.0
| 14,577 | 0 | 15 | 3,731 | 3,441 | 1,844 | 1,597 | 295 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-- Module : Test.AWS.CodeCommit
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Test.AWS.CodeCommit
( tests
, fixtures
) where
import Network.AWS.CodeCommit
import Test.AWS.Gen.CodeCommit
import Test.Tasty
tests :: [TestTree]
tests = []
fixtures :: [TestTree]
fixtures = []
|
fmapfmapfmap/amazonka
|
amazonka-codecommit/test/Test/AWS/CodeCommit.hs
|
mpl-2.0
| 752 | 0 | 5 | 201 | 73 | 50 | 23 | 11 | 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="ko-KR">
<title>Tips and Tricks | 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/tips/src/main/javahelp/org/zaproxy/zap/extension/tips/resources/help_ko_KR/helpset_ko_KR.hs
|
apache-2.0
| 977 | 80 | 66 | 161 | 417 | 211 | 206 | -1 | -1 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Dotnet
-- Copyright : (c) sof, 2003
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- Primitive operations and types for doing .NET interop
--
-----------------------------------------------------------------------------
module GHC.Dotnet
( Object
, unmarshalObject
, marshalObject
, unmarshalString
, marshalString
, checkResult
) where
import GHC.Prim
import GHC.Base
import GHC.IO
import GHC.IOBase
import GHC.Ptr
import Foreign.Marshal.Array
import Foreign.Marshal.Alloc
import Foreign.Storable
import Foreign.C.String
data Object a
= Object Addr#
checkResult :: (State# RealWorld -> (# State# RealWorld, a, Addr# #))
-> IO a
checkResult fun = IO $ \ st ->
case fun st of
(# st1, res, err #)
| err `eqAddr#` nullAddr# -> (# st1, res #)
| otherwise -> throw (IOException (raiseError err)) st1
-- ToDo: attach finaliser.
unmarshalObject :: Addr# -> Object a
unmarshalObject x = Object x
marshalObject :: Object a -> (Addr# -> IO b) -> IO b
marshalObject (Object x) cont = cont x
-- dotnet interop support passing and returning
-- strings.
marshalString :: String
-> (Addr# -> IO a)
-> IO a
marshalString str cont = withCString str (\ (Ptr x) -> cont x)
-- char** received back from a .NET interop layer.
unmarshalString :: Addr# -> String
unmarshalString p = unsafePerformIO $ do
let ptr = Ptr p
str <- peekCString ptr
free ptr
return str
-- room for improvement..
raiseError :: Addr# -> IOError
raiseError p = userError (".NET error: " ++ unmarshalString p)
|
FranklinChen/hugs98-plus-Sep2006
|
packages/base/GHC/Dotnet.hs
|
bsd-3-clause
| 1,819 | 10 | 15 | 366 | 441 | 237 | 204 | -1 | -1 |
-- |
-- Module : Crypto.ConstructHash.MiyaguchiPreneel
-- License : BSD-style
-- Maintainer : Kei Hibino <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- Provide the hash function construction method from block cipher
-- <https://en.wikipedia.org/wiki/One-way_compression_function>
--
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Crypto.ConstructHash.MiyaguchiPreneel
( compute, compute'
, MiyaguchiPreneel
) where
import Data.List (foldl')
import Crypto.Data.Padding (pad, Format (ZERO))
import Crypto.Cipher.Types
import Crypto.Error (throwCryptoError)
import Crypto.Internal.ByteArray (ByteArrayAccess, ByteArray, Bytes)
import qualified Crypto.Internal.ByteArray as B
newtype MiyaguchiPreneel a = MP Bytes
deriving (ByteArrayAccess)
instance Eq (MiyaguchiPreneel a) where
MP b1 == MP b2 = B.constEq b1 b2
-- | Compute Miyaguchi-Preneel one way compress using the supplied block cipher.
compute' :: (ByteArrayAccess bin, BlockCipher cipher)
=> (Bytes -> cipher) -- ^ key build function to compute Miyaguchi-Preneel. care about block-size and key-size
-> bin -- ^ input message
-> MiyaguchiPreneel cipher -- ^ output tag
compute' g = MP . foldl' (step $ g) (B.replicate bsz 0) . chunks . pad (ZERO bsz) . B.convert
where
bsz = blockSize ( g B.empty {- dummy to get block size -} )
chunks msg
| B.null msg = []
| otherwise = (hd :: Bytes) : chunks tl
where
(hd, tl) = B.splitAt bsz msg
-- | Compute Miyaguchi-Preneel one way compress using the inferred block cipher.
-- Only safe when KEY-SIZE equals to BLOCK-SIZE.
--
-- Simple usage /mp' msg :: MiyaguchiPreneel AES128/
compute :: (ByteArrayAccess bin, BlockCipher cipher)
=> bin -- ^ input message
-> MiyaguchiPreneel cipher -- ^ output tag
compute = compute' $ throwCryptoError . cipherInit
-- | computation step of Miyaguchi-Preneel
step :: (ByteArray ba, BlockCipher k)
=> (ba -> k)
-> ba
-> ba
-> ba
step g iv msg =
ecbEncrypt k msg `bxor` iv `bxor` msg
where
k = g iv
bxor :: ByteArray ba => ba -> ba -> ba
bxor = B.xor
|
vincenthz/cryptonite
|
Crypto/ConstructHash/MiyaguchiPreneel.hs
|
bsd-3-clause
| 2,286 | 0 | 12 | 576 | 487 | 273 | 214 | 38 | 1 |
module Control.Concurrent.Timer.Types
( Timer(..)
, TimerImmutable(..)
) where
------------------------------------------------------------------------------
import Control.Concurrent (ThreadId)
import Control.Concurrent.MVar (MVar)
import Control.Concurrent.Suspend (Delay)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | The data type representing the timer.
-- For now, the action and delay are fixed for the lifetime of the Timer.
data Timer m = Timer
{ timerImmutable :: MVar (Maybe (TimerImmutable m)) -- ^ If the MVar is empty, someone if mutating the timer. If the MVar contains Nothing, the timer was not started/initialized.
}
data TimerImmutable m = TimerImmutable
{ timerAction :: m ()
, timerDelay :: Delay
, timerThreadID :: ThreadId
}
|
Palmik/timers
|
src/Control/Concurrent/Timer/Types.hs
|
bsd-3-clause
| 938 | 0 | 13 | 170 | 126 | 80 | 46 | 12 | 0 |
-- |
-- Module: Network.FastIRC.Users
-- Copyright: (c) 2010 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <[email protected]>
-- Stability: alpha
--
-- This module includes parsers for IRC users.
module Network.FastIRC.Users
( UserSpec(..),
userIsServer,
showUserSpec,
userParser )
where
import qualified Data.ByteString.Char8 as B
import Control.Applicative
import Data.Attoparsec.Char8 as P
import Network.FastIRC.ServerSet
import Network.FastIRC.Types
import Network.FastIRC.Utils
-- | IRC user or server.
data UserSpec
-- | Nickname.
= Nick NickName
-- | Nickname, username and hostname.
| User NickName UserName HostName
deriving (Eq, Read, Show)
-- | Check whether a given nickname is a server.
userIsServer :: UserSpec -> ServerSet -> Bool
userIsServer (User _ _ _) _ = False
userIsServer (Nick nick) servers = isServer nick servers
-- | Turn a 'UserSpec' into a 'B.ByteString' in a format suitable to be
-- sent to the IRC server.
showUserSpec :: UserSpec -> MsgString
showUserSpec (Nick n) = n
showUserSpec (User n u h) = B.concat [ n, B.cons '!' u, B.cons '@' h ]
-- | A 'Parser' for IRC users and servers.
userParser :: Parser UserSpec
userParser =
try full <|> nickOnly
where
full :: Parser UserSpec
full =
User <$> P.takeWhile1 isNickChar <* char '!'
<*> P.takeWhile1 isUserChar <* char '@'
<*> P.takeWhile1 isHostChar
nickOnly :: Parser UserSpec
nickOnly = Nick <$> P.takeWhile1 isNickChar
|
chrisdone/hulk
|
fastirc-0.2.0/Network/FastIRC/Users.hs
|
bsd-3-clause
| 1,522 | 0 | 13 | 316 | 334 | 187 | 147 | 31 | 1 |
{-# LANGUAGE DeriveFunctor #-}
module Distribution.Solver.Modular.Flag
( FInfo(..)
, Flag
, FlagInfo
, FN(..)
, QFN
, QSN
, SN(..)
, WeakOrTrivial(..)
, mkFlag
, showFBool
, showQFN
, showQFNBool
, showQSN
, showQSNBool
) where
import Data.Map as M
import Prelude hiding (pi)
import Distribution.PackageDescription hiding (Flag) -- from Cabal
import Distribution.Solver.Modular.Package
import Distribution.Solver.Types.OptionalStanza
import Distribution.Solver.Types.PackagePath
-- | Flag name. Consists of a package instance and the flag identifier itself.
data FN qpn = FN (PI qpn) Flag
deriving (Eq, Ord, Show, Functor)
-- | Flag identifier. Just a string.
type Flag = FlagName
unFlag :: Flag -> String
unFlag (FlagName fn) = fn
mkFlag :: String -> Flag
mkFlag fn = FlagName fn
-- | Flag info. Default value, whether the flag is manual, and
-- whether the flag is weak. Manual flags can only be set explicitly.
-- Weak flags are typically deferred by the solver.
data FInfo = FInfo { fdefault :: Bool, fmanual :: Bool, fweak :: WeakOrTrivial }
deriving (Eq, Ord, Show)
-- | Flag defaults.
type FlagInfo = Map Flag FInfo
-- | Qualified flag name.
type QFN = FN QPN
-- | Stanza name. Paired with a package name, much like a flag.
data SN qpn = SN (PI qpn) OptionalStanza
deriving (Eq, Ord, Show, Functor)
-- | Qualified stanza name.
type QSN = SN QPN
-- | A property of flag and stanza choices that determines whether the
-- choice should be deferred in the solving process.
--
-- A choice is called weak if we do want to defer it. This is the
-- case for flags that should be implied by what's currently installed on
-- the system, as opposed to flags that are used to explicitly enable or
-- disable some functionality.
--
-- A choice is called trivial if it clearly does not matter. The
-- special case of triviality we actually consider is if there are no new
-- dependencies introduced by the choice.
newtype WeakOrTrivial = WeakOrTrivial { unWeakOrTrivial :: Bool }
deriving (Eq, Ord, Show)
unStanza :: OptionalStanza -> String
unStanza TestStanzas = "test"
unStanza BenchStanzas = "bench"
showQFNBool :: QFN -> Bool -> String
showQFNBool qfn@(FN pi _f) b = showPI pi ++ ":" ++ showFBool qfn b
showQSNBool :: QSN -> Bool -> String
showQSNBool qsn@(SN pi _f) b = showPI pi ++ ":" ++ showSBool qsn b
showFBool :: FN qpn -> Bool -> String
showFBool (FN _ f) True = "+" ++ unFlag f
showFBool (FN _ f) False = "-" ++ unFlag f
showSBool :: SN qpn -> Bool -> String
showSBool (SN _ s) True = "*" ++ unStanza s
showSBool (SN _ s) False = "!" ++ unStanza s
showQFN :: QFN -> String
showQFN (FN pi f) = showPI pi ++ ":" ++ unFlag f
showQSN :: QSN -> String
showQSN (SN pi f) = showPI pi ++ ":" ++ unStanza f
|
kolmodin/cabal
|
cabal-install/Distribution/Solver/Modular/Flag.hs
|
bsd-3-clause
| 2,796 | 0 | 8 | 577 | 695 | 391 | 304 | 55 | 1 |
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -O -funbox-strict-fields #-}
-- We always optimise this, otherwise performance of a non-optimised
-- compiler is severely affected
--
-- (c) The University of Glasgow 2002-2006
--
-- Binary I/O library, with special tweaks for GHC
--
-- Based on the nhc98 Binary library, which is copyright
-- (c) Malcolm Wallace and Colin Runciman, University of York, 1998.
-- Under the terms of the license for that software, we must tell you
-- where you can obtain the original version of the Binary library, namely
-- http://www.cs.york.ac.uk/fp/nhc98/
module Binary
( {-type-} Bin,
{-class-} Binary(..),
{-type-} BinHandle,
SymbolTable, Dictionary,
openBinMem,
-- closeBin,
seekBin,
seekBy,
tellBin,
castBin,
writeBinMem,
readBinMem,
fingerprintBinMem,
computeFingerprint,
isEOFBin,
putAt, getAt,
-- for writing instances:
putByte,
getByte,
-- lazy Bin I/O
lazyGet,
lazyPut,
UserData(..), getUserData, setUserData,
newReadState, newWriteState,
putDictionary, getDictionary, putFS,
) where
#include "HsVersions.h"
-- The *host* architecture version:
#include "../includes/MachDeps.h"
import {-# SOURCE #-} Name (Name)
import FastString
import Panic
import UniqFM
import FastMutInt
import Fingerprint
import BasicTypes
import SrcLoc
import Foreign
import Data.Array
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BS
import qualified Data.ByteString.Unsafe as BS
import Data.IORef
import Data.Char ( ord, chr )
import Data.Time
import Data.Typeable
import Control.Monad ( when )
import System.IO as IO
import System.IO.Unsafe ( unsafeInterleaveIO )
import System.IO.Error ( mkIOError, eofErrorType )
import GHC.Real ( Ratio(..) )
type BinArray = ForeignPtr Word8
---------------------------------------------------------------
-- BinHandle
---------------------------------------------------------------
data BinHandle
= BinMem { -- binary data stored in an unboxed array
bh_usr :: UserData, -- sigh, need parameterized modules :-)
_off_r :: !FastMutInt, -- the current offset
_sz_r :: !FastMutInt, -- size of the array (cached)
_arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1))
}
-- XXX: should really store a "high water mark" for dumping out
-- the binary data to a file.
getUserData :: BinHandle -> UserData
getUserData bh = bh_usr bh
setUserData :: BinHandle -> UserData -> BinHandle
setUserData bh us = bh { bh_usr = us }
---------------------------------------------------------------
-- Bin
---------------------------------------------------------------
newtype Bin a = BinPtr Int
deriving (Eq, Ord, Show, Bounded)
castBin :: Bin a -> Bin b
castBin (BinPtr i) = BinPtr i
---------------------------------------------------------------
-- class Binary
---------------------------------------------------------------
class Binary a where
put_ :: BinHandle -> a -> IO ()
put :: BinHandle -> a -> IO (Bin a)
get :: BinHandle -> IO a
-- define one of put_, put. Use of put_ is recommended because it
-- is more likely that tail-calls can kick in, and we rarely need the
-- position return value.
put_ bh a = do _ <- put bh a; return ()
put bh a = do p <- tellBin bh; put_ bh a; return p
putAt :: Binary a => BinHandle -> Bin a -> a -> IO ()
putAt bh p x = do seekBin bh p; put_ bh x; return ()
getAt :: Binary a => BinHandle -> Bin a -> IO a
getAt bh p = do seekBin bh p; get bh
openBinMem :: Int -> IO BinHandle
openBinMem size
| size <= 0 = error "Data.Binary.openBinMem: size must be >= 0"
| otherwise = do
arr <- mallocForeignPtrBytes size
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r size
return (BinMem noUserData ix_r sz_r arr_r)
tellBin :: BinHandle -> IO (Bin a)
tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix)
seekBin :: BinHandle -> Bin a -> IO ()
seekBin h@(BinMem _ ix_r sz_r _) (BinPtr p) = do
sz <- readFastMutInt sz_r
if (p >= sz)
then do expandBin h p; writeFastMutInt ix_r p
else writeFastMutInt ix_r p
seekBy :: BinHandle -> Int -> IO ()
seekBy h@(BinMem _ ix_r sz_r _) off = do
sz <- readFastMutInt sz_r
ix <- readFastMutInt ix_r
let ix' = ix + off
if (ix' >= sz)
then do expandBin h ix'; writeFastMutInt ix_r ix'
else writeFastMutInt ix_r ix'
isEOFBin :: BinHandle -> IO Bool
isEOFBin (BinMem _ ix_r sz_r _) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
return (ix >= sz)
writeBinMem :: BinHandle -> FilePath -> IO ()
writeBinMem (BinMem _ ix_r _ arr_r) fn = do
h <- openBinaryFile fn WriteMode
arr <- readIORef arr_r
ix <- readFastMutInt ix_r
withForeignPtr arr $ \p -> hPutBuf h p ix
hClose h
readBinMem :: FilePath -> IO BinHandle
-- Return a BinHandle with a totally undefined State
readBinMem filename = do
h <- openBinaryFile filename ReadMode
filesize' <- hFileSize h
let filesize = fromIntegral filesize'
arr <- mallocForeignPtrBytes (filesize*2)
count <- withForeignPtr arr $ \p -> hGetBuf h p filesize
when (count /= filesize) $
error ("Binary.readBinMem: only read " ++ show count ++ " bytes")
hClose h
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r filesize
return (BinMem noUserData ix_r sz_r arr_r)
fingerprintBinMem :: BinHandle -> IO Fingerprint
fingerprintBinMem (BinMem _ ix_r _ arr_r) = do
arr <- readIORef arr_r
ix <- readFastMutInt ix_r
withForeignPtr arr $ \p -> fingerprintData p ix
computeFingerprint :: Binary a
=> (BinHandle -> Name -> IO ())
-> a
-> IO Fingerprint
computeFingerprint put_name a = do
bh <- openBinMem (3*1024) -- just less than a block
bh <- return $ setUserData bh $ newWriteState put_name putFS
put_ bh a
fingerprintBinMem bh
-- expand the size of the array to include a specified offset
expandBin :: BinHandle -> Int -> IO ()
expandBin (BinMem _ _ sz_r arr_r) off = do
sz <- readFastMutInt sz_r
let sz' = head (dropWhile (<= off) (iterate (* 2) sz))
arr <- readIORef arr_r
arr' <- mallocForeignPtrBytes sz'
withForeignPtr arr $ \old ->
withForeignPtr arr' $ \new ->
copyBytes new old sz
writeFastMutInt sz_r sz'
writeIORef arr_r arr'
-- -----------------------------------------------------------------------------
-- Low-level reading/writing of bytes
putWord8 :: BinHandle -> Word8 -> IO ()
putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
-- double the size of the array if it overflows
if (ix >= sz)
then do expandBin h ix
putWord8 h w
else do arr <- readIORef arr_r
withForeignPtr arr $ \p -> pokeByteOff p ix w
writeFastMutInt ix_r (ix+1)
return ()
getWord8 :: BinHandle -> IO Word8
getWord8 (BinMem _ ix_r sz_r arr_r) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
when (ix >= sz) $
ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing)
arr <- readIORef arr_r
w <- withForeignPtr arr $ \p -> peekByteOff p ix
writeFastMutInt ix_r (ix+1)
return w
putByte :: BinHandle -> Word8 -> IO ()
putByte bh w = put_ bh w
getByte :: BinHandle -> IO Word8
getByte = getWord8
-- -----------------------------------------------------------------------------
-- Primitve Word writes
instance Binary Word8 where
put_ = putWord8
get = getWord8
instance Binary Word16 where
put_ h w = do -- XXX too slow.. inline putWord8?
putByte h (fromIntegral (w `shiftR` 8))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2)
instance Binary Word32 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 24))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 24) .|.
(fromIntegral w2 `shiftL` 16) .|.
(fromIntegral w3 `shiftL` 8) .|.
(fromIntegral w4))
instance Binary Word64 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 56))
putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
w5 <- getWord8 h
w6 <- getWord8 h
w7 <- getWord8 h
w8 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 56) .|.
(fromIntegral w2 `shiftL` 48) .|.
(fromIntegral w3 `shiftL` 40) .|.
(fromIntegral w4 `shiftL` 32) .|.
(fromIntegral w5 `shiftL` 24) .|.
(fromIntegral w6 `shiftL` 16) .|.
(fromIntegral w7 `shiftL` 8) .|.
(fromIntegral w8))
-- -----------------------------------------------------------------------------
-- Primitve Int writes
instance Binary Int8 where
put_ h w = put_ h (fromIntegral w :: Word8)
get h = do w <- get h; return $! (fromIntegral (w::Word8))
instance Binary Int16 where
put_ h w = put_ h (fromIntegral w :: Word16)
get h = do w <- get h; return $! (fromIntegral (w::Word16))
instance Binary Int32 where
put_ h w = put_ h (fromIntegral w :: Word32)
get h = do w <- get h; return $! (fromIntegral (w::Word32))
instance Binary Int64 where
put_ h w = put_ h (fromIntegral w :: Word64)
get h = do w <- get h; return $! (fromIntegral (w::Word64))
-- -----------------------------------------------------------------------------
-- Instances for standard types
instance Binary () where
put_ _ () = return ()
get _ = return ()
instance Binary Bool where
put_ bh b = putByte bh (fromIntegral (fromEnum b))
get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x))
instance Binary Char where
put_ bh c = put_ bh (fromIntegral (ord c) :: Word32)
get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word32)))
instance Binary Int where
put_ bh i = put_ bh (fromIntegral i :: Int64)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int64))
instance Binary a => Binary [a] where
put_ bh l = do
let len = length l
if (len < 0xff)
then putByte bh (fromIntegral len :: Word8)
else do putByte bh 0xff; put_ bh (fromIntegral len :: Word32)
mapM_ (put_ bh) l
get bh = do
b <- getByte bh
len <- if b == 0xff
then get bh
else return (fromIntegral b :: Word32)
let loop 0 = return []
loop n = do a <- get bh; as <- loop (n-1); return (a:as)
loop len
instance (Binary a, Binary b) => Binary (a,b) where
put_ bh (a,b) = do put_ bh a; put_ bh b
get bh = do a <- get bh
b <- get bh
return (a,b)
instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where
put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c
get bh = do a <- get bh
b <- get bh
c <- get bh
return (a,b,c)
instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where
put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (a,b,c,d)
instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d, e) where
put_ bh (a,b,c,d, e) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e;
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
e <- get bh
return (a,b,c,d,e)
instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f) => Binary (a,b,c,d, e, f) where
put_ bh (a,b,c,d, e, f) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; put_ bh f;
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
e <- get bh
f <- get bh
return (a,b,c,d,e,f)
instance Binary a => Binary (Maybe a) where
put_ bh Nothing = putByte bh 0
put_ bh (Just a) = do putByte bh 1; put_ bh a
get bh = do h <- getWord8 bh
case h of
0 -> return Nothing
_ -> do x <- get bh; return (Just x)
instance (Binary a, Binary b) => Binary (Either a b) where
put_ bh (Left a) = do putByte bh 0; put_ bh a
put_ bh (Right b) = do putByte bh 1; put_ bh b
get bh = do h <- getWord8 bh
case h of
0 -> do a <- get bh ; return (Left a)
_ -> do b <- get bh ; return (Right b)
instance Binary UTCTime where
put_ bh u = do put_ bh (utctDay u)
put_ bh (utctDayTime u)
get bh = do day <- get bh
dayTime <- get bh
return $ UTCTime { utctDay = day, utctDayTime = dayTime }
instance Binary Day where
put_ bh d = put_ bh (toModifiedJulianDay d)
get bh = do i <- get bh
return $ ModifiedJulianDay { toModifiedJulianDay = i }
instance Binary DiffTime where
put_ bh dt = put_ bh (toRational dt)
get bh = do r <- get bh
return $ fromRational r
--to quote binary-0.3 on this code idea,
--
-- TODO This instance is not architecture portable. GMP stores numbers as
-- arrays of machine sized words, so the byte format is not portable across
-- architectures with different endianess and word size.
--
-- This makes it hard (impossible) to make an equivalent instance
-- with code that is compilable with non-GHC. Do we need any instance
-- Binary Integer, and if so, does it have to be blazing fast? Or can
-- we just change this instance to be portable like the rest of the
-- instances? (binary package has code to steal for that)
--
-- yes, we need Binary Integer and Binary Rational in basicTypes/Literal.hs
instance Binary Integer where
-- XXX This is hideous
put_ bh i = put_ bh (show i)
get bh = do str <- get bh
case reads str of
[(i, "")] -> return i
_ -> fail ("Binary Integer: got " ++ show str)
{-
-- This code is currently commented out.
-- See https://ghc.haskell.org/trac/ghc/ticket/3379#comment:10 for
-- discussion.
put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#)
put_ bh (J# s# a#) = do
putByte bh 1
put_ bh (I# s#)
let sz# = sizeofByteArray# a# -- in *bytes*
put_ bh (I# sz#) -- in *bytes*
putByteArray bh a# sz#
get bh = do
b <- getByte bh
case b of
0 -> do (I# i#) <- get bh
return (S# i#)
_ -> do (I# s#) <- get bh
sz <- get bh
(BA a#) <- getByteArray bh sz
return (J# s# a#)
putByteArray :: BinHandle -> ByteArray# -> Int# -> IO ()
putByteArray bh a s# = loop 0#
where loop n#
| n# ==# s# = return ()
| otherwise = do
putByte bh (indexByteArray a n#)
loop (n# +# 1#)
getByteArray :: BinHandle -> Int -> IO ByteArray
getByteArray bh (I# sz) = do
(MBA arr) <- newByteArray sz
let loop n
| n ==# sz = return ()
| otherwise = do
w <- getByte bh
writeByteArray arr n w
loop (n +# 1#)
loop 0#
freezeByteArray arr
-}
{-
data ByteArray = BA ByteArray#
data MBA = MBA (MutableByteArray# RealWorld)
newByteArray :: Int# -> IO MBA
newByteArray sz = IO $ \s ->
case newByteArray# sz s of { (# s, arr #) ->
(# s, MBA arr #) }
freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray
freezeByteArray arr = IO $ \s ->
case unsafeFreezeByteArray# arr s of { (# s, arr #) ->
(# s, BA arr #) }
writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO ()
writeByteArray arr i (W8# w) = IO $ \s ->
case writeWord8Array# arr i w s of { s ->
(# s, () #) }
indexByteArray :: ByteArray# -> Int# -> Word8
indexByteArray a# n# = W8# (indexWord8Array# a# n#)
-}
instance (Binary a) => Binary (Ratio a) where
put_ bh (a :% b) = do put_ bh a; put_ bh b
get bh = do a <- get bh; b <- get bh; return (a :% b)
instance Binary (Bin a) where
put_ bh (BinPtr i) = put_ bh (fromIntegral i :: Int32)
get bh = do i <- get bh; return (BinPtr (fromIntegral (i :: Int32)))
-- -----------------------------------------------------------------------------
-- Instances for Data.Typeable stuff
instance Binary TyCon where
put_ bh tc = do
put_ bh (tyConPackage tc)
put_ bh (tyConModule tc)
put_ bh (tyConName tc)
get bh = do
p <- get bh
m <- get bh
n <- get bh
return (mkTyCon3 p m n)
instance Binary TypeRep where
put_ bh type_rep = do
let (ty_con, child_type_reps) = splitTyConApp type_rep
put_ bh ty_con
put_ bh child_type_reps
get bh = do
ty_con <- get bh
child_type_reps <- get bh
return (mkTyConApp ty_con child_type_reps)
-- -----------------------------------------------------------------------------
-- Lazy reading/writing
lazyPut :: Binary a => BinHandle -> a -> IO ()
lazyPut bh a = do
-- output the obj with a ptr to skip over it:
pre_a <- tellBin bh
put_ bh pre_a -- save a slot for the ptr
put_ bh a -- dump the object
q <- tellBin bh -- q = ptr to after object
putAt bh pre_a q -- fill in slot before a with ptr to q
seekBin bh q -- finally carry on writing at q
lazyGet :: Binary a => BinHandle -> IO a
lazyGet bh = do
p <- get bh -- a BinPtr
p_a <- tellBin bh
a <- unsafeInterleaveIO $ do
-- NB: Use a fresh off_r variable in the child thread, for thread
-- safety.
off_r <- newFastMutInt
getAt bh { _off_r = off_r } p_a
seekBin bh p -- skip over the object for now
return a
-- -----------------------------------------------------------------------------
-- UserData
-- -----------------------------------------------------------------------------
data UserData =
UserData {
-- for *deserialising* only:
ud_get_name :: BinHandle -> IO Name,
ud_get_fs :: BinHandle -> IO FastString,
-- for *serialising* only:
ud_put_name :: BinHandle -> Name -> IO (),
ud_put_fs :: BinHandle -> FastString -> IO ()
}
newReadState :: (BinHandle -> IO Name)
-> (BinHandle -> IO FastString)
-> UserData
newReadState get_name get_fs
= UserData { ud_get_name = get_name,
ud_get_fs = get_fs,
ud_put_name = undef "put_name",
ud_put_fs = undef "put_fs"
}
newWriteState :: (BinHandle -> Name -> IO ())
-> (BinHandle -> FastString -> IO ())
-> UserData
newWriteState put_name put_fs
= UserData { ud_get_name = undef "get_name",
ud_get_fs = undef "get_fs",
ud_put_name = put_name,
ud_put_fs = put_fs
}
noUserData :: a
noUserData = undef "UserData"
undef :: String -> a
undef s = panic ("Binary.UserData: no " ++ s)
---------------------------------------------------------
-- The Dictionary
---------------------------------------------------------
type Dictionary = Array Int FastString -- The dictionary
-- Should be 0-indexed
putDictionary :: BinHandle -> Int -> UniqFM (Int,FastString) -> IO ()
putDictionary bh sz dict = do
put_ bh sz
mapM_ (putFS bh) (elems (array (0,sz-1) (eltsUFM dict)))
getDictionary :: BinHandle -> IO Dictionary
getDictionary bh = do
sz <- get bh
elems <- sequence (take sz (repeat (getFS bh)))
return (listArray (0,sz-1) elems)
---------------------------------------------------------
-- The Symbol Table
---------------------------------------------------------
-- On disk, the symbol table is an array of IfaceExtName, when
-- reading it in we turn it into a SymbolTable.
type SymbolTable = Array Int Name
---------------------------------------------------------
-- Reading and writing FastStrings
---------------------------------------------------------
putFS :: BinHandle -> FastString -> IO ()
putFS bh fs = putBS bh $ fastStringToByteString fs
getFS :: BinHandle -> IO FastString
getFS bh = do bs <- getBS bh
return $! mkFastStringByteString bs
putBS :: BinHandle -> ByteString -> IO ()
putBS bh bs =
BS.unsafeUseAsCStringLen bs $ \(ptr, l) -> do
put_ bh l
let
go n | n == l = return ()
| otherwise = do
b <- peekElemOff (castPtr ptr) n
putByte bh b
go (n+1)
go 0
{- -- possible faster version, not quite there yet:
getBS bh@BinMem{} = do
(I# l) <- get bh
arr <- readIORef (arr_r bh)
off <- readFastMutInt (off_r bh)
return $! (mkFastSubBytesBA# arr off l)
-}
getBS :: BinHandle -> IO ByteString
getBS bh = do
l <- get bh
fp <- mallocForeignPtrBytes l
withForeignPtr fp $ \ptr -> do
let go n | n == l = return $ BS.fromForeignPtr fp 0 l
| otherwise = do
b <- getByte bh
pokeElemOff ptr n b
go (n+1)
--
go 0
instance Binary ByteString where
put_ bh f = putBS bh f
get bh = getBS bh
instance Binary FastString where
put_ bh f =
case getUserData bh of
UserData { ud_put_fs = put_fs } -> put_fs bh f
get bh =
case getUserData bh of
UserData { ud_get_fs = get_fs } -> get_fs bh
-- Here to avoid loop
instance Binary Fingerprint where
put_ h (Fingerprint w1 w2) = do put_ h w1; put_ h w2
get h = do w1 <- get h; w2 <- get h; return (Fingerprint w1 w2)
instance Binary FunctionOrData where
put_ bh IsFunction = putByte bh 0
put_ bh IsData = putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> return IsFunction
1 -> return IsData
_ -> panic "Binary FunctionOrData"
instance Binary TupleSort where
put_ bh BoxedTuple = putByte bh 0
put_ bh UnboxedTuple = putByte bh 1
put_ bh ConstraintTuple = putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> do return BoxedTuple
1 -> do return UnboxedTuple
_ -> do return ConstraintTuple
instance Binary Activation where
put_ bh NeverActive = do
putByte bh 0
put_ bh AlwaysActive = do
putByte bh 1
put_ bh (ActiveBefore aa) = do
putByte bh 2
put_ bh aa
put_ bh (ActiveAfter ab) = do
putByte bh 3
put_ bh ab
get bh = do
h <- getByte bh
case h of
0 -> do return NeverActive
1 -> do return AlwaysActive
2 -> do aa <- get bh
return (ActiveBefore aa)
_ -> do ab <- get bh
return (ActiveAfter ab)
instance Binary InlinePragma where
put_ bh (InlinePragma s a b c d) = do
put_ bh s
put_ bh a
put_ bh b
put_ bh c
put_ bh d
get bh = do
s <- get bh
a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (InlinePragma s a b c d)
instance Binary RuleMatchInfo where
put_ bh FunLike = putByte bh 0
put_ bh ConLike = putByte bh 1
get bh = do
h <- getByte bh
if h == 1 then return ConLike
else return FunLike
instance Binary InlineSpec where
put_ bh EmptyInlineSpec = putByte bh 0
put_ bh Inline = putByte bh 1
put_ bh Inlinable = putByte bh 2
put_ bh NoInline = putByte bh 3
get bh = do h <- getByte bh
case h of
0 -> return EmptyInlineSpec
1 -> return Inline
2 -> return Inlinable
_ -> return NoInline
instance Binary DefMethSpec where
put_ bh NoDM = putByte bh 0
put_ bh VanillaDM = putByte bh 1
put_ bh GenericDM = putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> return NoDM
1 -> return VanillaDM
_ -> return GenericDM
instance Binary RecFlag where
put_ bh Recursive = do
putByte bh 0
put_ bh NonRecursive = do
putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> do return Recursive
_ -> do return NonRecursive
instance Binary OverlapMode where
put_ bh (NoOverlap s) = putByte bh 0 >> put_ bh s
put_ bh (Overlaps s) = putByte bh 1 >> put_ bh s
put_ bh (Incoherent s) = putByte bh 2 >> put_ bh s
put_ bh (Overlapping s) = putByte bh 3 >> put_ bh s
put_ bh (Overlappable s) = putByte bh 4 >> put_ bh s
get bh = do
h <- getByte bh
case h of
0 -> (get bh) >>= \s -> return $ NoOverlap s
1 -> (get bh) >>= \s -> return $ Overlaps s
2 -> (get bh) >>= \s -> return $ Incoherent s
3 -> (get bh) >>= \s -> return $ Overlapping s
4 -> (get bh) >>= \s -> return $ Overlappable s
_ -> panic ("get OverlapMode" ++ show h)
instance Binary OverlapFlag where
put_ bh flag = do put_ bh (overlapMode flag)
put_ bh (isSafeOverlap flag)
get bh = do
h <- get bh
b <- get bh
return OverlapFlag { overlapMode = h, isSafeOverlap = b }
instance Binary FixityDirection where
put_ bh InfixL = do
putByte bh 0
put_ bh InfixR = do
putByte bh 1
put_ bh InfixN = do
putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> do return InfixL
1 -> do return InfixR
_ -> do return InfixN
instance Binary Fixity where
put_ bh (Fixity aa ab) = do
put_ bh aa
put_ bh ab
get bh = do
aa <- get bh
ab <- get bh
return (Fixity aa ab)
instance Binary WarningTxt where
put_ bh (WarningTxt s w) = do
putByte bh 0
put_ bh s
put_ bh w
put_ bh (DeprecatedTxt s d) = do
putByte bh 1
put_ bh s
put_ bh d
get bh = do
h <- getByte bh
case h of
0 -> do s <- get bh
w <- get bh
return (WarningTxt s w)
_ -> do s <- get bh
d <- get bh
return (DeprecatedTxt s d)
instance Binary StringLiteral where
put_ bh (StringLiteral st fs) = do
put_ bh st
put_ bh fs
get bh = do
st <- get bh
fs <- get bh
return (StringLiteral st fs)
instance Binary a => Binary (GenLocated SrcSpan a) where
put_ bh (L l x) = do
put_ bh l
put_ bh x
get bh = do
l <- get bh
x <- get bh
return (L l x)
instance Binary SrcSpan where
put_ bh (RealSrcSpan ss) = do
putByte bh 0
put_ bh (srcSpanFile ss)
put_ bh (srcSpanStartLine ss)
put_ bh (srcSpanStartCol ss)
put_ bh (srcSpanEndLine ss)
put_ bh (srcSpanEndCol ss)
put_ bh (UnhelpfulSpan s) = do
putByte bh 1
put_ bh s
get bh = do
h <- getByte bh
case h of
0 -> do f <- get bh
sl <- get bh
sc <- get bh
el <- get bh
ec <- get bh
return (mkSrcSpan (mkSrcLoc f sl sc)
(mkSrcLoc f el ec))
_ -> do s <- get bh
return (UnhelpfulSpan s)
|
AlexanderPankiv/ghc
|
compiler/utils/Binary.hs
|
bsd-3-clause
| 29,290 | 0 | 19 | 9,690 | 9,152 | 4,421 | 4,731 | 657 | 2 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__
{-# LANGUAGE MagicHash #-}
#endif
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Data.BitUtil
-- Copyright : (c) Clark Gaebel 2012
-- (c) Johan Tibel 2012
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
-----------------------------------------------------------------------------
module Data.BitUtil
( highestBitMask
) where
-- On GHC, include MachDeps.h to get WORD_SIZE_IN_BITS macro.
#if defined(__GLASGOW_HASKELL__)
# include "MachDeps.h"
#endif
import Data.Bits ((.|.), xor)
#if __GLASGOW_HASKELL__
import GHC.Exts (Word(..), Int(..))
import GHC.Prim (uncheckedShiftRL#)
#else
import Data.Word (shiftL, shiftR)
#endif
-- The highestBitMask implementation is based on
-- http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
-- which has been put in the public domain.
-- | Return a word where only the highest bit is set.
highestBitMask :: Word -> Word
highestBitMask x1 = let x2 = x1 .|. x1 `shiftRL` 1
x3 = x2 .|. x2 `shiftRL` 2
x4 = x3 .|. x3 `shiftRL` 4
x5 = x4 .|. x4 `shiftRL` 8
x6 = x5 .|. x5 `shiftRL` 16
#if !(defined(__GLASGOW_HASKELL__) && WORD_SIZE_IN_BITS==32)
x7 = x6 .|. x6 `shiftRL` 32
in x7 `xor` (x7 `shiftRL` 1)
#else
in x6 `xor` (x6 `shiftRL` 1)
#endif
{-# INLINE highestBitMask #-}
-- Right and left logical shifts.
shiftRL :: Word -> Int -> Word
#if __GLASGOW_HASKELL__
{--------------------------------------------------------------------
GHC: use unboxing to get @shiftRL@ inlined.
--------------------------------------------------------------------}
shiftRL (W# x) (I# i) = W# (uncheckedShiftRL# x i)
#else
shiftRL x i = shiftR x i
#endif
{-# INLINE shiftRL #-}
|
ariep/psqueues
|
src/Data/BitUtil.hs
|
bsd-3-clause
| 2,071 | 0 | 10 | 464 | 269 | 173 | 96 | 17 | 1 |
yes = mapMaybe id
|
mpickering/hlint-refactor
|
tests/examples/Default72.hs
|
bsd-3-clause
| 17 | 0 | 5 | 3 | 9 | 4 | 5 | 1 | 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="sr-CS">
<title>Encode/Decode/Hash Add-on</title>
<maps>
<homeID>encoder</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/encoder/src/main/javahelp/org/zaproxy/addon/encoder/resources/help_sr_CS/helpset_sr_CS.hs
|
apache-2.0
| 974 | 77 | 69 | 156 | 419 | 212 | 207 | -1 | -1 |
module Options.Phases where
import Types
phaseOptions :: [Flag]
phaseOptions =
[ flag { flagName = "-F"
, flagDescription =
"Enable the use of a :ref:`pre-processor <pre-processor>` "++
"(set with ``-pgmF``)"
, flagType = DynamicFlag
}
, flag { flagName = "-E"
, flagDescription = "Stop after preprocessing (``.hspp`` file)"
, flagType = ModeFlag
}
, flag { flagName = "-C"
, flagDescription = "Stop after generating C (``.hc`` file)"
, flagType = ModeFlag
}
, flag { flagName = "-S"
, flagDescription = "Stop after generating assembly (``.s`` file)"
, flagType = ModeFlag
}
, flag { flagName = "-c"
, flagDescription = "Stop after generating object (``.o``) file"
, flagType = ModeFlag
}
, flag { flagName = "-x⟨suffix⟩"
, flagDescription = "Override default behaviour for source files"
, flagType = DynamicFlag
}
]
|
ml9951/ghc
|
utils/mkUserGuidePart/Options/Phases.hs
|
bsd-3-clause
| 1,021 | 0 | 8 | 335 | 164 | 106 | 58 | 24 | 1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.ForeignPtr
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- The 'ForeignPtr' type and operations. This module is part of the
-- Foreign Function Interface (FFI) and will usually be imported via
-- the "Foreign" module.
--
-----------------------------------------------------------------------------
module Foreign.ForeignPtr (
-- * Finalised data pointers
ForeignPtr
, FinalizerPtr
, FinalizerEnvPtr
-- ** Basic operations
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
, withForeignPtr
, finalizeForeignPtr
-- ** Low-level operations
, touchForeignPtr
, castForeignPtr
-- ** Allocating managed memory
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
) where
import Foreign.ForeignPtr.Safe
|
lukexi/ghc
|
libraries/base/Foreign/ForeignPtr.hs
|
bsd-3-clause
| 1,306 | 0 | 4 | 327 | 83 | 62 | 21 | 20 | 0 |
{-# LANGUAGE FunctionalDependencies, PolyKinds, FlexibleInstances #-}
module T10570 where
import Data.Proxy
class ConsByIdx2 x a m cls | x -> m where
consByIdx2 :: x -> a -> m cls
instance ConsByIdx2 Int a Proxy cls where
consByIdx2 _ _ = Proxy
|
urbanslug/ghc
|
testsuite/tests/polykinds/T10570.hs
|
bsd-3-clause
| 257 | 0 | 9 | 54 | 71 | 38 | 33 | -1 | -1 |
{-# LANGUAGE NamedWildCards, ScopedTypeVariables #-}
module WildcardsInPatternAndExprSig where
bar (Just ([x :: _a] :: _) :: Maybe [_b]) (z :: _c) = [x, z] :: [_d]
|
urbanslug/ghc
|
testsuite/tests/partial-sigs/should_fail/WildcardsInPatternAndExprSig.hs
|
bsd-3-clause
| 165 | 0 | 12 | 27 | 64 | 37 | 27 | 3 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
module TypeLits
(
-- * Types
Scalar,
Vector,
Matrix,
-- * Classes
AccFunctor(..),
-- * Constructors
mkMatrix,
mkVector,
identityMatrix,
-- * Functions
-- ** Scalar & X
(.*^),
(./^),
(.*#),
(./#),
-- ** Matrix & Vector
(#*^),
(^*#),
-- ** Vector & Vector
(^+^),
(^-^),
(^*^),
-- ** Matrix & Matrix
(#+#),
(#-#),
(#*#),
(#**.),
)
where
import qualified Data.Array.Accelerate as A
import GHC.TypeLits
import Data.Array.Accelerate ( (:.)(..), Array
, Exp
, DIM0, DIM1, DIM2, Z(Z)
, IsFloating, IsNum, Elt, Acc
, All(All)
)
import Data.Proxy
type Scalar a = Acc (Array DIM0 a)
-- | A typesafe way to represent a Vector and its dimension
newtype Vector (dim :: Nat) a = AccVector { unVector :: Acc (Array DIM1 a)}
-- | A typesafe way to represent a Matrix and its rows/colums
newtype Matrix (rows :: Nat) (cols :: Nat) a = AccMatrix {unMatrix :: Acc (Array DIM2 a)}
-- | a functor like instance for a functor like instance for Accelerate computations
-- instead of working with simple functions `(a -> b)` this uses (Exp a -> Exp b)
class AccFunctor f where
afmap :: forall a b. (Elt a, Elt b) => (Exp a -> Exp b) -> f a -> f b
instance forall n. (KnownNat n) => AccFunctor (Vector n) where
afmap f (AccVector a) = AccVector (A.map f a)
instance forall m n. (KnownNat m, KnownNat n) => AccFunctor (Matrix m n) where
afmap f (AccMatrix a) = AccMatrix (A.map f a)
mkVector :: forall n a. (KnownNat n, Elt a) => [a] -> Maybe (Vector n a)
-- | a smart constructor to generate Vectors - returning Nothing
-- if the input list is not as long as the dimension of the Vector
mkVector as = if length as == n'
then Just $ AccVector (A.use $ A.fromList (Z:.n') as)
else Nothing
where n' = fromInteger $ natVal (Proxy :: Proxy n)
mkMatrix :: forall m n a. (KnownNat m, KnownNat n, Elt a)
=> [a] -> Maybe (Matrix m n a)
-- | a smart constructor to generate Matrices - returning Nothing
-- if the input list is not as long as the "length" of the Matrix, i.e. rows*colums
mkMatrix as = if length as == m'*n'
then Just $ AccMatrix (A.use $ A.fromList (Z:. m':.n') as)
else Nothing
where m' = fromInteger $ natVal (Proxy :: Proxy m)
n' = fromInteger $ natVal (Proxy :: Proxy n)
(#*^) :: forall m n a. (KnownNat m, KnownNat n, IsNum a, Elt a)
=> Matrix m n a -> Vector n a -> Vector n a
-- | the usual matrix-vector product
--
-- > ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛x₁⎞ ⎛ w₁₁*x₁ + w₁₂*x₂ + … w₁ₙ*xₙ ⎞
-- > ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜x₂⎟ ⎜ w₂₁*x₁ + w₂₂*x₂ + … w₂ₙ*xₙ ⎟
-- > ⎜ . . . ⎟ ⎜. ⎟ ⎜ . . . ⎟
-- > ⎜ . . . ⎟ ✕ ⎜. ⎟ = ⎜ . . . ⎟
-- > ⎜ . . . ⎟ ⎜. ⎟ ⎜ . . . ⎟
-- > ⎜ . . . ⎟ ⎜. ⎟ ⎜ . . . ⎟
-- > ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝xₙ⎠ ⎝ wₘ₁*x₁ + wₘ₂*x₂ + … wₘₙ*xₙ ⎠
ma #*^ va = let ma' = unMatrix ma
va' = unVector va
in AccVector $ A.fold1 (+)
$ A.zipWith (*)
ma'
(A.replicate (A.lift $ Z :. m' :. All) va')
where m' = fromInteger $ natVal (Proxy :: Proxy m) :: Int
infixl 7 #*^
(^*#) :: forall m n a. (KnownNat m, KnownNat n, IsNum a, Elt a)
=> Vector m a -> Matrix m n a -> Vector n a
-- | the usual matrix-vector product
--
-- > ⎛x₁⎞T ⎛w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ x₁*w₁₁ + x₂*w₁₂ + … xₙ*w₁ₙ ⎞
-- > ⎜x₂⎟ ⎜w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ x₁*w₂₁ + x₂*w₂₂ + … xₙ*w₂ₙ ⎟
-- > ⎜. ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎜. ⎟ ✕ ⎜ . . . ⎟ = ⎜ . . . ⎟
-- > ⎜. ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎜. ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎝xₘ⎠ ⎝wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ x₁*wₘ₁ + x₂*wₘ₂ + … xₙ*wₘₙ ⎠
va ^*# ma = let va' = unVector va
ma' = unMatrix ma
in AccVector $ A.fold1 (+)
$ A.zipWith (*)
(A.replicate (A.lift $ Z :. n' :. All) va')
ma'
where n' = fromInteger $ natVal (Proxy :: Proxy n) :: Int
infixr 7 ^*#
(^+^), (^-^) :: forall n a. (KnownNat n, IsNum a, Elt a)
=> Vector n a -> Vector n a -> Vector n a
-- | the usual vector addition/subtraction
--
-- > ⎛v₁⎞ ⎛w₁⎞ ⎛ v₁+w₁ ⎞
-- > ⎜v₂⎟ ⎜w₂⎟ ⎜ v₂+w₁ ⎟
-- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟
-- > ⎜. ⎟ + ⎜. ⎟ = ⎜ . ⎟
-- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟
-- > ⎜. ⎟ ⎜. ⎟ ⎜ . ⎟
-- > ⎝vₙ⎠ ⎝wₙ⎠ ⎝ vₙ*wₙ ⎠
v ^+^ w = AccVector $ A.zipWith (+) (unVector v) (unVector w)
v ^-^ w = AccVector $ A.zipWith (-) (unVector v) (unVector w)
infixl 6 ^+^
infixl 6 ^-^
(^*^) :: forall n a. (KnownNat n, IsNum a, Elt a)
=> Vector n a -> Vector n a -> Scalar a
-- | the usual vector addition/subtraction
--
-- > ⎛v₁⎞ ⎛w₁⎞
-- > ⎜v₂⎟ ⎜w₂⎟
-- > ⎜. ⎟ ⎜. ⎟
-- > ⎜. ⎟ * ⎜. ⎟ = v₁*w₁ + v₂*w₁ + … + vₙ*wₙ
-- > ⎜. ⎟ ⎜. ⎟
-- > ⎜. ⎟ ⎜. ⎟
-- > ⎝vₙ⎠ ⎝wₙ⎠
v ^*^ w = A.sum $ A.zipWith (*) (unVector v) (unVector w)
infixl 7 ^*^
(#+#), (#-#) :: forall m n a. (KnownNat m, KnownNat n, IsNum a, Elt a)
=> Matrix m n a -> Matrix m n a -> Matrix m n a
-- | the usual vector addition/subtraction
--
-- > ⎛ v₁₁ v₁₂ … v₁ₙ ⎞ ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ v₁₁+w₁₁ v₁₂+w₁₂ … v₁ₙ+w₁ₙ ⎞
-- > ⎜ v₂₁ v₂₂ … v₂ₙ ⎟ ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ v₂₁+w₂₁ v₂₂+w₂₂ … v₂ₙ+w₂ₙ ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎜ . . . ⎟ + ⎜ . . . ⎟ = ⎜ . . . ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎝ vₘ₁ vₘ₂ … vₘₙ ⎠ ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ vₘ₁+wₘ₁ wₘ₂+vₘ₂ … vₘₙ+wₘₙ ⎠
v #+# w = AccMatrix $ A.zipWith (+) (unMatrix v) (unMatrix w)
v #-# w = AccMatrix $ A.zipWith (-) (unMatrix v) (unMatrix w)
infixl 6 #+#
infixl 6 #-#
(#*#) :: forall k m n a. (KnownNat k, KnownNat m, KnownNat n, IsNum a, Elt a)
=> Matrix k m a -> Matrix m n a -> Matrix k n a
-- | the usual vector addition/subtraction
--
-- > ⎛ v₁₁ v₁₂ … v₁ₘ ⎞ ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ (v₁₁*w₁₁+v₁₂*w₂₁+…+v₁ₘ*wₘ₁) . . . (v₁₁*w₁ₙ+v₁₂*w₂ₙ+…+v₁ₘ*wₘₙ) ⎞
-- > ⎜ v₂₁ v₂₂ … v₂ₘ ⎟ ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ . . ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . ⎟
-- > ⎜ . . . ⎟ * ⎜ . . . ⎟ = ⎜ . . ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟ ⎜ . . ⎟
-- > ⎝ vₖ₁ vₖ₂ … vₖₘ ⎠ ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ (vₖ₁*w₁₁+vₖ₂*w₂₁+…+vₖₘ*wₘ₁) . . . (vₖ₁*w₁ₙ+vₖ₂*w₂ₙ+…+vₖₘ*wₘₙ) ⎠
v #*# w = AccMatrix $ A.generate (A.index2 k' n') (aux v w)
where k' = fromInteger $ natVal (Proxy :: Proxy k)
n' = fromInteger $ natVal (Proxy :: Proxy n)
aux a b sh = let (Z:.i:.j) = A.unlift sh :: (Z:.Exp Int):.Exp Int
a' = A.slice (unMatrix a) (A.lift $ Z:.i:.All)
b' = A.slice (unMatrix b) (A.lift $ Z:.All:.j)
in A.the $ A.sum $ A.zipWith (*) a' b'
infixl 7 #*#
(.*^) :: forall n a. (KnownNat n, IsNum a, Elt a)
=> Exp a -> Vector n a -> Vector n a
-- | the usual matrix-vector product
--
-- > ⎛x₁⎞ ⎛ a*x₁ ⎞
-- > ⎜x₂⎟ ⎜ a*x₂ ⎟
-- > ⎜. ⎟ ⎜ . ⎟
-- > a • ⎜. ⎟ = ⎜ . ⎟
-- > ⎜. ⎟ ⎜ . ⎟
-- > ⎜. ⎟ ⎜ . ⎟
-- > ⎝xₙ⎠ ⎝ a*xₙ ⎠
a .*^ v = let v' = unVector v
in AccVector $ A.map (* a) v'
(./^) :: forall n a. (KnownNat n, IsFloating a, Elt a)
=> Exp a -> Vector n a -> Vector n a
a ./^ v = let v' = unVector v
in AccVector $ A.map (/ a) v'
infixl 7 .*^
infixl 7 ./^
(.*#) :: forall m n a. (KnownNat m, KnownNat n, IsNum a, Elt a)
=> Exp a -> Matrix m n a -> Matrix m n a
-- | the usual matrix-vector product
--
-- > ⎛ w₁₁ w₁₂ … w₁ₙ ⎞ ⎛ a*w₁₁ a*w₁₂ … a*w₁ₙ ⎞
-- > ⎜ w₂₁ w₂₂ … w₂ₙ ⎟ ⎜ a*w₂₁ a*w₂₂ … a*w₂ₙ ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟
-- > a • ⎜ . . . ⎟ = ⎜ . . . ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎜ . . . ⎟ ⎜ . . . ⎟
-- > ⎝ wₘ₁ wₘ₂ … wₘₙ ⎠ ⎝ a*wₘ₁ a*wₘ₂ … a*wₘₙ ⎠
a .*# v = let v' = unMatrix v
in AccMatrix $ A.map (* a) v'
(./#) :: forall m n a. (KnownNat m ,KnownNat n, IsFloating a, Elt a)
=> Exp a -> Matrix m n a -> Matrix m n a
a ./# v = let v' = unMatrix v
in AccMatrix $ A.map (/ a) v'
infixl 7 .*#
infixl 7 ./#
(#**.) :: forall n a. (KnownNat n, IsNum a, Elt a)
=> Matrix n n a -> Int -> Matrix n n a
_ #**. 0 = identityMatrix
v #**. 1 = v
v #**. i | i < 0 = error $ "no negative exponents allowed in matrix exponetiation,"
++ "inverse function not yet implemented"
| otherwise = (v#**. (i-1)) #*# v
infixr 8 #**.
identityMatrix :: forall n a. (KnownNat n, IsNum a, Elt a) => Matrix n n a
identityMatrix = AccMatrix $ A.use $ A.fromFunction (Z:.n':.n') aux
where aux :: DIM2 -> a
aux (Z:.i:.j) = if i == j then 1 else 0
n' = fromInteger $ natVal (Proxy :: Proxy n)
|
epsilonhalbe/accelerate-typelits
|
bench/Data/Array/Accelerate/TypeLits.hs
|
isc
| 11,445 | 0 | 16 | 4,259 | 2,608 | 1,442 | 1,166 | 136 | 2 |
{-# LANGUAGE UnicodeSyntax #-}
module Pixs.Operations.PointOperations where
import Pixs.Information.Histogram (colorCount)
import Codec.Picture (Image, PixelRGBA8(..),
pixelAt, generateImage,
imageWidth, imageHeight)
import Pixs.Types (Color(..))
import qualified Data.Map as M
-- | Thresholds an image by pixel intensity. We define the intensity of a given
-- pixel (PixelRGBA8 r g b a)¹ to be the sum of the number of pixels with the
-- components r, g, b, and a. @threshold@ sifts out all pixels that have
-- intensity greater than the given threshold `n`. This is useful for things
-- like separating the backfground from the foreground. A complete explanation
-- of thresholding is given at:
-- http://homepages.inf.ed.ac.uk/rbf/HIPR2/threshld.htm
--
-- <<docs/example.png>> <<docs/example-thresholded.png>>
--
-- ¹: If that's not clear, I'm doing destructuring in the English language.
threshold ∷ Int → Image PixelRGBA8 → Image PixelRGBA8
threshold n img =
let black = PixelRGBA8 0 0 0 0xFF
white = PixelRGBA8 0xFF 0xFF 0xFF 0XFF
[redMap, greenMap, blueMap] = colorCount img <$> [Red, Green, Blue]
-- Dictionary meaning of "to thresh": separate grain from (a plant),
-- typically with a flail or by the action of a revolving mechanism:
-- machinery that can reap and thresh corn in the same process | (as noun
-- threshing) : farm workers started the afternoon's threshing.
thresh x y = let (PixelRGBA8 r g b _) = pixelAt img x y
(■) = zipWith id
intensity = (sum $ (M.findWithDefault 0 <$> [r, g, b])
■ [redMap, greenMap, blueMap]) `div` 3
in if (intensity > n) then black else white
in generateImage thresh (imageWidth img) (imageHeight img)
|
ayberkt/pixs
|
src/Pixs/Operations/PointOperations.hs
|
mit
| 2,041 | 0 | 20 | 638 | 316 | 184 | 132 | 19 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module LDAP.Classy.Types where
import Control.Lens
import Data.String (IsString)
import Data.Text (Text)
import Prelude (Eq, Int, Num, Show)
newtype Uid = Uid Text deriving (Show,IsString,Eq)
makeWrapped ''Uid
newtype UidNumber = UidNumber Int deriving (Show,Num,Eq)
makeWrapped ''UidNumber
newtype GidNumber = GidNumber Int deriving (Show,Num,Eq)
makeWrapped ''GidNumber
|
benkolera/haskell-ldap-classy
|
LDAP/Classy/Types.hs
|
mit
| 689 | 0 | 6 | 169 | 148 | 85 | 63 | 17 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
-- | Various utilities used in the scaffolded site.
module Yesod.Default.Util
( addStaticContentExternal
, globFile
, widgetFileNoReload
, widgetFileReload
, TemplateLanguage (..)
, defaultTemplateLanguages
, WidgetFileSettings
, wfsLanguages
, wfsHamletSettings
) where
import qualified Data.ByteString.Lazy as L
import Data.Text (Text, pack, unpack)
import Yesod.Core -- purposely using complete import so that Haddock will see addStaticContent
import Control.Monad (when, unless)
import Control.Monad.Trans.Resource (runResourceT)
import Data.Conduit (($$))
import Data.Conduit.Binary (sourceLbs, sinkFileCautious)
import System.Directory (doesFileExist, createDirectoryIfMissing)
import Language.Haskell.TH.Syntax
import Text.Lucius (luciusFile, luciusFileReload)
import Text.Julius (juliusFile, juliusFileReload)
import Text.Cassius (cassiusFile, cassiusFileReload)
import Text.Hamlet (HamletSettings, defaultHamletSettings)
import Data.Maybe (catMaybes)
import Data.Default.Class (Default (def))
-- | An implementation of 'addStaticContent' which stores the contents in an
-- external file. Files are created in the given static folder with names based
-- on a hash of their content. This allows expiration dates to be set far in
-- the future without worry of users receiving stale content.
addStaticContentExternal
:: (L.ByteString -> Either a L.ByteString) -- ^ javascript minifier
-> (L.ByteString -> String) -- ^ hash function to determine file name
-> FilePath -- ^ location of static directory. files will be placed within a "tmp" subfolder
-> ([Text] -> Route master) -- ^ route constructor, taking a list of pieces
-> Text -- ^ filename extension
-> Text -- ^ mime type
-> L.ByteString -- ^ file contents
-> HandlerT master IO (Maybe (Either Text (Route master, [(Text, Text)])))
addStaticContentExternal minify hash staticDir toRoute ext' _ content = do
liftIO $ createDirectoryIfMissing True statictmp
exists <- liftIO $ doesFileExist fn'
unless exists $
liftIO $ runResourceT $ sourceLbs content' $$ sinkFileCautious fn'
return $ Just $ Right (toRoute ["tmp", pack fn], [])
where
fn, statictmp, fn' :: FilePath
-- by basing the hash off of the un-minified content, we avoid a costly
-- minification if the file already exists
fn = hash content ++ '.' : unpack ext'
statictmp = staticDir ++ "/tmp/"
fn' = statictmp ++ fn
content' :: L.ByteString
content'
| ext' == "js" = either (const content) id $ minify content
| otherwise = content
-- | expects a file extension for each type, e.g: hamlet lucius julius
globFile :: String -> String -> FilePath
globFile kind x = "templates/" ++ x ++ "." ++ kind
data TemplateLanguage = TemplateLanguage
{ tlRequiresToWidget :: Bool
, tlExtension :: String
, tlNoReload :: FilePath -> Q Exp
, tlReload :: FilePath -> Q Exp
}
defaultTemplateLanguages :: HamletSettings -> [TemplateLanguage]
defaultTemplateLanguages hset =
[ TemplateLanguage False "hamlet" whamletFile' whamletFile'
, TemplateLanguage True "cassius" cassiusFile cassiusFileReload
, TemplateLanguage True "julius" juliusFile juliusFileReload
, TemplateLanguage True "lucius" luciusFile luciusFileReload
]
where
whamletFile' = whamletFileWithSettings hset
data WidgetFileSettings = WidgetFileSettings
{ wfsLanguages :: HamletSettings -> [TemplateLanguage]
, wfsHamletSettings :: HamletSettings
}
instance Default WidgetFileSettings where
def = WidgetFileSettings defaultTemplateLanguages defaultHamletSettings
widgetFileNoReload :: WidgetFileSettings -> FilePath -> Q Exp
widgetFileNoReload wfs x = combine "widgetFileNoReload" x False $ wfsLanguages wfs $ wfsHamletSettings wfs
widgetFileReload :: WidgetFileSettings -> FilePath -> Q Exp
widgetFileReload wfs x = combine "widgetFileReload" x True $ wfsLanguages wfs $ wfsHamletSettings wfs
combine :: String -> String -> Bool -> [TemplateLanguage] -> Q Exp
combine func file isReload tls = do
mexps <- qmexps
case catMaybes mexps of
[] -> error $ concat
[ "Called "
, func
, " on "
, show file
, ", but no templates were found."
]
exps -> return $ DoE $ map NoBindS exps
where
qmexps :: Q [Maybe Exp]
qmexps = mapM go tls
go :: TemplateLanguage -> Q (Maybe Exp)
go tl = whenExists file (tlRequiresToWidget tl) (tlExtension tl) ((if isReload then tlReload else tlNoReload) tl)
whenExists :: String
-> Bool -- ^ requires toWidget wrap
-> String -> (FilePath -> Q Exp) -> Q (Maybe Exp)
whenExists = warnUnlessExists False
warnUnlessExists :: Bool
-> String
-> Bool -- ^ requires toWidget wrap
-> String -> (FilePath -> Q Exp) -> Q (Maybe Exp)
warnUnlessExists shouldWarn x wrap glob f = do
let fn = globFile glob x
e <- qRunIO $ doesFileExist fn
when (shouldWarn && not e) $ qRunIO $ putStrLn $ "widget file not found: " ++ fn
if e
then do
ex <- f fn
if wrap
then do
tw <- [|toWidget|]
return $ Just $ tw `AppE` ex
else return $ Just ex
else return Nothing
|
tolysz/yesod
|
yesod/Yesod/Default/Util.hs
|
mit
| 5,460 | 0 | 19 | 1,274 | 1,293 | 693 | 600 | 110 | 3 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, CPP, DeriveDataTypeable, FlexibleContexts, GeneralizedNewtypeDeriving, MultiParamTypeClasses, TemplateHaskell, TypeFamilies, RecordWildCards #-}
import Control.Applicative ((<$>), optional)
import Control.Exception ( bracket )
import Control.Monad ( msum, forM_, mapM_ )
import Control.Monad.Reader ( ask )
import Control.Monad.State ( get, put )
import Data.Data ( Data, Typeable )
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text.Lazy (unpack)
import Happstack.Server (Response, ServerPart, dir, nullDir, nullConf, ok, simpleHTTP, toResponse, Method(..), method, seeOther, look, lookText, decodeBody, BodyPolicy, defaultBodyPolicy )
import Data.Acid ( AcidState, Query, Update
, makeAcidic, openLocalState )
import Data.Acid.Advanced ( query', update' )
import Data.Acid.Local ( createCheckpointAndClose )
import Data.SafeCopy ( base, deriveSafeCopy, SafeCopy )
import Text.Blaze.Html5 (Html, (!), a, form, input, p, toHtml, label)
import Text.Blaze.Html5.Attributes (action, enctype, href, name, size, type_, value)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Data.IxSet ( Indexable(..), IxSet(..), (@=)
, Proxy(..), getOne, ixFun, ixSet, toList, insert )
-- types for characters
newtype CharacterId = CharacterId { unCharacterId :: Integer }
deriving (Eq, Ord, Read, Show, Data, Enum, Typeable, SafeCopy)
type Initiative = (Integer, Integer) -- base and num of dice
data Character = Character {
charId :: CharacterId,
charName :: String,
charInitiative :: Maybe Initiative
} deriving (Eq, Ord, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''Character)
instance Indexable Character where
empty = ixSet
[ ixFun $ \bp -> [charId bp]
]
-- global app state
data AppState = AppState {
stateNextCharId :: Integer,
stateCharacters :: IxSet Character
} deriving (Eq, Ord, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''AppState)
initialAppState :: AppState
initialAppState = AppState 1 empty
-- state manipulation
peekCharacters :: Query AppState [Character]
peekCharacters = do
AppState{..} <- ask
return $ toList stateCharacters
addCharacter :: Character -> Update AppState [Character]
addCharacter c = do
a@AppState{..} <- get
let newChars = insert (c { charId = CharacterId stateNextCharId }) stateCharacters
let newNextId = stateNextCharId + 1
put $ a { stateCharacters = newChars, stateNextCharId = newNextId }
return $ toList newChars
$(makeAcidic ''AppState [ 'peekCharacters, 'addCharacter ])
-- web templates
templateCharacters :: [Character] -> ServerPart Response
templateCharacters cs =
ok $ template "characters" $ do
H.h1 "Characters"
H.table $ forM_ cs (\c ->
H.tr $ do
H.td $ (toHtml (unCharacterId $ charId c))
H.td $ (toHtml (charName c))
H.td $ (toHtml (show (charInitiative c)))
)
H.form ! action "/char" ! enctype "multipart/form-data" ! A.method "POST" $ do
label ! A.for "msg" $ "enter new name"
input ! type_ "text" ! A.id "name" ! name "name"
input ! type_ "submit" ! value "add character"
myPolicy :: BodyPolicy
myPolicy = (defaultBodyPolicy "/tmp/" 0 1000 1000)
handlers :: AcidState AppState -> ServerPart Response
handlers acid = do
decodeBody myPolicy
msum
[ dir "char" $ do
method GET
cs <- query' acid PeekCharacters
templateCharacters cs
, dir "char" $ do
method POST
name <- look "name"
-- decodeBody
c <- update' acid (AddCharacter (Character (CharacterId 0) name Nothing))
seeOther ("/char" :: String) (toResponse ())
, homePage
]
main :: IO ()
main =
bracket (openLocalState initialAppState)
(createCheckpointAndClose)
(\acid ->
simpleHTTP nullConf (handlers acid))
template :: Text -> Html -> Response
template title body = toResponse $
H.html $ do
H.head $ do
H.title (toHtml title)
H.body $ do
body
p $ a ! href "/" $ "back home"
homePage :: ServerPart Response
homePage =
ok $ template "home page" $ do
H.h1 "Hello!"
|
jpschaumloeffel/sr5gm
|
sr5gm/sr5gm.hs
|
mit
| 4,167 | 37 | 21 | 819 | 1,395 | 757 | 638 | 100 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Hash.MD5
import qualified Database.Redis as R
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Web.Scotty
import Network.HTTP.Types
import Control.Monad.Trans (liftIO)
import qualified Data.Text.Lazy.Encoding as TL
import Data.Tuple (swap)
import Data.List (unfoldr)
shorten :: String -> Int -> String
shorten = shorten' (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'])
shorten' :: String -> String -> Int -> String
shorten' charset url len = toCharset charset (convertToBase urlhash ((fromIntegral . length) charset))
where
urlhash = md5i (Str url) `mod` (fromIntegral (length charset) ^ len)
toCharset :: Integral a => String -> [a] -> String
toCharset ch = map ((ch!!) . fromIntegral)
convertToBase :: Integral a => a -> a -> [a]
convertToBase n b = unfoldr (tomb . swap . (`divMod` b)) n
where tomb x@(0, 0) = Nothing
tomb x = Just x
-- convertToBase n b = map snd $ takeWhile (\(a, b) -> a /= 0 || b /= 0) h
-- where h = divMod n b : map (\(a, _) -> divMod a b) h
addUrl :: String -> IO (Maybe String)
addUrl url = do conn <- R.connect R.defaultConnectInfo
R.runRedis conn $ do
u <- R.get (B.pack shortUrl)
case u of
Right Nothing -> do R.set (B.pack shortUrl) (B.pack url)
return (Just shortUrl)
Right (Just a) -> if a == B.pack url
then return (Just shortUrl)
else return Nothing
otherwise -> return Nothing
where shortUrl = shorten url 3
runServer :: IO ()
runServer = scotty 3000 $ do
get "/:short" $ do
short <- param "short"
con <- liftIO $ R.connect R.defaultConnectInfo
u <- liftIO $ R.runRedis con (R.get short)
case u of
Right (Just url) -> redirect (TL.decodeUtf8 (BL.fromStrict url))
otherwise -> do liftIO $ putStrLn "not found"
status status404
html "404 - not found"
|
EDmitry/shortener-hs
|
shortener.hs
|
mit
| 2,150 | 0 | 19 | 669 | 707 | 363 | 344 | 45 | 4 |
import Control.Monad.Reader
data Expr
= Val Int
| Add Expr Expr
| Var String
deriving (Show)
type Env = [(String, Int)]
type Eval a = ReaderT Env Maybe a
eval :: Expr -> Eval Int
eval (Val n) = return n
eval (Add x y) = liftM2 (+) (eval x) (eval y)
eval (Var x) = do
env <- ask
val <- lift (lookup x env)
return val
ex :: Eval Int
ex = eval (Add (Val 2) (Add (Val 1) (Var "x")))
env :: Env
env = [("x", 2), ("y", 5)]
example1, example2 :: Maybe Int
example1 = runReaderT ex env
example2 = runReaderT ex []
|
riwsky/wiwinwlh
|
src/transformer.hs
|
mit
| 527 | 4 | 11 | 128 | 300 | 152 | 148 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Time.Calendar.BankHolidaySpec (spec) where
import Data.Time
import Data.Time.Calendar.BankHoliday (isWeekday, isWeekend)
import Test.Hspec
spec :: Spec
spec = do
describe "isWeekday" $ do
it "is accurate" $ do
all (\d -> isWeekday d) [
(fromGregorian 1987 1 1)
, (fromGregorian 1999 5 3)
, (fromGregorian 1999 11 19)
, (fromGregorian 2014 7 4)
, (fromGregorian 2015 11 4)
, (fromGregorian 2015 12 16)
, (fromGregorian 2016 1 1)
]
describe "isWeekend" $ do
it "is accurate" $ do
all (\d -> isWeekend d) [
(fromGregorian 1987 1 10)
, (fromGregorian 1999 11 20)
, (fromGregorian 2015 11 15)
, (fromGregorian 2015 12 12)
, (fromGregorian 2015 7 4)
, (fromGregorian 2015 12 13)
, (fromGregorian 2015 11 14)
]
|
tippenein/BankHoliday
|
test/Data/Time/Calendar/BankHolidaySpec.hs
|
mit
| 911 | 0 | 16 | 282 | 309 | 164 | 145 | 27 | 1 |
module Aldus.Types where
|
lgastako/aldus
|
src/Aldus/Types.hs
|
mit
| 26 | 0 | 3 | 4 | 6 | 4 | 2 | 1 | 0 |
module Net.TFTP_Client(tftpGet,tftpPut) where
-- TFTP Client, protocol described in RFC 1350
-- See http://www.networksorcery.com/enp/rfc/rfc1350.txt
import Net.Concurrent
import Net.UDP_Client as UDP(Packet(..),template,listenAny,unlisten)
import qualified Net.PortNumber as Port
import Net.TFTP
import qualified Net.Interface as Net
import Net.Packet(listArray)
import Net.PacketParsing(doUnparse,doParse)
import Net.Utils(arraySize)
--import Monad.Util(whileM)
tftpGet debug udp serverIP filename mode =
do (tftp,close) <- initialize udp serverIP
result <- getBlocks tftp [] 0
close
return result
where
rrq = RRQ filename mode
getBlocks tftp bs last =
do p <- txRetry tftp (if last==0 then rrq else Ack last)
case p of
Nothing -> return $ Left "Timeout"
Just (Data nr b) ->
if nr==last+1
then if arraySize b<512
then do Net.txT tftp (Ack nr)
return (Right (reverse (b:bs)))
else getBlocks tftp (b:bs) nr
else if nr==last
then getBlocks tftp bs last -- ignore dupl
else return (Left "unexpected data block")
Just (Error c msg) ->
return $ Left $ "Server said: "++show c++" "++msg
Just msg -> return $ Left $ "Unexpected packet: "++show msg
tftpPut debug udp serverIP filename mode contents =
do (tftp,close) <- initialize udp serverIP
result <- putBlocks tftp (blocks contents) (WRQ filename mode) 0
close
return result
where
putBlocks tftp bs packet current =
do --debug $ "tftpPut send "++show packet
p <- txRetry tftp packet
--debug $ "tftpPut receive "++show p
case p of
Nothing -> return $ Left "Timeout"
Just (Ack nr) ->
if nr==current
then case bs of
[] -> return (Right ())
b:bs -> putBlocks tftp bs (Data nr b) nr
where nr=current+1
else if nr==current-1
then putBlocks tftp bs packet current -- hmm, ignore dupl
else return (Left "unexpected ack")
Just (Error c msg) ->
return $ Left $ "Server said: "++show c++" "++msg
Just msg -> return $ Left $ "Unexpected packet: "++show msg
blocks :: String -> [Data]
blocks s =
case splitAt 512 s of
([],_) -> []
(s1,s2) -> listArray (1,length s1) (conv s1):blocks s2
where
conv = map (fromIntegral.fromEnum)
txRetry tftp packet = rx 2
where
rx n =
do Net.txT tftp packet
maybe retry (return . Just) =<< Net.rxT tftp (Just t)
where
retry = if n>0 then rx (n-1) else return Nothing
t = 2000000 -- microseconds
{-
txRetry tftp packet = rx 2
where
rx n =
do waiting <- newRef True
fork $ whileM (readRef waiting) $ Net.tx tftp packet >> delay t
p <- Net.rx tftp
writeRef waiting False
return (Just p)
where
t = 2000000 -- microseconds
-}
initialize udp serverIP =
do (port,uclient) <- UDP.listenAny udp
portM <- newMVar Nothing
let rx t =
do r <- Net.rxT uclient t
case r of
Nothing -> return Nothing
Just (fromIP,udpP) ->
let sPort = sourcePort udpP in
case doParse (content udpP) of
Nothing -> rx t -- reduce t!!
Just p -> if fromIP==serverIP -- also check port number
then do optsp <- takeMVar portM
case optsp of
Nothing ->
do putMVar portM (Just sPort)
return (Just p)
Just port ->
do putMVar portM optsp
if port==sPort
then return (Just p)
else rx t -- wrong port!
else rx t
tx msg =
-- The initial request is sent to serverPort. After that,
-- messages are sent to the port chosen by the server.
do sPort <- maybe serverPort id `fmap` readMVar portM
Net.txT uclient (serverIP,udpP sPort)
where
udpP sPort = UDP.template port sPort bs
bs = doUnparse msg
return (Net.TimedInterface rx tx,unlisten udp port)
serverPort = Port.tftp -- standard TFTP server port
|
nh2/network-house
|
Net/TFTP_Client.hs
|
gpl-2.0
| 4,050 | 67 | 20 | 1,208 | 1,072 | 591 | 481 | 95 | 8 |
{-# LANGUAGE TypeSynonymInstances #-}
{- |
Module : $Header$
Description : Abstract syntax for common logic
Copyright : (c) Karl Luc, DFKI Bremen 2010, Eugen Kuksa and Uni Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Definition of abstract syntax for common logic
-}
{-
Ref.
ISO/IEC IS 24707:2007(E)
-}
module CommonLogic.AS_CommonLogic where
import Common.Id as Id
import Common.IRI
import Common.Doc
import Common.DocUtils
import Common.Keywords
import qualified Common.AS_Annotation as AS_Anno
import Data.Set (Set)
-- DrIFT command
{-! global: GetRange !-}
newtype BASIC_SPEC = Basic_spec [AS_Anno.Annoted BASIC_ITEMS]
deriving (Show, Ord, Eq)
data BASIC_ITEMS = Axiom_items [AS_Anno.Annoted TEXT_META]
deriving (Show, Ord, Eq)
type PrefixMapping = (String, IRI)
emptyTextMeta :: TEXT_META
emptyTextMeta = Text_meta { getText = Text [] nullRange
, textIri = Nothing
, nondiscourseNames = Nothing
, prefix_map = [] }
data TEXT_META = Text_meta { getText :: TEXT
, textIri :: Maybe IRI
, nondiscourseNames :: Maybe (Set NAME)
, prefix_map :: [PrefixMapping]
} deriving (Show, Ord, Eq)
-- TODO: check static analysis and other features on discourse names, as soon as parsers of segregated dialects are implemented
-- Common Logic Syntax
data TEXT = Text [PHRASE] Id.Range
| Named_text NAME TEXT Id.Range
deriving (Show, Ord, Eq)
data PHRASE = Module MODULE
| Sentence SENTENCE
| Importation IMPORTATION
| Comment_text COMMENT TEXT Id.Range
deriving (Show, Ord, Eq)
data COMMENT = Comment String Id.Range
deriving (Show, Ord, Eq)
data MODULE = Mod NAME TEXT Id.Range
| Mod_ex NAME [NAME] TEXT Id.Range
deriving (Show, Ord, Eq)
data IMPORTATION = Imp_name NAME
deriving (Show, Ord, Eq)
data SENTENCE = Quant_sent QUANT_SENT Id.Range
| Bool_sent BOOL_SENT Id.Range
| Atom_sent ATOM Id.Range
| Comment_sent COMMENT SENTENCE Id.Range
| Irregular_sent SENTENCE Id.Range
deriving (Show, Ord, Eq)
data QUANT_SENT = Universal [NAME_OR_SEQMARK] SENTENCE
| Existential [NAME_OR_SEQMARK] SENTENCE
deriving (Show, Ord, Eq)
data BOOL_SENT = Conjunction [SENTENCE]
| Disjunction [SENTENCE]
| Negation SENTENCE
| Implication SENTENCE SENTENCE
| Biconditional SENTENCE SENTENCE
deriving (Show, Ord, Eq)
data ATOM = Equation TERM TERM
| Atom TERM [TERM_SEQ]
deriving (Show, Ord, Eq)
data TERM = Name_term NAME
| Funct_term TERM [TERM_SEQ] Id.Range
| Comment_term TERM COMMENT Id.Range
deriving (Show, Ord, Eq)
data TERM_SEQ = Term_seq TERM
| Seq_marks SEQ_MARK
deriving (Show, Ord, Eq)
type NAME = Id.Token
type SEQ_MARK = Id.Token
-- binding seq
data NAME_OR_SEQMARK = Name NAME
| SeqMark SEQ_MARK
deriving (Show, Eq, Ord)
data SYMB_MAP_ITEMS = Symb_map_items [SYMB_OR_MAP] Id.Range
deriving (Show, Ord, Eq)
data SYMB_OR_MAP = Symb NAME_OR_SEQMARK
| Symb_mapN NAME NAME Id.Range
| Symb_mapS SEQ_MARK SEQ_MARK Id.Range
deriving (Show, Ord, Eq)
data SYMB_ITEMS = Symb_items [NAME_OR_SEQMARK] Id.Range
-- pos: SYMB_KIND, commas
deriving (Show, Ord, Eq)
-- pretty printing using CLIF
instance Pretty BASIC_SPEC where
pretty = printBasicSpec
instance Pretty BASIC_ITEMS where
pretty = printBasicItems
instance Pretty TEXT_META where
pretty = printTextMeta
instance Pretty TEXT where
pretty = printText
instance Pretty PHRASE where
pretty = printPhrase
instance Pretty MODULE where
pretty = printModule
instance Pretty IMPORTATION where
pretty = printImportation
instance Pretty SENTENCE where
pretty = printSentence
instance Pretty BOOL_SENT where
pretty = printBoolSent
instance Pretty QUANT_SENT where
pretty = printQuantSent
instance Pretty ATOM where
pretty = printAtom
instance Pretty TERM where
pretty = printTerm
instance Pretty TERM_SEQ where
pretty = printTermSeq
instance Pretty COMMENT where
pretty = printComment
instance Pretty NAME_OR_SEQMARK where
pretty = printNameOrSeqMark
instance Pretty SYMB_OR_MAP where
pretty = printSymbOrMap
instance Pretty SYMB_MAP_ITEMS where
pretty = printSymbMapItems
instance Pretty SYMB_ITEMS where
pretty = printSymbItems
printBasicSpec :: BASIC_SPEC -> Doc
printBasicSpec (Basic_spec xs) = vcat $ map pretty xs
printBasicItems :: BASIC_ITEMS -> Doc
printBasicItems (Axiom_items xs) = vcat $ map pretty xs
printTextMeta :: TEXT_META -> Doc
printTextMeta tm = pretty $ getText tm
-- print basic spec as pure clif-texts, without any annotations
exportCLIF :: [AS_Anno.Named TEXT_META] -> Doc
exportCLIF xs = vsep $ map (exportTextMeta . AS_Anno.sentence) xs
exportBasicSpec :: BASIC_SPEC -> Doc
exportBasicSpec (Basic_spec xs) = vsep $ map (exportBasicItems . AS_Anno.item) xs
exportBasicItems :: BASIC_ITEMS -> Doc
exportBasicItems (Axiom_items xs) = vsep $ map (exportTextMeta . AS_Anno.item) xs
exportTextMeta :: TEXT_META -> Doc
exportTextMeta = pretty . getText
-- using pure clif syntax from here
printText :: TEXT -> Doc
printText s = case s of
Text x _ -> fsep $ map pretty x
Named_text x y _ -> parens $ text clTextS <+> pretty x <+> pretty y
printPhrase :: PHRASE -> Doc
printPhrase s = case s of
Module x -> parens $ text clModuleS <+> pretty x
Sentence x -> pretty x
Importation x -> parens $ text clImportS <+> pretty x
Comment_text x y _ -> parens $ text clCommentS <+> pretty x <+> pretty y
printModule :: MODULE -> Doc
printModule (Mod x z _) = pretty x <+> pretty z
printModule (Mod_ex x y z _) =
pretty x <+> parens (text clExcludeS <+> fsep (map pretty y)) <+> pretty z
printImportation :: IMPORTATION -> Doc
printImportation (Imp_name x) = pretty x
printSentence :: SENTENCE -> Doc
printSentence s = case s of
Quant_sent xs _ -> parens $ pretty xs
Bool_sent xs _ -> parens $ pretty xs
Atom_sent xs _ -> pretty xs
Comment_sent x y _ -> parens $ text clCommentS <+> pretty x <+> pretty y
Irregular_sent xs _ -> parens $ pretty xs
printComment :: COMMENT -> Doc
printComment s = case s of
Comment x _ -> text x
printQuantSent :: QUANT_SENT -> Doc
printQuantSent s = case s of
Universal x y -> text forallS <+> parens (sep $ map pretty x) <+> pretty y
Existential x y -> text existsS <+> parens (sep $ map pretty x) <+> pretty y
printBoolSent :: BOOL_SENT -> Doc
printBoolSent s = case s of
Conjunction xs -> text andS <+> fsep (map pretty xs)
Disjunction xs -> text orS <+> fsep (map pretty xs)
Negation xs -> text notS <+> pretty xs
Implication x y -> text ifS <+> pretty x <+> pretty y
Biconditional x y -> text iffS <+> pretty x <+> pretty y
printAtom :: ATOM -> Doc
printAtom s = case s of
Equation a b -> parens $ equals <+> pretty a <+> pretty b
Atom t ts -> parens $ pretty t <+> sep (map pretty ts)
printTerm :: TERM -> Doc
printTerm s = case s of
Name_term a -> pretty a
Funct_term t ts _ -> parens $ pretty t <+> fsep (map pretty ts)
Comment_term t c _ -> parens $ text clCommentS <+> pretty c <+> pretty t
printTermSeq :: TERM_SEQ -> Doc
printTermSeq s = case s of
Term_seq t -> pretty t
Seq_marks m -> pretty m
-- Binding Seq
printNameOrSeqMark :: NAME_OR_SEQMARK -> Doc
printNameOrSeqMark s = case s of
Name x -> pretty x
SeqMark x -> pretty x
-- Alt x y -> pretty x <+> pretty y
printSymbOrMap :: SYMB_OR_MAP -> Doc
printSymbOrMap (Symb nos) = pretty nos
printSymbOrMap (Symb_mapN source dest _) =
pretty source <+> mapsto <+> pretty dest <> space
printSymbOrMap (Symb_mapS source dest _) =
pretty source <+> mapsto <+> pretty dest <> space -- space needed. without space the comma (from printSymbMapItems) would be part of the name @dest@
printSymbMapItems :: SYMB_MAP_ITEMS -> Doc
printSymbMapItems (Symb_map_items xs _) = ppWithCommas xs
printSymbItems :: SYMB_ITEMS -> Doc
printSymbItems (Symb_items xs _) = fsep $ map pretty xs
-- keywords, reservednames in CLIF
orS :: String
orS = "or"
iffS :: String
iffS = "iff"
clCommentS :: String
clCommentS = "cl-comment"
clTextS :: String
clTextS = "cl-text"
clImportS :: String
clImportS = "cl-imports"
clModuleS :: String
clModuleS = "cl-module"
clExcludeS :: String
clExcludeS = "cl-excludes"
-- Generated by DrIFT, look but don't touch!
instance GetRange BASIC_SPEC where
getRange = const nullRange
rangeSpan x = case x of
Basic_spec a -> joinRanges [rangeSpan a]
instance GetRange BASIC_ITEMS where
getRange = const nullRange
rangeSpan x = case x of
Axiom_items a -> joinRanges [rangeSpan a]
instance GetRange TEXT_META where
getRange = const nullRange
rangeSpan x = case x of
Text_meta a b c d -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c, rangeSpan d]
instance GetRange TEXT where
getRange = const nullRange
rangeSpan x = case x of
Text a b -> joinRanges [rangeSpan a, rangeSpan b]
Named_text a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
instance GetRange PHRASE where
getRange = const nullRange
rangeSpan x = case x of
Module a -> joinRanges [rangeSpan a]
Sentence a -> joinRanges [rangeSpan a]
Importation a -> joinRanges [rangeSpan a]
Comment_text a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
instance GetRange COMMENT where
getRange = const nullRange
rangeSpan x = case x of
Comment a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange MODULE where
getRange = const nullRange
rangeSpan x = case x of
Mod a b c -> joinRanges [rangeSpan a, rangeSpan b, rangeSpan c]
Mod_ex a b c d -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c, rangeSpan d]
instance GetRange IMPORTATION where
getRange = const nullRange
rangeSpan x = case x of
Imp_name a -> joinRanges [rangeSpan a]
instance GetRange SENTENCE where
getRange = const nullRange
rangeSpan x = case x of
Quant_sent a b -> joinRanges [rangeSpan a, rangeSpan b]
Bool_sent a b -> joinRanges [rangeSpan a, rangeSpan b]
Atom_sent a b -> joinRanges [rangeSpan a, rangeSpan b]
Comment_sent a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
Irregular_sent a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange QUANT_SENT where
getRange = const nullRange
rangeSpan x = case x of
Universal a b -> joinRanges [rangeSpan a, rangeSpan b]
Existential a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange BOOL_SENT where
getRange = const nullRange
rangeSpan x = case x of
Conjunction a -> joinRanges [rangeSpan a]
Disjunction a -> joinRanges [rangeSpan a]
Negation a -> joinRanges [rangeSpan a]
Implication a b -> joinRanges [rangeSpan a, rangeSpan b]
Biconditional a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange ATOM where
getRange = const nullRange
rangeSpan x = case x of
Equation a b -> joinRanges [rangeSpan a, rangeSpan b]
Atom a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange TERM where
getRange = const nullRange
rangeSpan x = case x of
Name_term a -> joinRanges [rangeSpan a]
Funct_term a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
Comment_term a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
instance GetRange TERM_SEQ where
getRange = const nullRange
rangeSpan x = case x of
Term_seq a -> joinRanges [rangeSpan a]
Seq_marks a -> joinRanges [rangeSpan a]
instance GetRange NAME_OR_SEQMARK where
getRange = const nullRange
rangeSpan x = case x of
Name a -> joinRanges [rangeSpan a]
SeqMark a -> joinRanges [rangeSpan a]
instance GetRange SYMB_MAP_ITEMS where
getRange = const nullRange
rangeSpan x = case x of
Symb_map_items a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange SYMB_OR_MAP where
getRange = const nullRange
rangeSpan x = case x of
Symb a -> joinRanges [rangeSpan a]
Symb_mapN a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
Symb_mapS a b c -> joinRanges [rangeSpan a, rangeSpan b,
rangeSpan c]
instance GetRange SYMB_ITEMS where
getRange = const nullRange
rangeSpan x = case x of
Symb_items a b -> joinRanges [rangeSpan a, rangeSpan b]
|
nevrenato/Hets_Fork
|
CommonLogic/AS_CommonLogic.hs
|
gpl-2.0
| 13,154 | 0 | 13 | 3,451 | 4,044 | 2,024 | 2,020 | 307 | 5 |
{-# LANGUAGE OverloadedStrings, CPP, ScopedTypeVariables #-}
{-
Copyright (C) 2012-2015 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.PDF
Copyright : Copyright (C) 2012-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of LaTeX documents to PDF.
-}
module Text.Pandoc.PDF ( makePDF ) where
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as BC
import qualified Data.ByteString as BS
import System.Exit (ExitCode (..))
import System.FilePath
import System.IO (stderr, stdout)
import System.Directory
import Data.Digest.Pure.SHA (showDigest, sha1)
import System.Environment
import Control.Monad (unless, when, (<=<))
import qualified Control.Exception as E
import Control.Applicative ((<$))
import Data.List (isInfixOf)
import Data.Maybe (fromMaybe)
import qualified Text.Pandoc.UTF8 as UTF8
import Text.Pandoc.Definition
import Text.Pandoc.Walk (walkM)
import Text.Pandoc.Shared (fetchItem', warn, withTempDir)
import Text.Pandoc.Options (WriterOptions(..))
import Text.Pandoc.MIME (extensionFromMimeType, getMimeType)
import Text.Pandoc.Process (pipeProcess)
import qualified Data.ByteString.Lazy as BL
import qualified Codec.Picture as JP
import qualified Graphics.Rasterific.Svg as RS
import qualified Graphics.Svg as Svg
#ifdef _WINDOWS
import Data.List (intercalate)
#endif
#ifdef _WINDOWS
changePathSeparators :: FilePath -> FilePath
changePathSeparators = intercalate "/" . splitDirectories
#endif
makePDF :: String -- ^ pdf creator (pdflatex, lualatex, xelatex)
-> (WriterOptions -> Pandoc -> String) -- ^ writer
-> WriterOptions -- ^ options
-> Pandoc -- ^ document
-> IO (Either ByteString ByteString)
makePDF program writer opts doc = withTempDir "tex2pdf." $ \tmpdir -> do
doc' <- handleImages opts tmpdir doc
let source = writer opts doc'
args = writerLaTeXArgs opts
tex2pdf' (writerVerbose opts) args tmpdir program source
handleImages :: WriterOptions
-> FilePath -- ^ temp dir to store images
-> Pandoc -- ^ document
-> IO Pandoc
handleImages opts tmpdir = walkM (convertImages tmpdir) <=< walkM (handleImage' opts tmpdir)
handleImage' :: WriterOptions
-> FilePath
-> Inline
-> IO Inline
handleImage' opts tmpdir (Image ils (src,tit)) = do
exists <- doesFileExist src
if exists
then return $ Image ils (src,tit)
else do
res <- fetchItem' (writerMediaBag opts) (writerSourceURL opts) src
case res of
Right (contents, Just mime) -> do
let ext = fromMaybe (takeExtension src) $
extensionFromMimeType mime
let basename = showDigest $ sha1 $ BL.fromChunks [contents]
let fname = tmpdir </> basename <.> ext
BS.writeFile fname contents
return $ Image ils (fname,tit)
_ -> do
warn $ "Could not find image `" ++ src ++ "', skipping..."
return $ Image ils (src,tit)
handleImage' _ _ x = return x
convertImages :: FilePath -> Inline -> IO Inline
convertImages tmpdir (Image ils (src, tit)) = do
img <- convertImage tmpdir src
newPath <-
case img of
Left e -> src <$ warn e
Right fp -> return fp
return (Image ils (newPath, tit))
convertImages _ x = return x
-- Convert formats which do not work well in pdf to png
convertImage :: FilePath -> FilePath -> IO (Either String FilePath)
convertImage tmpdir fname =
case mime of
Just "image/png" -> doNothing
Just "image/jpeg" -> doNothing
Just "application/pdf" -> doNothing
Just "image/svg+xml" -> renderSvgToPdf tmpdir fname
_ -> JP.readImage fname >>= \res ->
case res of
Left _ -> return $ Left $ "Unable to convert `" ++
fname ++ "' for use with pdflatex."
Right img ->
E.catch (Right fileOut <$ JP.savePngImage fileOut img) $
\(e :: E.SomeException) -> return (Left (show e))
where
fileOut = replaceDirectory (replaceExtension fname (".png")) tmpdir
mime = getMimeType fname
doNothing = return (Right fname)
renderSvgToPdf :: FilePath -> FilePath -> IO (Either String FilePath)
renderSvgToPdf tmpdir fname = do
fontCache <- RS.loadCreateFontCache $ tmpdir </> "pandoc-font-cache"
maySvg <- Svg.loadSvgFile fname
case maySvg of
Nothing -> return $ Left "Can't load SVG file"
Just svg -> do
(pdf, _) <- RS.pdfOfSvgDocument fontCache Nothing 96 svg
let fileOut =
replaceDirectory (replaceExtension fname ".pdf") tmpdir
BL.writeFile fileOut pdf
return $ Right fileOut
tex2pdf' :: Bool -- ^ Verbose output
-> [String] -- ^ Arguments to the latex-engine
-> FilePath -- ^ temp directory for output
-> String -- ^ tex program
-> String -- ^ tex source
-> IO (Either ByteString ByteString)
tex2pdf' verbose args tmpDir program source = do
let numruns = if "\\tableofcontents" `isInfixOf` source
then 3 -- to get page numbers
else 2 -- 1 run won't give you PDF bookmarks
(exit, log', mbPdf) <- runTeXProgram verbose program args 1 numruns tmpDir source
case (exit, mbPdf) of
(ExitFailure _, _) -> do
let logmsg = extractMsg log'
let extramsg =
case logmsg of
x | ("! Package inputenc Error" `BC.isPrefixOf` x
&& program /= "xelatex")
-> "\nTry running pandoc with --latex-engine=xelatex."
_ -> ""
return $ Left $ logmsg <> extramsg
(ExitSuccess, Nothing) -> return $ Left ""
(ExitSuccess, Just pdf) -> return $ Right pdf
(<>) :: ByteString -> ByteString -> ByteString
(<>) = B.append
-- parsing output
extractMsg :: ByteString -> ByteString
extractMsg log' = do
let msg' = dropWhile (not . ("!" `BC.isPrefixOf`)) $ BC.lines log'
let (msg'',rest) = break ("l." `BC.isPrefixOf`) msg'
let lineno = take 1 rest
if null msg'
then log'
else BC.unlines (msg'' ++ lineno)
-- running tex programs
-- Run a TeX program on an input bytestring and return (exit code,
-- contents of stdout, contents of produced PDF if any). Rerun
-- a fixed number of times to resolve references.
runTeXProgram :: Bool -> String -> [String] -> Int -> Int -> FilePath -> String
-> IO (ExitCode, ByteString, Maybe ByteString)
runTeXProgram verbose program args runNumber numRuns tmpDir source = do
let file = tmpDir </> "input.tex"
exists <- doesFileExist file
unless exists $ UTF8.writeFile file source
#ifdef _WINDOWS
-- note: we want / even on Windows, for TexLive
let tmpDir' = changePathSeparators tmpDir
let file' = changePathSeparators file
#else
let tmpDir' = tmpDir
let file' = file
#endif
let programArgs = ["-halt-on-error", "-interaction", "nonstopmode",
"-output-directory", tmpDir'] ++ args ++ [file']
env' <- getEnvironment
let sep = searchPathSeparator:[]
let texinputs = maybe (tmpDir' ++ sep) ((tmpDir' ++ sep) ++)
$ lookup "TEXINPUTS" env'
let env'' = ("TEXINPUTS", texinputs) :
[(k,v) | (k,v) <- env', k /= "TEXINPUTS"]
when (verbose && runNumber == 1) $ do
putStrLn $ "[makePDF] temp dir:"
putStrLn tmpDir'
putStrLn $ "[makePDF] Command line:"
putStrLn $ program ++ " " ++ unwords (map show programArgs)
putStr "\n"
putStrLn $ "[makePDF] Environment:"
mapM_ print env''
putStr "\n"
putStrLn $ "[makePDF] Contents of " ++ file' ++ ":"
B.readFile file' >>= B.putStr
putStr "\n"
(exit, out, err) <- pipeProcess (Just env'') program programArgs BL.empty
when verbose $ do
putStrLn $ "[makePDF] Run #" ++ show runNumber
B.hPutStr stdout out
B.hPutStr stderr err
putStr "\n"
if runNumber <= numRuns
then runTeXProgram verbose program args (runNumber + 1) numRuns tmpDir source
else do
let pdfFile = replaceDirectory (replaceExtension file ".pdf") tmpDir
pdfExists <- doesFileExist pdfFile
pdf <- if pdfExists
-- We read PDF as a strict bytestring to make sure that the
-- temp directory is removed on Windows.
-- See https://github.com/jgm/pandoc/issues/1192.
then (Just . B.fromChunks . (:[])) `fmap` BS.readFile pdfFile
else return Nothing
return (exit, out <> err, pdf)
|
Twinside/pandoc
|
src/Text/Pandoc/PDF.hs
|
gpl-2.0
| 9,647 | 0 | 24 | 2,623 | 2,358 | 1,222 | 1,136 | 179 | 6 |
module GRPSafety
( isSafe
, getSafeLines
, getSafetyPrefix
, dropSafetyPrefix
) where
import Data.List (isInfixOf)
import Data.Maybe
import Debug.Trace
--This Module deals with the safety prefix of genomes
-- (The source code up to "safeLines = n", designed to prevent careless change to the Genome's boilerplate)
--as well as various other safety criteria of the Genome
--NB: The safety prefix is not considered part of the Genome and can not be seen nor changed by the Code Gen.
--All these criteria should ensure that malicious code in a -XSafe-compiled genome can not have any ill effect.
getSafeLines :: String -> Maybe Int
getSafeLines source =
let
safeLinesInSource = filter (\line -> take 12 line == "safeLines = ") $ lines source
safeLinesCount = read $ drop 12 $ head safeLinesInSource
safeLinesFromValue = [lines source !! (safeLinesCount - 1)]
in if safeLinesInSource /= safeLinesFromValue then Nothing else Just safeLinesCount
--TODO: Optimization: refactor the following into a function that returns a Maybe (String, String) split in prefix and suffix
getSafetyPrefix :: String -> Maybe String
getSafetyPrefix source = fmap (\sl -> unlines $ take sl $ lines source) $ getSafeLines source
dropSafetyPrefix :: String -> Maybe String
dropSafetyPrefix source = fmap (\sl -> unlines $ drop sl $ lines source) $ getSafeLines source
--list of words that should not ever be in a program we evaluate.
prohibited = ["{-#", "#-}", "import", "IO"]
isSafe :: String -> (Bool, String)
isSafe source = do
let
saneSafeLines = isJust $ getSafeLines source
containsBadWords = any (\badWord -> badWord `isInfixOf` (fromJust $ dropSafetyPrefix source)) prohibited --drop the safety prefix here
hasBadChars = not $ null $ filter (\char -> not $ elem char ('\r':'\t':'\n':[' '..'~'])) source
if not saneSafeLines
then trace "GRPSafety: Error with safeLines" (False, "Safety: Please check safeLines limit of source code")
else if containsBadWords
then (False, "Safety: Prohibited words detected.")
else if hasBadChars
then (False, "Safety: Control Characters detected in source code.")
else (True, "")
testSources = ["{-#\n pragma stuff #-}\nimport stuff\nsafeLines = 4\nhere be pure code", "safeLines = 1\nimport", "safeLines = 1\n#-}"]
testResults = [True, False, False]
test :: [Bool]
test = zipWith (\src res -> (fst $ isSafe src) == res) testSources testResults
|
vektordev/GP
|
src/GRPSafety.hs
|
gpl-2.0
| 2,467 | 2 | 17 | 471 | 531 | 290 | 241 | 37 | 4 |
module Main where
import System.Environment
import System.Exit
import Text.EditDistance
main :: IO ()
main = do
args <- getArgs
(fn1, fn2) <- case args of
[fn1,fn2] -> return (fn1, fn2)
_ -> putStrLn "Usage: textdist file1 file2" >> exitFailure
f1 <- readFrom fn1
f2 <- readFrom fn2
let d = levenshteinDistance defaultEditCosts f1 f2
print d
readFrom :: String -> IO String
readFrom "-" = getContents
readFrom fn = readFile fn
|
alanfalloon/textdist
|
Main.hs
|
gpl-3.0
| 478 | 0 | 12 | 122 | 165 | 82 | 83 | 17 | 2 |
import Test.QuickCheck
import Data.List
myPack' :: Eq a => [[a]] -> [a] -> [[a]]
myPack' p [] = p
myPack' [] x = myPack' [[head x]] (tail x)
myPack' p x =
case (head x) == (last . last $ p) of
True -> myPack' (init p ++ [last p ++ [head x]]) (tail x)
False -> myPack' (p ++ [[head x]]) (tail x)
myPack :: Eq a => [a] -> [[a]]
myPack x = myPack' [] x
testMyPack :: [Char] -> Bool
testMyPack x = myPack x == group x
main = quickCheck testMyPack
|
CmdrMoozy/haskell99
|
009.hs
|
gpl-3.0
| 452 | 2 | 14 | 104 | 281 | 145 | 136 | 14 | 2 |
module Control.Concurrent.Utils
( forkIOUnmasked, runAfter, asyncThrowTo, forwardExceptions, withForkedIO
) where
import Control.Concurrent (ThreadId, forkIOWithUnmask, threadDelay, myThreadId)
import qualified Control.Exception as E
import Control.Lens.Operators
import Control.Monad (void)
forkIOUnmasked :: IO () -> IO ThreadId
forkIOUnmasked action = forkIOWithUnmask $ \unmask -> unmask action
runAfter :: Int -> IO () -> IO ThreadId
runAfter delay action =
do
threadDelay delay
action
& forkIOUnmasked
asyncThrowTo :: E.Exception e => ThreadId -> e -> IO ()
asyncThrowTo threadId exc = E.throwTo threadId exc & forkIOUnmasked & void
forwardExceptions :: IO a -> IO (IO a)
forwardExceptions action =
do
selfId <- myThreadId
return $ action `E.catch` \[email protected]{} ->
do
asyncThrowTo selfId exc
E.throwIO E.ThreadKilled
withForkedIO :: IO () -> IO a -> IO a
withForkedIO action =
E.bracket (forkIOUnmasked action) (`E.throwTo` E.ThreadKilled) . const
|
da-x/lamdu
|
bottlelib/Control/Concurrent/Utils.hs
|
gpl-3.0
| 1,100 | 0 | 12 | 266 | 342 | 177 | 165 | 27 | 1 |
{-
Copyright (C) 2008 John Goerzen <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Commands.Cat where
import System.Console.GetOpt
import System.Console.GetOpt.Utils
import System.Cmd.Utils
import Utils
import System.IO
import qualified Data.ByteString.Lazy as BSL
import HSH
import TarfIndex
cmd = simpleCmd "cat"
"Decode a Tarf-encoded tar file, output plain tar file" helptext
[Option "d" ["decoder"] (ReqArg (stdRequired "d") "PROGRAM")
"Program to use for decoding",
Option "r" ["readindex"] (ReqArg (stdRequired "r") "FILE")
"Read non-incoded index for input from FILE"
]
cmd_worker
cmd_worker (args, []) =
do decoder <- case lookup "d" args of
Just x -> return x
Nothing -> fail "tarf cat: --decoder required; see tarf decode --help"
indexfn <- case lookup "r" args of
Just x -> return x
Nothing -> fail "tarf cat: --readindex required; see tarf decode --help"
tarindexstr <- readFile indexfn
let tarindex' = parseIndex tarindexstr
let nullblock = last tarindex'
let tarindex = init tarindex'
seekable <- hIsSeekable stdin
let seekfunc =
case seekable of
True -> (\h -> hSeek h RelativeSeek)
False -> hSkip
processTar decoder seekfunc (tarindex ++ [nullblock])
cmd_worker _ =
fail $ "Invalid arguments to cat; please see tarf cat --help"
hSkip :: Handle -> Integer -> IO ()
hSkip _ 0 = return ()
hSkip handle count =
do r <- BSL.hGet handle ((fromIntegral) readAmt)
if BSL.null r
then fail $ "Trying to skip " ++ show count ++ " bytes, got EOF"
else hSkip handle (count - (fromIntegral)(BSL.length r))
where readAmt = min count 4096
processTar :: String -> (Handle -> Integer -> IO ()) -> TarFile -> IO ()
processTar decoder seekfunc tf =
do (cmpoffset, offset) <- processTar' decoder seekfunc 0 0 tf
-- Make sure we pad with nulls to next 10240-byte boundary
let neededPad = (fromIntegral) (offset `mod` 10240)
let nulls = replicate neededPad 0
BSL.putStr (BSL.pack nulls)
processTar' :: String -> (Handle -> Integer -> IO ()) -> Integer -> Integer -> TarFile -> IO (Integer, Integer)
processTar' _ _ cmpoffset offset [] = return (cmpoffset, offset)
processTar' decoder seekfunc cmpoffset offset (te:xs) =
do skipIt
runIO $ catBytes 4096 (Just (cmpSize te)) -|- decoder
processTar' decoder seekfunc newCmpOffset newOffset xs
where skipAmountCmp = cmpOff te - cmpoffset
newCmpOffset = cmpoffset + skipAmountCmp + cmpSize te
newOffset = offset + uncSize te
skipIt
| skipAmountCmp == 0 = return ()
| otherwise = seekfunc stdin skipAmountCmp
helptext =
"Usage: tarf cat -d cat -r /path/to/index -f file > tar\n\n\
\Read a tarf-formatted file from standard input. Using the index given\n\
\by -r, decode the file, using efficient seeks if supported by the\n\
\underlying input supply. Write resulting plain tar file to stdout.\n\
\\n\
\If -f is specified, read from the named file instead of stdin.\n"
|
jgoerzen/tarfilter
|
Commands/Cat.hs
|
gpl-3.0
| 3,884 | 0 | 15 | 1,027 | 829 | 412 | 417 | 63 | 4 |
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Nirum.TypeInstance.BoundModuleSpec where
import Data.Proxy
import Test.Hspec.Meta
import Text.InterpolatedString.Perl6 (qq)
import Nirum.Constructs.Annotation hiding (docs)
import Nirum.Constructs.Declaration
import Nirum.Constructs.Module hiding (docs)
import Nirum.Constructs.TypeDeclaration hiding (modulePath)
import Nirum.Package.Metadata
import Nirum.Package.MetadataSpec
import Nirum.PackageSpec (createValidPackage)
import Nirum.Targets.Python (Python (Python))
import Nirum.Targets.Python.CodeGen (minimumRuntime)
import Nirum.TypeInstance.BoundModule
spec :: Spec
spec = do
testPackage (Python "nirum-examples" minimumRuntime [] [])
testPackage DummyTarget
testPackage :: forall t . Target t => t -> Spec
testPackage target' = do
let targetName' = targetName (Proxy :: Proxy t)
validPackage = createValidPackage target'
specify "resolveBoundModule" $ do
let Just bm = resolveBoundModule ["foo"] validPackage
boundPackage bm `shouldBe` validPackage
modulePath bm `shouldBe` ["foo"]
resolveBoundModule ["baz"] validPackage `shouldBe` Nothing
describe [qq|BoundModule (target: $targetName')|] $ do
let Just bm = resolveBoundModule ["foo", "bar"] validPackage
Just abc = resolveBoundModule ["abc"] validPackage
Just xyz = resolveBoundModule ["xyz"] validPackage
Just zar = resolveBoundModule ["zar"] validPackage
specify "docs" $ do
docs bm `shouldBe` Just "foo.bar"
let Just bm' = resolveBoundModule ["foo"] validPackage
docs bm' `shouldBe` Just "foo"
specify "boundTypes" $ do
boundTypes bm `shouldBe` []
boundTypes abc `shouldBe`
[TypeDeclaration "a" (Alias "text") empty]
boundTypes xyz `shouldBe`
[ Import ["abc"] "a" "a" empty
, TypeDeclaration "x" (Alias "text") empty
]
specify "lookupType" $ do
lookupType "a" bm `shouldBe` Missing
lookupType "a" abc `shouldBe` Local (Alias "text")
lookupType "a" xyz `shouldBe` Imported ["abc"] "a" (Alias "text")
lookupType "aliased" zar `shouldBe`
Imported ["abc"] "a" (Alias "text")
lookupType "x" bm `shouldBe` Missing
lookupType "x" abc `shouldBe` Missing
lookupType "x" xyz `shouldBe` Local (Alias "text")
lookupType "quuz" zar `shouldBe` Local (Alias "text")
lookupType "text" bm `shouldBe`
Imported coreModulePath "text" (PrimitiveType Text String)
lookupType "text" abc `shouldBe` lookupType "text" bm
lookupType "text" xyz `shouldBe` lookupType "text" bm
lookupType "text" zar `shouldBe` lookupType "text" bm
|
spoqa/nirum
|
test/Nirum/TypeInstance/BoundModuleSpec.hs
|
gpl-3.0
| 2,920 | 0 | 17 | 736 | 812 | 415 | 397 | 61 | 1 |
import Data.Binary
import qualified Data.ByteString.Lazy as BS
makeInterval :: (Integer, Integer) -> IO ()
makeInterval (a, b) = do
let x = encode (a, b)
BS.writeFile (show a ++ "_" ++ show b ++ ".raw") x
makeMany :: [Integer] -> IO ()
makeMany (x:(y:xs)) = do
makeInterval (x+1, y)
makeMany (y:xs)
makeMany _ = return ()
|
GDCN/GDCN
|
GDCN_proj/dGDCN/jobs/Job1/resources/GeneratePrimeIndata.hs
|
gpl-3.0
| 341 | 0 | 12 | 75 | 179 | 93 | 86 | 11 | 1 |
import Colouring
import Control.Monad(liftM)
main = do
putStrLn "Means of 100 runs each"
putStr "G(100,0.4) : "
print =<< (liftM mean $ sampleIndSetColour 100 $ randomGraph 100 0.4)
putStr "G(100,0.5) : "
print =<< (liftM mean $ sampleIndSetColour 100 $ randomGraph 100 0.5)
putStr "G(100,0.6) : "
print =<< (liftM mean $ sampleIndSetColour 100 $ randomGraph 100 0.6)
putStr "G6(100,0.4) : "
print =<< (liftM mean $ sampleIndSetColour 100 $ (noEdgesMod 6 . randomGraph 100 0.4))
putStr "G6(100,0.5) : "
print =<< (liftM mean $ sampleIndSetColour 100 $ (noEdgesMod 6 . randomGraph 100 0.5))
putStr "G6(100,0.6) : "
print =<< (liftM mean $ sampleIndSetColour 100 $ (noEdgesMod 6 . randomGraph 100 0.6))
|
jamii/homework
|
17-1/Main.hs
|
gpl-3.0
| 714 | 1 | 13 | 125 | 269 | 118 | 151 | 16 | 1 |
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TypeOperators,
FlexibleContexts #-}
module Main where
import Control.Monad
import Data.List
import Data.Yaml
import Flow
import Flow.Builder ( rule )
import Flow.Kernel
import Kernel.Binning
import Kernel.Cleaning
import Kernel.Data
import Kernel.Degrid
import Kernel.Facet
import Kernel.FFT
import Kernel.Gridder
import Kernel.IO
import Kernel.Scheduling
import System.Environment
import System.Directory
import System.FilePath
-- ----------------------------------------------------------------------------
-- --- Functional ---
-- ----------------------------------------------------------------------------
-- Gridding
createGrid :: Flow UVGrid
createGrid = flow "create grid"
grid :: Flow Vis -> Flow GCFs -> Flow UVGrid -> Flow UVGrid
grid = flow "grid"
degrid :: Flow GCFs -> Flow FullUVGrid -> Flow Vis -> Flow Vis
degrid = flow "degrid"
gcf :: Flow Vis -> Flow GCFs
gcf = flow "gcf"
-- FFT
dft :: Flow Image -> Flow FullUVGrid
dft = flow "dft"
idft :: Flow UVGrid -> Flow Image
idft = flow "idft"
-- Image summation for continuum
createImage :: Flow Image
createImage = flow "create image"
facetSum :: Flow Image -> Flow Image -> Flow Image
facetSum = flow "facet sum"
sumImage :: Flow Image -> Flow Image -> Flow Image
sumImage = flow "sum image"
-- Cleaning
psfVis :: Flow Vis -> Flow Vis
psfVis = flow "make PSF visibilities"
clean :: Flow Image -> Flow Image -> Flow Image -> Flow Cleaned
clean = flow "clean"
splitModel :: Flow Cleaned -> Flow Image
splitModel = flow "model from cleaning"
splitResidual :: Flow Cleaned -> Flow Image
splitResidual = flow "residual from cleaning"
-- Compound actors
gridder :: Flow Vis -> Flow Vis -> Flow Image
gridder vis0 vis = idft (grid vis (gcf vis0) createGrid)
summed :: Flow Vis -> Flow Vis -> Flow Image
summed vis0 vis = sumImage (facetSum (gridder vis0 vis) createImage) createImage
-- | Calculate a point spread function, which tells us the image shape
-- of a single point source in the middle of the field of view
psf :: Flow Vis -> Flow Image
psf vis = summed vis (psfVis vis)
-- | Update a model by gridding the given (possibly corrected)
-- visibilities and cleaning the result.
model :: Flow Vis -> Flow Vis -> Flow Image -> Flow Image
model vis0 vis mdl = splitModel $ clean (psf vis0) (summed vis0 vis) mdl
-- | Calculate a residual by gridding the given visibilities and
-- cleaning the result.
residual :: Flow Vis -> Flow Vis -> Flow Image
residual vis0 vis = splitResidual $ clean (psf vis0) (summed vis0 vis) createImage
-- | Degrid a model, producing corrected visibilities where we
-- have attempted to eliminate the effects of sources in the model.
degridModel :: Flow Vis -> Flow Image -> Flow Vis
degridModel vis mdl = degrid (gcf vis) (dft mdl) vis
-- | Major loop iteration: From visibilities infer components in the
-- image and return the updated model.
loopIter :: Flow Vis -> Flow Image -> Flow Image
loopIter vis mdl = model vis (degridModel vis mdl) mdl
-- | Final major loop iteration: Do the same steps as usual, but
-- return just the residual.
finalLoopIter :: Flow Vis -> Flow Image -> Flow Image
finalLoopIter vis mdl = residual vis (degridModel vis mdl)
-- ----------------------------------------------------------------------------
-- --- Strategy ---
-- ----------------------------------------------------------------------------
cpuHints, allCpuHints :: [ProfileHint]
cpuHints = [floatHint, memHint]
allCpuHints = ioHint:cpuHints
-- | Implement one major iteration of continuum gridding (@loopIter@) for
-- the given input 'Flow's over a number of datasets given by the data
-- set domains @ddoms@. Internally, we will distribute twice over
-- @DDom@ and once over @UVDom@.
continuumGridStrat :: Config -> [DDom] -> TDom -> [UVDom] -> [LMDom]
-> Flow Index -> Flow Vis -> Flow Vis
-> Strategy (Flow Image)
continuumGridStrat cfg [ddomss,ddoms,ddom] tdom [uvdoms,uvdom] [_lmdoms,lmdom]
ixs vis0 vis
= implementing (summed vis0 vis) $ do
-- Helpers
let dkern :: IsKernelDef kf => kf -> kf
dkern = regionKernel ddom
gpar = cfgGrid cfg
gcfpar = cfgGCF cfg
strat = cfgStrategy cfg
-- Intermediate Flow nodes
let gridded = grid vis (gcf vis0) createGrid -- grid from vis
images = facetSum (idft gridded) createImage
summed' = summed vis0 vis -- images, summed over channels
-- Distribute over nodes
distribute ddoms ParSchedule $ do
-- Loop over data sets
distribute ddom SeqSchedule $ do
-- Loop over facets
distribute (fst lmdom) (fst $ stratFacetSched strat) $
distribute (snd lmdom) (snd $ stratFacetSched strat) $ do
let fkern :: IsKernelDef kf => kf -> kf
fkern = regionKernel (fst lmdom) . regionKernel (snd lmdom)
rkern :: IsKernelDef kf => kf -> kf
rkern = dkern . fkern
-- Read in visibilities
rebind ixs $ scheduleSplit ddomss ddom
bind vis0 $ hints [ioHint{hintReadBytes = cfgPoints cfg * 5 * 8 {-sizeof double-}}] $
oskarReader ddom tdom (cfgInput cfg) 0 0 ixs
-- Create w-binned domain, split
wdoms <- makeBinDomain $ dkern $ binSizer gpar tdom uvdom vis0
wdom <- split wdoms (gridBins gpar)
-- Create GCF u/v domains
gudom <- makeBinDomain $ dkern $ gcfSizer gcfpar wdom
gvdom <- makeBinDomain $ dkern $ gcfSizer gcfpar wdom
let guvdom = (gudom, gvdom)
-- Loop over tiles
distribute (snd uvdom) (snd $ stratTileSched strat) $
distribute (fst uvdom) (fst $ stratTileSched strat) $ do
-- Load GCFs
bindRule gcf $ rkern $ const $ hints allCpuHints $ gcfKernel gcfpar wdom guvdom
distribute wdom SeqSchedule $ calculate $ gcf vis0
-- Rotate visibilities
rebind vis0 $ dkern $ hints cpuHints $ rotateKernel cfg lmdom tdom
-- Bin visibilities (could distribute, but there's no benefit)
rebind vis0 $ rkern $ hints allCpuHints $ binner gpar tdom uvdom wdom
-- Degrid / generate PSF (depending on vis)
rule degrid $ \(gcfs :. uvgrid :. vis' :. Z) -> do
rebind uvgrid $ distributeGrid ddomss ddom lmdom gpar
bind (degrid gcfs uvgrid vis') $ rkern $
degridKernel (stratDegridder strat) gpar gcfpar uvdom wdom guvdom gcfs uvgrid vis'
bindRule psfVis $ rkern $ psfVisKernel uvdom wdom
calculate vis
-- Gridding
bind createGrid $ rkern $ gridInit gcfpar uvdom
bindRule grid $ rkern $ gridKernel (stratGridder strat) gpar gcfpar uvdoms wdom guvdom uvdom
calculate gridded
-- Compute the result by detiling & iFFT on tiles
bind createGrid $ rkern $ gridInitDetile uvdoms
bind gridded $ rkern $ gridDetiling gcfpar uvdom uvdoms gridded createGrid
bindRule idft $ rkern $ hints cpuHints $ ifftKern gpar uvdoms
calculate $ idft gridded
-- Sum up facets
bind createImage $ dkern $ imageInit gpar
let fsize = gridImageWidth gpar * gridImageHeight gpar * 8 {-sizeof double-}
bind images $ dkern $ hints [floatHint, memHint{hintMemoryReadBytes = fsize}] $
imageDefacet gpar lmdom (idft gridded) createImage
-- Sum up images locally
bind createImage $ regionKernel ddoms $ imageInit gpar
bindRule sumImage $ imageSum gpar ddom ddoms
calculate summed'
-- Sum up images over nodes
recover summed' $ regionKernel ddoms $ imageInit gpar
bind createImage $ regionKernel ddomss $ imageInit gpar
bind summed' $ imageSum gpar ddoms ddomss summed' createImage
continuumGridStrat _ _ _ _ _ _ _ _ = fail "continuumGridStrat: Not enough domain splits provided!"
majorIterationStrat :: Config -> [DDom] -> TDom -> [UVDom] -> [LMDom]
-> Flow Index -> Flow Vis -> Flow Image
-> Strategy (Flow Image, Flow Image)
majorIterationStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis mdl = do
-- Calculate model grid using FFT (once)
let gpar = cfgGrid cfg
bindRule dft $ regionKernel (head ddom_s) $ hints allCpuHints $ fftKern gpar
calculate (dft mdl)
-- Do continuum gridding for degridded visibilities. The actual
-- degridding will be done in the inner loop, see continuumGridStrat.
let vis' = degridModel vis mdl
void $ continuumGridStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis vis'
-- Clean
let cpar = cfgClean cfg
bindRule (\psfImg img mdl' -> splitModel $ clean psfImg img mdl') $
regionKernel (head ddom_s) $ cleanModel gpar cpar
bindRule (\mdl' psfImg img -> splitResidual $ clean psfImg img mdl') $
regionKernel (head ddom_s) $ const $ cleanResidual gpar cpar
-- (Note that the order of parameters to bindRule determines the
-- order the Flows get passed to the kernel. So in the above
-- definition, the "const" removes mdl' and passes the concrete
-- Flows for psfImg and img to the kernel)
return (loopIter vis mdl,
finalLoopIter vis mdl)
continuumStrat :: Config -> Strategy ()
continuumStrat cfg = do
-- Make index and point domains for visibilities
(ddomss, ixs) <- makeOskarDomain cfg (cfgParallelism cfg)
tdom <- makeRangeDomain 0 (cfgPoints cfg)
-- Split index domain - first into bins per node, then into
-- individual data sets. The repeatSplit must be large enough to
-- split the largest repeat possible.
let repeatSplits = 1 + maximum (map oskarRepeat (cfgInput cfg))
ddoms <- split ddomss (cfgParallelism cfg)
ddom <- split ddoms repeatSplits
let ddom_s = [ddomss, ddoms, ddom]
-- Data flows we want to calculate
vis <- uniq $ flow "vis" ixs
-- Create ranged domains for image coordinates (split into facets)
let gpar = cfgGrid cfg
ldoms <- makeRangeDomain 0 (gridImageWidth gpar)
mdoms <- makeRangeDomain 0 (gridImageHeight gpar)
ldom <- split ldoms (gridFacets gpar)
mdom <- split mdoms (gridFacets gpar)
let lmdom_s = [(ldoms, mdoms), (ldom, mdom)]
-- Create ranged domains for grid coordinates (split into tiles)
udoms <- makeRangeDomain 0 (gridWidth gpar)
vdoms <- makeRangeDomain 0 (gridHeight gpar)
vdom <- split vdoms (gridTiles gpar)
udom <- split udoms (gridTiles gpar)
let uvdom_s = [(udoms, vdoms), (udom, vdom)]
-- Compute PSF
psfFlow <- continuumGridStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis (psfVis vis)
void $ bindNew $ regionKernel ddomss $ imageWriter gpar "psf.img" psfFlow
-- Major loops
let start = (createImage, createImage)
(finalMod, finalRes) <- (\f -> foldM f start [1..cfgLoops cfg]) $ \(mod', _res) i -> do
-- Calculate/create model
bindRule createImage $ regionKernel ddomss $ imageInit gpar
when (i > 1) $ calculate createImage -- workaround
calculate mod'
-- Run major loop iteration
majorIterationStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis mod'
-- Write out model grid
bind createImage $ regionKernel ddomss $ imageInit gpar
void $ bindNew $ regionKernel ddomss $
imageWriter gpar (cfgOutput cfg ++ ".mod") finalMod
bind createImage $ regionKernel ddomss $ imageInit gpar
void $ bindNew $ regionKernel ddomss $
imageWriter gpar (cfgOutput cfg) finalRes
main :: IO ()
main = do
-- Determine work directory (might be given on the command line)
args <- getArgs
dir <- case find ((== "--workdir") . fst) $ zip args (tail args) of
Just (_, wdir) -> return wdir
Nothing -> getCurrentDirectory
-- Read configuration
let configFile = dir </> "continuum.yaml"
putStrLn $ "Reading configuration from " ++ configFile
m_config <- decodeFileEither configFile
case m_config of
Left err -> putStrLn $ "Failed to read configuration file: " ++ show err
Right config -> do
print $ stratFacetSched $ cfgStrategy config
-- Show strategy - but only for the root process
when (not ("--internal-rank" `elem` args)) $ do
dumpSteps $ continuumStrat config
putStrLn "----------------------------------------------------------------"
putStrLn ""
-- Execute strategy
execStrategyDNA (stratUseFiles $ cfgStrategy config) $ continuumStrat config
|
SKA-ScienceDataProcessor/RC
|
MS6/programs/continuum.hs
|
apache-2.0
| 12,331 | 0 | 28 | 2,846 | 3,360 | 1,623 | 1,737 | 194 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.Unversioned.ListMeta where
import GHC.Generics
import Data.Text
import qualified Data.Aeson
-- | ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
data ListMeta = ListMeta
{ selfLink :: Maybe Text -- ^ SelfLink is a URL representing this object. Populated by the system. Read-only.
, resourceVersion :: Maybe Text -- ^ String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON ListMeta
instance Data.Aeson.ToJSON ListMeta
|
minhdoboi/deprecated-openshift-haskell-api
|
openshift/lib/Openshift/Unversioned/ListMeta.hs
|
apache-2.0
| 1,103 | 0 | 9 | 159 | 93 | 56 | 37 | 15 | 0 |
{- MathHmatrix.hs
- Mapping of Linear algebra routines via the hMatrix library.
- hMatrix uses GSL and a BLAS implementation such as ATLAS.
-
- Timothy A. Chagnon
- CS 636 - Spring 2009
-}
module MathHmatrix where
import Numeric.LinearAlgebra
deg2rad :: RealT -> RealT
deg2rad d = d * pi / 180
type RealT = Double
type Vec3f = Vector Double
vec3f :: Double -> Double -> Double -> Vector Double
vec3f x y z = (3 |>) [x,y,z]
zeroVec3f :: Vec3f
zeroVec3f = vec3f 0 0 0
svMul :: Double -> Vec3f -> Vec3f
svMul = scale
dot :: Vec3f -> Vec3f -> Double
dot = Numeric.LinearAlgebra.dot
cross :: Vec3f -> Vec3f -> Vec3f
cross v1 v2 =
let [a, b, c] = toList v1 in
let [d, e, f] = toList v2 in
vec3f (b*f-c*e) (c*d-a*f) (a*e-b*d)
mag :: Vec3f -> Double
mag v = sqrt (magSq v)
magSq :: Vec3f -> Double
magSq v = v `Numeric.LinearAlgebra.dot` v
norm :: Vec3f -> Vec3f
norm v = (1/(mag v)) `svMul` v
type Mat4f = Matrix Double
mat4f :: Vec4f -> Vec4f -> Vec4f -> Vec4f -> Mat4f
mat4f a b c d = fromRows [a,b,c,d]
type Vec4f = Vector Double
vec4f :: Double -> Double -> Double -> Double -> Vector Double
vec4f x y z w = (4 |>) [x,y,z,w]
mvMul :: Mat4f -> Vec4f -> Vec4f
mvMul = (<>)
mmMul :: Mat4f -> Mat4f -> Mat4f
mmMul = (<>)
id4f :: Mat4f
id4f = ident 4
point4f :: Vec3f -> Vec4f
point4f v = 4 |> ((toList v) ++ [1.0])
point3f :: Vec4f -> Vec3f
point3f v =
let [x, y, z, w] = toList v in
if w == 0
then error "point3f divide by zero"
else vec3f (x/w) (y/w) (z/w)
direction4f :: Vec3f -> Vec4f
direction4f v = 4 |> ((toList v) ++ [0.0])
direction3f :: Vec4f -> Vec3f
direction3f = subVector 0 3
vec3fElts :: Vec3f -> (RealT, RealT, RealT)
vec3fElts v =
let [x,y,z] = toList v in
(x,y,z)
type ColMat3f = Matrix Double
colMat3f :: Vec3f -> Vec3f -> Vec3f -> ColMat3f
colMat3f a b c = fromColumns [a,b,c]
detMat3f :: ColMat3f -> RealT
detMat3f = det
|
tchagnon/cs636-raytracer
|
a1/MathHmatrix.hs
|
apache-2.0
| 1,933 | 0 | 13 | 465 | 846 | 460 | 386 | 58 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# OPTIONS_GHC -Wall -funbox-strict-fields -fno-warn-orphans -fno-warn-type-defaults -O2 #-}
#ifdef ST_HACK
{-# OPTIONS_GHC -fno-full-laziness #-}
#endif
--------------------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett 2015
-- License : BSD-style
-- Maintainer : Edward Kmett <[email protected]>
-- Portability : non-portable
--
-- This module suppose a Word64-based array-mapped PATRICIA Trie.
--
-- The most significant nybble is isolated by using techniques based on
-- <https://www.fpcomplete.com/user/edwardk/revisiting-matrix-multiplication/part-4>
-- but modified to work nybble-by-nybble rather than bit-by-bit.
--
--------------------------------------------------------------------------------
module Data.Discrimination.Internal.WordMap
( WordMap
, singleton
, empty
, insert
, lookup
, member
, fromList
) where
import Control.Applicative hiding (empty)
import Control.DeepSeq
import Control.Monad.ST hiding (runST)
import Data.Bits
import Data.Discrimination.Internal.SmallArray
import Data.Foldable
import Data.Functor
import Data.Monoid
import Data.Traversable
import Data.Word
import qualified GHC.Exts as Exts
import Prelude hiding (lookup, length, foldr)
import GHC.Types
import GHC.ST
type Key = Word64
type Mask = Word16
type Offset = Int
ptrEq :: a -> a -> Bool
ptrEq x y = isTrue# (Exts.reallyUnsafePtrEquality# x y Exts.==# 1#)
{-# INLINEABLE ptrEq #-}
ptrNeq :: a -> a -> Bool
ptrNeq x y = isTrue# (Exts.reallyUnsafePtrEquality# x y Exts./=# 1#)
{-# INLINEABLE ptrNeq #-}
data WordMap v
= Full !Key !Offset !(SmallArray (WordMap v))
| Node !Key !Offset !Mask !(SmallArray (WordMap v))
| Tip !Key v
| Nil
deriving Show
node :: Key -> Offset -> Mask -> SmallArray (WordMap v) -> WordMap v
node k o 0xffff a = Full k o a
node k o m a = Node k o m a
{-# INLINE node #-}
instance NFData v => NFData (WordMap v) where
rnf (Full _ _ a) = rnf a
rnf (Node _ _ _ a) = rnf a
rnf (Tip _ v) = rnf v
rnf Nil = ()
instance Functor WordMap where
fmap f = go where
go (Full k o a) = Full k o (fmap go a)
go (Node k o m a) = Node k o m (fmap go a)
go (Tip k v) = Tip k (f v)
go Nil = Nil
{-# INLINEABLE fmap #-}
instance Foldable WordMap where
foldMap f = go where
go (Full _ _ a) = foldMap go a
go (Node _ _ _ a) = foldMap go a
go (Tip _ v) = f v
go Nil = mempty
{-# INLINEABLE foldMap #-}
instance Traversable WordMap where
traverse f = go where
go (Full k o a) = Full k o <$> traverse go a
go (Node k o m a) = Node k o m <$> traverse go a
go (Tip k v) = Tip k <$> f v
go Nil = pure Nil
{-# INLINEABLE traverse #-}
-- Note: 'level 0' will return a negative shift, don't use it
level :: Key -> Int
level w = 60 - (countLeadingZeros w .&. 0x7c)
{-# INLINE level #-}
maskBit :: Key -> Offset -> Int
maskBit k o = fromIntegral (unsafeShiftR k o .&. 0xf)
{-# INLINE maskBit #-}
mask :: Key -> Offset -> Word16
mask k o = unsafeShiftL 1 (maskBit k o)
{-# INLINE mask #-}
-- offset :: Int -> Word16 -> Int
-- offset k w = popCount $ w .&. (unsafeShiftL 1 k - 1)
-- {-# INLINE offset #-}
fork :: Int -> Key -> WordMap v -> Key -> WordMap v -> WordMap v
fork o k n ok on = Node (k .&. unsafeShiftL 0xfffffffffffffff0 o) o (mask k o .|. mask ok o) $ runST $ do
arr <- newSmallArray 2 n
writeSmallArray arr (fromEnum (k < ok)) on
unsafeFreezeSmallArray arr
insert :: Key -> v -> WordMap v -> WordMap v
insert !k v xs0 = go xs0 where
go on@(Full ok n as)
| wd > 0xf = fork (level okk) k (Tip k v) ok on
| !oz <- indexSmallArray as d
, !z <- go oz
, ptrNeq z oz = Full ok n (update16 d z as)
| otherwise = on
where
okk = xor ok k
wd = unsafeShiftR okk n
d = fromIntegral wd
go on@(Node ok n m as)
| wd > 0xf = fork (level okk) k (Tip k v) ok on
| m .&. b == 0 = node ok n (m .|. b) (insertSmallArray odm (Tip k v) as)
| !oz <- indexSmallArray as odm
, !z <- go oz
, ptrNeq z oz = Node ok n m (updateSmallArray odm z as)
| otherwise = on
where
okk = xor ok k
wd = unsafeShiftR okk n
d = fromIntegral wd
b = unsafeShiftL 1 d
odm = popCount $ m .&. (b - 1)
go on@(Tip ok ov)
| k /= ok = fork (level (xor ok k)) k (Tip k v) ok on
| ptrEq v ov = on
| otherwise = Tip k v
go Nil = Tip k v
{-# INLINEABLE insert #-}
lookup :: Key -> WordMap v -> Maybe v
lookup !k (Full ok o a)
| z <- unsafeShiftR (xor k ok) o, z <= 0xf = lookup k $ indexSmallArray a (fromIntegral z)
| otherwise = Nothing
lookup k (Node ok o m a)
| z <= 0xf && m .&. b /= 0 = lookup k (indexSmallArray a (popCount (m .&. (b - 1))))
| otherwise = Nothing
where
z = unsafeShiftR (xor k ok) o
b = unsafeShiftL 1 (fromIntegral z)
lookup k (Tip ok ov)
| k == ok = Just ov
| otherwise = Nothing
lookup _ Nil = Nothing
{-# INLINEABLE lookup #-}
member :: Key -> WordMap v -> Bool
member !k (Full ok o a)
| z <- unsafeShiftR (xor k ok) o = z <= 0xf && member k (indexSmallArray a (fromIntegral z))
member k (Node ok o m a)
| z <- unsafeShiftR (xor k ok) o
= z <= 0xf && let b = unsafeShiftL 1 (fromIntegral z) in
m .&. b /= 0 && member k (indexSmallArray a (popCount (m .&. (b - 1))))
member k (Tip ok _) = k == ok
member _ Nil = False
{-# INLINEABLE member #-}
updateSmallArray :: Int -> a -> SmallArray a -> SmallArray a
updateSmallArray !k a i = runST $ do
let n = length i
o <- newSmallArray n undefined
copySmallArray o 0 i 0 n
writeSmallArray o k a
unsafeFreezeSmallArray o
{-# INLINEABLE updateSmallArray #-}
update16 :: Int -> a -> SmallArray a -> SmallArray a
update16 !k a i = runST $ do
o <- clone16 i
writeSmallArray o k a
unsafeFreezeSmallArray o
{-# INLINEABLE update16 #-}
insertSmallArray :: Int -> a -> SmallArray a -> SmallArray a
insertSmallArray !k a i = runST $ do
let n = length i
o <- newSmallArray (n + 1) a
copySmallArray o 0 i 0 k
copySmallArray o (k+1) i k (n-k)
unsafeFreezeSmallArray o
{-# INLINEABLE insertSmallArray #-}
clone16 :: SmallArray a -> ST s (SmallMutableArray s a)
clone16 i = do
o <- newSmallArray 16 undefined
indexSmallArrayM i 0 >>= writeSmallArray o 0
indexSmallArrayM i 1 >>= writeSmallArray o 1
indexSmallArrayM i 2 >>= writeSmallArray o 2
indexSmallArrayM i 3 >>= writeSmallArray o 3
indexSmallArrayM i 4 >>= writeSmallArray o 4
indexSmallArrayM i 5 >>= writeSmallArray o 5
indexSmallArrayM i 6 >>= writeSmallArray o 6
indexSmallArrayM i 7 >>= writeSmallArray o 7
indexSmallArrayM i 8 >>= writeSmallArray o 8
indexSmallArrayM i 9 >>= writeSmallArray o 9
indexSmallArrayM i 10 >>= writeSmallArray o 10
indexSmallArrayM i 11 >>= writeSmallArray o 11
indexSmallArrayM i 12 >>= writeSmallArray o 12
indexSmallArrayM i 13 >>= writeSmallArray o 13
indexSmallArrayM i 14 >>= writeSmallArray o 14
indexSmallArrayM i 15 >>= writeSmallArray o 15
return o
{-# INLINE clone16 #-}
-- | Build a singleton WordMap
singleton :: Key -> v -> WordMap v
singleton !k v = Tip k v
{-# INLINE singleton #-}
fromList :: [(Word64,v)] -> WordMap v
fromList xs = foldl' (\r (k,v) -> insert k v r) Nil xs
{-# INLINE fromList #-}
empty :: WordMap a
empty = Nil
{-# INLINE empty #-}
|
markus1189/discrimination
|
src/Data/Discrimination/Internal/WordMap.hs
|
bsd-2-clause
| 7,597 | 0 | 18 | 1,749 | 2,851 | 1,394 | 1,457 | 202 | 4 |
{-| Module describing an instance.
The instance data type holds very few fields, the algorithm
intelligence is in the "Node" and "Cluster" modules.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Instance
( Instance(..)
, Disk(..)
, AssocList
, List
, create
, isRunning
, isOffline
, notOffline
, instanceDown
, usesSecMem
, applyIfOnline
, setIdx
, setName
, setAlias
, setPri
, setSec
, setBoth
, setMovable
, specOf
, getTotalSpindles
, instBelowISpec
, instAboveISpec
, instMatchesPolicy
, shrinkByType
, localStorageTemplates
, hasSecondary
, requiredNodes
, allNodes
, usesLocalStorage
, mirrorType
) where
import Control.Monad (liftM2)
import Ganeti.BasicTypes
import qualified Ganeti.HTools.Types as T
import qualified Ganeti.HTools.Container as Container
import Ganeti.HTools.Nic (Nic)
import Ganeti.Utils
-- * Type declarations
data Disk = Disk
{ dskSize :: Int -- ^ Size in bytes
, dskSpindles :: Maybe Int -- ^ Number of spindles
} deriving (Show, Eq)
-- | The instance type.
data Instance = Instance
{ name :: String -- ^ The instance name
, alias :: String -- ^ The shortened name
, mem :: Int -- ^ Memory of the instance
, dsk :: Int -- ^ Total disk usage of the instance
, disks :: [Disk] -- ^ Sizes of the individual disks
, vcpus :: Int -- ^ Number of VCPUs
, runSt :: T.InstanceStatus -- ^ Original run status
, pNode :: T.Ndx -- ^ Original primary node
, sNode :: T.Ndx -- ^ Original secondary node
, idx :: T.Idx -- ^ Internal index
, util :: T.DynUtil -- ^ Dynamic resource usage
, movable :: Bool -- ^ Can and should the instance be moved?
, autoBalance :: Bool -- ^ Is the instance auto-balanced?
, diskTemplate :: T.DiskTemplate -- ^ The disk template of the instance
, spindleUse :: Int -- ^ The numbers of used spindles
, allTags :: [String] -- ^ List of all instance tags
, exclTags :: [String] -- ^ List of instance exclusion tags
, arPolicy :: T.AutoRepairPolicy -- ^ Instance's auto-repair policy
, nics :: [Nic] -- ^ NICs of the instance
} deriving (Show, Eq)
instance T.Element Instance where
nameOf = name
idxOf = idx
setAlias = setAlias
setIdx = setIdx
allNames n = [name n, alias n]
-- | Check if instance is running.
isRunning :: Instance -> Bool
isRunning (Instance {runSt = T.Running}) = True
isRunning (Instance {runSt = T.ErrorUp}) = True
isRunning _ = False
-- | Check if instance is offline.
isOffline :: Instance -> Bool
isOffline (Instance {runSt = T.StatusOffline}) = True
isOffline _ = False
-- | Helper to check if the instance is not offline.
notOffline :: Instance -> Bool
notOffline = not . isOffline
-- | Check if instance is down.
instanceDown :: Instance -> Bool
instanceDown inst | isRunning inst = False
instanceDown inst | isOffline inst = False
instanceDown _ = True
-- | Apply the function if the instance is online. Otherwise use
-- the initial value
applyIfOnline :: Instance -> (a -> a) -> a -> a
applyIfOnline = applyIf . notOffline
-- | Helper for determining whether an instance's memory needs to be
-- taken into account for secondary memory reservation.
usesSecMem :: Instance -> Bool
usesSecMem inst = notOffline inst && autoBalance inst
-- | Constant holding the local storage templates.
--
-- /Note:/ Currently Ganeti only exports node total/free disk space
-- for LVM-based storage; file-based storage is ignored in this model,
-- so even though file-based storage uses in reality disk space on the
-- node, in our model it won't affect it and we can't compute whether
-- there is enough disk space for a file-based instance. Therefore we
-- will treat this template as \'foreign\' storage.
localStorageTemplates :: [T.DiskTemplate]
localStorageTemplates = [ T.DTDrbd8, T.DTPlain ]
-- | Constant holding the movable disk templates.
--
-- This only determines the initial 'movable' state of the
-- instance. Further the movable state can be restricted more due to
-- user choices, etc.
movableDiskTemplates :: [T.DiskTemplate]
movableDiskTemplates =
[ T.DTDrbd8
, T.DTBlock
, T.DTSharedFile
, T.DTRbd
, T.DTExt
]
-- | A simple name for the int, instance association list.
type AssocList = [(T.Idx, Instance)]
-- | A simple name for an instance map.
type List = Container.Container Instance
-- * Initialization
-- | Create an instance.
--
-- Some parameters are not initialized by function, and must be set
-- later (via 'setIdx' for example).
create :: String -> Int -> Int -> [Disk] -> Int -> T.InstanceStatus
-> [String] -> Bool -> T.Ndx -> T.Ndx -> T.DiskTemplate -> Int
-> [Nic] -> Instance
create name_init mem_init dsk_init disks_init vcpus_init run_init tags_init
auto_balance_init pn sn dt su nics_init =
Instance { name = name_init
, alias = name_init
, mem = mem_init
, dsk = dsk_init
, disks = disks_init
, vcpus = vcpus_init
, runSt = run_init
, pNode = pn
, sNode = sn
, idx = -1
, util = T.baseUtil
, movable = supportsMoves dt
, autoBalance = auto_balance_init
, diskTemplate = dt
, spindleUse = su
, allTags = tags_init
, exclTags = []
, arPolicy = T.ArNotEnabled
, nics = nics_init
}
-- | Changes the index.
--
-- This is used only during the building of the data structures.
setIdx :: Instance -- ^ The original instance
-> T.Idx -- ^ New index
-> Instance -- ^ The modified instance
setIdx t i = t { idx = i }
-- | Changes the name.
--
-- This is used only during the building of the data structures.
setName :: Instance -- ^ The original instance
-> String -- ^ New name
-> Instance -- ^ The modified instance
setName t s = t { name = s, alias = s }
-- | Changes the alias.
--
-- This is used only during the building of the data structures.
setAlias :: Instance -- ^ The original instance
-> String -- ^ New alias
-> Instance -- ^ The modified instance
setAlias t s = t { alias = s }
-- * Update functions
-- | Changes the primary node of the instance.
setPri :: Instance -- ^ the original instance
-> T.Ndx -- ^ the new primary node
-> Instance -- ^ the modified instance
setPri t p = t { pNode = p }
-- | Changes the secondary node of the instance.
setSec :: Instance -- ^ the original instance
-> T.Ndx -- ^ the new secondary node
-> Instance -- ^ the modified instance
setSec t s = t { sNode = s }
-- | Changes both nodes of the instance.
setBoth :: Instance -- ^ the original instance
-> T.Ndx -- ^ new primary node index
-> T.Ndx -- ^ new secondary node index
-> Instance -- ^ the modified instance
setBoth t p s = t { pNode = p, sNode = s }
-- | Sets the movable flag on an instance.
setMovable :: Instance -- ^ The original instance
-> Bool -- ^ New movable flag
-> Instance -- ^ The modified instance
setMovable t m = t { movable = m }
-- | Try to shrink the instance based on the reason why we can't
-- allocate it.
shrinkByType :: Instance -> T.FailMode -> Result Instance
shrinkByType inst T.FailMem = let v = mem inst - T.unitMem
in if v < T.unitMem
then Bad "out of memory"
else Ok inst { mem = v }
shrinkByType inst T.FailDisk =
let newdisks = [d {dskSize = dskSize d - T.unitDsk}| d <- disks inst]
v = dsk inst - (length . disks $ inst) * T.unitDsk
in if any (< T.unitDsk) $ map dskSize newdisks
then Bad "out of disk"
else Ok inst { dsk = v, disks = newdisks }
shrinkByType inst T.FailCPU = let v = vcpus inst - T.unitCpu
in if v < T.unitCpu
then Bad "out of vcpus"
else Ok inst { vcpus = v }
shrinkByType inst T.FailSpindles =
case disks inst of
[Disk ds sp] -> case sp of
Nothing -> Bad "No spindles, shouldn't have happened"
Just sp' -> let v = sp' - T.unitSpindle
in if v < T.unitSpindle
then Bad "out of spindles"
else Ok inst { disks = [Disk ds (Just v)] }
d -> Bad $ "Expected one disk, but found " ++ show d
shrinkByType _ f = Bad $ "Unhandled failure mode " ++ show f
-- | Get the number of disk spindles
getTotalSpindles :: Instance -> Maybe Int
getTotalSpindles inst =
foldr (liftM2 (+) . dskSpindles ) (Just 0) (disks inst)
-- | Return the spec of an instance.
specOf :: Instance -> T.RSpec
specOf Instance { mem = m, dsk = d, vcpus = c, disks = dl } =
let sp = case dl of
[Disk _ (Just sp')] -> sp'
_ -> 0
in T.RSpec { T.rspecCpu = c, T.rspecMem = m,
T.rspecDsk = d, T.rspecSpn = sp }
-- | Checks if an instance is smaller/bigger than a given spec. Returns
-- OpGood for a correct spec, otherwise Bad one of the possible
-- failure modes.
instCompareISpec :: Ordering -> Instance-> T.ISpec -> Bool -> T.OpResult ()
instCompareISpec which inst ispec exclstor
| which == mem inst `compare` T.iSpecMemorySize ispec = Bad T.FailMem
| which `elem` map ((`compare` T.iSpecDiskSize ispec) . dskSize)
(disks inst) = Bad T.FailDisk
| which == vcpus inst `compare` T.iSpecCpuCount ispec = Bad T.FailCPU
| exclstor &&
case getTotalSpindles inst of
Nothing -> True
Just sp_sum -> which == sp_sum `compare` T.iSpecSpindleUse ispec
= Bad T.FailSpindles
| not exclstor && which == spindleUse inst `compare` T.iSpecSpindleUse ispec
= Bad T.FailSpindles
| diskTemplate inst /= T.DTDiskless &&
which == length (disks inst) `compare` T.iSpecDiskCount ispec
= Bad T.FailDiskCount
| otherwise = Ok ()
-- | Checks if an instance is smaller than a given spec.
instBelowISpec :: Instance -> T.ISpec -> Bool -> T.OpResult ()
instBelowISpec = instCompareISpec GT
-- | Checks if an instance is bigger than a given spec.
instAboveISpec :: Instance -> T.ISpec -> Bool -> T.OpResult ()
instAboveISpec = instCompareISpec LT
-- | Checks if an instance matches a min/max specs pair
instMatchesMinMaxSpecs :: Instance -> T.MinMaxISpecs -> Bool -> T.OpResult ()
instMatchesMinMaxSpecs inst minmax exclstor = do
instAboveISpec inst (T.minMaxISpecsMinSpec minmax) exclstor
instBelowISpec inst (T.minMaxISpecsMaxSpec minmax) exclstor
-- | Checks if an instance matches any specs of a policy
instMatchesSpecs :: Instance -> [T.MinMaxISpecs] -> Bool -> T.OpResult ()
-- Return Ok for no constraints, though this should never happen
instMatchesSpecs _ [] _ = Ok ()
instMatchesSpecs inst minmaxes exclstor =
-- The initial "Bad" should be always replaced by a real result
foldr eithermatch (Bad T.FailInternal) minmaxes
where eithermatch mm (Bad _) = instMatchesMinMaxSpecs inst mm exclstor
eithermatch _ y@(Ok ()) = y
-- | Checks if an instance matches a policy.
instMatchesPolicy :: Instance -> T.IPolicy -> Bool -> T.OpResult ()
instMatchesPolicy inst ipol exclstor = do
instMatchesSpecs inst (T.iPolicyMinMaxISpecs ipol) exclstor
if diskTemplate inst `elem` T.iPolicyDiskTemplates ipol
then Ok ()
else Bad T.FailDisk
-- | Checks whether the instance uses a secondary node.
--
-- /Note:/ This should be reconciled with @'sNode' ==
-- 'Node.noSecondary'@.
hasSecondary :: Instance -> Bool
hasSecondary = (== T.DTDrbd8) . diskTemplate
-- | Computed the number of nodes for a given disk template.
requiredNodes :: T.DiskTemplate -> Int
requiredNodes T.DTDrbd8 = 2
requiredNodes _ = 1
-- | Computes all nodes of an instance.
allNodes :: Instance -> [T.Ndx]
allNodes inst = case diskTemplate inst of
T.DTDrbd8 -> [pNode inst, sNode inst]
_ -> [pNode inst]
-- | Checks whether a given disk template uses local storage.
usesLocalStorage :: Instance -> Bool
usesLocalStorage = (`elem` localStorageTemplates) . diskTemplate
-- | Checks whether a given disk template supported moves.
supportsMoves :: T.DiskTemplate -> Bool
supportsMoves = (`elem` movableDiskTemplates)
-- | A simple wrapper over 'T.templateMirrorType'.
mirrorType :: Instance -> T.MirrorType
mirrorType = T.templateMirrorType . diskTemplate
|
apyrgio/snf-ganeti
|
src/Ganeti/HTools/Instance.hs
|
bsd-2-clause
| 13,964 | 0 | 20 | 3,572 | 2,755 | 1,541 | 1,214 | 236 | 7 |
{-# LANGUAGE BangPatterns #-}
{-|
Convenience 'Pipe's, analogous to those in "Control.Pipe.List", for 'Pipe's
containing binary data.
-}
module Control.Pipe.Binary
( -- * Producers
produce
-- ** Infinite streams
, iterate
, iterateM
, repeat
, repeatM
-- ** Bounded streams
, replicate
, replicateM
, unfold
, unfoldM
-- * Consumers
, consume
, consume'
, fold
, foldM
, mapM_
-- * Pipes
-- ** Maps
, map
, mapM
, concatMap
, concatMapM
-- ** Accumulating maps
, mapAccum
, mapAccumM
, concatMapAccum
, concatMapAccumM
-- ** Dropping input
, filter
, filterM
, drop
, dropWhile
, take
, takeWhile
, takeUntilByte
-- ** Other
, lines
, words
)
where
import Control.Monad (Monad (..), forever, liftM, when)
import Control.Monad.Trans (lift)
import Control.Pipe.Common
import qualified Control.Pipe.List as PL
import Data.Bool (Bool)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.Function ((.), ($))
import Data.Functor (fmap)
import Data.Maybe (Maybe (..))
import Data.Word (Word8)
import Prelude (Int, (+), (-), Ord (..), fromIntegral, otherwise)
------------------------------------------------------------------------------
-- | Produces a stream of byte chunks given a lazy 'L.ByteString'.
produce :: Monad m => L.ByteString -> Producer ByteString m ()
produce = PL.produce . L.toChunks
------------------------------------------------------------------------------
-- | @'iterate' f x@ produces an infinite stream of repeated applications of
-- @f@ to @x@.
iterate :: Monad m => (Word8 -> Word8) -> Word8 -> Producer ByteString m b
iterate f a = produce (L.iterate f a) >> discard
------------------------------------------------------------------------------
-- | Similar to 'iterate', except the iteration function is monadic.
iterateM :: Monad m => (Word8 -> m Word8) -> Word8 -> Producer ByteString m b
iterateM f a = PL.iterateM f a >+> pipe B.singleton
------------------------------------------------------------------------------
-- | Produces an infinite stream of a single byte.
repeat :: Monad m => Word8 -> Producer ByteString m b
repeat a = produce (L.repeat a) >> discard
------------------------------------------------------------------------------
-- | Produces an infinite stream of values. Each value is computed by the
-- underlying monad.
repeatM :: Monad m => m Word8 -> Producer ByteString m b
repeatM m = forever $ lift m >>= yield . B.singleton
------------------------------------------------------------------------------
-- | @'replicate' n x@ produces a stream containing @n@ copies of @x@.
replicate :: Monad m => Int -> Word8 -> Producer ByteString m ()
replicate n = produce . L.replicate (fromIntegral n)
------------------------------------------------------------------------------
-- | @'replicateM' n x@ produces a stream containing @n@ bytes, where each
-- byte is computed by the underlying monad.
replicateM :: Monad m => Int -> m Word8 -> Producer ByteString m ()
replicateM n m = PL.replicateM n m >+> pipe B.singleton
------------------------------------------------------------------------------
-- | Produces a stream of bytes by repeatedly applying a function to some
-- state, until 'Nothing' is returned.
unfold :: Monad m => (c -> Maybe (Word8, c)) -> c -> Producer ByteString m ()
unfold f = produce . L.unfoldr f
------------------------------------------------------------------------------
-- | Produces a stream of bytes by repeatedly applying a computation to some
-- state, until 'Nothing' is returned.
unfoldM
:: Monad m
=> (c -> m (Maybe (Word8, c)))
-> c
-> Producer ByteString m ()
unfoldM f c = PL.unfoldM f c >+> pipe B.singleton
------------------------------------------------------------------------------
-- | Consumes all input chunks and returns a lazy 'L.ByteString'.
consume :: Monad m => Consumer ByteString m L.ByteString
consume = L.fromChunks `liftM` PL.consume
------------------------------------------------------------------------------
-- | Consumes all input chunks and concatenate them into a strict
-- 'ByteString'.
consume' :: Monad m => Consumer ByteString m ByteString
consume' = B.concat `liftM` PL.consume
------------------------------------------------------------------------------
-- | Consume the entire input stream with a strict left monadic fold, one byte
-- at a time.
fold :: Monad m => (b -> Word8 -> b) -> b -> Consumer ByteString m b
fold = PL.fold . B.foldl
------------------------------------------------------------------------------
-- | Consume the entire input stream with a strict left fold, one byte at a
-- time.
foldM :: Monad m => (b -> Word8 -> m b) -> b -> Consumer ByteString m b
foldM f = PL.foldM $ \b -> B.foldl (\mb w -> mb >>= \b -> f b w) (return b)
------------------------------------------------------------------------------
-- | For every byte in a stream, run a computation and discard its result.
mapM_ :: Monad m => (Word8 -> m b) -> Consumer ByteString m r
mapM_ f = foldM (\() a -> f a >> return ()) () >> discard
------------------------------------------------------------------------------
-- | 'map' transforms a byte stream by applying a transformation to each byte
-- in the stream.
map :: Monad m => (Word8 -> Word8) -> Pipe ByteString ByteString m r
map = pipe . B.map
------------------------------------------------------------------------------
-- | 'map' transforms a byte stream by applying a monadic transformation to
-- each byte in the stream.
mapM :: Monad m => (Word8 -> m Word8) -> Pipe ByteString ByteString m r
mapM f = concatMapM (liftM B.singleton . f)
------------------------------------------------------------------------------
-- | 'concatMap' transforms a byte stream by applying a transformation to each
-- byte in the stream and concatenating the results.
concatMap
:: Monad m
=> (Word8 -> ByteString)
-> Pipe ByteString ByteString m r
concatMap = pipe . B.concatMap
------------------------------------------------------------------------------
-- | 'concatMapM' transforms a byte stream by applying a monadic
-- transformation to each byte in the stream and concatenating the results.
concatMapM
:: Monad m
=> (Word8 -> m ByteString)
-> Pipe ByteString ByteString m r
concatMapM f = forever $ do
await >>= B.foldl (\m w -> m >> lift (f w) >>= yield) (return ())
------------------------------------------------------------------------------
-- | Similar to 'map', but with a stateful step function.
mapAccum
:: Monad m
=> (c -> Word8 -> (c, Word8))
-> c
-> Pipe ByteString ByteString m r
mapAccum f = go
where
go !c = do
bs <- await
let (c', bs') = B.mapAccumL f c bs
yield bs'
go c'
------------------------------------------------------------------------------
-- | Similar to 'mapM', but with a stateful step function.
mapAccumM
:: Monad m
=> (c -> Word8 -> m (c, Word8))
-> c
-> Pipe ByteString ByteString m r
mapAccumM f = concatMapAccumM (\c w -> liftM (fmap B.singleton) (f c w))
------------------------------------------------------------------------------
-- | Similar to 'concatMap', but with a stateful step function.
concatMapAccum
:: Monad m
=> (c -> Word8 -> (c, ByteString))
-> c
-> Pipe ByteString ByteString m r
concatMapAccum f = concatMapAccumM (\c w -> return (f c w))
------------------------------------------------------------------------------
-- | Similar to 'concatMapM', but with a stateful step function.
concatMapAccumM
:: Monad m
=> (c -> Word8 -> m (c, ByteString))
-> c
-> Pipe ByteString ByteString m r
concatMapAccumM f = go
where
go c = await >>= B.foldl (\mc w -> do
c <- mc
(c', bs) <- lift (f c w)
yield bs
return c') (return c) >>= go
------------------------------------------------------------------------------
-- | @'filter' p@ keeps only the bytes in the stream which match the predicate
-- @p@.
filter :: Monad m => (Word8 -> Bool) -> Pipe ByteString ByteString m r
filter = pipe . B.filter
------------------------------------------------------------------------------
-- | @'filter' p@ keeps only the bytes in the stream which match the monadic
-- predicate @p@.
filterM :: Monad m => (Word8 -> m Bool) -> Pipe ByteString ByteString m r
filterM f = go
where
go = await >>= B.foldl (\m w -> do
m
bool <- lift (f w)
when bool $ yield $ B.singleton w) (return ()) >> go
------------------------------------------------------------------------------
-- | @'drop' n@ discards the first @n@ bytes from the stream.
drop :: Monad m => Int -> Pipe ByteString ByteString m ()
drop n = do
bs <- await
let n' = n - B.length bs
if n' > 0 then drop n' else do unuse $ B.drop n bs
------------------------------------------------------------------------------
-- | @'dropWhile' p@ discards bytes from the stream until they no longer match
-- the predicate @p@.
dropWhile :: Monad m => (Word8 -> Bool) -> Pipe ByteString ByteString m ()
dropWhile p = go
where
go = do
bs <- await
let (bad, good) = B.span p bs
if B.null good then go else unuse good
------------------------------------------------------------------------------
-- | @'take' n@ allows the first @n@ bytes to pass through the stream, and
-- then terminates.
take :: Monad m => Int -> Pipe ByteString ByteString m ()
take n = do
bs <- await
let n' = n - B.length bs
if n' > 0 then yield bs >> take n' else do
let (good, bad) = B.splitAt n bs
unuse bad
yield good
------------------------------------------------------------------------------
-- | @'takeWhile' p@ allows bytes to pass through the stream as long as they
-- match the predicate @p@, and terminates after the first byte that does not
-- match @p@.
takeWhile :: Monad m => (Word8 -> Bool) -> Pipe ByteString ByteString m ()
takeWhile p = go
where
go = do
bs <- await
let (good, bad) = B.span p bs
yield good
if B.null bad then go else unuse bad
------------------------------------------------------------------------------
-- | @'takeUntilByte' c@ allows bytes to pass through the stream until the
-- byte @w@ is found in the stream. This is equivalent to 'takeWhile'
-- @(not . (==c))@, but is more efficient.
takeUntilByte :: Monad m => Word8 -> Pipe ByteString ByteString m ()
takeUntilByte w = go
where
go = do
bs <- await
let (good, bad) = B.breakByte w bs
yield good
if B.null bad then go else unuse bad
------------------------------------------------------------------------------
-- | Split the input bytes into lines. This makes each input chunk correspend
-- to exactly one line, even if that line was originally spread across several
-- chunks.
lines :: Monad m => Pipe ByteString ByteString m r
lines = forever $ do
((takeUntilByte 10 >> return B.empty) >+> consume') >>= yield
drop 1
------------------------------------------------------------------------------
-- | Split the input bytes into words. This makes each input chunk correspend
-- to exactly one word, even if that word was originally spread across several
-- chunks.
words :: Monad m => Pipe ByteString ByteString m r
words = forever $ do
((takeUntilByte 32 >> return B.empty) >+> consume') >>= yield
drop 1
|
duairc/pipes
|
src/Control/Pipe/Binary.hs
|
bsd-3-clause
| 11,736 | 0 | 17 | 2,403 | 2,635 | 1,384 | 1,251 | 177 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Database.Sqroll.TH (
initializeAllTablesDec
) where
import Database.Sqroll.Internal (Sqroll, HasTable, sqrollInitializeTable)
import Data.Maybe
import Language.Haskell.TH
-- | create a function 'initializeAllTables :: Sqroll -> IO ()' that, when run,
-- will initialize tables for all datatypes with HasTable instances in scope in
-- the module where this is spliced.
--
-- Currently, only data types with kind * will be included. So if the
-- following are in scope:
--
-- > instance HasTable Foo
-- > instance HasTable (Bar Int)
-- > instance HasTable (Foo,Foo)
--
-- initializeAllTables will only initialize the table for 'Foo'
initializeAllTablesDec :: Q [Dec]
initializeAllTablesDec = do
ClassI _ instances <- reify ''HasTable
sqNm <- newName "sqroll"
let sqP = varP sqNm
sqE = varE sqNm
exprs = catMaybes $ map fromAppT instances
let allTheExprs = lamE [sqP] $ foldr accExpr [| return () |] exprs
accExpr x acc = [| sqrollInitializeTable $(sqE) $(x) >> $(acc) |]
[d| initializeAllTables :: Sqroll -> IO (); initializeAllTables = $(allTheExprs) |]
fromAppT :: Dec -> Maybe ExpQ
fromAppT (InstanceD _ (AppT (ConT cls) (ConT typName)) _) | cls == ''HasTable = Just $ sigE [|undefined|] (conT typName)
-- TODO: match on newtype and data instances
fromAppT _ = Nothing
|
pacak/sqroll
|
src/Database/Sqroll/TH.hs
|
bsd-3-clause
| 1,364 | 0 | 12 | 260 | 268 | 148 | 120 | 19 | 1 |
{-# LANGUAGE RankNTypes, GADTs,
MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, AllowAmbiguousTypes #-}
module HLib61
where
import Control.Category ((>>>))
import Control.Monad ((>=>))
import Data.Dynamic
type UserInput = String
class (Read n, Show n) => Serializable n
instance forall n. (Read n, Show n) => Serializable [n]
instance (Serializable a, Serializable b) => Serializable (a, b)
instance Serializable Int
instance Serializable ()
data Node s o = QNode {
execQNode :: (Serializable s, Serializable o) => s -> UserInput -> Target o
} | ANode {
execANode :: (Serializable s, Serializable o) => s -> Target o
}
data Target o where
Continuation :: forall o o'. (Serializable o, Serializable o') => Target (Node o o')
Recursion :: forall o o'. (Serializable o, Serializable o') => Target (Node o o')
EOD :: forall o. (Serializable o) => o -> Target o
Start :: forall o o'. {- (Serializable o, Serializable o') => -} (o' -> o) -> Node () o' -> Target o
Fork :: forall o o' o''. (Serializable o, Serializable o', Serializable o'') => o' -> Node o' o'' -> Node o'' o -> Target o
-- data Target o =
-- forall o'. Continuation (Node o o')
-- | forall o'. Recursion (Node o o')
-- | EOD o
-- | forall o'. Start (o' -> o) (Node () o')
-- | forall o' o''. Fork o' (Node o' o'') (Node o'' o)
askForANumber :: Node () Int
askForANumber = QNode {
execQNode = const $ EOD . read
}
getTwoNumbers :: Node [Int] [Int]
getTwoNumbers = ANode {
-- execQNode = \ s -> if length s < 2 then (3:s, Recursion getTwoNumbers) else (s, EOD)
execANode = \ s -> if length s < 2 then Start (:s) askForANumber else EOD s
}
getOperation :: Node () String
getOperation = QNode {
-- what do you want to do with these numbers?
execQNode = const EOD
}
getTwoNumbersAndOperation :: Node () ([Int], String)
getTwoNumbersAndOperation = ANode {
-- give us two numbers and an operation
execANode = const $ Fork [] getTwoNumbers makeOperation
}
makeOperation :: Node [Int] ([Int], String)
makeOperation = ANode {
-- mempty
execANode = \ s -> Start (\ b -> (s, b)) getOperation
}
applyOperation :: Node ([Int], String) Int
applyOperation = ANode {
-- and the result is
execANode = \ (num, op) -> EOD $ sum num
}
someOperation :: Node () Int
someOperation = ANode {
execANode = const $ Fork () getTwoNumbersAndOperation applyOperation
}
execNode :: (Serializable s, Serializable o) => s -> Node s o -> IO (Target o)
execNode s (QNode f) = do
i <- getLine
return $ f s i
execNode s (ANode f) = return $ f s
data ConversatioNodes n where
SomeOperation :: ConversatioNodes (Node () Int)
GetTwoNumbersAndOperation :: ConversatioNodes (Node () ([Int], String))
getNode :: ConversatioNodes n -> n
getNode SomeOperation = someOperation
getNode GetTwoNumbersAndOperation = getTwoNumbersAndOperation
getNode' :: String -> Dynamic
getNode' "A" = toDyn askForANumber
class (Serializable s, Serializable o) => Executable n s o where
exec :: n -> s -> (UserInput -> Target o)
instance (Serializable i, Serializable o) => Executable (Node i o) i o where
exec (ANode f) = const . f
exec (QNode f) = f
-- woo :: (Executable (Node [Int] [Int]) s o, Executable (Node () Int) s o) => String -> s -> UserInput -> Target o
woo "A" = exec askForANumber -- someOperation
woo "B" = exec getTwoNumbers
woo "C" = exec someOperation
-- woo = maybe (return $ EOD 0) id (execNode () <$> Just askForANumber)
-- woo' :: IO (Target Int)
-- woo' :: (Executable (Node [Int] [Int]) () o, Executable (Node () Int) () o) => Target o
woo' key s = do
r <- getLine
return $ woo key s r
hoop :: (Executable (Node [Int] [Int]) () o, Executable (Node [Int] [Int]) s o, Executable (Node () Int) s o) => s -> UserInput -> Target o
hoop = woo "A"
--
-- boop :: IO ()
-- boop = getLine >>= \r -> let a = hoop () r in return ()
-- tee :: (Serializable i, Serializable o, Executable n i o) => n -> IO ()
-- tee n = getLine >>= \r -> let a = exec askForANumber () r in return ()
data Func where
Func :: (A -> B) -> Func
-- data B b where
-- BInt :: Int -> B Int
-- BString :: String -> B String
data A = AInt Int | AString String deriving (Show)
data B = BInt Int | BString String deriving (Show)
class Funcable f where
fexec :: (Show b) => f -> A -> B
instance Funcable Func where
fexec (Func f) = f
f1 :: Func
f1 = Func $ \ (AInt i) -> BInt $ i * 2
--
f2 :: Func
f2 = Func $ \ (AString i) -> BString $ i ++ "!"
-- getF :: (Funcable f, Show a, Show b) => String -> a -> B
getF "f1" = f1
getF "f2" = f2
-- getF "f2" = f2
|
homam/fsm-conversational-ui
|
src/HLib61.hs
|
bsd-3-clause
| 4,576 | 0 | 12 | 982 | 1,429 | 777 | 652 | -1 | -1 |
module Evolution.Internal
( EvolutionRules
( EvolutionRules
, mutation
, breeding
, selection
, deaths
, expression
, optimumForGeneration
)
, evolution
) where
import Data.Random
import Data.Functor ()
import Individual
import Population
import Phenotype
import Expression
data EvolutionRules =
EvolutionRules
{ mutation :: ![Mutation]
, breeding :: ![Phenotype -> Int -> Breeding]
, selection :: ![Phenotype -> Selection]
, deaths :: ![Int -> PopulationChange]
, expression :: !ExpressionStrategy
, optimumForGeneration :: !(Int -> Phenotype)
}
step :: [PopulationChange] -> RVar [Individual] -> RVar [Individual]
step changes population = foldl (>>=) population changes
evolution :: Int -> EvolutionRules -> RVar Population -> RVar [Population]
evolution 0 _ _ = return []
evolution genToGen spec population = do
p <- population
let g = 1 + generation p
let todayOptimum = optimumForGeneration spec g
let breedingForGeneration = map (\f -> f todayOptimum g) $ breeding spec
let mutationForGeneration = mutation spec
let selectionForGeneration = map (\f -> f todayOptimum) $ selection spec
let deathForGeneration = map (\f -> f g) $ deaths spec
let stepAlgo = breedingForGeneration ++
mutationForGeneration ++
selectionForGeneration ++
deathForGeneration
newIndividuals <- step stepAlgo $ individuals <$> population
rest <- evolution (genToGen - 1) spec <$> return $ Population g newIndividuals
return (p : rest)
|
satai/FrozenBeagle
|
Simulation/Lib/src/Evolution/Internal.hs
|
bsd-3-clause
| 1,805 | 0 | 14 | 596 | 468 | 244 | 224 | 57 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{- |
Module : Verifier.SAW.Cryptol.Monadify
Copyright : Galois, Inc. 2021
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
This module implements a "monadification" transformation, which converts "pure"
SAW core terms that use inconsistent operations like @fix@ and convert them to
monadic SAW core terms that use monadic versions of these operations that are
consistent. The monad that is used is the @CompM@ monad that is axiomatized in
the SAW cxore prelude. This is only a partial transformation, meaning that it
will fail on some SAW core terms. Specifically, it requires that all
applications @f arg@ in a term either have a non-dependent function type for @f@
(i.e., a function with type @'Pi' x a b@ where @x@ does not occur in @b@) or a
pure argument @arg@ that does not use any of the inconsistent operations.
FIXME: explain this better
Type-level translation:
MT(Pi x (sort 0) b) = Pi x (sort 0) CompMT(b)
MT(Pi x Num b) = Pi x Num CompMT(b)
MT(Pi _ a b) = MT(a) -> CompMT(b)
MT(#(a,b)) = #(MT(a),MT(b))
MT(seq n a) = mseq n MT(a)
MT(f arg) = f MT(arg) -- NOTE: f must be a pure function!
MT(cnst) = cnst
MT(dt args) = dt MT(args)
MT(x) = x
MT(_) = error
CompMT(tp = Pi _ _ _) = MT(tp)
CompMT(n : Num) = n
CompMT(tp) = CompM MT(tp)
Term-level translation:
MonArg(t : tp) ==> MT(tp)
MonArg(t) =
case Mon(t) of
m : CompM MT(a) => shift \k -> m >>= \x -> k x
_ => t
Mon(t : tp) ==> MT(tp) or CompMT(tp) (which are the same type for pis)
Mon((f : Pi x a b) arg) = Mon(f) MT(arg)
Mon((f : Pi _ a b) arg) = Mon(f) MonArg(arg)
Mon(Lambda x a t) = Lambda x MT(a) Mon(t)
Mon((t,u)) = (MonArg(t),MonArg(u))
Mon(c args) = c MonArg(args)
Mon(x) = x
Mon(fix) = fixM (of some form...)
Mon(cnst) = cnstM if cnst is impure and monadifies to constM
Mon(cnst) = cnst otherwise
-}
module Verifier.SAW.Cryptol.Monadify where
import Data.Maybe
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Cont
import qualified Control.Monad.Fail as Fail
-- import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.Text as T
import qualified Text.URI as URI
import Verifier.SAW.Name
import Verifier.SAW.Term.Functor
import Verifier.SAW.SharedTerm
import Verifier.SAW.OpenTerm
-- import Verifier.SAW.SCTypeCheck
import Verifier.SAW.Recognizer
-- import Verifier.SAW.Position
import Verifier.SAW.Cryptol.PreludeM
import Debug.Trace
-- Type-check the Prelude, Cryptol, and CryptolM modules at compile time
{-
import Language.Haskell.TH
import Verifier.SAW.Cryptol.Prelude
$(runIO (mkSharedContext >>= \sc ->
scLoadPreludeModule sc >> scLoadCryptolModule sc >>
scLoadCryptolMModule sc >> return []))
-}
----------------------------------------------------------------------
-- * Typing All Subterms
----------------------------------------------------------------------
-- | A SAW core term where all of the subterms are typed
data TypedSubsTerm
= TypedSubsTerm { tpSubsIndex :: Maybe TermIndex,
tpSubsFreeVars :: BitSet,
tpSubsTermF :: TermF TypedSubsTerm,
tpSubsTypeF :: TermF TypedSubsTerm,
tpSubsSort :: Sort }
-- | Convert a 'Term' to a 'TypedSubsTerm'
typeAllSubterms :: SharedContext -> Term -> IO TypedSubsTerm
typeAllSubterms = error "FIXME HERE"
-- | Convert a 'TypedSubsTerm' back to a 'Term'
typedSubsTermTerm :: TypedSubsTerm -> Term
typedSubsTermTerm = error "FIXME HERE"
-- | Get the type of a 'TypedSubsTerm' as a 'TypedSubsTerm'
typedSubsTermType :: TypedSubsTerm -> TypedSubsTerm
typedSubsTermType tst =
TypedSubsTerm { tpSubsIndex = Nothing, tpSubsFreeVars = tpSubsFreeVars tst,
tpSubsTermF = tpSubsTypeF tst,
tpSubsTypeF = FTermF (Sort (tpSubsSort tst) False),
tpSubsSort = sortOf (tpSubsSort tst) }
-- | Count the number of right-nested pi-abstractions of a 'TypedSubsTerm'
typedSubsTermArity :: TypedSubsTerm -> Int
typedSubsTermArity (TypedSubsTerm { tpSubsTermF = Pi _ _ tst }) =
1 + typedSubsTermArity tst
typedSubsTermArity _ = 0
-- | Count the number of right-nested pi abstractions in a term, which
-- represents a type. This assumes that the type is in WHNF.
typeArity :: Term -> Int
typeArity tp = length $ fst $ asPiList tp
class ToTerm a where
toTerm :: a -> Term
instance ToTerm Term where
toTerm = id
instance ToTerm TypedSubsTerm where
toTerm = typedSubsTermTerm
unsharedApply :: Term -> Term -> Term
unsharedApply f arg = Unshared $ App f arg
----------------------------------------------------------------------
-- * Monadifying Types
----------------------------------------------------------------------
-- | Test if a 'Term' is a first-order function type
isFirstOrderType :: Term -> Bool
isFirstOrderType (asPi -> Just (_, asPi -> Just _, _)) = False
isFirstOrderType (asPi -> Just (_, _, tp_out)) = isFirstOrderType tp_out
isFirstOrderType _ = True
-- | A global definition, which is either a primitive or a constant. As
-- described in the documentation for 'ExtCns', the names need not be unique,
-- but the 'VarIndex' is, and this is what is used to index 'GlobalDef's.
data GlobalDef = GlobalDef { globalDefName :: NameInfo,
globalDefIndex :: VarIndex,
globalDefType :: Term,
globalDefTerm :: Term,
globalDefBody :: Maybe Term }
instance Eq GlobalDef where
gd1 == gd2 = globalDefIndex gd1 == globalDefIndex gd2
instance Ord GlobalDef where
compare gd1 gd2 = compare (globalDefIndex gd1) (globalDefIndex gd2)
instance Show GlobalDef where
show = show . globalDefName
-- | Get the 'String' name of a 'GlobalDef'
globalDefString :: GlobalDef -> String
globalDefString = T.unpack . toAbsoluteName . globalDefName
-- | Build an 'OpenTerm' from a 'GlobalDef'
globalDefOpenTerm :: GlobalDef -> OpenTerm
globalDefOpenTerm = closedOpenTerm . globalDefTerm
-- | Recognize a named global definition, including its type
asTypedGlobalDef :: Recognizer Term GlobalDef
asTypedGlobalDef t =
case unwrapTermF t of
FTermF (Primitive pn) ->
Just $ GlobalDef (ModuleIdentifier $
primName pn) (primVarIndex pn) (primType pn) t Nothing
Constant ec body ->
Just $ GlobalDef (ecName ec) (ecVarIndex ec) (ecType ec) t body
FTermF (ExtCns ec) ->
Just $ GlobalDef (ecName ec) (ecVarIndex ec) (ecType ec) t Nothing
_ -> Nothing
data MonKind = MKType Sort | MKNum | MKFun MonKind MonKind deriving Eq
-- | Convert a kind to a SAW core sort, if possible
monKindToSort :: MonKind -> Maybe Sort
monKindToSort (MKType s) = Just s
monKindToSort _ = Nothing
-- | Convert a 'MonKind' to the term it represents
monKindOpenTerm :: MonKind -> OpenTerm
monKindOpenTerm (MKType s) = sortOpenTerm s
monKindOpenTerm MKNum = dataTypeOpenTerm "Cryptol.Num" []
monKindOpenTerm (MKFun k1 k2) =
arrowOpenTerm "_" (monKindOpenTerm k1) (monKindOpenTerm k2)
data MonType
= MTyForall LocalName MonKind (MonType -> MonType)
| MTyArrow MonType MonType
| MTySeq OpenTerm MonType
| MTyPair MonType MonType
| MTyRecord [(FieldName, MonType)]
| MTyBase MonKind OpenTerm -- A "base type" or type var of a given kind
| MTyNum OpenTerm
-- | Make a base type of sort 0 from an 'OpenTerm'
mkMonType0 :: OpenTerm -> MonType
mkMonType0 = MTyBase (MKType $ mkSort 0)
-- | Make a 'MonType' for the Boolean type
boolMonType :: MonType
boolMonType = mkMonType0 $ globalOpenTerm "Prelude.Bool"
-- | Test that a monadification type is monomorphic, i.e., has no foralls
monTypeIsMono :: MonType -> Bool
monTypeIsMono (MTyForall _ _ _) = False
monTypeIsMono (MTyArrow tp1 tp2) = monTypeIsMono tp1 && monTypeIsMono tp2
monTypeIsMono (MTyPair tp1 tp2) = monTypeIsMono tp1 && monTypeIsMono tp2
monTypeIsMono (MTyRecord tps) = all (monTypeIsMono . snd) tps
monTypeIsMono (MTySeq _ tp) = monTypeIsMono tp
monTypeIsMono (MTyBase _ _) = True
monTypeIsMono (MTyNum _) = True
-- | Test if a monadification type @tp@ is considered a base type, meaning that
-- @CompMT(tp) = CompM MT(tp)@
isBaseType :: MonType -> Bool
isBaseType (MTyForall _ _ _) = False
isBaseType (MTyArrow _ _) = False
isBaseType (MTySeq _ _) = True
isBaseType (MTyPair _ _) = True
isBaseType (MTyRecord _) = True
isBaseType (MTyBase (MKType _) _) = True
isBaseType (MTyBase _ _) = True
isBaseType (MTyNum _) = False
-- | If a 'MonType' is a type-level number, return its 'OpenTerm', otherwise
-- return 'Nothing'
monTypeNum :: MonType -> Maybe OpenTerm
monTypeNum (MTyNum t) = Just t
monTypeNum (MTyBase MKNum t) = Just t
monTypeNum _ = Nothing
-- | Get the kind of a 'MonType', assuming it has one
monTypeKind :: MonType -> Maybe MonKind
monTypeKind (MTyForall _ _ _) = Nothing
monTypeKind (MTyArrow t1 t2) =
do s1 <- monTypeKind t1 >>= monKindToSort
s2 <- monTypeKind t2 >>= monKindToSort
return $ MKType $ maxSort [s1, s2]
monTypeKind (MTyPair tp1 tp2) =
do sort1 <- monTypeKind tp1 >>= monKindToSort
sort2 <- monTypeKind tp2 >>= monKindToSort
return $ MKType $ maxSort [sort1, sort2]
monTypeKind (MTyRecord tps) =
do sorts <- mapM (monTypeKind . snd >=> monKindToSort) tps
return $ MKType $ maxSort sorts
monTypeKind (MTySeq _ tp) =
do sort <- monTypeKind tp >>= monKindToSort
return $ MKType sort
monTypeKind (MTyBase k _) = Just k
monTypeKind (MTyNum _) = Just MKNum
-- | Get the 'Sort' @s@ of a 'MonType' if it has kind @'MKType' s@
monTypeSort :: MonType -> Maybe Sort
monTypeSort = monTypeKind >=> monKindToSort
-- | Convert a SAW core 'Term' to a monadification kind, if possible
monadifyKind :: Term -> Maybe MonKind
monadifyKind (asDataType -> Just (num, []))
| primName num == "Cryptol.Num" = return MKNum
monadifyKind (asSort -> Just s) = return $ MKType s
monadifyKind (asPi -> Just (_, tp_in, tp_out)) =
MKFun <$> monadifyKind tp_in <*> monadifyKind tp_out
monadifyKind _ = Nothing
-- | Get the kind of a type constructor with kind @k@ applied to type @t@, or
-- return 'Nothing' if the kinds do not line up
applyKind :: MonKind -> MonType -> Maybe MonKind
applyKind (MKFun k1 k2) t
| Just kt <- monTypeKind t
, kt == k1 = Just k2
applyKind _ _ = Nothing
-- | Perform 'applyKind' for 0 or more argument types
applyKinds :: MonKind -> [MonType] -> Maybe MonKind
applyKinds = foldM applyKind
-- | Convert a 'MonType' to the argument type @MT(tp)@ it represents
toArgType :: MonType -> OpenTerm
toArgType (MTyForall x k body) =
piOpenTerm x (monKindOpenTerm k) (\tp -> toCompType (body $ MTyBase k tp))
toArgType (MTyArrow t1 t2) =
arrowOpenTerm "_" (toArgType t1) (toCompType t2)
toArgType (MTySeq n t) =
applyOpenTermMulti (globalOpenTerm "CryptolM.mseq") [n, toArgType t]
toArgType (MTyPair mtp1 mtp2) =
pairTypeOpenTerm (toArgType mtp1) (toArgType mtp2)
toArgType (MTyRecord tps) =
recordTypeOpenTerm $ map (\(f,tp) -> (f, toArgType tp)) tps
toArgType (MTyBase _ t) = t
toArgType (MTyNum n) = n
-- | Convert a 'MonType' to the computation type @CompMT(tp)@ it represents
toCompType :: MonType -> OpenTerm
toCompType mtp@(MTyForall _ _ _) = toArgType mtp
toCompType mtp@(MTyArrow _ _) = toArgType mtp
toCompType mtp = applyOpenTerm (globalOpenTerm "Prelude.CompM") (toArgType mtp)
-- | The mapping for monadifying Cryptol typeclasses
-- FIXME: this is no longer needed, as it is now the identity
typeclassMonMap :: [(Ident,Ident)]
typeclassMonMap =
[("Cryptol.PEq", "Cryptol.PEq"),
("Cryptol.PCmp", "Cryptol.PCmp"),
("Cryptol.PSignedCmp", "Cryptol.PSignedCmp"),
("Cryptol.PZero", "Cryptol.PZero"),
("Cryptol.PLogic", "Cryptol.PLogic"),
("Cryptol.PRing", "Cryptol.PRing"),
("Cryptol.PIntegral", "Cryptol.PIntegral"),
("Cryptol.PLiteral", "Cryptol.PLiteral")]
-- | A context of local variables used for monadifying types, which includes the
-- variable names, their original types (before monadification), and, if their
-- types corespond to 'MonKind's, a local 'MonType' that quantifies over them.
--
-- NOTE: the reason this type is different from 'MonadifyCtx', the context type
-- for monadifying terms, is that monadifying arrow types does not introduce a
-- local 'MonTerm' argument, since they are not dependent functions and so do
-- not use a HOAS encoding.
type MonadifyTypeCtx = [(LocalName,Term,Maybe MonType)]
-- | Pretty-print a 'Term' relative to a 'MonadifyTypeCtx'
ppTermInTypeCtx :: MonadifyTypeCtx -> Term -> String
ppTermInTypeCtx ctx t =
scPrettyTermInCtx defaultPPOpts (map (\(x,_,_) -> x) ctx) t
-- | Extract the variables and their original types from a 'MonadifyTypeCtx'
typeCtxPureCtx :: MonadifyTypeCtx -> [(LocalName,Term)]
typeCtxPureCtx = map (\(x,tp,_) -> (x,tp))
-- | Make a monadification type that is to be considered a base type
mkTermBaseType :: MonadifyTypeCtx -> MonKind -> Term -> MonType
mkTermBaseType ctx k t =
MTyBase k $ openOpenTerm (typeCtxPureCtx ctx) t
-- | Monadify a type and convert it to its corresponding argument type
monadifyTypeArgType :: MonadifyTypeCtx -> Term -> OpenTerm
monadifyTypeArgType ctx t = toArgType $ monadifyType ctx t
-- | Apply a monadified type to a type or term argument in the sense of
-- 'applyPiOpenTerm', meaning give the type of applying @f@ of a type to a
-- particular argument @arg@
applyMonType :: MonType -> Either MonType ArgMonTerm -> MonType
applyMonType (MTyArrow _ tp_ret) (Right _) = tp_ret
applyMonType (MTyForall _ _ f) (Left mtp) = f mtp
applyMonType _ _ = error "applyMonType: application at incorrect type"
-- | Convert a SAW core 'Term' to a monadification type
monadifyType :: MonadifyTypeCtx -> Term -> MonType
{-
monadifyType ctx t
| trace ("\nmonadifyType:\n" ++ ppTermInTypeCtx ctx t) False = undefined
-}
monadifyType ctx (asPi -> Just (x, tp_in, tp_out))
| Just k <- monadifyKind tp_in =
MTyForall x k (\tp' -> monadifyType ((x,tp_in,Just tp'):ctx) tp_out)
monadifyType ctx tp@(asPi -> Just (_, _, tp_out))
| inBitSet 0 (looseVars tp_out) =
error ("monadifyType: " ++
"dependent function type with non-kind argument type: " ++
ppTermInTypeCtx ctx tp)
monadifyType ctx tp@(asPi -> Just (x, tp_in, tp_out)) =
MTyArrow (monadifyType ctx tp_in)
(monadifyType ((x,tp,Nothing):ctx) tp_out)
monadifyType ctx (asPairType -> Just (tp1, tp2)) =
MTyPair (monadifyType ctx tp1) (monadifyType ctx tp2)
monadifyType ctx (asRecordType -> Just tps) =
MTyRecord $ map (\(fld,tp) -> (fld, monadifyType ctx tp)) $ Map.toList tps
monadifyType ctx (asDataType -> Just (eq_pn, [k_trm, tp1, tp2]))
| primName eq_pn == "Prelude.Eq"
, isJust (monadifyKind k_trm) =
-- NOTE: technically this is a Prop and not a sort 0, but it doesn't matter
mkMonType0 $ dataTypeOpenTerm "Prelude.Eq" [monadifyTypeArgType ctx tp1,
monadifyTypeArgType ctx tp2]
monadifyType ctx (asDataType -> Just (pn, args))
| Just pn_k <- monadifyKind (primType pn)
, margs <- map (monadifyType ctx) args
, Just k_out <- applyKinds pn_k margs =
-- NOTE: this case only recognizes data types whose arguments are all types
-- and/or Nums
MTyBase k_out $ dataTypeOpenTerm (primName pn) (map toArgType margs)
monadifyType ctx (asVectorType -> Just (len, tp)) =
let lenOT = openOpenTerm (typeCtxPureCtx ctx) len in
MTySeq (ctorOpenTerm "Cryptol.TCNum" [lenOT]) $ monadifyType ctx tp
monadifyType ctx tp@(asApplyAll -> ((asGlobalDef -> Just seq_id), [n, a]))
| seq_id == "Cryptol.seq" =
case monTypeNum (monadifyType ctx n) of
Just n_trm -> MTySeq n_trm (monadifyType ctx a)
Nothing ->
error ("Monadify type: not a number: " ++ ppTermInTypeCtx ctx n
++ " in type: " ++ ppTermInTypeCtx ctx tp)
monadifyType ctx (asApp -> Just ((asGlobalDef -> Just f), arg))
| Just f_trans <- lookup f typeclassMonMap =
MTyBase (MKType $ mkSort 1) $
applyOpenTerm (globalOpenTerm f_trans) $ monadifyTypeArgType ctx arg
monadifyType _ (asGlobalDef -> Just bool_id)
| bool_id == "Prelude.Bool" =
mkMonType0 (globalOpenTerm "Prelude.Bool")
{-
monadifyType ctx (asApplyAll -> (f, args))
| Just glob <- asTypedGlobalDef f
, Just ec_k <- monadifyKind $ globalDefType glob
, margs <- map (monadifyType ctx) args
, Just k_out <- applyKinds ec_k margs =
MTyBase k_out (applyOpenTermMulti (globalDefOpenTerm glob) $
map toArgType margs)
-}
monadifyType ctx tp@(asCtor -> Just (pn, _))
| primName pn == "Cryptol.TCNum" || primName pn == "Cryptol.TCInf" =
MTyNum $ openOpenTerm (typeCtxPureCtx ctx) tp
monadifyType ctx (asLocalVar -> Just i)
| i < length ctx
, (_,_,Just tp) <- ctx!!i = tp
monadifyType ctx tp =
error ("monadifyType: not a valid type for monadification: "
++ ppTermInTypeCtx ctx tp)
----------------------------------------------------------------------
-- * Monadified Terms
----------------------------------------------------------------------
-- | A representation of a term that has been translated to argument type
-- @MT(tp)@
data ArgMonTerm
-- | A monadification term of a base type @MT(tp)@
= BaseMonTerm MonType OpenTerm
-- | A monadification term of non-depedent function type
| FunMonTerm LocalName MonType MonType (ArgMonTerm -> MonTerm)
-- | A monadification term of polymorphic type
| ForallMonTerm LocalName MonKind (MonType -> MonTerm)
-- | A representation of a term that has been translated to computational type
-- @CompMT(tp)@
data MonTerm
= ArgMonTerm ArgMonTerm
| CompMonTerm MonType OpenTerm
-- | Get the monadification type of a monadification term
class GetMonType a where
getMonType :: a -> MonType
instance GetMonType ArgMonTerm where
getMonType (BaseMonTerm tp _) = tp
getMonType (ForallMonTerm x k body) = MTyForall x k (getMonType . body)
getMonType (FunMonTerm _ tp_in tp_out _) = MTyArrow tp_in tp_out
instance GetMonType MonTerm where
getMonType (ArgMonTerm t) = getMonType t
getMonType (CompMonTerm tp _) = tp
-- | Convert a monadification term to a SAW core term of type @CompMT(tp)@
class ToCompTerm a where
toCompTerm :: a -> OpenTerm
instance ToCompTerm ArgMonTerm where
toCompTerm (BaseMonTerm mtp t) =
applyOpenTermMulti (globalOpenTerm "Prelude.returnM") [toArgType mtp, t]
toCompTerm (FunMonTerm x tp_in _ body) =
lambdaOpenTerm x (toArgType tp_in) (toCompTerm . body . fromArgTerm tp_in)
toCompTerm (ForallMonTerm x k body) =
lambdaOpenTerm x (monKindOpenTerm k) (toCompTerm . body . MTyBase k)
instance ToCompTerm MonTerm where
toCompTerm (ArgMonTerm amtrm) = toCompTerm amtrm
toCompTerm (CompMonTerm _ trm) = trm
-- | Convert an 'ArgMonTerm' to a SAW core term of type @MT(tp)@
toArgTerm :: ArgMonTerm -> OpenTerm
toArgTerm (BaseMonTerm _ t) = t
toArgTerm t = toCompTerm t
-- | Build a monadification term from a term of type @MT(tp)@
class FromArgTerm a where
fromArgTerm :: MonType -> OpenTerm -> a
instance FromArgTerm ArgMonTerm where
fromArgTerm (MTyForall x k body) t =
ForallMonTerm x k (\tp -> fromCompTerm (body tp) (applyOpenTerm t $
toArgType tp))
fromArgTerm (MTyArrow t1 t2) t =
FunMonTerm "_" t1 t2 (\x -> fromCompTerm t2 (applyOpenTerm t $ toArgTerm x))
fromArgTerm tp t = BaseMonTerm tp t
instance FromArgTerm MonTerm where
fromArgTerm mtp t = ArgMonTerm $ fromArgTerm mtp t
-- | Build a monadification term from a computational term of type @CompMT(tp)@
fromCompTerm :: MonType -> OpenTerm -> MonTerm
fromCompTerm mtp t | isBaseType mtp = CompMonTerm mtp t
fromCompTerm mtp t = ArgMonTerm $ fromArgTerm mtp t
-- | Build a monadification term from a function on terms which, when viewed as
-- a lambda, is a "semi-pure" function of the given monadification type, meaning
-- it maps terms of argument type @MT(tp)@ to an output value of argument type;
-- i.e., it has type @SemiP(tp)@, defined as:
--
-- > SemiP(Pi x (sort 0) b) = Pi x (sort 0) SemiP(b)
-- > SemiP(Pi x Num b) = Pi x Num SemiP(b)
-- > SemiP(Pi _ a b) = MT(a) -> SemiP(b)
-- > SemiP(a) = MT(a)
fromSemiPureTermFun :: MonType -> ([OpenTerm] -> OpenTerm) -> ArgMonTerm
fromSemiPureTermFun (MTyForall x k body) f =
ForallMonTerm x k $ \tp ->
ArgMonTerm $ fromSemiPureTermFun (body tp) (f . (toArgType tp:))
fromSemiPureTermFun (MTyArrow t1 t2) f =
FunMonTerm "_" t1 t2 $ \x ->
ArgMonTerm $ fromSemiPureTermFun t2 (f . (toArgTerm x:))
fromSemiPureTermFun tp f = BaseMonTerm tp (f [])
-- | Like 'fromSemiPureTermFun' but use a term rather than a term function
fromSemiPureTerm :: MonType -> OpenTerm -> ArgMonTerm
fromSemiPureTerm mtp t = fromSemiPureTermFun mtp (applyOpenTermMulti t)
-- | Build a 'MonTerm' that 'fail's when converted to a term
failMonTerm :: MonType -> String -> MonTerm
failMonTerm mtp str = fromArgTerm mtp (failOpenTerm str)
-- | Build an 'ArgMonTerm' that 'fail's when converted to a term
failArgMonTerm :: MonType -> String -> ArgMonTerm
failArgMonTerm tp str = fromArgTerm tp (failOpenTerm str)
-- | Apply a monadified term to a type or term argument
applyMonTerm :: MonTerm -> Either MonType ArgMonTerm -> MonTerm
applyMonTerm (ArgMonTerm (FunMonTerm _ _ _ f)) (Right arg) = f arg
applyMonTerm (ArgMonTerm (ForallMonTerm _ _ f)) (Left mtp) = f mtp
applyMonTerm _ _ = error "applyMonTerm: application at incorrect type"
-- | Apply a monadified term to 0 or more arguments
applyMonTermMulti :: MonTerm -> [Either MonType ArgMonTerm] -> MonTerm
applyMonTermMulti = foldl applyMonTerm
-- | Build a 'MonTerm' from a global of a given argument type
mkGlobalArgMonTerm :: MonType -> Ident -> ArgMonTerm
mkGlobalArgMonTerm tp ident = fromArgTerm tp (globalOpenTerm ident)
-- | Build a 'MonTerm' from a 'GlobalDef' of semi-pure type
mkSemiPureGlobalDefTerm :: GlobalDef -> ArgMonTerm
mkSemiPureGlobalDefTerm glob =
fromSemiPureTerm (monadifyType [] $
globalDefType glob) (globalDefOpenTerm glob)
-- | Build a 'MonTerm' from a constructor with the given 'PrimName'
mkCtorArgMonTerm :: PrimName Term -> ArgMonTerm
mkCtorArgMonTerm pn
| not (isFirstOrderType (primType pn)) =
failArgMonTerm (monadifyType [] $ primType pn)
("monadification failed: cannot handle constructor "
++ show (primName pn) ++ " with higher-order type")
mkCtorArgMonTerm pn =
fromSemiPureTermFun (monadifyType [] $ primType pn) (ctorOpenTerm $ primName pn)
----------------------------------------------------------------------
-- * Monadification Environments and Contexts
----------------------------------------------------------------------
-- | A monadification macro is a function that inspects its first @N@ arguments
-- before deciding how to monadify itself
data MonMacro = MonMacro {
macroNumArgs :: Int,
macroApply :: GlobalDef -> [Term] -> MonadifyM MonTerm }
-- | Make a simple 'MonMacro' that inspects 0 arguments and just returns a term
monMacro0 :: MonTerm -> MonMacro
monMacro0 mtrm = MonMacro 0 (\_ _ -> return mtrm)
-- | Make a 'MonMacro' that maps a named global to a global of semi-pure type.
-- (See 'fromSemiPureTermFun'.) Because we can't get access to the type of the
-- global until we apply the macro, we monadify its type at macro application
-- time.
semiPureGlobalMacro :: Ident -> Ident -> MonMacro
semiPureGlobalMacro from to =
MonMacro 0 $ \glob args ->
if globalDefName glob == ModuleIdentifier from && args == [] then
return $ ArgMonTerm $
fromSemiPureTerm (monadifyType [] $ globalDefType glob) (globalOpenTerm to)
else
error ("Monadification macro for " ++ show from ++ " applied incorrectly")
-- | Make a 'MonMacro' that maps a named global to a global of argument
-- type. Because we can't get access to the type of the global until we apply
-- the macro, we monadify its type at macro application time.
argGlobalMacro :: NameInfo -> Ident -> MonMacro
argGlobalMacro from to =
MonMacro 0 $ \glob args ->
if globalDefName glob == from && args == [] then
return $ ArgMonTerm $
mkGlobalArgMonTerm (monadifyType [] $ globalDefType glob) to
else
error ("Monadification macro for " ++ show from ++ " applied incorrectly")
-- | An environment of named primitives and how to monadify them
type MonadifyEnv = Map NameInfo MonMacro
-- | A context for monadifying 'Term's which maintains, for each deBruijn index
-- in scope, both its original un-monadified type along with either a 'MonTerm'
-- or 'MonType' for the translation of the variable to a local variable of
-- monadified type or monadified kind
type MonadifyCtx = [(LocalName,Term,Either MonType MonTerm)]
-- | Convert a 'MonadifyCtx' to a 'MonadifyTypeCtx'
ctxToTypeCtx :: MonadifyCtx -> MonadifyTypeCtx
ctxToTypeCtx = map (\(x,tp,arg) ->
(x,tp,case arg of
Left mtp -> Just mtp
Right _ -> Nothing))
-- | Pretty-print a 'Term' relative to a 'MonadifyCtx'
ppTermInMonCtx :: MonadifyCtx -> Term -> String
ppTermInMonCtx ctx t =
scPrettyTermInCtx defaultPPOpts (map (\(x,_,_) -> x) ctx) t
-- | A memoization table for monadifying terms
type MonadifyMemoTable = IntMap MonTerm
-- | The empty memoization table
emptyMemoTable :: MonadifyMemoTable
emptyMemoTable = IntMap.empty
----------------------------------------------------------------------
-- * The Monadification Monad
----------------------------------------------------------------------
-- | The read-only state of a monadification computation
data MonadifyROState = MonadifyROState {
-- | The monadification environment
monStEnv :: MonadifyEnv,
-- | The monadification context
monStCtx :: MonadifyCtx,
-- | The monadified return type of the top-level term being monadified
monStTopRetType :: OpenTerm
}
-- | The monad for monadifying SAW core terms
newtype MonadifyM a =
MonadifyM { unMonadifyM ::
ReaderT MonadifyROState (StateT MonadifyMemoTable
(Cont MonTerm)) a }
deriving (Functor, Applicative, Monad,
MonadReader MonadifyROState, MonadState MonadifyMemoTable)
instance Fail.MonadFail MonadifyM where
fail str =
do ret_tp <- topRetType
shiftMonadifyM $ \_ -> failMonTerm (mkMonType0 ret_tp) str
-- | Capture the current continuation and pass it to a function, which must
-- return the final computation result. Note that this is slightly differnet
-- from normal shift, and I think corresponds to the C operator, but my quick
-- googling couldn't find the right name...
shiftMonadifyM :: ((a -> MonTerm) -> MonTerm) -> MonadifyM a
shiftMonadifyM f = MonadifyM $ lift $ lift $ cont f
-- | Locally run a 'MonadifyM' computation with an empty memoization table,
-- making all binds be local to that computation, and return the result
resetMonadifyM :: OpenTerm -> MonadifyM MonTerm -> MonadifyM MonTerm
resetMonadifyM ret_tp m =
do ro_st <- ask
return $ runMonadifyM (monStEnv ro_st) (monStCtx ro_st) ret_tp m
-- | Get the monadified return type of the top-level term being monadified
topRetType :: MonadifyM OpenTerm
topRetType = monStTopRetType <$> ask
-- | Run a monadification computation
--
-- FIXME: document the arguments
runMonadifyM :: MonadifyEnv -> MonadifyCtx -> OpenTerm ->
MonadifyM MonTerm -> MonTerm
runMonadifyM env ctx top_ret_tp m =
let ro_st = MonadifyROState env ctx top_ret_tp in
runCont (evalStateT (runReaderT (unMonadifyM m) ro_st) emptyMemoTable) id
-- | Run a monadification computation using a mapping for identifiers that have
-- already been monadified and generate a SAW core term
runCompleteMonadifyM :: MonadIO m => SharedContext -> MonadifyEnv ->
Term -> MonadifyM MonTerm -> m Term
runCompleteMonadifyM sc env top_ret_tp m =
liftIO $ completeOpenTerm sc $ toCompTerm $
runMonadifyM env [] (toArgType $ monadifyType [] top_ret_tp) m
-- | Memoize a computation of the monadified term associated with a 'TermIndex'
memoizingM :: TermIndex -> MonadifyM MonTerm -> MonadifyM MonTerm
memoizingM i m =
(IntMap.lookup i <$> get) >>= \case
Just ret ->
return ret
Nothing ->
do ret <- m
modify (IntMap.insert i ret)
return ret
-- | Turn a 'MonTerm' of type @CompMT(tp)@ to a term of argument type @MT(tp)@
-- by inserting a monadic bind if the 'MonTerm' is computational
argifyMonTerm :: MonTerm -> MonadifyM ArgMonTerm
argifyMonTerm (ArgMonTerm mtrm) = return mtrm
argifyMonTerm (CompMonTerm mtp trm) =
do let tp = toArgType mtp
top_ret_tp <- topRetType
shiftMonadifyM $ \k ->
CompMonTerm (mkMonType0 top_ret_tp) $
applyOpenTermMulti (globalOpenTerm "Prelude.bindM")
[tp, top_ret_tp, trm,
lambdaOpenTerm "x" tp (toCompTerm . k . fromArgTerm mtp)]
-- | Build a proof of @isFinite n@ by calling @assertFiniteM@ and binding the
-- result to an 'ArgMonTerm'
assertIsFinite :: MonType -> MonadifyM ArgMonTerm
assertIsFinite (MTyNum n) =
argifyMonTerm (CompMonTerm
(mkMonType0 (applyOpenTerm
(globalOpenTerm "CryptolM.isFinite") n))
(applyOpenTerm (globalOpenTerm "CryptolM.assertFiniteM") n))
assertIsFinite _ =
fail ("assertIsFinite applied to non-Num argument")
----------------------------------------------------------------------
-- * Monadification
----------------------------------------------------------------------
-- | Monadify a type in the context of the 'MonadifyM' monad
monadifyTypeM :: Term -> MonadifyM MonType
monadifyTypeM tp =
do ctx <- monStCtx <$> ask
return $ monadifyType (ctxToTypeCtx ctx) tp
-- | Monadify a term to a monadified term of argument type
monadifyArg :: Maybe MonType -> Term -> MonadifyM ArgMonTerm
monadifyArg mtp t = monadifyTerm mtp t >>= argifyMonTerm
-- | Monadify a term to argument type and convert back to a term
monadifyArgTerm :: Maybe MonType -> Term -> MonadifyM OpenTerm
monadifyArgTerm mtp t = toArgTerm <$> monadifyArg mtp t
-- | Monadify a term
monadifyTerm :: Maybe MonType -> Term -> MonadifyM MonTerm
{-
monadifyTerm _ t
| trace ("Monadifying term: " ++ showTerm t) False
= undefined
-}
monadifyTerm mtp t@(STApp { stAppIndex = ix }) =
memoizingM ix $ monadifyTerm' mtp t
monadifyTerm mtp t =
monadifyTerm' mtp t
-- | The main implementation of 'monadifyTerm', which monadifies a term given an
-- optional monadification type. The type must be given for introduction forms
-- (i.e.,, lambdas, pairs, and records), but is optional for elimination forms
-- (i.e., applications, projections, and also in this case variables). Note that
-- this means monadification will fail on terms with beta or tuple redexes.
monadifyTerm' :: Maybe MonType -> Term -> MonadifyM MonTerm
monadifyTerm' (Just mtp) t@(asLambda -> Just _) =
ask >>= \(MonadifyROState { monStEnv = env, monStCtx = ctx }) ->
return $ monadifyLambdas env ctx mtp t
{-
monadifyTerm' (Just mtp@(MTyForall _ _ _)) t =
ask >>= \ro_st ->
get >>= \table ->
return $ monadifyLambdas (monStEnv ro_st) table (monStCtx ro_st) mtp t
monadifyTerm' (Just mtp@(MTyArrow _ _)) t =
ask >>= \ro_st ->
get >>= \table ->
return $ monadifyLambdas (monStEnv ro_st) table (monStCtx ro_st) mtp t
-}
monadifyTerm' (Just mtp@(MTyPair mtp1 mtp2)) (asPairValue ->
Just (trm1, trm2)) =
fromArgTerm mtp <$> (pairOpenTerm <$>
monadifyArgTerm (Just mtp1) trm1 <*>
monadifyArgTerm (Just mtp2) trm2)
monadifyTerm' (Just mtp@(MTyRecord fs_mtps)) (asRecordValue -> Just trm_map)
| length fs_mtps == Map.size trm_map
, (fs,mtps) <- unzip fs_mtps
, Just trms <- mapM (\f -> Map.lookup f trm_map) fs =
fromArgTerm mtp <$> recordOpenTerm <$> zip fs <$>
zipWithM monadifyArgTerm (map Just mtps) trms
monadifyTerm' _ (asPairSelector -> Just (trm, False)) =
do mtrm <- monadifyArg Nothing trm
mtp <- case getMonType mtrm of
MTyPair t _ -> return t
_ -> fail "Monadification failed: projection on term of non-pair type"
return $ fromArgTerm mtp $
pairLeftOpenTerm $ toArgTerm mtrm
monadifyTerm' (Just mtp@(MTySeq n mtp_elem)) (asFTermF ->
Just (ArrayValue _ trms)) =
do trms' <- traverse (monadifyArgTerm $ Just mtp_elem) trms
return $ fromArgTerm mtp $
applyOpenTermMulti (globalOpenTerm "CryptolM.seqToMseq")
[n, toArgType mtp_elem,
flatOpenTerm $ ArrayValue (toArgType mtp_elem) trms']
monadifyTerm' _ (asPairSelector -> Just (trm, True)) =
do mtrm <- monadifyArg Nothing trm
mtp <- case getMonType mtrm of
MTyPair _ t -> return t
_ -> fail "Monadification failed: projection on term of non-pair type"
return $ fromArgTerm mtp $
pairRightOpenTerm $ toArgTerm mtrm
monadifyTerm' _ (asRecordSelector -> Just (trm, fld)) =
do mtrm <- monadifyArg Nothing trm
mtp <- case getMonType mtrm of
MTyRecord mtps | Just mtp <- lookup fld mtps -> return mtp
_ -> fail ("Monadification failed: " ++
"record projection on term of incorrect type")
return $ fromArgTerm mtp $ projRecordOpenTerm (toArgTerm mtrm) fld
monadifyTerm' _ (asLocalVar -> Just ix) =
(monStCtx <$> ask) >>= \case
ctx | ix >= length ctx -> fail "Monadification failed: vaiable out of scope!"
ctx | (_,_,Right mtrm) <- ctx !! ix -> return mtrm
_ -> fail "Monadification failed: type variable used in term position!"
monadifyTerm' _ (asCtor -> Just (pn, args)) =
monadifyApply (ArgMonTerm $ mkCtorArgMonTerm pn) args
monadifyTerm' _ (asApplyAll -> (asTypedGlobalDef -> Just glob, args)) =
(Map.lookup (globalDefName glob) <$> monStEnv <$> ask) >>= \case
Just macro ->
do let (macro_args, reg_args) = splitAt (macroNumArgs macro) args
mtrm_f <- macroApply macro glob macro_args
monadifyApply mtrm_f reg_args
Nothing -> error ("Monadification failed: unhandled constant: "
++ globalDefString glob)
monadifyTerm' _ (asApp -> Just (f, arg)) =
do mtrm_f <- monadifyTerm Nothing f
monadifyApply mtrm_f [arg]
monadifyTerm' _ t =
(monStCtx <$> ask) >>= \ctx ->
fail ("Monadifiction failed: no case for term: " ++ ppTermInMonCtx ctx t)
-- | Monadify the application of a monadified term to a list of terms, using the
-- type of the already monadified to monadify the arguments
monadifyApply :: MonTerm -> [Term] -> MonadifyM MonTerm
monadifyApply f (t : ts)
| MTyArrow tp_in _ <- getMonType f =
do mtrm <- monadifyArg (Just tp_in) t
monadifyApply (applyMonTerm f (Right mtrm)) ts
monadifyApply f (t : ts)
| MTyForall _ _ _ <- getMonType f =
do mtp <- monadifyTypeM t
monadifyApply (applyMonTerm f (Left mtp)) ts
monadifyApply _ (_:_) = fail "monadifyApply: application at incorrect type"
monadifyApply f [] = return f
-- | FIXME: documentation; get our type down to a base type before going into
-- the MonadifyM monad
monadifyLambdas :: MonadifyEnv -> MonadifyCtx -> MonType -> Term -> MonTerm
monadifyLambdas env ctx (MTyForall _ k tp_f) (asLambda ->
Just (x, x_tp, body)) =
-- FIXME: check that monadifyKind x_tp == k
ArgMonTerm $ ForallMonTerm x k $ \mtp ->
monadifyLambdas env ((x,x_tp,Left mtp) : ctx) (tp_f mtp) body
monadifyLambdas env ctx (MTyArrow tp_in tp_out) (asLambda ->
Just (x, x_tp, body)) =
-- FIXME: check that monadifyType x_tp == tp_in
ArgMonTerm $ FunMonTerm x tp_in tp_out $ \arg ->
monadifyLambdas env ((x,x_tp,Right (ArgMonTerm arg)) : ctx) tp_out body
monadifyLambdas env ctx tp t =
monadifyEtaExpand env ctx tp tp t []
-- | FIXME: documentation
monadifyEtaExpand :: MonadifyEnv -> MonadifyCtx -> MonType -> MonType -> Term ->
[Either MonType ArgMonTerm] -> MonTerm
monadifyEtaExpand env ctx top_mtp (MTyForall x k tp_f) t args =
ArgMonTerm $ ForallMonTerm x k $ \mtp ->
monadifyEtaExpand env ctx top_mtp (tp_f mtp) t (args ++ [Left mtp])
monadifyEtaExpand env ctx top_mtp (MTyArrow tp_in tp_out) t args =
ArgMonTerm $ FunMonTerm "_" tp_in tp_out $ \arg ->
monadifyEtaExpand env ctx top_mtp tp_out t (args ++ [Right arg])
monadifyEtaExpand env ctx top_mtp mtp t args =
applyMonTermMulti
(runMonadifyM env ctx (toArgType mtp) (monadifyTerm (Just top_mtp) t))
args
----------------------------------------------------------------------
-- * Handling the Primitives
----------------------------------------------------------------------
-- | The macro for unsafeAssert, which checks the type of the objects being
-- compared and dispatches to the proper comparison function
unsafeAssertMacro :: MonMacro
unsafeAssertMacro = MonMacro 1 $ \_ ts ->
let numFunType =
MTyForall "n" (MKType $ mkSort 0) $ \n ->
MTyForall "m" (MKType $ mkSort 0) $ \m ->
MTyBase (MKType $ mkSort 0) $
dataTypeOpenTerm "Prelude.Eq"
[dataTypeOpenTerm "Cryptol.Num" [],
toArgType n, toArgType m] in
case ts of
[(asDataType -> Just (num, []))]
| primName num == "Cryptol.Num" ->
return $ ArgMonTerm $
mkGlobalArgMonTerm numFunType "CryptolM.numAssertEqM"
_ ->
fail "Monadification failed: unsafeAssert applied to non-Num type"
-- | The macro for if-then-else, which contains any binds in a branch to that
-- branch
iteMacro :: MonMacro
iteMacro = MonMacro 4 $ \_ args ->
do let (tp, cond, branch1, branch2) =
case args of
[t1, t2, t3, t4] -> (t1, t2, t3, t4)
_ -> error "iteMacro: wrong number of arguments!"
atrm_cond <- monadifyArg (Just boolMonType) cond
mtp <- monadifyTypeM tp
mtrm1 <- resetMonadifyM (toArgType mtp) $ monadifyTerm (Just mtp) branch1
mtrm2 <- resetMonadifyM (toArgType mtp) $ monadifyTerm (Just mtp) branch2
case (mtrm1, mtrm2) of
(ArgMonTerm atrm1, ArgMonTerm atrm2) ->
return $ fromArgTerm mtp $
applyOpenTermMulti (globalOpenTerm "Prelude.ite")
[toArgType mtp, toArgTerm atrm_cond, toArgTerm atrm1, toArgTerm atrm2]
_ ->
return $ fromCompTerm mtp $
applyOpenTermMulti (globalOpenTerm "Prelude.ite")
[toCompType mtp, toArgTerm atrm_cond,
toCompTerm mtrm1, toCompTerm mtrm2]
-- | Make a 'MonMacro' that maps a named global whose first argument is @n:Num@
-- to a global of semi-pure type that takes an additional argument of type
-- @isFinite n@
fin1Macro :: Ident -> Ident -> MonMacro
fin1Macro from to =
MonMacro 1 $ \glob args ->
do if globalDefName glob == ModuleIdentifier from && length args == 1 then
return ()
else error ("Monadification macro for " ++ show from ++
" applied incorrectly")
-- Monadify the first arg, n, and build a proof it is finite
n_mtp <- monadifyTypeM (head args)
let n = toArgType n_mtp
fin_pf <- assertIsFinite n_mtp
-- Apply the type of @glob@ to n, and apply @to@ to n and fin_pf
let glob_tp = monadifyType [] $ globalDefType glob
let glob_tp_app = applyMonType glob_tp $ Left n_mtp
let to_app = applyOpenTermMulti (globalOpenTerm to) [n, toArgTerm fin_pf]
-- Finally, return @to n fin_pf@ as a MonTerm of monadified type @to_tp n@
return $ ArgMonTerm $ fromSemiPureTerm glob_tp_app to_app
-- | Helper function: build a @LetRecType@ for a nested pi type
lrtFromMonType :: MonType -> OpenTerm
lrtFromMonType (MTyForall x k body_f) =
ctorOpenTerm "Prelude.LRT_Fun"
[monKindOpenTerm k,
lambdaOpenTerm x (monKindOpenTerm k) (\tp -> lrtFromMonType $
body_f $ MTyBase k tp)]
lrtFromMonType (MTyArrow mtp1 mtp2) =
ctorOpenTerm "Prelude.LRT_Fun"
[toArgType mtp1,
lambdaOpenTerm "_" (toArgType mtp1) (\_ -> lrtFromMonType mtp2)]
lrtFromMonType mtp =
ctorOpenTerm "Prelude.LRT_Ret" [toArgType mtp]
-- | The macro for fix
--
-- FIXME: does not yet handle mutual recursion
fixMacro :: MonMacro
fixMacro = MonMacro 2 $ \_ args -> case args of
[tp@(asPi -> Just _), f] ->
do mtp <- monadifyTypeM tp
amtrm_f <- monadifyArg (Just $ MTyArrow mtp mtp) f
return $ fromCompTerm mtp $
applyOpenTermMulti (globalOpenTerm "Prelude.multiArgFixM")
[lrtFromMonType mtp, toCompTerm amtrm_f]
[(asRecordType -> Just _), _] ->
fail "Monadification failed: cannot yet handle mutual recursion"
_ -> error "fixMacro: malformed arguments!"
-- | A "macro mapping" maps a single pure identifier to a 'MonMacro' for it
type MacroMapping = (NameInfo, MonMacro)
-- | Build a 'MacroMapping' for an identifier to a semi-pure named function
mmSemiPure :: Ident -> Ident -> MacroMapping
mmSemiPure from_id to_id =
(ModuleIdentifier from_id, semiPureGlobalMacro from_id to_id)
-- | Build a 'MacroMapping' for an identifier to a semi-pure named function
-- whose first argument is a @Num@ that requires an @isFinite@ proof
mmSemiPureFin1 :: Ident -> Ident -> MacroMapping
mmSemiPureFin1 from_id to_id =
(ModuleIdentifier from_id, fin1Macro from_id to_id)
-- | Build a 'MacroMapping' for an identifier to itself as a semi-pure function
mmSelf :: Ident -> MacroMapping
mmSelf self_id =
(ModuleIdentifier self_id, semiPureGlobalMacro self_id self_id)
-- | Build a 'MacroMapping' from an identifier to a function of argument type
mmArg :: Ident -> Ident -> MacroMapping
mmArg from_id to_id = (ModuleIdentifier from_id,
argGlobalMacro (ModuleIdentifier from_id) to_id)
-- | Build a 'MacroMapping' from an identifier and a custom 'MonMacro'
mmCustom :: Ident -> MonMacro -> MacroMapping
mmCustom from_id macro = (ModuleIdentifier from_id, macro)
-- | The default monadification environment
defaultMonEnv :: MonadifyEnv
defaultMonEnv =
Map.fromList
[
-- Prelude functions
mmCustom "Prelude.unsafeAssert" unsafeAssertMacro
, mmCustom "Prelude.ite" iteMacro
, mmCustom "Prelude.fix" fixMacro
-- Top-level sequence functions
, mmArg "Cryptol.seqMap" "CryptolM.seqMapM"
, mmSemiPure "Cryptol.seq_cong1" "CryptolM.mseq_cong1"
, mmArg "Cryptol.eListSel" "CryptolM.eListSelM"
-- List comprehensions
, mmArg "Cryptol.from" "CryptolM.fromM"
-- FIXME: continue here...
-- PEq constraints
, mmSemiPureFin1 "Cryptol.PEqSeq" "CryptolM.PEqMSeq"
, mmSemiPureFin1 "Cryptol.PEqSeqBool" "CryptolM.PEqMSeqBool"
-- PCmp constraints
, mmSemiPureFin1 "Cryptol.PCmpSeq" "CryptolM.PCmpMSeq"
, mmSemiPureFin1 "Cryptol.PCmpSeqBool" "CryptolM.PCmpMSeqBool"
-- PSignedCmp constraints
, mmSemiPureFin1 "Cryptol.PSignedCmpSeq" "CryptolM.PSignedCmpMSeq"
, mmSemiPureFin1 "Cryptol.PSignedCmpSeqBool" "CryptolM.PSignedCmpMSeqBool"
-- PZero constraints
, mmSemiPureFin1 "Cryptol.PZeroSeq" "CryptolM.PZeroMSeq"
-- PLogic constraints
, mmSemiPure "Cryptol.PLogicSeq" "CryptolM.PLogicMSeq"
, mmSemiPureFin1 "Cryptol.PLogicSeqBool" "CryptolM.PLogicMSeqBool"
-- PRing constraints
, mmSemiPure "Cryptol.PRingSeq" "CryptolM.PRingMSeq"
, mmSemiPureFin1 "Cryptol.PRingSeqBool" "CryptolM.PRingMSeqBool"
-- PIntegral constraints
, mmSemiPureFin1 "Cryptol.PIntegeralSeqBool" "CryptolM.PIntegeralMSeqBool"
-- PLiteral constraints
, mmSemiPureFin1 "Cryptol.PLiteralSeqBool" "CryptolM.PLiteralSeqBoolM"
-- The Cryptol Literal primitives
, mmSelf "Cryptol.ecNumber"
, mmSelf "Cryptol.ecFromZ"
-- The Ring primitives
, mmSelf "Cryptol.ecPlus"
, mmSelf "Cryptol.ecMinus"
, mmSelf "Cryptol.ecMul"
, mmSelf "Cryptol.ecNeg"
, mmSelf "Cryptol.ecToInteger"
-- The comparison primitives
, mmSelf "Cryptol.ecEq"
, mmSelf "Cryptol.ecNotEq"
, mmSelf "Cryptol.ecLt"
, mmSelf "Cryptol.ecLtEq"
, mmSelf "Cryptol.ecGt"
, mmSelf "Cryptol.ecGtEq"
-- Sequences
, mmSemiPure "Cryptol.ecShiftL" "CryptolM.ecShiftLM"
, mmSemiPure "Cryptol.ecShiftR" "CryptolM.ecShiftRM"
, mmSemiPure "Cryptol.ecSShiftR" "CryptolM.ecSShiftRM"
, mmSemiPureFin1 "Cryptol.ecRotL" "CryptolM.ecRotLM"
, mmSemiPureFin1 "Cryptol.ecRotR" "CryptolM.ecRotRM"
, mmSemiPureFin1 "Cryptol.ecCat" "CryptolM.ecCatM"
, mmSemiPure "Cryptol.ecTake" "CryptolM.ecTakeM"
, mmSemiPureFin1 "Cryptol.ecDrop" "CryptolM.ecDropM"
, mmSemiPure "Cryptol.ecJoin" "CryptolM.ecJoinM"
, mmSemiPure "Cryptol.ecSplit" "CryptolM.ecSplitM"
, mmSemiPureFin1 "Cryptol.ecReverse" "CryptolM.ecReverseM"
, mmSemiPure "Cryptol.ecTranspose" "CryptolM.ecTransposeM"
, mmArg "Cryptol.ecAt" "CryptolM.ecAtM"
-- , mmArgFin1 "Cryptol.ecAtBack" "CryptolM.ecAtBackM"
-- , mmSemiPureFin2 "Cryptol.ecFromTo" "CryptolM.ecFromToM"
, mmSemiPureFin1 "Cryptol.ecFromToLessThan" "CryptolM.ecFromToLessThanM"
-- , mmSemiPureNthFin 5 "Cryptol.ecFromThenTo" "CryptolM.ecFromThenToM"
, mmSemiPure "Cryptol.ecInfFrom" "CryptolM.ecInfFromM"
, mmSemiPure "Cryptol.ecInfFromThen" "CryptolM.ecInfFromThenM"
, mmArg "Cryptol.ecError" "CryptolM.ecErrorM"
]
----------------------------------------------------------------------
-- * Top-Level Entrypoints
----------------------------------------------------------------------
-- | Ensure that the @CryptolM@ module is loaded
ensureCryptolMLoaded :: SharedContext -> IO ()
ensureCryptolMLoaded sc =
scModuleIsLoaded sc (mkModuleName ["CryptolM"]) >>= \is_loaded ->
if is_loaded then return () else
scLoadCryptolMModule sc
-- | Monadify a type to its argument type and complete it to a 'Term'
monadifyCompleteArgType :: SharedContext -> Term -> IO Term
monadifyCompleteArgType sc tp =
completeOpenTerm sc $ monadifyTypeArgType [] tp
-- | Monadify a term of the specified type to a 'MonTerm' and then complete that
-- 'MonTerm' to a SAW core 'Term', or 'fail' if this is not possible
monadifyCompleteTerm :: SharedContext -> MonadifyEnv -> Term -> Term -> IO Term
monadifyCompleteTerm sc env trm tp =
runCompleteMonadifyM sc env tp $
monadifyTerm (Just $ monadifyType [] tp) trm
-- | Convert a name of a definition to the name of its monadified version
monadifyName :: NameInfo -> IO NameInfo
monadifyName (ModuleIdentifier ident) =
return $ ModuleIdentifier $ mkIdent (identModule ident) $
T.append (identBaseName ident) (T.pack "M")
monadifyName (ImportedName uri _) =
do frag <- URI.mkFragment (T.pack "M")
return $ ImportedName (uri { URI.uriFragment = Just frag }) []
-- | Monadify a 'Term' of the specified type with an optional body, bind the
-- result to a fresh SAW core constant generated from the supplied name, and
-- then convert that constant back to a 'MonTerm'
monadifyNamedTerm :: SharedContext -> MonadifyEnv ->
NameInfo -> Maybe Term -> Term -> IO MonTerm
monadifyNamedTerm sc env nmi maybe_trm tp =
trace ("Monadifying " ++ T.unpack (toAbsoluteName nmi)) $
do let mtp = monadifyType [] tp
nmi' <- monadifyName nmi
comp_tp <- completeOpenTerm sc $ toCompType mtp
const_trm <-
case maybe_trm of
Just trm ->
do trm' <- monadifyCompleteTerm sc env trm tp
scConstant' sc nmi' trm' comp_tp
Nothing -> scOpaqueConstant sc nmi' tp
return $ fromCompTerm mtp $ closedOpenTerm const_trm
-- | Monadify a term with the specified type along with all constants it
-- contains, adding the monadifications of those constants to the monadification
-- environment
monadifyTermInEnv :: SharedContext -> MonadifyEnv -> Term -> Term ->
IO (Term, MonadifyEnv)
monadifyTermInEnv sc top_env top_trm top_tp =
flip runStateT top_env $
do lift $ ensureCryptolMLoaded sc
let const_infos =
map snd $ Map.toAscList $ getConstantSet top_trm
forM_ const_infos $ \(nmi,tp,maybe_body) ->
get >>= \env ->
if Map.member nmi env then return () else
do mtrm <- lift $ monadifyNamedTerm sc env nmi maybe_body tp
put $ Map.insert nmi (monMacro0 mtrm) env
env <- get
lift $ monadifyCompleteTerm sc env top_trm top_tp
|
GaloisInc/saw-script
|
cryptol-saw-core/src/Verifier/SAW/Cryptol/Monadify.hs
|
bsd-3-clause
| 48,330 | 0 | 19 | 9,597 | 10,733 | 5,490 | 5,243 | -1 | -1 |
module HEP.Data.LHEF.Type where
import Data.IntMap (IntMap)
import HEP.Kinematics (HasFourMomentum (..))
import HEP.Kinematics.Vector.LorentzVector (setXYZT)
data EventInfo = EventInfo
{ nup :: Int -- ^ Number of particle entries in the event.
, idprup :: Int -- ^ ID of the process for the event.
, xwgtup :: Double -- ^ Event weight.
, scalup :: Double -- ^ Scale of the event in GeV.
, aqedup :: Double -- ^ The QED coupling \alpha_{QED} used for the event.
, aqcdup :: Double -- ^ The QCD coupling \alpha_{QCD} used for the event.
} deriving Show
data Particle = Particle
{ -- | Particle ID according to Particle Data Group convention.
idup :: Int
-- | Status code.
, istup :: Int
-- | Index of first and last mother.
, mothup :: (Int, Int)
-- | Integer tag for the color flow line passing through the
-- (anti-)color of the particle.
, icolup :: (Int, Int)
-- | Lab frame momentum (P_x, P_y, P_z, E, M) of particle in GeV.
, pup :: (Double, Double, Double, Double, Double)
-- | Invariant lifetime (distance from production to decay) in mm.
, vtimup :: Double
-- | Consine of the angle between the spin-vector of particle and
-- the three-momentum of the decaying particle, specified in the
-- lab frame.
, spinup :: Double
} deriving Show
instance HasFourMomentum Particle where
fourMomentum Particle { pup = (x, y, z, e, _) } = setXYZT x y z e
{-# INLINE fourMomentum #-}
pt Particle { pup = (x, y, _, _, _) } = sqrt $ x ** 2 + y ** 2
{-# INLINE pt #-}
epxpypz Particle { pup = (x, y, z, e, _) } = (e, x, y, z)
{-# INLINE epxpypz #-}
pxpypz Particle { pup = (x, y, z, _, _) } = (x, y, z)
{-# INLINE pxpypz #-}
pxpy Particle { pup = (x, y, _, _, _) } = (x, y)
{-# INLINE pxpy #-}
px Particle { pup = (x, _, _, _, _) } = x
{-# INLINE px #-}
py Particle { pup = (_, y, _, _, _) } = y
{-# INLINE py #-}
pz Particle { pup = (_, _, z, _, _) } = z
{-# INLINE pz #-}
energy Particle { pup = (_, _, _, e, _) } = e
{-# INLINE energy #-}
type EventEntry = IntMap Particle
type Event = (EventInfo, EventEntry)
newtype ParticleType = ParticleType { getParType :: [Int] } deriving (Show, Eq)
|
cbpark/lhef-tools
|
src/HEP/Data/LHEF/Type.hs
|
bsd-3-clause
| 2,679 | 0 | 10 | 1,016 | 594 | 373 | 221 | 43 | 0 |
{-# LANGUAGE QuasiQuotes, TypeFamilies #-}
import Prelude hiding (product, sum)
import Text.Papillon
import Data.Char
import System.Environment
main :: IO ()
main = do
arg : _ <- getArgs
case expr $ parse arg of
Right (r, _) -> print r
Left _ -> putStrLn "parse error"
[papillon|
value :: Int
= ds:(d:[isDigit d] { d })+ { read ds }
/ '(' e:expr ')' { e }
;
product :: Int
= v0:value ops:(op:('*' { (*) } / '/' { div }) v:value { (`op` v) })*
{ foldl (flip ($)) v0 ops }
;
expr :: Int
= p0:product ops:(op:('+' { (+) } / '-' { (-) }) p:product { (`op` p) })*
{ foldl (flip ($)) p0 ops }
;
|]
|
YoshikuniJujo/papillon
|
examples/arith_old.hs
|
bsd-3-clause
| 618 | 0 | 11 | 149 | 106 | 56 | 50 | 12 | 2 |
{-# LANGUAGE TypeFamilies #-}
module Network.EasyBitcoin.Internal.Transaction
where
import Network.EasyBitcoin.Internal.Words
import Network.EasyBitcoin.Internal.Base58 ( encodeBase58
, decodeBase58
, addRedundancy
, liftRedundacy
)
import Network.EasyBitcoin.Internal.ByteString
import Network.EasyBitcoin.Internal.InstanciationHelpers
import Network.EasyBitcoin.Internal.Signatures
import Network.EasyBitcoin.Keys
import Network.EasyBitcoin.BitcoinUnits
import Network.EasyBitcoin.Address
import Network.EasyBitcoin.Internal.Script
import Network.EasyBitcoin.Internal.InstanciationHelpers
import Network.EasyBitcoin.Internal.HashFunctions
import Data.Bits (testBit, clearBit, setBit)
import Control.Applicative
import Control.Monad(replicateM,forM_)
import qualified Data.ByteString as BS
import Data.Char
import Data.Binary
import Data.Aeson(ToJSON(..),FromJSON(..))
import Data.Binary.Get ( getWord64be
, getWord32be
, getWord64le
, getWord8
, getWord16le
, getWord32le
, getByteString
, Get
)
import Data.Binary.Put( putWord64be
, putWord32be
, putWord32le
, putWord64le
, putWord16le
, putWord8
, putByteString
)
import Data.Maybe(fromMaybe)
--------------------------------------------------------------------------------
-- | Bitcoin transaction.
-- When parsed, only syntax validation is performanced, particulary, signature validation is not.
data Tx net = Tx { txVersion :: Int -- !Word32
, txIn :: [TxIn]
, txOut :: [TxOut]
, txLockTime :: Int -- Either a b -- Word32
} deriving (Eq)
data TxIn = TxIn { prevOutput :: Outpoint -- ^ Reference the previous transaction output (hash + position)
, scriptInput :: Script
, txInSequence :: Int
} deriving (Show,Eq)
data TxOut = TxOut { outValue :: Int -- Word64 -- change to ¿BTC?
, scriptOutput :: Script
} deriving (Show,Eq)
instance Binary (Tx net) where
get = Tx <$> (fmap fromIntegral getWord32le)
<*> (replicateList =<< get)
<*> (replicateList =<< get)
<*> (fmap fromIntegral getWord32le)
where
replicateList (VarInt c) = replicateM (fromIntegral c) get
put (Tx v is os l) = do putWord32le (fromIntegral v)
put $ VarInt $ fromIntegral $ length is
forM_ is put
put $ VarInt $ fromIntegral $ length os
forM_ os put
putWord32le (fromIntegral l)
instance Binary TxOut where
get = do val <- getWord64le
VarInt len <- get
raw_script <- getByteString $ fromIntegral len
case decodeToMaybe raw_script of
Just script -> return$TxOut (fromIntegral val) script
_ -> fail "could not decode the pub-script"
put (TxOut o s) = do putWord64le (fromIntegral o)
let s_ = encode' s
put $ VarInt $ BS.length s_
putByteString s_
instance Binary TxIn where
get = do outpoint <- get
VarInt len <- get
raw_script <- getByteString $ fromIntegral len
val <- getWord32le
case decodeToMaybe raw_script of
Just script -> return$TxIn outpoint script (fromIntegral val)
_ -> fail "could not decode the sig-script"
put (TxIn o s q) = do put o
let s_ = encode' s
put $ VarInt $ BS.length s_
putByteString s_
putWord32le (fromIntegral q)
-- | Represents a reference to a transaction output, that is, a transaction hash ('Txid') plus the output position
-- within the output vector of the referenced transaction.
data Outpoint = Outpoint Txid Int deriving (Eq,Show,Ord,Read)
-- | A transaction identification as a hash of the transaction. 2 transaction are consider different if they have different
-- 'Txid's. In some cases, it might be possible for a peer to modify a transaction into an equivalent one having a different
-- 'Txid', for futher info read about the "transaction-malleability-issue".
--------------------------------------------------------------------------------------------------------------------------------------
-- | A transaction hash used to indentify a transaction. Notice that due to the "transaction-malleability-issue", it is possible for an adversary,
-- to derivated a new equivalent transaction with a different Txid.
data Txid = Txid{ txidHash :: Word256} deriving (Eq,Ord)
-- | Compute the 'Txid' of a given transaction.
txid:: Tx net -> Txid
txid = Txid . fromIntegral . doubleHash256 . encode'
instance Show (Txid) where
show (Txid x) = bsToHex . BS.reverse $ encode' x
instance Read Txid where
readsPrec _ str = case readsPrec__ str of
( Just result, rest) -> [(result,rest)]
_ -> []
where
readsPrec__ str = let (word , rest) = span (not.isSpace)$ dropWhile isSpace str
in (fmap Txid . decodeToMaybe . BS.reverse =<< hexToBS word ,rest)
instance Binary Txid where
get = Txid <$> get
put = put . txidHash
instance ToJSON Txid where
toJSON = toJSON.show
instance ToJSON (Tx net) where
toJSON = toJSON.show
instance Binary Outpoint where
get = Outpoint <$> get <*> (fromIntegral<$>getWord32le)
put (Outpoint h i) = put h >> putWord32le (fromIntegral i)
instance Show (Tx net) where
show = showAsBinary
instance Read (Tx net) where
readsPrec = readsPrecAsBinary
---------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
---------------------------------------------------------------------------------
-- Todo, create here the function "signatureOfTransaction..." so it does not need to export txSigHash
txSigHash :: Tx net -- ^ Transaction to sign.
-> Script -- ^ Output script that is being spent.
-> Int -- ^ Index of the input that is being signed.
-> SigHash -- ^ What parts of the transaction should be signed.
-> Word256 -- ^ Result hash to be signed.
txSigHash tx out i sh = do let newIn = buildInputs (txIn tx) out i sh
fromMaybe (setBit 0 248) -- When SigSingle and input index > outputs, then sign integer 1
$ do newOut <- buildOutputs (txOut tx) i sh
let newTx = tx{ txIn = newIn, txOut = newOut }
return $ doubleHash256 $ encode' newTx `BS.append` encodeSigHash32 sh
-- error $ (bsToHex $ encode' newTx) -- `BS.append` encodeSigHash32 sh)
-- ++ " ------------------------ " ++
-- (bsToHex.encode'.doubleHash256 $ encode' newTx `BS.append` encodeSigHash32 sh)
-- Builds transaction inputs for computing SigHashes
buildInputs :: [TxIn] -> Script -> Int -> SigHash -> [TxIn]
buildInputs txins out i sh
| anyoneCanPay sh = [ (txins !! i) { scriptInput = out } ]
| isSigAll sh || isSigUnknown sh = single
| otherwise = map noSeq $ zip single [0..]
where
empty = map (\ti -> ti{ scriptInput = Script [] }) txins
single = updateIndex i empty $ \ti -> ti{ scriptInput = out }
noSeq (ti,j)
| i == j = ti
| otherwise = ti{ txInSequence = 0 }
-- Build transaction outputs for computing SigHashes
buildOutputs :: [TxOut] -> Int -> SigHash -> Maybe [TxOut]
buildOutputs txos i sh
| isSigAll sh || isSigUnknown sh = return txos
| isSigNone sh = return []
| i >= length txos = Nothing
| otherwise = return $ buffer ++ [txos !! i]
where
buffer = replicate i $ TxOut (-1) (Script [])
updateIndex::Int -> [a] -> (a->a) -> [a]
updateIndex i xs f
| i < 0 || i >= length xs = xs
| otherwise = l ++ (f h : r)
where
(l,h:r) = splitAt i xs
-- | Encodes a 'SigHash' to a 32 bit-long bytestring.
encodeSigHash32 :: SigHash -> BS.ByteString
encodeSigHash32 sh = encode' sh `BS.append` BS.pack [0,0,0]
------------------------------------------------------------------------------------------------------
data SigHash = SigAll { anyoneCanPay :: !Bool }
| SigNone { anyoneCanPay :: !Bool }
| SigSingle { anyoneCanPay :: !Bool }
| SigUnknown { anyoneCanPay :: !Bool
, getSigCode :: !Word8
}
deriving (Eq, Show, Read)
data TxSignature = TxSignature { txSignature :: !Signature
, sigHashType :: !SigHash
} deriving (Eq, Show, Read)
instance Binary TxSignature where
put (TxSignature sig sh) = put sig >> put sh
get = TxSignature <$> get <*> get
instance Binary SigHash where
get = do w <- getWord8
let acp = testBit w 7
return $ case clearBit w 7 of
1 -> SigAll acp
2 -> SigNone acp
3 -> SigSingle acp
_ -> SigUnknown acp w
put sh = putWord8 $ case sh of
SigAll acp
| acp -> 0x81
| otherwise -> 0x01
SigNone acp
| acp -> 0x82
| otherwise -> 0x02
SigSingle acp
| acp -> 0x83
| otherwise -> 0x03
SigUnknown _ w -> w
-------------------------------------------------------------------------------------------------------
-- Returns True if the 'SigHash' has the value SigAll.
isSigAll :: SigHash -> Bool
isSigAll sh = case sh of
SigAll _ -> True
_ -> False
-- Returns True if the 'SigHash' has the value SigNone.
isSigNone :: SigHash -> Bool
isSigNone sh = case sh of
SigNone _ -> True
_ -> False
-- Returns True if the 'SigHash' has the value SigSingle.
isSigSingle :: SigHash -> Bool
isSigSingle sh = case sh of
SigSingle _ -> True
_ -> False
-- Returns True if the 'SigHash' has the value SigUnknown.
isSigUnknown :: SigHash -> Bool
isSigUnknown sh = case sh of
SigUnknown _ _ -> True
_ -> False
|
vwwv/easy-bitcoin
|
Network/EasyBitcoin/Internal/Transaction.hs
|
bsd-3-clause
| 12,007 | 0 | 15 | 4,634 | 2,461 | 1,283 | 1,178 | 208 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Numeric.Units.Dimensional.DK.HaTeX
where
import Text.LaTeX.Base
import Numeric.Units.Dimensional.DK
instance (Texy v, KnownDimension d, Fractional v) => Texy (Quantity d v) where
texy val = texy (val /~ siUnit)
|
bjornbm/dimensional-dk-experimental
|
src/Numeric/Units/Dimensional/DK/HaTeX.hs
|
bsd-3-clause
| 332 | 0 | 8 | 46 | 80 | 47 | 33 | 8 | 0 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
module FunPtr where
import Ivory.Compile.C.CmdlineFrontend
import Ivory.Language
f :: Def ('[Sint32] :-> Sint32)
f = proc "f" (\ n -> body (ret (n + 1)))
invoke :: Def ('[ ProcPtr ('[Sint32] :-> Sint32), Sint32] :-> Sint32)
invoke = proc "invoke" (\ k n -> body (ret =<< indirect k n))
test :: Def ('[] :-> Sint32)
test = proc "fun_ptr_test" (body (ret =<< call invoke (procPtr f) 10))
runFunPtr :: IO ()
runFunPtr = runCompiler [cmodule] [] initialOpts { outDir = Nothing }
cmodule :: Module
cmodule = package "FunPtr" $ do
incl f
incl test
incl invoke
|
Hodapp87/ivory
|
ivory-examples/examples/FunPtr.hs
|
bsd-3-clause
| 628 | 0 | 14 | 122 | 270 | 143 | 127 | 18 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Type alias for case insensitive strict text.
-- Copyright: (c) 2014 Peter Trsko
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: NoImplicitPrelude
--
-- Type alias for case insensitive strict text.
module Skeletos.Type.CIText (CIText)
where
import Data.CaseInsensitive (CI)
import qualified Data.Text as Strict (Text)
-- | Case insensitive strict 'Strict.Text'.
type CIText = CI Strict.Text
|
trskop/skeletos
|
src/Skeletos/Type/CIText.hs
|
bsd-3-clause
| 544 | 0 | 6 | 96 | 59 | 42 | 17 | 5 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.SGIX.BlendAlphaMinmax
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/SGIX/blend_alpha_minmax.txt SGIX_blend_alpha_minmax> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.SGIX.BlendAlphaMinmax (
-- * Enums
gl_ALPHA_MAX_SGIX,
gl_ALPHA_MIN_SGIX
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/SGIX/BlendAlphaMinmax.hs
|
bsd-3-clause
| 689 | 0 | 4 | 81 | 40 | 33 | 7 | 4 | 0 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
DeriveDataTypeable, TypeSynonymInstances, PatternGuards #-}
module Idris.AbsSyntaxTree where
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Typecheck
import Idris.Docstrings
import IRTS.Lang
import IRTS.CodegenCommon
import Util.Pretty
import Util.DynamicLinker
import Idris.Colours
import System.Console.Haskeline
import System.IO
import Prelude hiding ((<$>))
import Control.Applicative ((<|>))
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except
import qualified Control.Monad.Trans.Class as Trans (lift)
import Data.Data (Data)
import Data.Function (on)
import Data.Generics.Uniplate.Data (universe)
import Data.List hiding (group)
import Data.Char
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Data.Either
import qualified Data.Set as S
import Data.Word (Word)
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import Data.Traversable (Traversable)
import Data.Typeable
import Data.Foldable (Foldable)
import Debug.Trace
import Text.PrettyPrint.Annotated.Leijen
data ElabWhat = ETypes | EDefns | EAll
deriving (Show, Eq)
-- Data to pass to recursively called elaborators; e.g. for where blocks,
-- paramaterised declarations, etc.
-- rec_elabDecl is used to pass the top level elaborator into other elaborators,
-- so that we can have mutually recursive elaborators in separate modules without
-- having to muck about with cyclic modules.
data ElabInfo = EInfo { params :: [(Name, PTerm)],
inblock :: Ctxt [Name], -- names in the block, and their params
liftname :: Name -> Name,
namespace :: Maybe [String],
elabFC :: Maybe FC,
rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl ->
Idris () }
toplevel :: ElabInfo
toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented")
eInfoNames :: ElabInfo -> [Name]
eInfoNames info = map fst (params info) ++ M.keys (inblock info)
data IOption = IOption { opt_logLevel :: Int,
opt_typecase :: Bool,
opt_typeintype :: Bool,
opt_coverage :: Bool,
opt_showimp :: Bool, -- ^^ show implicits
opt_errContext :: Bool,
opt_repl :: Bool,
opt_verbose :: Bool,
opt_nobanner :: Bool,
opt_quiet :: Bool,
opt_codegen :: Codegen,
opt_outputTy :: OutputType,
opt_ibcsubdir :: FilePath,
opt_importdirs :: [FilePath],
opt_triple :: String,
opt_cpu :: String,
opt_cmdline :: [Opt], -- remember whole command line
opt_origerr :: Bool,
opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover
opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude
opt_optimise :: [Optimisation],
opt_printdepth :: Maybe Int,
opt_evaltypes :: Bool -- ^ normalise types in :t
}
deriving (Show, Eq)
defaultOpts = IOption { opt_logLevel = 0
, opt_typecase = False
, opt_typeintype = False
, opt_coverage = True
, opt_showimp = False
, opt_errContext = False
, opt_repl = True
, opt_verbose = True
, opt_nobanner = False
, opt_quiet = False
, opt_codegen = Via "c"
, opt_outputTy = Executable
, opt_ibcsubdir = ""
, opt_importdirs = []
, opt_triple = ""
, opt_cpu = ""
, opt_cmdline = []
, opt_origerr = False
, opt_autoSolve = True
, opt_autoImport = []
, opt_optimise = defaultOptimise
, opt_printdepth = Just 5000
, opt_evaltypes = True
}
data PPOption = PPOption {
ppopt_impl :: Bool -- ^^ whether to show implicits
, ppopt_depth :: Maybe Int
} deriving (Show)
data Optimisation = PETransform -- partial eval and associated transforms
deriving (Show, Eq)
defaultOptimise = [PETransform]
-- | Pretty printing options with default verbosity.
defaultPPOption :: PPOption
defaultPPOption = PPOption { ppopt_impl = False , ppopt_depth = Just 200 }
-- | Pretty printing options with the most verbosity.
verbosePPOption :: PPOption
verbosePPOption = PPOption { ppopt_impl = True, ppopt_depth = Just 200 }
-- | Get pretty printing options from the big options record.
ppOption :: IOption -> PPOption
ppOption opt = PPOption {
ppopt_impl = opt_showimp opt,
ppopt_depth = opt_printdepth opt
}
-- | Get pretty printing options from an idris state record.
ppOptionIst :: IState -> PPOption
ppOptionIst = ppOption . idris_options
data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
-- | The output mode in use
data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
| IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle
deriving Show
-- | How wide is the console?
data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
| ColsWide Int -- ^ Manually specified - must be positive
| AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
deriving (Show, Eq)
-- | The global state used in the Idris monad
data IState = IState {
tt_ctxt :: Context, -- ^ All the currently defined names and their terms
idris_constraints :: S.Set ConstraintFC,
-- ^ A list of universe constraints and their corresponding source locations
idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
idris_implicits :: Ctxt [PArg],
idris_statics :: Ctxt [Bool],
idris_classes :: Ctxt ClassInfo,
idris_dsls :: Ctxt DSL,
idris_optimisation :: Ctxt OptInfo,
idris_datatypes :: Ctxt TypeInfo,
idris_namehints :: Ctxt [Name],
idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
-- ^ list of lhs/rhs, and a list of missing clauses
idris_flags :: Ctxt [FnOpt],
idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
idris_calledgraph :: Ctxt [Name],
idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]),
idris_moduledocs :: Ctxt (Docstring DocTerm),
-- ^ module documentation is saved in a special MN so the context
-- mechanism can be used for disambiguation
idris_tyinfodata :: Ctxt TIData,
idris_fninfo :: Ctxt FnInfo,
idris_transforms :: Ctxt [(Term, Term)],
idris_autohints :: Ctxt [Name],
idris_totcheck :: [(FC, Name)], -- names to check totality on
idris_defertotcheck :: [(FC, Name)], -- names to check at the end
idris_totcheckfail :: [(FC, String)],
idris_options :: IOption,
idris_name :: Int,
idris_lineapps :: [((FilePath, Int), PTerm)],
-- ^ Full application LHS on source line
idris_metavars :: [(Name, (Maybe Name, Int, Bool))],
-- ^ The currently defined but not proven metavariables. The Int
-- is the number of vars to display as a context, the Maybe Name
-- is its top-level function, and the Bool is whether :p is
-- allowed
idris_coercions :: [Name],
idris_errRev :: [(Term, Term)],
syntax_rules :: SyntaxRules,
syntax_keywords :: [String],
imported :: [FilePath], -- ^ The imported modules
idris_scprims :: [(Name, (Int, PrimFn))],
idris_objs :: [(Codegen, FilePath)],
idris_libs :: [(Codegen, String)],
idris_cgflags :: [(Codegen, String)],
idris_hdrs :: [(Codegen, String)],
idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public
proof_list :: [(Name, (Bool, [String]))],
errSpan :: Maybe FC,
parserWarnings :: [(FC, Err)],
lastParse :: Maybe Name,
indent_stack :: [Int],
brace_stack :: [Maybe Int],
lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
idris_parsedSpan :: Maybe FC,
hide_list :: [(Name, Maybe Accessibility)],
default_access :: Accessibility,
default_total :: Bool,
ibc_write :: [IBCWrite],
compiled_so :: Maybe String,
idris_dynamic_libs :: [DynamicLib],
idris_language_extensions :: [LanguageExt],
idris_outputmode :: OutputMode,
idris_colourRepl :: Bool,
idris_colourTheme :: ColourTheme,
idris_errorhandlers :: [Name], -- ^ Global error handlers
idris_nameIdx :: (Int, Ctxt (Int, Name)),
idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
module_aliases :: M.Map [T.Text] [T.Text],
idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
idris_postulates :: S.Set Name,
idris_externs :: S.Set (Name, Int),
idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used
idris_whocalls :: Maybe (M.Map Name [Name]),
idris_callswho :: Maybe (M.Map Name [Name]),
idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined
elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance
-- (instances appear twice; also as a funtion name)
idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names)
idris_exports :: [Name], -- ^ Functions with ExportList
idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output
idris_parserHighlights :: [(FC, OutputAnnotation)] -- ^ Highlighting information from the parser
}
-- Required for parsers library, and therefore trifecta
instance Show IState where
show = const "{internal state}"
data SizeChange = Smaller | Same | Bigger | Unknown
deriving (Show, Eq)
{-!
deriving instance Binary SizeChange
deriving instance NFData SizeChange
!-}
type SCGEntry = (Name, [Maybe (Int, SizeChange)])
type UsageReason = (Name, Int) -- fn_name, its_arg_number
data CGInfo = CGInfo { argsdef :: [Name],
calls :: [(Name, [[Name]])],
scg :: [SCGEntry],
argsused :: [Name],
usedpos :: [(Int, [UsageReason])] }
deriving Show
{-!
deriving instance Binary CGInfo
deriving instance NFData CGInfo
!-}
primDefs = [sUN "unsafePerformPrimIO",
sUN "mkLazyForeignPrim",
sUN "mkForeignPrim",
sUN "void"]
-- information that needs writing for the current module's .ibc file
data IBCWrite = IBCFix FixDecl
| IBCImp Name
| IBCStatic Name
| IBCClass Name
| IBCInstance Bool Bool Name Name
| IBCDSL Name
| IBCData Name
| IBCOpt Name
| IBCMetavar Name
| IBCSyntax Syntax
| IBCKeyword String
| IBCImport (Bool, FilePath) -- True = import public
| IBCImportDir FilePath
| IBCObj Codegen FilePath
| IBCLib Codegen String
| IBCCGFlag Codegen String
| IBCDyLib String
| IBCHeader Codegen String
| IBCAccess Name Accessibility
| IBCMetaInformation Name MetaInformation
| IBCTotal Name Totality
| IBCFlags Name [FnOpt]
| IBCFnInfo Name FnInfo
| IBCTrans Name (Term, Term)
| IBCErrRev (Term, Term)
| IBCCG Name
| IBCDoc Name
| IBCCoercion Name
| IBCDef Name -- i.e. main context
| IBCNameHint (Name, Name)
| IBCLineApp FilePath Int PTerm
| IBCErrorHandler Name
| IBCFunctionErrorHandler Name Name Name
| IBCPostulate Name
| IBCExtern (Name, Int)
| IBCTotCheckErr FC String
| IBCParsedRegion FC
| IBCModDocs Name -- ^ The name is the special name used to track module docs
| IBCUsage (Name, Int)
| IBCExport Name
| IBCAutoHint Name Name
deriving Show
-- | The initial state for the compiler
idrisInit :: IState
idrisInit = IState initContext S.empty []
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext
[] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
[] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] []
(RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] []
-- | The monad for the main REPL - reading and processing files and updating
-- global state (hence the IO inner monad).
--type Idris = WriterT [Either String (IO ())] (State IState a))
type Idris = StateT IState (ExceptT Err IO)
catchError :: Idris a -> (Err -> Idris a) -> Idris a
catchError = liftCatch catchE
throwError :: Err -> Idris a
throwError = Trans.lift . throwE
-- Commands in the REPL
data Codegen = Via String
-- | ViaC
-- | ViaJava
-- | ViaNode
-- | ViaJavaScript
-- | ViaLLVM
| Bytecode
deriving (Show, Eq)
{-!
deriving instance NFData Codegen
!-}
data HowMuchDocs = FullDocs | OverviewDocs
-- | REPL commands
data Command = Quit
| Help
| Eval PTerm
| NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
| Undefine [Name]
| Check PTerm
| Core PTerm
| DocStr (Either Name Const) HowMuchDocs
| TotCheck Name
| Reload
| Load FilePath (Maybe Int) -- up to maximum line number
| ChangeDirectory FilePath
| ModImport String
| Edit
| Compile Codegen String
| Execute PTerm
| ExecVal PTerm
| Metavars
| Prove Bool Name -- ^ If false, use prover, if true, use elab shell
| AddProof (Maybe Name)
| RmProof Name
| ShowProof Name
| Proofs
| Universes
| LogLvl Int
| Spec PTerm
| WHNF PTerm
| TestInline PTerm
| Defn Name
| Missing Name
| DynamicLink FilePath
| ListDynamic
| Pattelab PTerm
| Search [String] PTerm
| CaseSplitAt Bool Int Name
| AddClauseFrom Bool Int Name
| AddProofClauseFrom Bool Int Name
| AddMissing Bool Int Name
| MakeWith Bool Int Name
| MakeLemma Bool Int Name
| DoProofSearch Bool Bool Int Name [Name]
-- ^ the first bool is whether to update,
-- the second is whether to search recursively (i.e. for the arguments)
| SetOpt Opt
| UnsetOpt Opt
| NOP
| SetColour ColourType IdrisColour
| ColourOn
| ColourOff
| ListErrorHandlers
| SetConsoleWidth ConsoleWidth
| SetPrinterDepth (Maybe Int)
| Apropos [String] String
| WhoCalls Name
| CallsWho Name
| Browse [String]
| MakeDoc String -- IdrisDoc
| Warranty
| PrintDef Name
| PPrint OutputFmt Int PTerm
| TransformInfo Name
-- Debugging commands
| DebugInfo Name
| DebugUnify PTerm PTerm
data OutputFmt = HTMLOutput | LaTeXOutput
data Opt = Filename String
| Quiet
| NoBanner
| ColourREPL Bool
| Idemode
| IdemodeSocket
| ShowLibs
| ShowLibdir
| ShowIncs
| ShowPkgs
| NoBasePkgs
| NoPrelude
| NoBuiltins -- only for the really primitive stuff!
| NoREPL
| OLogging Int
| Output String
| Interface
| TypeCase
| TypeInType
| DefaultTotal
| DefaultPartial
| WarnPartial
| WarnReach
| EvalTypes
| NoCoverage
| ErrContext
| ShowImpl
| Verbose
| Port String -- REPL TCP port
| IBCSubDir String
| ImportDir String
| PkgBuild String
| PkgInstall String
| PkgClean String
| PkgCheck String
| PkgREPL String
| PkgMkDoc String -- IdrisDoc
| PkgTest String
| PkgIndex FilePath
| WarnOnly
| Pkg String
| BCAsm String
| DumpDefun String
| DumpCases String
| UseCodegen Codegen
| CodegenArgs String
| OutputTy OutputType
| Extension LanguageExt
| InterpretScript String
| EvalExpr String
| TargetTriple String
| TargetCPU String
| OptLevel Int
| AddOpt Optimisation
| RemoveOpt Optimisation
| Client String
| ShowOrigErr
| AutoWidth -- ^ Automatically adjust terminal width
| AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
| UseConsoleWidth ConsoleWidth
| DumpHighlights
deriving (Show, Eq)
data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm
| EEval PTerm | ECheck PTerm | ESearch PTerm
| EDocStr (Either Name Const)
deriving (Show, Eq)
-- Parsed declarations
data Fixity = Infixl { prec :: Int }
| Infixr { prec :: Int }
| InfixN { prec :: Int }
| PrefixN { prec :: Int }
deriving Eq
{-!
deriving instance Binary Fixity
deriving instance NFData Fixity
!-}
instance Show Fixity where
show (Infixl i) = "infixl " ++ show i
show (Infixr i) = "infixr " ++ show i
show (InfixN i) = "infix " ++ show i
show (PrefixN i) = "prefix " ++ show i
data FixDecl = Fix Fixity String
deriving Eq
instance Show FixDecl where
show (Fix f s) = show f ++ " " ++ s
{-!
deriving instance Binary FixDecl
deriving instance NFData FixDecl
!-}
instance Ord FixDecl where
compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
data Static = Static | Dynamic
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Static
deriving instance NFData Static
!-}
-- Mark bindings with their explicitness, and laziness
data Plicity = Imp { pargopts :: [ArgOpt],
pstatic :: Static,
pparam :: Bool,
pscoped :: Maybe ImplicitInfo -- Nothing, if top level
}
| Exp { pargopts :: [ArgOpt],
pstatic :: Static,
pparam :: Bool } -- this is a param (rather than index)
| Constraint { pargopts :: [ArgOpt],
pstatic :: Static }
| TacImp { pargopts :: [ArgOpt],
pstatic :: Static,
pscript :: PTerm }
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Plicity
deriving instance NFData Plicity
!-}
is_scoped :: Plicity -> Maybe ImplicitInfo
is_scoped (Imp _ _ _ s) = s
is_scoped _ = Nothing
impl = Imp [] Dynamic False Nothing
forall_imp = Imp [] Dynamic False (Just (Impl False))
forall_constraint = Imp [] Dynamic False (Just (Impl True))
expl = Exp [] Dynamic False
expl_param = Exp [] Dynamic True
constraint = Constraint [] Static
tacimpl t = TacImp [] Dynamic t
data FnOpt = Inlinable -- always evaluate when simplifying
| TotalFn | PartialFn | CoveringFn
| Coinductive | AssertTotal
| Dictionary -- type class dictionary, eval only when
-- a function argument, and further evaluation resutls
| Implicit -- implicit coercion
| NoImplicit -- do not apply implicit coercions
| CExport String -- export, with a C name
| ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
| ErrorReverse -- ^^ attempt to reverse normalise before showing in error
| Reflection -- a reflecting function, compile-time only
| Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
| Constructor -- Data constructor type
| AutoHint -- use in auto implicit search
| PEGenerated -- generated by partial evaluator
deriving (Show, Eq)
{-!
deriving instance Binary FnOpt
deriving instance NFData FnOpt
!-}
type FnOpts = [FnOpt]
inlinable :: FnOpts -> Bool
inlinable = elem Inlinable
dictionary :: FnOpts -> Bool
dictionary = elem Dictionary
-- | Type provider - what to provide
data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
| ProvPostulate t -- ^ goal type must be Type, so only term
deriving (Show, Eq, Functor)
type ProvideWhat = ProvideWhat' PTerm
-- | Top-level declarations such as compiler directives, definitions,
-- datatypes and typeclasses.
data PDecl' t
= PFix FC Fixity [String] -- ^ Fixity declaration
| PTy (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location)
| PPostulate Bool -- external def if true
(Docstring (Either Err PTerm)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location
| PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
| PCAF FC Name t -- ^ Top level constant
| PData (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
| PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
| PNamespace String FC [PDecl' t]
-- ^ New namespace, where FC is accurate location of the
-- namespace in the file
| PRecord (Docstring (Either Err PTerm)) SyntaxInfo FC DataOpts
Name -- Record name
FC -- Record name precise location
[(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
[(Name, Docstring (Either Err PTerm))] -- Param Docs
[((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err PTerm)))] -- Fields
(Maybe (Name, FC)) -- Optional constructor name and location
(Docstring (Either Err PTerm)) -- Constructor doc
SyntaxInfo -- Constructor SyntaxInfo
-- ^ Record declaration
| PClass (Docstring (Either Err PTerm)) SyntaxInfo FC
[(Name, t)] -- constraints
Name -- class name
FC -- accurate location of class name
[(Name, FC, t)] -- parameters and precise locations
[(Name, Docstring (Either Err PTerm))] -- parameter docstrings
[(Name, FC)] -- determining parameters and precise locations
[PDecl' t] -- declarations
(Maybe (Name, FC)) -- instance constructor name and location
(Docstring (Either Err PTerm)) -- instance constructor docs
-- ^ Type class: arguments are documentation, syntax info, source location, constraints,
-- class name, class name location, parameters, method declarations, optional constructor name
| PInstance
(Docstring (Either Err PTerm)) -- Instance docs
[(Name, Docstring (Either Err PTerm))] -- Parameter docs
SyntaxInfo
FC [(Name, t)] -- constraints
Name -- class
FC -- precise location of class
[t] -- parameters
t -- full instance type
(Maybe Name) -- explicit name
[PDecl' t]
-- ^ Instance declaration: arguments are documentation, syntax info, source
-- location, constraints, class name, parameters, full instance
-- type, optional explicit name, and definitions
| PDSL Name (DSL' t) -- ^ DSL declaration
| PSyntax FC Syntax -- ^ Syntax definition
| PMutual FC [PDecl' t] -- ^ Mutual block
| PDirective Directive -- ^ Compiler directive.
| PProvider (Docstring (Either Err PTerm)) SyntaxInfo FC FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term. The second FC is precise highlighting location.
| PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
-- bool is True, lhs and rhs must be convertible
deriving Functor
{-!
deriving instance Binary PDecl'
deriving instance NFData PDecl'
!-}
-- | The set of source directives
data Directive = DLib Codegen String |
DLink Codegen String |
DFlag Codegen String |
DInclude Codegen String |
DHide Name |
DFreeze Name |
DAccess Accessibility |
DDefault Bool |
DLogging Integer |
DDynamicLibs [String] |
DNameHint Name FC [(Name, FC)] |
DErrorHandlers Name FC Name FC [(Name, FC)] |
DLanguage LanguageExt |
DUsed FC Name Name
-- | A set of instructions for things that need to happen in IState
-- after a term elaboration when there's been reflected elaboration.
data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
| RClausesInstrs Name [([Name], Term, Term)]
| RAddInstance Name Name
-- | For elaborator state
data EState = EState {
case_decls :: [(Name, PDecl)],
delayed_elab :: [(Int, Elab' EState ())],
new_tyDecls :: [RDeclInstructions],
highlighting :: [(FC, OutputAnnotation)]
}
initEState :: EState
initEState = EState [] [] [] []
type ElabD a = Elab' EState a
highlightSource :: FC -> OutputAnnotation -> ElabD ()
highlightSource fc annot =
updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
-- | One clause of a top-level definition. Term arguments to constructors are:
--
-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
--
-- 2. The list of extra 'with' patterns
--
-- 3. The right-hand side
--
-- 4. The where block (PDecl' t)
data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
| PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
| PClauseR FC [t] t [PDecl' t]
| PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
deriving Functor
{-!
deriving instance Binary PClause'
deriving instance NFData PClause'
!-}
-- | Data declaration
data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
d_name_fc :: FC, -- ^ The precise location of the type constructor name
d_tcon :: t, -- ^ Type constructor
d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
}
-- ^ Data declaration
| PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t }
-- ^ "Placeholder" for data whose constructors are defined later
deriving Functor
{-!
deriving instance Binary PData'
deriving instance NFData PData'
!-}
-- Handy to get a free function for applying PTerm -> PTerm functions
-- across a program, by deriving Functor
type PDecl = PDecl' PTerm
type PData = PData' PTerm
type PClause = PClause' PTerm
-- get all the names declared in a decl
declared :: PDecl -> [Name]
declared (PFix _ _ _) = []
declared (PTy _ _ _ _ _ n fc t) = [n]
declared (PPostulate _ _ _ _ _ _ n t) = [n]
declared (PClauses _ _ n _) = [] -- not a declaration
declared (PCAF _ n _) = [n]
declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
declared (PParams _ _ ds) = concatMap declared ds
declared (PNamespace _ _ ds) = concatMap declared ds
declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
declared (PDSL n _) = [n]
declared (PSyntax _ _) = []
declared (PMutual _ ds) = concatMap declared ds
declared (PDirective _) = []
declared _ = []
-- get the names declared, not counting nested parameter blocks
tldeclared :: PDecl -> [Name]
tldeclared (PFix _ _ _) = []
tldeclared (PTy _ _ _ _ _ n _ t) = [n]
tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
tldeclared (PClauses _ _ n _) = [] -- not a declaration
tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
tldeclared (PParams _ _ ds) = []
tldeclared (PMutual _ ds) = concatMap tldeclared ds
tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
tldeclared _ = []
defined :: PDecl -> [Name]
defined (PFix _ _ _) = []
defined (PTy _ _ _ _ _ n _ t) = []
defined (PPostulate _ _ _ _ _ _ n t) = []
defined (PClauses _ _ n _) = [n] -- not a declaration
defined (PCAF _ n _) = [n]
defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
defined (PParams _ _ ds) = concatMap defined ds
defined (PNamespace _ _ ds) = concatMap defined ds
defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
defined (PDSL n _) = [n]
defined (PSyntax _ _) = []
defined (PMutual _ ds) = concatMap defined ds
defined (PDirective _) = []
defined _ = []
updateN :: [(Name, Name)] -> Name -> Name
updateN ns n | Just n' <- lookup n ns = n'
updateN _ n = n
updateNs :: [(Name, Name)] -> PTerm -> PTerm
updateNs [] t = t
updateNs ns t = mapPT updateRef t
where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
updateRef t = t
-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
-- updateDNs [] t = t
-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
-- where updateCNs ns (PClause n l ts r ds)
-- = PClause (updateN ns n) (fmap (updateNs ns) l)
-- (map (fmap (updateNs ns)) ts)
-- (fmap (updateNs ns) r)
-- (map (updateDNs ns) ds)
-- updateDNs ns c = c
data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable)
-- | High level language terms
data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
| PRef FC [FC] Name -- ^ A reference to a variable. The FC is its precise source location for highlighting. The list of FCs is a collection of additional highlighting locations.
| PInferRef FC [FC] Name -- ^ A name to be defined later
| PPatvar FC Name -- ^ A pattern variable
| PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
| PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
| PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
| PTyped PTerm PTerm -- ^ Term with explicit type
| PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
| PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
| PAppBind FC PTerm [PArg] -- ^ implicitly bound application
| PMatchApp FC Name -- ^ Make an application by type matching
| PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
| PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
| PTrue FC PunInfo -- ^ Unit type..?
| PResolveTC FC -- ^ Solve this dictionary by type class resolution
| PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
| PPair FC [FC] PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration). The list of FCs is its punctuation.
| PDPair FC [FC] PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration). The [FC] is its punctuation.
| PAs FC Name PTerm -- ^ @-pattern, valid LHS only
| PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
| PHidden PTerm -- ^ Irrelevant or hidden pattern
| PType FC -- ^ 'Type' type
| PUniverse Universe -- ^ Some universe
| PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
| PConstant FC Const -- ^ Builtin types
| Placeholder -- ^ Underscore
| PDoBlock [PDo] -- ^ Do notation
| PIdiom FC PTerm -- ^ Idiom brackets
| PReturn FC
| PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
| PProof [PTactic] -- ^ Proof script
| PTactics [PTactic] -- ^ As PProof, but no auto solving
| PElabError Err -- ^ Error to report on elaboration
| PImpossible -- ^ Special case for declaring when an LHS can't typecheck
| PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
| PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
| PUnifyLog PTerm -- ^ dump a trace of unifications when building term
| PNoImplicits PTerm -- ^ never run implicit converions on the term
| PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
| PUnquote PTerm -- ^ ~Term
| PQuoteName Name FC -- ^ `{n} where the FC is the precise highlighting for the name in particular
| PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace.
| PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later.
deriving (Eq, Data, Typeable)
data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
| FirstSuccess
| TryImplicit
deriving (Eq, Data, Typeable)
-- | Transform the FCs in a PTerm. The first function transforms the
-- general-purpose FCs, and the second transforms those that are used
-- for semantic source highlighting, so they can be treated specially.
mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
mapPTermFC f g (PQuote q) = PQuote q
mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PLet fc n fc' t1 t2 t3) = PLet (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PCase fc t cases) = PCase (f fc) (mapPTermFC f g t) (map (\(l,r) -> (mapPTermFC f g l, mapPTermFC f g r)) cases)
mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PDPair fc hls info t1 t2 t3) = PDPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
mapPTermFC f g (PType fc) = PType (f fc)
mapPTermFC f g (PUniverse u) = PUniverse u
mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
mapPTermFC f g Placeholder = Placeholder
mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
mapPDoFC (DoBindP fc t1 t2 alts) =
DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
mapPTermFC f g (PReturn fc) = PReturn (f fc)
mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
mapPTermFC f g (PElabError err) = PElabError err
mapPTermFC f g PImpossible = PImpossible
mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
mapPTermFC f g (PQuoteName n fc) = PQuoteName n (g fc)
{-!
dg instance Binary PTerm
deriving instance NFData PTerm
!-}
mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
mapPT f t = f (mpt t) where
mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
(fmap (mapPT f) g)
mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
mpt (PHidden t) = PHidden (mapPT f t)
mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
mpt x = x
data PTactic' t = Intro [Name] | Intros | Focus Name
| Refine Name [Bool] | Rewrite t | DoUnify
| Induction t
| CaseTac t
| Equiv t
| Claim Name t
| Unfocus
| MatchRefine Name
| LetTac Name t | LetTacTy Name t t
| Exact t | Compute | Trivial | TCInstance
| ProofSearch Bool Bool Int (Maybe Name) [Name]
-- ^ the bool is whether to search recursively
| Solve
| Attack
| ProofState | ProofTerm | Undo
| Try (PTactic' t) (PTactic' t)
| TSeq (PTactic' t) (PTactic' t)
| ApplyTactic t -- see Language.Reflection module
| ByReflection t
| Reflect t
| Fill t
| GoalType String (PTactic' t)
| TCheck t
| TEval t
| TDocStr (Either Name Const)
| TSearch t
| Skip
| TFail [ErrorReportPart]
| Qed | Abandon
| SourceFC
deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
{-!
deriving instance Binary PTactic'
deriving instance NFData PTactic'
!-}
instance Sized a => Sized (PTactic' a) where
size (Intro nms) = 1 + size nms
size Intros = 1
size (Focus nm) = 1 + size nm
size (Refine nm bs) = 1 + size nm + length bs
size (Rewrite t) = 1 + size t
size (Induction t) = 1 + size t
size (LetTac nm t) = 1 + size nm + size t
size (Exact t) = 1 + size t
size Compute = 1
size Trivial = 1
size Solve = 1
size Attack = 1
size ProofState = 1
size ProofTerm = 1
size Undo = 1
size (Try l r) = 1 + size l + size r
size (TSeq l r) = 1 + size l + size r
size (ApplyTactic t) = 1 + size t
size (Reflect t) = 1 + size t
size (Fill t) = 1 + size t
size Qed = 1
size Abandon = 1
size Skip = 1
size (TFail ts) = 1 + size ts
size SourceFC = 1
size DoUnify = 1
size (CaseTac x) = 1 + size x
size (Equiv t) = 1 + size t
size (Claim x y) = 1 + size x + size y
size Unfocus = 1
size (MatchRefine x) = 1 + size x
size (LetTacTy x y z) = 1 + size x + size y + size z
size TCInstance = 1
type PTactic = PTactic' PTerm
data PDo' t = DoExp FC t
| DoBind FC Name FC t -- ^ second FC is precise name location
| DoBindP FC t t [(t,t)]
| DoLet FC Name FC t t -- ^ second FC is precise name location
| DoLetP FC t t
deriving (Eq, Functor, Data, Typeable)
{-!
deriving instance Binary PDo'
deriving instance NFData PDo'
!-}
instance Sized a => Sized (PDo' a) where
size (DoExp fc t) = 1 + size fc + size t
size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
size (DoLetP fc l r) = 1 + size fc + size l + size r
type PDo = PDo' PTerm
-- The priority gives a hint as to elaboration order. Best to elaborate
-- things early which will help give a more concrete type to other
-- variables, e.g. a before (interpTy a).
data PArg' t = PImp { priority :: Int,
machine_inf :: Bool, -- true if the machine inferred it
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PExp { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PConstraint { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PTacImplicit { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getScript :: t,
getTm :: t }
deriving (Show, Eq, Functor, Data, Typeable)
data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp
deriving (Show, Eq, Data, Typeable)
instance Sized a => Sized (PArg' a) where
size (PImp p _ l nm trm) = 1 + size nm + size trm
size (PExp p l nm trm) = 1 + size nm + size trm
size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
{-!
deriving instance Binary PArg'
deriving instance NFData PArg'
!-}
pimp n t mach = PImp 1 mach [] n t
pexp t = PExp 1 [] (sMN 0 "arg") t
pconst t = PConstraint 1 [] (sMN 0 "carg") t
ptacimp n s t = PTacImplicit 2 [] n s t
type PArg = PArg' PTerm
-- | Get the highest FC in a term, if one exists
highestFC :: PTerm -> Maybe FC
highestFC (PQuote _) = Nothing
highestFC (PRef fc _ _) = Just fc
highestFC (PInferRef fc _ _) = Just fc
highestFC (PPatvar fc _) = Just fc
highestFC (PLam fc _ _ _ _) = Just fc
highestFC (PPi _ _ _ _ _) = Nothing
highestFC (PLet fc _ _ _ _ _) = Just fc
highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
highestFC (PApp fc _ _) = Just fc
highestFC (PAppBind fc _ _) = Just fc
highestFC (PMatchApp fc _) = Just fc
highestFC (PCase fc _ _) = Just fc
highestFC (PIfThenElse fc _ _ _) = Just fc
highestFC (PTrue fc _) = Just fc
highestFC (PResolveTC fc) = Just fc
highestFC (PRewrite fc _ _ _) = Just fc
highestFC (PPair fc _ _ _ _) = Just fc
highestFC (PDPair fc _ _ _ _ _) = Just fc
highestFC (PAs fc _ _) = Just fc
highestFC (PAlternative _ _ args) =
case mapMaybe highestFC args of
[] -> Nothing
(fc:_) -> Just fc
highestFC (PHidden _) = Nothing
highestFC (PType fc) = Just fc
highestFC (PUniverse _) = Nothing
highestFC (PGoal fc _ _ _) = Just fc
highestFC (PConstant fc _) = Just fc
highestFC Placeholder = Nothing
highestFC (PDoBlock lines) =
case map getDoFC lines of
[] -> Nothing
(fc:_) -> Just fc
where
getDoFC (DoExp fc t) = fc
getDoFC (DoBind fc nm nfc t) = fc
getDoFC (DoBindP fc l r alts) = fc
getDoFC (DoLet fc nm nfc l r) = fc
getDoFC (DoLetP fc l r) = fc
highestFC (PIdiom fc _) = Just fc
highestFC (PReturn fc) = Just fc
highestFC (PMetavar fc _) = Just fc
highestFC (PProof _) = Nothing
highestFC (PTactics _) = Nothing
highestFC (PElabError _) = Nothing
highestFC PImpossible = Nothing
highestFC (PCoerced tm) = highestFC tm
highestFC (PDisamb _ opts) = highestFC opts
highestFC (PUnifyLog tm) = highestFC tm
highestFC (PNoImplicits tm) = highestFC tm
highestFC (PQuasiquote _ _) = Nothing
highestFC (PUnquote tm) = highestFC tm
highestFC (PQuoteName _ fc) = Just fc
highestFC (PRunElab fc _ _) = Just fc
highestFC (PConstSugar fc _) = Just fc
highestFC (PAppImpl t _) = highestFC t
-- Type class data
data ClassInfo = CI { instanceCtorName :: Name,
class_methods :: [(Name, (FnOpts, PTerm))],
class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
class_default_superclasses :: [PDecl],
class_params :: [Name],
class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded
class_determiners :: [Int] }
deriving Show
{-!
deriving instance Binary ClassInfo
deriving instance NFData ClassInfo
!-}
-- Type inference data
data TIData = TIPartial -- ^ a function with a partially defined type
| TISolution [Term] -- ^ possible solutions to a metavariable in a type
deriving Show
-- | Miscellaneous information about functions
data FnInfo = FnInfo { fn_params :: [Int] }
deriving Show
{-!
deriving instance Binary FnInfo
deriving instance NFData FnInfo
!-}
data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
detaggable :: Bool }
deriving Show
{-!
deriving instance Binary OptInfo
deriving instance NFData OptInfo
!-}
-- | Syntactic sugar info
data DSL' t = DSL { dsl_bind :: t,
dsl_return :: t,
dsl_apply :: t,
dsl_pure :: t,
dsl_var :: Maybe t,
index_first :: Maybe t,
index_next :: Maybe t,
dsl_lambda :: Maybe t,
dsl_let :: Maybe t,
dsl_pi :: Maybe t
}
deriving (Show, Functor)
{-!
deriving instance Binary DSL'
deriving instance NFData DSL'
!-}
type DSL = DSL' PTerm
data SynContext = PatternSyntax | TermSyntax | AnySyntax
deriving Show
{-!
deriving instance Binary SynContext
deriving instance NFData SynContext
!-}
data Syntax = Rule [SSymbol] PTerm SynContext
deriving Show
syntaxNames :: Syntax -> [Name]
syntaxNames (Rule syms _ _) = mapMaybe ename syms
where ename (Keyword n) = Just n
ename _ = Nothing
syntaxSymbols :: Syntax -> [SSymbol]
syntaxSymbols (Rule ss _ _) = ss
{-!
deriving instance Binary Syntax
deriving instance NFData Syntax
!-}
data SSymbol = Keyword Name
| Symbol String
| Binding Name
| Expr Name
| SimpleExpr Name
deriving (Show, Eq)
{-!
deriving instance Binary SSymbol
deriving instance NFData SSymbol
!-}
newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
emptySyntaxRules :: SyntaxRules
emptySyntaxRules = SyntaxRules []
updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
where
newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
ruleSort [] [] = EQ
ruleSort [] _ = LT
ruleSort _ [] = GT
ruleSort (s1:ss1) (s2:ss2) =
case symCompare s1 s2 of
EQ -> ruleSort ss1 ss2
r -> r
-- Better than creating Ord instance for SSymbol since
-- in general this ordering does not really make sense.
symCompare (Keyword n1) (Keyword n2) = compare n1 n2
symCompare (Keyword _) _ = LT
symCompare (Symbol _) (Keyword _) = GT
symCompare (Symbol s1) (Symbol s2) = compare s1 s2
symCompare (Symbol _) _ = LT
symCompare (Binding _) (Keyword _) = GT
symCompare (Binding _) (Symbol _) = GT
symCompare (Binding b1) (Binding b2) = compare b1 b2
symCompare (Binding _) _ = LT
symCompare (Expr _) (Keyword _) = GT
symCompare (Expr _) (Symbol _) = GT
symCompare (Expr _) (Binding _) = GT
symCompare (Expr e1) (Expr e2) = compare e1 e2
symCompare (Expr _) _ = LT
symCompare (SimpleExpr _) (Keyword _) = GT
symCompare (SimpleExpr _) (Symbol _) = GT
symCompare (SimpleExpr _) (Binding _) = GT
symCompare (SimpleExpr _) (Expr _) = GT
symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
initDSL = DSL (PRef f [] (sUN ">>="))
(PRef f [] (sUN "return"))
(PRef f [] (sUN "<*>"))
(PRef f [] (sUN "pure"))
Nothing
Nothing
Nothing
Nothing
Nothing
Nothing
where f = fileFC "(builtin)"
data Using = UImplicit Name PTerm
| UConstraint Name [Name]
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Using
deriving instance NFData Using
!-}
data SyntaxInfo = Syn { using :: [Using],
syn_params :: [(Name, PTerm)],
syn_namespace :: [String],
no_imp :: [Name],
imp_methods :: [Name], -- class methods. When expanding
-- implicits, these should be expanded even under
-- binders
decoration :: Name -> Name,
inPattern :: Bool,
implicitAllowed :: Bool,
maxline :: Maybe Int,
mut_nesting :: Int,
dsl_info :: DSL,
syn_in_quasiquote :: Int }
deriving Show
{-!
deriving instance NFData SyntaxInfo
deriving instance Binary SyntaxInfo
!-}
defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0
expandNS :: SyntaxInfo -> Name -> Name
expandNS syn n@(NS _ _) = n
expandNS syn n = case syn_namespace syn of
[] -> n
xs -> sNS n xs
-- For inferring types of things
bi = fileFC "builtin"
inferTy = sMN 0 "__Infer"
inferCon = sMN 0 "__infer"
inferDecl = PDatadecl inferTy NoFC
(PType bi)
[(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) (
PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType"))
(PRef bi [] inferTy)), bi, [])]
inferOpts = []
infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
infP = P (TCon 6 0) inferTy (TType (UVal 0))
getInferTerm, getInferType :: Term -> Term
getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
getInferTerm (App _ (App _ _ _) tm) = tm
getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
where toTy (Lam t) = Pi Nothing t (TType (UVar 0))
toTy (PVar t) = PVTy t
toTy b = b
getInferType (App _ (App _ _ ty) _) = ty
-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
primNames = [inferTy, inferCon]
unitTy = sUN "Unit"
unitCon = sUN "MkUnit"
falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
"The empty type, also known as the trivially false proposition." ++
"\n\n" ++
"Use `void` or `absurd` to prove anything if you have a variable " ++
"of type `Void` in scope."
falseTy = sUN "Void"
pairTy = sNS (sUN "Pair") ["Builtins"]
pairCon = sNS (sUN "MkPair") ["Builtins"]
upairTy = sNS (sUN "UPair") ["Builtins"]
upairCon = sNS (sUN "MkUPair") ["Builtins"]
eqTy = sUN "="
eqCon = sUN "Refl"
eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
"The propositional equality type. A proof that `x` = `y`." ++
"\n\n" ++
"To use such a proof, pattern-match on it, and the two equal things will " ++
"then need to be the _same_ pattern." ++
"\n\n" ++
"**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
"is possible to state equalities between values of potentially different " ++
"types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
"\n\n" ++
"You may need to use `(~=~)` to explicitly request heterogeneous equality."
eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
(piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
(PType bi)))
[(reflDoc, reflParamDoc,
eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) (
PPi impl (n "x") NoFC (PRef bi [] (n "A"))
(PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
pimp (n "B") Placeholder False,
pexp (PRef bi [] (n "x")),
pexp (PRef bi [] (n "x"))])), bi, [])]
where n a = sUN a
reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
"A proof that `x` in fact equals `x`. To construct this, you must have already " ++
"shown that both sides are in fact equal."
reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
(n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
(n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
]
where n a = sUN a
eqOpts = []
-- | The special name to be used in the module documentation context -
-- not for use in the main definition context. The namespace around it
-- will determine the module to which the docs adhere.
modDocName :: Name
modDocName = sMN 0 "ModuleDocs"
-- Defined in builtins.idr
sigmaTy = sNS (sUN "Sigma") ["Builtins"]
sigmaCon = sNS (sUN "MkSigma") ["Builtins"]
piBind :: [(Name, PTerm)] -> PTerm -> PTerm
piBind = piBindp expl
piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
piBindp p [] t = t
piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
-- Pretty-printing declarations and terms
-- These "show" instances render to an absurdly wide screen because inserted line breaks
-- could interfere with interactive editing, which calls "show".
instance Show PTerm where
showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
instance Show PDecl where
showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
instance Show PClause where
showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
instance Show PData where
showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
instance Pretty PTerm OutputAnnotation where
pretty = prettyImp defaultPPOption
-- | Colourise annotations according to an Idris state. It ignores the names
-- in the annotation, as there's no good way to show extended information on a
-- terminal.
consoleDecorate :: IState -> OutputAnnotation -> String -> String
consoleDecorate ist _ | not (idris_colourRepl ist) = id
consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist
in if constIsType c
then colouriseType theme
else colouriseData theme
consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist)
consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist)
consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
theme = idris_colourTheme ist
in case () of
_ | isDConName n ctxt -> colouriseData theme
_ | isFnName n ctxt -> colouriseFun theme
_ | isTConName n ctxt -> colouriseType theme
_ | isPostulateName n ist -> colourisePostulate theme
_ | otherwise -> id -- don't colourise unknown names
consoleDecorate ist (AnnFC _) = id
consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
where colour BoldText = IdrisColour Nothing True False True False
colour UnderlineText = IdrisColour Nothing True True False False
colour ItalicText = IdrisColour Nothing True False False True
consoleDecorate ist (AnnTerm _ _) = id
consoleDecorate ist (AnnSearchResult _) = id
consoleDecorate ist (AnnErr _) = id
consoleDecorate ist (AnnNamespace _ _) = id
consoleDecorate ist (AnnLink url) =
\txt -> Idris.Colours.colourise (IdrisColour Nothing True True False False) txt ++ " (" ++ url ++ ")"
isPostulateName :: Name -> IState -> Bool
isPostulateName n ist = S.member n (idris_postulates ist)
-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
prettyImp :: PPOption -- ^^ pretty printing options
-> PTerm -- ^^ the term to pretty-print
-> Doc OutputAnnotation
prettyImp impl = pprintPTerm impl [] [] []
-- | Serialise something to base64 using its Binary instance.
-- | Do the right thing for rendering a term in an IState
prettyIst :: IState -> PTerm -> Doc OutputAnnotation
prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
-- | Pretty-print a high-level Idris term in some bindings context with infix info
pprintPTerm :: PPOption -- ^^ pretty printing options
-> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
-> [Name] -- ^^ names to always show in pi, even if not used
-> [FixDecl] -- ^^ Fixity declarations
-> PTerm -- ^^ the term to pretty-print
-> Doc OutputAnnotation
pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
where
startPrec = 0
funcAppPrec = 10
prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
prettySe d p bnd (PQuote r) =
text "![" <> pretty r <> text "]"
prettySe d p bnd (PPatvar fc n) = pretty n
prettySe d p bnd e
| Just str <- slist d p bnd e = depth d $ str
| Just n <- snat d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
prettySe d p bnd (PLam fc n nfc ty sc) =
depth d . bracket p startPrec . group . align . hang 2 $
text "\\" <> prettyBindingOf n False <+> text "=>" <$>
prettySe (decD d) startPrec ((n, False):bnd) sc
prettySe d p bnd (PLet fc n nfc ty v sc) =
depth d . bracket p startPrec . group . align $
kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
| n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs =
depth d . bracket p startPrec . group $
enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
| otherwise =
depth d . bracket p startPrec . group $
group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
group (prettySe (decD d) startPrec ((n, False):bnd) sc)
where
st =
case s of
Static -> text "[static]" <> space
_ -> empty
prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc)
| ppopt_impl ppo =
depth d . bracket p startPrec $
lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
| otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
where
st =
case s of
Static -> text "[static]" <> space
_ -> empty
prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
depth d . bracket p startPrec $
prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _])) n _ ty sc) =
lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
depth d . bracket p startPrec $
lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
-- This case preserves the behavior of the former constructor PEq.
-- It should be removed if feasible when the pretty-printing of infix
-- operators in general is improved.
prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
| n == eqTy, ppopt_impl ppo =
depth d . bracket p eqPrec $
enclose lparen rparen eq <+>
align (group (vsep (map (prettyArgS (decD d) bnd)
[lt, rt, l, r])))
| n == eqTy =
depth d . bracket p eqPrec . align . group $
prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
where eq = annName eqTy (text "=")
eqPrec = startPrec
prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
| UN nm <- basename f
, not (ppopt_impl ppo) && null (getShowArgs args) =
prettyName True (ppopt_impl ppo) bnd f
prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
| not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
| UN nm <- basename op
, not (tnull nm) &&
(not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
case getShowArgs args of
[] -> opName True
[x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
[l,r] -> let precedence = maybe (startPrec - 1) prec f
in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
(l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) ->
depth d . bracket p funcAppPrec $
enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
align (group (vsep (map (prettyArgS d bnd) rest)))
as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
f = getFixity (opStr op)
left = case f of
Nothing -> funcAppPrec + 1
Just (Infixl p') -> p'
Just f' -> prec f' + 1
right = case f of
Nothing -> funcAppPrec + 1
Just (Infixr p') -> p'
Just f' -> prec f' + 1
inFix l r = align . group $
(prettySe (decD d) left bnd l <+> opName False) <$>
group (prettySe (decD d) right bnd r)
prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
| PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
let args = getShowArgs as
fp = prettySe (decD d) (startPrec + 1) bnd f
shownArgs = if ppopt_impl ppo then as else args
in
depth d . bracket p funcAppPrec . group $
if null shownArgs
then fp
else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
prettySe d p bnd (PCase _ scr cases) =
align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
depth d (indent 2 (vsep (map ppcase cases)))
where
ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
([(n, False) | n <- vars l] ++ bnd)
in nest nestingSize $
prettyCase l <+> text "=>" <+> prettyCase r
-- Warning: this is a bit of a hack. At this stage, we don't have the
-- global context, so we can't determine which names are constructors,
-- which are types, and which are pattern variables on the LHS of the
-- case pattern. We use the heuristic that names without a namespace
-- are patvars, because right now case blocks in PTerms are always
-- delaborated from TT before being sent to the pretty-printer. If they
-- start getting printed directly, THIS WILL BREAK.
-- Potential solution: add a list of known patvars to the cases in
-- PCase, and have the delaborator fill it out, kind of like the pun
-- disambiguation on PDPair.
vars tm = filter noNS (allNamesIn tm)
noNS (NS _ _) = False
noNS _ = True
prettySe d p bnd (PIfThenElse _ c t f) =
depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
[ kwd "if" <+> prettySe (decD d) startPrec bnd c
, kwd "then" <+> prettySe (decD d) startPrec bnd t
, kwd "else" <+> prettySe (decD d) startPrec bnd f
]
prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
prettySe d p bnd (PResolveTC _) = kwd "%instance"
prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
prettySe d p bnd (PRewrite _ l r _) =
depth d . bracket p startPrec $
text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r
prettySe d p bnd (PTyped l r) =
lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
| Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
align . group . vsep . punctuate (ann comma) $
map (prettySe (decD d) startPrec bnd) elts
where ann = case pun of
TypeOrTerm -> id
IsType -> annName pairTy
IsTerm -> annName pairCon
prettySe d p bnd (PDPair _ _ pun l t r) =
depth d $
annotated lparen <>
left <+>
annotated (text "**") <+>
prettySe (decD d) startPrec (addBinding bnd) r <>
annotated rparen
where annotated = case pun of
IsType -> annName sigmaTy
IsTerm -> annName sigmaCon
TypeOrTerm -> id
(left, addBinding) = case (l, pun) of
(PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
_ -> (prettySe (decD d) startPrec bnd l, id)
prettySe d p bnd (PAlternative ns a as) =
lparen <> text "|" <> prettyAs <> text "|" <> rparen
where
prettyAs =
foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as
prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
-- XXX: add pretty for tactics
prettySe d p bnd (PProof ts) =
kwd "proof" <+> lbrace <> ellipsis <> rbrace
prettySe d p bnd (PTactics ts) =
kwd "tactics" <+> lbrace <> ellipsis <> rbrace
prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
prettySe d p bnd (PReturn f) = kwd "return"
prettySe d p bnd PImpossible = kwd "impossible"
prettySe d p bnd Placeholder = text "_"
prettySe d p bnd (PDoBlock dos) =
bracket p startPrec $
kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
ppdo bnd (DoBind _ bn _ tm : dos) =
(prettyBindingOf bn False <+> text "<-" <+>
group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
ppdo ((bn, False):bnd) dos
ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
text "no pretty printer for pattern-matching do binding" :
ppdo bnd dos
ppdo bnd (DoLet _ ln _ ty v : dos) =
(kwd "let" <+> prettyBindingOf ln False <+>
(if ty /= Placeholder
then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
else text "=") <+>
group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
ppdo ((ln, False):bnd) dos
ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
text "no pretty printer for pattern-matching do binding" :
ppdo bnd dos
ppdo _ [] = []
prettySe d p bnd (PCoerced t) = prettySe d p bnd t
prettySe d p bnd (PElabError s) = pretty s
-- Quasiquote pprinting ignores bound vars
prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
prettySe d p bnd (PQuoteName n _) = text "`{" <> prettyName True (ppopt_impl ppo) bnd n <> text "}"
prettySe d p bnd (PRunElab _ tm _) =
bracket p funcAppPrec . group . align . hang 2 $
text "%runElab" <$>
prettySe (decD d) funcAppPrec bnd tm
prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
prettySe d p bnd _ = text "missing pretty-printer for term"
prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
where display (UN n) = T.unpack n
display (MN _ n) = T.unpack n
-- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n
display n = show n
prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
annName n = annotate (AnnName n Nothing Nothing Nothing)
opStr :: Name -> String
opStr (NS n _) = opStr n
opStr (UN n) = T.unpack n
slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
slist' (Just d) _ _ _ | d <= 0 = Nothing
slist' d _ _ e
| containsHole e = Nothing
slist' d p bnd (PApp _ (PRef _ _ nil) _)
| not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
slist' d p bnd (PRef _ _ nil)
| not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
slist' d p bnd (PApp _ (PRef _ _ cons) args)
| nsroot cons == sUN "::",
(PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
all isImp imps,
Just tl' <- slist' (decD d) p bnd tl
= Just (prettySe d startPrec bnd hd : tl')
where
isImp (PImp {}) = True
isImp _ = False
slist' _ _ _ tm = Nothing
slist d p bnd e | Just es <- slist' d p bnd e = Just $
case es of
[] -> annotate (AnnData "" "") $ text "[]"
[x] -> enclose left right . group $ x
xs -> enclose left right .
align . group . vsep .
punctuate comma $ xs
where left = (annotate (AnnData "" "") (text "["))
right = (annotate (AnnData "" "") (text "]"))
comma = (annotate (AnnData "" "") (text ","))
slist _ _ _ _ = Nothing
pairElts :: PTerm -> Maybe [PTerm]
pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
| otherwise = Just [x, y]
pairElts _ = Nothing
natns = "Prelude.Nat."
snat :: Maybe Int -> Int -> PTerm -> Maybe Integer
snat (Just x) _ _ | x <= 0 = Nothing
snat d p (PRef _ _ z)
| show z == (natns++"Z") || show z == "Z" = Just 0
snat d p (PApp _ s [PExp {getTm=n}])
| show s == (natns++"S") || show s == "S",
Just n' <- snat (decD d) p n
= Just $ 1 + n'
snat _ _ _ = Nothing
bracket outer inner doc
| outer > inner = lparen <> doc <> rparen
| otherwise = doc
ellipsis = text "..."
depth Nothing = id
depth (Just d) = if d <= 0 then const (ellipsis) else id
decD = fmap (\x -> x - 1)
kwd = annotate AnnKeyword . text
fixities :: M.Map String Fixity
fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
getFixity :: String -> Maybe Fixity
getFixity = flip M.lookup fixities
-- | Strip away namespace information
basename :: Name -> Name
basename (NS n _) = basename n
basename n = n
-- | Determine whether a name was the one inserted for a hole or
-- guess by the delaborator
isHoleName :: Name -> Bool
isHoleName (UN n) = n == T.pack "[__]"
isHoleName _ = False
-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
containsHole :: PTerm -> Bool
containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
-- | Pretty-printer helper for names that attaches the correct annotations
prettyName
:: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
-> Bool -- ^^ whether to show namespaces
-> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
-> Name -- ^^ the name to pprint
-> Doc OutputAnnotation
prettyName infixParen showNS bnd n
| (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
| (UN n') <- n, T.unpack n' == "_" = text "_"
| Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
| otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
where fullName = text nameSpace <> parenthesise (text (baseName n))
baseName (UN n) = T.unpack n
baseName (NS n ns) = baseName n
baseName (MN i s) = T.unpack s
baseName other = show other
nameSpace = case n of
(NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
_ -> ""
isInfix = case baseName n of
"" -> False
(c : _) -> not (isAlpha c)
parenthesise = if isInfix && infixParen then enclose lparen rparen else id
showCImp :: PPOption -> PClause -> Doc OutputAnnotation
showCImp ppo (PClause _ n l ws r w)
= prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
<+> text "where" <+> text (show w)
where
showWs [] = empty
showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
showCImp ppo (PWith _ n l ws r pn w)
= prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
<+> braces (text (show w))
where
showWs [] = empty
showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
showDImp :: PPOption -> PData -> Doc OutputAnnotation
showDImp ppo (PDatadecl n nfc ty cons)
= text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
(indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
showDecls o ds = vsep (map (showDeclImp o) ds)
showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
indent 2 (vsep (map (showCImp o) cs))
showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
= text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds)
= text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
showDeclImp _ _ = text "..."
-- showDeclImp (PImport o) = "import " ++ o
getImps :: [PArg] -> [(Name, PTerm)]
getImps [] = []
getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
getImps (_ : xs) = getImps xs
getExps :: [PArg] -> [PTerm]
getExps [] = []
getExps (PExp _ _ _ tm : xs) = tm : getExps xs
getExps (_ : xs) = getExps xs
getShowArgs :: [PArg] -> [PArg]
getShowArgs [] = []
getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
| PImp _ _ _ _ tm <- e
, containsHole tm = e : getShowArgs xs
getShowArgs (_ : xs) = getShowArgs xs
getConsts :: [PArg] -> [PTerm]
getConsts [] = []
getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
getConsts (_ : xs) = getConsts xs
getAll :: [PArg] -> [PTerm]
getAll = map getTm
-- | Show Idris name
showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
-> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
-> PPOption -- ^^ pretty printing options
-> Bool -- ^^ whether to colourise
-> Name -- ^^ the term to show
-> String
showName ist bnd ppo colour n = case ist of
Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
Nothing -> showbasic n
where name = if ppopt_impl ppo then show n else showbasic n
showbasic n@(UN _) = showCG n
showbasic (MN i s) = str s
showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
showbasic (SN s) = show s
fst3 (x, _, _) = x
colourise n t = let ctxt' = fmap tt_ctxt ist in
case ctxt' of
Nothing -> name
Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
else colouriseBound t name
| isDConName n ctxt -> colouriseData t name
| isFnName n ctxt -> colouriseFun t name
| isTConName n ctxt -> colouriseType t name
-- The assumption is that if a name is not bound and does not exist in the
-- global context, then we're somewhere in which implicit info has been lost
-- (like error messages). Thus, unknown vars are colourised as implicits.
| otherwise -> colouriseImplicit t name
showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
-> PTerm -- ^^ the term to show
-> String
showTm ist = displayDecorated (consoleDecorate ist) .
renderPretty 0.8 100000 .
prettyImp (ppOptionIst ist)
-- | Show a term with implicits, no colours
showTmImpls :: PTerm -> String
showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
instance Sized PTerm where
size (PQuote rawTerm) = size rawTerm
size (PRef fc _ name) = size name
size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
size (PTyped trm ty) = 1 + size trm + size ty
size (PApp fc name args) = 1 + size args
size (PAppBind fc name args) = 1 + size args
size (PCase fc trm bdy) = 1 + size trm + size bdy
size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
size (PTrue fc _) = 1
size (PResolveTC fc) = 1
size (PRewrite fc left right _) = 1 + size left + size right
size (PPair fc _ _ left right) = 1 + size left + size right
size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
size (PAlternative _ a alts) = 1 + size alts
size (PHidden hidden) = size hidden
size (PUnifyLog tm) = size tm
size (PDisamb _ tm) = size tm
size (PNoImplicits tm) = size tm
size (PType _) = 1
size (PUniverse _) = 1
size (PConstant fc const) = 1 + size fc + size const
size Placeholder = 1
size (PDoBlock dos) = 1 + size dos
size (PIdiom fc term) = 1 + size term
size (PReturn fc) = 1
size (PMetavar _ name) = 1
size (PProof tactics) = size tactics
size (PElabError err) = size err
size PImpossible = 1
size _ = 0
getPArity :: PTerm -> Int
getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
getPArity _ = 0
-- Return all names, free or globally bound, in the given term.
allNamesIn :: PTerm -> [Name]
allNamesIn tm = nub $ ni [] tm
where -- TODO THINK added niTacImp, but is it right?
ni env (PRef _ _ n)
| not (n `elem` env) = [n]
ni env (PPatvar _ n) = [n]
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
ni env (PIfThenElse _ c t f) = ni env c ++ ni env t ++ ni env f
ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
ni env (PLet _ n _ ty val sc) = ni env ty ++ ni env val ++ ni (n:env) sc
ni env (PHidden tm) = ni env tm
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a ls) = concatMap (ni env) ls
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
niTacImp env (TacImp _ _ scr) = ni env scr
niTacImp _ _ = []
-- Return all names defined in binders in the given term
boundNamesIn :: PTerm -> [Name]
boundNamesIn tm = S.toList (ni S.empty tm)
where -- TODO THINK Added niTacImp, but is it right?
ni set (PApp _ f as) = niTms (ni set f) (map getTm as)
ni set (PAppBind _ f as) = niTms (ni set f) (map getTm as)
ni set (PCase _ c os) = niTms (ni set c) (map snd os)
ni set (PIfThenElse _ c t f) = niTms set [c, t, f]
ni set (PLam fc n _ ty sc) = S.insert n $ ni (ni set ty) sc
ni set (PLet fc n nfc ty val sc) = S.insert n $ ni (ni (ni set ty) val) sc
ni set (PPi p n _ ty sc) = niTacImp (S.insert n $ ni (ni set ty) sc) p
ni set (PRewrite _ l r _) = ni (ni set l) r
ni set (PTyped l r) = ni (ni set l) r
ni set (PPair _ _ _ l r) = ni (ni set l) r
ni set (PDPair _ _ _ (PRef _ _ n) t r) = ni (ni set t) r
ni set (PDPair _ _ _ l t r) = ni (ni (ni set l) t) r
ni set (PAlternative ns a as) = niTms set as
ni set (PHidden tm) = ni set tm
ni set (PUnifyLog tm) = ni set tm
ni set (PDisamb _ tm) = ni set tm
ni set (PNoImplicits tm) = ni set tm
ni set _ = set
niTms set [] = set
niTms set (x : xs) = niTms (ni set x) xs
niTacImp set (TacImp _ _ scr) = ni set scr
niTacImp set _ = set
-- Return names which are valid implicits in the given term (type).
implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
implicitNamesIn uvars ist tm = nub $ ni [] tm
where
ni env (PRef _ _ n)
| not (n `elem` env)
= case lookupTy n (tt_ctxt ist) of
[] -> [n]
_ -> if n `elem` uvars then [n] else []
ni env (PApp _ f@(PRef _ _ n) as)
| n `elem` uvars = ni env f ++ concatMap (ni env) (map getTm as)
| otherwise = concatMap (ni env) (map getTm as)
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++
-- names in 'os', not counting the names bound in the cases
(nub (concatMap (ni env) (map snd os))
\\ nub (concatMap (ni env) (map fst os)))
ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f]
ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a as) = concatMap (ni env) as
ni env (PHidden tm) = ni env tm
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
-- Return names which are free in the given term.
namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
namesIn uvars ist tm = nub $ ni [] tm
where
ni env (PRef _ _ n)
| not (n `elem` env)
= case lookupTy n (tt_ctxt ist) of
[] -> [n]
_ -> if n `elem` (map fst uvars) then [n] else []
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++
-- names in 'os', not counting the names bound in the cases
(nub (concatMap (ni env) (map snd os))
\\ nub (concatMap (ni env) (map fst os)))
ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f]
ni env (PLam fc n nfc ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a as) = concatMap (ni env) as
ni env (PHidden tm) = ni env tm
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
niTacImp env (TacImp _ _ scr) = ni env scr
niTacImp _ _ = []
-- Return which of the given names are used in the given term.
usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
usedNamesIn vars ist tm = nub $ ni [] tm
where -- TODO THINK added niTacImp, but is it right?
ni env (PRef _ _ n)
| n `elem` vars && not (n `elem` env)
= case lookupDefExact n (tt_ctxt ist) of
Nothing -> [n]
_ -> []
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f]
ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a as) = concatMap (ni env) as
ni env (PHidden tm) = ni env tm
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
niTacImp env (TacImp _ _ scr) = ni env scr
niTacImp _ _ = []
-- Return the list of inaccessible (= dotted) positions for a name.
getErasureInfo :: IState -> Name -> [Int]
getErasureInfo ist n =
case lookupCtxtExact n (idris_optimisation ist) of
Just (Optimise inacc detagg) -> map fst inacc
Nothing -> []
|
athanclark/Idris-dev
|
src/Idris/AbsSyntaxTree.hs
|
bsd-3-clause
| 95,914 | 728 | 49 | 30,789 | 31,057 | 16,368 | 14,689 | 1,708 | 94 |
module MainSpec (main, spec) where
import Test.Hspec
import Test.HUnit (assertEqual, Assertion)
import Control.Exception
import System.Directory (getCurrentDirectory, setCurrentDirectory)
import System.FilePath
import Runner (Summary(..))
import Run hiding (doctest)
import System.IO.Silently
import System.IO
withCurrentDirectory :: FilePath -> IO a -> IO a
withCurrentDirectory workingDir action = do
bracket getCurrentDirectory setCurrentDirectory $ \_ -> do
setCurrentDirectory workingDir
action
-- | Construct a doctest specific 'Assertion'.
doctest :: FilePath -- ^ current directory of `doctest` process
-> [String] -- ^ args, given to `doctest`
-> Summary -- ^ expected test result
-> Assertion
doctest workingDir args summary = do
r <- withCurrentDirectory ("test/integration" </> workingDir) (hSilence [stderr] $ doctest_ args)
assertEqual label summary r
where
label = workingDir ++ " " ++ show args
cases :: Int -> Summary
cases n = Summary n n 0 0
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "doctest" $ do
it "testSimple" $ do
doctest "." ["testSimple/Fib.hs"]
(cases 1)
it "failing" $ do
doctest "." ["failing/Foo.hs"]
(cases 1) {sFailures = 1}
it "skips subsequent examples from the same group if an example fails" $
doctest "." ["failing-multiple/Foo.hs"]
(cases 4) {sTried = 2, sFailures = 1}
it "testImport" $ do
doctest "testImport" ["ModuleA.hs"]
(cases 3)
doctest ".." ["-iintegration/testImport", "integration/testImport/ModuleA.hs"]
(cases 3)
it "testCommentLocation" $ do
doctest "." ["testCommentLocation/Foo.hs"]
(cases 11)
it "testPutStr" $ do
doctest "testPutStr" ["Fib.hs"]
(cases 3)
it "fails on multi-line expressions, introduced with :{" $ do
doctest "testFailOnMultiline" ["Fib.hs"]
(cases 2) {sErrors = 2}
it "testBlankline" $ do
doctest "testBlankline" ["Fib.hs"]
(cases 1)
it "examples from the same Haddock comment share the same scope" $ do
doctest "testCombinedExample" ["Fib.hs"]
(cases 4)
it "testDocumentationForArguments" $ do
doctest "testDocumentationForArguments" ["Fib.hs"]
(cases 1)
it "template-haskell" $ do
doctest "template-haskell" ["Foo.hs"]
(cases 2)
it "handles source files with CRLF line endings" $ do
doctest "dos-line-endings" ["Fib.hs"]
(cases 1)
it "runs $setup before each test group" $ do
doctest "setup" ["Foo.hs"]
(cases 2)
it "skips subsequent tests from a module, if $setup fails" $ do
doctest "setup-skip-on-failure" ["Foo.hs"]
(cases 3) {sTried = 1, sFailures = 1}
it "works with additional object files" $ do
doctest "with-cbits" ["Bar.hs", "../../../dist/build/spec/spec-tmp/test/integration/with-cbits/foo.o"]
(cases 1)
it "ignores trailing whitespace when matching test output" $ do
doctest "trailing-whitespace" ["Foo.hs"]
(cases 1)
describe "doctest as a runner for QuickCheck properties" $ do
it "runs a boolean property" $ do
doctest "property-bool" ["Foo.hs"]
(cases 1)
it "runs an explicitly quantified property" $ do
doctest "property-quantified" ["Foo.hs"]
(cases 1)
it "runs an implicitly quantified property" $ do
doctest "property-implicitly-quantified" ["Foo.hs"]
(cases 1)
it "reports a failing property" $ do
doctest "property-failing" ["Foo.hs"]
(cases 1) {sFailures = 1}
it "runs a boolean property with an explicit type signature" $ do
doctest "property-bool-with-type-signature" ["Foo.hs"]
(cases 1)
it "runs $setup before each property" $ do
doctest "property-setup" ["Foo.hs"]
(cases 3)
describe "doctest (regression tests)" $ do
it "bugfixWorkingDirectory" $ do
doctest "bugfixWorkingDirectory" ["Fib.hs"]
(cases 1)
doctest "bugfixWorkingDirectory" ["examples/Fib.hs"]
(cases 2)
it "bugfixOutputToStdErr" $ do
doctest "bugfixOutputToStdErr" ["Fib.hs"]
(cases 2)
it "bugfixImportHierarchical" $ do
doctest "bugfixImportHierarchical" ["ModuleA.hs", "ModuleB.hs"]
(cases 3)
it "bugfixMultipleModules" $ do
doctest "bugfixMultipleModules" ["ModuleA.hs"]
(cases 5)
it "testCPP" $ do
doctest "testCPP" ["-cpp", "Foo.hs"]
(cases 1) {sFailures = 1}
doctest "testCPP" ["-cpp", "-DFOO", "Foo.hs"]
(cases 1)
it "template-haskell-bugfix" $ do
doctest "template-haskell-bugfix" ["Main.hs"]
(cases 2)
|
ekmett/doctest
|
test/MainSpec.hs
|
mit
| 4,830 | 0 | 16 | 1,269 | 1,268 | 610 | 658 | 122 | 1 |
module Lamdu.Data.Db
( withDB, ImplicitFreshDb(..)
) where
import Control.Exception (onException)
import qualified Lamdu.Data.Db.Init as DbInit
import Lamdu.Data.Db.Layout (DbM(..), ViewM, curDbSchemaVersion)
import Lamdu.Data.Export.JSON (fileImportAll)
import qualified Lamdu.Paths as Paths
import qualified Revision.Deltum.Db as Db
import Revision.Deltum.Transaction (Transaction)
import qualified Revision.Deltum.Transaction as Transaction
import qualified System.Directory as Directory
import System.FilePath ((</>))
import Lamdu.Prelude
type T = Transaction
data ImplicitFreshDb = ImplicitFreshDb | NoImplicitFreshDb | FailIfFresh String
deriving (Eq, Show)
importFreshDb :: ImplicitFreshDb -> IO (T ViewM ())
importFreshDb NoImplicitFreshDb = pure (pure ())
importFreshDb (FailIfFresh msg) = fail msg
importFreshDb ImplicitFreshDb =
Paths.getDataFileName "freshdb.json" >>= fileImportAll <&> snd
withDB :: FilePath -> ImplicitFreshDb -> (Transaction.Store DbM -> IO a) -> IO a
withDB lamduDir implicitFreshDb body =
do
Directory.createDirectoryIfMissing False lamduDir
alreadyExist <- Directory.doesDirectoryExist dbPath
let options =
Db.defaultOptions
{ Db.createIfMissing = not alreadyExist
, Db.errorIfExists = not alreadyExist
}
Db.withDB dbPath options $
\ioDb ->
do
let db = Transaction.onStoreM DbM ioDb
let dbInit = importFreshDb implicitFreshDb >>= DbInit.initDb db
dbInit `onException` Directory.removeDirectoryRecursive dbPath
& unless alreadyExist
body db
where
dbPath = lamduDir </> "schema-" <> show curDbSchemaVersion <> ".db"
|
lamdu/lamdu
|
src/Lamdu/Data/Db.hs
|
gpl-3.0
| 1,851 | 0 | 16 | 481 | 455 | 249 | 206 | 39 | 1 |
class GeenWhere a
|
roberth/uu-helium
|
test/typeClassesParse/ClassEmptyWhere.hs
|
gpl-3.0
| 26 | 0 | 5 | 11 | 8 | 3 | 5 | -1 | -1 |
{-
Copyright 2012-2013 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Plush.Job (
-- * Shell Thread
startShell,
ShellThread,
-- * Jobs
submitJob,
pollJobs,
offerInput,
withHistory,
) where
import Control.Applicative ((<$>))
import Control.Concurrent
import Control.Monad (forM_, unless, void)
import qualified Control.Monad.Exception as Exception
import System.Exit
import System.Posix
import qualified System.Posix.Missing as PM
import Plush.Job.History
import Plush.Job.Output
import Plush.Job.StdIO
import Plush.Job.Types
import Plush.Run
import Plush.Run.Execute (execute)
import Plush.Run.ExecuteType (execType, ExecuteType(..))
import Plush.Run.Posix.Utilities (writeStr)
import Plush.Run.Script (parse)
import Plush.Run.ShellExec (getFlags, setFlags)
import qualified Plush.Run.ShellFlags as F
import Plush.Run.Types (statusExitCode)
-- | An opaque type, holding information about a running job.
-- See 'gatherOutput'
data RunningState = RS {
rsIO :: RunningIO
, rsProcessID :: Maybe ProcessID
, rsCheckDone :: IO ()
, rsHistory :: HistoryFile
}
-- | A job can be in one of these states:
data Status
= Running RunningState
-- ^ the 'RunningState' value can be used with 'gatherOutput'
| JobDone ExitCode [OutputItem]
-- ^ the exit status of the job, and any remaining gathered output
| ParseError String
-- ^ the command didn't parse
type ScoreBoard = [(JobName, Status)]
-- | A handle to the shell thread.
data ShellThread = ShellThread
{ stJobRequest :: MVar CommandRequest
, stScoreBoard :: MVar ScoreBoard
, stHistory :: MVar History
}
-- | Start the shell as an indpendent thread, which will process jobs and
-- report on their status.
--
-- N.B.: The shell uses 'stdout' and 'stderr' for its own purposes, and so after
-- the shell is stated, they must not be used for communicating. The returned
-- handles are tied to the original 'stdout' and 'stderr' and can be used to
-- communicate to the original streams.
startShell :: IO Runner -> IO (ShellThread, Fd, Fd)
startShell mkRunner = do
origInFd <- PM.dupFdCloseOnExec stdInput upperFd
origOutFd <- PM.dupFdCloseOnExec stdOutput upperFd
origErrFd <- PM.dupFdCloseOnExec stdError upperFd
reserveShellFds
foregroundStdIOParts <- makeStdIOParts
foregroundRIO <- stdIOLocalPrep foregroundStdIOParts
runner <- mkRunner
jobRequestVar <- newEmptyMVar
scoreBoardVar <- newMVar []
historyVar <- initHistory runner >>= newMVar
let st = ShellThread jobRequestVar scoreBoardVar historyVar
let childPrep = do
mapM_ closeFd [origInFd, origOutFd, origErrFd]
stdIOCloseMasters foregroundStdIOParts
_ <- forkIO $ shellThread st foregroundRIO origErrFd childPrep runner
return (st, origOutFd, origErrFd)
where
upperFd = Fd 20
-- | Reserve FDs 0 - 9 as these can addressed by shell commands.
reserveShellFds = do
devNullFd <- openFd "/dev/null" ReadWrite Nothing defaultFileFlags
forM_ [0..9] $ \fd -> do
unless (devNullFd == fd) $ void $ dupTo devNullFd fd
setFdOption fd CloseOnExec True
unless (devNullFd <= 0) $ closeFd devNullFd
shellThread :: ShellThread -> RunningIO -> Fd -> IO () -> Runner -> IO ()
shellThread st foregroundRIO origErrFd childPrep = go
where
go runner =
(takeMVar (stJobRequest st) >>= runJob' runner >>= go)
`Exception.catchAll`
(\e -> writeStr origErrFd (show e) >> go runner)
runJob' = runJob st foregroundRIO childPrep
runJob :: ShellThread -> RunningIO -> IO () -> Runner -> CommandRequest -> IO Runner
runJob st foregroundRIO childPrep r0
cr@(CommandRequest j record (CommandItem cmd)) = do
(pr, r1) <- run (parse cmd) r0
-- This won't echo even if verbose (-v) or parseout (-P) are set
case pr of
Left errs -> parseError errs >> return r1
Right (cl, _rest) -> do
(et, r2) <- run (execType cl) r1
case et of
ExecuteForeground -> foreground cl r2
ExecuteMidground -> background cl r2
ExecuteBackground -> foreground cl r2 -- TODO: fix!
where
foreground cl runner = do
setUp Nothing foregroundRIO (return ())
(status, runner') <- runCommand cl runner
cleanUp (return ()) $ statusExitCode status
return runner'
background cl runner = do
sp <- makeStdIOParts
pid <- forkProcess $ do
childPrep
stdIOChildPrep sp
(status, _runner') <- runCommand cl runner
exitWith $ statusExitCode status
rio <- stdIOMasterPrep sp
setUp (Just pid) rio $ checkUp (stdIOCloseMasters sp) pid
return runner
runCommand cl runner = run (runEnv $ execute cl) runner
runEnv act = if record
then act
else Exception.bracket getFlags setFlags $
\f -> setFlags (utilFlags f) >> act
-- If the command is not being recorded, it is being run by the
-- the front end itself. In this case, don't let the noexec (-n)
-- or xtrace (-x) interfere with the execution or output.
utilFlags f = f { F.noexec = False, F.xtrace = False }
parseError errs =
modifyMVar_ (stScoreBoard st) $ \sb ->
return $ (j, ParseError errs) : sb
setUp mpid rio checker = do
hFd <- modifyMVar (stHistory st) $ startHistory cr
let rs = RS rio mpid checker hFd
writeHistory (rsHistory rs) (HiCommand $ CommandItem cmd)
modifyMVar_ (stScoreBoard st) $ \sb ->
return $ (j, Running rs) : sb
checkUp closeMs pid = do
mStat <- getProcessStatus False False pid
case mStat of
Nothing -> return ()
Just (Exited ec) -> cleanUp closeMs ec
Just Terminated {} -> cleanUp closeMs $ ExitFailure 129
Just (Stopped _) -> return ()
cleanUp closeMs exitCode = do
modifyMVar_ (stScoreBoard st) $ \sb -> do
let (f,sb') = findJob j sb
case f of
Just (Running rs') -> do
oi <- gatherOutput rs'
writeHistory (rsHistory rs')
$ HiFinished $ FinishedItem exitCode
endHistory (rsHistory rs')
return $ (j, JobDone exitCode oi):sb'
_ -> return sb
closeMs
-- | Submit a job for processing.
-- N.B.: This may block until the shell thread is able to receive a request.
submitJob :: ShellThread -> CommandRequest -> IO ()
submitJob st cr = putMVar (stJobRequest st) cr
-- | Poll jobs for status. A `RunningItem` or `FinishedItem` is returned for
-- each job the shell knows about. `OutputItem` entries may be returned for
-- either kind of job, and will come first.
--
-- N.B.: Finished jobs are removed from internal book-keeping once reviewed.
pollJobs :: ShellThread -> IO [ReportOne StatusItem]
pollJobs st = do
readMVar (stScoreBoard st) >>= sequence_ . map checker
modifyMVar (stScoreBoard st) $ \sb -> do
r <- mapM (uncurry report) sb
return (filter running sb, concat r)
where
checker (_, Running rs) = rsCheckDone rs
checker _ = return ()
running (_, Running _) = True
running _ = False
report :: JobName -> Status -> IO [ReportOne StatusItem]
report job (Running rs) = do
ois <- gatherOutput rs
report' job ois $ SiRunning RunningItem
report job (JobDone e ois) =
report' job ois $ SiFinished (FinishedItem e)
report job (ParseError e) = return $ map (ReportOne job)
[ SiParseError (ParseErrorItem e)
, SiFinished (FinishedItem $ ExitFailure 2)
]
report' job ois si = return $ map (ReportOne job) $ map SiOutput ois ++ [si]
-- | Gather as much output is available from stdout, stderr, and jsonout.
-- Note that the order of output to stderr and stdout is lost given the way we
-- collect these from separate pttys. This infelicity is the trade off for being
-- able which text came from stderr vs. stdout. stderr is gathered and reported
-- which tends to work better. It also ensures that xtrace (-x) output preceeds
-- the command's output.
gatherOutput :: RunningState -> IO [OutputItem]
gatherOutput rs = do
err <- wrap OutputItemStdErr <$> getAvailable (rioStdErr $ rsIO rs)
out <- wrap OutputItemStdOut <$> getAvailable (rioStdOut $ rsIO rs)
jout <- wrap OutputItemJsonOut <$> getAvailable (rioJsonOut $ rsIO rs)
let ois = err ++ out ++ jout
mapM_ (writeOutput (rsHistory rs)) ois
return ois
where
wrap _ [] = []
wrap c vs = [c vs]
-- | Find a job by name in a 'ScoreBoard'. Returns the first 'Status' found,
-- if any, and a copy of the 'ScoreBoard' without that job enry.
findJob :: JobName -> ScoreBoard -> (Maybe Status, ScoreBoard)
findJob j ((j',s):sbs) | j == j' = (Just s,sbs)
findJob j (sb:sbs) = let (s,sbs') = findJob j sbs in (s,sb:sbs')
findJob _ [] = (Nothing,[])
-- | Give input to a running job. If the job isn't running, then the input is
-- dropped on the floor.
offerInput :: ShellThread -> JobName -> InputItem -> IO ()
offerInput st job input = modifyMVar_ (stScoreBoard st) $ \sb -> do
case findJob job sb of
(Just (Running rs), _) -> send input rs
-- TODO: should catch errors here
_ -> return ()
return sb
where
send (InputItemInput s) rs = writeStr (rioStdIn $ rsIO rs) s
send (InputItemEof) rs = closeFd (rioStdIn $ rsIO rs)
send (InputItemSignal sig) rs =
maybe (return ()) (signalProcess sig) $ rsProcessID rs
-- | Wrapper for adapting functions on History.
withHistory :: ShellThread -> (History -> IO a) -> IO a
withHistory st = withMVar (stHistory st)
|
kustomzone/plush
|
src/Plush/Job.hs
|
apache-2.0
| 10,433 | 0 | 22 | 2,727 | 2,679 | 1,348 | 1,331 | 181 | 9 |
{-# OPTIONS -Wall #-}
module Examples.HMM where
import Prelude hiding (Real)
import Language.Hakaru.Syntax
import Language.Hakaru.Expect (Expect(..))
import Language.Hakaru.Sample (Sample(..))
import System.Random.MWC (withSystemRandom)
import Control.Monad (replicateM)
import Data.Number.LogFloat (LogFloat)
-- Conditional probability tables (ignore Expect and unExpect on first reading)
type Table = Vector (Vector Prob)
reflect :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr Table -> Expect repr (Int -> Measure Int)
reflect m = lam (\i -> let v = index (Expect m) i
in weight (summateV v) (categorical v))
reify :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr Int -> repr Int ->
Expect repr (Int -> Measure Int) -> repr Table
reify domainSize rangeSize m =
vector domainSize (\i ->
vector rangeSize (\j ->
app (snd_ (app (unExpect m) i)) (lam (\j' -> if_ (equal j j') 1 0))))
--------------------------------------------------------------------------------
-- Model: A one-dimensional random walk among 20 discrete states (numbered
-- 0 through 19 and arranged in a row) starting at state 10 at time 0.
-- Query: Given that the state is less than 8 at time 6,
-- what's the posterior distribution over states at time 12?
type Time = Int
type State = Int
-- hmm is a model that disintegration might produce: it already incorporates
-- the observed data, hence "emission ... bind_ ... unit".
hmm :: (Mochastic repr, Lambda repr) => repr (Measure State)
hmm = liftM snd_ (app (chain (vector (12+1) $ \t ->
lam $ \s ->
emission t s `bind_`
transition s `bind` \s' ->
dirac (pair unit s')))
10)
emission :: (Mochastic repr) =>
repr Time -> repr State -> repr (Measure ())
emission t s = if_ (equal t 6)
(if_ (less s 8) (dirac unit) (superpose []))
(dirac unit)
transition :: (Mochastic repr) => repr State -> repr (Measure State)
transition s = categorical (vector 20 (\s' ->
if_ (and_ [less (s-2) s', less s' (s+2)]) 1 0))
-- Because our observed data has substantial probability (unlike in practice),
-- we can even sample blindly to answer the query approximately.
try :: IO [Maybe (Int, LogFloat)]
try = replicateM 100
$ withSystemRandom
$ unSample (hmm :: Sample IO (Measure State)) 1
-- Using the default implementation of "chain" in terms of "reduce",
-- and eliminating the "unit"s, we can simplify "hmm" to
hmm' :: (Mochastic repr, Lambda repr) => repr (Measure State)
hmm' = app (chain' (vector 13 $ \t ->
lam $ \s ->
emission t s `bind_`
transition s `bind` \s' ->
dirac s'))
10
chain' :: (Mochastic repr, Lambda repr) =>
repr (Vector (a -> Measure a)) -> repr (a -> Measure a)
chain' = reduce bindo (lam dirac)
-- in which the type of reduced elements is "State -> Measure State".
-- To compute this exactly in polynomial time, we just need to represent these
-- elements as tables instead. That is, we observe that all our values of type
-- "State -> Measure State" have the form "reflect m", and
-- bindo (reflect m) (reflect n) == reflect (bindo' m n)
-- in which bindo', defined below, runs in polynomial time given m and n.
-- So we can simplify "hmm'" to
hmm'' :: (Mochastic repr, Lambda repr, Integrate repr) =>
Expect repr (Measure State)
hmm'' = app (reflect (chain'' (vector 13 $ \t ->
reify 20 20 $
lam $ \s ->
emission (Expect t) s `bind_`
transition s `bind` \s' ->
dirac s')))
10
chain'' :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr (Vector Table) -> repr Table
chain'' = reduce bindo' (reify 20 20 (lam dirac))
bindo' :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr Table -> repr Table -> repr Table
bindo' m n = reify 20 20 (bindo (reflect m) (reflect n))
-- Of course bindo' can be optimized a lot further internally, but this is the
-- main idea. We are effectively multiplying matrix*matrix*...*matrix*vector,
-- so it would also be better to associate these multiplications to the right.
|
bitemyapp/hakaru
|
Examples/HMM.hs
|
bsd-3-clause
| 4,483 | 0 | 19 | 1,281 | 1,216 | 641 | 575 | 67 | 1 |
module HLearn.Models.Classifiers.Perceptron
where
import qualified Data.Map as Map
import qualified Data.Vector.Unboxed as VU
import HLearn.Algebra
import HLearn.Models.Distributions
import HLearn.Models.Classifiers.Common
import HLearn.Models.Classifiers.Centroid
import HLearn.Models.Classifiers.NaiveNN
-------------------------------------------------------------------------------
-- data structures
data Perceptron label dp = Perceptron
{ centroids :: Map.Map label (Centroid dp)
}
-- deriving (Read,Show,Eq,Ord)
deriving instance (Show (Centroid dp), Show label) => Show (Perceptron label dp)
-------------------------------------------------------------------------------
-- algebra
instance (Ord label, Monoid (Centroid dp)) => Monoid (Perceptron label dp) where
mempty = Perceptron mempty
p1 `mappend` p2 = Perceptron
{ centroids = Map.unionWith (<>) (centroids p1) (centroids p2)
}
-------------------------------------------------------------------------------
-- model
instance
( Monoid dp
, Num (Scalar dp)
, Ord label
) => HomTrainer (Perceptron label dp)
where
type Datapoint (Perceptron label dp) = (label,dp)
train1dp (label,dp) = Perceptron $ Map.singleton label $ train1dp dp
-------------------------------------------------------------------------------
-- classification
instance Probabilistic (Perceptron label dp) where
type Probability (Perceptron label dp) = Scalar dp
-- instance
-- ( Ord label
-- , Ord (Scalar dp)
-- , MetricSpace (Centroid dp)
-- , Monoid dp
-- , HasScalar dp
-- , label ~ Scalar dp
-- ) => ProbabilityClassifier (Perceptron label dp)
-- where
-- type ResultDistribution (Perceptron label dp) = (Categorical (Scalar dp) label)
--
-- probabilityClassify model dp = probabilityClassify nn (train1dp (dp) :: Centroid dp)
-- where
-- nn = NaiveNN $ Map.toList $ centroids model
--
-- instance
-- ( ProbabilityClassifier (Perceptron label dp)
-- , Ord dp
-- , Ord (Scalar dp)
-- , Ord label
-- , Num (Scalar dp)
-- ) => Classifier (Perceptron label dp)
-- where
-- classify model dp = mean $ probabilityClassify model dp
|
iamkingmaker/HLearn
|
src/HLearn/Models/Classifiers/Perceptron.hs
|
bsd-3-clause
| 2,296 | 0 | 11 | 497 | 378 | 225 | 153 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
-- | Likes handling
-- <http://instagram.com/developer/endpoints/likes/#>
module Instagram.Likes (
getLikes
,like
,unlike
)where
import Instagram.Monad
import Instagram.Types
import qualified Network.HTTP.Types as HT
-- | Get a list of users who have liked this media.
getLikes :: (MonadBaseControl IO m, MonadResource m) => MediaID
-> Maybe OAuthToken
-> InstagramT m (Envelope [User])
getLikes mid token =getGetEnvelopeM ["/v1/media/",mid,"/likes"] token ([]::HT.Query)
-- | Set a like on this media by the currently authenticated user.
like :: (MonadBaseControl IO m, MonadResource m) => MediaID
-> OAuthToken
-> InstagramT m (Envelope NoResult)
like mid token =getPostEnvelope ["/v1/media/",mid,"/likes"] token ([]::HT.Query)
-- | Remove a like on this media by the currently authenticated user.
unlike :: (MonadBaseControl IO m, MonadResource m) => MediaID
-> OAuthToken
-> InstagramT m (Envelope NoResult)
unlike mid token =getDeleteEnvelope ["/v1/media/",mid,"/likes"] token ([]::HT.Query)
|
potomak/ig
|
src/Instagram/Likes.hs
|
bsd-3-clause
| 1,068 | 0 | 11 | 171 | 279 | 156 | 123 | 20 | 1 |
-------------------------------------------------------------------------------
-- |
-- Module : OpenAI.Gym.Data
-- License : BSD3
-- Stability : experimental
-- Portability: non-portable
-------------------------------------------------------------------------------
module Data.Gym
where
{-
( GymEnv (..)
, InstID (..)
, Environment (..)
, Observation (..)
, Step (..)
, Outcome (..)
, Info (..)
, Action (..)
, Monitor (..)
, Config (..)
) where
import Reinforce.Prelude
import Data.HashMap.Strict
import Data.Aeson -- ((.=), ToJSON(..), FromJSON(..))
data GymEnv
-- | Classic Control Environments
= CartPoleV0 -- ^ Balance a pole on a cart (for a short time).
| CartPoleV1 -- ^ Balance a pole on a cart.
| AcrobotV1 -- ^ Swing up a two-link robot.
| MountainCarV0 -- ^ Drive up a big hill.
| MountainCarContinuousV0 -- ^ Drive up a big hill with continuous control.
| PendulumV0 -- ^ Swing up a pendulum.
-- Toy text games
| FrozenLakeV0 -- ^ Swing up a pendulum.
-- | Atari Games
| PongRamV0 -- ^ Maximize score in the game Pong, with RAM as input
| PongV0 -- ^ Maximize score in the game Pong
deriving (Eq, Enum, Ord)
instance Show GymEnv where
show CartPoleV0 = "CartPole-v0"
show CartPoleV1 = "CartPole-v1"
show AcrobotV1 = "Acrobot-v1"
show MountainCarV0 = "MountainCar-v0"
show MountainCarContinuousV0 = "MountainCarContinuous-v0"
show PendulumV0 = "Pendulum-v0"
show FrozenLakeV0 = "FrozenLake-v0"
show PongRamV0 = "Pong-ram-v0"
show PongV0 = "Pong-v0"
instance ToJSON GymEnv where
toJSON env = object [ "env_id" .= show env ]
data InstID = InstID !Text
deriving (Eq, Show, Generic)
instance ToJSON InstID where
toJSON (InstID i) = toSingleton "instance_id" i
instance FromJSON InstID where
parseJSON = parseSingleton InstID "instance_id"
newtype Environment = Environment { all_envs :: HashMap Text Text }
deriving (Eq, Show, Generic)
instance ToJSON Environment
instance FromJSON Environment
data Observation = Observation !Value
deriving (Eq, Show, Generic)
instance ToJSON Observation where
toJSON (Observation v) = toSingleton "observation" v
instance FromJSON Observation where
parseJSON = parseSingleton Observation "observation"
data Step = Step
{ action :: !Value
, render :: !Bool
} deriving (Eq, Generic, Show)
instance ToJSON Step
data Outcome = Outcome
{ observation :: !Value
, reward :: !Double
, done :: !Bool
, info :: !Object
} deriving (Eq, Show, Generic)
instance ToJSON Outcome
instance FromJSON Outcome
data Info = Info !Object
deriving (Eq, Show, Generic)
instance ToJSON Info where
toJSON (Info v) = toSingleton "info" v
instance FromJSON Info where
parseJSON = parseSingleton Info "info"
data Action = Action !Value
deriving (Eq, Show, Generic)
instance ToJSON Action where
toJSON (Action v) = toSingleton "action" v
instance FromJSON Action where
parseJSON = parseSingleton Action "action"
data Monitor = Monitor
{ directory :: !Text
, force :: !Bool
, resume :: !Bool
, video_callable :: !Bool
} deriving (Generic, Eq, Show)
instance ToJSON Monitor
data Config = Config
{ training_dir :: !Text
, algorithm_id :: !Text
, api_key :: !Text
} deriving (Generic, Eq, Show)
instance ToJSON Config
-}
|
stites/reinforce
|
reinforce-environments/src/Data/Gym.hs
|
bsd-3-clause
| 3,572 | 0 | 3 | 913 | 14 | 12 | 2 | 1 | 0 |
-- | Interface to the management event bus.
module Control.Distributed.Process.Management.Internal.Bus
( publishEvent
) where
import Control.Distributed.Process.Internal.CQueue
( enqueue
)
import Control.Distributed.Process.Internal.Types
( MxEventBus(..)
, Message
)
import Data.Foldable (forM_)
import System.Mem.Weak (deRefWeak)
publishEvent :: MxEventBus -> Message -> IO ()
publishEvent MxEventBusInitialising _ = return ()
publishEvent (MxEventBus _ _ wqRef _) msg = do
mQueue <- deRefWeak wqRef
forM_ mQueue $ \queue -> enqueue queue msg
|
qnikst/distributed-process
|
src/Control/Distributed/Process/Management/Internal/Bus.hs
|
bsd-3-clause
| 571 | 0 | 9 | 93 | 155 | 88 | 67 | 14 | 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="sr-SP">
<title>Groovy Support</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>
|
thc202/zap-extensions
|
addOns/groovy/src/main/javahelp/org/zaproxy/zap/extension/groovy/resources/help_sr_SP/helpset_sr_SP.hs
|
apache-2.0
| 959 | 82 | 52 | 156 | 390 | 206 | 184 | -1 | -1 |
-- Refactoring: move myFringe to module D3. This example aims to test the change of qualifiers,
-- and the import/exports.
module C3(Tree(..), SameOrNot(..)) where
data Tree a = Leaf a | Branch (Tree a) (Tree a)
sumTree:: (Num a) => Tree a -> a
sumTree (Leaf x ) = x
sumTree (Branch left right) = sumTree left + sumTree right
class SameOrNot a where
isSame :: a -> a -> Bool
isNotSame :: a -> a -> Bool
instance SameOrNot Int where
isSame a b = a == b
isNotSame a b = a /= b
|
SAdams601/HaRe
|
old/testing/moveDefBtwMods/C3_TokOut.hs
|
bsd-3-clause
| 500 | 0 | 8 | 120 | 183 | 98 | 85 | 11 | 1 |
import Control.Concurrent
import Control.Exception
-- Test blocking of async exceptions in an exception handler.
-- The exception raised in the main thread should not be delivered
-- until the first exception handler finishes.
main = do
main_thread <- myThreadId
m <- newEmptyMVar
forkIO (do { takeMVar m; throwTo main_thread (ErrorCall "foo") })
(do { throwIO (ErrorCall "wibble")
`Control.Exception.catch`
(\e -> let _ = e::ErrorCall in
do putMVar m (); evaluate (sum [1..10000]); putStrLn "done.")
; myDelay 500000 })
`Control.Exception.catch`
\e -> putStrLn ("caught: " ++ show (e::SomeException))
-- compensate for the fact that threadDelay is non-interruptible
-- on Windows with the threaded RTS in 6.6.
myDelay usec = do
m <- newEmptyMVar
forkIO $ do threadDelay usec; putMVar m ()
takeMVar m
|
tjakway/ghcjvm
|
testsuite/tests/concurrent/should_run/conc014.hs
|
bsd-3-clause
| 864 | 4 | 21 | 185 | 243 | 122 | 121 | 17 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies,
FlexibleInstances, UndecidableInstances #-}
-- UndecidableInstances now needed because the Coverage Condition fails
module ShouldFail where
-- A stripped down functional-dependency
-- example that causes GHC 4.08.1 to crash with:
-- "basicTypes/Var.lhs:194: Non-exhaustive patterns in function readMutTyVar"
-- Reported by Thomas Hallgren Nov 00
-- July 07: I'm changing this from "should fail" to "should succeed"
-- See Note [Important subtlety in oclose] in FunDeps
primDup :: Int -> IO Int
primDup = undefined
dup () = call primDup
-- call :: Call c h => c -> h
--
-- call primDup :: {Call (Int -> IO Int) h} => h with
-- Using the instance decl gives
-- call primDup :: {Call (IO Int) h'} => Int -> h'
-- The functional dependency means that h must be constant
-- Hence program is rejected because it can't find an instance
-- for {Call (IO Int) h'}
class Call c h | c -> h where
call :: c -> h
instance Call c h => Call (Int->c) (Int->h) where
call f = call . f
|
lukexi/ghc-7.8-arm64
|
testsuite/tests/typecheck/should_fail/tcfail093.hs
|
bsd-3-clause
| 1,075 | 0 | 7 | 227 | 121 | 71 | 50 | 10 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.