code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE CPP, MagicHash, UnboxedTuples, ForeignFunctionInterface #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.STM.TVar
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- TVar: Transactional variables
--
-----------------------------------------------------------------------------
module Control.STMHaskell.STM (
-- * TVars
STM,
TVar,
atomically,
newTVar,
readTVar,
writeTVar,
printStats
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.Conc
#else
import Control.Sequential.STM
#endif
foreign import ccall "stmPrintStats" printStats :: IO()
| ml9951/ghc | libraries/pastm/Control/STMHaskell/STM.hs | bsd-3-clause | 973 | 0 | 7 | 189 | 78 | 56 | 22 | 11 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Server.ServerT where
import Control.Lens (makeLenses)
import qualified Data.Vector as V
import qualified Constants
import Game.EntityStateT
import QCommon.SizeBufT
import Types
makeLenses ''ServerT
newServerT :: ServerT
newServerT = ServerT
{ _sState = 0
, _sAttractLoop = False
, _sLoadGame = False
, _sTime = 0
, _sFrameNum = 0
, _sName = ""
, _sModels = V.replicate Constants.maxModels (Ref (-1))
, _sConfigStrings = V.replicate Constants.maxConfigStrings ""
, _sBaselines = V.replicate Constants.maxEdicts (newEntityStateT Nothing)
, _sMulticast = newSizeBufT
, _sMulticastBuf = ""
, _sDemoFile = Nothing
, _sTimeDemo = 0
} | ksaveljev/hake-2 | src/Server/ServerT.hs | bsd-3-clause | 842 | 0 | 11 | 267 | 184 | 111 | 73 | 24 | 1 |
data Customer = Customer Int String [String]
deriving (Show)
customerID :: Customer -> Int
customerID (Customer id _ _) = id
customerName :: Customer -> String
customerName (Customer _ name _) = name
customerAddress :: Customer -> [String]
customerAddress (Customer _ _ address) = address
| NeonGraal/rwh-stack | ch03/AltCustomer.hs | bsd-3-clause | 308 | 0 | 7 | 64 | 108 | 57 | 51 | 8 | 1 |
module Tc.TcLcg where
-- this module implements the functions for compute
-- the least commom generalization of two simple
-- types.
import Control.Monad
import Control.Monad.Trans
import Data.Char
import Data.List
import qualified Data.Map as Map
import Language.Haskell.Exts
import Tc.TcMonad
import Tc.TcSubst
import Utils.ErrMsg
import Utils.Id
type Var = Type -- INVARIANT: Always hold a type variable
-- a historic of possible generalizations
type History = [((Type, Type), Var)]
-- the main lcg function
lcg :: Id -> [Type] -> TcM Type
lcg i ts
= do
(t,_) <- lcg' i ts []
return t
lcg' :: Id -> [Type] -> History -> TcM (Type, History)
lcg' i [t] h
= do
t' <- freshInst t
return (t', h)
lcg' i (t:ts) h
= do
(ctxs, ts') <- liftM (unzip . map splitTy) (mapM freshInst ts)
(t',h') <- lcgn' ts' h
(ctxi,ti) <- liftM splitTy (freshInst t)
(t'', h'') <- lcgp t' ti h'
let vs = (tv t'') \\ (tv t' ++ tv ti)
vs' = tv ctxs `union` tv ctxi
s = gensubst vs' h''
cs = apply s (concat ctxs ++ ctxi)
return (TyForall Nothing (nub $ (gen i vs) ++ cs) t'', h'')
lcg' i [] _ = emptyLcgList
gensubst :: [Var] -> History -> Subst
gensubst vs h
= foldr step [] h
where
step ((t1,t2),t) ac
| t1 `elem` vs || t2 `elem` vs = (t1,t) : (t2,t) : ac
| otherwise = ac
lcgp :: Type -> Type -> History -> TcM (Type, History)
lcgp t1 t2 h
= case lookup (t1,t2) h of
Just v -> return (v,h)
Nothing -> lcgp' t1 t2 h
lcgp' :: Type -> Type -> History -> TcM (Type, History)
lcgp' t1@(TyVar _) t2@(TyVar _) h
= return (t1, ((t1,t2),t1):h)
lcgp' t1@(TyVar _) t2 h
= do
v <- newFreshVar
return (v, ((t1,t2),v):h)
lcgp' t1 t2@(TyVar _) h
= do
v <- newFreshVar
return (v, ((t1,t2),v):h)
lcgp' t1@(TyCon c1) t2@(TyCon c2) h
| c1 == c2 = return (t1,h)
| otherwise
= do
v <- newFreshVar
return (v, ((t1,t2), v) : h)
lcgp' t1@(TyFun l1 r1) t2@(TyFun l2 r2) h
= do
(lr,h1) <- lcgp l1 l2 h
(rr,h2) <- lcgp r1 r2 h1
return (TyFun lr rr,h2)
lcgp' (TyApp l1 r1) (TyApp l2 r2) h
= do
(lr,h1) <- lcgp l1 l2 h
(rr,h2) <- lcgp r1 r2 h1
return (TyApp lr rr,h2)
lcgp' (TyList t) (TyList t') h
= do
(tr, h') <- lcgp t t' h
return (TyList tr, h')
lcgp' t1@(TyTuple x ts) t2@(TyTuple y ts') h
| length ts == length ts'
= do
(tr, h') <- lcgzip ts ts' h
return (TyTuple x tr, h')
| otherwise
= do
v <- newFreshVar
return (v, ((t1,t2),v):h)
lcgp' t1@(TyApp l r) t2@(TyList t) h
= lcgp' (toListApp t) (TyApp l r) h
lcgp' t1@(TyList t) t2@(TyApp l r) h
= lcgp' (toListApp t) (TyApp l r) h
lcgp' t1@(TyTuple _ ts) t2@(TyApp l r) h
= lcgp' (toTupleApp ts) (TyApp l r) h
lcgp' t1@(TyApp l r) t2@(TyTuple _ ts) h
= lcgp' (toTupleApp ts) (TyApp l r) h
lcgp' (TyParen t) (TyParen t') h
= do
(tf, h') <- lcgp' t t' h
return (TyParen tf, h')
lcgp' t1 t2 h
= do
v <- newFreshVar
return (v, ((t1,t2),v):h)
lcgn' :: [Type] -> History -> TcM (Type, History)
lcgn' [t] h = return (t,h)
lcgn' [t1,t2] h = lcgp t1 t2 h
lcgn' (t1:t2:ts) h
= do
(ts',h') <- lcgn' ts h
(t',h'') <- lcgp t1 t2 h'
lcgp ts' t' h''
lcgzip :: [Type] -> [Type] -> History -> TcM ([Type], History)
lcgzip [] [] h' = return ([], h')
lcgzip (t:ts) (t':ts') h
= do
(tr, h') <- lcgp t t' h
lcgzip ts ts h'
gen :: Id -> [Type] -> [Asst]
gen i t
| isId i = [ClassA ii t]
| otherwise = [ClassA i' t]
where
i' = UnQual (Ident ("_" ++ (show i)))
ii = UnQual (Ident n)
n = let x = show i in (toUpper (head x) : tail x)
-- lcg of substitutions
lcgs :: [Subst] -> TcM Subst
lcgs ss
= do
let m = Map.toList $ foldr step Map.empty ss
step s ac = foldr go ac s
go (v,t) ac = Map.insertWith (++) v [t] ac
foldM (\ac (v,ts)
-> do {
(t', _) <- lcgn' ts [] ;
return ((v,t') : ac)
}) nullSubst m
-- some auxiliar functions
splitTy :: Type -> (Context, Type)
splitTy (TyForall _ ctx t) = (ctx,t)
splitTy t = ([],t)
isId = isLetter . head . show
| rodrigogribeiro/mptc | src/Tc/TcLcg.hs | bsd-3-clause | 4,623 | 3 | 15 | 1,659 | 2,268 | 1,183 | 1,085 | 138 | 2 |
module Main where
import System
import System.Cmd
import Language.MUDA.AST
import Language.MUDA.Parser
import Language.MUDA.PPrint
debugPrinter ast = do putStrLn $ "// [DBG]"
putStrLn $ show ast
main = do args <- getArgs
if length args > 0
then
do { runLex program (args !! 0) (args !! 0) debugPrinter }
else
error "muda"
| syoyo/MUDA | Main.hs | bsd-3-clause | 419 | 0 | 12 | 149 | 116 | 62 | 54 | 12 | 2 |
module Cauterize.Options where
import Cauterize.Version (versionString)
import Options.Applicative
data CautOpts = CautOpts
{ schemaFile :: FilePath
, specPath :: FilePath
} deriving (Show)
runWithOptions :: (CautOpts -> IO ()) -> IO ()
runWithOptions fn = do
mopts <- execParser options
case mopts of
Just opts -> fn opts
Nothing -> putStr versionString
options :: ParserInfo (Maybe CautOpts)
options = info (helper <*> o)
( fullDesc
`mappend` progDesc "Compile a Cauterize schema into a Cauterize specification"
)
where
o = flag' Nothing (long "version" `mappend` hidden)
<|> (Just <$> optParser)
optParser :: Parser CautOpts
optParser = CautOpts
<$> argument str
( metavar "SCHEMA"
`mappend` help "Cauterize schema input file."
)
<*> argument str
( metavar "SPEC"
`mappend` help "Cauterize specification output file."
)
| cauterize-tools/cauterize | bin/Cauterize/Options.hs | bsd-3-clause | 911 | 0 | 11 | 210 | 260 | 136 | 124 | 27 | 2 |
module EFA.Flow.Topology.Variable where
import qualified EFA.Flow.Topology.Index as Idx
import qualified EFA.Flow.Part.Index as PartIdx
import qualified EFA.Flow.SequenceState.Index as FlowIdx
import qualified EFA.Graph.Topology.Node as Node
import qualified EFA.Equation.RecordIndex as RecIdx
import qualified EFA.Equation.Record as Record
import qualified EFA.Report.Format as Format
import EFA.Report.Format (Format)
import EFA.Report.FormatValue
(FormatValue, formatValue,
FormatSignalIndex, formatSignalIndex)
data Signal node =
Energy (Idx.Energy node)
| Power (Idx.Power node)
| Eta (Idx.Eta node)
| DTime (Idx.DTime node)
| X (Idx.X node)
| Sum (Idx.Sum node)
deriving (Show, Eq, Ord)
type RecordSignal rec node = RecIdx.Record (Record.ToIndex rec) (Signal node)
class FormatSignalIndex t => Index t where
index :: t a -> Signal a
instance Index Idx.Energy where index = Energy
instance Index Idx.Power where index = Power
instance Index Idx.Eta where index = Eta
instance Index Idx.DTime where index = DTime
instance Index Idx.X where index = X
instance Index Idx.Sum where index = Sum
ident :: Format output => Signal node -> output
ident var =
case var of
Energy _idx -> Format.energy
Power _idx -> Format.power
Eta _idx -> Format.eta
X _idx -> Format.xfactor
DTime _idx -> Format.dtime
Sum _idx -> Format.signalSum
instance FlowIdx.Identifier Signal where
identifier = ident
formatSignalValue ::
(Format output, PartIdx.Format part, Node.C node) =>
Signal node -> part -> output
formatSignalValue var s =
case var of
Energy idx -> formatSignalIndex idx s
Power idx -> formatSignalIndex idx s
Eta idx -> formatSignalIndex idx s
X idx -> formatSignalIndex idx s
DTime idx -> formatSignalIndex idx s
Sum idx -> formatSignalIndex idx s
instance FormatSignalIndex Signal where
formatSignalIndex = formatSignalValue
instance (Node.C node) => FormatValue (Signal node) where
formatValue var =
case var of
Energy idx -> formatValue idx
Power idx -> formatValue idx
Eta idx -> formatValue idx
X idx -> formatValue idx
DTime idx -> formatValue idx
Sum idx -> formatValue idx
instance Idx.Identifier Signal where
identifier = ident
class FormatIndex idx where
formatIndex :: (Node.C node, Format output) => idx node -> output
instance FormatIndex Idx.Energy where
formatIndex = formatValue
instance FormatIndex Idx.Power where
formatIndex = formatValue
instance FormatIndex Idx.Eta where
formatIndex = formatValue
instance FormatIndex Idx.X where
formatIndex = formatValue
instance FormatIndex Idx.DTime where
formatIndex = formatValue
instance FormatIndex Idx.Sum where
formatIndex = formatValue
checkedLookup ::
(Node.C node, FormatIndex idx) =>
String -> (idx node -> t -> Maybe b) -> idx node -> t -> b
checkedLookup name lk idx =
maybe (error $
"Topology." ++ name ++
" " ++ Format.unUnicode (formatIndex idx)) id .
lk idx
| energyflowanalysis/efa-2.1 | src/EFA/Flow/Topology/Variable.hs | bsd-3-clause | 3,136 | 0 | 11 | 715 | 982 | 513 | 469 | 86 | 6 |
{-# LANGUAGE TypeSynonymInstances, OverlappingInstances, FlexibleInstances #-}
module Json (
Jsonable(..),
JsonArray,
JsonObject
) where
import Data.Char (toLower, toUpper)
import Data.List.Utils (join)
import qualified Text.Parse as Parse
import qualified Text.ParserCombinators.Poly.Plain as PolyPlain
import qualified Text.ParserCombinators.Poly.Base as PolyBase
import Json.Internal
type JsonArray a = [a]
type JsonObject a = [(String, a)]
class Jsonable a where
readJson :: Jsonable a => String -> Either String a
readJson = runParser parser
writeJson :: Jsonable a => a -> String
parser :: Parse.TextParser a
instance Jsonable String where
writeJson = show
parser = Parse.parseByRead "String"
instance Jsonable Integer where
writeJson = wrapQuote . show
parser = parseQuoted $ Parse.parseSigned Parse.parseDec
instance Jsonable Float where
writeJson = wrapQuote . show
parser = parseQuoted $ Parse.parseSigned Parse.parseFloat
-- Extra complication in here because I want to use the builtin methods to read/write
-- booleans, but in JSON booleans are all lowercase; in Haskell, they're uppercase for
-- the first letter.
instance Jsonable Bool where
readJson s = runParser Parse.word s >>= makeBool
where makeBool s = case s of
"true" -> Right True
"false" -> Right False
m -> Left $ m ++ " is not one of [true, false]"
-- Show gives capital T/F, and lowercase is "correct"
writeJson = firstToLower . show
where
firstToLower (x:xs) = toLower x:xs
-- A bit complicated because JSON bools are all lowercase
parser = Parse.word >>= readJsonBool
where
readJsonBool s = case s of
"true" -> return True
"false" -> return False
e -> fail $ "Expected true or false, got " ++ e
-- [ele1, ele2, ele3, ...]
instance (Jsonable a) => Jsonable (JsonArray a) where
writeJson = wrapBracket . join "," . map writeJson
parser = PolyBase.bracketSep lb sep rb parser
where
lb = satisfyAndDropWhitespace (=='[')
sep = satisfyAndDropWhitespace (==',')
rb = PolyPlain.satisfy (==']')
-- {"name": val1, "name": val2, ...}
instance (Jsonable a) => Jsonable (JsonObject a) where
writeJson = wrapBrace . join "," . map (\(a, b) -> writeJson a ++ ":" ++ writeJson b)
parser = PolyBase.bracketSep lb sep rb recordParser
where
recordParser = do
name <- parser
satisfyAndDropWhitespace (==':')
val <- parser; return (name, val)
lb = satisfyAndDropWhitespace (=='{')
sep = satisfyAndDropWhitespace (==',')
rb = PolyPlain.satisfy (=='}')
| dyreshark/learn-haskell | Json.hs | bsd-3-clause | 2,891 | 3 | 12 | 843 | 669 | 369 | 300 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
module Install.Fetch where
import Control.Monad.Error (MonadError, MonadIO, liftIO, throwError)
import qualified Codec.Archive.Zip as Zip
import qualified Data.List as List
import qualified Network.HTTP.Client as Client
import System.Directory (doesDirectoryExist, getDirectoryContents, renameDirectory)
import System.FilePath ((</>))
import qualified Elm.Package.Name as N
import qualified Elm.Package.Version as V
import qualified CommandLine.Helpers as Cmd
import qualified Utils.Http as Http
package :: (MonadIO m, MonadError String m) => N.Name -> V.Version -> m ()
package name@(N.Name user _) version =
ifNotExists name version $ do
Http.send zipball extract
files <- liftIO $ getDirectoryContents "."
case List.find (List.isPrefixOf user) files of
Nothing ->
throwError "Could not download source code successfully."
Just dir ->
liftIO $ renameDirectory dir (V.toString version)
where
zipball =
"http://github.com/" ++ N.toUrl name ++ "/zipball/" ++ V.toString version ++ "/"
ifNotExists :: (MonadIO m, MonadError String m) => N.Name -> V.Version -> m () -> m ()
ifNotExists name version command =
do let directory = N.toFilePath name
exists <- liftIO $ doesDirectoryExist (directory </> V.toString version)
if exists
then return ()
else Cmd.inDir directory command
extract :: Client.Request -> Client.Manager -> IO ()
extract request manager =
do response <- Client.httpLbs request manager
let archive = Zip.toArchive (Client.responseBody response)
Zip.extractFilesFromArchive [] archive
| rtfeldman/elm-package | src/Install/Fetch.hs | bsd-3-clause | 1,665 | 0 | 15 | 335 | 503 | 266 | 237 | 36 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Docker.Redhat (
Redhat
, Redhat6
, Redhat7
, centos6
, centos7
, InotifyTools
, inotifyTools
, SHA256(..)
, installRpm
, installRpm'
) where
import qualified Data.Text as T
import Data.Monoid ((<>))
import Data.Dockerfile
------------------------------------------------------------------------
data Redhat
data Redhat6
data Redhat7
centos6 :: Dockerfile '[Redhat, Redhat6]
centos6 = base (RepoTag "centos" "6")
centos7 :: Dockerfile '[Redhat, Redhat7]
centos7 = base (RepoTag "centos" "7")
------------------------------------------------------------------------
data InotifyTools
inotifyTools :: Requires Redhat cs => Fragment cs (InotifyTools ': cs)
inotifyTools = installRpm url sha >>> addCapability
where
url = "http://dl.fedoraproject.org/pub/epel/6/x86_64/inotify-tools-3.14-1.el6.x86_64.rpm"
sha = SHA256 "dbbf546acb824bf972433eb55f5ef9b4f16ad74833a5161d0916aa8c543b5bc7"
------------------------------------------------------------------------
newtype SHA256 = SHA256 T.Text
installRpm :: Requires Redhat cs => T.Text -> SHA256 -> Fragment cs cs
installRpm = installRpm' []
installRpm' :: Requires Redhat cs => [(T.Text, T.Text)] -> T.Text -> SHA256 -> Fragment cs cs
installRpm' cookies url (SHA256 sha) = runMany [writeSHA, fetch, showSHA, checkSHA, install, rm]
where
fetch = [ "curl", "--progress-bar"
, "-L", url
, "-o", name ] ++ cookieArgs
cookieArgs | null cookies = []
| otherwise = [ "-b", T.intercalate ";"
. map (\(n,v) -> n <> "=" <> v)
$ cookies ]
shaFile = name <> ".sha256"
writeSHA = [ "echo", sha <> " " <> name, ">", shaFile ]
showSHA = [ "sha256sum", name ]
checkSHA = [ "sha256sum", "-c", shaFile ]
install = [ "yum", "install", "-y", name ]
rm = [ "rm", name ]
(_, name) = T.breakOnEnd "/" url
| jystic/sandwich-press | src/Docker/Redhat.hs | bsd-3-clause | 2,132 | 0 | 15 | 527 | 545 | 311 | 234 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module ProveEverywhere.Server where
import Prelude hiding (lookup)
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar
import Control.Exception
import Control.Monad (void)
import Data.Aeson
import Data.CaseInsensitive ()
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Handler.Warp (run)
import ProveEverywhere.Util
import ProveEverywhere.Types
import ProveEverywhere.Coqtop
type CoqtopMap = HashMap Int Coqtop
runServer :: Config -> IO ()
runServer config = do
coqtopMap <- newMVar HM.empty
seed <- newMVar 0
maybe (return ()) (void . forkIO . sweeper coqtopMap) $ configKillTime config
run (configPort config) (server config coqtopMap seed)
sweeper :: MVar CoqtopMap -> Int -> IO ()
sweeper coqtopMap minute = do
now <- getCurrentTime
pairs <- withMVar coqtopMap $ return . filter (isExpired now) . HM.toList
mapM_ kill pairs
threadDelay 60000000 -- 1 minute
sweeper coqtopMap minute
where
kill (i, c) = do
terminateCoqtop c
delete coqtopMap i
isExpired now (_, c) =
let diff = diffUTCTime now (coqtopLastModified c) in
diff > fromInteger (toInteger (minute * 60))
server :: Config -> MVar CoqtopMap -> MVar Int -> Application
server config coqtopMap seed req respond = handle unknownError $
case (pathInfo req, requestMethod req) of
(["list"], "GET") -> list
(["start"], "POST") -> start
(["command", n], "POST") | isNatural n -> command $ read $ T.unpack n
(["terminate", n], "DELETE") | isNatural n -> terminate $ read $ T.unpack n
(_, "OPTIONS") -> respond $ responseJSON status200 EmptyObject
(paths, _) -> do
let res = NoSuchApiError paths
respond $ errorResponse res
where
initialResponse (coqtop, o) = do
let n = coqtopId coqtop
insert coqtopMap n coqtop
return $ responseJSON status200 InitialInfo
{ initialInfoId = n
, initialInfoOutput = o
, initialInfoState = coqtopState coqtop
}
commandResponse (coqtop, output) = do
insert coqtopMap (coqtopId coqtop) coqtop
return $ responseJSON status200 output
unknownError :: SomeException -> IO ResponseReceived
unknownError = respond . errorResponse . UnknownError . T.pack . show
list = do
coqtops <- withMVar coqtopMap $ return . HM.elems
respond $ responseJSON status200 coqtops
start = case configMaxNumProcs config of
Nothing -> start'
Just limit -> do
n <- size coqtopMap
if n < limit then start' else
respond $ errorResponse $ ExceededMaxProcsError limit
where
start' = do
n <- fresh seed
res <- handleError (startCoqtop n) initialResponse
respond res
command n = do
res <- withCoqtop coqtopMap n $ \coqtop -> do
withDecodedBody req $ \cmd -> do
handleError (commandCoqtop coqtop cmd) commandResponse
respond res
terminate n = do
res <- withCoqtop coqtopMap n $ \coqtop -> do
terminateCoqtop coqtop
delete coqtopMap n
return $ responseJSON status200 EmptyObject
respond res
fresh :: MVar Int -> IO Int
fresh seed = modifyMVar seed (\n -> return (n + 1, n))
insert :: MVar CoqtopMap -> Int -> Coqtop -> IO ()
insert coqtopMap n coqtop = modifyMVar_ coqtopMap (return . HM.insert n coqtop)
lookup :: MVar CoqtopMap -> Int -> IO (Maybe Coqtop)
lookup coqtopMap n = withMVar coqtopMap $ return . HM.lookup n
delete :: MVar CoqtopMap -> Int -> IO ()
delete coqtopMap n = modifyMVar_ coqtopMap (return . HM.delete n)
size :: MVar CoqtopMap -> IO Int
size coqtopMap = withMVar coqtopMap $ return . HM.size
responseJSON :: ToJSON a => Status -> a -> Response
responseJSON status a =
responseLBS status [ (hContentType, "application/json")
, (hAccessControlAllowOrigin, "*")
, (hAccessControlAllowMethods, "GET, POST, PUT, DELETE, OPTIONS")
, (hAccessControlAllowHeaders, "Accept, Content-Type")
] (encode a)
where
hAccessControlAllowOrigin = "Access-Control-Allow-Origin"
hAccessControlAllowMethods = "Access-Control-Allow-Methods"
hAccessControlAllowHeaders = "Access-Control-Allow-Headers"
withCoqtop :: MVar CoqtopMap -> Int -> (Coqtop -> IO Response) -> IO Response
withCoqtop coqtopMap n cont = do
result <- lookup coqtopMap n
maybe
(return $ errorResponse $ NoSuchCoqtopError n)
cont
result
handleError :: IO (Either ServerError a) -> (a -> IO Response) -> IO Response
handleError io cont = io >>= either (return . errorResponse) cont
errorResponse :: ServerError -> Response
errorResponse e@(NoSuchCoqtopError _) = responseJSON status404 e
errorResponse e@(PromptParseError _) = responseJSON status500 e
errorResponse e@(RequestParseError _) = responseJSON status400 e
errorResponse e@(NoSuchApiError _) = responseJSON status404 e
errorResponse e@(UnknownError _) = responseJSON status500 e
errorResponse e@(ExceededMaxProcsError _) = responseJSON status400 e
withDecodedBody :: FromJSON a => Request -> (a -> IO Response) -> IO Response
withDecodedBody req cont = do
body <- requestBody req
maybe
(return $ errorResponse $ RequestParseError body)
cont
(decodeStrict body)
| prove-everywhere/server | src/ProveEverywhere/Server.hs | bsd-3-clause | 5,669 | 0 | 20 | 1,406 | 1,790 | 893 | 897 | 129 | 8 |
module HW5.StackVM (StackVal(..), StackExp(..), Stack, Program, stackVM) where
-- Values that may appear in the stack. Such a value will also be
-- returned by the stackVM program execution function.
data StackVal = IVal Integer | BVal Bool | Void deriving Show
-- The various expressions our VM understands.
data StackExp = PushI Integer
| PushB Bool
| Add
| Mul
| And
| Or
deriving (Show, Eq)
type Stack = [StackVal]
type Program = [StackExp]
-- Execute the given program. Returns either an error message or the
-- value on top of the stack after execution.
stackVM :: Program -> Either String StackVal
stackVM = execute []
errType :: String -> Either String a
errType op = Left $ "Encountered '" ++ op ++ "' opcode with ill-typed stack."
errUnderflow :: String -> Either String a
errUnderflow op = Left $ "Stack underflow with '" ++ op ++ "' opcode."
-- Execute a program against a given stack.
execute :: Stack -> Program -> Either String StackVal
execute [] [] = Right Void
execute (s:_) [] = Right s
execute s (PushI x : xs) = execute (IVal x : s) xs
execute s (PushB x : xs) = execute (BVal x : s) xs
execute (IVal s1 : IVal s2 : ss) (Add : xs) = execute (s':ss) xs
where s' = IVal (s1 + s2)
execute (_:_:_) (Add:_) = errType "Add"
execute _ (Add:_) = errUnderflow "Add"
execute (IVal s1:IVal s2:ss) (Mul : xs) = execute (s':ss) xs
where s' = IVal (s1 * s2)
execute (_:_:_) (Mul:_) = errType "Mul"
execute _ (Mul:_) = errUnderflow "Mul"
execute (BVal s1:BVal s2:ss) (And : xs) = execute (s':ss) xs
where s' = BVal (s1 && s2)
execute (_:_:_) (And:_) = errType "And"
execute _ (And:_) = errUnderflow "And"
execute (BVal s1 : BVal s2 : ss) (Or : xs) = execute (s':ss) xs
where s' = BVal (s1 || s2)
execute (_:_:_) (Or:_) = errType "Or"
execute _ (Or:_) = errUnderflow "Or"
test = stackVM [PushI 3, PushI 5, Add]
| cgag/cis-194-solutions | src/HW5/StackVM.hs | bsd-3-clause | 2,223 | 0 | 9 | 749 | 810 | 425 | 385 | 39 | 1 |
module Math.IRT.Model.Generic where
class GenericModel a where
fromRasch :: Double -> a
fromOnePLM :: Double -> a
fromTwoPLM :: Double -> Double -> a
fromThreePLM :: Double -> Double -> Double -> a
fromFourPLM :: Double -> Double -> Double -> Double -> a
| argiopetech/irt | Math/IRT/Model/Generic.hs | bsd-3-clause | 284 | 0 | 10 | 73 | 86 | 47 | 39 | 7 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Test.Framework
import Game
main = do
let g = read "{0|{0|*}}" :: Game
g' = read "{0|*}" :: Game
print g
print $ rawShow g
print $ isnumber g
print $ zero <* g'
defaultMain [
gameTests ]
| girving/games | Tests.hs | bsd-3-clause | 270 | 0 | 10 | 72 | 90 | 44 | 46 | 13 | 1 |
module CVTool.Writers (writePDF, writeLaTeX, writeHtml, writeJSON, writeMarkdown) where
import qualified Text.Pandoc as P (
writeJSON,
writeMarkdown,
writeLaTeX,
writeHtmlString,
WriterOptions(..),
def)
import Text.Pandoc.PDF
setOptions :: String -> P.WriterOptions
setOptions template = P.def { P.writerTemplate = Just template }
handleCitations pandocData = pandocData
writeText :: (P.WriterOptions -> a -> b) -> String -> a -> b
writeText writer template pandocData = writer (setOptions template) $ handleCitations pandocData
writeJSON = writeText P.writeJSON
writeMarkdown = writeText P.writeMarkdown
writeLaTeX = writeText P.writeLaTeX
writeHtml = writeText P.writeHtmlString
writePDF pdfCreator template = makePDF pdfCreator P.writeLaTeX (setOptions template)
| wbthomason/cv-tool | lib/CVTool/Writers.hs | bsd-3-clause | 783 | 0 | 8 | 107 | 226 | 124 | 102 | 19 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Language.Fixpoint.Smt.Bitvector
( -- * Constructor
Bv (..)
-- * Sizes
, BvSize (..)
-- * Operators
, BvOp (..)
-- * BitVector Sort Constructor
, mkSort
-- * BitVector Expression Constructor
, eOp
-- * BitVector Type Constructor
, bvTyCon
) where
import Data.Generics (Data)
import qualified Data.Text as T
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Language.Fixpoint.Types.Names
import Language.Fixpoint.Types
data Bv = Bv BvSize String
data BvSize = S32 | S64
deriving (Eq, Ord, Show, Data, Typeable, Generic)
data BvOp = BvAnd | BvOr
deriving (Eq, Ord, Show, Data, Typeable, Generic)
-- | Construct the bitvector `Sort` from its `BvSize`
mkSort :: BvSize -> Sort
mkSort s = fApp (fTyconSort bvTyCon) [ fTyconSort (sizeTyCon s) ]
bvTyCon :: FTycon
bvTyCon = symbolFTycon $ dummyLoc bitVecName
sizeTyCon :: BvSize -> FTycon
sizeTyCon = symbolFTycon . dummyLoc . sizeName
sizeName :: BvSize -> Symbol
sizeName S32 = size32Name
sizeName S64 = size64Name
-- | Construct an `Expr` using a raw string, e.g. (Bv S32 "#x02000000")
instance Expression Bv where
expr (Bv sz v) = ECon $ L (T.pack v) (mkSort sz)
-- | Apply some bitvector operator to a list of arguments
eOp :: BvOp -> [Expr] -> Expr
eOp = EApp . opName
opName :: BvOp -> LocSymbol
opName BvAnd = dummyLoc bvAndName
opName BvOr = dummyLoc bvOrName
-- sizeSort = (`FApp` [fObj $ dummyLoc $ symbol "obj"]) . sizeTC
-- s32TyCon = symbolFTycon $ dummyLoc size32Name
-- s64TyCon = symbolFTycon $ dummyLoc size64Name
| gridaphobe/liquid-fixpoint | src/Language/Fixpoint/Smt/Bitvector.hs | bsd-3-clause | 1,847 | 0 | 10 | 533 | 397 | 227 | 170 | 37 | 1 |
import Graphics.Gloss
import Data.Fixed
import Graphics.Gloss.Data.ViewPort
import Data.List
import Control.Monad.Random
import System.Random
bslash :: Float -- ^ Thickness
-> (Float, Float) -- ^ Width, height
-> Picture
bslash t (w,h) = Polygon [(0,0),(t,0),(w,h-t),(w,h),(w-t,h),(0,t)]
fslash :: Float -- ^ Thickness
-> (Float, Float) -- ^ Width, height
-> Picture
fslash t (w,h) = Polygon [(w,0),(w,t),(t,h),(0,h),(0,h-t),(w-t,0)]
render :: (Float,Float) -> Float -> [Picture] -> Picture
render (w,h) x ps =
let maxX = x*w - w
f (xs,(x,y)) p
| x < maxX = (translate (x+w) y p : xs, (x+w,y))
| otherwise = (translate 0 (y+h) p : xs, (0,y+h))
in pictures $ fst $ foldl' f ([],(-w,0)) ps
randList :: RandomGen g => Int -> [a] -> Rand g [a]
randList 0 _ = return []
randList n xs = do
i <- getRandomR (0,length xs - 1)
rest <- randList (n-1) xs
return ((xs!!i):rest)
renderMaze :: MazeState -> Picture
renderMaze ms =
let baseX = (-screenWidth ms / 2)
baseY = (-screenHeight ms / 2)
in translate (baseX - transX ms) (baseY - transY ms)
$ render (slashWidth ms, slashHeight ms)
(screenWidth ms / slashWidth ms) (slashes ms)
step :: ViewPort -> Float -> MazeState -> MazeState
step v t ms
| transY ms > slashHeight ms = step v t (addRows ms)
| otherwise = ms { transY = transY ms + 100 * t }
addRows :: MazeState -> MazeState
addRows ms =
let needed = floor (transY ms / slashHeight ms
* (screenWidth ms / slashWidth ms))
choices = map (\s -> color (slashColor ms)
$ s (slashThickness ms)
(slashWidth ms, slashHeight ms))
[fslash,bslash]
(new,g') = runRand (randList needed choices) (gen ms)
in ms { slashes = drop needed (slashes ms) ++ new
, transY = transY ms `mod'` slashHeight ms
, gen = g' }
data MazeState = MazeState
{ slashes :: [Picture]
, transX :: Float
, transY :: Float
, screenWidth :: Float
, screenHeight :: Float
, slashWidth :: Float
, slashHeight :: Float
, slashThickness :: Float
, slashColor :: Color
, gen :: StdGen
}
main :: IO ()
main = do
g <- getStdGen
let w = 1536; w' = fromIntegral w
h = 960; h' = fromIntegral h
lx = w `div` n'
ly = h `div` n'
t = 12
n = 48
n' = round n
bc = makeColor 0.15 0.4 1 1
fc = makeColor 1 1 1 0.9
sls = evalRand (randList (lx*ly*2)
(map (\s -> color fc $ s t (n,n)) [fslash,bslash])) g
simulate (InWindow "Float" (w,h) (0,0)) bc 60
(MazeState sls 5 0 w' h' n n t fc g)
renderMaze step
| jchmrt/tenprint | main.hs | mit | 2,696 | 0 | 19 | 795 | 1,295 | 703 | 592 | 78 | 1 |
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
-- | Test transforming floats in to doubles
module Norm.FloatToDoubleTest (
allTests
) where
import Norm.NormTestUtil
import Norm.FloatToDouble
normalizers :: NormalizerCU
normalizers = [ normFloatToDoubleVars, normFloatToDoubleRet ]
allTests :: TestTree
allTests = normTestsDir "Norm.FloatToDouble" "floattodouble" [normalizers] | DATX02-17-26/DATX02-17-26 | Test/Norm/FloatToDoubleTest.hs | gpl-2.0 | 1,163 | 0 | 6 | 203 | 59 | 36 | 23 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.InsertMap
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
module Yi.Keymap.Vim.InsertMap (defInsertMap) where
import Prelude hiding (head)
import Lens.Micro.Platform (use)
import Control.Monad (forM, liftM2, replicateM_, void, when)
import Data.Char (isDigit)
import Data.List.NonEmpty (NonEmpty (..), head, toList)
import Data.Monoid ((<>))
import qualified Data.Text as T (pack, unpack)
import qualified Yi.Buffer as B (bdeleteB, deleteB, deleteRegionB, insertB, insertN)
import Yi.Buffer as BA hiding (Insert)
import Yi.Editor (EditorM, getEditorDyn, withCurrentBuffer)
import Yi.Event (Event)
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.Digraph (charFromDigraph, DigraphTbl)
import Yi.Keymap.Vim.EventUtils (eventToEventString, parseEvents)
import Yi.Keymap.Vim.Motion (Move (Move), stringToMove)
import Yi.Keymap.Vim.StateUtils
import Yi.Keymap.Vim.Utils (selectBinding, selectPureBinding)
import Yi.Monad (whenM)
import qualified Yi.Rope as R (fromString, fromText)
import Yi.TextCompletion (CompletionScope (..), completeWordB)
defInsertMap :: DigraphTbl -> [VimBinding]
defInsertMap digraphs =
[rawPrintable] <> specials digraphs <> [printable]
specials :: DigraphTbl -> [VimBinding]
specials digraphs =
[exitBinding digraphs, pasteRegisterBinding, digraphBinding digraphs
, oneshotNormalBinding, completionBinding, cursorBinding]
exitBinding :: DigraphTbl -> VimBinding
exitBinding digraphs = VimBindingE f
where
f :: EventString -> VimState -> MatchResult (EditorM RepeatToken)
f evs (VimState { vsMode = (Insert _) })
| evs `elem` ["<Esc>", "<C-c>"]
= WholeMatch $ do
count <- getCountE
(Insert starter) <- fmap vsMode getEditorDyn
when (count > 1) $ do
inputEvents <- fmap (parseEvents . vsOngoingInsertEvents) getEditorDyn
replicateM_ (count - 1) $ do
when (starter `elem` ['O', 'o']) $ withCurrentBuffer $ insertB '\n'
replay digraphs inputEvents
modifyStateE $ \s -> s { vsOngoingInsertEvents = mempty }
withCurrentBuffer $ moveXorSol 1
modifyStateE $ \s -> s { vsSecondaryCursors = mempty }
resetCountE
switchModeE Normal
withCurrentBuffer $ whenM isCurrentLineAllWhiteSpaceB $ moveToSol >> deleteToEol
return Finish
f _ _ = NoMatch
rawPrintable :: VimBinding
rawPrintable = VimBindingE f
where
f :: EventString -> VimState -> MatchResult (EditorM RepeatToken)
f evs s@(VimState { vsMode = (Insert _)})
| vsPaste s && evs `notElem` ["<Esc>", "<C-c>"]
= WholeMatch . withCurrentBuffer $ do
case evs of
"<lt>" -> insertB '<'
"<CR>" -> newlineB
"<Tab>" -> insertB '\t'
"<BS>" -> bdeleteB
"<C-h>" -> bdeleteB
"<Del>" -> deleteB Character Forward
"<Home>" -> moveToSol
"<End>" -> moveToEol
"<PageUp>" -> scrollScreensB (-1)
"<PageDown>" -> scrollScreensB 1
c -> insertN (R.fromText $ _unEv c)
return Continue
f _ _ = NoMatch
replay :: DigraphTbl -> [Event] -> EditorM ()
replay _ [] = return ()
replay digraphs (e1:es1) = do
state <- getEditorDyn
let recurse = replay digraphs
evs1 = eventToEventString e1
bindingMatch1 = selectPureBinding evs1 state (defInsertMap digraphs)
case bindingMatch1 of
WholeMatch action -> void action >> recurse es1
PartialMatch -> case es1 of
[] -> return ()
(e2:es2) -> do
let evs2 = evs1 <> eventToEventString e2
bindingMatch2 = selectPureBinding evs2 state (defInsertMap digraphs)
case bindingMatch2 of
WholeMatch action -> void action >> recurse es2
_ -> recurse es2
_ -> recurse es1
oneshotNormalBinding :: VimBinding
oneshotNormalBinding = VimBindingE (f . T.unpack . _unEv)
where
f "<C-o>" (VimState { vsMode = Insert _ }) = PartialMatch
f ('<':'C':'-':'o':'>':evs) (VimState { vsMode = Insert _ }) =
action evs <$ stringToMove (Ev . T.pack $ dropWhile isDigit evs)
f _ _ = NoMatch
action evs = do
let (countString, motionCmd) = span isDigit evs
WholeMatch (Move _style _isJump move) = stringToMove . Ev . T.pack $ motionCmd
withCurrentBuffer $ move (if null countString then Nothing else Just (read countString))
return Continue
pasteRegisterBinding :: VimBinding
pasteRegisterBinding = VimBindingE (f . T.unpack . _unEv)
where f "<C-r>" (VimState { vsMode = Insert _ }) = PartialMatch
f ('<':'C':'-':'r':'>':regName:[]) (VimState { vsMode = Insert _ })
= WholeMatch $ do
mr <- getRegisterE regName
case mr of
Nothing -> return ()
Just (Register _style rope) -> withCurrentBuffer $ insertRopeWithStyleB rope Inclusive
return Continue
f _ _ = NoMatch
digraphBinding :: DigraphTbl -> VimBinding
digraphBinding digraphs = VimBindingE (f . T.unpack . _unEv)
where f ('<':'C':'-':'k':'>':c1:c2:[]) (VimState { vsMode = Insert _ })
= WholeMatch $ do
maybe (return ()) (withCurrentBuffer . insertB) $ charFromDigraph digraphs c1 c2
return Continue
f ('<':'C':'-':'k':'>':_c1:[]) (VimState { vsMode = Insert _ }) = PartialMatch
f "<C-k>" (VimState { vsMode = Insert _ }) = PartialMatch
f _ _ = NoMatch
printable :: VimBinding
printable = VimBindingE f
where f evs state@(VimState { vsMode = Insert _ } ) =
case selectBinding evs state (specials undefined) of
NoMatch -> WholeMatch (printableAction evs)
_ -> NoMatch
f _ _ = NoMatch
printableAction :: EventString -> EditorM RepeatToken
printableAction evs = do
saveInsertEventStringE evs
currentCursor <- withCurrentBuffer pointB
IndentSettings et _ sw <- withCurrentBuffer indentSettingsB
secondaryCursors <- fmap vsSecondaryCursors getEditorDyn
let allCursors = currentCursor :| secondaryCursors
marks <- withCurrentBuffer $ forM' allCursors $ \cursor -> do
moveTo cursor
getMarkB Nothing
-- Using autoindenting with multiple cursors
-- is just too broken.
let (insertB', insertN', deleteB', bdeleteB', deleteRegionB') =
if null secondaryCursors
then (BA.insertB, BA.insertN, BA.deleteB,
BA.bdeleteB, BA.deleteRegionB)
else (B.insertB, B.insertN, B.deleteB,
B.bdeleteB, B.deleteRegionB)
let bufAction = case T.unpack . _unEv $ evs of
(c:[]) -> insertB' c
"<CR>" -> do
isOldLineEmpty <- isCurrentLineEmptyB
shouldTrimOldLine <- isCurrentLineAllWhiteSpaceB
if isOldLineEmpty
then newlineB
else if shouldTrimOldLine
then savingPointB $ do
moveToSol
newlineB
else do
newlineB
indentAsTheMostIndentedNeighborLineB
firstNonSpaceB
"<Tab>" -> do
if et
then insertN' . R.fromString $ replicate sw ' '
else insertB' '\t'
"<C-t>" -> modifyIndentB (+ sw)
"<C-d>" -> modifyIndentB (max 0 . subtract sw)
"<C-e>" -> insertCharWithBelowB
"<C-y>" -> insertCharWithAboveB
"<BS>" -> bdeleteB'
"<C-h>" -> bdeleteB'
"<Home>" -> moveToSol
"<End>" -> moveToEol >> leftOnEol
"<PageUp>" -> scrollScreensB (-1)
"<PageDown>" -> scrollScreensB 1
"<Del>" -> deleteB' Character Forward
"<C-w>" -> deleteRegionB' =<< regionOfPartNonEmptyB unitViWordOnLine Backward
"<C-u>" -> bdeleteLineB
"<lt>" -> insertB' '<'
evs' -> error $ "Unhandled event " <> show evs' <> " in insert mode"
updatedCursors <- withCurrentBuffer $ do
updatedCursors <- forM' marks $ \mark -> do
moveTo =<< use (markPointA mark)
bufAction
pointB
mapM_ deleteMarkB $ toList marks
moveTo $ head updatedCursors
return $ toList updatedCursors
modifyStateE $ \s -> s { vsSecondaryCursors = drop 1 updatedCursors }
return Continue
where
forM' :: Monad m => NonEmpty a -> (a -> m b) -> m (NonEmpty b)
forM' (x :| xs) f = liftM2 (:|) (f x) (forM xs f)
completionBinding :: VimBinding
completionBinding = VimBindingE (f . T.unpack . _unEv)
where f evs (VimState { vsMode = (Insert _) })
| evs `elem` ["<C-n>", "<C-p>"]
= WholeMatch $ do
let _direction = if evs == "<C-n>" then Forward else Backward
completeWordB FromAllBuffers
return Continue
f _ _ = NoMatch
cursorBinding :: VimBinding
cursorBinding = VimBindingE f
where
f "<C-b>" (VimState { vsMode = (Insert _) })
= WholeMatch $ do
withCurrentBuffer $ moveXorSol 1
return Continue
f "<C-f>" (VimState { vsMode = (Insert _) })
= WholeMatch $ do
withCurrentBuffer $ moveXorEol 1
return Continue
f evs (VimState { vsMode = (Insert _) })
| evs `elem` ["<Up>", "<Left>", "<Down>", "<Right>"]
= WholeMatch $ do
let WholeMatch (Move _style _isJump move) = stringToMove evs
withCurrentBuffer $ move Nothing
return Continue
f _ _ = NoMatch
| noughtmare/yi | yi-keymap-vim/src/Yi/Keymap/Vim/InsertMap.hs | gpl-2.0 | 10,368 | 0 | 22 | 3,431 | 2,933 | 1,497 | 1,436 | 215 | 22 |
-- $Id$
module NPDA.Dot
( module Autolib.Dot.Dot
)
where
import NPDA.Type
import Autolib.Dot.Dot
import qualified Autolib.Dot.Graph as G
import qualified Autolib.Dot.Node as N
import qualified Autolib.Dot.Edge as E
import Autolib.ToDoc
import Autolib.Set
import Autolib.FiniteMap
import Data.Maybe
-- | zustände werden mit [0 .. ] durchnumeriert
-- akzeptierende zustände bekommen doppelkreis drumrum
-- startzustände bekommen pfeil dran,
-- dieser kommt aus unsichtbarem zustand mit idents U0, U1, ..
instance NPDAC Char Char z
=> ToDot ( NPDA Char Char z ) where
toDot a =
let fm = listToFM $ zip (setToList $ zustandsmenge a) $ [ 0.. ]
num = fromMaybe (error "NPDA.Dot.num") . lookupFM fm
-- tatsächliche knoten (zustände)
ns = do let finals = case akzeptiert a of
Leerer_Keller -> emptySet
Zustand xs -> xs
p <- setToList $ zustandsmenge a
let sh = case p `elementOf` finals of
True -> "doublecircle"
False -> "circle"
return $ N.blank
{ N.ident = show $ num p
, N.label = Just $ render $ toDoc p
, N.shape = Just sh
}
-- unsichtbare knoten (für start-pfeile)
uns = do let p = startzustand a
return $ N.blank
{ N.ident = "U" ++ show ( num p )
, N.node_style = Just "invis"
}
-- tatsächliche zustandsübergänge
es = do ( mx, z, y, z', ys' ) <- unCollect' $ transitionen a
let form "" = "Eps" ; form cs = cs
lab = "(" ++ form ( maybeToList mx )
++ "," ++ [ y ]
++ "," ++ form ys'
++ ")"
return $ E.blank
{ E.from = show $ num z
, E.to = show $ num z'
, E.taillabel = Just $ show lab
}
-- start-pfeile
ss = do p <- [ startzustand a ]
return $ E.blank
{ E.from = "U" ++ show ( num p )
, E.to = show $ num p
}
in G.Type
{ G.directed = True
, G.name = "NPDA"
, G.nodes = ns ++ uns
, G.edges = es ++ ss
, G.attributes = []
}
| florianpilz/autotool | src/NPDA/Dot.hs | gpl-2.0 | 2,053 | 58 | 18 | 661 | 658 | 361 | 297 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.DataPipeline.DeletePipeline
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes a pipeline, its pipeline definition, and its run history. AWS Data
-- Pipeline attempts to cancel instances associated with the pipeline that are
-- currently being processed by task runners.
--
-- Deleting a pipeline cannot be undone. You cannot query or restore a deleted
-- pipeline. To temporarily pause a pipeline instead of deleting it, call 'SetStatus' with the status set to 'PAUSE' on individual components. Components that are
-- paused by 'SetStatus' can be resumed.
--
-- <http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DeletePipeline.html>
module Network.AWS.DataPipeline.DeletePipeline
(
-- * Request
DeletePipeline
-- ** Request constructor
, deletePipeline
-- ** Request lenses
, dpPipelineId
-- * Response
, DeletePipelineResponse
-- ** Response constructor
, deletePipelineResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.DataPipeline.Types
import qualified GHC.Exts
newtype DeletePipeline = DeletePipeline
{ _dpPipelineId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeletePipeline' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dpPipelineId' @::@ 'Text'
--
deletePipeline :: Text -- ^ 'dpPipelineId'
-> DeletePipeline
deletePipeline p1 = DeletePipeline
{ _dpPipelineId = p1
}
-- | The ID of the pipeline.
dpPipelineId :: Lens' DeletePipeline Text
dpPipelineId = lens _dpPipelineId (\s a -> s { _dpPipelineId = a })
data DeletePipelineResponse = DeletePipelineResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeletePipelineResponse' constructor.
deletePipelineResponse :: DeletePipelineResponse
deletePipelineResponse = DeletePipelineResponse
instance ToPath DeletePipeline where
toPath = const "/"
instance ToQuery DeletePipeline where
toQuery = const mempty
instance ToHeaders DeletePipeline
instance ToJSON DeletePipeline where
toJSON DeletePipeline{..} = object
[ "pipelineId" .= _dpPipelineId
]
instance AWSRequest DeletePipeline where
type Sv DeletePipeline = DataPipeline
type Rs DeletePipeline = DeletePipelineResponse
request = post "DeletePipeline"
response = nullResponse DeletePipelineResponse
| romanb/amazonka | amazonka-datapipeline/gen/Network/AWS/DataPipeline/DeletePipeline.hs | mpl-2.0 | 3,381 | 0 | 9 | 708 | 362 | 223 | 139 | 48 | 1 |
{-# OPTIONS_GHC -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Comonad.Context.Class
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
----------------------------------------------------------------------------
module Control.Comonad.Context.Class
( module Control.Comonad
, ComonadContext(..)
, putC
, experiment
) where
import Control.Comonad
class Comonad w => ComonadContext s w | w -> s where
getC :: w a -> s
modifyC :: (s -> s) -> w a -> a
putC :: ComonadContext s w => s -> w a -> a
putC = modifyC . const
experiment :: (ComonadContext s w, Functor f) => f (s -> s) -> w a -> f a
experiment ms a = fmap (flip modifyC a) ms
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Comonad/Context/Class.hs | apache-2.0 | 882 | 4 | 9 | 164 | 212 | 118 | 94 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
module API where
data Null = Null { a, b :: Int }
null :: Null
null = Null { a = 42 , b = 1 }
| abuiles/turbinado-blog | tmp/dependencies/hs-plugins-1.3.1/testsuite/unload/sjwtrap/api/API.hs | bsd-3-clause | 129 | 0 | 8 | 36 | 46 | 30 | 16 | 5 | 1 |
-- | A renderer that produces a native Haskell 'String', mostly meant for
-- debugging purposes.
--
{-# LANGUAGE OverloadedStrings #-}
module Text.Blaze.Renderer.String
( fromChoiceString
, renderMarkup
, renderHtml
) where
import Data.List (isInfixOf)
import qualified Data.ByteString.Char8 as SBC
import qualified Data.Text as T
import qualified Data.ByteString as S
import Text.Blaze.Internal
-- | Escape predefined XML entities in a string
--
escapeMarkupEntities :: String -- ^ String to escape
-> String -- ^ String to append
-> String -- ^ Resulting string
escapeMarkupEntities [] k = k
escapeMarkupEntities (c:cs) k = case c of
'<' -> '&' : 'l' : 't' : ';' : escapeMarkupEntities cs k
'>' -> '&' : 'g' : 't' : ';' : escapeMarkupEntities cs k
'&' -> '&' : 'a' : 'm' : 'p' : ';' : escapeMarkupEntities cs k
'"' -> '&' : 'q' : 'u' : 'o' : 't' : ';' : escapeMarkupEntities cs k
'\'' -> '&' : '#' : '3' : '9' : ';' : escapeMarkupEntities cs k
x -> x : escapeMarkupEntities cs k
-- | Render a 'ChoiceString'.
--
fromChoiceString :: ChoiceString -- ^ String to render
-> String -- ^ String to append
-> String -- ^ Resulting string
fromChoiceString (Static s) = getString s
fromChoiceString (String s) = escapeMarkupEntities s
fromChoiceString (Text s) = escapeMarkupEntities $ T.unpack s
fromChoiceString (ByteString s) = (SBC.unpack s ++)
fromChoiceString (PreEscaped x) = case x of
String s -> (s ++)
Text s -> (\k -> T.foldr (:) k s)
s -> fromChoiceString s
fromChoiceString (External x) = case x of
-- Check that the sequence "</" is *not* in the external data.
String s -> if "</" `isInfixOf` s then id else (s ++)
Text s -> if "</" `T.isInfixOf` s then id else (\k -> T.foldr (:) k s)
ByteString s -> if "</" `S.isInfixOf` s then id else (SBC.unpack s ++)
s -> fromChoiceString s
fromChoiceString (AppendChoiceString x y) =
fromChoiceString x . fromChoiceString y
fromChoiceString EmptyChoiceString = id
{-# INLINE fromChoiceString #-}
-- | Render some 'Markup' to an appending 'String'.
--
renderString :: Markup -- ^ Markup to render
-> String -- ^ String to append
-> String -- ^ Resulting String
renderString = go id
where
go :: (String -> String) -> MarkupM b -> String -> String
go attrs (Parent _ open close content) =
getString open . attrs . ('>' :) . go id content . getString close
go attrs (CustomParent tag content) =
('<' :) . fromChoiceString tag . attrs . ('>' :) . go id content .
("</" ++) . fromChoiceString tag . ('>' :)
go attrs (Leaf _ begin end) = getString begin . attrs . getString end
go attrs (CustomLeaf tag close) =
('<' :) . fromChoiceString tag . attrs .
(if close then (" />" ++) else ('>' :))
go attrs (AddAttribute _ key value h) = flip go h $
getString key . fromChoiceString value . ('"' :) . attrs
go attrs (AddCustomAttribute key value h) = flip go h $
(' ' :) . fromChoiceString key . ("=\"" ++) . fromChoiceString value .
('"' :) . attrs
go _ (Content content) = fromChoiceString content
go _ (Comment comment) =
("<!-- " ++) . fromChoiceString comment . (" -->" ++)
go attrs (Append h1 h2) = go attrs h1 . go attrs h2
go _ Empty = id
{-# NOINLINE go #-}
{-# INLINE renderString #-}
-- | Render markup to a lazy 'String'.
--
renderMarkup :: Markup -> String
renderMarkup html = renderString html ""
{-# INLINE renderMarkup #-}
renderHtml :: Markup -> String
renderHtml = renderMarkup
{-# INLINE renderHtml #-}
{-# DEPRECATED renderHtml
"Use renderHtml from Text.Blaze.Html.Renderer.String instead" #-}
| FranklinChen/blaze-markup | src/Text/Blaze/Renderer/String.hs | bsd-3-clause | 3,906 | 0 | 14 | 1,070 | 1,145 | 611 | 534 | 74 | 11 |
module CodeGen.Shared(generateShared) where
import Types
import CCode.Main
import CodeGen.CCodeNames
import CodeGen.Typeclasses
import CodeGen.Function
import CodeGen.ClassTable
import qualified AST.AST as A
import Data.Maybe
import Data.List
-- | Generates a file containing the shared (but not included) C
-- code of the translated program
generateShared :: A.Program -> ProgramTable -> CCode FIN
generateShared prog@(A.Program{A.source, A.classes, A.functions, A.imports}) table =
Program $
Concat $
(LocalInclude "header.h") :
embeddedCode ++
-- [commentSection "Shared messages"] ++
-- sharedMessages ++
[commentSection "Global functions"] ++
globalFunctions ++
[mainFunction]
where
globalFunctions =
[translate f table globalFunction | f <- functions] ++
[globalFunctionWrapper f | f <- functions] ++
[initFunctionClosure f | f <- functions]
embeddedCode = embedded prog
where
embedded A.Program{A.source, A.etl} =
[commentSection $ "Embedded Code from " ++ show source] ++
map (Embed . A.etlbody) etl
sharedMessages = [msgAllocDecl, msgFutResumeDecl, msgFutSuspendDecl, msgFutAwaitDecl, msgFutRunClosureDecl]
where
msgAllocDecl =
AssignTL (Decl (ponyMsgT, Var "m_MSG_alloc"))
(Record [Int 0, Record ([] :: [CCode Expr])])
msgFutResumeDecl =
AssignTL (Decl (ponyMsgT, Var "m_resume_get"))
(Record [Int 1, Record [encorePrimitive]])
msgFutSuspendDecl =
AssignTL (Decl (ponyMsgT, Var "m_resume_suspend"))
(Record [Int 1, Record [encorePrimitive]])
msgFutAwaitDecl =
AssignTL (Decl (ponyMsgT, Var "m_resume_await"))
(Record [Int 2, Record [encorePrimitive, encorePrimitive]])
msgFutRunClosureDecl =
AssignTL (Decl (ponyMsgT, Var "m_run_closure"))
(Record [Int 3, Record [encorePrimitive, encorePrimitive, encorePrimitive]])
mainFunction =
Function (Typ "int") (Nam "main")
[(Typ "int", Var "argc"), (Ptr . Ptr $ char, Var "argv")]
$ Return encoreStart
where
encoreStart =
case find isLocalMain classes of
Just mainClass ->
Call (Nam "encore_start")
[AsExpr $ Var "argc"
,AsExpr $ Var "argv"
,Amp (AsLval $ runtimeTypeName (A.cname mainClass))
]
Nothing ->
let msg =
"This program has no Main class and will now exit"
in Call (Nam "puts") [String msg]
isLocalMain c@A.Class{A.cname} = A.isMainClass c &&
getRefSourceFile cname == source
commentSection :: String -> CCode Toplevel
commentSection s = Embed $ (take (5 + length s) $ repeat '/') ++ "\n// " ++ s
| Paow/encore | src/back/CodeGen/Shared.hs | bsd-3-clause | 3,165 | 0 | 20 | 1,114 | 829 | 436 | 393 | -1 | -1 |
-- | Exposes things that are considered to be too unstable for inclusion in the exports of "Data.Graph.Wrapper".
--
-- Use of this module should be avoided as it will change frequently and changes to this module alone will not necessarily
-- follow the Package Versioning Policy.
{-# OPTIONS_HADDOCK not-home #-}
module Data.Graph.Wrapper.Internal where
import Control.Applicative (Applicative)
import Data.Array
import Data.Maybe (fromMaybe)
import qualified Data.Graph as G
import qualified Data.Foldable as Foldable
import qualified Data.Traversable as Traversable
-- This module currently contains just enough definitions that lets us put the definition of Graph
-- here and not have any orphan instances
-- | An edge from the first vertex to the second
type Edge i = (i, i)
-- | A directed graph
data Graph i v = G {
graph :: G.Graph,
indexGVertexArray :: Array G.Vertex i,
gVertexVertexArray :: Array G.Vertex v
}
instance (Ord i, Show i, Show v) => Show (Graph i v) where
show g = "fromVerticesEdges " ++ show ([(i, vertex g i) | i <- vertices g]) ++ " " ++ show (edges g)
instance Functor (Graph i) where
fmap f g = g { gVertexVertexArray = fmap f (gVertexVertexArray g) }
instance Foldable.Foldable (Graph i) where
foldMap f g = Foldable.foldMap f (gVertexVertexArray g)
instance Traversable.Traversable (Graph i) where
traverse f g = fmap (\gvva -> g { gVertexVertexArray = gvva }) (Traversable.traverse f (gVertexVertexArray g))
traverseWithKey :: Applicative t => (i -> a -> t b) -> Graph i a -> t (Graph i b)
traverseWithKey f g = fmap (\gvva -> g { gVertexVertexArray = gvva }) (traverseWithIndex (\gv -> f (gVertexIndex g gv)) (gVertexVertexArray g))
where
traverseWithIndex :: Applicative t => (G.Vertex -> a -> t b) -> Array G.Vertex a -> t (Array G.Vertex b)
traverseWithIndex f a = fmap (array (bounds a)) $ flip Traversable.traverse (assocs a) $ \(k, v) -> fmap ((,) k) $ f k v
{-# RULES "indexGVertex/gVertexIndex" forall g i. gVertexIndex g (indexGVertex g i) = i #-}
{-# RULES "gVertexIndex/indexGVertex" forall g v. indexGVertex g (gVertexIndex g v) = v #-}
{-# NOINLINE [0] indexGVertex #-}
indexGVertex :: Ord i => Graph i v -> i -> G.Vertex
indexGVertex g i = indexGVertex' (indexGVertexArray g) i
{-# NOINLINE [0] gVertexIndex #-}
gVertexIndex :: Graph i v -> G.Vertex -> i
gVertexIndex g gv = indexGVertexArray g ! gv
gVertexVertex :: Graph i v -> G.Vertex -> v
gVertexVertex g gv = gVertexVertexArray g ! gv
-- | Retrieve data associated with the vertex
vertex :: Ord i => Graph i v -> i -> v
vertex g = gVertexVertex g . indexGVertex g
indexGVertex' :: Ord i => Array G.Vertex i -> i -> G.Vertex
indexGVertex' key_map k = fromMaybe (error "Data.Graph.Wrapper.fromList: one of the edges of a vertex pointed to a vertex that was not supplied in the input") (indexGVertex'_maybe key_map k)
indexGVertex'_maybe :: Ord i => Array G.Vertex i -> i -> Maybe G.Vertex
indexGVertex'_maybe key_map k = go 0 (snd (bounds key_map))
where
go a b | a > b = Nothing
| otherwise = case compare k (key_map ! mid) of
LT -> go a (mid - 1)
EQ -> Just mid
GT -> go (mid + 1) b
where mid = (a + b) `div` 2
-- | Exhaustive list of vertices in the graph
vertices :: Graph i v -> [i]
vertices g = map (gVertexIndex g) $ G.vertices (graph g)
-- | Exhaustive list of edges in the graph
edges :: Graph i v -> [Edge i]
edges g = map (\(x, y) -> (gVertexIndex g x, gVertexIndex g y)) $ G.edges (graph g)
| batterseapower/graph-wrapper | Data/Graph/Wrapper/Internal.hs | bsd-3-clause | 3,574 | 0 | 14 | 778 | 1,142 | 592 | 550 | 51 | 3 |
{- |
Module : $Header$
Description : A process interface for communication with other programs
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Ewaryst.Schulz@dfki.de
Stability : provisional
Portability : non-portable (various -fglasgow-exts extensions)
Interface for communication with other processes
-}
module Interfaces.Process where
import Control.Monad (liftM, when)
import Control.Monad.Trans (MonadIO (..))
import Control.Monad.State (MonadState (..))
import Common.IO (catchIOException)
import Data.Time
import Data.Maybe
import qualified System.Process as SP
import System.Exit
import System.IO
import Common.IOS
{- ----------------------------------------------------------------------
ReadState, controlled reading from a handle
---------------------------------------------------------------------- -}
type DTime = NominalDiffTime
type Time = UTCTime
data IntelligentReadState = IRS { timeout :: DTime -- ^ total timeout
, started :: Time -- ^ start timestamp
, updated :: Time -- ^ last update stamp
, readtime :: Time -- ^ stamp of last read
, hasread :: Bool -- ^ got data
, waitForRead :: Bool -- ^
, waittimeInp :: Int -- ^ same as waitForInp
} deriving Show
data TimeConfig = TimeConfig { waitForInp :: Int
-- ^ How many milliseconds waiting for next data
, startTimeout :: DTime
-- ^ Give the application some time to come up
, cleanTimeout :: DTime
-- ^
} deriving Show
defaultConfig :: TimeConfig
defaultConfig = TimeConfig { waitForInp = 1
, startTimeout = 0.7
, cleanTimeout = 0.001 }
zeroTime :: Time
zeroTime = UTCTime { utctDay = ModifiedJulianDay { toModifiedJulianDay = 0 }
, utctDayTime = 0 } -- 17.11.1858 00:00:00
initIRS :: Int -> DTime -> Bool -> IO IntelligentReadState
initIRS w t b = do
ts <- getCurrentTime
return $ IRS t ts ts zeroTime False b w
{- |
This class provides an interface to control the output retrieval from an
output handler (in the code of getOutput' you can see this control in action).
-}
class ReadState a where
-- | For updating the ReadState, you may want to set new timestamps, etc.
increment :: a -- ^ the ReadState
-> Bool -- ^ a flag for "got data"
-> IO a {- ^ the updated readstate
A predicate to tell when to abort a read-try, usally when some
timeout has passed -}
abort :: a -> Bool
-- | Wait-time for new input
waitInp :: a -- ^ the ReadState
-> Int -- ^ The milliseconds to wait for new input on the handle
{- | Aborts the read attempt if one of the following holds:
1. the timeout is up
(= last update timestamp - start timestamp >= timeout)
2. between last RS-update and last read with data more than 10% of
timeout passed, AND
some data was already read OR the waitForRead flag is not set
This decision-tree is the reason why we call this ReadState 'Intelligent'
-}
instance ReadState IntelligentReadState where
increment irs ngd =
do
ts <- getCurrentTime
return $ if ngd then irs { updated = ts, readtime = ts, hasread = ngd}
else irs { updated = ts }
abort (IRS to st lus slr gd b _) =
to <= diffUTCTime lus st
|| ((not b || gd)
-- TODO: experiment with the 10 percent!
&& let tr = diffUTCTime lus slr in tr > 0 && to / tr < 10)
waitInp = waittimeInp
getOutput :: (ReadState a) => Handle -> a -> IO String
getOutput hdl rs = do
s <- getOutput' rs hdl ""
return $ reverse s
{- builds the string in the wrong order
tail-recursive function shouldn't make stack problems -}
getOutput' :: (ReadState a) => a -> Handle -> String -> IO String
getOutput' rs hdl s = do
b <- if abort rs then return Nothing {- timeout gone
eventually error on eof so abort -}
else catchIOException Nothing
$ liftM Just $ hWaitForInput hdl $ waitInp rs
case b of Nothing -> return s
Just b' ->
do
ns <- if b' then liftM (: s) $ hGetChar hdl else return s
nrs <- increment rs b'
getOutput' nrs hdl ns
{- | From given Time a ReadState is created and the output is fetched using
getOutput -}
getOutp :: Handle -> Int -> DTime -> IO String
getOutp hdl w t = initIRS w t True >>= getOutput hdl
{- ----------------------------------------------------------------------
A Command Interface using the read state
---------------------------------------------------------------------- -}
{- | This is just a type to hold the information returned by
System.Process.runInteractiveCommand -}
data CommandState = CS { inp :: Handle, outp :: Handle, err :: Handle
, pid :: SP.ProcessHandle, verbosity :: Int
, tc :: TimeConfig }
-- | The IO State-Monad with state CommandState
type Command = IOS CommandState
-- | initialize the connection by running the given command string
start :: String -- ^ shell string to run the program
-> Int -- ^ Verbosity level
-> Maybe TimeConfig
-> IO CommandState
start shcmd v mTc = do
when (v > 0) $ putStrLn $ "Running " ++ shcmd ++ " ..."
(i, o, e, p) <- SP.runInteractiveCommand shcmd
let cs = CS i o e p v $ fromMaybe defaultConfig mTc
verbMessageIO cs 3 "start: Setting buffer modes"
-- configure the handles
mapM_ (`hSetBinaryMode` False) [i, o, e]
mapM_ (`hSetBuffering` NoBuffering) [o, e]
hSetBuffering i LineBuffering
-- clear all output from the output pipe (TIME: wait 300 milliseconds)
verbMessageIO cs 3 "start: Clearing connection output."
x <- getOutp o (waitForInp $ tc cs) $ startTimeout $ tc cs
verbMessageIO cs 4 $ "start: Received\n--------------\n" ++ x
++ "\n--------------"
return cs
-- | Just read output from the connection waiting at most Time
readOutput :: DTime -> Command String
readOutput t = do
s <- get
liftIO $ getOutp (outp s) (waitForInp $ tc s) t
-- | Just read error output from the connection waiting at most Time
readErr :: DTime -> Command String
readErr t = do
s <- get
liftIO $ getOutp (err s) (waitForInp $ tc s) t
-- | Send some String and don't wait for response
send :: String -> Command ()
send str = do
s <- get
verbMessage s 2 $ "send: Sending " ++ str
liftIO $ hPutStrLn (inp s) str
-- | Send some String and wait Time for response
call :: DTime -- ^ Waits this time until abort call (Use float for seconds)
-> String -- ^ Send this string over the connection
-> Command String -- ^ Response
call t str = do
s <- get
-- first clear all output from the output pipe (wait 50 milliseconds)
verbMessage s 3 "call: Clearing connection output."
x <- liftIO $ getOutp (outp s) (waitForInp $ tc s) $ cleanTimeout $ tc s
verbMessage s 4 $ "\n--------------\n" ++ x ++ "\n--------------"
verbMessage s 2 $ "call: Sending " ++ str
liftIO $ hPutStrLn (inp s) str
res <- liftIO $ getOutp (outp s) (waitForInp $ tc s) t
verbMessage s 2 $ "call: Received " ++ res
return res
verbMessageIO :: CommandState -> Int -> String -> IO String
verbMessageIO cs v s =
if verbosity cs >= v then putStrLn s >> return s else return ""
verbMessage :: CommandState -> Int -> String -> Command String
verbMessage cs v s = liftIO $ verbMessageIO cs v s
{- | Send some exit command if there is one to close the connection.
This is the best one, but may be blocked by the application. -}
close :: Maybe String -> Command (Maybe ExitCode)
close str = do
s <- get
case str of Nothing -> do
verbMessage s 3 "close: No exit command"
return ()
Just excmd -> do
verbMessage s 2 $ "close: sending exit command: " ++ excmd
liftIO $ hPutStrLn (inp s) excmd
-- TODO: find out how to get the process id from the process handle
verbMessage s 3 "close: waiting for process to terminate"
e <- liftIO $ SP.waitForProcess $ pid s
verbMessage s 2 $ "close: process exited with code " ++ show e
return $ Just e
{-
-- Close variants:
-- | Send some exit command if there is one to close the connection
-- , and in addition terminate after wait
close2 :: Maybe String -> Command (Maybe ExitCode)
close2 str = do
s <- get
case str of Nothing -> do
verbMessage s 3 "close: No exit command"
return ()
Just excmd -> do
verbMessage s 2 $ "close: sending exit command: " ++ excmd
liftIO $ hPutStrLn (inp s) excmd
-- TODO: find out how to get the process id from the process handle
verbMessage s 3 $ "close: waiting for process to terminate"
e <- liftIO $ SP.waitForProcess $ pid s
verbMessage s 2 $ "close: process exited with code " ++ show e
verbMessage s 2 $ "close: forcing termination..."
liftIO $ SP.terminateProcess $ pid s
return $ Just e
-- | Send some exit command if there is one to close the connection
-- , but do not wait
close1 :: Maybe String -> Command (Maybe ExitCode)
close1 str = do
s <- get
case str of Nothing -> do
verbMessage s 3 "close: No exit command"
return ()
Just excmd -> do
verbMessage s 2 $ "close: sending exit command: " ++ excmd
liftIO $ hPutStrLn (inp s) excmd
-- TODO: find out how to get the process id from the process handle
verbMessage s 3 $ "close: waiting for process to terminate"
mE <- liftIO $ SP.getProcessExitCode $ pid s
case mE of
Just e -> do
verbMessage s 2 $ "close: process exited with code " ++ show e
return ()
Nothing -> do
verbMessage s 2 $ "close: process did not terminate in time, "
++ "forcing termination..."
liftIO $ SP.terminateProcess $ pid s
return mE
-}
| mariefarrell/Hets | Interfaces/Process.hs | gpl-2.0 | 10,397 | 0 | 16 | 3,081 | 1,778 | 918 | 860 | 136 | 4 |
-- |
-- Module : Data.UUID.Named
-- Copyright : (c) 2008 Antoine Latter
--
-- License : BSD-style
--
-- Maintainer : aslatter@gmail.com
-- Stability : experimental
-- Portability : portable
--
--
-- This module implements Version 3/5 UUIDs as specified
-- in RFC 4122.
--
-- These UUIDs identify an object within a namespace,
-- and are deterministic.
--
-- The namespace is identified by a UUID. Several sample
-- namespaces are enclosed.
module Data.UUID.Named
(generateNamed
,namespaceDNS
,namespaceURL
,namespaceOID
,namespaceX500
) where
import Data.UUID.Internal
import Control.Applicative ((<*>),(<$>))
import Data.Binary.Get (runGet, getWord32be)
import Data.Maybe
import Data.Word (Word8)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
-- |Generate a 'UUID' within the specified namespace out of the given
-- object.
generateNamed :: (B.ByteString -> B.ByteString) -- ^Hash
-> Word8 -- ^Version
-> UUID -- ^Namespace
-> [Word8] -- ^Object
-> UUID
generateNamed hash version namespace object =
let chunk = B.pack $ toList namespace ++ object
bytes = BL.fromChunks . (:[]) $ hash chunk
w = getWord32be
unpackBytes = runGet $
buildFromWords version <$> w <*> w <*> w <*> w
in unpackBytes bytes
unsafeFromString :: String -> UUID
unsafeFromString = fromJust . fromString
-- |The namespace for DNS addresses
namespaceDNS :: UUID
namespaceDNS = unsafeFromString "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
-- |The namespace for URLs
namespaceURL :: UUID
namespaceURL = unsafeFromString "6ba7b811-9dad-11d1-80b4-00c04fd430c8"
-- |The namespace for ISO OIDs
namespaceOID :: UUID
namespaceOID = unsafeFromString "6ba7b812-9dad-11d1-80b4-00c04fd430c8"
-- |The namespace for X.500 DNs
namespaceX500 :: UUID
namespaceX500 = unsafeFromString "6ba7b814-9dad-11d1-80b4-00c04fd430c8"
| alphaHeavy/uuid | Data/UUID/Named.hs | bsd-3-clause | 1,959 | 0 | 14 | 399 | 325 | 198 | 127 | 35 | 1 |
import FFI
import Prelude
main = do
let a1 = ("string",1) :: (String,Int)
putStrLn $ showPair a1
putStrLn $ showList [1..3]
putStrLn $ showString "Just a plain string"
l1 <- readList "[4,5,6]"
putStrLn . showList . map (1+) $ l1
(s,i) <- readPair "[\"first\",2]"
putStrLn $ s ++ " was first and " ++ showInt i ++ " was second"
showInt :: Int -> String
showInt = ffi "JSON.stringify(%1)"
showString :: String -> String
showString = ffi "JSON.stringify(%1)"
showPair :: (String,Int) -> String
showPair = ffi "JSON.stringify(%1)"
showList :: [Int] -> String
showList = ffi "JSON.stringify(%1)"
readList :: String -> Fay [Int]
readList = ffi "JSON.parse(%1)"
readPair :: String -> Fay (String,Int)
readPair = ffi "JSON.parse(%1)"
{-
compile with:
fay showExamples.hs
run with: (on Debian)
nodejs showExamples.hs
Produces:
["string",1]
[1,2,3]
"Just a plain string"
[5,6,7]
first was first and 2 was second
-}
| fpco/fay | examples/showExamples.hs | bsd-3-clause | 956 | 0 | 10 | 194 | 268 | 138 | 130 | 23 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Lazyfoo.Lesson19 (main) where
import Prelude hiding (any, mapM_)
import Control.Monad hiding (mapM_)
import Data.Int
import Data.Maybe
import Data.Monoid
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import qualified Data.Vector as V
import Paths_sdl2 (getDataFileName)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
import Data.Foldable
#endif
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
joystickDeadZone :: Int16
joystickDeadZone = 8000
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
let key = V4 0 maxBound maxBound maxBound
SDL.surfaceColorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> Maybe (SDL.Rectangle CInt) -> Maybe CDouble -> Maybe (Point V2 CInt) -> Maybe (V2 Bool) -> IO ()
renderTexture r (Texture t size) xy clip theta center flips =
let dstSize =
maybe size (\(SDL.Rectangle _ size') -> size') clip
in SDL.copyEx r
t
clip
(Just (SDL.Rectangle xy dstSize))
(fromMaybe 0 theta)
center
(fromMaybe (pure False) flips)
textureSize :: Texture -> V2 CInt
textureSize (Texture _ sz) = sz
getJoystick :: IO (SDL.Joystick)
getJoystick = do
joysticks <- SDL.availableJoysticks
joystick <- if V.length joysticks == 0
then error "No joysticks connected!"
else return (joysticks V.! 0)
SDL.openJoystick joystick
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo, SDL.InitJoystick]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererType = SDL.AcceleratedVSyncRenderer
, SDL.rendererTargetTexture = False
})
SDL.rendererDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
arrowTexture <- loadTexture renderer "examples/lazyfoo/arrow.bmp"
joystick <- getJoystick
joystickID <- SDL.getJoystickID joystick
let loop (xDir', yDir') = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
let (Any quit, Last newDir) =
foldMap (\case
SDL.QuitEvent -> (Any True, mempty)
SDL.KeyboardEvent e ->
if | SDL.keyboardEventKeyMotion e == SDL.Pressed ->
let scancode = SDL.keysymScancode (SDL.keyboardEventKeysym e)
in if | scancode == SDL.ScancodeEscape -> (Any True, mempty)
| otherwise -> mempty
| otherwise -> mempty
SDL.JoyAxisEvent e ->
if | SDL.joyAxisEventWhich e == joystickID ->
(\x -> (mempty, Last $ Just x)) $
case SDL.joyAxisEventAxis e of
0 -> if | SDL.joyAxisEventValue e < -joystickDeadZone -> (-1, yDir')
| SDL.joyAxisEventValue e > joystickDeadZone -> (1, yDir')
| otherwise -> (0, yDir')
1 -> if | SDL.joyAxisEventValue e < -joystickDeadZone -> (xDir', -1)
| SDL.joyAxisEventValue e > joystickDeadZone -> (xDir', 1)
| otherwise -> (xDir', 0)
_ -> (xDir', yDir')
| otherwise -> mempty
_ -> mempty) $
map SDL.eventPayload events
SDL.rendererDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.clear renderer
let dir@(xDir, yDir) = fromMaybe (xDir', yDir') newDir
phi = if xDir == 0 && yDir == 0
then 0
else (atan2 yDir xDir) * (180.0 / pi)
renderTexture renderer arrowTexture (P (fmap (`div` 2) (V2 screenWidth screenHeight) - fmap (`div` 2) (textureSize arrowTexture))) Nothing (Just phi) Nothing Nothing
SDL.present renderer
unless quit $ loop dir
loop (0, 0)
SDL.closeJoystick joystick
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
| seppeljordan/sdl2 | examples/lazyfoo/Lesson19.hs | bsd-3-clause | 5,244 | 0 | 33 | 1,732 | 1,516 | 756 | 760 | 121 | 15 |
import Graphics.UI.Gtk
main :: IO ()
main = do
initGUI
window <- windowNew
set window [windowTitle := "File Chooser Widget",
windowDefaultWidth := 500,
windowDefaultHeight := 400 ]
fch <- fileChooserWidgetNew FileChooserActionOpen
containerAdd window fch
selopt <- checkButtonNewWithLabel "Multiple File Selection"
fileChooserSetExtraWidget fch selopt
hsfilt <- fileFilterNew
fileFilterAddPattern hsfilt "*.hs"
fileFilterSetName hsfilt "Haskell Source"
fileChooserAddFilter fch hsfilt
nofilt <- fileFilterNew
fileFilterAddPattern nofilt "*.*"
fileFilterSetName nofilt "All Files"
fileChooserAddFilter fch nofilt
img <- imageNew
fileChooserSetPreviewWidget fch img
onUpdatePreview fch $
do file <- fileChooserGetPreviewFilename fch
case file of
Nothing -> putStrLn "No File Selected"
Just fpath -> imageSetFromFile img fpath
onFileActivated fch $
do dir <- fileChooserGetCurrentFolder fch
case dir of
Just dpath -> putStrLn
("The current directory is: " ++ dpath)
Nothing -> putStrLn "Nothing"
mul <- fileChooserGetSelectMultiple fch
if mul
then do
fls <- fileChooserGetFilenames fch
putStrLn
("You selected " ++ (show (length fls)) ++" files:")
sequence_ (map putStrLn fls)
else do
file <- fileChooserGetFilename fch
case file of
Just fpath -> putStrLn ("You selected: " ++ fpath)
Nothing -> putStrLn "Nothing"
onToggled selopt $ do state <- toggleButtonGetActive selopt
fileChooserSetSelectMultiple fch state
widgetShowAll window
onDestroy window mainQuit
mainGUI
| phischu/gtk2hs | docs/tutorial/Tutorial_Port/Example_Code/GtkChap5-2a.hs | lgpl-3.0 | 1,964 | 0 | 20 | 688 | 443 | 191 | 252 | 50 | 5 |
-- This triggers the same issue that prevents HashTable from building
data Foo a = Foo [a] deriving Show
data Bar a = Bar !(Foo a) deriving Show
main = print (Bar (Foo ["Hi!"]))
| hvr/jhc | regress/tests/6_fixed_bugs/UnpackedPoly.hs | mit | 181 | 0 | 10 | 37 | 61 | 34 | 27 | 5 | 1 |
module ScopeProgram(scopeProgram,scopeProgram',PNT(..)) where
import ScopeModule
import PNT(PNT(..))
import PrettyPrint
import OutputM
import HsModule(hsModName)
scopeProgram (mss0,wms) =
if null errors
then return (mss,wms)
else fail (pp $ vcat errors)
where
(mss,mrefs) = scopeProgram' (mss0,wms)
errors = [m<>": "<>msg | (m,refs)<-mrefs, (sp,i,os)<-refs, msg<-err i os]
err i [] = [not_in_scope i]
err i [o] = []
err i os = [ambiguous i os]
not_in_scope i = "Not in scope: "<>i
ambiguous i os = "Ambiguous: "<>i<>": "<>os
scopeProgram' (mss,wms) = listOutput $ mapM (mapM scopeMod) mss
where
-- Hmm. scopeModule outputs exactly one element
scopeMod mod = p (scopeModule wm mod)
where
Just wm = lookup m wms
m = hsModName mod
p (x,refs) = output (m,refs) >> return x
| forste/haReFork | tools/base/ScopeProgram.hs | bsd-3-clause | 851 | 1 | 11 | 200 | 369 | 199 | 170 | 22 | 4 |
{-# LANGUAGE EmptyDataDecls, TypeFamilies, TypeOperators, GADTs, KindSignatures #-}
module T3330c where
import Data.Kind
data (f :+: g) x = Inl (f x) | Inr (g x)
data R :: (Type -> Type) -> Type where
RSum :: R f -> R g -> R (f :+: g)
class Rep f where
rep :: R f
instance (Rep f, Rep g) => Rep (f :+: g) where
rep = RSum rep rep
type family Der (f :: Type -> Type) :: Type -> Type
type instance Der (f :+: g) = Der f :+: Der g
plug :: Rep f => Der f x -> x -> f x
plug = plug' rep where
plug' :: R f -> Der f x -> x -> f x
plug' (RSum rf rg) (Inl df) x = Inl (plug rf df x)
{-
rf :: R f1, rg :: R g1
Given by GADT match: f ~ f1 :+: g1
Second arg has type (Der f x)
= (Der (f1:+:g1) x)
= (:+:) (Der f1) (Der g1) x
Hence df :: Der f1 x
Inl {f3,g3,x} (plug {f2,x1} rf df x) gives rise to
result of Inl: ((:+:) f3 g3 x ~ f x)
first arg (rf): (R f1 ~ Der f2 x1)
second arg (df): (Der f1 x ~ x1)
result of plug: (f2 x1 ~ x -> f3 x)
result of Inl: ((:+:) f3 g3 x ~ f x)
by given ((:+:) f3 g3 x ~ (:+:) f1 g1 x)
hence need f3~f1, g3~g1
So we are left with
first arg: (R f1 ~ Der f2 x1)
second arg: (Der f1 x ~ x1)
result: (f2 x1 ~ (->) x (f3 x))
Decompose result:
f2 ~ (->) x
x1 ~ f1 x
Hence
first: R f1 ~ Der ((->) x) (f1 x)
decompose : R ~ Der ((->) x)
f1 ~ f1 x
-}
| sdiehl/ghc | testsuite/tests/indexed-types/should_fail/T3330c.hs | bsd-3-clause | 1,393 | 9 | 8 | 445 | 291 | 154 | 137 | -1 | -1 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds, PolyKinds #-}
module T13780a where
data family Sing (a :: k)
data Foo a = a ~ Bool => MkFoo
data instance Sing (z :: Foo a) = (z ~ MkFoo) => SMkFoo
| sdiehl/ghc | testsuite/tests/dependent/should_fail/T13780a.hs | bsd-3-clause | 247 | 0 | 8 | 46 | 67 | 40 | 27 | 7 | 0 |
{-# LANGUAGE PartialTypeSignatures, NamedWildCards #-}
module UncurryNamed where
unc :: (_a -> _b -> _c) -> (_a, _b) -> _c
unc = uncurry
| urbanslug/ghc | testsuite/tests/partial-sigs/should_compile/UncurryNamed.hs | bsd-3-clause | 138 | 0 | 8 | 24 | 40 | 24 | 16 | 4 | 1 |
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Foreign.Marshal.Utils.Compat"
-- from a globally unique namespace.
module Foreign.Marshal.Utils.Compat.Repl (
module Foreign.Marshal.Utils.Compat
) where
import "this" Foreign.Marshal.Utils.Compat
| haskell-compat/base-compat | base-compat/src/Foreign/Marshal/Utils/Compat/Repl.hs | mit | 316 | 0 | 5 | 31 | 31 | 24 | 7 | 5 | 0 |
import Control.Applicative
import Control.Monad
import Data.List
import Text.Printf
data Sign a = Pos a | Neg a
deriving Eq
main :: IO ()
main = do
tests <- readLn
forM_ [1..tests] $ \caseNum -> do
[l, x] <- map read <$> words <$> getLine
s <- concat . replicate x <$> getLine
let ans = solve "ijk" (Pos '1') $ map Pos s
where
solve [] _ [] = True
solve [] _ _ = False
solve _ _ [] = False
solve (c:cs) n xs = let next = reduce c n xs
done = solve cs (Pos '1') next
in if done
then True
else solve (c:cs) (Pos c) next
reduce _ _ [] = []
reduce c n (x:xs) = let val = n `quaternions` x in
if val == Pos c
then xs
else reduce c val xs
printf "Case #%d: %s\n" (caseNum::Int) (if ans then "YES" else "NO")
quaternions a b = case (a, b) of
(Pos x, Pos y) -> multiplicative x y
(Pos x, Neg y) -> inv $ multiplicative x y
(Neg x, Pos y) -> inv $ multiplicative x y
(Neg x, Neg y) -> multiplicative x y
where
inv (Pos x) = Neg x
inv (Neg x) = Pos x
multiplicative x y = case (x,y) of
('1', '1') -> Pos '1'
('1', 'i') -> Pos 'i'
('1', 'j') -> Pos 'j'
('1', 'k') -> Pos 'k'
('i', '1') -> Pos 'i'
('i', 'i') -> Neg '1'
('i', 'j') -> Neg 'k'
('i', 'k') -> Pos 'j'
('j', '1') -> Pos 'j'
('j', 'i') -> Pos 'k'
('j', 'j') -> Neg '1'
('j', 'k') -> Neg 'k'
('k', '1') -> Pos 'k'
('k', 'i') -> Neg 'j'
('k', 'j') -> Pos 'i'
('k', 'k') -> Neg '1'
| marknsikora/codejam | 6224486/C.hs | mit | 2,196 | 0 | 22 | 1,165 | 799 | 410 | 389 | 51 | 20 |
bar x b
where bar x = zap
foo a c d = quux
| chreekat/vim-haskell-syntax | test/golden/nested/where-decl.hs | mit | 55 | 1 | 5 | 24 | 30 | 14 | 16 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
module Parse
( LayerParseDefinition(..)
, NetworkParseDefinition(..)
, TrainingParseDefinition(..)
, InputParseDefinition(..)
, toMatrixFloat
, toNetwork
) where
import Network.Layer
import Network.Neuron
import Network.Network
import Data.Aeson
import GHC.Generics
import Linear
import System.Random
data LayerParseDefinition = LayerParseDefinition { ntype :: String
, ncount :: Int
, connectivity :: String
, id :: String
} deriving (Generic, Show)
instance FromJSON LayerParseDefinition
instance ToJSON LayerParseDefinition
-- to extend for other types of neurons, pattern match on neuron
-- TODO: change result of otherwise to something more error-like
toLayerDefinition :: (Floating a) => LayerParseDefinition -> LayerDefinition a
toLayerDefinition LayerParseDefinition {ntype=neuron, ncount=count, connectivity=conn}
| neuron == "sigmoidNeuron" = LayerDefinition {neuronDef=sigmoidNeuron, neuronCount=count, connect=connectFully}
| otherwise = LayerDefinition {neuronDef=sigmoidNeuron, neuronCount=count, connect=connectFully}
data NetworkParseDefinition = NetworkParseDefinition { layerDefs :: [LayerParseDefinition]
, initDist :: String
} deriving (Generic, Show)
instance FromJSON NetworkParseDefinition
instance ToJSON NetworkParseDefinition
toNetwork :: (Random a, Floating a) => NetworkParseDefinition -> Network a
toNetwork NetworkParseDefinition {layerDefs=layers, initDist=initDistribution}
| initDistribution == "normals" = createNetwork normals (mkStdGen 4) (map toLayerDefinition layers)
| initDistribution == "uniforms" = createNetwork uniforms (mkStdGen 4) (map toLayerDefinition layers)
| otherwise = createNetwork uniforms (mkStdGen 4) (map toLayerDefinition layers)
data TrainingParseDefinition = TrainingParseDefinition { trainingdata :: [(Matrix Float, Matrix Float)]
, nw :: [Matrix Float]
} deriving (Generic, Show)
instance FromJSON TrainingParseDefinition
instance ToJSON TrainingParseDefinition
--toTrainingDefinition :: TrainingParseDefinition -> TrainingData a
--toTrainingDefinition TrainingParseDefinition {trainingdata=data,nw=network} =
data InputParseDefinition = InputParseDefinition { inputs :: [Float]
, network :: [Matrix Float]
} deriving (Generic, Show)
instance FromJSON InputParseDefinition
instance ToJSON InputParseDefinition
toMatrixFloat :: (Floating a) => Network a -> [Matrix a]
toMatrixFloat n = zipWith combine (map weightMatrix (layers n)) (map biasMatrix (layers n))
| jbarrow/LambdaNet-browser | Parse.hs | mit | 2,956 | 0 | 11 | 772 | 631 | 347 | 284 | 48 | 1 |
{-# LANGUAGE DeriveFunctor #-}
module Vimus.Command.Parser where
import Prelude hiding (takeWhile)
import Data.List (intercalate)
import Control.Monad
import Control.Applicative
type Name = String
type Value = String
-- | Errors are ordered from less specific to more specific. More specific
-- errors take precedence over less specific ones.
data ParseError =
Empty
| ParseError String
| SuperfluousInput Value
| MissingArgument Name
| InvalidArgument Name Value
| SpecificArgumentError String
deriving (Eq, Ord)
instance Show ParseError where
show e = case e of
Empty -> "Control.Applicative.Alternative.empty"
ParseError err -> "parse error: " ++ err
SuperfluousInput input -> case words input of
[] -> "superfluous input: " ++ show input
[x] -> "unexpected argument: " ++ show x
xs -> "unexpected arguments: " ++ intercalate ", " (map show xs)
MissingArgument name -> "missing required argument: " ++ name
InvalidArgument name value -> "argument " ++ show value ++ " is not a valid " ++ name
SpecificArgumentError err -> err
newtype Parser a = Parser {runParser :: String -> Either ParseError (a, String)}
deriving Functor
instance Applicative Parser where
pure = return
(<*>) = ap
instance Monad Parser where
return a = Parser $ \input -> Right (a, input)
p1 >>= p2 = Parser $ \input -> runParser p1 input >>= uncurry (runParser . p2)
instance MonadFail Parser where
fail = parserFail . ParseError
instance Alternative Parser where
empty = parserFail Empty
p1 <|> p2 = Parser $ \input -> case runParser p1 input of
Left err -> either (Left . max err) (Right) (runParser p2 input)
x -> x
-- | Recognize a character that satisfies a given predicate.
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser go
where
go (x:xs)
| p x = Right (x, xs)
| otherwise = (Left . ParseError) ("satisfy: unexpected " ++ show x)
go "" = (Left . ParseError) "satisfy: unexpected end of input"
-- | Recognize a given character.
char :: Char -> Parser Char
char c = satisfy (== c)
-- | Recognize a given string.
string :: String -> Parser String
string = mapM char
parserFail :: ParseError -> Parser a
parserFail = Parser . const . Left
takeWhile :: (Char -> Bool) -> Parser String
takeWhile p = Parser $ Right . span p
takeWhile1 :: (Char -> Bool) -> Parser String
takeWhile1 p = Parser go
where
go "" = (Left . ParseError) "takeWhile1: unexpected end of input"
go (x:xs)
| p x = let (ys, zs) = span p xs in Right (x:ys, zs)
| otherwise = (Left . ParseError) ("takeWhile1: unexpected " ++ show x)
skipWhile :: (Char -> Bool) -> Parser ()
skipWhile p = takeWhile p *> pure ()
-- | Consume and return all remaining input.
takeInput :: Parser String
takeInput = Parser $ \input -> Right (input, "")
-- | Succeed only if all input has been consumed.
endOfInput :: Parser ()
endOfInput = Parser $ \input -> case input of
"" -> Right ((), "")
xs -> (Left . ParseError) ("endOfInput: remaining input " ++ show xs)
| vimus/vimus | src/Vimus/Command/Parser.hs | mit | 3,179 | 0 | 15 | 788 | 992 | 513 | 479 | 70 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module RegisterTest
( registerSpecs
) where
import TestImport
import qualified Data.Text as T
import qualified Data.List as L
cleanDB :: YesodExample App ()
cleanDB = do
runDB $ deleteWhere ([] :: [Filter Wish])
runDB $ deleteWhere ([] :: [Filter Wishlist])
runDB $ deleteWhere ([] :: [Filter User])
registerSpecs :: Specs
registerSpecs =
ydescribe "The register page" $ do
yit "displays the correct elements" $ do
cleanDB
get RegisterR
statusIs 200
htmlAllContain "h1" "Create new wish list"
bodyContains "Lilleengen Programvarefabrikk"
bodyContains "Name of wish list"
bodyContains "Administrator password"
bodyContains "Guest password"
yit "registers new lists and users through POST requests" $ do
cleanDB
get RegisterR
request $ do
setMethod "POST"
setUrl RegisterR
addNonce
byLabel "Name of wish list" "foo bar LOLZ"
byLabel "Short name used for guest URL (http://wishsys.lulf.no/wishlist/<short name>/guest)" "foobar"
byLabel "Administrator password" "foo"
byLabel "Guest password" "bar"
statusIs 303
lists <- runDB $ selectList ([] :: [Filter Wishlist]) []
assertEqual "wish list was not registered!" 1 $ L.length lists
let (Entity _ list) = head lists
assertEqual "list name is not correct" "foobar" $ wishlistUrlName list
users <- runDB $ selectList ([] :: [Filter User]) []
assertEqual "users not registered" 2 $ L.length users
let (Entity _ first) = head users
let (Entity _ second) = head $ tail users
assertEqual "admin user not correct" "admin_foobar" $ T.unpack $ userName first
assertEqual "guest user not correct" "guest_foobar" $ T.unpack $ userName second
yit "provides a useful error message if list already exists" $ do
cleanDB
get RegisterR
request $ do
setMethod "POST"
setUrl RegisterR
addNonce
byLabel "Name of wish list" "foo bar LOLZ"
byLabel "Short name used for guest URL (http://wishsys.lulf.no/wishlist/<short name>/guest)" "foobar"
byLabel "Administrator password" "foo"
byLabel "Guest password" "bar"
statusIs 303
get RegisterR
request $ do
setMethod "POST"
setUrl RegisterR
addNonce
byLabel "Name of wish list" "foo bar LOLZ"
byLabel "Short name used for guest URL (http://wishsys.lulf.no/wishlist/<short name>/guest)" "foobar"
byLabel "Administrator password" "mamma"
byLabel "Guest password" "pappa"
statusIs 303
get RegisterR
htmlAnyContain "div" "Wish list already exists, please choose a different name"
| lulf/wishsys | tests/RegisterTest.hs | mit | 3,145 | 0 | 16 | 1,105 | 652 | 281 | 371 | 69 | 1 |
module Main where
import Password (findNextPassword)
input = "hepxcrrq"
partOne = findNextPassword input
partTwo = fmap findNextPassword $ findNextPassword input
main = print partTwo
| corajr/adventofcode2015 | 11/Main.hs | mit | 187 | 0 | 6 | 28 | 48 | 26 | 22 | 6 | 1 |
module Exercise2 where
import Test.QuickCheck
-- maxi x y returns the maximum of x and y
maxi :: Int -> Int -> Int
maxi i j | i >= j = i
| otherwise = j
-- sumsq n returns 1*1 + 2*2 + ... + n*n
sumsq :: Int -> Int
sumsq 0 = 0
sumsq i = (i' * i') + (sumsq (i' - 1))
where
i' = abs i
sumsq' :: Int -> Int
sumsq' n = n * (n+1) * (2*n + 1) `div` 6
prop_sumsq :: Int -> Bool
prop_sumsq n = sumsq' n' == sumsq n'
where
n' = abs n
-- fib n computes the nth Fibonacci number
fib :: Int -> Int
fib 0 = 1
fib 1 = 1
fib n = fib (n - 2) + fib (n - 1)
smallestFactor :: Int -> Int
smallestFactor n = nextFactor 2 n
nextFactor :: Int -> Int -> Int
nextFactor k n | n `mod` k == 0 = k
| otherwise = nextFactor (k + 1) n
numFactors :: Int -> [Int]
numFactors n = [x | x <- [1..n], n `mod` x == 0]
prop_numfac :: Int -> Bool
prop_numfac n = and $ map (\x -> n `mod` x == 0) (numFactors n)
prop_smallfac :: Int -> Bool
prop_smallfac n = and $ map (\x -> n `mod` x /= 0) ps
where
sf = smallestFactor n
ps = [2..sf]
multiply :: Num a => [a] -> a
multiply [] = 1
multiply (x:xs) = x * multiply xs
prop_multL :: [Int] -> Bool
prop_multL i = product i == multiply i
duplicates :: Eq a => [a] -> Bool
duplicates xs = length xs == length (removeDuplicates xs)
removeDuplicates :: Eq a => [a] -> [a]
removeDuplicates [] = []
removeDuplicates (x:xs) = case x `elem` xs of
True -> removeDuplicates xs
False -> x:removeDuplicates xs
prop_duplicatesRemoved :: [Integer] -> Bool
prop_duplicatesRemoved xs = not (duplicates (removeDuplicates xs)) | tdeekens/tda452-code | Exercises/exercise-2.hs | mit | 1,660 | 0 | 10 | 476 | 742 | 387 | 355 | 45 | 2 |
module Eval (flatten, reduceB, beta) where
import Defs
import Data.Maybe
import Data.List
import Control.Applicative
flatten :: [Defn] -> Maybe Lambda
flatten ds = flatten' <$> main
where
main = snd <$> find ((== "Main").fst) resolved
flatten' :: Lambda -> Lambda
flatten' (Free s) = fromMaybe (Free s) $ lookup s resolved
flatten' (Var s) = (Var s)
flatten' (Abs v b) = Abs v $ flatten' b
flatten' (App f a) = App (flatten' f) (flatten' a)
resolved = head $ drop 10 $ iterate (map (resolve' <$>)) ds -- I am a bad person... TODO
where
resolve' (Var v) = (Var v)
resolve' (Abs f b) = Abs f $ resolve' b
resolve' (App f ar) = App (resolve' f) (resolve' ar)
resolve' (Free f) = fromMaybe (Free f) $ lookup f ds
reduceB :: Lambda -> Lambda
reduceB l = go l (beta l)
where
go p Nothing = p
go _ (Just n) = go n (beta n)
beta :: Lambda -> Maybe Lambda
beta (Var _) = Nothing
beta (Free _) = Nothing
beta (Abs f b) = Abs <$> pure f <*> beta b
beta (App (Abs v b) ar) = Just $ replace b v ar
beta (App (Free f) ar) = App (Free f) <$> beta ar
beta (App f ar) = App <$> beta f <*> pure ar
replace :: Lambda -> Int -> Lambda -> Lambda
replace (App f a) s ar = App (replace f s ar) (replace a s ar)
replace (Free s) _ _ = Free s
replace (Var s) s' ar | s == s' = ar
| otherwise = Var s
replace (Abs s b) s' ar | s == s' = Abs s b
| otherwise = Abs s (replace b s' ar)
| lukegrehan/lambda | Eval.hs | mit | 1,537 | 0 | 12 | 478 | 772 | 380 | 392 | 36 | 7 |
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
module Matek.Inline
( mkScalar
, mkDecomposable
, blockMap
, matekCtx
) where
import qualified Data.Map as M
import Data.Monoid
import Data.Traversable
import qualified Language.C.Inline.Context as C
import qualified Language.C.Inline.Unsafe as CU
import qualified Language.C.Inline.Cpp as C
import qualified Language.C.Types as C
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Language
import Text.ParserCombinators.Parsec.Token
import qualified Text.RawString.QQ as RS
import Matek.Types
data Token
= CharToken Char
| TypeQuoteToken String
| MapQuoteToken String Access
deriving (Eq, Ord, Show)
tokenize :: String -> [ Token ]
tokenize s = case parse (many $ try parseMapQuote <|> try parseTypeQuote <|> (CharToken <$> anyChar)) "" s of
Left err -> error $ "impossibly failed to tokenize: " ++ show err
Right ts -> ts
where
TokenParser {..} = makeTokenParser haskellDef
parseMapQuote = do
_ <- string "$map"
acc <- (RW <$ try (string "RW")) <|> (R <$ string "R")
_ <- string "("
cmName <- identifier
_ <- string ")"
return $ MapQuoteToken cmName acc
parseTypeQuote = do
_ <- string "$type("
cmName <- identifier
_ <- string ")"
return $ TypeQuoteToken cmName
-- like C.block but $map(r) (where r is a CMatrix a) gets replaced with an Eigen Map with the given element type
blockMap :: String -> (String -> ( Name, String )) -> Q Exp
blockMap cBlock mapTypeOf = do
let cBlockTokens = tokenize cBlock
blockResults <- for cBlockTokens $ \case
CharToken c -> return ( [ c ], [] )
MapQuoteToken cmName acc -> do
let ptrName = mkName (cmName ++ "_cmPtr_inline")
let rowsName = mkName (cmName ++ "_cmRows_inline")
let colsName = mkName (cmName ++ "_cmCols_inline")
let ( mapType, cType ) = mapTypeOf cmName
let replacement = concat
[ "Map<"
, case acc of { RW -> ""; R -> "const " }
, "Matrix<"
, cType
, ", Dynamic, Dynamic>>($("
, cType
, "* "
, nameBase ptrName
, "), $(size_t "
, nameBase rowsName
, "), $(size_t "
, nameBase colsName
, "))"
]
return ( replacement, [ ( ptrName, rowsName, colsName, mkName cmName, mapType, acc ) ] )
TypeQuoteToken cmName -> do
let ( _ , cType ) = mapTypeOf cmName
return ( cType, [] )
let ( translatedCBlockStrings, cmBinds ) = unzip blockResults
let translatedCBlock = concat translatedCBlockStrings
let bindCMs =
[ letS
[ valD
(recP 'CMatrix
[ fieldPat 'cmData (varP ptrName)
, fieldPat 'cmRows (varP rowsName)
, fieldPat 'cmCols (varP colsName)
])
(normalB [e| $(varE cmName) :: CMatrix $(accType) $(mapTypeType) |] )
[]
]
| ( ptrName, rowsName, colsName, cmName, mapType, acc ) <- concat cmBinds
, let mapTypeType = conT mapType
, let accType = case acc of
R -> [t|'R|]
RW -> [t|'RW|]
]
doE (bindCMs ++ [ noBindS (quoteExp CU.block translatedCBlock) ])
mkScalar :: Name -> Name -> String -> DecsQ
mkScalar scalarName cScalarName cType =
[d|
instance Scalar $(scalar) where
type CScalar $(scalar) = $(cScalar)
cmPlus r x y = $(blockMap [RS.r| void {
$mapRW(r) = $mapR(x) + $mapR(y);
} |] (const ( scalarName, cType )))
cmMinus r x y = $(blockMap [RS.r| void {
$mapRW(r) = $mapR(x) - $mapR(y);
} |] (const ( scalarName, cType )))
cmMul r x y = $(blockMap [RS.r| void {
$mapRW(r) = $mapR(x) * $mapR(y);
} |] (const ( scalarName, cType )))
cmTranspose r x = $(blockMap [RS.r| void {
$mapRW(r) = $mapR(x).transpose();
} |] (const ( scalarName, cType )))
cmAbs r x = $(blockMap [RS.r| void {
$mapRW(r).array() = $mapR(x).array().abs();
} |] (const ( scalarName, cType )))
cmMap f r x = $(blockMap [RS.r| void {
$mapRW(r) = $mapR(x).unaryExpr(std::ptr_fun($($type(x) (*f)($type(x)) )));
} |] (const ( scalarName, cType )))
cmSignum r x = $(blockMap [RS.r| void {
auto signum = []($type(x) n) { return n > 0 ? 1 : (n == 0 ? 0 : -1); };
$mapRW(r) = $mapR(x).unaryExpr(signum);
} |] (const ( scalarName, cType )))
cmScale k r x = $(blockMap [RS.r| void {
$mapRW(r) = $mapR(x) * $($type(x) k);
} |] (const ( scalarName, cType )))
cmCopyBlock r dstRow dstCol x = $(blockMap [RS.r| void {
auto src = $mapR(x);
$mapRW(r).block($(size_t dstRow), $(size_t dstCol), src.rows(), src.cols()) = src;
} |] (const ( scalarName, cType )))
|]
where
scalar = conT scalarName
cScalar = conT cScalarName
mkDecomposable :: Name -> String -> DecsQ
mkDecomposable scalarName cType =
[d|
instance Decomposable $(conT scalarName) where
cmFullSVD u s v m = $(blockMap [RS.r| void {
JacobiSVD<Matrix<$type(m), Dynamic, Dynamic>> svd($mapR(m), ComputeFullU | ComputeFullV);
$mapRW(u) = svd.matrixU();
$mapRW(s) = svd.singularValues();
$mapRW(v) = svd.matrixU();
} |] (const ( scalarName, cType )))
|]
matekTypesTable :: M.Map C.TypeSpecifier TypeQ
matekTypesTable = M.fromList
[ (C.TypeName "CEigenException", [t| CEigenException |]) -- needs a typedef
]
matekCtx :: C.Context
matekCtx = C.cppCtx <> ctx
where
ctx = mempty { C.ctxTypesTable = matekTypesTable } | chpatrick/matek | src/Matek/Inline.hs | mit | 6,030 | 20 | 22 | 1,756 | 1,413 | 784 | 629 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
module ProC.ParserSpec
( spec
) where
import ProC.Language
import ProC.Parser
import Test.Hspec
import Text.RawString.QQ
spec :: Spec
spec =
describe "parseProC" $ do
it "parses Hello World" $
parseProC [r| print("Hello World"); |] `shouldReturn`
Right (Seq [Print (PStrLiteral "Hello World")])
it "parses assignment" $
parseProC [r| int a=1; a=2; |] `shouldReturn`
Right
(Seq
[ PIntVarDcl (Identifier "a") (PIntLiteral 1)
, PIntVarAss (Identifier "a") (PIntLiteral 2)
])
it "parses blocks" $
parseProC [r| { print("Hello World"); } |] `shouldReturn`
Right (Seq [Block [Print (PStrLiteral "Hello World")]])
it "allows references to outer scopes" $
parseProC [r| int a=0; { int b=a; } |] `shouldReturn`
Right
(Seq
[ PIntVarDcl (Identifier "a") (PIntLiteral 0)
, Block [PIntVarDcl (Identifier "b") (PIntVariable (Identifier "a"))]
])
it "allows shadowing in blocks" $
parseProC [r| int a=0; { int a=1; } |] `shouldReturn`
Right
(Seq
[ PIntVarDcl (Identifier "a") (PIntLiteral 0)
, Block [PIntVarDcl (Identifier "a") (PIntLiteral 1)]
])
it "allows statements after blocks" $
parseProC [r| { int a=1; } print("Hello World"); |] `shouldReturn`
Right
(Seq
[ Block [PIntVarDcl (Identifier "a") (PIntLiteral 1)]
, Print (PStrLiteral "Hello World")
])
it "allows shadowing after blocks" $
parseProC [r| { int a=1; } int a=0; |] `shouldReturn`
Right
(Seq
[ Block [PIntVarDcl (Identifier "a") (PIntLiteral 1)]
, PIntVarDcl (Identifier "a") (PIntLiteral 0)
])
it "parses whl loops" $
parseProC [r| whl (tru) { print("Hello World"); } |] `shouldReturn`
Right (Seq [Whl (PBlnLiteral True) [Print (PStrLiteral "Hello World")]])
| ianagbip1oti/ProC | test/ProC/ParserSpec.hs | mit | 2,026 | 0 | 19 | 626 | 584 | 305 | 279 | 49 | 1 |
module Vector
( Vect,
xComp,
yComp,
zComp,
vect,
(^+^),
(^-^),
(*^),
(^*),
(^/),
(<.>),
(><),
magnitude,
zeroVect,
negateVect,
sumVect
)
where
infixl 6 ^+^
infixl 6 ^-^
infixl 7 *^
infixl 7 ^*
infixl 7 ^/
infixl 7 ><
infixl 7 <.>
-- | data type for vectors.
data Vect = Vect { xComp :: Double,
yComp :: Double,
zComp :: Double
}
deriving Eq
instance Show Vect where
show (Vect x y z) = "vect" ++ showDouble x ++ " "
++ showDouble y ++ " "
++ showDouble z
showDouble :: Double -> String
showDouble x
| x < 0 = "(" ++ show x ++ ")"
| otherwise = show x
-- | smart constructor for vectors.
vect :: Double -> Double -> Double -> Vect
vect = Vect
-- | addition.
(^+^) :: Vect -> Vect -> Vect
Vect ax ay az ^+^ Vect bx by bz = Vect (ax + bx) (ay + by) (az + bz)
-- | subtraction.
(^-^) :: Vect -> Vect -> Vect
Vect ax ay az ^-^ Vect bx by bz = Vect (ax - bx) (ay - by) (az - bz)
-- | scalar multiplication (vector on right).
(*^) :: Double -> Vect -> Vect
c *^ Vect ax ay az = Vect (c * ax) (c * ay) (c * az)
-- | scalar multiplication (vector on left).
(^*) :: Vect -> Double -> Vect
Vect ax ay az ^* c = Vect (c * ax) (c * ay) (c * az)
-- | scalar division (vector on left).
(^/) :: Vect -> Double -> Vect
Vect ax ay az ^/ c = Vect (ax / c) (ay / c) (az / c)
-- | cross product.
(><) :: Vect -> Vect -> Vect
Vect ax ay az >< Vect bx by bz = Vect ((ay * bz) - (az * by)) ((az * bx) - (ax * bz)) ((ax * by) - (ay * bx))
-- | dot product.
(<.>) :: Vect -> Vect -> Double
Vect ax ay az <.> Vect bx by bz = ax * bx + ay * by + az * bz
-- | magnitude of a vector
magnitude :: Vect -> Double
magnitude v = sqrt(v <.> v)
-- | zero vector.
zeroVect :: Vect
zeroVect = Vect 0 0 0
-- | additive inverse of a vector.
negateVect :: Vect -> Vect
negateVect (Vect ax ay az) = Vect (-ax) (-ay) (-az)
-- | sum of a list of vectors.
sumVect :: [Vect] -> Vect
sumVect = foldr (^+^) zeroVect
| abbottk/MICL | DSL/PNP/Vector.hs | cc0-1.0 | 2,185 | 0 | 11 | 747 | 879 | 482 | 397 | 60 | 1 |
module Tests.ParseJuicyTest (parseJuicyTestDo) where
import Test.HUnit
import Scan.ParseJuicy( getThePixelsRightOfCenter, convertPixelsToMillmeters, calculateRadiusFrom, averageValueOf,
removeLeftOfCenterPixels, TargetValueIndex(..), calculatePixelsPerMillmeter )
import CornerPoints.Radius(Radius(..))
import Helpers.DSL (ofThe, forThe, andThen, adjustedFor, andThe,)
import qualified Data.Map as Map
parseJuicyTestDo = do
runTestTT calculateRadiusFromPixelsRightOfCenterTest
runTestTT calculateMillimetersTest
--get pixels right of center
runTestTT adjustPixelIndexForLeftSlopeTestRedo
runTestTT calculatePixelsPerMillmeterTest
--get rid of blank values
runTestTT whatIsDivdeZeroBy
runTestTT averageValueOfValidListTest
runTestTT averageValueOfEmptyListTest
--runTestTT filePathBuilderBaseAllGoodTest
--runTestTT filePathBuilderBaseNoSlashTest
{-
fileNameBuilder and filePathBuilderBase do not need to be exported, and
have been moved into a let clause.
Keep for testing them if required.
filePathBuilderBaseAllGoodTest = TestCase $ assertEqual
"filePathBuilderBaseAllGoodTest"
(Map.fromList [(0,"myPath/myFileName1010.JPG"),
(10,"myPath/myFileName1011.JPG")
])
(filePathBuilderBase "myPath/" fileNameBuilder "myFileName" "JPG" [1010..] [0,10] )
filePathBuilderBaseNoSlashTest = TestCase $ assertEqual
"filePathBuilderBaseNoSlashTest"
(Map.fromList [(0,"myPath/myFileName1010.JPG"),
(10,"myPath/myFileName1011.JPG")
])
(filePathBuilderBase "myPath" fileNameBuilder "myFileName" "JPG" [1010..] [0,10] )
-}
calculateRadiusFromPixelsRightOfCenterTest = TestCase $ assertEqual
("calculate Radius From Pixels Right Of Center Test")
(Radius 4)
(let pixelsPerMillemter = 100/1
pixelsRightOfCenter = 200
cameraAngle = 30
in calculateRadiusFrom pixelsRightOfCenter (adjustedFor pixelsPerMillemter) $ andThe cameraAngle
)
calculatePixelsPerMillmeterTest = TestCase $ assertEqual
"calculatePixelsPerMillmeterTest"
(18.14220374220374)
(calculatePixelsPerMillmeter 2592 390 37 101 )
--calculatePixelsPerMillmeter :: NumberOfPixels -> Millimeters -> Millimeters -> Millimeters -> PixelsPerMillimeter
--calculatePixelsPerMillmeter imageWidthPx imageWidthMM objectWidthReadWorldMM objectWidthOnScreenMM =
calculateMillimetersTest = TestCase $ assertEqual
("calculate millimeters from pixels")
(2)
(let pixelsPerMillemter = 50/1
in convertPixelsToMillmeters pixelsPerMillemter 100
)
{-
Given a center for top and bottom of image, and an index of the target value,
calculate the radius of the target value, adjusting for the slope of the laser line.
-}
adjustPixelIndexForLeftSlopeTestRedo = TestCase $ assertEqual
("adjust Pixel Index For Left Slope Test")
([10.0::TargetValueIndex, 20.0::TargetValueIndex, 30.0::TargetValueIndex])
(let totalRows = 100
topCenter = 110
btmCenter = 90
topRow = 0
middleRow = 50
btmRow = totalRows
targetValueIndex = 120
pixelsRightOfCenter = getThePixelsRightOfCenter $ andThen (removeLeftOfCenterPixels btmCenter topCenter totalRows)
in
[
pixelsRightOfCenter (forThe targetValueIndex) $ ofThe topRow,
pixelsRightOfCenter (forThe targetValueIndex) $ ofThe middleRow,
pixelsRightOfCenter (forThe targetValueIndex) $ ofThe btmRow
]
)
whatIsDivdeZeroBy = TestCase $ assertEqual
"whatIsDivdeZeroBy"
0
(0/3)
averageValueOfValidListTest = TestCase $ assertEqual
"averageValueOfValidListTest"
1.5
(averageValueOf [1,2])
averageValueOfEmptyListTest = TestCase $ assertEqual
"averageValueOfEmptyListTest"
True
(isNaN $ averageValueOf [])
| heathweiss/Tricad | src/Tests/ParseJuicyTest.hs | gpl-2.0 | 3,865 | 0 | 15 | 753 | 537 | 289 | 248 | 58 | 1 |
module Shortlines where
-- interact :: (String -> String) -> IO ()
main :: IO ()
main = interact (unlines . filter ((<10) . length) . lines)
-- cat resources/quotes | runhaskell shortline
-- I'm
-- trying
-- to
-- free
-- your
-- mind,
-- Neo.
| ardumont/haskell-lab | src/io/shortline.hs | gpl-2.0 | 247 | 0 | 12 | 50 | 56 | 35 | 21 | 3 | 1 |
{-# language TemplateHaskell #-}
{-# language DeriveDataTypeable #-}
{-# language GeneralizedNewtypeDeriving #-}
module FD.Data where
import Autolib.Reader
import Autolib.ToDoc
import qualified Data.Set as S
import Data.Typeable
import Control.Applicative ((<$>),(<*>))
formula0 :: Formula
formula0 =
[ Atom (Rel "P") [ Var "x", Var "y", Var "z" ]
, Atom (Rel "P") [ Var "x", Var "x", Var "y" ]
, Atom (Rel "G") [ Var "y", Var "x" ]
]
newtype Var = Var { unVar :: String }
deriving (Eq, Ord, Typeable )
instance ToDoc Var where toDoc = text . unVar
instance Show Var where show = render . toDoc
instance Reader Var where reader = Var <$> my_identifier
newtype Rel = Rel { unRel :: String }
deriving (Eq, Ord, Typeable )
instance ToDoc Rel where toDoc = text . unRel
instance Show Rel where show = render . toDoc
instance Reader Rel where reader = Rel <$> my_identifier
data Atom = Atom { rel :: Rel, args :: [ Var ] }
deriving (Eq, Ord, Typeable )
instance ToDoc Atom where
toDoc (Atom rel args) = toDoc rel <+> dutch_tuple (map toDoc args)
instance Show Atom where show = render . toDoc
instance Reader Atom where
reader = Atom <$> reader <*> my_parens ( my_commaSep reader )
type Formula = [ Atom ]
variables :: Formula -> S.Set Var
variables = S.fromList . concat . map args
| marcellussiegburg/autotool | collection/src/FD/Data.hs | gpl-2.0 | 1,342 | 0 | 9 | 294 | 476 | 262 | 214 | 34 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module OpenSandbox.World.ChunkSpec (main,spec) where
import Common
import Control.Monad
import Data.NBTSpec()
import qualified Data.Vector as V
import Data.Word
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Test
import OpenSandbox.Data.Block (BlockIndice)
import OpenSandbox.Data.BlockSpec()
import OpenSandbox.World
instance Arbitrary BlockIndice where
arbitrary = fromIntegral <$> (arbitrary :: Gen Word8) :: Gen BlockIndice
instance Arbitrary BlockIndices where
arbitrary = BlockIndices <$> vectorOf 4096 arbitrary
instance Arbitrary ChunkColumn where
arbitrary = mkChunkColumn <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary ChunkColumnData where
arbitrary = do
k <- choose (1,16) :: Gen Int
chunks <- V.fromList <$> vectorOf k arbitrary
case mkChunkColumnData chunks of
Left err -> fail err
Right chunkColumnData -> return chunkColumnData
instance Arbitrary ChunkBlock where
arbitrary = do
dat <- arbitrary :: Gen ChunkBlockData
blockLight <- (V.fromList <$> vectorOf 2048 arbitrary)
skyLight <- (V.fromList <$> vectorOf 2048 arbitrary)
case mkChunkBlock dat blockLight skyLight of
Left err -> fail err
Right chunkBlock -> return chunkBlock
instance Arbitrary ChunkBlockData where
arbitrary = do
blocks <- vectorOf 4096 arbitrary
case (mkChunkBlockData . V.fromList $ blocks) of
Left err -> fail err
Right chunkBlockData -> return chunkBlockData
instance Arbitrary BiomeIndices where
arbitrary = do
indices <- vectorOf 256 arbitrary
case (mkBiomeIndices . V.fromList $ indices) of
Left err -> fail err
Right biomeIndices -> return biomeIndices
instance Arbitrary BitsPerBlock where
arbitrary = fmap mkBitsPerBlock (arbitrary :: Gen BitsPerBlockOption)
instance Arbitrary BitsPerBlockOption where
arbitrary = fmap toEnum (choose (4,13) :: Gen Int)
instance Arbitrary PrimaryBitMask where
arbitrary = mkPrimaryBitMask <$> arbitrary
prop_IdentityPackIndices :: BlockIndices -> Bool
prop_IdentityPackIndices indices =
unBlockIndices indices == unpackIndices bpb 0 0 (packIndices bpb 0 0 indices)
where
bpb = mkBitsPerBlock BitsPerBlock16
prop_IdentityCompressIndices :: ChunkBlockData -> Bool
prop_IdentityCompressIndices indices = indices == decompressIndices bpb palette (compressIndices bpb palette indices)
where
(bpb,palette) = calcPalette indices
spec :: Spec
spec = do
describe "ChunkColumn" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs { maxSize = 20, maxSuccess = 20 }
(prop_SerializeIdentity :: ChunkColumn -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "ChunkColumnData" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs { maxSize = 20, maxSuccess = 20 }
(prop_SerializeIdentity :: ChunkColumnData -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "ChunkBlock" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs { maxSize = 20, maxSuccess = 50 }
(prop_SerializeIdentity :: ChunkBlock -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "BiomeIndices" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: BiomeIndices -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "BitsPerBlock" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: BitsPerBlock -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "PrimaryBitMask" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
(prop_SerializeIdentity :: PrimaryBitMask -> Bool)
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "Packing Indices" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
prop_IdentityPackIndices
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
describe "Compressing Indices" $
it "Identity" $ do
r <- quickCheckWithResult
stdArgs
prop_IdentityCompressIndices
unless (isSuccess r) $ print r
isSuccess r `shouldBe` True
main :: IO ()
main = hspec spec
| oldmanmike/opensandbox | test/OpenSandbox/World/ChunkSpec.hs | gpl-3.0 | 4,470 | 0 | 13 | 999 | 1,305 | 638 | 667 | 120 | 1 |
-- | Parse RNAfold output
-- For more information on RNAfold consult: <http://www.tbi.univie.ac.at/RNA/RNAfold>
module Bio.RNAfoldParser (
systemRNAfold,
parseRNAfold,
readRNAfold,
systemRNAfoldOptions,
parseRNAMEAfold,
readRNAMEAfold,
module Bio.RNAfoldData
) where
import Bio.RNAfoldData
import Text.ParserCombinators.Parsec
import Bio.ViennaRNAParserLibrary
import System.Process
import System.Exit
import qualified Control.Exception.Base as CE
-- | Run external RNAfold command and read the output into the corresponding datatype
systemRNAfold :: String -> String -> IO ExitCode
systemRNAfold inputFilePath outputFilePath = system ("RNAfold --noPS <" ++ inputFilePath ++ " >" ++ outputFilePath)
-- | Run external RNAfold command and read the output into the corresponding datatype
systemRNAfoldOptions :: String -> String -> String -> IO ExitCode
systemRNAfoldOptions foldoptions inputFilePath outputFilePath = system ("RNAfold --noPS " ++ foldoptions ++ " <" ++ inputFilePath ++ " >" ++ outputFilePath)
-- | Parse the RNAfold results
genParserRNAfold :: GenParser Char st RNAfold
genParserRNAfold = do
string (">")
_sequenceIdentifier <- many1 (noneOf "\n")
newline
_sequence <- many1 (noneOf "\n")
newline
_secondaryStructure <- many1 (oneOf "&().,")
space
string ("(")
_foldingEnergy <- many1 (noneOf ")")
string (")")
return $ RNAfold _sequenceIdentifier _sequence _secondaryStructure (readDouble _foldingEnergy)
-- | parse RNAfold output from input string
parseRNAfold :: [Char] -> Either ParseError RNAfold
parseRNAfold input = parse genParserRNAfold "genParseRNAfold" input
-- | parse RNAfold output from input filePath
readRNAfold :: String -> IO (Either ParseError RNAfold)
readRNAfold filePath = do
parsedFile <- parseFromFile genParserRNAfold filePath
CE.evaluate parsedFile
-- | Parse the RNAfold maximum expected accuracy results
genParserRNAMEAfold :: GenParser Char st RNAfoldMEA
genParserRNAMEAfold = do
string (">")
_sequenceIdentifier <- many1 (noneOf "\n")
newline
_sequence <- many1 (noneOf "\n")
newline
--MFE
_mfestructure <- many1 (oneOf "&().,")
space
string ("(")
_mfefoldingEnergy <- many1 (noneOf ")")
string (")")
--coarse representation
newline
_coarsestructure <- many1 (oneOf "&().,")
space
string ("[")
_coarsefoldingEnergy <- many1 (noneOf "]")
string ("]")
--centroid structure
newline
_centroidstructure <- many1 (oneOf "&().,")
space
string ("{")
_centroidfoldingEnergy <- many1 (noneOf " ")
string (" ")
_centroiddistance <- many1 (noneOf "}")
string ("}")
--MEA
newline
_meastructure <- many1 (oneOf "&().,")
space
string ("{")
_meafoldingenergy <- many1 (noneOf " ")
string (" ")
_meadistance <- many1 (noneOf "}")
string ("}")
newline
string " frequency of mfe structure in ensemble "
_mfefreq <- many1 (noneOf ";")
string "; ensemble diversity "
_ensemblediversity <- many1 (noneOf " ")
string " "
return $ RNAfoldMEA _sequenceIdentifier _sequence _mfestructure (readDouble _mfefoldingEnergy) _coarsestructure (readDouble _coarsefoldingEnergy) _centroidstructure (readDouble _centroidfoldingEnergy) (readDouble _centroiddistance) _meastructure (readDouble _meafoldingenergy) (readDouble _meadistance) (readDouble _mfefreq) (readDouble _ensemblediversity)
-- | parse RNAfold output from input string
parseRNAMEAfold :: [Char] -> Either ParseError RNAfoldMEA
parseRNAMEAfold input = parse genParserRNAMEAfold "genParseRNAfold" input
-- | parse RNAfold output from input filePath
readRNAMEAfold :: String -> IO (Either ParseError RNAfoldMEA)
readRNAMEAfold filePath = do
parsedFile <- parseFromFile genParserRNAMEAfold filePath
CE.evaluate parsedFile
| eggzilla/ViennaRNAParser | src/Bio/RNAfoldParser.hs | gpl-3.0 | 4,062 | 0 | 11 | 915 | 954 | 455 | 499 | 84 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Lib.Syntax.Annotated where
import Control.Comonad
import Control.Comonad.Cofree
import Control.Monad.Free
import Data.Traversable
import Control.Monad.Error
import Lib.Errors
import Lib.Syntax.Core
import Lib.Syntax.Surface (SurfaceAst, SurfaceExpr ())
import Lib.Syntax.Symbol
-- | Annotated Expressions
-- An annotated expression is a 'CoreExpr' inverted, with every branch
-- containing an annotation of some carrier type.
type AnnotatedExpr = Cofree CoreAst
-- | Converts a 'CoreExpr' fresh out of the parser into an 'AnnotatedExpr'.
annotated
:: (MonadError PsiloError m, Traversable f)
=> Free f ()
-> m (Cofree f ())
annotated (Pure _) = throwError $ PreprocessError "Error annotating syntax tree"
annotated (Free m) = fmap (() :<) $ traverse annotated m
| gatlin/psilo | src/Lib/Syntax/Annotated.hs | gpl-3.0 | 903 | 0 | 10 | 207 | 182 | 104 | 78 | 18 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidEnterprise.Enterprises.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Looks up an enterprise by domain name. This is only supported for
-- enterprises created via the Google-initiated creation flow. Lookup of
-- the id is not needed for enterprises created via the EMM-initiated flow
-- since the EMM learns the enterprise ID in the callback specified in the
-- Enterprises.generateSignupUrl call.
--
-- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.enterprises.list@.
module Network.Google.Resource.AndroidEnterprise.Enterprises.List
(
-- * REST Resource
EnterprisesListResource
-- * Creating a Request
, enterprisesList
, EnterprisesList
-- * Request Lenses
, elDomain
) where
import Network.Google.AndroidEnterprise.Types
import Network.Google.Prelude
-- | A resource alias for @androidenterprise.enterprises.list@ method which the
-- 'EnterprisesList' request conforms to.
type EnterprisesListResource =
"androidenterprise" :>
"v1" :>
"enterprises" :>
QueryParam "domain" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] EnterprisesListResponse
-- | Looks up an enterprise by domain name. This is only supported for
-- enterprises created via the Google-initiated creation flow. Lookup of
-- the id is not needed for enterprises created via the EMM-initiated flow
-- since the EMM learns the enterprise ID in the callback specified in the
-- Enterprises.generateSignupUrl call.
--
-- /See:/ 'enterprisesList' smart constructor.
newtype EnterprisesList = EnterprisesList'
{ _elDomain :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EnterprisesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'elDomain'
enterprisesList
:: Text -- ^ 'elDomain'
-> EnterprisesList
enterprisesList pElDomain_ =
EnterprisesList'
{ _elDomain = pElDomain_
}
-- | The exact primary domain name of the enterprise to look up.
elDomain :: Lens' EnterprisesList Text
elDomain = lens _elDomain (\ s a -> s{_elDomain = a})
instance GoogleRequest EnterprisesList where
type Rs EnterprisesList = EnterprisesListResponse
type Scopes EnterprisesList =
'["https://www.googleapis.com/auth/androidenterprise"]
requestClient EnterprisesList'{..}
= go (Just _elDomain) (Just AltJSON)
androidEnterpriseService
where go
= buildClient
(Proxy :: Proxy EnterprisesListResource)
mempty
| rueshyna/gogol | gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Enterprises/List.hs | mpl-2.0 | 3,433 | 0 | 12 | 739 | 313 | 195 | 118 | 49 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ServiceManagement.Services.SetIAMPolicy
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets the access control policy on the specified resource. Replaces any
-- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and
-- \`PERMISSION_DENIED\` errors.
--
-- /See:/ <https://cloud.google.com/service-management/ Service Management API Reference> for @servicemanagement.services.setIamPolicy@.
module Network.Google.Resource.ServiceManagement.Services.SetIAMPolicy
(
-- * REST Resource
ServicesSetIAMPolicyResource
-- * Creating a Request
, servicesSetIAMPolicy
, ServicesSetIAMPolicy
-- * Request Lenses
, ssipXgafv
, ssipUploadProtocol
, ssipAccessToken
, ssipUploadType
, ssipPayload
, ssipResource
, ssipCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceManagement.Types
-- | A resource alias for @servicemanagement.services.setIamPolicy@ method which the
-- 'ServicesSetIAMPolicy' request conforms to.
type ServicesSetIAMPolicyResource =
"v1" :>
CaptureMode "resource" "setIamPolicy" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SetIAMPolicyRequest :>
Post '[JSON] Policy
-- | Sets the access control policy on the specified resource. Replaces any
-- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and
-- \`PERMISSION_DENIED\` errors.
--
-- /See:/ 'servicesSetIAMPolicy' smart constructor.
data ServicesSetIAMPolicy =
ServicesSetIAMPolicy'
{ _ssipXgafv :: !(Maybe Xgafv)
, _ssipUploadProtocol :: !(Maybe Text)
, _ssipAccessToken :: !(Maybe Text)
, _ssipUploadType :: !(Maybe Text)
, _ssipPayload :: !SetIAMPolicyRequest
, _ssipResource :: !Text
, _ssipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesSetIAMPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ssipXgafv'
--
-- * 'ssipUploadProtocol'
--
-- * 'ssipAccessToken'
--
-- * 'ssipUploadType'
--
-- * 'ssipPayload'
--
-- * 'ssipResource'
--
-- * 'ssipCallback'
servicesSetIAMPolicy
:: SetIAMPolicyRequest -- ^ 'ssipPayload'
-> Text -- ^ 'ssipResource'
-> ServicesSetIAMPolicy
servicesSetIAMPolicy pSsipPayload_ pSsipResource_ =
ServicesSetIAMPolicy'
{ _ssipXgafv = Nothing
, _ssipUploadProtocol = Nothing
, _ssipAccessToken = Nothing
, _ssipUploadType = Nothing
, _ssipPayload = pSsipPayload_
, _ssipResource = pSsipResource_
, _ssipCallback = Nothing
}
-- | V1 error format.
ssipXgafv :: Lens' ServicesSetIAMPolicy (Maybe Xgafv)
ssipXgafv
= lens _ssipXgafv (\ s a -> s{_ssipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ssipUploadProtocol :: Lens' ServicesSetIAMPolicy (Maybe Text)
ssipUploadProtocol
= lens _ssipUploadProtocol
(\ s a -> s{_ssipUploadProtocol = a})
-- | OAuth access token.
ssipAccessToken :: Lens' ServicesSetIAMPolicy (Maybe Text)
ssipAccessToken
= lens _ssipAccessToken
(\ s a -> s{_ssipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ssipUploadType :: Lens' ServicesSetIAMPolicy (Maybe Text)
ssipUploadType
= lens _ssipUploadType
(\ s a -> s{_ssipUploadType = a})
-- | Multipart request metadata.
ssipPayload :: Lens' ServicesSetIAMPolicy SetIAMPolicyRequest
ssipPayload
= lens _ssipPayload (\ s a -> s{_ssipPayload = a})
-- | REQUIRED: The resource for which the policy is being specified. See the
-- operation documentation for the appropriate value for this field.
ssipResource :: Lens' ServicesSetIAMPolicy Text
ssipResource
= lens _ssipResource (\ s a -> s{_ssipResource = a})
-- | JSONP
ssipCallback :: Lens' ServicesSetIAMPolicy (Maybe Text)
ssipCallback
= lens _ssipCallback (\ s a -> s{_ssipCallback = a})
instance GoogleRequest ServicesSetIAMPolicy where
type Rs ServicesSetIAMPolicy = Policy
type Scopes ServicesSetIAMPolicy =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient ServicesSetIAMPolicy'{..}
= go _ssipResource _ssipXgafv _ssipUploadProtocol
_ssipAccessToken
_ssipUploadType
_ssipCallback
(Just AltJSON)
_ssipPayload
serviceManagementService
where go
= buildClient
(Proxy :: Proxy ServicesSetIAMPolicyResource)
mempty
| brendanhay/gogol | gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/SetIAMPolicy.hs | mpl-2.0 | 5,584 | 0 | 16 | 1,216 | 784 | 459 | 325 | 115 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTubeAnalytics.Groups.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a collection of groups that match the API request parameters.
-- For example, you can retrieve all groups that the authenticated user
-- owns, or you can retrieve one or more groups by their unique IDs.
--
-- /See:/ <http://developers.google.com/youtube/analytics/ YouTube Analytics API Reference> for @youtubeAnalytics.groups.list@.
module Network.Google.Resource.YouTubeAnalytics.Groups.List
(
-- * REST Resource
GroupsListResource
-- * Creating a Request
, groupsList
, GroupsList
-- * Request Lenses
, glMine
, glOnBehalfOfContentOwner
, glId
, glPageToken
) where
import Network.Google.Prelude
import Network.Google.YouTubeAnalytics.Types
-- | A resource alias for @youtubeAnalytics.groups.list@ method which the
-- 'GroupsList' request conforms to.
type GroupsListResource =
"youtube" :>
"analytics" :>
"v1" :>
"groups" :>
QueryParam "mine" Bool :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "id" Text :>
QueryParam "pageToken" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GroupListResponse
-- | Returns a collection of groups that match the API request parameters.
-- For example, you can retrieve all groups that the authenticated user
-- owns, or you can retrieve one or more groups by their unique IDs.
--
-- /See:/ 'groupsList' smart constructor.
data GroupsList = GroupsList'
{ _glMine :: !(Maybe Bool)
, _glOnBehalfOfContentOwner :: !(Maybe Text)
, _glId :: !(Maybe Text)
, _glPageToken :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'GroupsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'glMine'
--
-- * 'glOnBehalfOfContentOwner'
--
-- * 'glId'
--
-- * 'glPageToken'
groupsList
:: GroupsList
groupsList =
GroupsList'
{ _glMine = Nothing
, _glOnBehalfOfContentOwner = Nothing
, _glId = Nothing
, _glPageToken = Nothing
}
-- | Set this parameter\'s value to true to instruct the API to only return
-- groups owned by the authenticated user.
glMine :: Lens' GroupsList (Maybe Bool)
glMine = lens _glMine (\ s a -> s{_glMine = a})
-- | Note: This parameter is intended exclusively for YouTube content
-- partners. The onBehalfOfContentOwner parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The CMS account that the user authenticates with must be linked
-- to the specified YouTube content owner.
glOnBehalfOfContentOwner :: Lens' GroupsList (Maybe Text)
glOnBehalfOfContentOwner
= lens _glOnBehalfOfContentOwner
(\ s a -> s{_glOnBehalfOfContentOwner = a})
-- | The id parameter specifies a comma-separated list of the YouTube group
-- ID(s) for the resource(s) that are being retrieved. In a group resource,
-- the id property specifies the group\'s YouTube group ID.
glId :: Lens' GroupsList (Maybe Text)
glId = lens _glId (\ s a -> s{_glId = a})
-- | The pageToken parameter identifies a specific page in the result set
-- that should be returned. In an API response, the nextPageToken property
-- identifies the next page that can be retrieved.
glPageToken :: Lens' GroupsList (Maybe Text)
glPageToken
= lens _glPageToken (\ s a -> s{_glPageToken = a})
instance GoogleRequest GroupsList where
type Rs GroupsList = GroupListResponse
type Scopes GroupsList =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtubepartner",
"https://www.googleapis.com/auth/yt-analytics.readonly"]
requestClient GroupsList'{..}
= go _glMine _glOnBehalfOfContentOwner _glId
_glPageToken
(Just AltJSON)
youTubeAnalyticsService
where go
= buildClient (Proxy :: Proxy GroupsListResource)
mempty
| rueshyna/gogol | gogol-youtube-analytics/gen/Network/Google/Resource/YouTubeAnalytics/Groups/List.hs | mpl-2.0 | 5,346 | 0 | 16 | 1,234 | 577 | 347 | 230 | 82 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.CloudBilling.Services.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all public cloud services.
--
-- /See:/ <https://cloud.google.com/billing/ Cloud Billing API Reference> for @cloudbilling.services.list@.
module Network.Google.Resource.CloudBilling.Services.List
(
-- * REST Resource
ServicesListResource
-- * Creating a Request
, servicesList
, ServicesList
-- * Request Lenses
, slXgafv
, slUploadProtocol
, slAccessToken
, slUploadType
, slPageToken
, slPageSize
, slCallback
) where
import Network.Google.Billing.Types
import Network.Google.Prelude
-- | A resource alias for @cloudbilling.services.list@ method which the
-- 'ServicesList' request conforms to.
type ServicesListResource =
"v1" :>
"services" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListServicesResponse
-- | Lists all public cloud services.
--
-- /See:/ 'servicesList' smart constructor.
data ServicesList =
ServicesList'
{ _slXgafv :: !(Maybe Xgafv)
, _slUploadProtocol :: !(Maybe Text)
, _slAccessToken :: !(Maybe Text)
, _slUploadType :: !(Maybe Text)
, _slPageToken :: !(Maybe Text)
, _slPageSize :: !(Maybe (Textual Int32))
, _slCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'slXgafv'
--
-- * 'slUploadProtocol'
--
-- * 'slAccessToken'
--
-- * 'slUploadType'
--
-- * 'slPageToken'
--
-- * 'slPageSize'
--
-- * 'slCallback'
servicesList
:: ServicesList
servicesList =
ServicesList'
{ _slXgafv = Nothing
, _slUploadProtocol = Nothing
, _slAccessToken = Nothing
, _slUploadType = Nothing
, _slPageToken = Nothing
, _slPageSize = Nothing
, _slCallback = Nothing
}
-- | V1 error format.
slXgafv :: Lens' ServicesList (Maybe Xgafv)
slXgafv = lens _slXgafv (\ s a -> s{_slXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
slUploadProtocol :: Lens' ServicesList (Maybe Text)
slUploadProtocol
= lens _slUploadProtocol
(\ s a -> s{_slUploadProtocol = a})
-- | OAuth access token.
slAccessToken :: Lens' ServicesList (Maybe Text)
slAccessToken
= lens _slAccessToken
(\ s a -> s{_slAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
slUploadType :: Lens' ServicesList (Maybe Text)
slUploadType
= lens _slUploadType (\ s a -> s{_slUploadType = a})
-- | A token identifying a page of results to return. This should be a
-- \`next_page_token\` value returned from a previous \`ListServices\`
-- call. If unspecified, the first page of results is returned.
slPageToken :: Lens' ServicesList (Maybe Text)
slPageToken
= lens _slPageToken (\ s a -> s{_slPageToken = a})
-- | Requested page size. Defaults to 5000.
slPageSize :: Lens' ServicesList (Maybe Int32)
slPageSize
= lens _slPageSize (\ s a -> s{_slPageSize = a}) .
mapping _Coerce
-- | JSONP
slCallback :: Lens' ServicesList (Maybe Text)
slCallback
= lens _slCallback (\ s a -> s{_slCallback = a})
instance GoogleRequest ServicesList where
type Rs ServicesList = ListServicesResponse
type Scopes ServicesList =
'["https://www.googleapis.com/auth/cloud-billing",
"https://www.googleapis.com/auth/cloud-billing.readonly",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient ServicesList'{..}
= go _slXgafv _slUploadProtocol _slAccessToken
_slUploadType
_slPageToken
_slPageSize
_slCallback
(Just AltJSON)
billingService
where go
= buildClient (Proxy :: Proxy ServicesListResource)
mempty
| brendanhay/gogol | gogol-billing/gen/Network/Google/Resource/CloudBilling/Services/List.hs | mpl-2.0 | 4,982 | 0 | 17 | 1,202 | 809 | 469 | 340 | 113 | 1 |
module Cloud.Haskzure.Resources where
import Cloud.Haskzure.Resources.Networking
import Cloud.Haskzure.Resources.ResourceGroups (ResourceGroup (..))
| aznashwan/haskzure | Cloud/Haskzure/Resources.hs | apache-2.0 | 171 | 0 | 6 | 31 | 30 | 21 | 9 | 3 | 0 |
module Examples.NextHop
( nhExamples
) where
import Utils
import LaTeX
import Algebra.Matrix
import Algebra.Semiring
import PathInformations.NextHop
nhExamples :: Int -> Matrix NextHop
nhExamples 0 = M (toArray 5 [ zero, A 1 2, zero, zero, zero
, zero, zero, zero, zero, zero
, zero, A 3 2, zero, A 3 4, zero
, A 4 1, zero, zero, zero, A 4 5
, A 5 1, zero, A 5 3, zero, zero])
nhExamples _ = error "Undefined example of NextHop"
| sdynerow/Semirings-Library | haskell/Examples/NextHop.hs | apache-2.0 | 552 | 0 | 9 | 203 | 184 | 104 | 80 | 14 | 1 |
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Data.Authenticated.Fix (FixAuth(..)) where
import Data.Authenticated
newtype FixAuth f a = FixAuth { unFixAuth :: f (Auth (FixAuth f a) a) }
instance (Show (f (Auth (FixAuth f a) a))) => Show (FixAuth f a) where
showsPrec n (FixAuth f) = showsPrec n f
instance (Digest (FixAuth f Prover) ~ Digest (FixAuth f Verifier), Functor f) => MapAuth (FixAuth f) where
mapAuth (FixAuth f) = FixAuth (fmap shallowAuth f)
-- Requires UndecidableInstances
instance (Authenticated a, Digestible (f (Auth (FixAuth f a) a))) => Digestible (FixAuth f a) where
type Digest (FixAuth f a) = Digest (f (Auth (FixAuth f a) a))
digest (FixAuth f) = digest f
| derekelkins/ads | Data/Authenticated/Fix.hs | bsd-2-clause | 730 | 0 | 12 | 135 | 316 | 165 | 151 | -1 | -1 |
{- |
Module : Data.Graph.Analysis.Algorithms.Clustering
Description : Clustering and grouping algorithms.
Copyright : (c) Ivan Lazar Miljenovic 2009
License : 2-Clause BSD
Maintainer : Ivan.Miljenovic@gmail.com
Clustering and grouping algorithms that are graph-invariant and require
no user intervention.
For a clustering algorithm that works only on directed graphs, see
@levelGraph@ in "Data.Graph.Analysis.Algorithms.Directed".
-}
module Data.Graph.Analysis.Algorithms.Clustering
( -- * Clustering Algorithms
-- ** Non-deterministic algorithms
-- $chinesewhispers
chineseWhispers,
-- ** Spatial Algorithms
-- $relneighbours
relativeNeighbourhood,
-- * Graph Collapsing
-- $collapsing
CNodes,
collapseGraph,
collapseGraphBy,
collapseAndReplace,
collapseAndReplace',
trivialCollapse,
) where
import Data.Graph.Analysis.Internal
import Data.Graph.Analysis.Types
import Data.Graph.Analysis.Utils
import Data.Graph.Analysis.Algorithms.Common
import Data.Graph.Inductive.Graph
import Data.List(foldl', tails, delete, intersect)
import Data.Function(on)
import Data.Maybe(fromJust)
import qualified Data.Set.BKTree as BK
import Data.Set.BKTree(BKTree, Metric(..))
import Control.Arrow(first, second, (***))
import System.Random(RandomGen, randomR)
-- -----------------------------------------------------------------------------
{- $chinesewhispers
The Chinese Whispers Algorithm.
This is an adaptation of the algorithm described in:
Biemann, C. (2006): Chinese Whispers - an Efficient Graph Clustering
Algorithm and its Application to Natural Language Processing Problems.
Proceedings of the HLT-NAACL-06 Workshops on Textgraphs-06, New York, USA
<http://wortschatz.uni-leipzig.de/~cbiemann/pub/2006/BiemannTextGraph06.pdf>
The adaptations to this algorithm are as follows:
* Ignore any edge weightings that may exist, as we can't depend on them
(also, we want the algorithm to be dependent solely upon the
/structure/ of the graph, not what it contains).
* Explicitly shuffle the node order for each iteration.
Simplistically, the way it works is this:
1. Every node is assigned into its own unique cluster.
2. Sort the nodes into some random order. Each node joins the
most popular cluster in its neighbourhood (where popularity
is defined as the sum of the node weightings in that cluster).
3. Repeat step 2. until a fixed point is reached.
Note that this algorithm is non-deterministic, and that for some graphs
no fixed point may be reached (and the algorithm may oscillate between
a few different graph clusterings).
Chinese Whispers is @O(number of edges)@.
-}
-- | The actual Chinese Whispers algorithm.
chineseWhispers :: (RandomGen g, Eq a, Eq b, DynGraph gr) => g -> gr a b
-> gr (GenCluster a) b
chineseWhispers g gr = reCluster . fst $ fixPointBy eq whispering (gr',g)
where
eq = equal `on` fst
ns = nodes gr
whispering (gr'',g') = foldl' whisperNode (gr'',g'') ns'
where
-- Shuffle the nodes to ensure the order of choosing a new
-- cluster is random.
(ns',g'') = shuffle g' ns
gr' = addWhispers gr
-- | Choose a new cluster for the given 'Node'. Note that this updates
-- the graph each time a new cluster value is chosen.
whisperNode :: (RandomGen g, DynGraph gr) => (gr (GenCluster a) b,g)
-> Node -> (gr (GenCluster a) b,g)
whisperNode (gr,g) n = (c' & gr',g')
where
(Just c,gr') = match n gr
(g',c') = whisper gr g c
-- | Choose a new cluster for the given @Context@.
whisper :: (RandomGen g, Graph gr) => gr (GenCluster a) b -> g
-> Context (GenCluster a) b -> (g,Context (GenCluster a) b)
whisper gr g (p,n,al,s) = (g',(p,n,al { clust = w' },s))
where
(w',g') = case (neighbors gr n) of
[] -> (clust al,g)
-- Add this current node to the list of neighbours to add
-- extra weighting, as it seems to give better results.
ns -> chooseWhisper g (addLabels gr (n:ns))
-- | Choose which cluster to pick by taking the one with maximum number of
-- nodes. If more than one has the same maximum, choose one
-- randomly.
chooseWhisper :: (RandomGen g) => g -> [LNode (GenCluster a)]
-> (Int,g)
chooseWhisper g lns = pick maxWsps
where
-- This isn't the most efficient method of choosing a random list element,
-- but the graph is assumed to be relatively sparse and thus ns should
-- be relatively short.
pick ns = first (ns!!) $ randomR (0,length ns - 1) g
whisps = map (second length) . groupElems clust $ map label lns
maxWsps = map fst . snd . head $ groupElems (negate . snd) whisps
-- | Convert the graph into a form suitable for the Chinese Whispers algorithm.
addWhispers :: (DynGraph gr) => gr a b -> gr (GenCluster a) b
addWhispers g = gmap augment g
where
augment (p,n,l,s) = (p,n, GC { clust = n, nLbl = l }, s)
{-
Originally used for the clustering coefficient, didn't seem to give good
results.
http://en.wikipedia.org/wiki/Clustering_coefficient
clusteringCoef :: (Graph gr) => gr a b -> Node -> Double
clusteringCoef g n = if (liftM2 (||) isNaN isInfinite $ coef)
then 0
else coef
where
d = fromIntegral $ deg g n
coef = (fromIntegral nes) / (k*(k - 1))
ns = (neighbors g n)
k = fromIntegral $ length ns
nes = length $ concatMap (union ns . neighbors g) ns
-}
-- -----------------------------------------------------------------------------
{- $relneighbours
This implements the algorithm called CLUSTER, from the paper:
Bandyopadhyay, S. (2003): An automatic shape independent clustering
technique. Pattern Recognition, vol. 37, pp. 33-45.
Simplistically, it defines clusters as groups of nodes that are
spatially located closer to each other than to nodes in
other clusters. It utilises the concept of a /Relative
Neighbour Graph/ [RNG] to determine the spatial structure of a set
of two-dimensional data points.
The adaptations to this algorithm are as follows:
* Due to the limitations of the BKTree data structure, we utilise a
/fuzzy/ distance function defined as the ceiling of the standard
Euclidian distance.
* We utilise 'toPosGraph' to get the spatial locations. As such,
these locations may not be optimal, especially for smaller
graphs.
* The actual algorithm is applied to each connected component of
the graph. The actual paper is unclear what to do in this
scenario, but Graphviz may locate nodes from separate
components together, despite them not being related.
The algorithm is renamed 'relativeNeighbourhood'. Experimentally, it
seems to work better with larger graphs (i.e. more nodes), since
then Graphviz makes the apparent clusters more obvious. The actual
algorithm is @O(n^2)@, where /n/ is the number of 'Node's in the graph.
-}
-- | The renamed CLUSTER algorithm. Attempts to cluster a graph by using
-- the spatial locations used by Graphviz.
relativeNeighbourhood :: (DynGraph gr, Eq a, Ord b) => Bool -> gr a b
-> gr (GenCluster a) b
relativeNeighbourhood dir g = setCluster cMap g
where
cMap = createLookup $ rn g
rn g' = nbrCluster rng
where
rng :: AGr () Int
rng = makeRNG $ getPositions dir g'
-- | We take the ceiling of the Euclidian distance function to use as our
-- metric function.
instance (Eq a) => Metric (PosLabel a) where
distance = (ceiling . ) . euclidian
-- Note that this throws an orphan instance warning.
-- | The Euclidian distance function.
euclidian :: PosLabel a -> PosLabel a -> Double
euclidian n1 n2 = sqrt . fI $ posBy xPos + posBy yPos
where
posBy p = sq $ p n1 - p n2
-- | Converts the positional labels into an RNG.
makeRNG :: (Eq a, Graph gr) => [PosLabel a] -> gr () Int
makeRNG ls = mkGraph ns es
where
ns = map (\l -> (pnode l,())) ls
tree = BK.fromList ls
tls = tails ls
es = [ (pnode l1,pnode l2,distance l1 l2)
| (l1:ls') <- tls
, l2 <- ls'
, areRelative tree l1 l2 ]
-- | Determines if the two given nodes should be connected in the RNG.
-- Nodes are connected if there is no node that is closer to both of them.
areRelative :: (Metric a) => BKTree a -> a -> a -> Bool
areRelative t l1 l2 = null lune
where
d = distance l1 l2
-- Find all nodes distance <= d away from the given node.
-- Note that n is distance 0 <= d away from n, so we need to
-- remove it from the list of results.
rgnFor l = delete l $ BK.elemsDistance d l t
-- The nodes that are between the two given nodes.
lune = intersect (rgnFor l1) (rgnFor l2)
-- | Performs the actual clustering algorithm on the RNG.
nbrCluster :: (DynGraph gr) => gr a Int -> [NGroup]
nbrCluster g
| numNodes == 1 = [ns] -- Can't split up a single node.
| eMax < 2*eMin = [ns] -- The inter-cluster relative neighbours
-- are too close too each other.
| null thrs = [ns] -- No threshold value available.
| single cg' = [ns] -- No edges meet the threshold deletion
-- criteria.
| nCgs > sNum = [ns] -- Over-fragmentation of the graph.
| otherwise = concatMap nbrCluster cg'
where
ns = nodes g
numNodes = noNodes g
sNum = floor (sqrt $ fI numNodes :: Double)
les = labEdges g
(es,eMin,eMax) = sortMinMax $ map eLabel les
es' = zip es (tail es)
sub = uncurry subtract
-- First order differences.
-- We don't care about the list, just what the min and max diffs are.
(_,dfMin,dfMax) = sortMinMax $ map sub es'
-- We are going to do >= tests on t, but using Int values, so
-- take the ceiling.
t = ceiling ((fI dfMin + fI dfMax)/2 :: Double)
-- Edges that meet the threshold criteria.
thrs = filter (\ejs@(ej,_) -> (ej >= 2*eMin) && (sub ejs >= t)) es'
-- Take the first edges that meets the threshold criteria.
thresh = fst $ head thrs
-- Edges that meet the threshold deletion criteria.
rEs = map edge $ filter ((>= thresh) . eLabel) les
g' = delEdges rEs g
-- Each of these will also be an RNG
cg' = componentsOf g'
nCgs = length cg'
-- -----------------------------------------------------------------------------
{- $collapsing
Collapse the parts of a graph down to try and show a compressed
overview of the whole graph.
It may be possible to extend this to a clustering algorithm by
collapsing low density regions into high density regions.
If providing custom collapsing functions, you should ensure that
for each function, it is not possible to have a recursive situation
where a collapsed node keeps getting collapsed to itself.
-}
-- | A collapsed node contains a list of nodes that it represents.
type CNodes a = [a]
-- | Collapse the cliques, cycles and chains in the graph down. Note
-- that this doesn't work too well on undirected graphs, since every
-- pair of nodes forms a K_2 subgraph.
collapseGraph :: (DynGraph gr, Eq b) => gr a b -> gr (CNodes a) b
collapseGraph = collapseGraphBy interestingParts
where
interestingParts = [cliquesIn', cyclesIn', chainsIn']
-- | Use the given functions to determine which nodes to collapse.
collapseGraphBy :: (DynGraph gr) => [gr (CNodes a) b -> [NGroup]]
-> gr a b -> gr (CNodes a) b
collapseGraphBy fs = fst . collapseGr fs'
where
fs' = map (map (flip (,) Nothing) .) fs
-- | Use the given functions to determine which nodes to collapse,
-- with a new label to represent the collapsed nodes.
collapseAndReplace :: (DynGraph gr) => [gr a b -> [(NGroup, a)]]
-> gr a b -> gr a b
collapseAndReplace fs = fst . collapseAndReplace' fs
-- | As with 'collapseAndReplace', but also return the
-- @('NGroup', a)@'s calculated with the functions provided.
collapseAndReplace' :: (DynGraph gr) => [gr a b -> [(NGroup, a)]]
-> gr a b -> (gr a b, [(NGroup, a)])
collapseAndReplace' fs = (unCollapse *** strip) . collapseGr fs'
where
-- convert gr a b -> [(NGroup, a)] to
-- gr (CNodes a) b -> [(NGroup, Maybe a)]
fs' = map ((. nmap head) . (map (second Just) .)) fs
-- Strip the Maybes
strip = map (second fromJust)
-- | Collapse the graph.
collapseGr :: (DynGraph gr) => [gr (CNodes a) b -> [(NGroup, Maybe a)]]
-> gr a b -> (gr (CNodes a) b, [(NGroup, Maybe a)])
collapseGr fs g = foldl' collapseAllBy (makeCollapsible g, []) fs
-- | Return @'True'@ if the collapsed graph is either a singleton node
-- or else isomorphic to the original graph (i.e. not collapsed at all).
trivialCollapse :: (Graph gr) => gr (CNodes a) b -> Bool
trivialCollapse cg = allCollapsed || notCollapsed
where
allCollapsed = single lns || null lns
notCollapsed = all single lns
lns = labels cg
-- | Allow the graph to be collapsed.
makeCollapsible :: (DynGraph gr) => gr a b -> gr (CNodes a) b
makeCollapsible = nmap return
unCollapse :: (DynGraph gr) => gr (CNodes a) b -> gr a b
unCollapse = nmap head
-- | Collapse the two given nodes into one node.
collapse :: (DynGraph gr) => gr (CNodes a) b -> Node -> Node
-> gr (CNodes a) b
collapse g n1 n2 = if n1 == n2
then g
else c' & g''
where
(Just c1, g') = match n1 g
(Just c2, g'') = match n2 g'
-- The new edges.
nbrBy f = map swap
. filter (\(n,_) -> notElem n [n1,n2])
$ (f c1 ++ f c2)
p = nbrBy lpre'
s = nbrBy lsuc'
l1 = lab' c1
l2 = lab' c2
c' = (p,n1,l1++l2,s)
-- | Collapse the list of nodes down to one node.
collapseAll :: (DynGraph gr) => (NGroup, Maybe a)
-> gr (CNodes a) b
-> gr (CNodes a) b
collapseAll ([],_) g = g -- This case shouldn't occur
collapseAll ([n],ma) g = maybeAdjustLabel n ma g
collapseAll ((n:ns),ma) g = foldl' collapser g' ns
where
g' = maybeAdjustLabel n ma g
collapser = flip collapse n
maybeAdjustLabel :: (DynGraph gr) => Node -> Maybe a -> gr (CNodes a) b
-> gr (CNodes a) b
maybeAdjustLabel n = maybe id (adjustLabel n)
-- | Replace the label of the provided node with @[a]@.
adjustLabel :: (DynGraph gr) => Node -> a
-> gr (CNodes a) b -> gr (CNodes a) b
adjustLabel n a g = c & g'
where
(Just (p,_,_,s), g') = match n g
c = (p,n,[a],s)
-- | Collapse all results of the given function.
collapseAllBy :: (DynGraph gr) => (gr (CNodes a) b, [(NGroup, Maybe a)])
-> (gr (CNodes a) b -> [(NGroup, Maybe a)])
-> (gr (CNodes a) b, [(NGroup, Maybe a)])
collapseAllBy g f = case (filter (not . null . fst) $ f (fst g)) of
[] -> g
-- We re-evaluate the function in case
-- the original results used nodes that
-- have been collapsed down.
(nsr:_) -> second (nsr :)
$ collapseAllBy (first (collapseAll nsr) g) f
| ivan-m/Graphalyze | Data/Graph/Analysis/Algorithms/Clustering.hs | bsd-2-clause | 15,781 | 0 | 14 | 4,429 | 3,304 | 1,784 | 1,520 | 165 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Err
-- Copyright : (c) The University of Glasgow, 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- The "GHC.Err" module defines the code for the wired-in error functions,
-- which have a special type in the compiler (with \"open tyvars\").
--
-- We cannot define these functions in a module where they might be used
-- (e.g., "GHC.Base"), because the magical wired-in type will get confused
-- with what the typechecker figures out.
--
-----------------------------------------------------------------------------
module GHC.Err( absentErr, error, undefined ) where
import GHC.CString ()
import GHC.IO (unsafeDupablePerformIO)
import GHC.Types
import GHC.Prim
import GHC.Integer () -- Make sure Integer is compiled first
-- because GHC depends on it in a wired-in way
-- so the build system doesn't see the dependency
import {-# SOURCE #-} GHC.Exception( errorCallException )
import {-# SOURCE #-} GHC.Stack (ccsToStrings, getCurrentCCS, renderStack)
-- | 'error' stops execution and displays an error message.
error :: [Char] -> a
error s = unsafeDupablePerformIO $ do
stack <- ccsToStrings =<< getCurrentCCS s
raise# (errorCallException s stack)
-- | A special case of 'error'.
-- It is expected that compilers will recognize this and insert error
-- messages which are more appropriate to the context in which 'undefined'
-- appears.
undefined :: a
undefined = error "Prelude.undefined"
-- | Used for compiler-generated error message;
-- encoding saves bytes of string junk.
absentErr :: a
absentErr = error "Oops! The program has entered an `absent' argument!\n"
| bitemyapp/ghc | libraries/base/GHC/Err.hs | bsd-3-clause | 1,969 | 0 | 10 | 351 | 190 | 121 | 69 | 19 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
-- | Assign codes and inner layer to each word according to Huffman coding
module Huffman(Code,
Bin(..),
Coding(..),
huffmanEncode,
asNum) where
import Data.HashMap.Strict(empty,
insert,
HashMap,
toList,
fromList)
import qualified Data.Heap as H
import Data.Maybe(fromJust)
data Bin = Zero | One deriving (Eq, Ord, Show, Read)
type Code = [Bin]
asNum :: (Num a ) => Bin -> a
asNum Zero = 0
asNum One = 1
instance Enum Code where
toEnum n = case n `mod` 2 of
0 -> Zero : toEnum' (n `div` 2)
1 -> One : toEnum' (n `div` 2)
where
toEnum' 0 = []
toEnum' n = toEnum n
fromEnum [] = 0
fromEnum (Zero:b) = 2 * fromEnum b
fromEnum (One:b) = 2 * fromEnum b + 1
data Coding = Coding {
-- Index of word in corpus
index :: Int,
-- Frequency of word in corpus
frequency :: Int,
-- Huffman encoding of a word, LSB first
huffman :: Code,
-- List of indices of path from root to word in encoding
-- The indices are built in sucha way that most frequent words have smaller indices
wordPoints :: [Int]
} deriving (Eq, Show, Read)
huffmanEncode :: HashMap String Int -> HashMap String Coding
huffmanEncode = encode . arborify . heapify
instance Ord Coding where
compare (Coding _ f _ _ ) (Coding _ f' _ _ ) = compare f f'
buildWord :: ([Huffman],Int) -> (String, Int) -> ([Huffman],Int)
buildWord (ws, n) (w,f) = ((Leaf w (Coding n f [] [])):ws, n+1)
-- |Returns the list of words stored in given heap in ascending order.
ascWords :: H.MinHeap Huffman -> [ String ]
ascWords = map unWord . H.toAscList
where
unWord (Leaf w _) = w
-- |Build a heap from hashmap of words frequencies.
--
-- The heap is built with the frequency as ordering factor. Each word is built into a `Word`
-- object that contains the frequency, the index of the word relative to size of vocabulary.
--
-- >>> ascWords $ heapify (fromList [("foo",3), ("bar",2)])
-- ["bar","foo"]
heapify :: HashMap String Int -> H.MinHeap Huffman
heapify = foldl (flip H.insert) H.empty . fst . foldl buildWord ([],0) . toList
data Huffman = Node Huffman Huffman Coding
| Leaf String Coding
deriving (Eq,Show)
freq :: Huffman -> Int
freq (Node _ _ (Coding _ f _ _)) = f
freq (Leaf _ (Coding _ f _ _)) = f
instance Ord Huffman where
compare (Node _ _ c) (Node _ _ c') = compare c c'
compare (Node _ _ c) (Leaf _ c') = compare c c'
compare (Leaf _ c) (Node _ _ c') = compare c c'
compare (Leaf _ c) (Leaf _ c') = compare c c'
-- | Build a tree from heap with only words
--
arborify :: H.MinHeap Huffman -> H.MinHeap Huffman
arborify h = foldl buildTree h [0.. sizeOfVocabulary -1]
where
sizeOfVocabulary = H.size h
buildTree h n = let (min1,h1) = fromJust $ H.view h
in case H.view h1 of
Just (min2,h2) -> H.insert (Node min1 min2
(Coding n
(freq min1 + freq min2)
[]
[])) h2
Nothing -> h
encode :: H.MinHeap Huffman -> HashMap String Coding
encode h = encode' (fst $ fromJust $ H.view h) [] [] empty
where
encode' (Leaf w c) code points map = insert w c { huffman = code, wordPoints = points } map
encode' (Node left right c) code points map = let pts = index c : points
m1 = encode' left (Zero:code) pts map
in
encode' right (One:code) pts m1
-- # Tests
-- | test Enum implementation
--
-- >>> toEnum 0 :: Code
-- [Zero]
-- >>> toEnum 1 :: Code
-- [One]
-- >>> toEnum 2 :: Code
-- [Zero,One]
testToEnum :: Int -> Code
testToEnum = toEnum
-- | test Enum implementation
--
-- >>> fromEnum [Zero]
-- 0
-- >>> fromEnum [One]
-- 1
-- >>> fromEnum [Zero,One]
-- 2
-- >>> fromEnum [Zero,One,Zero,One]
-- 10
testFromEnum :: Code -> Int
testFromEnum = fromEnum
| RayRacine/hs-word2vec | Huffman.hs | bsd-3-clause | 4,434 | 0 | 19 | 1,552 | 1,284 | 692 | 592 | 77 | 2 |
module Data.Array.Accelerate.BLAS.Internal.Nrm2 where
import Data.Array.Accelerate.BLAS.Internal.Common
import Data.Array.Accelerate
import Data.Array.Accelerate.CUDA.Foreign
import qualified Foreign.CUDA.BLAS as BL
import Prelude hiding (zipWith, map)
cudaNrm2F :: Vector Float -> CIO (Scalar Float)
cudaNrm2F x = do
let n = arraySize (arrayShape x)
res <- allocScalar
xptr <- devVF x
resptr <- devSF res
liftIO $ BL.withCublas $ \handle -> execute handle n xptr resptr
return res
where
execute h n xp rp =
BL.snrm2 h n xp 1 rp
cudaNrm2D :: Vector Double -> CIO (Scalar Double)
cudaNrm2D x = do
let n = arraySize (arrayShape x)
res <- allocScalar
xptr <- devVD x
resptr <- devSD res
liftIO $ BL.withCublas $ \handle -> execute handle n xptr resptr
return res
where
execute h n xp rp =
BL.dnrm2 h n xp 1 rp
-- | Returns the 2-norm of the given vector of `Float`s.
-- Equivalent to:
--
-- >>> sqrt . sum . map (\x -> x * x)
snrm2 :: Acc (Vector Float) -> Acc (Scalar Float)
snrm2 = foreignAcc foreignNrm2F pureNrm2F
where foreignNrm2F = CUDAForeignAcc "cudaNrm2F" cudaNrm2F
pureNrm2F :: Acc (Vector Float) -> Acc (Scalar Float)
pureNrm2F = map sqrt . fold (+) 0 . map (\x -> x*x)
-- | Returns the 2-norm of the given vector of `Double`s.
-- Equivalent to:
--
-- >>> sqrt . sum . map (\x -> x * x)
dnrm2 :: Acc (Vector Double) -> Acc (Scalar Double)
dnrm2 = foreignAcc foreignNrm2D pureNrm2D
where foreignNrm2D = CUDAForeignAcc "cudaNrm2D" cudaNrm2D
pureNrm2D :: Acc (Vector Double) -> Acc (Scalar Double)
pureNrm2D = map sqrt . fold (+) 0 . map (\x -> x*x)
| alpmestan/accelerate-blas | src/Data/Array/Accelerate/BLAS/Internal/Nrm2.hs | bsd-3-clause | 1,742 | 0 | 12 | 453 | 562 | 286 | 276 | 36 | 1 |
{-# LANGUAGE OverloadedStrings, PackageImports #-}
import Control.Applicative
import Control.Arrow
import Control.Monad
import "monads-tf" Control.Monad.Trans
import Data.Maybe
import Data.Pipe
import Data.HandleLike
import Text.XML.Pipe
import Network
import Network.PeyoTLS.Client
import Network.PeyoTLS.ReadFile
import "crypto-random" Crypto.Random
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Base64 as B64
import Papillon
import Digest
import Caps (profanityCaps, capsToXml, capsToQuery)
import System.IO.Unsafe
import System.Environment
sender, recipient :: BS.ByteString
-- sender = "yoshikuni"
-- recipient = "yoshio"
[sender, recipient] = map BSC.pack $ unsafePerformIO getArgs
main :: IO ()
main = do
h <- connectTo "localhost" (PortNumber 54492)
BS.hPut h $ xmlString begin
BS.hPut h $ xmlString startTls
void . runPipe $ handleP h
=$= xmlEvent
=$= convert fromJust
=$= (xmlBegin >>= xmlNodeUntil isProceed)
=$= printP h
ca <- readCertificateStore ["cacert.sample_pem"]
g <- cprgCreate <$> createEntropyPool :: IO SystemRNG
(`run` g) $ do
p <- open' h "localhost" ["TLS_RSA_WITH_AES_128_CBC_SHA"] [] ca
xmpp p
startTls :: [XmlNode]
startTls = [
XmlNode (("", Nothing), "starttls")
[("", "urn:ietf:params:xml:ns:xmpp-tls")] [] [] ]
isProceed :: XmlNode -> Bool
isProceed (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-tls"), "proceed") _ [] [])
= True
isProceed _ = False
xmpp :: HandleLike h => h -> HandleMonad h ()
xmpp h = do
hlPut h $ xmlString begin
hlPut h $ xmlString selectDigestMd5
voidM . runPipe $ handleP h
=$= xmlEvent
=$= convert fromJust
-- =$= (xmlBegin >>= xmlNode)
=$= xmlPipe
=$= convert showResponse
=$= processResponse h
=$= printP h
voidM :: Monad m => m a -> m ()
voidM m = m >> return ()
xmlPipe :: Monad m => Pipe XmlEvent XmlNode m ()
xmlPipe = do
c <- xmlBegin >>= xmlNode
when c $ xmlPipe
data ShowResponse
= SRStream [(Tag, BS.ByteString)]
| SRFeatures [Feature]
| SRChallenge {
realm :: BS.ByteString,
nonce :: BS.ByteString,
qop :: BS.ByteString,
charset :: BS.ByteString,
algorithm :: BS.ByteString }
| SRChallengeRspauth BS.ByteString
| SRSaslSuccess
| SRIq [(IqTag, BS.ByteString)] IqBody
| SRPresence [(Tag, BS.ByteString)] Caps
| SRMessage [(IqTag, BS.ByteString)] MessageBody MessageDelay MessageXDelay
| SRRaw XmlNode
deriving Show
data MessageBody
= MessageBody BS.ByteString
| MBRaw XmlNode
deriving Show
data MessageDelay
= MessageDelay [(DelayTag, BS.ByteString)]
| MDRaw XmlNode
deriving Show
data DelayTag = DTFrom | DTStamp | DlyTRaw QName deriving Show
data MessageXDelay
= MessageXDelay [(XDelayTag, BS.ByteString)]
| MXDRaw XmlNode
deriving Show
data XDelayTag = XDTFrom | XDTStamp | XDlyTRaw QName deriving Show
toXDelay :: XmlNode -> MessageXDelay
toXDelay (XmlNode ((_, Just "jabber:x:delay"), "x") _ as []) =
MessageXDelay $ map (first toXDelayTag) as
toXDelay n = MXDRaw n
toXDelayTag :: QName -> XDelayTag
toXDelayTag ((_, Just "jabber:x:delay"), "from") = XDTFrom
toXDelayTag ((_, Just "jabber:x:delay"), "stamp") = XDTStamp
toXDelayTag n = XDlyTRaw n
toDelayTag :: QName -> DelayTag
toDelayTag ((_, Just "urn:xmpp:delay"), "from") = DTFrom
toDelayTag ((_, Just "urn:xmpp:delay"), "stamp") = DTStamp
toDelayTag n = DlyTRaw n
toBody :: XmlNode -> MessageBody
toBody (XmlNode ((_, Just "jabber:client"), "body") _ [] [XmlCharData b]) =
MessageBody b
toBody n = MBRaw n
toDelay :: XmlNode -> MessageDelay
toDelay (XmlNode ((_, Just "urn:xmpp:delay"), "delay") _ as []) = MessageDelay $
map (first toDelayTag) as
toDelay n = MDRaw n
data Feature
= Mechanisms [Mechanism]
| Caps {ctHash :: BS.ByteString,
ctNode :: BS.ByteString,
ctVer :: BS.ByteString } -- [(CapsTag, BS.ByteString)]
| Rosterver Requirement
| Bind Requirement
| Session Requirement
| FeatureRaw XmlNode
deriving (Eq, Show)
toFeature :: XmlNode -> Feature
toFeature (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "mechanisms")
_ [] ns) = Mechanisms $ map toMechanism ns
toFeature (XmlNode ((_, Just "http://jabber.org/protocol/caps"), "c") _ as []) =
let h = map (first toCapsTag) as in Caps {
ctHash = fromJust $ lookup CTHash h,
ctNode = fromJust $ lookup CTNode h,
ctVer = (\(Right r) -> r) . B64.decode . fromJust $ lookup CTVer h }
-- Caps $ map (first toCapsTag) as
toFeature (XmlNode ((_, Just "urn:xmpp:features:rosterver"), "ver") _ [] r) =
Rosterver $ toRequirement r
toFeature (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-bind"), "bind") _ [] r) =
Bind $ toRequirement r
toFeature (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-session"), "session")
_ [] r) = Session $ toRequirement r
toFeature n = FeatureRaw n
data Requirement = Optional | Required | NoRequirement [XmlNode]
deriving (Eq, Show)
toRequirement :: [XmlNode] -> Requirement
toRequirement [XmlNode (_, "optional") _ [] []] = Optional
toRequirement [XmlNode (_, "required") _ [] []] = Required
toRequirement n = NoRequirement n
data Mechanism = ScramSha1 | DigestMd5 | MechanismRaw XmlNode deriving (Eq, Show)
toMechanism :: XmlNode -> Mechanism
toMechanism (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "mechanism")
_ [] [XmlCharData "SCRAM-SHA-1"]) = ScramSha1
toMechanism (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "mechanism")
_ [] [XmlCharData "DIGEST-MD5"]) = DigestMd5
toMechanism n = MechanismRaw n
data Tag = Id | From | Version | Lang | TagRaw QName deriving (Eq, Show)
qnameToTag :: QName -> Tag
qnameToTag ((_, Just "jabber:client"), "id") = Id
qnameToTag ((_, Just "jabber:client"), "from") = From
qnameToTag ((_, Just "jabber:client"), "version") = Version
qnameToTag (("xml", Nothing), "lang") = Lang
qnameToTag n = TagRaw n
data CapsTag = CTHash | CTNode | CTVer | CTRaw QName deriving (Eq, Show)
toCapsTag :: QName -> CapsTag
toCapsTag ((_, Just "http://jabber.org/protocol/caps"), "hash") = CTHash
toCapsTag ((_, Just "http://jabber.org/protocol/caps"), "ver") = CTVer
toCapsTag ((_, Just "http://jabber.org/protocol/caps"), "node") = CTNode
toCapsTag n = CTRaw n
data IqTag = IqId | IqType | IqTo | IqFrom | IqRaw QName deriving (Eq, Show)
toIqTag :: QName -> IqTag
toIqTag ((_, Just "jabber:client"), "id") = IqId
toIqTag ((_, Just "jabber:client"), "type") = IqType
toIqTag ((_, Just "jabber:client"), "to") = IqTo
toIqTag ((_, Just "jabber:client"), "from") = IqFrom
toIqTag n = IqRaw n
data DiscoTag = DTNode | DTRaw QName deriving (Eq, Show)
toDiscoTag :: QName -> DiscoTag
toDiscoTag ((_, Just "http://jabber.org/protocol/disco#info"), "node") = DTNode
toDiscoTag n = DTRaw n
data IqBody
= IqBind Bind
| IqRoster [(RosterTag, BS.ByteString)] -- QueryRoster
| IqDiscoInfo
| IqDiscoInfoNode [(DiscoTag, BS.ByteString)]
| IqDiscoInfoFull [(DiscoTag, BS.ByteString)] Identity [InfoFeature]
| IqBodyNull
| IqBodyRaw [XmlNode]
deriving Show
toIqBody :: [XmlNode] -> IqBody
toIqBody [XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-bind"), "bind") _ [] ns] =
IqBind $ toBind ns
toIqBody [XmlNode ((_, Just "jabber:iq:roster"), "query") _ as []] =
IqRoster $ map (first toRosterTag) as
toIqBody [XmlNode ((_, Just "http://jabber.org/protocol/disco#info"), "query")
_ [] []] = IqDiscoInfo
toIqBody [XmlNode ((_, Just "http://jabber.org/protocol/disco#info"), "query")
_ as []] = IqDiscoInfoNode $ map (first toDiscoTag) as
toIqBody [XmlNode ((_, Just "http://jabber.org/protocol/disco#info"), "query")
_ as (i : ns)] = IqDiscoInfoFull
(map (first toDiscoTag) as)
(toIdentity i)
(map toInfoFeature ns)
toIqBody [] = IqBodyNull
toIqBody ns = IqBodyRaw ns
data Identity
= Identity [(IdentityTag, BS.ByteString)]
| IdentityRaw XmlNode
deriving Show
data IdentityTag
= IDTType | IDTName | IDTCategory | IDTRaw QName deriving (Eq, Show)
toIdentityTag :: QName -> IdentityTag
toIdentityTag ((_, Just "http://jabber.org/protocol/disco#info"), "type") = IDTType
toIdentityTag ((_, Just "http://jabber.org/protocol/disco#info"), "name") = IDTName
toIdentityTag ((_, Just "http://jabber.org/protocol/disco#info"), "category") =
IDTCategory
toIdentityTag n = IDTRaw n
toIdentity :: XmlNode -> Identity
toIdentity (XmlNode ((_, Just "http://jabber.org/protocol/disco#info"), "identity")
_ as []) = Identity $ map (first toIdentityTag) as
toIdentity n = IdentityRaw n
data InfoFeature
= InfoFeature BS.ByteString
| InfoFeatureSemiRaw [(InfoFeatureTag, BS.ByteString)]
| InfoFeatureRaw XmlNode
deriving Show
data InfoFeatureTag
= IFTVar
| IFTVarRaw QName
deriving (Eq, Show)
toInfoFeatureTag :: QName -> InfoFeatureTag
toInfoFeatureTag ((_, Just "http://jabber.org/protocol/disco#info"), "var") = IFTVar
toInfoFeatureTag n = IFTVarRaw n
toInfoFeature :: XmlNode -> InfoFeature
toInfoFeature (XmlNode ((_, Just "http://jabber.org/protocol/disco#info"),
"feature") _ as []) = case map (first toInfoFeatureTag) as of
[(IFTVar, v)] -> InfoFeature v
atts -> InfoFeatureSemiRaw atts
toInfoFeature n = InfoFeatureRaw n
data Bind
= Jid BS.ByteString
| BindRaw [XmlNode]
deriving Show
data RosterTag = RTVer | RTRaw QName deriving (Eq, Show)
toRosterTag :: QName -> RosterTag
toRosterTag ((_, Just "jabber:iq:roster"), "ver") = RTVer
toRosterTag n = RTRaw n
toBind :: [XmlNode] -> Bind
toBind [XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-bind"), "jid") _ []
[XmlCharData cd]] = Jid cd
toBind ns = BindRaw ns
data Caps
= C [(CapsTag, BS.ByteString)]
| CapsRaw [XmlNode]
deriving Show
toCaps :: [XmlNode] -> Caps
toCaps [XmlNode ((_, Just "http://jabber.org/protocol/caps"), "c") _ as []] =
C $ map (first toCapsTag) as
toCaps ns = CapsRaw ns
showResponse :: XmlNode -> ShowResponse
showResponse (XmlStart ((_, Just "http://etherx.jabber.org/streams"), "stream")
_ atts) = SRStream $ map (first qnameToTag) atts
showResponse (XmlNode ((_, Just "http://etherx.jabber.org/streams"), "features")
_ [] nds) = SRFeatures $ map toFeature nds
showResponse (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "challenge")
_ [] [XmlCharData c]) = let
Right d = B64.decode c
Just a = parseAtts d in
case a of
[("rspauth", ra)] -> SRChallengeRspauth ra
_ -> SRChallenge {
realm = fromJust $ lookup "realm" a,
nonce = fromJust $ lookup "nonce" a,
qop = fromJust $ lookup "qop" a,
charset = fromJust $ lookup "charset" a,
algorithm = fromJust $ lookup "algorithm" a }
showResponse (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "success")
_ [] []) = SRSaslSuccess
showResponse (XmlNode ((_, Just "jabber:client"), "iq") _ as ns) =
SRIq (map (first toIqTag) as) $ toIqBody ns
showResponse (XmlNode ((_, Just "jabber:client"), "presence") _ as ns) =
SRPresence (map (first qnameToTag) as) $ toCaps ns
showResponse (XmlNode ((_, Just "jabber:client"), "message") _ as
(b : d : xd : [])) = SRMessage
(map (first toIqTag) as)
(toBody b)
(toDelay d)
(toXDelay xd)
showResponse n = SRRaw n
-- processResponse :: Handle -> Pipe ShowResponse ShowResponse IO ()
processResponse :: HandleLike h =>
h -> Pipe ShowResponse ShowResponse (HandleMonad h) ()
processResponse h = do
mr <- await
case mr of
Just r -> lift (procR h r) >> yield r >> processResponse h
_ -> return ()
nullQ :: (BS.ByteString, Maybe BS.ByteString)
nullQ = ("", Nothing)
bind :: XmlNode
bind = XmlNode (nullQ, "bind") [("", "urn:ietf:params:xml:ns:xmpp-bind")] []
[XmlNode (nullQ, "required") [] [] [], resource]
resource :: XmlNode
resource = XmlNode (nullQ, "resource") [] [] [XmlCharData "profanity"]
session :: XmlNode
session = XmlNode (nullQ, "session")
[("", "urn:ietf:params:xml:ns:xmpp-session")] [] []
iqSession :: XmlNode
iqSession = XmlNode (nullQ, "iq") []
[((nullQ, "id"), "_xmpp_session1"), ((nullQ, "type"), "set")] [session]
iqRoster :: XmlNode
iqRoster = XmlNode (nullQ, "iq") []
[((nullQ, "id"), "roster"), ((nullQ, "type"), "get")] [roster]
roster :: XmlNode
roster = XmlNode (nullQ, "query") [("", "jabber:iq:roster")] [] []
procR :: HandleLike h => h -> ShowResponse -> HandleMonad h ()
procR h (SRFeatures fs)
| Rosterver Optional `elem` fs = do
hlPut h . xmlString . (: []) $ XmlNode
(nullQ, "iq") [] [
((nullQ, "id"), "_xmpp_bind1"),
((nullQ, "type"), "set") ] [bind]
hlPut h $ xmlString [iqSession]
hlPut h $ xmlString [iqRoster]
hlPut h . xmlString . (: []) $ XmlNode
(nullQ, "presence") []
[((nullQ, "id"), "prof_presence_1")]
[capsToXml profanityCaps "http://www.profanity.im"]
procR h (SRChallenge r n q c _a) = do
-- print (r, n, q, c, a)
let dr = DR { drUserName = sender,
drRealm = r,
drPassword = "password",
drCnonce = "00DEADBEEF00",
drNonce = n,
drNc = "00000001",
drQop = q,
drDigestUri = "xmpp/localhost",
drCharset = c }
let ret = kvsToS $ responseToKvs True dr
let Just sret = lookup "response" $ responseToKvs False dr
let node = xmlString . (: []) $ XmlNode
(("", Nothing), "response")
[("", "urn:ietf:params:xml:ns:xmpp-sasl")] []
[XmlCharData $ encode ret]
-- print ret
hlDebug h "strict" $ showBS sret
-- print node
hlPut h node
procR h (SRChallengeRspauth _) = do
hlPut h . xmlString . (: []) $ XmlNode
(("", Nothing), "response")
[("", "urn:ietf:params:xml:ns:xmpp-sasl")] [] []
procR h SRSaslSuccess = hlPut h $ xmlString begin
procR h (SRPresence _ (C [(CTHash, "sha-1"), (CTVer, v), (CTNode, n)])) =
hlPut h . xmlString . (: []) $ XmlNode
(("", Nothing), "iq") [] [
((("", Nothing), "id"), "prof_caps_2"),
((("", Nothing), "to"),
sender `BS.append` "@localhost/profanity"),
((("", Nothing), "type"), "get")] [capsQuery v n]
procR h (SRIq [(IqId, i), (IqType, "get"), (IqTo, to),
(IqFrom, f)] (IqDiscoInfoNode [(DTNode, n)]))
| to == sender `BS.append` "@localhost/profanity" = do
hlPut h . xmlString . (: []) $ XmlNode
(("", Nothing), "iq") [] [
((("", Nothing), "id"), i),
((("", Nothing), "to"), f),
((("", Nothing), "type"), "result")]
[capsToQuery profanityCaps n]
hlPut h . xmlString . (: []) $ XmlNode
(("", Nothing), "message") [] [
((("", Nothing), "id"), "prof_3"),
((("", Nothing), "to"), recipient `BS.append` "@localhost"),
((("", Nothing), "type"), "chat") ] [message]
hlPut h "</stream:stream>"
procR _ _ = return ()
message :: XmlNode
message = XmlNode (("", Nothing), "body") [] [] [XmlCharData "Hello, darkness!"]
capsQuery :: BS.ByteString -> BS.ByteString -> XmlNode
capsQuery v n = XmlNode (("", Nothing), "query")
[("", "http://jabber.org/protocol/disco#info")]
[((("", Nothing), "node"), n `BS.append` "#" `BS.append` v)] []
begin :: [XmlNode]
begin = [
XmlDecl (1, 0),
XmlStart (("stream", Nothing), "stream")
[ ("", "jabber:client"),
("stream", "http://etherx.jabber.org/streams") ]
[ ((("", Nothing), "to"), "localhost"),
((("", Nothing), "version"), "1.0"),
((("xml", Nothing), "lang"), "en") ] ]
selectDigestMd5 :: [XmlNode]
selectDigestMd5 = (: []) $ XmlNode (("", Nothing), "auth")
[("", "urn:ietf:params:xml:ns:xmpp-sasl")]
[((("", Nothing), "mechanism"), "DIGEST-MD5")] []
handleP :: HandleLike h => h -> Pipe () BS.ByteString (HandleMonad h) ()
handleP h = do
c <- lift $ hlGetContent h
yield c
handleP h
-- printP :: (Show a, Monad m, MonadIO m) => Pipe a () m ()
printP :: (Show a, HandleLike h) => h -> Pipe a () (HandleMonad h) ()
printP h = await >>=
maybe (return ()) (\x -> lift (hlDebug h "critical" $ showBS x) >> printP h)
showBS :: Show a => a -> BS.ByteString
showBS = BSC.pack . (++ "\n") . show
convert :: Monad m => (a -> b) -> Pipe a b m ()
convert f = await >>= maybe (return ()) (\x -> yield (f x) >> convert f)
| YoshikuniJujo/forest | subprojects/xmpipe/tls.hs | bsd-3-clause | 15,582 | 254 | 15 | 2,594 | 6,350 | 3,458 | 2,892 | 399 | 2 |
{- FSQL : Parser/Base.hs -- Basic parser definitions
-
- Copyright (C) 2015 gahag
- All rights reserved.
-
- This software may be modified and distributed under the terms
- of the BSD license. See the LICENSE file for details.
-}
module Parser.Base (
Parser, OperatorTable
) where
import Data.Functor.Identity (Identity)
import Text.Parsec (Parsec)
import qualified Text.Parsec.Expr as E (OperatorTable)
type Parser = Parsec String () -- String as stream type, no user state.
type OperatorTable a = E.OperatorTable String () Identity a
| gahag/FSQL | src/Parser/Base.hs | bsd-3-clause | 599 | 0 | 6 | 147 | 84 | 52 | 32 | 7 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TemplateHaskell #-}
module Database.DSH.Backend.Sql.HDBC
( hdbcKey
, hdbcDescr
, hdbcInteger
, hdbcDouble
, hdbcBool
, hdbcChar
, hdbcText
, hdbcDecimal
, hdbcDay
) where
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lex.Fractional as BD
import qualified Data.ByteString.Lex.Integral as BI
import Data.Decimal
import qualified Data.Text as T
import Data.Time.Calendar
import qualified Database.HDBC as H
import Text.Printf
import qualified Data.Text.Encoding as TE
import Database.DSH.Backend
import Database.DSH.Common.Impossible
hdbcKey :: H.SqlValue -> KeyVal
hdbcKey !v = case v of
H.SqlInt32 !i -> KInt (fromIntegral i)
H.SqlInt64 !i -> KInt (fromIntegral i)
H.SqlWord32 !i -> KInt (fromIntegral i)
H.SqlWord64 !i -> KInt (fromIntegral i)
H.SqlInteger !i -> KInt (fromIntegral i)
H.SqlString !s -> KByteString (BSC.pack s)
H.SqlByteString !s -> KByteString s
H.SqlLocalDate !d -> KDay d
o -> error $ printf "hdbcKey: %s" (show o)
hdbcDescr :: H.SqlValue -> Int
hdbcDescr (H.SqlInt32 !i) = fromIntegral i
hdbcDescr (H.SqlInteger !i) = fromIntegral i
hdbcDescr v = error $ printf "hdbcDescr: %s" (show v)
hdbcInteger :: H.SqlValue -> Integer
hdbcInteger (H.SqlInteger !i) = i
hdbcInteger (H.SqlInt32 !i) = fromIntegral i
hdbcInteger (H.SqlInt64 !i) = fromIntegral i
hdbcInteger (H.SqlWord32 !i) = fromIntegral i
hdbcInteger (H.SqlWord64 !i) = fromIntegral i
hdbcInteger (H.SqlDouble !d) = truncate d
hdbcInteger (H.SqlByteString !s) = case BI.readSigned BI.readDecimal s of
Just (i, s') | BSC.null s' -> i
_ ->
error $ printf "hdbcInteger: %s" (show s)
hdbcInteger v = error $ printf "hdbcInteger: %s" (show v)
hdbcDouble :: H.SqlValue -> Double
hdbcDouble (H.SqlDouble !d) = d
hdbcDouble (H.SqlRational !d) = fromRational d
hdbcDouble (H.SqlInteger !d) = fromIntegral d
hdbcDouble (H.SqlInt32 !d) = fromIntegral d
hdbcDouble (H.SqlInt64 !d) = fromIntegral d
hdbcDouble (H.SqlWord32 !d) = fromIntegral d
hdbcDouble (H.SqlWord64 !d) = fromIntegral d
hdbcDouble (H.SqlByteString !c) = case BD.readSigned BD.readDecimal c of
Just (!v, _) -> v
Nothing -> $impossible
hdbcDouble v = error $ printf "hdbcDouble: %s" (show v)
hdbcBool :: H.SqlValue -> Bool
hdbcBool (H.SqlBool !b) = b
hdbcBool (H.SqlInteger !i) = i /= 0
hdbcBool (H.SqlInt32 !i) = i /= 0
hdbcBool (H.SqlInt64 !i) = i /= 0
hdbcBool (H.SqlWord32 !i) = i /= 0
hdbcBool (H.SqlWord64 !i) = i /= 0
hdbcBool (H.SqlByteString !s) = case BI.readDecimal s of
Just (!d, _) -> d /= (0 :: Int)
Nothing -> $impossible
hdbcBool v = error $ printf "hdbcBool: %s" (show v)
hdbcChar :: H.SqlValue -> Char
hdbcChar (H.SqlChar !c) = c
hdbcChar (H.SqlString (c:_)) = c
hdbcChar (H.SqlByteString !s) = case T.uncons (TE.decodeUtf8 s) of
Just (!c, _) -> c
Nothing -> $impossible
hdbcChar v = error $ printf "hdbcChar: %s" (show v)
hdbcText :: H.SqlValue -> T.Text
hdbcText (H.SqlString !t) = T.pack t
hdbcText (H.SqlByteString !s) = TE.decodeUtf8 s
hdbcText v = error $ printf "hdbcText: %s" (show v)
hdbcDecimal :: H.SqlValue -> Decimal
hdbcDecimal (H.SqlRational !d) = fromRational d
hdbcDecimal (H.SqlByteString !c) =
case BD.readSigned BD.readDecimal c of
Just (!d, _) -> d
Nothing -> error $ show c
hdbcDecimal v = error $ printf "hdbcDecimal: %s" (show v)
hdbcDay :: H.SqlValue -> Day
hdbcDay (H.SqlLocalDate d) = d
hdbcDay v = error $ printf "hdbcDay: %s" (show v)
| ulricha/dsh-sql | src/Database/DSH/Backend/Sql/HDBC.hs | bsd-3-clause | 4,288 | 0 | 12 | 1,417 | 1,441 | 708 | 733 | 94 | 9 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
import Control.Monad
import qualified Data.Text as T
import Web.Spock
import Web.Spock.Config
import AutoPlaylist.Api (app)
import AutoPlaylist.Environment (Config(..), Environment(..), initEnvironment)
import Server.Utils (staticMiddleware)
import Spotify.Api
import Spotify.Auth.Client
import System.Environment (getArgs)
main :: IO ()
main = do
args <- getArgs
case args of
[] -> putStrLn "Usage: auto-playlist-server config.json"
(confFp:_) -> do
eEnv <- initEnvironment confFp
case eEnv of
Left err -> putStrLn $ T.unpack err
Right env -> do
spockCfg <- defaultSpockCfg () PCNoDatabase env
runSpock 3000 $ spock spockCfg $ middleware staticMiddleware >> app
| tdietert/auto-playlist | web/Server.hs | bsd-3-clause | 971 | 0 | 20 | 306 | 230 | 122 | 108 | 25 | 3 |
{-# LANGUAGE GADTs #-}
module DBOp where
import Prelude hiding (Read)
{- DB operations DSL -}
data Create
data Read
data Update
data Delete
data DBOp o r a where
Find :: DBOp Read r a
Create :: DBOp Create r a
Chain :: (a -> DBOp o r b) -> DBOp o r a -> DBOp o r b
Map :: (a -> b) -> DBOp o r a -> DBOp o r b
| lambdatoast/gadt-spec | src/DBOp.hs | bsd-3-clause | 325 | 0 | 9 | 91 | 133 | 74 | 59 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE BangPatterns #-}
module TestCont where
import Haskus.Utils.ContFlow
import Haskus.Utils.Monad
import Haskus.Utils.Variant
import Data.Char
-- | Explicit CPS
sample1 :: (Int -> IO r) -> (Float -> IO r) -> (String -> IO r) -> IO r
sample1 cint cfloat cstring = do
putStrLn "Test"
if (10 :: Int) > 20
then cint 10
else cstring "Pif"
-- | CPS into tuple
sample2 :: ( Int -> IO r, Float -> IO r, String -> IO r) -> IO r
sample2 (cint, cfloat, cstring) = do
putStrLn "Test"
if (10 :: Int) > 20
then cint 10
else cstring "Pif"
-- | CPS into tuple by explicit type
sample3 :: (Int -> IO r, Float -> IO r, String -> IO r) -> IO r
sample3 cs = do
putStrLn "Test"
if (10 :: Int) > 20
then fret @Int cs 10
else fret @String cs "Pif"
-- | CPS into tuple by implicit type
sample4 :: (Int -> IO r, Float -> IO r, String -> IO r) -> IO r
sample4 cs = do
putStrLn "Test"
if (10 :: Int) > 20
then fret cs (10 :: Int)
else fret cs "Pif"
-- | Generalize
sample5 :: (Int -> r, Float -> r, String -> r) -> r
sample5 cs =
if (10 :: Int) > 20
then fret cs (10 :: Int)
else fret cs "Pif"
-- | Put in a generic tuple
sample6 :: ContListToTuple '[Int,Float,String] r -> r
sample6 cs =
if (10 :: Int) > 20
then fret cs (10 :: Int)
else fret cs "Pif"
-- | Wrap in a newtype
sample7 :: ContFlow '[Int,Float,String] r
sample7 = ContFlow $ \cs ->
if (10 :: Int) > 20
then fret cs (10 :: Int)
else fret cs "Pif"
-- | Example of using a flow
sample8 :: IO Int
sample8 = sample7 >::>
( \(x :: Int) -> putStrLn ("Int: " ++ show x) >> return 1
, \(x :: Float) -> putStrLn ("Float: " ++ show x) >> return 2
, \(x :: String) -> putStrLn ("String: " ++ show x) >> return 3
)
-- | Example of combined flows
sample9 :: ContFlow '[Double,Char] (IO r)
sample9 = ContFlow $ \cs -> do
putStrLn "Forcing an IO monad"
sample7 >::>
( \(x :: Int) -> fret cs 'a'
, \(x :: Float) -> fret cs (2.0 :: Double)
, \(x :: String) -> fret cs 'b'
)
sample9' :: ContFlow '[Float,Char] (IO r)
sample9' = ContFlow $ \cs -> do
putStrLn "Forcing an IO monad"
sample7 >::>
( \(x :: Int) -> fret cs 'a'
, fret cs -- direct transfer of the result
, \(x :: String) -> fret cs 'b'
)
sample10 :: IO ()
sample10 = do
putStrLn "Test test test!"
sample9 >::>
( \(x :: Double) -> putStrLn ("Double: " ++ show x)
, \(x :: Char) -> putStrLn ("Char: " ++ show x)
)
-- | What we would like to write (made up syntax)
-- sample11 :: ContFlow '[Double,Char] r
-- sample11 = cdo
-- ccase sample7 of
-- (x :: Int) -> return 'a'
-- (x :: Float) -> return (2.0 :: Double)
-- (x :: String) -> return 'b'
--
-- this define has to be defined in each module using ContFlow for now
#define fdo ContFlow $ \__cs -> let ?__cs = __cs in do
-- | Implicit parameters
sample12 :: MonadIO m => Int -> ContFlow '[Double,Char] (m r)
sample12 n = fdo
liftIO $ putStrLn "Forcing an IO monad"
sample7 >::>
( \(x :: Int) -> freturnN @1 'a' -- indexed return
, \(x :: Float) -> freturn (2.0 :: Double)
, \(x :: String) -> if n < 10
then frec (sample12 (n+1)) -- recursive call
else freturn (fromIntegral n :: Double)
)
sample13 :: IO ()
sample13 = do
putStrLn "Test test test!"
sample12 0 >::>
( \(x :: Double) -> putStrLn ("Double: " ++ show x)
, \(x :: Char) -> putStrLn ("Char: " ++ show x)
)
parseDigit :: String -> ContFlow '[(Int,String), String, ()] r
parseDigit s = fdo
case s of
"" -> freturn ()
(x:xs) | o <- ord x, o >= ord '0' && o <= ord '9'
-> freturn (o - ord '0',xs)
_ -> freturn s
parseDigits :: String -> [Int]
parseDigits s = parseDigit s >::>
( \(x,xs) -> x : parseDigits xs
, \(x:xs) -> parseDigits xs
, \() -> []
)
parseNum :: forall r. String -> ContFlow '[(Int,String), String, ()] r
parseNum str = fdo
let
go :: Bool -> Int -> String -> r
go b i s = parseDigit s >::>
( \(x,xs) -> go True (i*10+x) xs
, \xs -> if b then freturn (i,xs) else freturn xs
, \() -> if b then freturn (i,"") else freturn ()
)
go False 0 str
data Token = TokenInt Int | TokenString String deriving (Show)
parseTokens :: String -> [Token]
parseTokens str = go str ""
where
go s lb = parseNum s >:~:> -- support wrong order
( \(x,xs) -> if lb /= "" then TokenString (reverse lb) : TokenInt x : go xs ""
else TokenInt x : go xs ""
, \() -> if lb /= "" then [TokenString (reverse lb)] else []
, \(x:xs) -> go xs (x:lb)
)
testIf :: Bool -> IO ()
testIf b = do
fIf b >:~:>
( \Else -> putStrLn "No!"
, \Then -> putStrLn "Yes!"
)
{-# NOINLINE testWhile #-}
testWhile :: ContFlow '[()] (IO r)
testWhile = fdo
c <- getChar
if c == 'e'
then do
putStrLn "Loop ended"
freturn ()
else do
putStrLn "Looping!"
frec testWhile
ffor :: forall m a r. Monad m => (a -> Bool) -> (a -> a) -> (a -> m r) -> a -> ContFlow '[a] (m r)
ffor test inc f !v = fdo
let forLoop !x = if test x
then freturn x
else do
f x
forLoop (inc x)
forLoop v
{-# NOINLINE testFor #-}
testFor :: IO ()
testFor = ffor (== (10 :: Int)) (+1) (putStrLn . show) 0 >:-:> const (putStrLn "Ended")
testParse :: IO ()
testParse = print (parseTokens "123adsf456sfds789")
v :: Variant '[Int,String,Double]
v = setVariant "Hi!"
testVariant :: IO ()
testVariant = do
variantToCont v >::>
( \i -> putStrLn ("Int: " ++ show i)
, \s -> putStrLn ("String: " ++ show s)
, \d -> putStrLn ("Double: " ++ show d)
)
r <- contToVariantM (sample12 5)
print r
| hsyl20/ViperVM | scripts/ContFlow.hs | bsd-3-clause | 6,180 | 13 | 15 | 1,939 | 2,377 | 1,258 | 1,119 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Url.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Test.Tasty.HUnit
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
import Duckling.Testing.Types
import Duckling.Url.Corpus
import Duckling.Url.Types
tests :: TestTree
tests = testGroup "Url Tests"
[ makeCorpusTest [This Url] corpus
, makeNegativeCorpusTest [This Url] negativeCorpus
, surroundTests
]
surroundTests :: TestTree
surroundTests = testCase "Surround Tests" $
mapM_ (analyzedFirstTest testContext . withTargets [This Url]) xs
where
xs = examples (UrlData "www.lets-try-this-one.co.uk/episode-7" "lets-try-this-one.co.uk")
[ "phishing link: www.lets-try-this-one.co.uk/episode-7 If you want my job"
]
| rfranek/duckling | tests/Duckling/Url/Tests.hs | bsd-3-clause | 1,128 | 0 | 11 | 200 | 178 | 103 | 75 | 22 | 1 |
{-# LANGUAGE CPP #-}
module Flag where
import DynFlags
import Types
listFlags :: Options -> IO String
listFlags opt = return $ convert opt $
[ "-f" ++ prefix ++ option
#if __GLASGOW_HASKELL__ == 702
| (option,_,_,_) <- fFlags
#else
| (option,_,_) <- fFlags
#endif
, prefix <- ["","no-"]
]
| conal/ghc-mod | Flag.hs | bsd-3-clause | 307 | 0 | 9 | 68 | 90 | 52 | 38 | 9 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
module Util.QuakeFile ( QuakeFile
, open
, close
, writeString
, readString
, writeInt
, readInt
, writeEdict
, writeLevelLocals
, readLevelLocals
, writeGClient
, readGClient
, writeGameLocals
, readGameLocals
) where
import Control.Lens ((^.))
import Control.Monad (void)
import Data.Binary.Get
import Data.Binary.Put
import Data.Functor ((<$>))
import Data.Int (Int8, Int16)
import Linear (V3(..), V4(..))
import System.IO (openFile, IOMode(ReadWriteMode), Handle, hClose)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Char8 as BC
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import Game.GameLocalsT
import Game.EntityStateT
import Game.MFrameT
import Game.MMoveT
import Game.MonsterInfoT
import Game.MoveInfoT
import Game.ClientRespawnT
import Game.ClientPersistantT
import Game.GClientT
import Game.PlayerStateT
import Types
import Game.PMoveStateT
import QuakeState
import Game.EdictT
import Game.LevelLocalsT
import Util.Binary
import qualified Constants
data QuakeFile = QuakeFile Handle
open :: B.ByteString -> IO QuakeFile
open name = QuakeFile <$> openFile (BC.unpack name) ReadWriteMode
close :: QuakeFile -> IO ()
close (QuakeFile h) = hClose h -- IMPROVE: catch exception?
writeString :: QuakeFile -> Maybe B.ByteString -> IO ()
writeString (QuakeFile h) Nothing = do
print "writeString = Nothing"
BL.hPut h $ runPut $ putInt (-1)
writeString (QuakeFile h) (Just str) = do
print ("writeString = " `B.append` str)
BL.hPut h $ runPut $ do
putInt (B.length str)
putByteString str
readString :: QuakeFile -> IO (Maybe B.ByteString)
readString (QuakeFile h) = do
stringSize <- BL.hGet h 4
if BL.length stringSize /= 4
then do
print "readString FAILURE"
return Nothing
else do
let len :: Int = runGet getInt stringSize
if | len == -1 -> do
print "readString = Nothing"
return Nothing
| len == 0 -> do
print "readString = \"\""
return (Just "")
| otherwise -> do
str <- B.hGet h len
if B.length str /= len
then do
print "readString = FAILURE"
return Nothing
else do
print ("readString = " `B.append` str)
return $ Just str
writeInt :: QuakeFile -> Int -> IO ()
writeInt (QuakeFile h) num = do
print ("writeInt = " ++ show num)
BL.hPut h $ runPut $ putInt num
readInt :: QuakeFile -> IO Int
readInt (QuakeFile h) = do
num <- BL.hGet h 4
print ("readInt = " ++ show (runGet getInt num))
return (runGet getInt num)
writeShort :: QuakeFile -> Int16 -> IO ()
writeShort (QuakeFile h) num = do
print ("writeShort = " ++ show num)
BL.hPut h $ runPut $ putInt16 num
readShort :: QuakeFile -> IO Int16
readShort (QuakeFile h) = do
num <- BL.hGet h 2
print ("readShort = " ++ show (runGet getInt16 num))
return (runGet getInt16 num)
writeByte :: QuakeFile -> Int8 -> IO ()
writeByte (QuakeFile h) num = do
print ("writeByte = " ++ show num)
BL.hPut h $ runPut $ putWord8 (fromIntegral num)
readByte :: QuakeFile -> IO Int8
readByte (QuakeFile h) = do
num <- BL.hGet h 1
print ("readByte = " ++ show (runGet getWord8 num))
return (fromIntegral $ runGet getWord8 num)
writeFloat :: QuakeFile -> Float -> IO ()
writeFloat (QuakeFile h) num = do
print ("writeFloat = " ++ show num)
BL.hPut h $ runPut $ putFloat num
readFloat :: QuakeFile -> IO Float
readFloat (QuakeFile h) = do
num <- BL.hGet h 4
print ("readFloat = " ++ show (runGet getFloat num))
return (runGet getFloat num)
writeBool :: QuakeFile -> Bool -> IO ()
writeBool (QuakeFile h) p = do
print ("writeBool = " ++ show p)
BL.hPut h $ runPut $ putBool p
readBool :: QuakeFile -> IO Bool
readBool (QuakeFile h) = do
p <- BL.hGet h 1
print ("readBool = " ++ show (runGet getBool p))
return (runGet getBool p)
writeEdictRef :: QuakeFile -> Maybe (Ref EdictT) -> IO ()
writeEdictRef saveFile Nothing = writeInt saveFile (-1)
writeEdictRef saveFile (Just (Ref idx)) = writeInt saveFile idx
readEdictRef :: QuakeFile -> IO (Maybe (Ref EdictT))
readEdictRef (QuakeFile h) = do
num <- BL.hGet h 4
let idx = runGet getInt num
return $ if idx == -1
then Nothing
else Just (Ref idx) -- IMPROVE: if (i > GameBase.g_edicts.length) {
-- Com.DPrintf("jake2: illegal edict num:" + i + "\n");
-- return null;
-- }
writeVector :: QuakeFile -> V3 Float -> IO ()
writeVector saveFile (V3 a b c) = do
writeFloat saveFile a
writeFloat saveFile b
writeFloat saveFile c
readVector :: QuakeFile -> IO (V3 Float)
readVector saveFile = do
a <- readFloat saveFile
b <- readFloat saveFile
c <- readFloat saveFile
return (V3 a b c)
writeVectorShort :: QuakeFile -> V3 Int16 -> IO ()
writeVectorShort saveFile (V3 a b c) = do
writeShort saveFile a
writeShort saveFile b
writeShort saveFile c
readVectorShort :: QuakeFile -> IO (V3 Int16)
readVectorShort saveFile = do
a <- readShort saveFile
b <- readShort saveFile
c <- readShort saveFile
return (V3 a b c)
writeLevelLocals :: QuakeFile -> LevelLocalsT -> IO ()
writeLevelLocals saveFile level = do
print "writeLevelLocals"
writeInt saveFile (level^.llFrameNum)
writeFloat saveFile (level^.llTime)
writeString saveFile (Just $ level^.llLevelName)
writeString saveFile (Just $ level^.llMapName)
writeString saveFile (Just $ level^.llNextMap)
writeFloat saveFile (level^.llIntermissionTime)
writeString saveFile (Just $ level^.llChangeMap)
writeBool saveFile (level^.llExitIntermission)
writeVector saveFile (level^.llIntermissionOrigin)
writeVector saveFile (level^.llIntermissionAngle)
writeEdictRef saveFile (level^.llSightClient)
writeEdictRef saveFile (level^.llSightEntity)
writeInt saveFile (level^.llSightEntityFrameNum)
writeEdictRef saveFile (level^.llSoundEntity)
writeInt saveFile (level^.llSoundEntityFrameNum)
writeEdictRef saveFile (level^.llSound2Entity)
writeInt saveFile (level^.llSound2EntityFrameNum)
writeInt saveFile (level^.llPicHealth)
writeInt saveFile (level^.llTotalSecrets)
writeInt saveFile (level^.llFoundSecrets)
writeInt saveFile (level^.llTotalGoals)
writeInt saveFile (level^.llFoundGoals)
writeInt saveFile (level^.llTotalMonsters)
writeInt saveFile (level^.llKilledMonsters)
writeEdictRef saveFile (level^.llCurrentEntity)
writeInt saveFile (level^.llBodyQue) -- dead bodies
writeInt saveFile (level^.llPowerCubes) -- ugly necessity for coop
-- rst's checker :-)
writeInt saveFile 4711
readLevelLocals :: QuakeFile -> IO (LevelLocalsT)
readLevelLocals saveFile = do
putStrLn "QuakeFile.readLevelLocals" >> undefined -- TODO
writeEdict :: QuakeFile -> EdictT -> IO ()
writeEdict saveFile edict = do
print "writeEdict"
writeEntityState saveFile (edict^.eEntityState)
writeBool saveFile (edict^.eInUse)
writeInt saveFile (edict^.eLinkCount)
writeInt saveFile (edict^.eNumClusters)
writeInt saveFile 9999
writeInt saveFile Constants.maxEntClusters
UV.mapM_ (writeInt saveFile) (edict^.eClusterNums)
writeInt saveFile (edict^.eHeadNode)
writeInt saveFile (edict^.eAreaNum)
writeInt saveFile (edict^.eAreaNum2)
writeInt saveFile (edict^.eSvFlags)
writeVector saveFile (edict^.eMins)
writeVector saveFile (edict^.eMaxs)
writeVector saveFile (edict^.eAbsMin)
writeVector saveFile (edict^.eAbsMax)
writeVector saveFile (edict^.eSize)
writeInt saveFile (edict^.eSolid)
writeInt saveFile (edict^.eClipMask)
writeInt saveFile (edict^.eMoveType)
writeInt saveFile (edict^.eFlags)
writeString saveFile (edict^.eiModel)
writeFloat saveFile (edict^.eFreeTime)
writeString saveFile (edict^.eMessage)
writeString saveFile (Just $ edict^.eClassName)
writeInt saveFile (edict^.eSpawnFlags)
writeFloat saveFile (edict^.eTimeStamp)
writeFloat saveFile (edict^.eAngle)
writeString saveFile (edict^.eTarget)
writeString saveFile (edict^.eTargetName)
writeString saveFile (edict^.eKillTarget)
writeString saveFile (edict^.eTeam)
writeString saveFile (edict^.ePathTarget)
writeString saveFile (edict^.eDeathTarget)
writeString saveFile (edict^.eCombatTarget)
writeEdictRef saveFile (edict^.eTargetEnt)
writeFloat saveFile (edict^.eSpeed)
writeFloat saveFile (edict^.eAccel)
writeFloat saveFile (edict^.eDecel)
writeVector saveFile (edict^.eMoveDir)
writeVector saveFile (edict^.ePos1)
writeVector saveFile (edict^.ePos2)
writeVector saveFile (edict^.eVelocity)
writeVector saveFile (edict^.eAVelocity)
writeInt saveFile (edict^.eMass)
writeFloat saveFile (edict^.eAirFinished)
writeFloat saveFile (edict^.eGravity)
writeEdictRef saveFile (edict^.eGoalEntity)
writeEdictRef saveFile (edict^.eMoveTarget)
writeFloat saveFile (edict^.eYawSpeed)
writeFloat saveFile (edict^.eIdealYaw)
writeFloat saveFile (edict^.eNextThink)
writeAdapter saveFile (edict^.ePrethink)
writeAdapter saveFile (edict^.eThink)
writeAdapter saveFile (edict^.eBlocked)
writeAdapter saveFile (edict^.eTouch)
writeAdapter saveFile (edict^.eUse)
writeAdapter saveFile (edict^.ePain)
writeAdapter saveFile (edict^.eDie)
writeFloat saveFile (edict^.eTouchDebounceTime)
writeFloat saveFile (edict^.ePainDebounceTime)
writeFloat saveFile (edict^.eDamageDebounceTime)
writeFloat saveFile (edict^.eFlySoundDebounceTime)
writeFloat saveFile (edict^.eLastMoveTime)
writeInt saveFile (edict^.eHealth)
writeInt saveFile (edict^.eMaxHealth)
writeInt saveFile (edict^.eGibHealth)
writeInt saveFile (edict^.eDeadFlag)
writeInt saveFile (edict^.eShowHostile)
writeFloat saveFile (edict^.ePowerArmorTime)
writeString saveFile (edict^.eMap)
writeInt saveFile (edict^.eViewHeight)
writeInt saveFile (edict^.eTakeDamage)
writeInt saveFile (edict^.eDmg)
writeInt saveFile (edict^.eRadiusDmg)
writeFloat saveFile (edict^.eDmgRadius)
writeInt saveFile (edict^.eSounds)
writeInt saveFile (edict^.eCount)
writeEdictRef saveFile (edict^.eChain)
writeEdictRef saveFile (edict^.eEnemy)
writeEdictRef saveFile (edict^.eOldEnemy)
writeEdictRef saveFile (edict^.eActivator)
writeEdictRef saveFile (edict^.eGroundEntity)
writeInt saveFile (edict^.eGroundEntityLinkCount)
writeEdictRef saveFile (edict^.eTeamChain)
writeEdictRef saveFile (edict^.eTeamMaster)
writeEdictRef saveFile (edict^.eMyNoise)
writeEdictRef saveFile (edict^.eMyNoise2)
writeInt saveFile (edict^.eNoiseIndex)
writeInt saveFile (edict^.eNoiseIndex2)
writeFloat saveFile (edict^.eVolume)
writeFloat saveFile (edict^.eAttenuation)
writeFloat saveFile (edict^.eWait)
writeFloat saveFile (edict^.eDelay)
writeFloat saveFile (edict^.eRandom)
writeFloat saveFile (edict^.eTeleportTime)
writeInt saveFile (edict^.eWaterType)
writeInt saveFile (edict^.eWaterLevel)
writeVector saveFile (edict^.eMoveOrigin)
writeVector saveFile (edict^.eMoveAngles)
writeInt saveFile (edict^.eLightLevel)
writeInt saveFile (edict^.eStyle)
writeItemRef saveFile (edict^.eItem)
writeMoveInfo saveFile (edict^.eMoveInfo)
writeMonsterInfo saveFile (edict^.eMonsterInfo)
case edict^.eClient of
Nothing -> writeInt saveFile (-1)
Just (Ref idx) -> writeInt saveFile idx
writeEdictRef saveFile (edict^.eOwner)
-- rst's checker :-)
writeInt saveFile 9876
writeEntityState :: QuakeFile -> EntityStateT -> IO ()
writeEntityState saveFile entityState = do
print "writeEntityState"
writeEdictRef saveFile (entityState^.esSurroundingEnt)
writeVector saveFile (entityState^.esOrigin)
writeVector saveFile (entityState^.esAngles)
writeVector saveFile (entityState^.esOldOrigin)
writeInt saveFile (entityState^.esModelIndex)
writeInt saveFile (entityState^.esModelIndex2)
writeInt saveFile (entityState^.esModelIndex3)
writeInt saveFile (entityState^.esModelIndex4)
writeInt saveFile (entityState^.esFrame)
writeInt saveFile (entityState^.esSkinNum)
writeInt saveFile (entityState^.esEffects)
writeInt saveFile (entityState^.esRenderFx)
writeInt saveFile (entityState^.esSolid)
writeInt saveFile (entityState^.esSound)
writeInt saveFile (entityState^.esEvent)
writeAdapter :: SuperAdapter a => QuakeFile -> Maybe a -> IO ()
writeAdapter saveFile mAdapter = do
print "writeAdapter"
writeInt saveFile 3988
case mAdapter of
Nothing -> writeString saveFile Nothing
Just adapter -> writeString saveFile (Just $ getID adapter)
writeItemRef :: QuakeFile -> Maybe GItemReference -> IO ()
writeItemRef saveFile Nothing = writeInt saveFile (-1)
writeItemRef saveFile (Just (GItemReference idx)) = writeInt saveFile idx
readItemRef :: QuakeFile -> IO (Maybe GItemReference)
readItemRef saveFile = do
idx <- readInt saveFile
return $ if idx == -1
then Nothing
else Just (GItemReference idx)
writeMoveInfo :: QuakeFile -> MoveInfoT -> IO ()
writeMoveInfo saveFile moveInfo = do
print "writeMoveInfo"
writeVector saveFile (moveInfo^.miStartOrigin)
writeVector saveFile (moveInfo^.miStartAngles)
writeVector saveFile (moveInfo^.miEndOrigin)
writeVector saveFile (moveInfo^.miEndAngles)
writeInt saveFile (moveInfo^.miSoundStart)
writeInt saveFile (moveInfo^.miSoundMiddle)
writeInt saveFile (moveInfo^.miSoundEnd)
writeFloat saveFile (moveInfo^.miAccel)
writeFloat saveFile (moveInfo^.miSpeed)
writeFloat saveFile (moveInfo^.miDecel)
writeFloat saveFile (moveInfo^.miDistance)
writeFloat saveFile (moveInfo^.miWait)
writeInt saveFile (moveInfo^.miState)
writeVector saveFile (moveInfo^.miDir)
writeFloat saveFile (moveInfo^.miCurrentSpeed)
writeFloat saveFile (moveInfo^.miMoveSpeed)
writeFloat saveFile (moveInfo^.miNextSpeed)
writeFloat saveFile (moveInfo^.miRemainingDistance)
writeFloat saveFile (moveInfo^.miDecelDistance)
writeAdapter saveFile (moveInfo^.miEndFunc)
writeMonsterInfo :: QuakeFile -> MonsterInfoT -> IO ()
writeMonsterInfo saveFile monsterInfo = do
print "writeMonsterInfo"
case monsterInfo^.miCurrentMove of
Nothing -> writeBool saveFile False
Just move -> writeBool saveFile True >> writeMMove saveFile move
writeInt saveFile (monsterInfo^.miAIFlags)
writeInt saveFile (monsterInfo^.miNextFrame)
writeFloat saveFile (monsterInfo^.miScale)
writeAdapter saveFile (monsterInfo^.miStand)
writeAdapter saveFile (monsterInfo^.miIdle)
writeAdapter saveFile (monsterInfo^.miSearch)
writeAdapter saveFile (monsterInfo^.miWalk)
writeAdapter saveFile (monsterInfo^.miRun)
writeAdapter saveFile (monsterInfo^.miDodge)
writeAdapter saveFile (monsterInfo^.miAttack)
writeAdapter saveFile (monsterInfo^.miMelee)
writeAdapter saveFile (monsterInfo^.miSight)
writeAdapter saveFile (monsterInfo^.miCheckAttack)
writeFloat saveFile (monsterInfo^.miPauseTime)
writeFloat saveFile (monsterInfo^.miAttackFinished)
writeVector saveFile (monsterInfo^.miSavedGoal)
writeFloat saveFile (monsterInfo^.miSearchTime)
writeFloat saveFile (monsterInfo^.miTrailTime)
writeVector saveFile (monsterInfo^.miLastSighting)
writeInt saveFile (monsterInfo^.miAttackState)
writeInt saveFile (monsterInfo^.miLefty)
writeFloat saveFile (monsterInfo^.miIdleTime)
writeInt saveFile (monsterInfo^.miLinkCount)
writeInt saveFile (monsterInfo^.miPowerArmorPower)
writeInt saveFile (monsterInfo^.miPowerArmorType)
writeMMove :: QuakeFile -> MMoveT -> IO ()
writeMMove saveFile move = do
print "writeMMove"
writeString saveFile (Just $ move^.mmId)
writeInt saveFile (move^.mmFirstFrame)
writeInt saveFile (move^.mmLastFrame)
writeInt saveFile (V.length (move^.mmFrame))
V.mapM_ (writeMFrame saveFile) (move^.mmFrame)
writeAdapter saveFile (move^.mmEndFunc)
writeMFrame :: QuakeFile -> MFrameT -> IO ()
writeMFrame saveFile frame = do
print "writeMFrame"
writeAdapter saveFile (frame^.mfAI)
writeFloat saveFile (frame^.mfDist)
writeAdapter saveFile (frame^.mfThink)
writeGClient :: QuakeFile -> GClientT -> IO ()
writeGClient saveFile gClient = do
print "writeGClient"
writePlayerState saveFile (gClient^.gcPlayerState)
writeInt saveFile (gClient^.gcPing)
writeClientPersistant saveFile (gClient^.gcPers)
writeClientRespawn saveFile (gClient^.gcResp)
writePMoveState saveFile (gClient^.gcOldPMove)
writeBool saveFile (gClient^.gcShowScores)
writeBool saveFile (gClient^.gcShowInventory)
writeBool saveFile (gClient^.gcShowHelp)
writeBool saveFile (gClient^.gcShowHelpIcon)
writeInt saveFile (gClient^.gcAmmoIndex)
writeInt saveFile (gClient^.gcButtons)
writeInt saveFile (gClient^.gcOldButtons)
writeInt saveFile (gClient^.gcLatchedButtons)
writeBool saveFile (gClient^.gcWeaponThunk)
writeItemRef saveFile (gClient^.gcNewWeapon)
writeInt saveFile (gClient^.gcDamageArmor)
writeInt saveFile (gClient^.gcDamagePArmor)
writeInt saveFile (gClient^.gcDamageBlood)
writeInt saveFile (gClient^.gcDamageKnockback)
writeVector saveFile (gClient^.gcDamageFrom)
writeFloat saveFile (gClient^.gcKillerYaw)
writeInt saveFile (gClient^.gcWeaponState)
writeVector saveFile (gClient^.gcKickAngles)
writeVector saveFile (gClient^.gcKickOrigin)
writeFloat saveFile (gClient^.gcVDmgRoll)
writeFloat saveFile (gClient^.gcVDmgPitch)
writeFloat saveFile (gClient^.gcVDmgTime)
writeFloat saveFile (gClient^.gcFallTime)
writeFloat saveFile (gClient^.gcFallValue)
writeFloat saveFile (gClient^.gcDamageAlpha)
writeFloat saveFile (gClient^.gcBonusAlpha)
writeVector saveFile (gClient^.gcDamageBlend)
writeVector saveFile (gClient^.gcVAngle)
writeFloat saveFile (gClient^.gcBobTime)
writeVector saveFile (gClient^.gcOldViewAngles)
writeVector saveFile (gClient^.gcOldVelocity)
writeFloat saveFile (gClient^.gcNextDrownTime)
writeInt saveFile (gClient^.gcOldWaterLevel)
writeInt saveFile (gClient^.gcBreatherSound)
writeInt saveFile (gClient^.gcMachinegunShots)
writeInt saveFile (gClient^.gcAnimEnd)
writeInt saveFile (gClient^.gcAnimPriority)
writeBool saveFile (gClient^.gcAnimDuck)
writeBool saveFile (gClient^.gcAnimRun)
writeFloat saveFile (gClient^.gcQuadFrameNum)
writeFloat saveFile (gClient^.gcInvincibleFrameNum)
writeFloat saveFile (gClient^.gcBreatherFrameNum)
writeFloat saveFile (gClient^.gcEnviroFrameNum)
writeBool saveFile (gClient^.gcGrenadeBlewUp)
writeFloat saveFile (gClient^.gcGrenadeTime)
writeInt saveFile (gClient^.gcSilencerShots)
writeInt saveFile (gClient^.gcWeaponSound)
writeFloat saveFile (gClient^.gcPickupMsgTime)
writeFloat saveFile (gClient^.gcFloodLockTill)
UV.mapM_ (writeFloat saveFile) (gClient^.gcFloodWhen)
writeInt saveFile (gClient^.gcFloodWhenHead)
writeFloat saveFile (gClient^.gcRespawnTime)
writeEdictRef saveFile (gClient^.gcChaseTarget)
writeBool saveFile (gClient^.gcUpdateChase)
writeInt saveFile 8765
readGClient :: QuakeFile -> Int -> IO (GClientT)
readGClient saveFile idx = do
print "readGClient"
playerState <- readPlayerState saveFile
ping <- readInt saveFile
pers <- readClientPersistant saveFile
resp <- readClientRespawn saveFile
oldPMove <- readPMoveState saveFile
showScores <- readBool saveFile
showInventory <- readBool saveFile
showHelp <- readBool saveFile
showHelpIcon <- readBool saveFile
ammoIndex <- readInt saveFile
buttons <- readInt saveFile
oldButtons <- readInt saveFile
latchedButtons <- readInt saveFile
weaponThunk <- readBool saveFile
newWeapon <- readItemRef saveFile
damageArmor <- readInt saveFile
damagePArmor <- readInt saveFile
damageBlood <- readInt saveFile
damageKnockback <- readInt saveFile
damageFrom <- readVector saveFile
killerYaw <- readFloat saveFile
weaponState <- readInt saveFile
kickAngles <- readVector saveFile
kickOrigin <- readVector saveFile
vDmgRoll <- readFloat saveFile
vDmgPitch <- readFloat saveFile
vDmgTime <- readFloat saveFile
fallTime <- readFloat saveFile
fallValue <- readFloat saveFile
damageAlpha <- readFloat saveFile
bonusAlpha <- readFloat saveFile
damageBlend <- readVector saveFile
vAngle <- readVector saveFile
bobTime <- readFloat saveFile
oldViewAngles <- readVector saveFile
oldVelocity <- readVector saveFile
nextDrownTime <- readFloat saveFile
oldWaterLevel <- readInt saveFile
breatherSound <- readInt saveFile
machinegunShots <- readInt saveFile
animEnd <- readInt saveFile
animPriority <- readInt saveFile
animDuck <- readBool saveFile
animRun <- readBool saveFile
quadFrameNum <- readFloat saveFile
invincibleFrameNum <- readFloat saveFile
breatherFrameNum <- readFloat saveFile
enviroFrameNum <- readFloat saveFile
grenadeBlewUp <- readBool saveFile
grenadeTime <- readFloat saveFile
silencerShots <- readInt saveFile
weaponSound <- readInt saveFile
pickupMsgTime <- readFloat saveFile
floodLockTill <- readFloat saveFile
floodWhen <- mapM (const $ readFloat saveFile) [0..9]
floodWhenHead <- readInt saveFile
respawnTime <- readFloat saveFile
chaseTarget <- readEdictRef saveFile
updateChase <- readBool saveFile
check <- readInt saveFile
return GClientT { _gcPlayerState = playerState
, _gcPing = ping
, _gcPers = pers
, _gcResp = resp
, _gcOldPMove = oldPMove
, _gcShowScores = showScores
, _gcShowInventory = showInventory
, _gcShowHelp = showHelp
, _gcShowHelpIcon = showHelpIcon
, _gcAmmoIndex = ammoIndex
, _gcButtons = buttons
, _gcOldButtons = oldButtons
, _gcLatchedButtons = latchedButtons
, _gcWeaponThunk = weaponThunk
, _gcNewWeapon = newWeapon
, _gcDamageArmor = damageArmor
, _gcDamagePArmor = damagePArmor
, _gcDamageBlood = damageBlood
, _gcDamageKnockback = damageKnockback
, _gcDamageFrom = damageFrom
, _gcKillerYaw = killerYaw
, _gcWeaponState = weaponState
, _gcKickAngles = kickAngles
, _gcKickOrigin = kickOrigin
, _gcVDmgRoll = vDmgRoll
, _gcVDmgPitch = vDmgPitch
, _gcVDmgTime = vDmgTime
, _gcFallTime = fallTime
, _gcFallValue = fallValue
, _gcDamageAlpha = damageAlpha
, _gcBonusAlpha = bonusAlpha
, _gcDamageBlend = damageBlend
, _gcVAngle = vAngle
, _gcBobTime = bobTime
, _gcOldViewAngles = oldViewAngles
, _gcOldVelocity = oldVelocity
, _gcNextDrownTime = nextDrownTime
, _gcOldWaterLevel = oldWaterLevel
, _gcBreatherSound = breatherSound
, _gcMachinegunShots = machinegunShots
, _gcAnimEnd = animEnd
, _gcAnimPriority = animPriority
, _gcAnimDuck = animDuck
, _gcAnimRun = animRun
, _gcQuadFrameNum = quadFrameNum
, _gcInvincibleFrameNum = invincibleFrameNum
, _gcBreatherFrameNum = breatherFrameNum
, _gcEnviroFrameNum = enviroFrameNum
, _gcGrenadeBlewUp = grenadeBlewUp
, _gcGrenadeTime = grenadeTime
, _gcSilencerShots = silencerShots
, _gcWeaponSound = weaponSound
, _gcPickupMsgTime = pickupMsgTime
, _gcFloodLockTill = floodLockTill
, _gcFloodWhen = UV.fromList floodWhen
, _gcFloodWhenHead = floodWhenHead
, _gcRespawnTime = respawnTime
, _gcChaseTarget = chaseTarget
, _gcUpdateChase = updateChase
, _gcIndex = idx
}
{- TODO: how do we do it?
when (check /= 8765) $
Com.dprintf "game client load failed for num=" + index
-}
writeGameLocals :: QuakeFile -> GameLocalsT -> IO ()
writeGameLocals saveFile gameLocals = do
print "writeGameLocals"
writeString saveFile (Just $ gameLocals^.glHelpMessage1)
writeString saveFile (Just $ gameLocals^.glHelpMessage2)
writeInt saveFile (gameLocals^.glHelpChanged)
writeString saveFile (Just $ gameLocals^.glSpawnPoint)
writeInt saveFile (gameLocals^.glMaxClients)
writeInt saveFile (gameLocals^.glMaxEntities)
writeInt saveFile (gameLocals^.glServerFlags)
writeInt saveFile (gameLocals^.glNumItems)
writeBool saveFile (gameLocals^.glAutosaved)
-- rst's checker :-)
writeInt saveFile 1928
readGameLocals :: QuakeFile -> IO (GameLocalsT)
readGameLocals saveFile = do
print "readGameLocals"
Just helpMessage1 <- readString saveFile
Just helpMessage2 <- readString saveFile
helpChanged <- readInt saveFile
Just spawnPoint <- readString saveFile
maxClients <- readInt saveFile
maxEntities <- readInt saveFile
serverFlags <- readInt saveFile
numItems <- readInt saveFile
autoSaved <- readBool saveFile
check <- readInt saveFile
return newGameLocalsT { _glHelpMessage1 = helpMessage1
, _glHelpMessage2 = helpMessage2
, _glHelpChanged = helpChanged
, _glSpawnPoint = spawnPoint
, _glMaxClients = maxClients
, _glMaxEntities = maxEntities
, _glServerFlags = serverFlags
, _glNumItems = numItems
, _glAutosaved = autoSaved
}
{- TODO: how do we do it?
when (check /= 1928) $
Com.dprintf "error in loading game_locals, 1928\n"
-}
writePlayerState :: QuakeFile -> PlayerStateT -> IO ()
writePlayerState saveFile playerState = do
print "writePlayerState"
writePMoveState saveFile (playerState^.psPMoveState)
writeVector saveFile (playerState^.psViewAngles)
writeVector saveFile (playerState^.psViewOffset)
writeVector saveFile (playerState^.psKickAngles)
writeVector saveFile (playerState^.psGunAngles)
writeVector saveFile (playerState^.psGunOffset)
writeInt saveFile (playerState^.psGunIndex)
writeInt saveFile (playerState^.psGunFrame)
let V4 a b c d = playerState^.psBlend
writeFloat saveFile a
writeFloat saveFile b
writeFloat saveFile c
writeFloat saveFile d
writeFloat saveFile (playerState^.psFOV)
writeInt saveFile (playerState^.psRDFlags)
UV.mapM_ (writeShort saveFile) (playerState^.psStats)
readPlayerState :: QuakeFile -> IO (PlayerStateT)
readPlayerState saveFile = do
print "readPlayerState"
pMoveState <- readPMoveState saveFile
viewAngles <- readVector saveFile
viewOffset <- readVector saveFile
kickAngles <- readVector saveFile
gunAngles <- readVector saveFile
gunOffset <- readVector saveFile
gunIndex <- readInt saveFile
gunFrame <- readInt saveFile
a <- readFloat saveFile
b <- readFloat saveFile
c <- readFloat saveFile
d <- readFloat saveFile
fov <- readFloat saveFile
rdFlags <- readInt saveFile
stats <- mapM (const $ readShort saveFile) [0..Constants.maxStats-1]
return PlayerStateT { _psPMoveState = pMoveState
, _psViewAngles = viewAngles
, _psViewOffset = viewOffset
, _psKickAngles = kickAngles
, _psGunAngles = gunAngles
, _psGunOffset = gunOffset
, _psGunIndex = gunIndex
, _psGunFrame = gunFrame
, _psBlend = V4 a b c d
, _psFOV = fov
, _psRDFlags = rdFlags
, _psStats = UV.fromList stats
}
writeClientPersistant :: QuakeFile -> ClientPersistantT -> IO ()
writeClientPersistant saveFile clientPersistant = do
print "writeClientPersistant"
writeString saveFile (Just $ clientPersistant^.cpUserInfo)
writeString saveFile (Just $ clientPersistant^.cpNetName)
writeInt saveFile (clientPersistant^.cpHand)
writeBool saveFile (clientPersistant^.cpConnected)
writeInt saveFile (clientPersistant^.cpHealth)
writeInt saveFile (clientPersistant^.cpMaxHealth)
writeInt saveFile (clientPersistant^.cpSavedFlags)
writeInt saveFile (clientPersistant^.cpSelectedItem)
UV.mapM_ (writeInt saveFile) (clientPersistant^.cpInventory)
writeInt saveFile (clientPersistant^.cpMaxBullets)
writeInt saveFile (clientPersistant^.cpMaxShells)
writeInt saveFile (clientPersistant^.cpMaxRockets)
writeInt saveFile (clientPersistant^.cpMaxGrenades)
writeInt saveFile (clientPersistant^.cpMaxCells)
writeInt saveFile (clientPersistant^.cpMaxSlugs)
writeItemRef saveFile (clientPersistant^.cpWeapon)
writeItemRef saveFile (clientPersistant^.cpLastWeapon)
writeInt saveFile (clientPersistant^.cpPowerCubes)
writeInt saveFile (clientPersistant^.cpScore)
writeInt saveFile (clientPersistant^.cpGameHelpChanged)
writeInt saveFile (clientPersistant^.cpHelpChanged)
writeBool saveFile (clientPersistant^.cpSpectator)
readClientPersistant :: QuakeFile -> IO (ClientPersistantT)
readClientPersistant saveFile = do
print "readClientPersistant"
Just userInfo <- readString saveFile
Just netName <- readString saveFile
hand <- readInt saveFile
connected <- readBool saveFile
health <- readInt saveFile
maxHealth <- readInt saveFile
savedFlags <- readInt saveFile
selectedItem <- readInt saveFile
inventory <- mapM (const $ readInt saveFile) [0..Constants.maxItems-1]
maxBullets <- readInt saveFile
maxShells <- readInt saveFile
maxRockets <- readInt saveFile
maxGrenades <- readInt saveFile
maxCells <- readInt saveFile
maxSlugs <- readInt saveFile
weapon <- readItemRef saveFile
lastWeapon <- readItemRef saveFile
powerCubes <- readInt saveFile
score <- readInt saveFile
gameHelpChanged <- readInt saveFile
helpChanged <- readInt saveFile
spectator <- readBool saveFile
return ClientPersistantT { _cpUserInfo = userInfo
, _cpNetName = netName
, _cpHand = hand
, _cpConnected = connected
, _cpHealth = health
, _cpMaxHealth = maxHealth
, _cpSavedFlags = savedFlags
, _cpSelectedItem = selectedItem
, _cpInventory = UV.fromList inventory
, _cpMaxBullets = maxBullets
, _cpMaxShells = maxShells
, _cpMaxRockets = maxRockets
, _cpMaxGrenades = maxGrenades
, _cpMaxCells = maxCells
, _cpMaxSlugs = maxSlugs
, _cpWeapon = weapon
, _cpLastWeapon = lastWeapon
, _cpPowerCubes = powerCubes
, _cpScore = score
, _cpGameHelpChanged = gameHelpChanged
, _cpHelpChanged = helpChanged
, _cpSpectator = spectator
}
writeClientRespawn :: QuakeFile -> ClientRespawnT -> IO ()
writeClientRespawn saveFile clientRespawn = do
print "writeClientRespawn"
writeClientPersistant saveFile (clientRespawn^.crCoopRespawn)
writeInt saveFile (clientRespawn^.crEnterFrame)
writeInt saveFile (clientRespawn^.crScore)
writeVector saveFile (clientRespawn^.crCmdAngles)
writeBool saveFile (clientRespawn^.crSpectator)
readClientRespawn :: QuakeFile -> IO (ClientRespawnT)
readClientRespawn saveFile = do
print "readClientRespawn"
coopRespawn <- readClientPersistant saveFile
enterFrame <- readInt saveFile
score <- readInt saveFile
cmdAngles <- readVector saveFile
spectator <- readBool saveFile
return ClientRespawnT { _crCoopRespawn = coopRespawn
, _crEnterFrame = enterFrame
, _crScore = score
, _crCmdAngles = cmdAngles
, _crSpectator = spectator
}
writePMoveState :: QuakeFile -> PMoveStateT -> IO ()
writePMoveState saveFile pMoveState = do
print "writePMoveState"
writeInt saveFile (pMoveState^.pmsPMType)
writeVectorShort saveFile (pMoveState^.pmsOrigin)
writeVectorShort saveFile (pMoveState^.pmsVelocity)
writeByte saveFile (pMoveState^.pmsPMFlags)
writeByte saveFile (pMoveState^.pmsPMTime)
writeShort saveFile (pMoveState^.pmsGravity)
writeShort saveFile 0
writeVectorShort saveFile (pMoveState^.pmsDeltaAngles)
readPMoveState :: QuakeFile -> IO (PMoveStateT)
readPMoveState saveFile = do
print "readPMoveState"
pmType <- readInt saveFile
origin <- readVectorShort saveFile
velocity <- readVectorShort saveFile
pmFlags <- readByte saveFile
pmTime <- readByte saveFile
gravity <- readShort saveFile
void $ readShort saveFile
deltaAngles <- readVectorShort saveFile
return PMoveStateT { _pmsPMType = pmType
, _pmsOrigin = origin
, _pmsVelocity = velocity
, _pmsPMFlags = pmFlags
, _pmsPMTime = pmTime
, _pmsGravity = gravity
, _pmsDeltaAngles = deltaAngles
}
| ksaveljev/hake-2 | src/Util/QuakeFile.hs | bsd-3-clause | 38,210 | 0 | 19 | 11,754 | 9,844 | 4,699 | 5,145 | 803 | 5 |
module HasOffers.API.Affiliate.AffiliateUser
where
import Data.Text
import GHC.Generics
import Data.Aeson
import Control.Applicative
import Network.HTTP.Client
import qualified Data.ByteString.Char8 as BS
import HasOffers.API.Common
--------------------------------------------------------------------------------
| kelecorix/api-hasoffers | src/HasOffers/API/Affiliate/AffiliateUser.hs | bsd-3-clause | 324 | 0 | 4 | 31 | 50 | 34 | 16 | 8 | 0 |
module Main
( main
) where
import Cauterize.GHC7.Generate
import Cauterize.GHC7.Options
import Cauterize.GHC7.Version
import Options.Applicative (execParser)
main :: IO ()
main = runWithOptions caut2hs
runWithOptions :: (CautGHC7Opts -> IO ()) -> IO ()
runWithOptions fn = do
mopts <- execParser options
case mopts of
Just opts -> fn opts
Nothing -> do
putStr versionString
putStrLn "dependencies:"
putStr dependencyString
| cauterize-tools/caut-ghc7-ref | src/Main.hs | bsd-3-clause | 462 | 0 | 12 | 96 | 142 | 71 | 71 | 17 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-- | Variables, commands and functions. The /interface/ to
-- the processing.js API (<http://processingjs.org/reference>),
-- with some additions, deletions and modifications.
module Graphics.Web.Processing.Core.Interface (
-- * Predefined values
screenWidth, screenHeight
-- * Commands
-- ** General
, random
, noise
-- ** Drawing
, Drawing
-- *** Colors
, Color (..)
, stroke, fill, background
-- *** Stroke settings
, strokeWeight
-- *** Figures
, Proc_Point
, ellipse
, circle
, arc
, line
, point
, quad
, rect
, triangle
, bezier
, polygon
-- *** Text
, drawtext
-- ** Setup
, size
, setFrameRate
-- * Transformations
, translate
, rotate
, scale
, resetMatrix
-- * Mouse
, getMousePoint
-- * Keyboard
, Key (..)
, ArrowKey (..)
, KeyModifier (..)
, SpecialKey (..)
, matchKey
-- * Conditionals
, ifM
-- * Others
, frameCount
, getFrameRate
, comment
-- * Processing monads
, ProcMonad
) where
-- Internal
import Graphics.Web.Processing.Core.Primal
( Proc_Key (..)
, Proc_KeyCode (..)
, varFromText
, Proc_Float (..)
, noisef
, ProcType (..)
, ProcArg
)
import Graphics.Web.Processing.Core.Types
import Graphics.Web.Processing.Core.Monad
import Graphics.Web.Processing.Core.Var
--
import Control.Arrow (first)
import Data.Text (Text)
---- PREDEFINED VALUES
-- | Width of the canvas.
screenWidth :: Proc_Int
screenWidth = proc_read $ varFromText "screenWidth"
-- | Height of the canvas.
screenHeight :: Proc_Int
screenHeight = proc_read $ varFromText "screenHeight"
---- PREDEFINED VARIABLES
-- | Frames since the beginning of the script execution.
frameCount :: (ProcMonad m, Monad (m c)) => m c Proc_Int
frameCount = liftProc $ readVar $ varFromText "frameCount"
-- | Approximate number of frames per second.
getFrameRate :: (ProcMonad m, Monad (m c)) => m c Proc_Int
getFrameRate = liftProc $ readVar $ varFromText "frameRate"
-- COMMANDS
---- GENERAL
-- | Noise random function.
noise :: (ProcMonad m, Monad (m c)) => Proc_Point -> m c Proc_Float
noise (x,y) = return $ noisef x y
-- | Write a variable with a random number within an interval.
random :: ProcMonad m
=> Var Proc_Float -- ^ Target variable.
-> Proc_Float -- ^ Left endpoint of the interval.
-> Proc_Float -- ^ Right endpoint of the interval.
-> m c ()
random v a b = writeVar v $ Float_Random a b
---- DRAWING
-- | Class of contexts where the user can draw pictures
-- in the screen.
class Drawing a where
instance Drawing Setup where
instance Drawing Draw where
instance Drawing MouseClicked where
instance Drawing MouseReleased where
------ COLORS
-- | RGBA colors. Values must be between
-- 0 and 255, including in the alpha channel.
data Color = Color {
-- | Red channel.
redc :: Proc_Int
-- | Blue channel.
, bluec :: Proc_Int
-- | Green channel.
, greenc :: Proc_Int
-- | Alpha channel (opacity).
-- 0 means transparent, and 255 opaque.
, alphac :: Proc_Int
}
colorArgs :: Color -> [ProcArg]
colorArgs (Color r g b a) = fmap proc_arg [r,g,b,a]
-- | Set the drawing color.
stroke :: (ProcMonad m, Drawing c) => Color -> m c ()
stroke = commandM "stroke" . colorArgs
-- | Set the filling color.
fill :: (ProcMonad m, Drawing c) => Color -> m c ()
fill = commandM "fill" . colorArgs
-- | Fill the screen with a given color.
background :: (ProcMonad m, Drawing c) => Color -> m c ()
background = commandM "background" . colorArgs
-- | Set the weight of the lines.
strokeWeight :: (ProcMonad m, Drawing c) => Proc_Int -> m c ()
strokeWeight n = commandM "strokeWeight" [proc_arg n]
------ FIGURES
-- | A point as a pair of floating point numbers.
type Proc_Point = (Proc_Float,Proc_Float)
-- | Draw a ellipse.
ellipse :: (ProcMonad m, Drawing c)
=> Proc_Point -- ^ Center of the ellipse.
-> Proc_Float -- ^ Width of the ellipse.
-> Proc_Float -- ^ Height of the ellipse.
-> m c ()
ellipse (x,y) w h = commandM "ellipse" $ fmap proc_arg [x,y,w,h]
-- | Draw a circle.
circle :: (ProcMonad m, Drawing c)
=> Proc_Point -- ^ Center of the circle.
-> Proc_Float -- ^ Radius.
-> m c ()
circle p r = ellipse p (2*r) (2*r)
-- | Draw an arc.
--
-- The arc is drawn following the line of an ellipse
-- between two angles.
arc :: (ProcMonad m, Drawing c)
=> Proc_Point -- ^ Center of the ellipse.
-> Proc_Float -- ^ Width of the ellipse.
-> Proc_Float -- ^ Height of the ellipse.
-> Proc_Float -- ^ Initial angle (in radians).
-> Proc_Float -- ^ End angle (in radians).
-> m c ()
arc (x,y) w h a0 a1 = commandM "arc" $ fmap proc_arg [x,y,w,h,a0,a1]
-- | Draw a line.
line :: (ProcMonad m, Drawing c)
=> Proc_Point -- ^ Starting point.
-> Proc_Point -- ^ End point.
-> m c ()
line (x0,y0) (x1,y1) = commandM "line" $ fmap proc_arg [x0,y0,x1,y1]
-- | Prints a dot.
point :: (ProcMonad m, Drawing c)
=> Proc_Point -- ^ Location of the point.
-> m c ()
point (x,y) = commandM "point" $ fmap proc_arg [x,y]
-- | A quad is a quadrilateral, a four sided polygon.
-- The first parameter is the first vertex and the
-- subsequent parameters should proceed clockwise or
-- counter-clockwise around the defined shape.
quad :: (ProcMonad m, Drawing c)
=> Proc_Point -> Proc_Point -> Proc_Point -> Proc_Point
-> m c ()
quad (x0,y0) (x1,y1) (x2,y2) (x3,y3) =
commandM "quad" $ fmap proc_arg [x0,y0,x1,y1,x2,y2,x3,y3]
-- | Draws a rectangle to the screen. A rectangle is a
-- four-sided shape with every angle at ninety degrees.
-- The first parameter set the location, the
-- second sets the width, and the third sets the height.
rect :: (ProcMonad m, Drawing c)
=> Proc_Point -- ^ Location of the rectangle.
-> Proc_Float -- ^ Width of the rectangle.
-> Proc_Float -- ^ Height of the rectangle.
-> m c ()
rect (x,y) w h = commandM "rect" $ fmap proc_arg [x,y,w,h]
-- | A triangle is a plane created by connecting three points.
triangle :: (ProcMonad m, Drawing c)
=> Proc_Point -> Proc_Point -> Proc_Point
-> m c ()
triangle (x0,y0) (x1,y1) (x2,y2) =
commandM "triangle" $ fmap proc_arg [x0,y0,x1,y1,x2,y2]
-- | Bézier curve.
bezier :: (ProcMonad m, Drawing c)
=> Proc_Point -- ^ Initial point.
-> Proc_Point -- ^ First control point.
-> Proc_Point -- ^ Second control point.
-> Proc_Point -- ^ End point.
-> m c ()
bezier (x0,y0) (x1,y1) (x2,y2) (x3,y3) =
commandM "bezier" $ fmap proc_arg [x0,y0,x1,y1,x2,y2,x3,y3]
-- | Begin shape command. Not exported.
beginShape :: (ProcMonad m, Drawing c) => m c ()
beginShape = commandM "beginShape" []
-- | End shape command. Not exported.
endShape :: (ProcMonad m, Drawing c) => m c ()
endShape = commandM "endShape" []
-- | Vertex command. Not exported.
vertex :: (ProcMonad m, Drawing c) => Proc_Point -> m c ()
vertex (x,y) = commandM "vertex" [proc_arg x,proc_arg y]
-- | Polygon drawer.
polygon :: (ProcMonad m, Monad (m c), Drawing c) => [Proc_Point] -> m c ()
polygon ps = beginShape >> mapM_ vertex ps >> endShape
---- TEXT
-- | Display a text in the screen.
-- The color is specified by 'fill'.
drawtext :: (ProcMonad m, Drawing c)
=> Proc_Text -- ^ Text to draw.
-> Proc_Point -- ^ Position.
-> Proc_Float -- ^ Width.
-> Proc_Float -- ^ Height.
-> m c ()
drawtext t (x,y) w h =
commandM "text" $ [ proc_arg t
, proc_arg x, proc_arg y
, proc_arg w, proc_arg h
]
---- TRANSFORMATIONS
-- | Apply a rotation to the following pictures, centered
-- at the current position.
rotate :: (ProcMonad m, Drawing c) => Proc_Float -> m c ()
rotate a = commandM "rotate" [ proc_arg a ]
-- | Apply a scaling to the following pictures, centered
-- at the current position.
scale :: (ProcMonad m, Drawing c)
=> Proc_Float -- ^ Horizontal scaling.
-> Proc_Float -- ^ Vertical scaling.
-> m c ()
scale x y = commandM "scale" [ proc_arg x, proc_arg y ]
-- | Move the current position.
translate :: (ProcMonad m, Drawing c)
=> Proc_Float -- ^ Horizontal displacement.
-> Proc_Float -- ^ Vertical displacement.
-> m c ()
translate x y = commandM "translate" [ proc_arg x, proc_arg y ]
-- | Reset the transformation matrix.
resetMatrix :: (ProcMonad m, Drawing c)
=> m c ()
resetMatrix = commandM "resetMatrix" []
---- CONDITIONAL
-- | Conditional execution. When the boolean value is 'true',
-- it executes the first monadic argument. Otherwise, it
-- executes the other one. In any case, the result is discarded.
-- See also 'if_'.
ifM :: ProcMonad m => Proc_Bool -> m c a -> m c b -> m c ()
ifM = iff
---- MOUSE
-- | Get the current position of the mouse pointer.
getMousePoint :: (ProcMonad m, Monad (m c)) => m c Proc_Point
getMousePoint = do
x <- liftProc $ readVar $ varFromText "mouseX"
y <- liftProc $ readVar $ varFromText "mouseY"
return (x,y)
---- KEYBOARD
-- | Keyboard keys recognized by Processing.
data Key =
CharKey Char
| SpecialKey SpecialKey
| ArrowKey ArrowKey
| ModKey KeyModifier Key
-- | Arrow keys.
data ArrowKey = UP | DOWN | LEFT | RIGHT
-- | Key modifiers.
data KeyModifier = ALT | CONTROL | SHIFT
-- | Special keys.
data SpecialKey =
BACKSPACE
| TAB
| ENTER
| RETURN
| ESC
-- CODED UNCODED
keySplit :: Key -> ([Proc_KeyCode],Maybe (Either Proc_Key Proc_KeyCode))
keySplit (CharKey c) = ([],Just $ Left $ Key_Char c)
keySplit (SpecialKey BACKSPACE) = ([],Just $ Right $ KeyCode_BACKSPACE)
keySplit (SpecialKey TAB) = ([],Just $ Right $ KeyCode_TAB)
keySplit (SpecialKey ENTER) = ([],Just $ Right $ KeyCode_ENTER)
keySplit (SpecialKey RETURN) = ([],Just $ Right $ KeyCode_RETURN)
keySplit (SpecialKey ESC) = ([],Just $ Right $ KeyCode_ESC)
keySplit (ArrowKey UP) = ([KeyCode_UP], Nothing)
keySplit (ArrowKey DOWN) = ([KeyCode_DOWN], Nothing)
keySplit (ArrowKey LEFT) = ([KeyCode_LEFT], Nothing)
keySplit (ArrowKey RIGHT) = ([KeyCode_RIGHT], Nothing)
keySplit (ModKey m k) =
let modToKeyCode :: KeyModifier -> Proc_KeyCode
modToKeyCode ALT = KeyCode_ALT
modToKeyCode CONTROL = KeyCode_CONTROL
modToKeyCode SHIFT = KeyCode_SHIFT
in first (modToKeyCode m:) $ keySplit k
-- | This function takes a variable of type 'Proc_Bool' and a 'Key', and sets the variable to
-- 'true' if the key pressed is the given 'Key'. Otherwise, the variable is set to 'false'.
matchKey :: (ProcMonad m, Monad (m KeyPressed)) => Var Proc_Bool -> Key -> m KeyPressed ()
matchKey v k = do
let (codedKeys,uncodedKey) = keySplit k
if null codedKeys
then writeVar v true
else iff (Key_Var #== Key_CODED)
(writeVar v $ foldr1 (#&&) $ fmap (KeyCode_Var #==) codedKeys)
(writeVar v false)
b <- liftProc $ readVar v
case uncodedKey of
Nothing -> return ()
Just (Left pk) -> writeVar v $ Key_Var #== pk #&& b
Just (Right ck) -> writeVar v $ KeyCode_Var #== ck #&& b
---- SETUP
-- | Set the size of the canvas.
size :: ProcMonad m => Proc_Int -> Proc_Int -> m c ()
size w h = commandM "size" [proc_arg w, proc_arg h]
-- | Specify the number of frames to be displayed every second.
-- The default rate is 60 frames per second.
setFrameRate :: ProcMonad m => Proc_Int -> m Setup ()
setFrameRate r = commandM "frameRate" [proc_arg r]
---- COMMENTS
-- | Include a comment in the current position of the code.
-- You normally don't need to read the processing.js code output,
-- but this function can be useful to analyse or debug it.
comment :: ProcMonad m => Text -> m c ()
comment = writeComment
| Daniel-Diaz/processing | Graphics/Web/Processing/Core/Interface.hs | bsd-3-clause | 11,859 | 0 | 13 | 2,794 | 3,193 | 1,770 | 1,423 | -1 | -1 |
{-# LANGUAGE GADTs #-}
-- | Pretty printing
module Pretty where
import AST
pretty :: Pretty a => a -> String
pretty x = bpretty 0 x ""
class Pretty a where
bpretty :: Int -> a -> ShowS
instance Pretty a => Pretty [a] where
bpretty _ list = showString "[" . go list
where
go [] = showString "]"
go [x] = bpretty 0 x . go []
go (x:xs) = bpretty 0 x . showString ", " . go xs
instance (Pretty a, Pretty b) => Pretty (a, b) where
bpretty _ (x, y) =
showString "(" . bpretty 0 x .
showString ", " . bpretty 0 y .
showString ")"
instance (Pretty a, Pretty b, Pretty c) => Pretty (a, b, c) where
bpretty _ (x, y, z) =
showString "(" . bpretty 0 x .
showString ", " . bpretty 0 y .
showString ", " . bpretty 0 z .
showString ")"
instance Pretty Var where
bpretty _ (Var v) = showString v
instance Pretty TVar where
bpretty _ (TypeVar v) = showString v
instance Pretty (Type a) where
bpretty d typ = case typ of
TUnit -> showString "()"
TVar v -> bpretty d v
TExists v -> showParen (d > exists_prec) $
showString "∃ " . bpretty exists_prec v
TForall v t -> showParen (d > forall_prec) $
showString "∀ " . bpretty (forall_prec + 1) v .
showString ". " . bpretty forall_prec t
TFun t1 t2 -> showParen (d > fun_prec) $
bpretty (fun_prec + 1) t1 . showString " → " .
bpretty fun_prec t2
where
exists_prec = 10
forall_prec :: Int
forall_prec = 1
fun_prec = 1
instance Pretty Expr where
bpretty d expr = case expr of
EVar v -> bpretty d v
EUnit -> showString "()"
EAbs v e -> showParen (d > abs_prec) $
showString "λ" . bpretty (abs_prec + 1) v .
showString ". " . bpretty abs_prec e
EApp e1 e2 -> showParen (d > app_prec) $
bpretty app_prec e1 . showString " " . bpretty (app_prec + 1) e2
EAnno e t -> showParen (d > anno_prec) $
bpretty (anno_prec + 1) e . showString " : " . bpretty anno_prec t
where
abs_prec = 1
app_prec = 10
anno_prec = 1
instance Pretty (GContext a) where
bpretty d (Context xs) = bpretty d $ reverse xs
instance Pretty (ContextElem a) where
bpretty d cxte = case cxte of
CForall v -> bpretty d v
CVar v t -> showParen (d > hastype_prec) $
bpretty (hastype_prec + 1) v . showString " : " . bpretty hastype_prec t
CExists v -> showParen (d > exists_prec) $
showString "∃ " . bpretty exists_prec v
CExistsSolved v t -> showParen (d > exists_prec) $
showString "∃ " . bpretty exists_prec v .
showString " = " . bpretty exists_prec t
CMarker v -> showParen (d > app_prec) $
showString "▶ " . bpretty (app_prec + 1) v
where
exists_prec = 1
hastype_prec = 1
app_prec = 10
| ollef/Bidirectional | Pretty.hs | bsd-3-clause | 2,828 | 0 | 15 | 844 | 1,147 | 555 | 592 | 74 | 1 |
{-|
Module : Idris.Elab.Implementation
Description : Code to elaborate instances.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Implementation(elabImplementation) where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.Core.CaseTree
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Coverage
import Idris.DataOpts
import Idris.DeepSeq
import Idris.Delaborate
import Idris.Docstrings
import Idris.DSL
import Idris.Elab.Data
import Idris.Elab.Term
import Idris.Elab.Type
import Idris.Elab.Utils
import Idris.Error
import Idris.Imports
import Idris.Inliner
import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)
import Idris.PartialEval
import Idris.Primitives
import Idris.Providers
import IRTS.Lang
import Util.Pretty (pretty, text)
import Prelude hiding (id, (.))
import Control.Applicative hiding (Const)
import Control.Category
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import Data.Char (isLetter, toLower)
import Data.List
import Data.List.Split (splitOn)
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Text as T
import Debug.Trace
elabImplementation :: ElabInfo
-> SyntaxInfo
-> Docstring (Either Err PTerm)
-> [(Name, Docstring (Either Err PTerm))]
-> ElabWhat -- ^ phase
-> FC
-> [(Name, PTerm)] -- ^ constraints
-> [Name] -- ^ parent dictionary names (optionally)
-> Accessibility
-> FnOpts
-> Name -- ^ the interface
-> FC -- ^ precise location of interface name
-> [PTerm] -- ^ interface parameters (i.e. implementation)
-> [(Name, PTerm)] -- ^ Extra arguments in scope (e.g. implementation in where block)
-> PTerm -- ^ full implementation type
-> Maybe Name -- ^ explicit name
-> [PDecl]
-> Idris ()
elabImplementation info syn doc argDocs what fc cs parents acc opts n nfc ps pextra t expn ds = do
ist <- getIState
(n, ci) <- case lookupCtxtName n (idris_interfaces ist) of
[c] -> return c
[] -> ifail $ show fc ++ ":" ++ show n ++ " is not an interface"
cs -> tclift $ tfail $ At fc
(CantResolveAlts (map fst cs))
let constraint = PApp fc (PRef fc [] n) (map pexp ps)
let iname = mkiname n (namespace info) ps expn
putIState (ist { hide_list = addDef iname acc (hide_list ist) })
ist <- getIState
let totopts = Dictionary : Inlinable : opts
let emptyinterface = null (interface_methods ci)
when (what /= EDefns) $ do
nty <- elabType' True info syn doc argDocs fc totopts iname NoFC
(piBindp expl_param pextra t)
-- if the implementation type matches any of the implementations we have already,
-- and it's not a named implementation, then it's overlapping, so report an error
case expn of
Nothing
| OverlappingDictionary `notElem` opts ->
do mapM_ (maybe (return ()) overlapping . findOverlapping ist (interface_determiners ci) (delab ist nty))
(map fst $ interface_implementations ci)
addImplementation intImpl True n iname
_ -> addImplementation intImpl False n iname
when (what /= ETypes && (not (null ds && not emptyinterface))) $ do
-- Add the parent implementation names to the privileged set
oldOpen <- addOpenImpl parents
let ips = zip (interface_params ci) ps
let ns = case n of
NS n ns' -> ns'
_ -> []
-- get the implicit parameters that need passing through to the
-- where block
wparams <- mapM (\p -> case p of
PApp _ _ args -> getWParams (map getTm args)
a@(PRef fc _ f) -> getWParams [a]
_ -> return []) ps
ist <- getIState
let pnames = nub $ map pname (concat (nub wparams)) ++
concatMap (namesIn [] ist) ps
let superInterfaceImplementations = map (substImplementation ips pnames) (interface_default_super_interfaces ci)
undefinedSuperInterfaceImplementations <- filterM (fmap not . isOverlapping ist) superInterfaceImplementations
mapM_ (rec_elabDecl info EAll info) undefinedSuperInterfaceImplementations
ist <- getIState
-- Bring variables in implementation head into scope when building the
-- dictionary
let headVars = nub $ concatMap getHeadVars ps
let (headVarTypes, ty)
= case lookupTyExact iname (tt_ctxt ist) of
Just ty -> (map (\n -> (n, getTypeIn ist n ty)) headVars, ty)
_ -> (zip headVars (repeat Placeholder), Erased)
let impps = getImpParams ist (interface_impparams ci)
(snd (unApply (substRetTy ty)))
let iimpps = zip (interface_impparams ci) impps
logElab 5 $ "ImpPS: " ++ show impps ++ " --- " ++ show iimpps
logElab 5 $ "Head var types " ++ show headVarTypes ++ " from " ++ show ty
let all_meths = map (nsroot . fst) (interface_methods ci)
let mtys = map (\ (n, (inj, op, t)) ->
let t_in = substMatchesShadow (iimpps ++ ips) pnames t
mnamemap =
map (\n -> (n, PApp fc (PRef fc [] (decorate ns iname n))
(map (toImp fc) headVars)))
all_meths
t' = substMatchesShadow mnamemap pnames t_in in
(decorate ns iname n,
op, coninsert cs pextra t', t'))
(interface_methods ci)
logElab 5 (show (mtys, (iimpps ++ ips)))
logElab 5 ("Before defaults: " ++ show ds ++ "\n" ++ show (map fst (interface_methods ci)))
let ds_defs = insertDefaults ist iname (interface_defaults ci) ns ds
logElab 3 ("After defaults: " ++ show ds_defs ++ "\n")
let ds' = reorderDefs (map fst (interface_methods ci)) ds_defs
logElab 1 ("Reordered: " ++ show ds' ++ "\n")
mapM_ (warnMissing ds' ns iname) (map fst (interface_methods ci))
mapM_ (checkInInterface (map fst (interface_methods ci))) (concatMap defined ds')
let wbTys = map mkTyDecl mtys
let wbVals_orig = map (decorateid (decorate ns iname)) ds'
ist <- getIState
let wbVals = map (expandParamsD False ist id pextra (map methName mtys)) wbVals_orig
let wb = wbTys ++ wbVals
logElab 3 $ "Method types " ++ showSep "\n" (map (show . showDeclImp verbosePPOption . mkTyDecl) mtys)
logElab 3 $ "Implementation is " ++ show ps ++ " implicits " ++ show (concat (nub wparams))
let lhsImps = map (\n -> pimp n (PRef fc [] n) True) headVars
let lhs = PApp fc (PRef fc [] iname) (lhsImps ++ map (toExp .fst) pextra)
let rhs = PApp fc (PRef fc [] (implementationCtorName ci))
(map (pexp . (mkMethApp lhsImps)) mtys)
logElab 5 $ "Implementation LHS " ++ show totopts ++ "\n" ++ showTmImpls lhs ++ " " ++ show headVars
logElab 5 $ "Implementation RHS " ++ show rhs
push_estack iname True
logElab 3 ("Method types: " ++ show wbTys)
logElab 3 ("Method bodies (before params): " ++ show wbVals_orig)
logElab 3 ("Method bodies: " ++ show wbVals)
let idecls = [PClauses fc totopts iname
[PClause fc iname lhs [] rhs []]]
mapM_ (rec_elabDecl info EAll info) (map (impBind headVarTypes) wbTys)
mapM_ (rec_elabDecl info EAll info) idecls
ctxt <- getContext
let ifn_ty = case lookupTyExact iname ctxt of
Just t -> t
Nothing -> error "Can't happen (interface constructor)"
let ifn_is = case lookupCtxtExact iname (idris_implicits ist) of
Just t -> t
Nothing -> []
let prop_params = getParamsInType ist [] ifn_is ifn_ty
logElab 3 $ "Propagating parameters to methods: "
++ show (iname, prop_params)
let wbVals' = map (addParams prop_params) wbVals
logElab 5 ("Elaborating method bodies: " ++ show wbVals')
mapM_ (rec_elabDecl info EAll info) wbVals'
mapM_ (checkInjectiveDef fc (interface_methods ci)) (zip ds' wbVals')
pop_estack
setOpenImpl oldOpen
-- totalityCheckBlock
checkInjectiveArgs fc n (interface_determiners ci) (lookupTyExact iname (tt_ctxt ist))
addIBC (IBCImplementation intImpl (isNothing expn) n iname)
where
getImpParams ist = zipWith (\n tm -> delab ist tm)
intImpl = case ps of
[PConstant NoFC (AType (ATInt ITNative))] -> True
_ -> False
mkiname n' ns ps' expn' =
case expn' of
Nothing -> case ns of
[] -> SN (sImplementationN n' (map show ps'))
m -> sNS (SN (sImplementationN n' (map show ps'))) m
Just nm -> nm
substImplementation ips pnames (PImplementation doc argDocs syn _ cs parents acc opts n nfc ps pextra t expn ds)
= PImplementation doc argDocs syn fc cs parents acc opts n nfc
(map (substMatchesShadow ips pnames) ps)
pextra
(substMatchesShadow ips pnames t) expn ds
isOverlapping i (PImplementation doc argDocs syn _ _ _ _ _ n nfc ps pextra t expn _)
= case lookupCtxtName n (idris_interfaces i) of
[(n, ci)] -> let iname = (mkiname n (namespace info) ps expn) in
case lookupTy iname (tt_ctxt i) of
[] -> elabFindOverlapping i ci iname syn t
(_:_) -> return True
_ -> return False -- couldn't find interface, just let elabImplementation fail later
-- TODO: largely based upon elabType' - should try to abstract
-- Issue #1614 in the issue tracker:
-- https://github.com/idris-lang/Idris-dev/issues/1614
elabFindOverlapping i ci iname syn t
= do ty' <- addUsingConstraints syn fc t
-- TODO think: something more in info?
ty' <- implicit info syn iname ty'
let ty = addImpl [] i ty'
ctxt <- getContext
(ElabResult tyT _ _ ctxt' newDecls highlights newGName, _) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) iname (TType (UVal 0)) initEState
(errAt "type of " iname Nothing (erun fc (build i info ERHS [] iname ty)))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
ctxt <- getContext
(cty, _) <- recheckC (constraintNS info) fc id [] tyT
let nty = normalise ctxt [] cty
return $ any (isJust . findOverlapping i (interface_determiners ci) (delab i nty)) (map fst $ interface_implementations ci)
findOverlapping i dets t n
| SN (ParentN _ _) <- n = Nothing
| Just opts <- lookupCtxtExact n (idris_flags i),
OverlappingDictionary `elem` opts = Nothing
| otherwise
= case lookupTy n (tt_ctxt i) of
[t'] -> let tret = getRetType t
tret' = getRetType (delab i t') in
case matchArgs i dets tret' tret of
Right _ -> Just tret'
Left _ -> case matchArgs i dets tret tret' of
Right _ -> Just tret'
Left _ -> Nothing
_ -> Nothing
overlapping t' = tclift $ tfail (At fc (Msg $
"Overlapping implementation: " ++ show t' ++ " already defined"))
getRetType (PPi _ _ _ _ sc) = getRetType sc
getRetType t = t
matchArgs i dets x y =
let x' = keepDets dets x
y' = keepDets dets y in
matchClause i x' y'
keepDets dets (PApp fc f args)
= PApp fc f $ let a' = zip [0..] args in
map snd (filter (\(i, _) -> i `elem` dets) a')
keepDets dets t = t
methName (n, _, _, _) = n
toExp n = pexp (PRef fc [] n)
mkMethApp ps (n, _, _, ty)
= lamBind 0 ty (papp fc (PRef fc [] n)
(ps ++ map (toExp . fst) pextra ++ methArgs 0 ty))
where
needed is p = pname p `elem` map pname is
lamBind i (PPi (Constraint _ _ _) _ _ _ sc) sc'
= PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc')
lamBind i (PPi _ n _ ty sc) sc'
= PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc')
lamBind i _ sc = sc
methArgs i (PPi (Imp _ _ _ _ _ _) n _ ty sc)
= PImp 0 True [] n (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc
methArgs i (PPi (Exp _ _ _ _) n _ ty sc)
= PExp 0 [] (sMN 0 "marg") (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc
methArgs i (PPi (Constraint _ _ _) n _ ty sc)
= PConstraint 0 [] (sMN 0 "marg") (PResolveTC fc) : methArgs (i+1) sc
methArgs i _ = []
papp fc f [] = f
papp fc f as = PApp fc f as
getWParams [] = return []
getWParams (p : ps)
| PRef _ _ n <- p
= do ps' <- getWParams ps
ctxt <- getContext
case lookupP n ctxt of
[] -> return (pimp n (PRef fc [] n) True : ps')
_ -> return ps'
getWParams (_ : ps) = getWParams ps
decorate ns iname (NS (UN nm) s)
= NS (SN (WhereN 0 iname (SN (MethodN (UN nm))))) ns
decorate ns iname nm
= NS (SN (WhereN 0 iname (SN (MethodN nm)))) ns
mkTyDecl (n, op, t, _)
= PTy emptyDocstring [] syn fc op n NoFC
(mkUniqueNames [] [] t)
conbind :: [(Name, PTerm)] -> PTerm -> PTerm
conbind ((c,ty) : ns) x = PPi constraint c NoFC ty (conbind ns x)
conbind [] x = x
extrabind :: [(Name, PTerm)] -> PTerm -> PTerm
extrabind ((c,ty) : ns) x = PPi expl c NoFC ty (extrabind ns x)
extrabind [] x = x
coninsert :: [(Name, PTerm)] -> [(Name, PTerm)] -> PTerm -> PTerm
coninsert cs ex (PPi p@(Imp _ _ _ _ _ _) n fc t sc) = PPi p n fc t (coninsert cs ex sc)
coninsert cs ex sc = conbind cs (extrabind ex sc)
-- Reorder declarations to be in the same order as defined in the
-- interface declaration (important so that we insert default definitions
-- in the right place, and so that dependencies between methods are
-- respected)
reorderDefs :: [Name] -> [PDecl] -> [PDecl]
reorderDefs ns [] = []
reorderDefs [] ds = ds
reorderDefs (n : ns) ds = case pick n [] ds of
Just (def, ds') -> def : reorderDefs ns ds'
Nothing -> reorderDefs ns ds
pick n acc [] = Nothing
pick n acc (def@(PClauses _ _ cn cs) : ds)
| nsroot n == nsroot cn = Just (def, acc ++ ds)
pick n acc (d : ds) = pick n (acc ++ [d]) ds
insertDefaults :: IState -> Name ->
[(Name, (Name, PDecl))] -> [T.Text] ->
[PDecl] -> [PDecl]
insertDefaults i iname [] ns ds = ds
insertDefaults i iname ((n,(dn, clauses)) : defs) ns ds
= insertDefaults i iname defs ns (insertDef i n dn clauses ns iname ds)
insertDef i meth def clauses ns iname decls
| not $ any (clauseFor meth iname ns) decls
= let newd = expandParamsD False i (\n -> meth) [] [def] clauses in
-- trace (show newd) $
decls ++ [newd]
| otherwise = decls
warnMissing decls ns iname meth
| not $ any (clauseFor meth iname ns) decls
= iWarn fc . text $ "method " ++ show meth ++ " not defined"
| otherwise = return ()
checkInInterface ns meth
| any (eqRoot meth) ns = return ()
| otherwise = tclift $ tfail (At fc (Msg $
show meth ++ " not a method of interface " ++ show n))
eqRoot x y = nsroot x == nsroot y
clauseFor m iname ns (PClauses _ _ m' _)
= decorate ns iname m == decorate ns iname m'
clauseFor m iname ns _ = False
getHeadVars :: PTerm -> [Name]
getHeadVars (PRef _ _ n) | implicitable n = [n]
getHeadVars (PApp _ _ args) = concatMap getHeadVars (map getTm args)
getHeadVars (PPair _ _ _ l r) = getHeadVars l ++ getHeadVars r
getHeadVars (PDPair _ _ _ l t r) = getHeadVars l ++ getHeadVars t ++ getHeadVars t
getHeadVars _ = []
-- | Implicitly bind variables from the implementation head in method types
impBind :: [(Name, PTerm)] -> PDecl -> PDecl
impBind vs (PTy d ds syn fc opts n fc' t)
= PTy d ds syn fc opts n fc'
(doImpBind (filter (\(n, ty) -> n `notElem` boundIn t) vs) t)
where
doImpBind [] ty = ty
doImpBind ((n, argty) : ns) ty
= PPi impl n NoFC argty (doImpBind ns ty)
boundIn (PPi _ n _ _ sc) = n : boundIn sc
boundIn _ = []
getTypeIn :: IState -> Name -> Type -> PTerm
getTypeIn ist n (Bind x b sc)
| n == x = delab ist (binderTy b)
| otherwise = getTypeIn ist n (substV (P Ref x Erased) sc)
getTypeIn ist n tm = Placeholder
toImp fc n = pimp n (PRef fc [] n) True
-- | Propagate interface parameters to method bodies, if they're not
-- already there, and they are needed (i.e. appear in method's type)
addParams :: [Name] -> PDecl -> PDecl
addParams ps (PClauses fc opts n cs) = PClauses fc opts n (map addCParams cs)
where
addCParams (PClause fc n lhs ws rhs wb)
= PClause fc n (addTmParams (dropPs (allNamesIn lhs) ps) lhs) ws rhs wb
addCParams (PWith fc n lhs ws sc pn ds)
= PWith fc n (addTmParams (dropPs (allNamesIn lhs) ps) lhs) ws sc pn
(map (addParams ps) ds)
addCParams c = c
addTmParams ps (PRef fc hls n)
= PApp fc (PRef fc hls n) (map (toImp fc) ps)
addTmParams ps (PApp fc ap@(PRef fc' hls n) args)
= PApp fc ap (mergePs (map (toImp fc) ps) args)
addTmParams ps tm = tm
mergePs [] args = args
mergePs (p : ps) args
| isImplicit p,
pname p `notElem` map pname args
= p : mergePs ps args
where
isImplicit (PExp{}) = False
isImplicit _ = True
mergePs (p : ps) args
= mergePs ps args
-- Don't propagate a parameter if the name is rebound explicitly
dropPs :: [Name] -> [Name] -> [Name]
dropPs ns = filter (\x -> x `notElem` ns)
addParams ps d = d
-- | Check a given method definition is injective, if the interface info
-- says it needs to be. Takes originally written decl and the one
-- with name decoration, so we know which name to look up.
checkInjectiveDef :: FC -> [(Name, (Bool, FnOpts, PTerm))] ->
(PDecl, PDecl) -> Idris ()
checkInjectiveDef fc ns (PClauses _ _ n cs, PClauses _ _ elabn _)
| Just (True, _, _) <- clookup n ns
= do ist <- getIState
case lookupDefExact elabn (tt_ctxt ist) of
Just (CaseOp _ _ _ _ _ cdefs) ->
checkInjectiveCase ist (snd (cases_compiletime cdefs))
where
checkInjectiveCase ist (STerm tm)
= checkInjectiveApp ist (fst (unApply tm))
checkInjectiveCase _ _ = notifail
checkInjectiveApp ist (P (TCon _ _) n _) = return ()
checkInjectiveApp ist (P (DCon _ _ _) n _) = return ()
checkInjectiveApp ist (P Ref n _)
| Just True <- lookupInjectiveExact n (tt_ctxt ist) = return ()
checkInjectiveApp ist (P Ref n _) = notifail
checkInjectiveApp _ _ = notifail
notifail = ierror $ At fc (Msg (show n ++ " must be defined by a type or data constructor"))
clookup n [] = Nothing
clookup n ((n', d) : ds) | nsroot n == nsroot n' = Just d
| otherwise = Nothing
checkInjectiveDef fc ns _ = return ()
checkInjectiveArgs :: FC -> Name -> [Int] -> Maybe Type -> Idris ()
checkInjectiveArgs fc n ds Nothing = return ()
checkInjectiveArgs fc n ds (Just ty)
= do ist <- getIState
let (_, args) = unApply (instantiateRetTy ty)
ci 0 ist args
where
ci i ist (a : as) | i `elem` ds
= if isInj ist a then ci (i + 1) ist as
else tclift $ tfail (At fc (InvalidTCArg n a))
ci i ist (a : as) = ci (i + 1) ist as
ci i ist [] = return ()
isInj i (P Bound n _) = True
isInj i (P _ n _) = isConName n (tt_ctxt i)
isInj i (App _ f a) = isInj i f && isInj i a
isInj i (V _) = True
isInj i (Bind n b sc) = isInj i sc
isInj _ _ = True
instantiateRetTy (Bind n (Pi _ _ _ _) sc)
= substV (P Bound n Erased) (instantiateRetTy sc)
instantiateRetTy t = t
| jmitchell/Idris-dev | src/Idris/Elab/Implementation.hs | bsd-3-clause | 21,539 | 1 | 28 | 7,290 | 7,682 | 3,819 | 3,863 | 399 | 40 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module GHC.Hs.PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
-- | Abstract Haskell syntax for expressions.
module GHC.Hs.Expr where
#include "HsVersions.h"
-- friends:
import GhcPrelude
import GHC.Hs.Decls
import GHC.Hs.Pat
import GHC.Hs.Lit
import GHC.Hs.PlaceHolder ( NameOrRdrName )
import GHC.Hs.Extension
import GHC.Hs.Types
import GHC.Hs.Binds
-- others:
import TcEvidence
import CoreSyn
import DynFlags ( gopt, GeneralFlag(Opt_PrintExplicitCoercions) )
import Name
import NameSet
import BasicTypes
import ConLike
import SrcLoc
import Util
import Outputable
import FastString
import Type
import TysWiredIn (mkTupleStr)
import TcType (TcType)
import {-# SOURCE #-} TcRnTypes (TcLclEnv)
-- libraries:
import Data.Data hiding (Fixity(..))
import qualified Data.Data as Data (Fixity(..))
import Data.Maybe (isNothing)
import GHCi.RemoteTypes ( ForeignRef )
import qualified Language.Haskell.TH as TH (Q)
{-
************************************************************************
* *
\subsection{Expressions proper}
* *
************************************************************************
-}
-- * Expressions proper
-- | Located Haskell Expression
type LHsExpr p = Located (HsExpr p)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
-- in a list
-- For details on above see note [Api annotations] in ApiAnnotation
-------------------------
-- | Post-Type checking Expression
--
-- PostTcExpr is an evidence expression attached to the syntax tree by the
-- type checker (c.f. postTcType).
type PostTcExpr = HsExpr GhcTc
-- | Post-Type checking Table
--
-- We use a PostTcTable where there are a bunch of pieces of evidence, more
-- than is convenient to keep individually.
type PostTcTable = [(Name, PostTcExpr)]
-------------------------
-- | Syntax Expression
--
-- SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
-- by the renamer. It's used for rebindable syntax.
--
-- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
-- @(>>=)@, and then instantiated by the type checker with its type args
-- etc
--
-- This should desugar to
--
-- > syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0)
-- > (syn_arg_wraps[1] arg1) ...
--
-- where the actual arguments come from elsewhere in the AST.
-- This could be defined using @GhcPass p@ and such, but it's
-- harder to get it all to work out that way. ('noSyntaxExpr' is hard to
-- write, for example.)
data SyntaxExpr p = SyntaxExpr { syn_expr :: HsExpr p
, syn_arg_wraps :: [HsWrapper]
, syn_res_wrap :: HsWrapper }
-- | This is used for rebindable-syntax pieces that are too polymorphic
-- for tcSyntaxOp (trS_fmap and the mzip in ParStmt)
noExpr :: HsExpr (GhcPass p)
noExpr = HsLit noExtField (HsString (SourceText "noExpr") (fsLit "noExpr"))
noSyntaxExpr :: SyntaxExpr (GhcPass p)
-- Before renaming, and sometimes after,
-- (if the syntax slot makes no sense)
noSyntaxExpr = SyntaxExpr { syn_expr = HsLit noExtField
(HsString NoSourceText
(fsLit "noSyntaxExpr"))
, syn_arg_wraps = []
, syn_res_wrap = WpHole }
-- | Make a 'SyntaxExpr (HsExpr _)', missing its HsWrappers.
mkSyntaxExpr :: HsExpr (GhcPass p) -> SyntaxExpr (GhcPass p)
mkSyntaxExpr expr = SyntaxExpr { syn_expr = expr
, syn_arg_wraps = []
, syn_res_wrap = WpHole }
-- | Make a 'SyntaxExpr Name' (the "rn" is because this is used in the
-- renamer), missing its HsWrappers.
mkRnSyntaxExpr :: Name -> SyntaxExpr GhcRn
mkRnSyntaxExpr name = mkSyntaxExpr $ HsVar noExtField $ noLoc name
-- don't care about filling in syn_arg_wraps because we're clearly
-- not past the typechecker
instance OutputableBndrId p
=> Outputable (SyntaxExpr (GhcPass p)) where
ppr (SyntaxExpr { syn_expr = expr
, syn_arg_wraps = arg_wraps
, syn_res_wrap = res_wrap })
= sdocWithDynFlags $ \ dflags ->
getPprStyle $ \s ->
if debugStyle s || gopt Opt_PrintExplicitCoercions dflags
then ppr expr <> braces (pprWithCommas ppr arg_wraps)
<> braces (ppr res_wrap)
else ppr expr
-- | Command Syntax Table (for Arrow syntax)
type CmdSyntaxTable p = [(Name, HsExpr p)]
-- See Note [CmdSyntaxTable]
{-
Note [CmdSyntaxtable]
~~~~~~~~~~~~~~~~~~~~~
Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
track of the methods needed for a Cmd.
* Before the renamer, this list is an empty list
* After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
For example, for the 'arr' method
* normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
* with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
where @arr_22@ is whatever 'arr' is in scope
* After the type checker, it takes the form [(std_name, <expression>)]
where <expression> is the evidence for the method. This evidence is
instantiated with the class, but is still polymorphic in everything
else. For example, in the case of 'arr', the evidence has type
forall b c. (b->c) -> a b c
where 'a' is the ambient type of the arrow. This polymorphism is
important because the desugarer uses the same evidence at multiple
different types.
This is Less Cool than what we normally do for rebindable syntax, which is to
make fully-instantiated piece of evidence at every use site. The Cmd way
is Less Cool because
* The renamer has to predict which methods are needed.
See the tedious GHC.Rename.Expr.methodNamesCmd.
* The desugarer has to know the polymorphic type of the instantiated
method. This is checked by Inst.tcSyntaxName, but is less flexible
than the rest of rebindable syntax, where the type is less
pre-ordained. (And this flexibility is useful; for example we can
typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
-}
-- | A Haskell expression.
data HsExpr p
= HsVar (XVar p)
(Located (IdP p)) -- ^ Variable
-- See Note [Located RdrNames]
| HsUnboundVar (XUnboundVar p)
OccName -- ^ Unbound variable; also used for "holes"
-- (_ or _x).
-- Turned from HsVar to HsUnboundVar by the
-- renamer, when it finds an out-of-scope
-- variable or hole.
-- Turned into HsVar by type checker, to support
-- deferred type errors.
| HsConLikeOut (XConLikeOut p)
ConLike -- ^ After typechecker only; must be different
-- HsVar for pretty printing
| HsRecFld (XRecFld p)
(AmbiguousFieldOcc p) -- ^ Variable pointing to record selector
-- Not in use after typechecking
| HsOverLabel (XOverLabel p)
(Maybe (IdP p)) FastString
-- ^ Overloaded label (Note [Overloaded labels] in GHC.OverloadedLabels)
-- @Just id@ means @RebindableSyntax@ is in use, and gives the id of the
-- in-scope 'fromLabel'.
-- NB: Not in use after typechecking
| HsIPVar (XIPVar p)
HsIPName -- ^ Implicit parameter (not in use after typechecking)
| HsOverLit (XOverLitE p)
(HsOverLit p) -- ^ Overloaded literals
| HsLit (XLitE p)
(HsLit p) -- ^ Simple (non-overloaded) literals
| HsLam (XLam p)
(MatchGroup p (LHsExpr p))
-- ^ Lambda abstraction. Currently always a single match
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnRarrow',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsLamCase (XLamCase p) (MatchGroup p (LHsExpr p)) -- ^ Lambda-case
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsApp (XApp p) (LHsExpr p) (LHsExpr p) -- ^ Application
| HsAppType (XAppTypeE p) (LHsExpr p) (LHsWcType (NoGhcTc p)) -- ^ Visible type application
--
-- Explicit type argument; e.g f @Int x y
-- NB: Has wildcards, but no implicit quantification
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt',
-- | Operator applications:
-- NB Bracketed ops such as (+) come out as Vars.
-- NB We need an expr for the operator in an OpApp/Section since
-- the typechecker may need to apply the operator to a few types.
| OpApp (XOpApp p)
(LHsExpr p) -- left operand
(LHsExpr p) -- operator
(LHsExpr p) -- right operand
-- | Negation operator. Contains the negated expression and the name
-- of 'negate'
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
-- For details on above see note [Api annotations] in ApiAnnotation
| NegApp (XNegApp p)
(LHsExpr p)
(SyntaxExpr p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsPar (XPar p)
(LHsExpr p) -- ^ Parenthesised expr; see Note [Parens in HsSyn]
| SectionL (XSectionL p)
(LHsExpr p) -- operand; see Note [Sections in HsSyn]
(LHsExpr p) -- operator
| SectionR (XSectionR p)
(LHsExpr p) -- operator; see Note [Sections in HsSyn]
(LHsExpr p) -- operand
-- | Used for explicit tuples and sections thereof
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
-- Note [ExplicitTuple]
| ExplicitTuple
(XExplicitTuple p)
[LHsTupArg p]
Boxity
-- | Used for unboxed sum types
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
-- 'ApiAnnotation.AnnVbar', 'ApiAnnotation.AnnClose' @'#)'@,
--
-- There will be multiple 'ApiAnnotation.AnnVbar', (1 - alternative) before
-- the expression, (arity - alternative) after it
| ExplicitSum
(XExplicitSum p)
ConTag -- Alternative (one-based)
Arity -- Sum arity
(LHsExpr p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
-- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCase (XCase p)
(LHsExpr p)
(MatchGroup p (LHsExpr p))
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
-- 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnElse',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsIf (XIf p)
(Maybe (SyntaxExpr p)) -- cond function
-- Nothing => use the built-in 'if'
-- See Note [Rebindable if]
(LHsExpr p) -- predicate
(LHsExpr p) -- then part
(LHsExpr p) -- else part
-- | Multi-way if
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsMultiIf (XMultiIf p) [LGRHS p (LHsExpr p)]
-- | let(rec)
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
-- 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsLet (XLet p)
(LHsLocalBinds p)
(LHsExpr p)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
-- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsDo (XDo p) -- Type of the whole expression
(HsStmtContext Name) -- The parameterisation is unimportant
-- because in this context we never use
-- the PatGuard or ParStmt variant
(Located [ExprLStmt p]) -- "do":one or more stmts
-- | Syntactic list: [a,b,c,...]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
-- 'ApiAnnotation.AnnClose' @']'@
-- For details on above see note [Api annotations] in ApiAnnotation
-- See Note [Empty lists]
| ExplicitList
(XExplicitList p) -- Gives type of components of list
(Maybe (SyntaxExpr p))
-- For OverloadedLists, the fromListN witness
[LHsExpr p]
-- | Record construction
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| RecordCon
{ rcon_ext :: XRecordCon p
, rcon_con_name :: Located (IdP p) -- The constructor name;
-- not used after type checking
, rcon_flds :: HsRecordBinds p } -- The fields
-- | Record update
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| RecordUpd
{ rupd_ext :: XRecordUpd p
, rupd_expr :: LHsExpr p
, rupd_flds :: [LHsRecUpdField p]
}
-- For a type family, the arg types are of the *instance* tycon,
-- not the family tycon
-- | Expression with an explicit type signature. @e :: type@
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
-- For details on above see note [Api annotations] in ApiAnnotation
| ExprWithTySig
(XExprWithTySig p)
(LHsExpr p)
(LHsSigWcType (NoGhcTc p))
-- | Arithmetic sequence
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
-- 'ApiAnnotation.AnnClose' @']'@
-- For details on above see note [Api annotations] in ApiAnnotation
| ArithSeq
(XArithSeq p)
(Maybe (SyntaxExpr p))
-- For OverloadedLists, the fromList witness
(ArithSeqInfo p)
-- For details on above see note [Api annotations] in ApiAnnotation
-----------------------------------------------------------
-- MetaHaskell Extensions
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpenE','ApiAnnotation.AnnOpenEQ',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnCloseQ'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsBracket (XBracket p) (HsBracket p)
-- See Note [Pending Splices]
| HsRnBracketOut
(XRnBracketOut p)
(HsBracket GhcRn) -- Output of the renamer is the *original* renamed
-- expression, plus
[PendingRnSplice] -- _renamed_ splices to be type checked
| HsTcBracketOut
(XTcBracketOut p)
(Maybe QuoteWrapper) -- The wrapper to apply type and dictionary argument
-- to the quote.
(HsBracket GhcRn) -- Output of the type checker is the *original*
-- renamed expression, plus
[PendingTcSplice] -- _typechecked_ splices to be
-- pasted back in by the desugarer
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsSpliceE (XSpliceE p) (HsSplice p)
-----------------------------------------------------------
-- Arrow notation extension
-- | @proc@ notation for Arrows
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
-- 'ApiAnnotation.AnnRarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsProc (XProc p)
(LPat p) -- arrow abstraction, proc
(LHsCmdTop p) -- body of the abstraction
-- always has an empty stack
---------------------------------------
-- static pointers extension
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsStatic (XStatic p) -- Free variables of the body
(LHsExpr p) -- Body
---------------------------------------
-- Haskell program coverage (Hpc) Support
| HsTick
(XTick p)
(Tickish (IdP p))
(LHsExpr p) -- sub-expression
| HsBinTick
(XBinTick p)
Int -- module-local tick number for True
Int -- module-local tick number for False
(LHsExpr p) -- sub-expression
---------------------------------------
-- Expressions annotated with pragmas, written as {-# ... #-}
| HsPragE (XPragE p) (HsPragE p) (LHsExpr p)
---------------------------------------
-- Finally, HsWrap appears only in typechecker output
-- The contained Expr is *NOT* itself an HsWrap.
-- See Note [Detecting forced eta expansion] in DsExpr. This invariant
-- is maintained by GHC.Hs.Utils.mkHsWrap.
| HsWrap (XWrap p)
HsWrapper -- TRANSLATION
(HsExpr p)
| XExpr (XXExpr p) -- Note [Trees that Grow] extension constructor
-- | Extra data fields for a 'RecordCon', added by the type checker
data RecordConTc = RecordConTc
{ rcon_con_like :: ConLike -- The data constructor or pattern synonym
, rcon_con_expr :: PostTcExpr -- Instantiated constructor function
}
-- | Extra data fields for a 'RecordUpd', added by the type checker
data RecordUpdTc = RecordUpdTc
{ rupd_cons :: [ConLike]
-- Filled in by the type checker to the
-- _non-empty_ list of DataCons that have
-- all the upd'd fields
, rupd_in_tys :: [Type] -- Argument types of *input* record type
, rupd_out_tys :: [Type] -- and *output* record type
-- The original type can be reconstructed
-- with conLikeResTy
, rupd_wrap :: HsWrapper -- See note [Record Update HsWrapper]
} deriving Data
-- ---------------------------------------------------------------------
type instance XVar (GhcPass _) = NoExtField
type instance XUnboundVar (GhcPass _) = NoExtField
type instance XConLikeOut (GhcPass _) = NoExtField
type instance XRecFld (GhcPass _) = NoExtField
type instance XOverLabel (GhcPass _) = NoExtField
type instance XIPVar (GhcPass _) = NoExtField
type instance XOverLitE (GhcPass _) = NoExtField
type instance XLitE (GhcPass _) = NoExtField
type instance XLam (GhcPass _) = NoExtField
type instance XLamCase (GhcPass _) = NoExtField
type instance XApp (GhcPass _) = NoExtField
type instance XAppTypeE (GhcPass _) = NoExtField
type instance XOpApp GhcPs = NoExtField
type instance XOpApp GhcRn = Fixity
type instance XOpApp GhcTc = Fixity
type instance XNegApp (GhcPass _) = NoExtField
type instance XPar (GhcPass _) = NoExtField
type instance XSectionL (GhcPass _) = NoExtField
type instance XSectionR (GhcPass _) = NoExtField
type instance XExplicitTuple (GhcPass _) = NoExtField
type instance XExplicitSum GhcPs = NoExtField
type instance XExplicitSum GhcRn = NoExtField
type instance XExplicitSum GhcTc = [Type]
type instance XCase (GhcPass _) = NoExtField
type instance XIf (GhcPass _) = NoExtField
type instance XMultiIf GhcPs = NoExtField
type instance XMultiIf GhcRn = NoExtField
type instance XMultiIf GhcTc = Type
type instance XLet (GhcPass _) = NoExtField
type instance XDo GhcPs = NoExtField
type instance XDo GhcRn = NoExtField
type instance XDo GhcTc = Type
type instance XExplicitList GhcPs = NoExtField
type instance XExplicitList GhcRn = NoExtField
type instance XExplicitList GhcTc = Type
type instance XRecordCon GhcPs = NoExtField
type instance XRecordCon GhcRn = NoExtField
type instance XRecordCon GhcTc = RecordConTc
type instance XRecordUpd GhcPs = NoExtField
type instance XRecordUpd GhcRn = NoExtField
type instance XRecordUpd GhcTc = RecordUpdTc
type instance XExprWithTySig (GhcPass _) = NoExtField
type instance XArithSeq GhcPs = NoExtField
type instance XArithSeq GhcRn = NoExtField
type instance XArithSeq GhcTc = PostTcExpr
type instance XBracket (GhcPass _) = NoExtField
type instance XRnBracketOut (GhcPass _) = NoExtField
type instance XTcBracketOut (GhcPass _) = NoExtField
type instance XSpliceE (GhcPass _) = NoExtField
type instance XProc (GhcPass _) = NoExtField
type instance XStatic GhcPs = NoExtField
type instance XStatic GhcRn = NameSet
type instance XStatic GhcTc = NameSet
type instance XTick (GhcPass _) = NoExtField
type instance XBinTick (GhcPass _) = NoExtField
type instance XPragE (GhcPass _) = NoExtField
type instance XWrap (GhcPass _) = NoExtField
type instance XXExpr (GhcPass _) = NoExtCon
-- ---------------------------------------------------------------------
-- | A pragma, written as {-# ... #-}, that may appear within an expression.
data HsPragE p
= HsPragSCC (XSCC p)
SourceText -- Note [Pragma source text] in BasicTypes
StringLiteral -- "set cost centre" SCC pragma
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@,
-- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsPragCore (XCoreAnn p)
SourceText -- Note [Pragma source text] in BasicTypes
StringLiteral -- hdaume: core annotation
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnMinus',
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
-- 'ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsPragTick -- A pragma introduced tick
(XTickPragma p)
SourceText -- Note [Pragma source text] in BasicTypes
(StringLiteral,(Int,Int),(Int,Int))
-- external span for this tick
((SourceText,SourceText),(SourceText,SourceText))
-- Source text for the four integers used in the span.
-- See note [Pragma source text] in BasicTypes
| XHsPragE (XXPragE p)
type instance XSCC (GhcPass _) = NoExtField
type instance XCoreAnn (GhcPass _) = NoExtField
type instance XTickPragma (GhcPass _) = NoExtField
type instance XXPragE (GhcPass _) = NoExtCon
-- | Located Haskell Tuple Argument
--
-- 'HsTupArg' is used for tuple sections
-- @(,a,)@ is represented by
-- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@
-- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@
type LHsTupArg id = Located (HsTupArg id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
-- | Haskell Tuple Argument
data HsTupArg id
= Present (XPresent id) (LHsExpr id) -- ^ The argument
| Missing (XMissing id) -- ^ The argument is missing, but this is its type
| XTupArg (XXTupArg id) -- ^ Note [Trees that Grow] extension point
type instance XPresent (GhcPass _) = NoExtField
type instance XMissing GhcPs = NoExtField
type instance XMissing GhcRn = NoExtField
type instance XMissing GhcTc = Type
type instance XXTupArg (GhcPass _) = NoExtCon
tupArgPresent :: LHsTupArg id -> Bool
tupArgPresent (L _ (Present {})) = True
tupArgPresent (L _ (Missing {})) = False
tupArgPresent (L _ (XTupArg {})) = False
{-
Note [Parens in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~
HsPar (and ParPat in patterns, HsParTy in types) is used as follows
* HsPar is required; the pretty printer does not add parens.
* HsPars are respected when rearranging operator fixities.
So a * (b + c) means what it says (where the parens are an HsPar)
* For ParPat and HsParTy the pretty printer does add parens but this should be
a no-op for ParsedSource, based on the pretty printer round trip feature
introduced in
https://phabricator.haskell.org/rGHC499e43824bda967546ebf95ee33ec1f84a114a7c
* ParPat and HsParTy are pretty printed as '( .. )' regardless of whether or
not they are strictly necessary. This should be addressed when #13238 is
completed, to be treated the same as HsPar.
Note [Sections in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~~~
Sections should always appear wrapped in an HsPar, thus
HsPar (SectionR ...)
The parser parses sections in a wider variety of situations
(See Note [Parsing sections]), but the renamer checks for those
parens. This invariant makes pretty-printing easier; we don't need
a special case for adding the parens round sections.
Note [Rebindable if]
~~~~~~~~~~~~~~~~~~~~
The rebindable syntax for 'if' is a bit special, because when
rebindable syntax is *off* we do not want to treat
(if c then t else e)
as if it was an application (ifThenElse c t e). Why not?
Because we allow an 'if' to return *unboxed* results, thus
if blah then 3# else 4#
whereas that would not be possible using a all to a polymorphic function
(because you can't call a polymorphic function at an unboxed type).
So we use Nothing to mean "use the old built-in typing rule".
Note [Record Update HsWrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is a wrapper in RecordUpd which is used for the *required*
constraints for pattern synonyms. This wrapper is created in the
typechecking and is then directly used in the desugaring without
modification.
For example, if we have the record pattern synonym P,
pattern P :: (Show a) => a -> Maybe a
pattern P{x} = Just x
foo = (Just True) { x = False }
then `foo` desugars to something like
foo = case Just True of
P x -> P False
hence we need to provide the correct dictionaries to P's matcher on
the RHS so that we can build the expression.
Note [Located RdrNames]
~~~~~~~~~~~~~~~~~~~~~~~
A number of syntax elements have seemingly redundant locations attached to them.
This is deliberate, to allow transformations making use of the API Annotations
to easily correlate a Located Name in the RenamedSource with a Located RdrName
in the ParsedSource.
There are unfortunately enough differences between the ParsedSource and the
RenamedSource that the API Annotations cannot be used directly with
RenamedSource, so this allows a simple mapping to be used based on the location.
Note [ExplicitTuple]
~~~~~~~~~~~~~~~~~~~~
An ExplicitTuple is never just a data constructor like (,,,).
That is, the `[LHsTupArg p]` argument of `ExplicitTuple` has at least
one `Present` member (and is thus never empty).
A tuple data constructor like () or (,,,) is parsed as an `HsVar`, not an
`ExplicitTuple`, and stays that way. This is important for two reasons:
1. We don't need -XTupleSections for (,,,)
2. The type variables in (,,,) can be instantiated with visible type application.
That is,
(,,) :: forall a b c. a -> b -> c -> (a,b,c)
(True,,) :: forall {b} {c}. b -> c -> (Bool,b,c)
Note that the tuple section has *inferred* arguments, while the data
constructor has *specified* ones.
(See Note [Required, Specified, and Inferred for types] in TcTyClsDecls
for background.)
Sadly, the grammar for this is actually ambiguous, and it's only thanks to the
preference of a shift in a shift/reduce conflict that the parser works as this
Note details. Search for a reference to this Note in Parser.y for further
explanation.
Note [Empty lists]
~~~~~~~~~~~~~~~~~~
An empty list could be considered either a data constructor (stored with
HsVar) or an ExplicitList. This Note describes how empty lists flow through the
various phases and why.
Parsing
-------
An empty list is parsed by the sysdcon nonterminal. It thus comes to life via
HsVar nilDataCon (defined in TysWiredIn). A freshly-parsed (HsExpr GhcPs) empty list
is never a ExplicitList.
Renaming
--------
If -XOverloadedLists is enabled, we must type-check the empty list as if it
were a call to fromListN. (This is true regardless of the setting of
-XRebindableSyntax.) This is very easy if the empty list is an ExplicitList,
but an annoying special case if it's an HsVar. So the renamer changes a
HsVar nilDataCon to an ExplicitList [], but only if -XOverloadedLists is on.
(Why not always? Read on, dear friend.) This happens in the HsVar case of rnExpr.
Type-checking
-------------
We want to accept an expression like [] @Int. To do this, we must infer that
[] :: forall a. [a]. This is easy if [] is a HsVar with the right DataCon inside.
However, the type-checking for explicit lists works differently: [x,y,z] is never
polymorphic. Instead, we unify the types of x, y, and z together, and use the
unified type as the argument to the cons and nil constructors. Thus, treating
[] as an empty ExplicitList in the type-checker would prevent [] @Int from working.
However, if -XOverloadedLists is on, then [] @Int really shouldn't be allowed:
it's just like fromListN 0 [] @Int. Since
fromListN :: forall list. IsList list => Int -> [Item list] -> list
that expression really should be rejected. Thus, the renamer's behaviour is
exactly what we want: treat [] as a datacon when -XNoOverloadedLists, and as
an empty ExplicitList when -XOverloadedLists.
See also #13680, which requested [] @Int to work.
-}
instance (OutputableBndrId p) => Outputable (HsExpr (GhcPass p)) where
ppr expr = pprExpr expr
-----------------------
-- pprExpr, pprLExpr, pprBinds call pprDeeper;
-- the underscore versions do not
pprLExpr :: (OutputableBndrId p) => LHsExpr (GhcPass p) -> SDoc
pprLExpr (L _ e) = pprExpr e
pprExpr :: (OutputableBndrId p) => HsExpr (GhcPass p) -> SDoc
pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
| otherwise = pprDeeper (ppr_expr e)
isQuietHsExpr :: HsExpr id -> Bool
-- Parentheses do display something, but it gives little info and
-- if we go deeper when we go inside them then we get ugly things
-- like (...)
isQuietHsExpr (HsPar {}) = True
-- applications don't display anything themselves
isQuietHsExpr (HsApp {}) = True
isQuietHsExpr (HsAppType {}) = True
isQuietHsExpr (OpApp {}) = True
isQuietHsExpr _ = False
pprBinds :: (OutputableBndrId idL, OutputableBndrId idR)
=> HsLocalBindsLR (GhcPass idL) (GhcPass idR) -> SDoc
pprBinds b = pprDeeper (ppr b)
-----------------------
ppr_lexpr :: (OutputableBndrId p) => LHsExpr (GhcPass p) -> SDoc
ppr_lexpr e = ppr_expr (unLoc e)
ppr_expr :: forall p. (OutputableBndrId p)
=> HsExpr (GhcPass p) -> SDoc
ppr_expr (HsVar _ (L _ v)) = pprPrefixOcc v
ppr_expr (HsUnboundVar _ uv)= pprPrefixOcc uv
ppr_expr (HsConLikeOut _ c) = pprPrefixOcc c
ppr_expr (HsIPVar _ v) = ppr v
ppr_expr (HsOverLabel _ _ l)= char '#' <> ppr l
ppr_expr (HsLit _ lit) = ppr lit
ppr_expr (HsOverLit _ lit) = ppr lit
ppr_expr (HsPar _ e) = parens (ppr_lexpr e)
ppr_expr (HsPragE _ prag e) = sep [ppr prag, ppr_lexpr e]
ppr_expr e@(HsApp {}) = ppr_apps e []
ppr_expr e@(HsAppType {}) = ppr_apps e []
ppr_expr (OpApp _ e1 op e2)
| Just pp_op <- ppr_infix_expr (unLoc op)
= pp_infixly pp_op
| otherwise
= pp_prefixly
where
pp_e1 = pprDebugParendExpr opPrec e1 -- In debug mode, add parens
pp_e2 = pprDebugParendExpr opPrec e2 -- to make precedence clear
pp_prefixly
= hang (ppr op) 2 (sep [pp_e1, pp_e2])
pp_infixly pp_op
= hang pp_e1 2 (sep [pp_op, nest 2 pp_e2])
ppr_expr (NegApp _ e _) = char '-' <+> pprDebugParendExpr appPrec e
ppr_expr (SectionL _ expr op)
| Just pp_op <- ppr_infix_expr (unLoc op)
= pp_infixly pp_op
| otherwise
= pp_prefixly
where
pp_expr = pprDebugParendExpr opPrec expr
pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
4 (hsep [pp_expr, text "x_ )"])
pp_infixly v = (sep [pp_expr, v])
ppr_expr (SectionR _ op expr)
| Just pp_op <- ppr_infix_expr (unLoc op)
= pp_infixly pp_op
| otherwise
= pp_prefixly
where
pp_expr = pprDebugParendExpr opPrec expr
pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
4 (pp_expr <> rparen)
pp_infixly v = sep [v, pp_expr]
ppr_expr (ExplicitTuple _ exprs boxity)
-- Special-case unary boxed tuples so that they are pretty-printed as
-- `Unit x`, not `(x)`
| [L _ (Present _ expr)] <- exprs
, Boxed <- boxity
= hsep [text (mkTupleStr Boxed 1), ppr expr]
| otherwise
= tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
where
ppr_tup_args [] = []
ppr_tup_args (Present _ e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
ppr_tup_args (XTupArg x : es) = (ppr x <> punc es) : ppr_tup_args es
punc (Present {} : _) = comma <> space
punc (Missing {} : _) = comma
punc (XTupArg {} : _) = comma <> space
punc [] = empty
ppr_expr (ExplicitSum _ alt arity expr)
= text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)"
where
ppr_bars n = hsep (replicate n (char '|'))
ppr_expr (HsLam _ matches)
= pprMatches matches
ppr_expr (HsLamCase _ matches)
= sep [ sep [text "\\case"],
nest 2 (pprMatches matches) ]
ppr_expr (HsCase _ expr matches@(MG { mg_alts = L _ [_] }))
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
nest 2 (pprMatches matches) <+> char '}']
ppr_expr (HsCase _ expr matches)
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
nest 2 (pprMatches matches) ]
ppr_expr (HsIf _ _ e1 e2 e3)
= sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
nest 4 (ppr e2),
text "else",
nest 4 (ppr e3)]
ppr_expr (HsMultiIf _ alts)
= hang (text "if") 3 (vcat (map ppr_alt alts))
where ppr_alt (L _ (GRHS _ guards expr)) =
hang vbar 2 (ppr_one one_alt)
where
ppr_one [] = panic "ppr_exp HsMultiIf"
ppr_one (h:t) = hang h 2 (sep t)
one_alt = [ interpp'SP guards
, text "->" <+> pprDeeper (ppr expr) ]
ppr_alt (L _ (XGRHS x)) = ppr x
-- special case: let ... in let ...
ppr_expr (HsLet _ (L _ binds) expr@(L _ (HsLet _ _ _)))
= sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
ppr_lexpr expr]
ppr_expr (HsLet _ (L _ binds) expr)
= sep [hang (text "let") 2 (pprBinds binds),
hang (text "in") 2 (ppr expr)]
ppr_expr (HsDo _ do_or_list_comp (L _ stmts)) = pprDo do_or_list_comp stmts
ppr_expr (ExplicitList _ _ exprs)
= brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds })
= hang (ppr con_id) 2 (ppr rbinds)
ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds })
= hang (ppr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds))))
ppr_expr (ExprWithTySig _ expr sig)
= hang (nest 2 (ppr_lexpr expr) <+> dcolon)
4 (ppr sig)
ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
ppr_expr (HsWrap _ co_fn e)
= pprHsWrapper co_fn (\parens -> if parens then pprExpr e
else pprExpr e)
ppr_expr (HsSpliceE _ s) = pprSplice s
ppr_expr (HsBracket _ b) = pprHsBracket b
ppr_expr (HsRnBracketOut _ e []) = ppr e
ppr_expr (HsRnBracketOut _ e ps) = ppr e $$ text "pending(rn)" <+> ppr ps
ppr_expr (HsTcBracketOut _ _wrap e []) = ppr e
ppr_expr (HsTcBracketOut _ _wrap e ps) = ppr e $$ text "pending(tc)" <+> ppr ps
ppr_expr (HsProc _ pat (L _ (HsCmdTop _ cmd)))
= hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd]
ppr_expr (HsProc _ pat (L _ (XCmdTop x)))
= hsep [text "proc", ppr pat, ptext (sLit "->"), ppr x]
ppr_expr (HsStatic _ e)
= hsep [text "static", ppr e]
ppr_expr (HsTick _ tickish exp)
= pprTicks (ppr exp) $
ppr tickish <+> ppr_lexpr exp
ppr_expr (HsBinTick _ tickIdTrue tickIdFalse exp)
= pprTicks (ppr exp) $
hcat [text "bintick<",
ppr tickIdTrue,
text ",",
ppr tickIdFalse,
text ">(",
ppr exp, text ")"]
ppr_expr (HsRecFld _ f) = ppr f
ppr_expr (XExpr x) = ppr x
ppr_infix_expr :: (OutputableBndrId p) => HsExpr (GhcPass p) -> Maybe SDoc
ppr_infix_expr (HsVar _ (L _ v)) = Just (pprInfixOcc v)
ppr_infix_expr (HsConLikeOut _ c) = Just (pprInfixOcc (conLikeName c))
ppr_infix_expr (HsRecFld _ f) = Just (pprInfixOcc f)
ppr_infix_expr (HsUnboundVar _ occ) = Just (pprInfixOcc occ)
ppr_infix_expr (HsWrap _ _ e) = ppr_infix_expr e
ppr_infix_expr _ = Nothing
ppr_apps :: (OutputableBndrId p)
=> HsExpr (GhcPass p)
-> [Either (LHsExpr (GhcPass p)) (LHsWcType (NoGhcTc (GhcPass p)))]
-> SDoc
ppr_apps (HsApp _ (L _ fun) arg) args
= ppr_apps fun (Left arg : args)
ppr_apps (HsAppType _ (L _ fun) arg) args
= ppr_apps fun (Right arg : args)
ppr_apps fun args = hang (ppr_expr fun) 2 (fsep (map pp args))
where
pp (Left arg) = ppr arg
-- pp (Right (LHsWcTypeX (HsWC { hswc_body = L _ arg })))
-- = char '@' <> pprHsType arg
pp (Right arg)
= char '@' <> ppr arg
pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc
pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4))
= ppr (src,(n1,n2),(n3,n4))
{-
HsSyn records exactly where the user put parens, with HsPar.
So generally speaking we print without adding any parens.
However, some code is internally generated, and in some places
parens are absolutely required; so for these places we use
pprParendLExpr (but don't print double parens of course).
For operator applications we don't add parens, because the operator
fixities should do the job, except in debug mode (-dppr-debug) so we
can see the structure of the parse tree.
-}
pprDebugParendExpr :: (OutputableBndrId p)
=> PprPrec -> LHsExpr (GhcPass p) -> SDoc
pprDebugParendExpr p expr
= getPprStyle (\sty ->
if debugStyle sty then pprParendLExpr p expr
else pprLExpr expr)
pprParendLExpr :: (OutputableBndrId p)
=> PprPrec -> LHsExpr (GhcPass p) -> SDoc
pprParendLExpr p (L _ e) = pprParendExpr p e
pprParendExpr :: (OutputableBndrId p)
=> PprPrec -> HsExpr (GhcPass p) -> SDoc
pprParendExpr p expr
| hsExprNeedsParens p expr = parens (pprExpr expr)
| otherwise = pprExpr expr
-- Using pprLExpr makes sure that we go 'deeper'
-- I think that is usually (always?) right
-- | @'hsExprNeedsParens' p e@ returns 'True' if the expression @e@ needs
-- parentheses under precedence @p@.
hsExprNeedsParens :: PprPrec -> HsExpr p -> Bool
hsExprNeedsParens p = go
where
go (HsVar{}) = False
go (HsUnboundVar{}) = False
go (HsConLikeOut{}) = False
go (HsIPVar{}) = False
go (HsOverLabel{}) = False
go (HsLit _ l) = hsLitNeedsParens p l
go (HsOverLit _ ol) = hsOverLitNeedsParens p ol
go (HsPar{}) = False
go (HsApp{}) = p >= appPrec
go (HsAppType {}) = p >= appPrec
go (OpApp{}) = p >= opPrec
go (NegApp{}) = p > topPrec
go (SectionL{}) = True
go (SectionR{}) = True
go (ExplicitTuple{}) = False
go (ExplicitSum{}) = False
go (HsLam{}) = p > topPrec
go (HsLamCase{}) = p > topPrec
go (HsCase{}) = p > topPrec
go (HsIf{}) = p > topPrec
go (HsMultiIf{}) = p > topPrec
go (HsLet{}) = p > topPrec
go (HsDo _ sc _)
| isComprehensionContext sc = False
| otherwise = p > topPrec
go (ExplicitList{}) = False
go (RecordUpd{}) = False
go (ExprWithTySig{}) = p >= sigPrec
go (ArithSeq{}) = False
go (HsPragE{}) = p >= appPrec
go (HsWrap _ _ e) = go e
go (HsSpliceE{}) = False
go (HsBracket{}) = False
go (HsRnBracketOut{}) = False
go (HsTcBracketOut{}) = False
go (HsProc{}) = p > topPrec
go (HsStatic{}) = p >= appPrec
go (HsTick _ _ (L _ e)) = go e
go (HsBinTick _ _ _ (L _ e)) = go e
go (RecordCon{}) = False
go (HsRecFld{}) = False
go (XExpr{}) = True
-- | @'parenthesizeHsExpr' p e@ checks if @'hsExprNeedsParens' p e@ is true,
-- and if so, surrounds @e@ with an 'HsPar'. Otherwise, it simply returns @e@.
parenthesizeHsExpr :: PprPrec -> LHsExpr (GhcPass p) -> LHsExpr (GhcPass p)
parenthesizeHsExpr p le@(L loc e)
| hsExprNeedsParens p e = L loc (HsPar noExtField le)
| otherwise = le
stripParensHsExpr :: LHsExpr (GhcPass p) -> LHsExpr (GhcPass p)
stripParensHsExpr (L _ (HsPar _ e)) = stripParensHsExpr e
stripParensHsExpr e = e
isAtomicHsExpr :: HsExpr id -> Bool
-- True of a single token
isAtomicHsExpr (HsVar {}) = True
isAtomicHsExpr (HsConLikeOut {}) = True
isAtomicHsExpr (HsLit {}) = True
isAtomicHsExpr (HsOverLit {}) = True
isAtomicHsExpr (HsIPVar {}) = True
isAtomicHsExpr (HsOverLabel {}) = True
isAtomicHsExpr (HsUnboundVar {}) = True
isAtomicHsExpr (HsWrap _ _ e) = isAtomicHsExpr e
isAtomicHsExpr (HsPar _ e) = isAtomicHsExpr (unLoc e)
isAtomicHsExpr (HsRecFld{}) = True
isAtomicHsExpr _ = False
instance Outputable (HsPragE (GhcPass p)) where
ppr (HsPragCore _ stc (StringLiteral sta s)) =
pprWithSourceText stc (text "{-# CORE")
<+> pprWithSourceText sta (doubleQuotes $ ftext s) <+> text "#-}"
ppr (HsPragSCC _ st (StringLiteral stl lbl)) =
pprWithSourceText st (text "{-# SCC")
-- no doublequotes if stl empty, for the case where the SCC was written
-- without quotes.
<+> pprWithSourceText stl (ftext lbl) <+> text "#-}"
ppr (HsPragTick _ st (StringLiteral sta s, (v1,v2), (v3,v4)) ((s1,s2),(s3,s4))) =
pprWithSourceText st (text "{-# GENERATED")
<+> pprWithSourceText sta (doubleQuotes $ ftext s)
<+> pprWithSourceText s1 (ppr v1) <+> char ':' <+> pprWithSourceText s2 (ppr v2)
<+> char '-'
<+> pprWithSourceText s3 (ppr v3) <+> char ':' <+> pprWithSourceText s4 (ppr v4)
<+> text "#-}"
ppr (XHsPragE x) = noExtCon x
{-
************************************************************************
* *
\subsection{Commands (in arrow abstractions)}
* *
************************************************************************
We re-use HsExpr to represent these.
-}
-- | Located Haskell Command (for arrow syntax)
type LHsCmd id = Located (HsCmd id)
-- | Haskell Command (e.g. a "statement" in an Arrow proc block)
data HsCmd id
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
-- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
-- 'ApiAnnotation.AnnRarrowtail'
-- For details on above see note [Api annotations] in ApiAnnotation
= HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
(XCmdArrApp id) -- type of the arrow expressions f,
-- of the form a t t', where arg :: t
(LHsExpr id) -- arrow expression, f
(LHsExpr id) -- input expression, arg
HsArrAppType -- higher-order (-<<) or first-order (-<)
Bool -- True => right-to-left (f -< arg)
-- False => left-to-right (arg >- f)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@,
-- 'ApiAnnotation.AnnCloseB' @'|)'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
(XCmdArrForm id)
(LHsExpr id) -- The operator.
-- After type-checking, a type abstraction to be
-- applied to the type of the local environment tuple
LexicalFixity -- Whether the operator appeared prefix or infix when
-- parsed.
(Maybe Fixity) -- fixity (filled in by the renamer), for forms that
-- were converted from OpApp's by the renamer
[LHsCmdTop id] -- argument commands
| HsCmdApp (XCmdApp id)
(LHsCmd id)
(LHsExpr id)
| HsCmdLam (XCmdLam id)
(MatchGroup id (LHsCmd id)) -- kappa
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnRarrow',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdPar (XCmdPar id)
(LHsCmd id) -- parenthesised command
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdCase (XCmdCase id)
(LHsExpr id)
(MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
-- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdIf (XCmdIf id)
(Maybe (SyntaxExpr id)) -- cond function
(LHsExpr id) -- predicate
(LHsCmd id) -- then part
(LHsCmd id) -- else part
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
-- 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnElse',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdLet (XCmdLet id)
(LHsLocalBinds id) -- let(rec)
(LHsCmd id)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
-- 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdDo (XCmdDo id) -- Type of the whole expression
(Located [CmdLStmt id])
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
-- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdWrap (XCmdWrap id)
HsWrapper
(HsCmd id) -- If cmd :: arg1 --> res
-- wrap :: arg1 "->" arg2
-- Then (HsCmdWrap wrap cmd) :: arg2 --> res
| XCmd (XXCmd id) -- Note [Trees that Grow] extension point
type instance XCmdArrApp GhcPs = NoExtField
type instance XCmdArrApp GhcRn = NoExtField
type instance XCmdArrApp GhcTc = Type
type instance XCmdArrForm (GhcPass _) = NoExtField
type instance XCmdApp (GhcPass _) = NoExtField
type instance XCmdLam (GhcPass _) = NoExtField
type instance XCmdPar (GhcPass _) = NoExtField
type instance XCmdCase (GhcPass _) = NoExtField
type instance XCmdIf (GhcPass _) = NoExtField
type instance XCmdLet (GhcPass _) = NoExtField
type instance XCmdDo GhcPs = NoExtField
type instance XCmdDo GhcRn = NoExtField
type instance XCmdDo GhcTc = Type
type instance XCmdWrap (GhcPass _) = NoExtField
type instance XXCmd (GhcPass _) = NoExtCon
-- | Haskell Array Application Type
data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
deriving Data
{- | Top-level command, introducing a new arrow.
This may occur inside a proc (where the stack is empty) or as an
argument of a command-forming operator.
-}
-- | Located Haskell Top-level Command
type LHsCmdTop p = Located (HsCmdTop p)
-- | Haskell Top-level Command
data HsCmdTop p
= HsCmdTop (XCmdTop p)
(LHsCmd p)
| XCmdTop (XXCmdTop p) -- Note [Trees that Grow] extension point
data CmdTopTc
= CmdTopTc Type -- Nested tuple of inputs on the command's stack
Type -- return type of the command
(CmdSyntaxTable GhcTc) -- See Note [CmdSyntaxTable]
type instance XCmdTop GhcPs = NoExtField
type instance XCmdTop GhcRn = CmdSyntaxTable GhcRn -- See Note [CmdSyntaxTable]
type instance XCmdTop GhcTc = CmdTopTc
type instance XXCmdTop (GhcPass _) = NoExtCon
instance (OutputableBndrId p) => Outputable (HsCmd (GhcPass p)) where
ppr cmd = pprCmd cmd
-----------------------
-- pprCmd and pprLCmd call pprDeeper;
-- the underscore versions do not
pprLCmd :: (OutputableBndrId p) => LHsCmd (GhcPass p) -> SDoc
pprLCmd (L _ c) = pprCmd c
pprCmd :: (OutputableBndrId p) => HsCmd (GhcPass p) -> SDoc
pprCmd c | isQuietHsCmd c = ppr_cmd c
| otherwise = pprDeeper (ppr_cmd c)
isQuietHsCmd :: HsCmd id -> Bool
-- Parentheses do display something, but it gives little info and
-- if we go deeper when we go inside them then we get ugly things
-- like (...)
isQuietHsCmd (HsCmdPar {}) = True
-- applications don't display anything themselves
isQuietHsCmd (HsCmdApp {}) = True
isQuietHsCmd _ = False
-----------------------
ppr_lcmd :: (OutputableBndrId p) => LHsCmd (GhcPass p) -> SDoc
ppr_lcmd c = ppr_cmd (unLoc c)
ppr_cmd :: forall p. (OutputableBndrId p) => HsCmd (GhcPass p) -> SDoc
ppr_cmd (HsCmdPar _ c) = parens (ppr_lcmd c)
ppr_cmd (HsCmdApp _ c e)
= let (fun, args) = collect_args c [e] in
hang (ppr_lcmd fun) 2 (sep (map ppr args))
where
collect_args (L _ (HsCmdApp _ fun arg)) args = collect_args fun (arg:args)
collect_args fun args = (fun, args)
ppr_cmd (HsCmdLam _ matches)
= pprMatches matches
ppr_cmd (HsCmdCase _ expr matches)
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
nest 2 (pprMatches matches) ]
ppr_cmd (HsCmdIf _ _ e ct ce)
= sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")],
nest 4 (ppr ct),
text "else",
nest 4 (ppr ce)]
-- special case: let ... in let ...
ppr_cmd (HsCmdLet _ (L _ binds) cmd@(L _ (HsCmdLet {})))
= sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
ppr_lcmd cmd]
ppr_cmd (HsCmdLet _ (L _ binds) cmd)
= sep [hang (text "let") 2 (pprBinds binds),
hang (text "in") 2 (ppr cmd)]
ppr_cmd (HsCmdDo _ (L _ stmts)) = pprDo ArrowExpr stmts
ppr_cmd (HsCmdWrap _ w cmd)
= pprHsWrapper w (\_ -> parens (ppr_cmd cmd))
ppr_cmd (HsCmdArrApp _ arrow arg HsFirstOrderApp True)
= hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
ppr_cmd (HsCmdArrApp _ arrow arg HsFirstOrderApp False)
= hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
ppr_cmd (HsCmdArrApp _ arrow arg HsHigherOrderApp True)
= hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
ppr_cmd (HsCmdArrApp _ arrow arg HsHigherOrderApp False)
= hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
ppr_cmd (HsCmdArrForm _ (L _ (HsVar _ (L _ v))) _ (Just _) [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm _ (L _ (HsVar _ (L _ v))) Infix _ [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm _ (L _ (HsConLikeOut _ c)) _ (Just _) [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm _ (L _ (HsConLikeOut _ c)) Infix _ [arg1, arg2])
= hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
, pprCmdArg (unLoc arg2)])
ppr_cmd (HsCmdArrForm _ op _ _ args)
= hang (text "(|" <+> ppr_lexpr op)
4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)")
ppr_cmd (XCmd x) = ppr x
pprCmdArg :: (OutputableBndrId p) => HsCmdTop (GhcPass p) -> SDoc
pprCmdArg (HsCmdTop _ cmd)
= ppr_lcmd cmd
pprCmdArg (XCmdTop x) = ppr x
instance (OutputableBndrId p) => Outputable (HsCmdTop (GhcPass p)) where
ppr = pprCmdArg
{-
************************************************************************
* *
\subsection{Record binds}
* *
************************************************************************
-}
-- | Haskell Record Bindings
type HsRecordBinds p = HsRecFields p (LHsExpr p)
{-
************************************************************************
* *
\subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
* *
************************************************************************
@Match@es are sets of pattern bindings and right hand sides for
functions, patterns or case branches. For example, if a function @g@
is defined as:
\begin{verbatim}
g (x,y) = y
g ((x:ys),y) = y+1,
\end{verbatim}
then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
It is always the case that each element of an @[Match]@ list has the
same number of @pats@s inside it. This corresponds to saying that
a function defined by pattern matching must have the same number of
patterns in each equation.
-}
data MatchGroup p body
= MG { mg_ext :: XMG p body -- Post-typechecker, types of args and result
, mg_alts :: Located [LMatch p body] -- The alternatives
, mg_origin :: Origin }
-- The type is the type of the entire group
-- t1 -> ... -> tn -> tr
-- where there are n patterns
| XMatchGroup (XXMatchGroup p body)
data MatchGroupTc
= MatchGroupTc
{ mg_arg_tys :: [Type] -- Types of the arguments, t1..tn
, mg_res_ty :: Type -- Type of the result, tr
} deriving Data
type instance XMG GhcPs b = NoExtField
type instance XMG GhcRn b = NoExtField
type instance XMG GhcTc b = MatchGroupTc
type instance XXMatchGroup (GhcPass _) b = NoExtCon
-- | Located Match
type LMatch id body = Located (Match id body)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
-- list
-- For details on above see note [Api annotations] in ApiAnnotation
data Match p body
= Match {
m_ext :: XCMatch p body,
m_ctxt :: HsMatchContext (NameOrRdrName (IdP p)),
-- See note [m_ctxt in Match]
m_pats :: [LPat p], -- The patterns
m_grhss :: (GRHSs p body)
}
| XMatch (XXMatch p body)
type instance XCMatch (GhcPass _) b = NoExtField
type instance XXMatch (GhcPass _) b = NoExtCon
instance (OutputableBndrId pr, Outputable body)
=> Outputable (Match (GhcPass pr) body) where
ppr = pprMatch
{-
Note [m_ctxt in Match]
~~~~~~~~~~~~~~~~~~~~~~
A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and
so on.
In order to simplify tooling processing and pretty print output, the provenance
is captured in an HsMatchContext.
This is particularly important for the API Annotations for a multi-equation
FunBind.
The parser initially creates a FunBind with a single Match in it for
every function definition it sees.
These are then grouped together by getMonoBind into a single FunBind,
where all the Matches are combined.
In the process, all the original FunBind fun_id's bar one are
discarded, including the locations.
This causes a problem for source to source conversions via API
Annotations, so the original fun_ids and infix flags are preserved in
the Match, when it originates from a FunBind.
Example infix function definition requiring individual API Annotations
(&&& ) [] [] = []
xs &&& [] = xs
( &&& ) [] ys = ys
-}
isInfixMatch :: Match id body -> Bool
isInfixMatch match = case m_ctxt match of
FunRhs {mc_fixity = Infix} -> True
_ -> False
isEmptyMatchGroup :: MatchGroup id body -> Bool
isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms
isEmptyMatchGroup (XMatchGroup {}) = False
-- | Is there only one RHS in this list of matches?
isSingletonMatchGroup :: [LMatch id body] -> Bool
isSingletonMatchGroup matches
| [L _ match] <- matches
, Match { m_grhss = GRHSs { grhssGRHSs = [_] } } <- match
= True
| otherwise
= False
matchGroupArity :: MatchGroup (GhcPass id) body -> Arity
-- Precondition: MatchGroup is non-empty
-- This is called before type checking, when mg_arg_tys is not set
matchGroupArity (MG { mg_alts = alts })
| L _ (alt1:_) <- alts = length (hsLMatchPats alt1)
| otherwise = panic "matchGroupArity"
matchGroupArity (XMatchGroup nec) = noExtCon nec
hsLMatchPats :: LMatch (GhcPass id) body -> [LPat (GhcPass id)]
hsLMatchPats (L _ (Match { m_pats = pats })) = pats
hsLMatchPats (L _ (XMatch nec)) = noExtCon nec
-- | Guarded Right-Hand Sides
--
-- GRHSs are used both for pattern bindings and for Matches
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
-- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
-- For details on above see note [Api annotations] in ApiAnnotation
data GRHSs p body
= GRHSs {
grhssExt :: XCGRHSs p body,
grhssGRHSs :: [LGRHS p body], -- ^ Guarded RHSs
grhssLocalBinds :: LHsLocalBinds p -- ^ The where clause
}
| XGRHSs (XXGRHSs p body)
type instance XCGRHSs (GhcPass _) b = NoExtField
type instance XXGRHSs (GhcPass _) b = NoExtCon
-- | Located Guarded Right-Hand Side
type LGRHS id body = Located (GRHS id body)
-- | Guarded Right Hand Side.
data GRHS p body = GRHS (XCGRHS p body)
[GuardLStmt p] -- Guards
body -- Right hand side
| XGRHS (XXGRHS p body)
type instance XCGRHS (GhcPass _) b = NoExtField
type instance XXGRHS (GhcPass _) b = NoExtCon
-- We know the list must have at least one @Match@ in it.
pprMatches :: (OutputableBndrId idR, Outputable body)
=> MatchGroup (GhcPass idR) body -> SDoc
pprMatches MG { mg_alts = matches }
= vcat (map pprMatch (map unLoc (unLoc matches)))
-- Don't print the type; it's only a place-holder before typechecking
pprMatches (XMatchGroup x) = ppr x
-- Exported to GHC.Hs.Binds, which can't see the defn of HsMatchContext
pprFunBind :: (OutputableBndrId idR, Outputable body)
=> MatchGroup (GhcPass idR) body -> SDoc
pprFunBind matches = pprMatches matches
-- Exported to GHC.Hs.Binds, which can't see the defn of HsMatchContext
pprPatBind :: forall bndr p body. (OutputableBndrId bndr,
OutputableBndrId p,
Outputable body)
=> LPat (GhcPass bndr) -> GRHSs (GhcPass p) body -> SDoc
pprPatBind pat (grhss)
= sep [ppr pat,
nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext (IdP (GhcPass p))) grhss)]
pprMatch :: (OutputableBndrId idR, Outputable body)
=> Match (GhcPass idR) body -> SDoc
pprMatch match
= sep [ sep (herald : map (nest 2 . pprParendLPat appPrec) other_pats)
, nest 2 (pprGRHSs ctxt (m_grhss match)) ]
where
ctxt = m_ctxt match
(herald, other_pats)
= case ctxt of
FunRhs {mc_fun=L _ fun, mc_fixity=fixity, mc_strictness=strictness}
| strictness == SrcStrict -> ASSERT(null $ m_pats match)
(char '!'<>pprPrefixOcc fun, m_pats match)
-- a strict variable binding
| fixity == Prefix -> (pprPrefixOcc fun, m_pats match)
-- f x y z = e
-- Not pprBndr; the AbsBinds will
-- have printed the signature
| null pats2 -> (pp_infix, [])
-- x &&& y = e
| otherwise -> (parens pp_infix, pats2)
-- (x &&& y) z = e
where
pp_infix = pprParendLPat opPrec pat1
<+> pprInfixOcc fun
<+> pprParendLPat opPrec pat2
LambdaExpr -> (char '\\', m_pats match)
_ -> if null (m_pats match)
then (empty, [])
else ASSERT2( null pats1, ppr ctxt $$ ppr pat1 $$ ppr pats1 )
(ppr pat1, []) -- No parens around the single pat
(pat1:pats1) = m_pats match
(pat2:pats2) = pats1
pprGRHSs :: (OutputableBndrId idR, Outputable body)
=> HsMatchContext idL -> GRHSs (GhcPass idR) body -> SDoc
pprGRHSs ctxt (GRHSs _ grhss (L _ binds))
= vcat (map (pprGRHS ctxt . unLoc) grhss)
-- Print the "where" even if the contents of the binds is empty. Only
-- EmptyLocalBinds means no "where" keyword
$$ ppUnless (eqEmptyLocalBinds binds)
(text "where" $$ nest 4 (pprBinds binds))
pprGRHSs _ (XGRHSs x) = ppr x
pprGRHS :: (OutputableBndrId idR, Outputable body)
=> HsMatchContext idL -> GRHS (GhcPass idR) body -> SDoc
pprGRHS ctxt (GRHS _ [] body)
= pp_rhs ctxt body
pprGRHS ctxt (GRHS _ guards body)
= sep [vbar <+> interpp'SP guards, pp_rhs ctxt body]
pprGRHS _ (XGRHS x) = ppr x
pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
{-
************************************************************************
* *
\subsection{Do stmts and list comprehensions}
* *
************************************************************************
-}
-- | Located @do@ block Statement
type LStmt id body = Located (StmtLR id id body)
-- | Located Statement with separate Left and Right id's
type LStmtLR idL idR body = Located (StmtLR idL idR body)
-- | @do@ block Statement
type Stmt id body = StmtLR id id body
-- | Command Located Statement
type CmdLStmt id = LStmt id (LHsCmd id)
-- | Command Statement
type CmdStmt id = Stmt id (LHsCmd id)
-- | Expression Located Statement
type ExprLStmt id = LStmt id (LHsExpr id)
-- | Expression Statement
type ExprStmt id = Stmt id (LHsExpr id)
-- | Guard Located Statement
type GuardLStmt id = LStmt id (LHsExpr id)
-- | Guard Statement
type GuardStmt id = Stmt id (LHsExpr id)
-- | Ghci Located Statement
type GhciLStmt id = LStmt id (LHsExpr id)
-- | Ghci Statement
type GhciStmt id = Stmt id (LHsExpr id)
-- The SyntaxExprs in here are used *only* for do-notation and monad
-- comprehensions, which have rebindable syntax. Otherwise they are unused.
-- | API Annotations when in qualifier lists or guards
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
-- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
-- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
-- For details on above see note [Api annotations] in ApiAnnotation
data StmtLR idL idR body -- body should always be (LHs**** idR)
= LastStmt -- Always the last Stmt in ListComp, MonadComp,
-- and (after the renamer, see GHC.Rename.Expr.checkLastStmt) DoExpr, MDoExpr
-- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
(XLastStmt idL idR body)
body
Bool -- True <=> return was stripped by ApplicativeDo
(SyntaxExpr idR) -- The return operator
-- The return operator is used only for MonadComp
-- For ListComp we use the baked-in 'return'
-- For DoExpr, MDoExpr, we don't apply a 'return' at all
-- See Note [Monad Comprehensions]
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| BindStmt (XBindStmt idL idR body) -- Post typechecking,
-- result type of the function passed to bind;
-- that is, S in (>>=) :: Q -> (R -> S) -> T
(LPat idL)
body
(SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts]
(SyntaxExpr idR) -- The fail operator
-- The fail operator is noSyntaxExpr
-- if the pattern match can't fail
-- | 'ApplicativeStmt' represents an applicative expression built with
-- '<$>' and '<*>'. It is generated by the renamer, and is desugared into the
-- appropriate applicative expression by the desugarer, but it is intended
-- to be invisible in error messages.
--
-- For full details, see Note [ApplicativeDo] in GHC.Rename.Expr
--
| ApplicativeStmt
(XApplicativeStmt idL idR body) -- Post typecheck, Type of the body
[ ( SyntaxExpr idR
, ApplicativeArg idL) ]
-- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
(Maybe (SyntaxExpr idR)) -- 'join', if necessary
| BodyStmt (XBodyStmt idL idR body) -- Post typecheck, element type
-- of the RHS (used for arrows)
body -- See Note [BodyStmt]
(SyntaxExpr idR) -- The (>>) operator
(SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
-- See notes [Monad Comprehensions]
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
-- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
-- For details on above see note [Api annotations] in ApiAnnotation
| LetStmt (XLetStmt idL idR body) (LHsLocalBindsLR idL idR)
-- ParStmts only occur in a list/monad comprehension
| ParStmt (XParStmt idL idR body) -- Post typecheck,
-- S in (>>=) :: Q -> (R -> S) -> T
[ParStmtBlock idL idR]
(HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
(SyntaxExpr idR) -- The `>>=` operator
-- See notes [Monad Comprehensions]
-- After renaming, the ids are the binders
-- bound by the stmts and used after themp
| TransStmt {
trS_ext :: XTransStmt idL idR body, -- Post typecheck,
-- R in (>>=) :: Q -> (R -> S) -> T
trS_form :: TransForm,
trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
-- which generates the tuples to be grouped
trS_bndrs :: [(IdP idR, IdP idR)], -- See Note [TransStmt binder map]
trS_using :: LHsExpr idR,
trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
-- Invariant: if trS_form = GroupBy, then grp_by = Just e
trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
-- the inner monad comprehensions
trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
-- Only for 'group' forms
-- Just a simple HsExpr, because it's
-- too polymorphic for tcSyntaxOp
} -- See Note [Monad Comprehensions]
-- Recursive statement (see Note [How RecStmt works] below)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
-- For details on above see note [Api annotations] in ApiAnnotation
| RecStmt
{ recS_ext :: XRecStmt idL idR body
, recS_stmts :: [LStmtLR idL idR body]
-- The next two fields are only valid after renaming
, recS_later_ids :: [IdP idR]
-- The ids are a subset of the variables bound by the
-- stmts that are used in stmts that follow the RecStmt
, recS_rec_ids :: [IdP idR]
-- Ditto, but these variables are the "recursive" ones,
-- that are used before they are bound in the stmts of
-- the RecStmt.
-- An Id can be in both groups
-- Both sets of Ids are (now) treated monomorphically
-- See Note [How RecStmt works] for why they are separate
-- Rebindable syntax
, recS_bind_fn :: SyntaxExpr idR -- The bind function
, recS_ret_fn :: SyntaxExpr idR -- The return function
, recS_mfix_fn :: SyntaxExpr idR -- The mfix function
}
| XStmtLR (XXStmtLR idL idR body)
-- Extra fields available post typechecking for RecStmt.
data RecStmtTc =
RecStmtTc
{ recS_bind_ty :: Type -- S in (>>=) :: Q -> (R -> S) -> T
, recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
, recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
-- with recS_later_ids and recS_rec_ids,
-- and are the expressions that should be
-- returned by the recursion.
-- They may not quite be the Ids themselves,
-- because the Id may be *polymorphic*, but
-- the returned thing has to be *monomorphic*,
-- so they may be type applications
, recS_ret_ty :: Type -- The type of
-- do { stmts; return (a,b,c) }
-- With rebindable syntax the type might not
-- be quite as simple as (m (tya, tyb, tyc)).
}
type instance XLastStmt (GhcPass _) (GhcPass _) b = NoExtField
type instance XBindStmt (GhcPass _) GhcPs b = NoExtField
type instance XBindStmt (GhcPass _) GhcRn b = NoExtField
type instance XBindStmt (GhcPass _) GhcTc b = Type
type instance XApplicativeStmt (GhcPass _) GhcPs b = NoExtField
type instance XApplicativeStmt (GhcPass _) GhcRn b = NoExtField
type instance XApplicativeStmt (GhcPass _) GhcTc b = Type
type instance XBodyStmt (GhcPass _) GhcPs b = NoExtField
type instance XBodyStmt (GhcPass _) GhcRn b = NoExtField
type instance XBodyStmt (GhcPass _) GhcTc b = Type
type instance XLetStmt (GhcPass _) (GhcPass _) b = NoExtField
type instance XParStmt (GhcPass _) GhcPs b = NoExtField
type instance XParStmt (GhcPass _) GhcRn b = NoExtField
type instance XParStmt (GhcPass _) GhcTc b = Type
type instance XTransStmt (GhcPass _) GhcPs b = NoExtField
type instance XTransStmt (GhcPass _) GhcRn b = NoExtField
type instance XTransStmt (GhcPass _) GhcTc b = Type
type instance XRecStmt (GhcPass _) GhcPs b = NoExtField
type instance XRecStmt (GhcPass _) GhcRn b = NoExtField
type instance XRecStmt (GhcPass _) GhcTc b = RecStmtTc
type instance XXStmtLR (GhcPass _) (GhcPass _) b = NoExtCon
data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
= ThenForm -- then f or then f by e (depending on trS_by)
| GroupForm -- then group using f or then group by e using f (depending on trS_by)
deriving Data
-- | Parenthesised Statement Block
data ParStmtBlock idL idR
= ParStmtBlock
(XParStmtBlock idL idR)
[ExprLStmt idL]
[IdP idR] -- The variables to be returned
(SyntaxExpr idR) -- The return operator
| XParStmtBlock (XXParStmtBlock idL idR)
type instance XParStmtBlock (GhcPass pL) (GhcPass pR) = NoExtField
type instance XXParStmtBlock (GhcPass pL) (GhcPass pR) = NoExtCon
-- | Applicative Argument
data ApplicativeArg idL
= ApplicativeArgOne -- A single statement (BindStmt or BodyStmt)
{ xarg_app_arg_one :: (XApplicativeArgOne idL)
, app_arg_pattern :: (LPat idL) -- WildPat if it was a BodyStmt (see below)
, arg_expr :: (LHsExpr idL)
, is_body_stmt :: Bool -- True <=> was a BodyStmt
-- False <=> was a BindStmt
-- See Note [Applicative BodyStmt]
, fail_operator :: (SyntaxExpr idL) -- The fail operator
-- The fail operator is needed if this is a BindStmt
-- where the pattern can fail. E.g.:
-- (Just a) <- stmt
-- The fail operator will be invoked if the pattern
-- match fails.
-- The fail operator is noSyntaxExpr
-- if the pattern match can't fail
}
| ApplicativeArgMany -- do { stmts; return vars }
{ xarg_app_arg_many :: (XApplicativeArgMany idL)
, app_stmts :: [ExprLStmt idL] -- stmts
, final_expr :: (HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn)
, bv_pattern :: (LPat idL) -- (v1,...,vn)
}
| XApplicativeArg (XXApplicativeArg idL)
type instance XApplicativeArgOne (GhcPass _) = NoExtField
type instance XApplicativeArgMany (GhcPass _) = NoExtField
type instance XXApplicativeArg (GhcPass _) = NoExtCon
{-
Note [The type of bind in Stmts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some Stmts, notably BindStmt, keep the (>>=) bind operator.
We do NOT assume that it has type
(>>=) :: m a -> (a -> m b) -> m b
In some cases (see #303, #1537) it might have a more
exotic type, such as
(>>=) :: m i j a -> (a -> m j k b) -> m i k b
So we must be careful not to make assumptions about the type.
In particular, the monad may not be uniform throughout.
Note [TransStmt binder map]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The [(idR,idR)] in a TransStmt behaves as follows:
* Before renaming: []
* After renaming:
[ (x27,x27), ..., (z35,z35) ]
These are the variables
bound by the stmts to the left of the 'group'
and used either in the 'by' clause,
or in the stmts following the 'group'
Each item is a pair of identical variables.
* After typechecking:
[ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
Each pair has the same unique, but different *types*.
Note [BodyStmt]
~~~~~~~~~~~~~~~
BodyStmts are a bit tricky, because what they mean
depends on the context. Consider the following contexts:
A do expression of type (m res_ty)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E any_ty: do { ....; E; ... }
E :: m any_ty
Translation: E >> ...
A list comprehensions of type [elt_ty]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E Bool: [ .. | .... E ]
[ .. | ..., E, ... ]
[ .. | .... | ..., E | ... ]
E :: Bool
Translation: if E then fail else ...
A guard list, guarding a RHS of type rhs_ty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
E :: Bool
Translation: if E then fail else ...
A monad comprehension of type (m res_ty)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E Bool: [ .. | .... E ]
E :: Bool
Translation: guard E >> ...
Array comprehensions are handled like list comprehensions.
Note [How RecStmt works]
~~~~~~~~~~~~~~~~~~~~~~~~
Example:
HsDo [ BindStmt x ex
, RecStmt { recS_rec_ids = [a, c]
, recS_stmts = [ BindStmt b (return (a,c))
, LetStmt a = ...b...
, BindStmt c ec ]
, recS_later_ids = [a, b]
, return (a b) ]
Here, the RecStmt binds a,b,c; but
- Only a,b are used in the stmts *following* the RecStmt,
- Only a,c are used in the stmts *inside* the RecStmt
*before* their bindings
Why do we need *both* rec_ids and later_ids? For monads they could be
combined into a single set of variables, but not for arrows. That
follows from the types of the respective feedback operators:
mfix :: MonadFix m => (a -> m a) -> m a
loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
* For mfix, the 'a' covers the union of the later_ids and the rec_ids
* For 'loop', 'c' is the later_ids and 'd' is the rec_ids
Note [Typing a RecStmt]
~~~~~~~~~~~~~~~~~~~~~~~
A (RecStmt stmts) types as if you had written
(v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
do { stmts
; return (v1,..vn, r1, ..., rm) })
where v1..vn are the later_ids
r1..rm are the rec_ids
Note [Monad Comprehensions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monad comprehensions require separate functions like 'return' and
'>>=' for desugaring. These functions are stored in the statements
used in monad comprehensions. For example, the 'return' of the 'LastStmt'
expression is used to lift the body of the monad comprehension:
[ body | stmts ]
=>
stmts >>= \bndrs -> return body
In transform and grouping statements ('then ..' and 'then group ..') the
'return' function is required for nested monad comprehensions, for example:
[ body | stmts, then f, rest ]
=>
f [ env | stmts ] >>= \bndrs -> [ body | rest ]
BodyStmts require the 'Control.Monad.guard' function for boolean
expressions:
[ body | exp, stmts ]
=>
guard exp >> [ body | stmts ]
Parallel statements require the 'Control.Monad.Zip.mzip' function:
[ body | stmts1 | stmts2 | .. ]
=>
mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
In any other context than 'MonadComp', the fields for most of these
'SyntaxExpr's stay bottom.
Note [Applicative BodyStmt]
(#12143) For the purposes of ApplicativeDo, we treat any BodyStmt
as if it was a BindStmt with a wildcard pattern. For example,
do
x <- A
B
return x
is transformed as if it were
do
x <- A
_ <- B
return x
so it transforms to
(\(x,_) -> x) <$> A <*> B
But we have to remember when we treat a BodyStmt like a BindStmt,
because in error messages we want to emit the original syntax the user
wrote, not our internal representation. So ApplicativeArgOne has a
Bool flag that is True when the original statement was a BodyStmt, so
that we can pretty-print it correctly.
-}
instance (Outputable (StmtLR idL idL (LHsExpr idL)),
Outputable (XXParStmtBlock idL idR))
=> Outputable (ParStmtBlock idL idR) where
ppr (ParStmtBlock _ stmts _ _) = interpp'SP stmts
ppr (XParStmtBlock x) = ppr x
instance (OutputableBndrId pl, OutputableBndrId pr,
Outputable body)
=> Outputable (StmtLR (GhcPass pl) (GhcPass pr) body) where
ppr stmt = pprStmt stmt
pprStmt :: forall idL idR body . (OutputableBndrId idL,
OutputableBndrId idR,
Outputable body)
=> (StmtLR (GhcPass idL) (GhcPass idR) body) -> SDoc
pprStmt (LastStmt _ expr ret_stripped _)
= whenPprDebug (text "[last]") <+>
(if ret_stripped then text "return" else empty) <+>
ppr expr
pprStmt (BindStmt _ pat expr _ _) = hsep [ppr pat, larrow, ppr expr]
pprStmt (LetStmt _ (L _ binds)) = hsep [text "let", pprBinds binds]
pprStmt (BodyStmt _ expr _ _) = ppr expr
pprStmt (ParStmt _ stmtss _ _) = sep (punctuate (text " | ") (map ppr stmtss))
pprStmt (TransStmt { trS_stmts = stmts, trS_by = by
, trS_using = using, trS_form = form })
= sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
, recS_later_ids = later_ids })
= text "rec" <+>
vcat [ ppr_do_stmts segment
, whenPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids
, text "later_ids=" <> ppr later_ids])]
pprStmt (ApplicativeStmt _ args mb_join)
= getPprStyle $ \style ->
if userStyle style
then pp_for_user
else pp_debug
where
-- make all the Applicative stuff invisible in error messages by
-- flattening the whole ApplicativeStmt nest back to a sequence
-- of statements.
pp_for_user = vcat $ concatMap flattenArg args
-- ppr directly rather than transforming here, because we need to
-- inject a "return" which is hard when we're polymorphic in the id
-- type.
flattenStmt :: ExprLStmt (GhcPass idL) -> [SDoc]
flattenStmt (L _ (ApplicativeStmt _ args _)) = concatMap flattenArg args
flattenStmt stmt = [ppr stmt]
flattenArg :: forall a . (a, ApplicativeArg (GhcPass idL)) -> [SDoc]
flattenArg (_, ApplicativeArgOne _ pat expr isBody _)
| isBody = -- See Note [Applicative BodyStmt]
[ppr (BodyStmt (panic "pprStmt") expr noSyntaxExpr noSyntaxExpr
:: ExprStmt (GhcPass idL))]
| otherwise =
[ppr (BindStmt (panic "pprStmt") pat expr noSyntaxExpr noSyntaxExpr
:: ExprStmt (GhcPass idL))]
flattenArg (_, ApplicativeArgMany _ stmts _ _) =
concatMap flattenStmt stmts
flattenArg (_, XApplicativeArg nec) = noExtCon nec
pp_debug =
let
ap_expr = sep (punctuate (text " |") (map pp_arg args))
in
if isNothing mb_join
then ap_expr
else text "join" <+> parens ap_expr
pp_arg :: (a, ApplicativeArg (GhcPass idL)) -> SDoc
pp_arg (_, ApplicativeArgOne _ pat expr isBody _)
| isBody = -- See Note [Applicative BodyStmt]
ppr (BodyStmt (panic "pprStmt") expr noSyntaxExpr noSyntaxExpr
:: ExprStmt (GhcPass idL))
| otherwise =
ppr (BindStmt (panic "pprStmt") pat expr noSyntaxExpr noSyntaxExpr
:: ExprStmt (GhcPass idL))
pp_arg (_, ApplicativeArgMany _ stmts return pat) =
ppr pat <+>
text "<-" <+>
ppr (HsDo (panic "pprStmt") DoExpr (noLoc
(stmts ++
[noLoc (LastStmt noExtField (noLoc return) False noSyntaxExpr)])))
pp_arg (_, XApplicativeArg x) = ppr x
pprStmt (XStmtLR x) = ppr x
pprTransformStmt :: (OutputableBndrId p)
=> [IdP (GhcPass p)] -> LHsExpr (GhcPass p)
-> Maybe (LHsExpr (GhcPass p)) -> SDoc
pprTransformStmt bndrs using by
= sep [ text "then" <+> whenPprDebug (braces (ppr bndrs))
, nest 2 (ppr using)
, nest 2 (pprBy by)]
pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
pprTransStmt by using ThenForm
= sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)]
pprTransStmt by using GroupForm
= sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
pprBy :: Outputable body => Maybe body -> SDoc
pprBy Nothing = empty
pprBy (Just e) = text "by" <+> ppr e
pprDo :: (OutputableBndrId p, Outputable body)
=> HsStmtContext any -> [LStmt (GhcPass p) body] -> SDoc
pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts
pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts
pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts
pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts
pprDo ListComp stmts = brackets $ pprComp stmts
pprDo MonadComp stmts = brackets $ pprComp stmts
pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
ppr_do_stmts :: (OutputableBndrId idL, OutputableBndrId idR,
Outputable body)
=> [LStmtLR (GhcPass idL) (GhcPass idR) body] -> SDoc
-- Print a bunch of do stmts
ppr_do_stmts stmts = pprDeeperList vcat (map ppr stmts)
pprComp :: (OutputableBndrId p, Outputable body)
=> [LStmt (GhcPass p) body] -> SDoc
pprComp quals -- Prints: body | qual1, ..., qualn
| Just (initStmts, L _ (LastStmt _ body _ _)) <- snocView quals
= if null initStmts
-- If there are no statements in a list comprehension besides the last
-- one, we simply treat it like a normal list. This does arise
-- occasionally in code that GHC generates, e.g., in implementations of
-- 'range' for derived 'Ix' instances for product datatypes with exactly
-- one constructor (e.g., see #12583).
then ppr body
else hang (ppr body <+> vbar) 2 (pprQuals initStmts)
| otherwise
= pprPanic "pprComp" (pprQuals quals)
pprQuals :: (OutputableBndrId p, Outputable body)
=> [LStmt (GhcPass p) body] -> SDoc
-- Show list comprehension qualifiers separated by commas
pprQuals quals = interpp'SP quals
{-
************************************************************************
* *
Template Haskell quotation brackets
* *
************************************************************************
-}
-- | Haskell Splice
data HsSplice id
= HsTypedSplice -- $$z or $$(f 4)
(XTypedSplice id)
SpliceDecoration -- Whether $$( ) variant found, for pretty printing
(IdP id) -- A unique name to identify this splice point
(LHsExpr id) -- See Note [Pending Splices]
| HsUntypedSplice -- $z or $(f 4)
(XUntypedSplice id)
SpliceDecoration -- Whether $( ) variant found, for pretty printing
(IdP id) -- A unique name to identify this splice point
(LHsExpr id) -- See Note [Pending Splices]
| HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice
(XQuasiQuote id)
(IdP id) -- Splice point
(IdP id) -- Quoter
SrcSpan -- The span of the enclosed string
FastString -- The enclosed string
-- AZ:TODO: use XSplice instead of HsSpliced
| HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in
-- GHC.Rename.Splice.
-- This is the result of splicing a splice. It is produced by
-- the renamer and consumed by the typechecker. It lives only
-- between the two.
(XSpliced id)
ThModFinalizers -- TH finalizers produced by the splice.
(HsSplicedThing id) -- The result of splicing
| HsSplicedT
DelayedSplice
| XSplice (XXSplice id) -- Note [Trees that Grow] extension point
type instance XTypedSplice (GhcPass _) = NoExtField
type instance XUntypedSplice (GhcPass _) = NoExtField
type instance XQuasiQuote (GhcPass _) = NoExtField
type instance XSpliced (GhcPass _) = NoExtField
type instance XXSplice (GhcPass _) = NoExtCon
-- | A splice can appear with various decorations wrapped around it. This data
-- type captures explicitly how it was originally written, for use in the pretty
-- printer.
data SpliceDecoration
= DollarSplice -- ^ $splice or $$splice
| BareSplice -- ^ bare splice
deriving (Data, Eq, Show)
instance Outputable SpliceDecoration where
ppr x = text $ show x
isTypedSplice :: HsSplice id -> Bool
isTypedSplice (HsTypedSplice {}) = True
isTypedSplice _ = False -- Quasi-quotes are untyped splices
-- | Finalizers produced by a splice with
-- 'Language.Haskell.TH.Syntax.addModFinalizer'
--
-- See Note [Delaying modFinalizers in untyped splices] in GHC.Rename.Splice. For how
-- this is used.
--
newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())]
-- A Data instance which ignores the argument of 'ThModFinalizers'.
instance Data ThModFinalizers where
gunfold _ z _ = z $ ThModFinalizers []
toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
-- See Note [Running typed splices in the zonker]
-- These are the arguments that are passed to `TcSplice.runTopSplice`
data DelayedSplice =
DelayedSplice
TcLclEnv -- The local environment to run the splice in
(LHsExpr GhcRn) -- The original renamed expression
TcType -- The result type of running the splice, unzonked
(LHsExpr GhcTcId) -- The typechecked expression to run and splice in the result
-- A Data instance which ignores the argument of 'DelayedSplice'.
instance Data DelayedSplice where
gunfold _ _ _ = panic "DelayedSplice"
toConstr a = mkConstr (dataTypeOf a) "DelayedSplice" [] Data.Prefix
dataTypeOf a = mkDataType "HsExpr.DelayedSplice" [toConstr a]
-- | Haskell Spliced Thing
--
-- Values that can result from running a splice.
data HsSplicedThing id
= HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression
| HsSplicedTy (HsType id) -- ^ Haskell Spliced Type
| HsSplicedPat (Pat id) -- ^ Haskell Spliced Pattern
-- See Note [Pending Splices]
type SplicePointName = Name
-- | Pending Renamer Splice
data PendingRnSplice
= PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr GhcRn)
data UntypedSpliceFlavour
= UntypedExpSplice
| UntypedPatSplice
| UntypedTypeSplice
| UntypedDeclSplice
deriving Data
-- | Pending Type-checker Splice
data PendingTcSplice
= PendingTcSplice SplicePointName (LHsExpr GhcTc)
{-
Note [Pending Splices]
~~~~~~~~~~~~~~~~~~~~~~
When we rename an untyped bracket, we name and lift out all the nested
splices, so that when the typechecker hits the bracket, it can
typecheck those nested splices without having to walk over the untyped
bracket code. So for example
[| f $(g x) |]
looks like
HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
which the renamer rewrites to
HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
[PendingRnSplice UntypedExpSplice sn (g x)]
* The 'sn' is the Name of the splice point, the SplicePointName
* The PendingRnExpSplice gives the splice that splice-point name maps to;
and the typechecker can now conveniently find these sub-expressions
* The other copy of the splice, in the second argument of HsSpliceE
in the renamed first arg of HsRnBracketOut
is used only for pretty printing
There are four varieties of pending splices generated by the renamer,
distinguished by their UntypedSpliceFlavour
* Pending expression splices (UntypedExpSplice), e.g.,
[|$(f x) + 2|]
UntypedExpSplice is also used for
* quasi-quotes, where the pending expression expands to
$(quoter "...blah...")
(see GHC.Rename.Splice.makePending, HsQuasiQuote case)
* cross-stage lifting, where the pending expression expands to
$(lift x)
(see GHC.Rename.Splice.checkCrossStageLifting)
* Pending pattern splices (UntypedPatSplice), e.g.,
[| \$(f x) -> x |]
* Pending type splices (UntypedTypeSplice), e.g.,
[| f :: $(g x) |]
* Pending declaration (UntypedDeclSplice), e.g.,
[| let $(f x) in ... |]
There is a fifth variety of pending splice, which is generated by the type
checker:
* Pending *typed* expression splices, (PendingTcSplice), e.g.,
[||1 + $$(f 2)||]
It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
output of the renamer. However, when pretty printing the output of the renamer,
e.g., in a type error message, we *do not* want to print out the pending
splices. In contrast, when pretty printing the output of the type checker, we
*do* want to print the pending splices. So splitting them up seems to make
sense, although I hate to add another constructor to HsExpr.
-}
instance OutputableBndrId p
=> Outputable (HsSplicedThing (GhcPass p)) where
ppr (HsSplicedExpr e) = ppr_expr e
ppr (HsSplicedTy t) = ppr t
ppr (HsSplicedPat p) = ppr p
instance (OutputableBndrId p) => Outputable (HsSplice (GhcPass p)) where
ppr s = pprSplice s
pprPendingSplice :: (OutputableBndrId p)
=> SplicePointName -> LHsExpr (GhcPass p) -> SDoc
pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr (stripParensHsExpr e))
pprSpliceDecl :: (OutputableBndrId p)
=> HsSplice (GhcPass p) -> SpliceExplicitFlag -> SDoc
pprSpliceDecl e@HsQuasiQuote{} _ = pprSplice e
pprSpliceDecl e ExplicitSplice = text "$" <> ppr_splice_decl e
pprSpliceDecl e ImplicitSplice = ppr_splice_decl e
ppr_splice_decl :: (OutputableBndrId p)
=> HsSplice (GhcPass p) -> SDoc
ppr_splice_decl (HsUntypedSplice _ _ n e) = ppr_splice empty n e empty
ppr_splice_decl e = pprSplice e
pprSplice :: (OutputableBndrId p) => HsSplice (GhcPass p) -> SDoc
pprSplice (HsTypedSplice _ DollarSplice n e)
= ppr_splice (text "$$") n e empty
pprSplice (HsTypedSplice _ BareSplice _ _ )
= panic "Bare typed splice" -- impossible
pprSplice (HsUntypedSplice _ DollarSplice n e)
= ppr_splice (text "$") n e empty
pprSplice (HsUntypedSplice _ BareSplice n e)
= ppr_splice empty n e empty
pprSplice (HsQuasiQuote _ n q _ s) = ppr_quasi n q s
pprSplice (HsSpliced _ _ thing) = ppr thing
pprSplice (HsSplicedT {}) = text "Unevaluated typed splice"
pprSplice (XSplice x) = ppr x
ppr_quasi :: OutputableBndr p => p -> p -> FastString -> SDoc
ppr_quasi n quoter quote = whenPprDebug (brackets (ppr n)) <>
char '[' <> ppr quoter <> vbar <>
ppr quote <> text "|]"
ppr_splice :: (OutputableBndrId p)
=> SDoc -> (IdP (GhcPass p)) -> LHsExpr (GhcPass p) -> SDoc -> SDoc
ppr_splice herald n e trail
= herald <> whenPprDebug (brackets (ppr n)) <> ppr e <> trail
-- | Haskell Bracket
data HsBracket p
= ExpBr (XExpBr p) (LHsExpr p) -- [| expr |]
| PatBr (XPatBr p) (LPat p) -- [p| pat |]
| DecBrL (XDecBrL p) [LHsDecl p] -- [d| decls |]; result of parser
| DecBrG (XDecBrG p) (HsGroup p) -- [d| decls |]; result of renamer
| TypBr (XTypBr p) (LHsType p) -- [t| type |]
| VarBr (XVarBr p) Bool (IdP p) -- True: 'x, False: ''T
-- (The Bool flag is used only in pprHsBracket)
| TExpBr (XTExpBr p) (LHsExpr p) -- [|| expr ||]
| XBracket (XXBracket p) -- Note [Trees that Grow] extension point
type instance XExpBr (GhcPass _) = NoExtField
type instance XPatBr (GhcPass _) = NoExtField
type instance XDecBrL (GhcPass _) = NoExtField
type instance XDecBrG (GhcPass _) = NoExtField
type instance XTypBr (GhcPass _) = NoExtField
type instance XVarBr (GhcPass _) = NoExtField
type instance XTExpBr (GhcPass _) = NoExtField
type instance XXBracket (GhcPass _) = NoExtCon
isTypedBracket :: HsBracket id -> Bool
isTypedBracket (TExpBr {}) = True
isTypedBracket _ = False
instance OutputableBndrId p
=> Outputable (HsBracket (GhcPass p)) where
ppr = pprHsBracket
pprHsBracket :: (OutputableBndrId p) => HsBracket (GhcPass p) -> SDoc
pprHsBracket (ExpBr _ e) = thBrackets empty (ppr e)
pprHsBracket (PatBr _ p) = thBrackets (char 'p') (ppr p)
pprHsBracket (DecBrG _ gp) = thBrackets (char 'd') (ppr gp)
pprHsBracket (DecBrL _ ds) = thBrackets (char 'd') (vcat (map ppr ds))
pprHsBracket (TypBr _ t) = thBrackets (char 't') (ppr t)
pprHsBracket (VarBr _ True n)
= char '\'' <> pprPrefixOcc n
pprHsBracket (VarBr _ False n)
= text "''" <> pprPrefixOcc n
pprHsBracket (TExpBr _ e) = thTyBrackets (ppr e)
pprHsBracket (XBracket e) = ppr e
thBrackets :: SDoc -> SDoc -> SDoc
thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+>
pp_body <+> text "|]"
thTyBrackets :: SDoc -> SDoc
thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]")
instance Outputable PendingRnSplice where
ppr (PendingRnSplice _ n e) = pprPendingSplice n e
instance Outputable PendingTcSplice where
ppr (PendingTcSplice n e) = pprPendingSplice n e
{-
************************************************************************
* *
\subsection{Enumerations and list comprehensions}
* *
************************************************************************
-}
-- | Arithmetic Sequence Information
data ArithSeqInfo id
= From (LHsExpr id)
| FromThen (LHsExpr id)
(LHsExpr id)
| FromTo (LHsExpr id)
(LHsExpr id)
| FromThenTo (LHsExpr id)
(LHsExpr id)
(LHsExpr id)
-- AZ: Should ArithSeqInfo have a TTG extension?
instance OutputableBndrId p
=> Outputable (ArithSeqInfo (GhcPass p)) where
ppr (From e1) = hcat [ppr e1, pp_dotdot]
ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
ppr (FromThenTo e1 e2 e3)
= hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
pp_dotdot :: SDoc
pp_dotdot = text " .. "
{-
************************************************************************
* *
\subsection{HsMatchCtxt}
* *
************************************************************************
-}
-- | Haskell Match Context
--
-- Context of a pattern match. This is more subtle than it would seem. See Note
-- [Varieties of pattern matches].
data HsMatchContext id -- Not an extensible tag
= FunRhs { mc_fun :: Located id -- ^ function binder of @f@
, mc_fixity :: LexicalFixity -- ^ fixing of @f@
, mc_strictness :: SrcStrictness -- ^ was @f@ banged?
-- See Note [FunBind vs PatBind]
}
-- ^A pattern matching on an argument of a
-- function binding
| LambdaExpr -- ^Patterns of a lambda
| CaseAlt -- ^Patterns and guards on a case alternative
| IfAlt -- ^Guards of a multi-way if alternative
| ProcExpr -- ^Patterns of a proc
| PatBindRhs -- ^A pattern binding eg [y] <- e = e
| PatBindGuards -- ^Guards of pattern bindings, e.g.,
-- (Just b) | Just _ <- x = e
-- | otherwise = e'
| RecUpd -- ^Record update [used only in DsExpr to
-- tell matchWrapper what sort of
-- runtime error message to generate]
| StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension,
-- pattern guard, etc
| ThPatSplice -- ^A Template Haskell pattern splice
| ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |]
| PatSyn -- ^A pattern synonym declaration
deriving Functor
deriving instance (Data id) => Data (HsMatchContext id)
instance OutputableBndr id => Outputable (HsMatchContext id) where
ppr m@(FunRhs{}) = text "FunRhs" <+> ppr (mc_fun m) <+> ppr (mc_fixity m)
ppr LambdaExpr = text "LambdaExpr"
ppr CaseAlt = text "CaseAlt"
ppr IfAlt = text "IfAlt"
ppr ProcExpr = text "ProcExpr"
ppr PatBindRhs = text "PatBindRhs"
ppr PatBindGuards = text "PatBindGuards"
ppr RecUpd = text "RecUpd"
ppr (StmtCtxt _) = text "StmtCtxt _"
ppr ThPatSplice = text "ThPatSplice"
ppr ThPatQuote = text "ThPatQuote"
ppr PatSyn = text "PatSyn"
isPatSynCtxt :: HsMatchContext id -> Bool
isPatSynCtxt ctxt =
case ctxt of
PatSyn -> True
_ -> False
-- | Haskell Statement Context. It expects to be parameterised with one of
-- 'RdrName', 'Name' or 'Id'
data HsStmtContext id
= ListComp
| MonadComp
| DoExpr -- ^do { ... }
| MDoExpr -- ^mdo { ... } ie recursive do-expression
| ArrowExpr -- ^do-notation in an arrow-command context
| GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs
| PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing
| ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt
| TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt
deriving Functor
deriving instance (Data id) => Data (HsStmtContext id)
isComprehensionContext :: HsStmtContext id -> Bool
-- Uses comprehension syntax [ e | quals ]
isComprehensionContext ListComp = True
isComprehensionContext MonadComp = True
isComprehensionContext (ParStmtCtxt c) = isComprehensionContext c
isComprehensionContext (TransStmtCtxt c) = isComprehensionContext c
isComprehensionContext _ = False
-- | Should pattern match failure in a 'HsStmtContext' be desugared using
-- 'MonadFail'?
isMonadFailStmtContext :: HsStmtContext id -> Bool
isMonadFailStmtContext MonadComp = True
isMonadFailStmtContext DoExpr = True
isMonadFailStmtContext MDoExpr = True
isMonadFailStmtContext GhciStmtCtxt = True
isMonadFailStmtContext (ParStmtCtxt ctxt) = isMonadFailStmtContext ctxt
isMonadFailStmtContext (TransStmtCtxt ctxt) = isMonadFailStmtContext ctxt
isMonadFailStmtContext _ = False -- ListComp, PatGuard, ArrowExpr
isMonadCompContext :: HsStmtContext id -> Bool
isMonadCompContext MonadComp = True
isMonadCompContext _ = False
matchSeparator :: HsMatchContext id -> SDoc
matchSeparator (FunRhs {}) = text "="
matchSeparator CaseAlt = text "->"
matchSeparator IfAlt = text "->"
matchSeparator LambdaExpr = text "->"
matchSeparator ProcExpr = text "->"
matchSeparator PatBindRhs = text "="
matchSeparator PatBindGuards = text "="
matchSeparator (StmtCtxt _) = text "<-"
matchSeparator RecUpd = text "=" -- This can be printed by the pattern
-- match checker trace
matchSeparator ThPatSplice = panic "unused"
matchSeparator ThPatQuote = panic "unused"
matchSeparator PatSyn = panic "unused"
pprMatchContext :: (Outputable (NameOrRdrName id),Outputable id)
=> HsMatchContext id -> SDoc
pprMatchContext ctxt
| want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
| otherwise = text "a" <+> pprMatchContextNoun ctxt
where
want_an (FunRhs {}) = True -- Use "an" in front
want_an ProcExpr = True
want_an _ = False
pprMatchContextNoun :: (Outputable (NameOrRdrName id),Outputable id)
=> HsMatchContext id -> SDoc
pprMatchContextNoun (FunRhs {mc_fun=L _ fun})
= text "equation for"
<+> quotes (ppr fun)
pprMatchContextNoun CaseAlt = text "case alternative"
pprMatchContextNoun IfAlt = text "multi-way if alternative"
pprMatchContextNoun RecUpd = text "record-update construct"
pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
pprMatchContextNoun PatBindRhs = text "pattern binding"
pprMatchContextNoun PatBindGuards = text "pattern binding guards"
pprMatchContextNoun LambdaExpr = text "lambda abstraction"
pprMatchContextNoun ProcExpr = text "arrow abstraction"
pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
$$ pprAStmtContext ctxt
pprMatchContextNoun PatSyn = text "pattern synonym declaration"
-----------------
pprAStmtContext, pprStmtContext :: (Outputable id,
Outputable (NameOrRdrName id))
=> HsStmtContext id -> SDoc
pprAStmtContext ctxt = article <+> pprStmtContext ctxt
where
pp_an = text "an"
pp_a = text "a"
article = case ctxt of
MDoExpr -> pp_an
GhciStmtCtxt -> pp_an
_ -> pp_a
-----------------
pprStmtContext GhciStmtCtxt = text "interactive GHCi command"
pprStmtContext DoExpr = text "'do' block"
pprStmtContext MDoExpr = text "'mdo' block"
pprStmtContext ArrowExpr = text "'do' block in an arrow command"
pprStmtContext ListComp = text "list comprehension"
pprStmtContext MonadComp = text "monad comprehension"
pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
-- Drop the inner contexts when reporting errors, else we get
-- Unexpected transform statement
-- in a transformed branch of
-- transformed branch of
-- transformed branch of monad comprehension
pprStmtContext (ParStmtCtxt c) =
ifPprDebug (sep [text "parallel branch of", pprAStmtContext c])
(pprStmtContext c)
pprStmtContext (TransStmtCtxt c) =
ifPprDebug (sep [text "transformed branch of", pprAStmtContext c])
(pprStmtContext c)
instance (Outputable (GhcPass p), Outputable (NameOrRdrName (GhcPass p)))
=> Outputable (HsStmtContext (GhcPass p)) where
ppr = pprStmtContext
-- Used to generate the string for a *runtime* error message
matchContextErrString :: Outputable id
=> HsMatchContext id -> SDoc
matchContextErrString (FunRhs{mc_fun=L _ fun}) = text "function" <+> ppr fun
matchContextErrString CaseAlt = text "case"
matchContextErrString IfAlt = text "multi-way if"
matchContextErrString PatBindRhs = text "pattern binding"
matchContextErrString PatBindGuards = text "pattern binding guards"
matchContextErrString RecUpd = text "record update"
matchContextErrString LambdaExpr = text "lambda"
matchContextErrString ProcExpr = text "proc"
matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard"
matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command"
matchContextErrString (StmtCtxt DoExpr) = text "'do' block"
matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block"
matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block"
matchContextErrString (StmtCtxt ListComp) = text "list comprehension"
matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension"
pprMatchInCtxt :: (OutputableBndrId idR,
-- TODO:AZ these constraints do not make sense
Outputable (NameOrRdrName (NameOrRdrName (IdP (GhcPass idR)))),
Outputable body)
=> Match (GhcPass idR) body -> SDoc
pprMatchInCtxt match = hang (text "In" <+> pprMatchContext (m_ctxt match)
<> colon)
4 (pprMatch match)
pprStmtInCtxt :: (OutputableBndrId idL,
OutputableBndrId idR,
Outputable body)
=> HsStmtContext (IdP (GhcPass idL))
-> StmtLR (GhcPass idL) (GhcPass idR) body
-> SDoc
pprStmtInCtxt ctxt (LastStmt _ e _ _)
| isComprehensionContext ctxt -- For [ e | .. ], do not mutter about "stmts"
= hang (text "In the expression:") 2 (ppr e)
pprStmtInCtxt ctxt stmt
= hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon)
2 (ppr_stmt stmt)
where
-- For Group and Transform Stmts, don't print the nested stmts!
ppr_stmt (TransStmt { trS_by = by, trS_using = using
, trS_form = form }) = pprTransStmt by using form
ppr_stmt stmt = pprStmt stmt
| sdiehl/ghc | compiler/GHC/Hs/Expr.hs | bsd-3-clause | 111,958 | 0 | 20 | 31,900 | 20,624 | 10,954 | 9,670 | 1,365 | 40 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Distributed.Process.ManagedProcess.Client
-- Copyright : (c) Tim Watson 2012 - 2013
-- License : BSD3 (see the file LICENSE)
--
-- Maintainer : Tim Watson <watson.timothy@gmail.com>
-- Stability : experimental
-- Portability : non-portable (requires concurrency)
--
-- The Client Portion of the /Managed Process/ API.
-----------------------------------------------------------------------------
module Control.Distributed.Process.ManagedProcess.Client
( -- * API for client interactions with the process
sendControlMessage
, shutdown
, call
, safeCall
, tryCall
, callTimeout
, flushPendingCalls
, callAsync
, cast
, callChan
, syncCallChan
, syncSafeCallChan
) where
import Control.Distributed.Process hiding (call)
import Control.Distributed.Process.Serializable
import Control.Distributed.Process.Async hiding (check)
import Control.Distributed.Process.ManagedProcess.Internal.Types
import qualified Control.Distributed.Process.ManagedProcess.Internal.Types as T
import Control.Distributed.Process.Extras hiding (monitor, sendChan)
import Control.Distributed.Process.Extras.Time
import Data.Maybe (fromJust)
import Prelude hiding (init)
-- | Send a control message over a 'ControlPort'.
--
sendControlMessage :: Serializable m => ControlPort m -> m -> Process ()
sendControlMessage cp m = sendChan (unPort cp) (CastMessage m)
-- | Send a signal instructing the process to terminate. The /receive loop/ which
-- manages the process mailbox will prioritise @Shutdown@ signals higher than
-- any other incoming messages, but the server might be busy (i.e., still in the
-- process of excuting a handler) at the time of sending however, so the caller
-- should not make any assumptions about the timeliness with which the shutdown
-- signal will be handled. If responsiveness is important, a better approach
-- might be to send an /exit signal/ with 'Shutdown' as the reason. An exit
-- signal will interrupt any operation currently underway and force the running
-- process to clean up and terminate.
shutdown :: ProcessId -> Process ()
shutdown pid = cast pid Shutdown
-- | Make a synchronous call - will block until a reply is received.
-- The calling process will exit with 'ExitReason' if the calls fails.
call :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> Process b
call sid msg = initCall sid msg >>= waitResponse Nothing >>= decodeResult
where decodeResult (Just (Right r)) = return r
decodeResult (Just (Left err)) = die err
decodeResult Nothing {- the impossible happened -} = terminate
-- | Safe version of 'call' that returns information about the error
-- if the operation fails. If an error occurs then the explanation will be
-- will be stashed away as @(ExitOther String)@.
safeCall :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> Process (Either ExitReason b)
safeCall s m = initCall s m >>= waitResponse Nothing >>= return . fromJust
-- | Version of 'safeCall' that returns 'Nothing' if the operation fails. If
-- you need information about *why* a call has failed then you should use
-- 'safeCall' or combine @catchExit@ and @call@ instead.
tryCall :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> Process (Maybe b)
tryCall s m = initCall s m >>= waitResponse Nothing >>= decodeResult
where decodeResult (Just (Right r)) = return $ Just r
decodeResult _ = return Nothing
-- | Make a synchronous call, but timeout and return @Nothing@ if a reply
-- is not received within the specified time interval.
--
-- If the result of the call is a failure (or the call was cancelled) then
-- the calling process will exit, with the 'ExitReason' given as the reason.
-- If the call times out however, the semantics on the server side are
-- undefined, i.e., the server may or may not successfully process the
-- request and may (or may not) send a response at a later time. From the
-- callers perspective, this is somewhat troublesome, since the call result
-- cannot be decoded directly. In this case, the 'flushPendingCalls' API /may/
-- be used to attempt to receive the message later on, however this makes
-- /no attempt whatsoever/ to guarantee /which/ call response will in fact
-- be returned to the caller. In those semantics are unsuited to your
-- application, you might choose to @exit@ or @die@ in case of a timeout,
-- or alternatively, use the 'callAsync' API and associated @waitTimeout@
-- function (in the /Async API/), which takes a re-usable handle on which
-- to wait (with timeouts) multiple times.
--
callTimeout :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> TimeInterval -> Process (Maybe b)
callTimeout s m d = initCall s m >>= waitResponse (Just d) >>= decodeResult
where decodeResult :: (Serializable b)
=> Maybe (Either ExitReason b)
-> Process (Maybe b)
decodeResult Nothing = return Nothing
decodeResult (Just (Right result)) = return $ Just result
decodeResult (Just (Left reason)) = die reason
flushPendingCalls :: forall b . (Serializable b)
=> TimeInterval
-> (b -> Process b)
-> Process (Maybe b)
flushPendingCalls d proc = do
receiveTimeout (asTimeout d) [
match (\(CallResponse (m :: b) _) -> proc m)
]
-- | Invokes 'call' /out of band/, and returns an /async handle/.
--
callAsync :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> Process (Async b)
callAsync server msg = async $ task $ call server msg
-- | Sends a /cast/ message to the server identified by @server@. The server
-- will not send a response. Like Cloud Haskell's 'send' primitive, cast is
-- fully asynchronous and /never fails/ - therefore 'cast'ing to a non-existent
-- (e.g., dead) server process will not generate an error.
--
cast :: forall a m . (Addressable a, Serializable m)
=> a -> m -> Process ()
cast server msg = sendTo server ((CastMessage msg) :: T.Message m ())
-- | Sends a /channel/ message to the server and returns a @ReceivePort@ on
-- which the reponse can be delivered, if the server so chooses (i.e., the
-- might ignore the request or crash).
callChan :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> Process (ReceivePort b)
callChan server msg = do
(sp, rp) <- newChan
sendTo server ((ChanMessage msg sp) :: T.Message a b)
return rp
-- | A synchronous version of 'callChan'.
syncCallChan :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> Process b
syncCallChan server msg = do
r <- syncSafeCallChan server msg
case r of
Left e -> die e
Right r' -> return r'
-- | A safe version of 'syncCallChan', which returns @Left ExitReason@ if the
-- call fails.
syncSafeCallChan :: forall s a b . (Addressable s, Serializable a, Serializable b)
=> s -> a -> Process (Either ExitReason b)
syncSafeCallChan server msg = do
rp <- callChan server msg
awaitResponse server [ matchChan rp (return . Right) ]
| qnikst/distributed-process-client-server | src/Control/Distributed/Process/ManagedProcess/Client.hs | bsd-3-clause | 7,433 | 0 | 15 | 1,543 | 1,356 | 742 | 614 | 83 | 3 |
module Main where
import Test.HUnit
import qualified System.CrawlerServiceTest (tests)
import qualified Unit.Model.CrawlerTest (tests)
import qualified Unit.Service.CrawlerServiceTest (tests)
main :: IO ()
main = runTestTT unitTests
>> runTestTT systemTests
>> return ()
unitTests = test [
"CrawlerTest" ~: Unit.Model.CrawlerTest.tests
,"CrawlerServiceTest" ~: Unit.Service.CrawlerServiceTest.tests
]
systemTests = test [
"CrawlerServiceTest" ~: System.CrawlerServiceTest.tests
] | ptek/sclent | tests/RunTests.hs | bsd-3-clause | 499 | 0 | 8 | 69 | 126 | 73 | 53 | 14 | 1 |
module HaskellTools.Types where
import Data.Vector (Vector)
import qualified Data.Text as T
data Repo = Repo
{ repoPackageName :: T.Text
, stars :: Integer
, forks :: Integer
, collaborators :: Integer
} deriving (Show, Eq)
type PackageRepos = (Vector (T.Text, T.Text, T.Text))
| diogob/haskell-tools | src/HaskellTools/Types.hs | bsd-3-clause | 291 | 0 | 9 | 55 | 97 | 60 | 37 | 10 | 0 |
import Text.ParserCombinators.Parsec
csvFile = endBy line eol
line = sepBy cell (char ',')
cell = many (noneOf ",\n\r")
{-- snippet eol --}
eol =
do char '\n'
char '\r' <|> return '\n'
{-- /snippet eol --}
parseCSV :: String -> Either ParseError [[String]]
parseCSV input = parse csvFile "(unknown)" input
| binesiyu/ifl | examples/ch16/csv5.hs | mit | 321 | 0 | 8 | 65 | 108 | 54 | 54 | 9 | 1 |
-- Tic-tac-toe example from chapter 11 of Programming in Haskell,
-- Graham Hutton, Cambridge University Press, 2016.
-- Basic declarations
import Data.Char
import Data.List
import System.IO
size :: Int
size = 3
type Grid = [[Player]]
data Player = O | B | X
deriving (Eq, Ord, Show)
next :: Player -> Player
next O = X
next B = B
next X = O
-- Grid utilities
empty :: Grid
empty = replicate size (replicate size B)
full :: Grid -> Bool
full = all (/= B) . concat
turn :: Grid -> Player
turn g = if os <= xs then O else X
where
os = length (filter (== O) ps)
xs = length (filter (== X) ps)
ps = concat g
wins :: Player -> Grid -> Bool
wins p g = any line (rows ++ cols ++ dias)
where
line = all (== p)
rows = g
cols = transpose g
dias = [diag g, diag (map reverse g)]
diag :: Grid -> [Player]
diag g = [g !! n !! n | n <- [0..size-1]]
won :: Grid -> Bool
won g = wins O g || wins X g
-- Displaying a grid
putGrid :: Grid -> IO ()
putGrid =
putStrLn . unlines . concat . interleave bar . map showRow
where bar = [replicate ((size*4)-1) '-']
showRow :: [Player] -> [String]
showRow = beside . interleave bar . map showPlayer
where
beside = foldr1 (zipWith (++))
bar = replicate 3 "|"
showPlayer :: Player -> [String]
showPlayer O = [" ", " O ", " "]
showPlayer B = [" ", " ", " "]
showPlayer X = [" ", " X ", " "]
interleave :: a -> [a] -> [a]
interleave x [] = []
interleave x [y] = [y]
interleave x (y:ys) = y : x : interleave x ys
-- Making a move
valid :: Grid -> Int -> Bool
valid g i = 0 <= i && i < size^2 && concat g !! i == B
move:: Grid -> Int -> Player -> [Grid]
move g i p =
if valid g i then [chop size (xs ++ [p] ++ ys)] else []
where (xs,B:ys) = splitAt i (concat g)
chop :: Int -> [a] -> [[a]]
chop n [] = []
chop n xs = take n xs : chop n (drop n xs)
-- Reading a natural number
getNat :: String -> IO Int
getNat prompt = do putStr prompt
xs <- getLine
if xs /= [] && all isDigit xs then
return (read xs)
else
do putStrLn "ERROR: Invalid number"
getNat prompt
-- Human vs human
tictactoe :: IO ()
tictactoe = run empty O
run :: Grid -> Player -> IO ()
run g p = do cls
goto (1,1)
putGrid g
run' g p
run' :: Grid -> Player -> IO ()
run' g p | wins O g = putStrLn "Player O wins!\n"
| wins X g = putStrLn "Player X wins!\n"
| full g = putStrLn "It's a draw!\n"
| otherwise =
do i <- getNat (prompt p)
case move g i p of
[] -> do putStrLn "ERROR: Invalid move"
run' g p
[g'] -> run g' (next p)
prompt :: Player -> String
prompt p = "Player " ++ show p ++ ", enter your move: "
cls :: IO ()
cls = putStr "\ESC[2J"
goto :: (Int,Int) -> IO ()
goto (x,y) = putStr ("\ESC[" ++ show y ++ ";" ++ show x ++ "H")
-- Game trees
data Tree a = Node a [Tree a]
deriving Show
gametree :: Grid -> Player -> Tree Grid
gametree g p = Node g [gametree g' (next p) | g' <- moves g p]
moves :: Grid -> Player -> [Grid]
moves g p | won g = []
| full g = []
| otherwise = concat [move g i p | i <- [0..((size^2)-1)]]
prune :: Int -> Tree a -> Tree a
prune 0 (Node x _) = Node x []
prune n (Node x ts) = Node x [prune (n-1) t | t <- ts]
depth :: Int
depth = 9
-- Minimax
minimax :: Tree Grid -> Tree (Grid,Player)
minimax (Node g [])
| wins O g = Node (g,O) []
| wins X g = Node (g,X) []
| otherwise = Node (g,B) []
minimax (Node g ts)
| turn g == O = Node (g, minimum ps) ts'
| turn g == X = Node (g, maximum ps) ts'
where
ts' = map minimax ts
ps = [p | Node (_,p) _ <- ts']
bestmove :: Grid -> Player -> Grid
bestmove g p = head [g' | Node (g',p') _ <- ts, p' == best]
where
tree = prune depth (gametree g p)
Node (_,best) ts = minimax tree
-- Human vs computer
main :: IO ()
main = do hSetBuffering stdout NoBuffering
play empty O
play :: Grid -> Player -> IO ()
play g p = do cls
goto (1,1)
putGrid g
play' g p
play' :: Grid -> Player -> IO ()
play' g p
| wins O g = putStrLn "Player O wins!\n"
| wins X g = putStrLn "Player X wins!\n"
| full g = putStrLn "It's a draw!\n"
| p == O = do i <- getNat (prompt p)
case move g i p of
[] -> do putStrLn "ERROR: Invalid move"
play' g p
[g'] -> play g' (next p)
| p == X = do putStr "Player X is thinking... "
(play $! (bestmove g p)) (next p)
| thalerjonathan/phd | coding/learning/haskell/grahambook/Code_Solutions/tictactoe.hs | gpl-3.0 | 4,990 | 0 | 14 | 1,848 | 2,213 | 1,111 | 1,102 | 133 | 2 |
module SigNoDef where
main :: IO ()
| roberth/uu-helium | test/staticerrors/SigNoDef.hs | gpl-3.0 | 38 | 0 | 6 | 9 | 14 | 8 | 6 | 2 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module CO4.Example.LPOSL
where
import Language.Haskell.TH (runIO)
import qualified Satchmo.Core.SAT.Minisat
import qualified Satchmo.Core.Decode
import CO4
import CO4.Util (bitWidth)
import CO4.Prelude
import CO4.Example.LPOSLStandalone
$( compileFile [Cache,ImportPrelude] "test/CO4/Example/LPOSLStandalone.hs" )
parameter :: (Trs, [Sigma])
allocator :: TAllocator (Precedence, Interpretation)
(parameter, allocator) =
let funSym@ [tSym,pSym,fSym,gSym,aSym] = map nat [0 .. 4]
arities = [ 2 , 2 , 1 , 2 , 0 ]
varSym@[xSym,ySym,zSym] = map nat [0 .. 2]
t a b = Node tSym [a,b]
p a b = Node pSym [a,b]
f a = Node fSym [a]
g a b = Node gSym [a,b]
a = Node aSym []
x = Var xSym
y = Var ySym
z = Var zSym
trs = [ (t (t x y) z , t x (t y z))
, (t (p x y) z , p (t x z) (t y z))
, (t x (p y (f z)), t (g x z) (p y a)) ]
carrierSize = 2
carrier = map nat [0 .. (carrierSize - 1)]
argumentAllocs arity = map allocatorList
$ sequence
$ replicate arity
$ map fromKnown carrier
assignments = map (zip varSym)
$ sequence
$ replicate (length varSym) carrier
precWidth = 3
precAlloc = allocatorList
$ concatMap (\(sym,arity) ->
map (\a -> knownTuple2 (knownTuple2 (fromKnown sym) a) (uNat precWidth))
$ argumentAllocs arity
)
$ zip funSym arities
interAlloc = allocatorList
$ map (\(sym,arity) ->
knownTuple2 (fromKnown sym)
$ allocatorList
$ map (\a -> knownTuple2 a (uNat $ fromInteger carrierSize))
$ argumentAllocs arity
)
$ zip funSym arities
in
((trs, assignments), knownTuple2 precAlloc interAlloc)
result = solveAndTestP parameter allocator encConstraint constraint
{-
result = do
r <- solveAndTestP parameter allocator encConstraint constraint
case r of
Nothing -> return ()
Just (p,i) -> do
let ltrs = labelledTrs i (snd parameter) (fst parameter)
putStrLn $ showTrs showTerm $ fst parameter
putStrLn $ showInterpretation i
putStrLn $ showTrs showLTerm ltrs
putStrLn $ showPrec p
showTrs showT = unlines . map (\(lhs,rhs) -> unwords [ showT lhs, "->", showT rhs ])
showTerm t = case t of Var v -> showVarSym v
Node f ts -> unwords [showFunSym f, "(", unwords $ map showTerm ts, ")"]
showLTerm t = case t of LVar v -> showVarSym v
LNode f l ts -> unwords [showFunSym f, showArgs l
, "(", unwords $ map showLTerm ts, ")"]
showVarSym v = case value v of 0 -> "x"
1 -> "y"
2 -> "z"
showFunSym f = case value f of 0 -> "t"
1 -> "p"
2 -> "f"
3 -> "g"
4 -> "a"
showInterpretation = unlines . map (\(s,f) -> showFunction s f)
showArgs args = unwords ["[", unwords $ map (show . value) args, "]"]
showFunction s = unlines . map (\(args,r) -> unwords [ showFunSym s, showArgs args, show $ value r ])
showPrec = unlines . map (\((s,l),p) -> unwords [showFunSym s, showArgs l, ": ", show $ value p])
-}
| abau/co4 | test/CO4/Example/LPOSL.hs | gpl-3.0 | 3,823 | 0 | 22 | 1,461 | 749 | 406 | 343 | 55 | 1 |
module ExportShowInstance2 where
data A = MkA Int deriving Show
| roberth/uu-helium | test/make/ExportShowInstance2.hs | gpl-3.0 | 66 | 0 | 6 | 12 | 16 | 10 | 6 | 2 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.StorageGateway.DescribeBandwidthRateLimit
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation returns the bandwidth rate limits of a gateway. By
-- default, these limits are not set, which means no bandwidth rate
-- limiting is in effect.
--
-- This operation only returns a value for a bandwidth rate limit only if
-- the limit is set. If no limits are set for the gateway, then this
-- operation returns only the gateway ARN in the response body. To specify
-- which gateway to describe, use the Amazon Resource Name (ARN) of the
-- gateway in your request.
--
-- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeBandwidthRateLimit.html AWS API Reference> for DescribeBandwidthRateLimit.
module Network.AWS.StorageGateway.DescribeBandwidthRateLimit
(
-- * Creating a Request
describeBandwidthRateLimit
, DescribeBandwidthRateLimit
-- * Request Lenses
, dbrlGatewayARN
-- * Destructuring the Response
, describeBandwidthRateLimitResponse
, DescribeBandwidthRateLimitResponse
-- * Response Lenses
, dbrlrsGatewayARN
, dbrlrsAverageUploadRateLimitInBitsPerSec
, dbrlrsAverageDownloadRateLimitInBitsPerSec
, dbrlrsResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.StorageGateway.Types
import Network.AWS.StorageGateway.Types.Product
-- | A JSON object containing the of the gateway.
--
-- /See:/ 'describeBandwidthRateLimit' smart constructor.
newtype DescribeBandwidthRateLimit = DescribeBandwidthRateLimit'
{ _dbrlGatewayARN :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeBandwidthRateLimit' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dbrlGatewayARN'
describeBandwidthRateLimit
:: Text -- ^ 'dbrlGatewayARN'
-> DescribeBandwidthRateLimit
describeBandwidthRateLimit pGatewayARN_ =
DescribeBandwidthRateLimit'
{ _dbrlGatewayARN = pGatewayARN_
}
-- | Undocumented member.
dbrlGatewayARN :: Lens' DescribeBandwidthRateLimit Text
dbrlGatewayARN = lens _dbrlGatewayARN (\ s a -> s{_dbrlGatewayARN = a});
instance AWSRequest DescribeBandwidthRateLimit where
type Rs DescribeBandwidthRateLimit =
DescribeBandwidthRateLimitResponse
request = postJSON storageGateway
response
= receiveJSON
(\ s h x ->
DescribeBandwidthRateLimitResponse' <$>
(x .?> "GatewayARN") <*>
(x .?> "AverageUploadRateLimitInBitsPerSec")
<*> (x .?> "AverageDownloadRateLimitInBitsPerSec")
<*> (pure (fromEnum s)))
instance ToHeaders DescribeBandwidthRateLimit where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("StorageGateway_20130630.DescribeBandwidthRateLimit"
:: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON DescribeBandwidthRateLimit where
toJSON DescribeBandwidthRateLimit'{..}
= object
(catMaybes [Just ("GatewayARN" .= _dbrlGatewayARN)])
instance ToPath DescribeBandwidthRateLimit where
toPath = const "/"
instance ToQuery DescribeBandwidthRateLimit where
toQuery = const mempty
-- | A JSON object containing the following fields:
--
-- /See:/ 'describeBandwidthRateLimitResponse' smart constructor.
data DescribeBandwidthRateLimitResponse = DescribeBandwidthRateLimitResponse'
{ _dbrlrsGatewayARN :: !(Maybe Text)
, _dbrlrsAverageUploadRateLimitInBitsPerSec :: !(Maybe Nat)
, _dbrlrsAverageDownloadRateLimitInBitsPerSec :: !(Maybe Nat)
, _dbrlrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeBandwidthRateLimitResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dbrlrsGatewayARN'
--
-- * 'dbrlrsAverageUploadRateLimitInBitsPerSec'
--
-- * 'dbrlrsAverageDownloadRateLimitInBitsPerSec'
--
-- * 'dbrlrsResponseStatus'
describeBandwidthRateLimitResponse
:: Int -- ^ 'dbrlrsResponseStatus'
-> DescribeBandwidthRateLimitResponse
describeBandwidthRateLimitResponse pResponseStatus_ =
DescribeBandwidthRateLimitResponse'
{ _dbrlrsGatewayARN = Nothing
, _dbrlrsAverageUploadRateLimitInBitsPerSec = Nothing
, _dbrlrsAverageDownloadRateLimitInBitsPerSec = Nothing
, _dbrlrsResponseStatus = pResponseStatus_
}
-- | Undocumented member.
dbrlrsGatewayARN :: Lens' DescribeBandwidthRateLimitResponse (Maybe Text)
dbrlrsGatewayARN = lens _dbrlrsGatewayARN (\ s a -> s{_dbrlrsGatewayARN = a});
-- | The average upload bandwidth rate limit in bits per second. This field
-- does not appear in the response if the upload rate limit is not set.
dbrlrsAverageUploadRateLimitInBitsPerSec :: Lens' DescribeBandwidthRateLimitResponse (Maybe Natural)
dbrlrsAverageUploadRateLimitInBitsPerSec = lens _dbrlrsAverageUploadRateLimitInBitsPerSec (\ s a -> s{_dbrlrsAverageUploadRateLimitInBitsPerSec = a}) . mapping _Nat;
-- | The average download bandwidth rate limit in bits per second. This field
-- does not appear in the response if the download rate limit is not set.
dbrlrsAverageDownloadRateLimitInBitsPerSec :: Lens' DescribeBandwidthRateLimitResponse (Maybe Natural)
dbrlrsAverageDownloadRateLimitInBitsPerSec = lens _dbrlrsAverageDownloadRateLimitInBitsPerSec (\ s a -> s{_dbrlrsAverageDownloadRateLimitInBitsPerSec = a}) . mapping _Nat;
-- | The response status code.
dbrlrsResponseStatus :: Lens' DescribeBandwidthRateLimitResponse Int
dbrlrsResponseStatus = lens _dbrlrsResponseStatus (\ s a -> s{_dbrlrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-storagegateway/gen/Network/AWS/StorageGateway/DescribeBandwidthRateLimit.hs | mpl-2.0 | 6,635 | 0 | 14 | 1,299 | 768 | 458 | 310 | 95 | 1 |
{-# LANGUAGE RecordWildCards, FlexibleInstances, MultiParamTypeClasses #-}
module Network.MQTT.EncoderSpec (spec) where
import Network.MQTT.Packet
import Network.MQTT.Encoder ( encodePacket )
import Network.MQTT.Parser ( parsePacket )
import Test.SmallCheck.Series ( (<~>), Serial, decDepth , getNonEmpty, series )
import Test.SmallCheck ( (==>) )
import Test.Hspec
import Test.Hspec.SmallCheck ( property )
import Test.SmallCheck.Series.Instances ()
import Data.Attoparsec.ByteString ( parseOnly )
import Data.ByteString.Builder ( toLazyByteString )
import Data.ByteString.Lazy ( toStrict )
import qualified Data.Text as T
import qualified Data.ByteString as BS
import Data.Maybe ( isJust, isNothing )
spec :: Spec
spec = do
describe "Parser-Encoder" $ do
it "parsePacket . encodePacket = id" $ property $ \p ->
let bytes = toStrict . toLazyByteString $ encodePacket p
in valid p ==> parseOnly parsePacket bytes == Right p
describe "Encoder" $ do
let shouldBeEncodedAs p bytes =
(toStrict . toLazyByteString . encodePacket) p `shouldBe` BS.pack bytes
it "should encode packet having a big payload" $ do
let bigPayload = replicate 121 0xab
PUBLISH PublishPacket{ publishDup = True
, publishMessage = Message
(TopicName $ T.pack "a/b")
(BS.pack bigPayload)
QoS2
True
, publishPacketIdentifier = Just (PacketIdentifier 10)
}
`shouldBeEncodedAs` ([0x3d, 0x80, 0x01, 0x00, 0x03, 0x61, 0x2f, 0x62, 0x00, 0x0a] ++ bigPayload)
valid :: Packet -> Bool
valid packet = case packet of
CONNACK ConnackPacket{..} -> not (connackReturnCode /= Accepted && connackSessionPresent)
PUBLISH PublishPacket{..} ->
not ((messageQoS publishMessage /= QoS0 && isNothing publishPacketIdentifier) ||
(messageQoS publishMessage == QoS0 && (publishDup || isJust publishPacketIdentifier)))
CONNECT ConnectPacket{..} -> not (isNothing connectUserName && isJust connectPassword)
_ -> True
instance Monad m => Serial m Packet
instance Monad m => Serial m ConnectPacket where
series = ConnectPacket <$> decDepth (decDepth series)
<~> decDepth (decDepth (decDepth series))
<~> series
<~> decDepth series
<~> decDepth series
<~> decDepth (decDepth (decDepth series))
<~> decDepth (decDepth (decDepth series))
instance Monad m => Serial m ConnackPacket
instance Monad m => Serial m PublishPacket
instance Monad m => Serial m PubackPacket
instance Monad m => Serial m PubrecPacket
instance Monad m => Serial m PubrelPacket
instance Monad m => Serial m PubcompPacket
instance Monad m => Serial m SubscribePacket where
series = SubscribePacket <$> series <~> (getNonEmpty <$> series)
instance Monad m => Serial m SubackPacket where
series = SubackPacket <$> series <~> (getNonEmpty <$> series)
instance Monad m => Serial m UnsubscribePacket where
series = UnsubscribePacket <$> series <~> (getNonEmpty <$> series)
instance Monad m => Serial m UnsubackPacket
instance Monad m => Serial m PingreqPacket
instance Monad m => Serial m PingrespPacket
instance Monad m => Serial m DisconnectPacket
instance Monad m => Serial m ConnackReturnCode
instance Monad m => Serial m Message
instance Monad m => Serial m QoS
instance Monad m => Serial m ClientIdentifier
instance Monad m => Serial m PacketIdentifier
instance Monad m => Serial m UserName
instance Monad m => Serial m Password
instance Monad m => Serial m TopicName where
series = TopicName <$> (T.pack . getNonEmpty) <$> series
instance Monad m => Serial m TopicFilter where
series = TopicFilter <$> (T.pack . getNonEmpty) <$> series
| rasendubi/arachne | test/Network/MQTT/EncoderSpec.hs | bsd-3-clause | 4,311 | 0 | 21 | 1,357 | 1,166 | 590 | 576 | 79 | 4 |
module Challenger.Ident where
-- $Id$
data Ident = Ident {aufgabe :: Int } deriving (Show, Read)
showIdentForDatei :: Ident -> String
showIdentForDatei i = show (aufgabe i)
| florianpilz/autotool | src/Challenger/Ident.hs | gpl-2.0 | 182 | 0 | 8 | 36 | 59 | 33 | 26 | 4 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PolyKinds #-}
{-| This module is an internal GHC module. It declares the constants used
in the implementation of type-level natural numbers. The programmer interface
for working with type-level naturals should be defined in a separate library.
@since 4.6.0.0
-}
module GHC.TypeLits
( -- * Kinds
Nat, Symbol -- Both declared in GHC.Types in package ghc-prim
-- * Linking type and value level
, N.KnownNat, natVal, natVal'
, KnownSymbol, symbolVal, symbolVal'
, N.SomeNat(..), SomeSymbol(..)
, someNatVal, someSymbolVal
, N.sameNat, sameSymbol
-- * Functions on type literals
, type (N.<=), type (N.<=?), type (N.+), type (N.*), type (N.^), type (N.-)
, type N.Div, type N.Mod, type N.Log2
, AppendSymbol
, N.CmpNat, CmpSymbol
-- * User-defined type errors
, TypeError
, ErrorMessage(..)
) where
import GHC.Base(Eq(..), Ord(..), Ordering(..), otherwise)
import GHC.Types( Nat, Symbol )
import GHC.Num(Integer, fromInteger)
import GHC.Base(String)
import GHC.Show(Show(..))
import GHC.Read(Read(..))
import GHC.Real(toInteger)
import GHC.Prim(magicDict, Proxy#)
import Data.Maybe(Maybe(..))
import Data.Proxy (Proxy(..))
import Data.Type.Equality((:~:)(Refl))
import Unsafe.Coerce(unsafeCoerce)
import GHC.TypeNats (KnownNat)
import qualified GHC.TypeNats as N
--------------------------------------------------------------------------------
-- | This class gives the string associated with a type-level symbol.
-- There are instances of the class for every concrete literal: "hello", etc.
--
-- @since 4.7.0.0
class KnownSymbol (n :: Symbol) where
symbolSing :: SSymbol n
-- | @since 4.7.0.0
natVal :: forall n proxy. KnownNat n => proxy n -> Integer
natVal p = toInteger (N.natVal p)
-- | @since 4.7.0.0
symbolVal :: forall n proxy. KnownSymbol n => proxy n -> String
symbolVal _ = case symbolSing :: SSymbol n of
SSymbol x -> x
-- | @since 4.8.0.0
natVal' :: forall n. KnownNat n => Proxy# n -> Integer
natVal' p = toInteger (N.natVal' p)
-- | @since 4.8.0.0
symbolVal' :: forall n. KnownSymbol n => Proxy# n -> String
symbolVal' _ = case symbolSing :: SSymbol n of
SSymbol x -> x
-- | This type represents unknown type-level symbols.
data SomeSymbol = forall n. KnownSymbol n => SomeSymbol (Proxy n)
-- ^ @since 4.7.0.0
-- | Convert an integer into an unknown type-level natural.
--
-- @since 4.7.0.0
someNatVal :: Integer -> Maybe N.SomeNat
someNatVal n
| n >= 0 = Just (N.someNatVal (fromInteger n))
| otherwise = Nothing
-- | Convert a string into an unknown type-level symbol.
--
-- @since 4.7.0.0
someSymbolVal :: String -> SomeSymbol
someSymbolVal n = withSSymbol SomeSymbol (SSymbol n) Proxy
-- | @since 4.7.0.0
instance Eq SomeSymbol where
SomeSymbol x == SomeSymbol y = symbolVal x == symbolVal y
-- | @since 4.7.0.0
instance Ord SomeSymbol where
compare (SomeSymbol x) (SomeSymbol y) = compare (symbolVal x) (symbolVal y)
-- | @since 4.7.0.0
instance Show SomeSymbol where
showsPrec p (SomeSymbol x) = showsPrec p (symbolVal x)
-- | @since 4.7.0.0
instance Read SomeSymbol where
readsPrec p xs = [ (someSymbolVal a, ys) | (a,ys) <- readsPrec p xs ]
--------------------------------------------------------------------------------
-- | Comparison of type-level symbols, as a function.
--
-- @since 4.7.0.0
type family CmpSymbol (m :: Symbol) (n :: Symbol) :: Ordering
-- | Concatenation of type-level symbols.
--
-- @since 4.10.0.0
type family AppendSymbol (m ::Symbol) (n :: Symbol) :: Symbol
-- | A description of a custom type error.
data {-kind-} ErrorMessage = Text Symbol
-- ^ Show the text as is.
| forall t. ShowType t
-- ^ Pretty print the type.
-- @ShowType :: k -> ErrorMessage@
| ErrorMessage :<>: ErrorMessage
-- ^ Put two pieces of error message next
-- to each other.
| ErrorMessage :$$: ErrorMessage
-- ^ Stack two pieces of error message on top
-- of each other.
infixl 5 :$$:
infixl 6 :<>:
-- | The type-level equivalent of 'error'.
--
-- The polymorphic kind of this type allows it to be used in several settings.
-- For instance, it can be used as a constraint, e.g. to provide a better error
-- message for a non-existent instance,
--
-- @
-- -- in a context
-- instance TypeError (Text "Cannot 'Show' functions." :$$:
-- Text "Perhaps there is a missing argument?")
-- => Show (a -> b) where
-- showsPrec = error "unreachable"
-- @
--
-- It can also be placed on the right-hand side of a type-level function
-- to provide an error for an invalid case,
--
-- @
-- type family ByteSize x where
-- ByteSize Word16 = 2
-- ByteSize Word8 = 1
-- ByteSize a = TypeError (Text "The type " :<>: ShowType a :<>:
-- Text " is not exportable.")
-- @
--
-- @since 4.9.0.0
type family TypeError (a :: ErrorMessage) :: b where
--------------------------------------------------------------------------------
-- | We either get evidence that this function was instantiated with the
-- same type-level symbols, or 'Nothing'.
--
-- @since 4.7.0.0
sameSymbol :: (KnownSymbol a, KnownSymbol b) =>
Proxy a -> Proxy b -> Maybe (a :~: b)
sameSymbol x y
| symbolVal x == symbolVal y = Just (unsafeCoerce Refl)
| otherwise = Nothing
--------------------------------------------------------------------------------
-- PRIVATE:
newtype SSymbol (s :: Symbol) = SSymbol String
data WrapS a b = WrapS (KnownSymbol a => Proxy a -> b)
-- See Note [magicDictId magic] in "basicType/MkId.hs"
withSSymbol :: (KnownSymbol a => Proxy a -> b)
-> SSymbol a -> Proxy a -> b
withSSymbol f x y = magicDict (WrapS f) x y
| ezyang/ghc | libraries/base/GHC/TypeLits.hs | bsd-3-clause | 6,427 | 2 | 10 | 1,504 | 1,231 | 724 | 507 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module T12522b where
import Data.Kind (Type)
newtype I a = I a
type family Curry (as :: [Type]) b = f | f -> as b where
Curry '[] b = I b
Curry (a:as) b = a -> Curry as b
data Uncurried (as :: [Type]) b
def :: Curry as b -> Uncurried as b
def = undefined
-- test2 :: Uncurried [Bool, Bool] Bool
test2 = def $ \a b -> I $ a && b
| sdiehl/ghc | testsuite/tests/indexed-types/should_compile/T12522b.hs | bsd-3-clause | 511 | 0 | 8 | 114 | 160 | 96 | 64 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Data.Text.Lazy.Read
-- Copyright : (c) 2010, 2011 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : GHC
--
-- Functions used frequently when reading textual data.
module Data.Text.Lazy.Read
(
Reader
, decimal
, hexadecimal
, signed
, rational
, double
) where
import Control.Monad (liftM)
import Data.Char (isDigit, isHexDigit, ord)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Ratio ((%))
import Data.Text.Lazy as T
import Data.Word (Word, Word8, Word16, Word32, Word64)
-- | Read some text. If the read succeeds, return its value and the
-- remaining text, otherwise an error message.
type Reader a = Text -> Either String (a,Text)
-- | Read a decimal integer. The input must begin with at least one
-- decimal digit, and is consumed until a non-digit or end of string
-- is reached.
--
-- This function does not handle leading sign characters. If you need
-- to handle signed input, use @'signed' 'decimal'@.
--
-- /Note/: For fixed-width integer types, this function does not
-- attempt to detect overflow, so a sufficiently long input may give
-- incorrect results. If you are worried about overflow, use
-- 'Integer' for your result type.
decimal :: Integral a => Reader a
{-# SPECIALIZE decimal :: Reader Int #-}
{-# SPECIALIZE decimal :: Reader Int8 #-}
{-# SPECIALIZE decimal :: Reader Int16 #-}
{-# SPECIALIZE decimal :: Reader Int32 #-}
{-# SPECIALIZE decimal :: Reader Int64 #-}
{-# SPECIALIZE decimal :: Reader Integer #-}
{-# SPECIALIZE decimal :: Reader Word #-}
{-# SPECIALIZE decimal :: Reader Word8 #-}
{-# SPECIALIZE decimal :: Reader Word16 #-}
{-# SPECIALIZE decimal :: Reader Word32 #-}
{-# SPECIALIZE decimal :: Reader Word64 #-}
decimal txt
| T.null h = Left "input does not start with a digit"
| otherwise = Right (T.foldl' go 0 h, t)
where (h,t) = T.span isDigit txt
go n d = (n * 10 + fromIntegral (digitToInt d))
-- | Read a hexadecimal integer, consisting of an optional leading
-- @\"0x\"@ followed by at least one decimal digit. Input is consumed
-- until a non-hex-digit or end of string is reached. This function
-- is case insensitive.
--
-- This function does not handle leading sign characters. If you need
-- to handle signed input, use @'signed' 'hexadecimal'@.
--
-- /Note/: For fixed-width integer types, this function does not
-- attempt to detect overflow, so a sufficiently long input may give
-- incorrect results. If you are worried about overflow, use
-- 'Integer' for your result type.
hexadecimal :: Integral a => Reader a
{-# SPECIALIZE hexadecimal :: Reader Int #-}
{-# SPECIALIZE hexadecimal :: Reader Integer #-}
hexadecimal txt
| h == "0x" || h == "0X" = hex t
| otherwise = hex txt
where (h,t) = T.splitAt 2 txt
hex :: Integral a => Reader a
{-# SPECIALIZE hexadecimal :: Reader Int #-}
{-# SPECIALIZE hexadecimal :: Reader Int8 #-}
{-# SPECIALIZE hexadecimal :: Reader Int16 #-}
{-# SPECIALIZE hexadecimal :: Reader Int32 #-}
{-# SPECIALIZE hexadecimal :: Reader Int64 #-}
{-# SPECIALIZE hexadecimal :: Reader Integer #-}
{-# SPECIALIZE hexadecimal :: Reader Word #-}
{-# SPECIALIZE hexadecimal :: Reader Word8 #-}
{-# SPECIALIZE hexadecimal :: Reader Word16 #-}
{-# SPECIALIZE hexadecimal :: Reader Word32 #-}
{-# SPECIALIZE hexadecimal :: Reader Word64 #-}
hex txt
| T.null h = Left "input does not start with a hexadecimal digit"
| otherwise = Right (T.foldl' go 0 h, t)
where (h,t) = T.span isHexDigit txt
go n d = (n * 16 + fromIntegral (hexDigitToInt d))
hexDigitToInt :: Char -> Int
hexDigitToInt c
| c >= '0' && c <= '9' = ord c - ord '0'
| c >= 'a' && c <= 'f' = ord c - (ord 'a' - 10)
| otherwise = ord c - (ord 'A' - 10)
digitToInt :: Char -> Int
digitToInt c = ord c - ord '0'
-- | Read an optional leading sign character (@\'-\'@ or @\'+\'@) and
-- apply it to the result of applying the given reader.
signed :: Num a => Reader a -> Reader a
{-# INLINE signed #-}
signed f = runP (signa (P f))
-- | Read a rational number.
--
-- This function accepts an optional leading sign character, followed
-- by at least one decimal digit. The syntax similar to that accepted
-- by the 'read' function, with the exception that a trailing @\'.\'@
-- or @\'e\'@ /not/ followed by a number is not consumed.
--
-- Examples:
--
-- >rational "3" == Right (3.0, "")
-- >rational "3.1" == Right (3.1, "")
-- >rational "3e4" == Right (30000.0, "")
-- >rational "3.1e4" == Right (31000.0, "")
-- >rational ".3" == Left "input does not start with a digit"
-- >rational "e3" == Left "input does not start with a digit"
--
-- Examples of differences from 'read':
--
-- >rational "3.foo" == Right (3.0, ".foo")
-- >rational "3e" == Right (3.0, "e")
rational :: Fractional a => Reader a
{-# SPECIALIZE rational :: Reader Double #-}
rational = floaty $ \real frac fracDenom -> fromRational $
real % 1 + frac % fracDenom
-- | Read a rational number.
--
-- The syntax accepted by this function is the same as for 'rational'.
--
-- /Note/: This function is almost ten times faster than 'rational',
-- but is slightly less accurate.
--
-- The 'Double' type supports about 16 decimal places of accuracy.
-- For 94.2% of numbers, this function and 'rational' give identical
-- results, but for the remaining 5.8%, this function loses precision
-- around the 15th decimal place. For 0.001% of numbers, this
-- function will lose precision at the 13th or 14th decimal place.
double :: Reader Double
double = floaty $ \real frac fracDenom ->
fromIntegral real +
fromIntegral frac / fromIntegral fracDenom
signa :: Num a => Parser a -> Parser a
{-# SPECIALIZE signa :: Parser Int -> Parser Int #-}
{-# SPECIALIZE signa :: Parser Int8 -> Parser Int8 #-}
{-# SPECIALIZE signa :: Parser Int16 -> Parser Int16 #-}
{-# SPECIALIZE signa :: Parser Int32 -> Parser Int32 #-}
{-# SPECIALIZE signa :: Parser Int64 -> Parser Int64 #-}
{-# SPECIALIZE signa :: Parser Integer -> Parser Integer #-}
signa p = do
sign <- perhaps '+' $ char (\c -> c == '-' || c == '+')
if sign == '+' then p else negate `liftM` p
newtype Parser a = P {
runP :: Reader a
}
instance Monad Parser where
return a = P $ \t -> Right (a,t)
{-# INLINE return #-}
m >>= k = P $ \t -> case runP m t of
Left err -> Left err
Right (a,t') -> runP (k a) t'
{-# INLINE (>>=) #-}
fail msg = P $ \_ -> Left msg
perhaps :: a -> Parser a -> Parser a
perhaps def m = P $ \t -> case runP m t of
Left _ -> Right (def,t)
r@(Right _) -> r
char :: (Char -> Bool) -> Parser Char
char p = P $ \t -> case T.uncons t of
Just (c,t') | p c -> Right (c,t')
_ -> Left "character does not match"
data T = T !Integer !Int
floaty :: Fractional a => (Integer -> Integer -> Integer -> a) -> Reader a
{-# INLINE floaty #-}
floaty f = runP $ do
sign <- perhaps '+' $ char (\c -> c == '-' || c == '+')
real <- P decimal
T fraction fracDigits <- perhaps (T 0 0) $ do
_ <- char (=='.')
digits <- P $ \t -> Right (fromIntegral . T.length $ T.takeWhile isDigit t, t)
n <- P decimal
return $ T n digits
let e c = c == 'e' || c == 'E'
power <- perhaps 0 (char e >> signa (P decimal) :: Parser Int)
let n = if fracDigits == 0
then if power == 0
then fromIntegral real
else fromIntegral real * (10 ^^ power)
else if power == 0
then f real fraction (10 ^ fracDigits)
else f real fraction (10 ^ fracDigits) * (10 ^^ power)
return $! if sign == '+'
then n
else -n
| mightymoose/liquidhaskell | benchmarks/text-0.11.2.3/Data/Text/Lazy/Read.hs | bsd-3-clause | 7,930 | 0 | 19 | 1,961 | 1,609 | 860 | 749 | 130 | 5 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -O #-} -- -O casused a Lint error in the simplifier, so I'm putting that in
-- all the time, so we don't miss it in a fast validate
module T7891 where
import Data.Kind (Type)
newtype T = T (forall t. t -> t)
tf :: T
tf = T id
-- Can't write this type signature:
f :: t -> t
T f = tf
-- But with an indirection we can:
g :: t -> t
g = f
-- We can still use f as it were fully polymorphic (which is good):
a :: ()
a = f ()
b :: Char
b = f 'b'
-------------
class C t where
data F t :: Type
mkF :: t -> F t
instance C () where
data F () = FUnit (forall t. t -> t)
mkF () = FUnit id
-- Can't write a type for f here either:
k :: t -> t
FUnit k = mkF ()
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T7891.hs | bsd-3-clause | 771 | 0 | 10 | 221 | 220 | 122 | 98 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Haddock
-- Copyright : (c) Andrea Vezzosi 2009
-- License : BSD-like
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Interfacing with Haddock
--
-----------------------------------------------------------------------------
module Distribution.Client.Haddock
(
regenerateHaddockIndex
)
where
import Data.List (maximumBy)
import System.Directory (createDirectoryIfMissing, renameFile)
import System.FilePath ((</>), splitFileName)
import Distribution.Package
( packageVersion )
import Distribution.Simple.Haddock (haddockPackagePaths)
import Distribution.Simple.Program (haddockProgram, ProgramConfiguration
, rawSystemProgram, requireProgramVersion)
import Distribution.Version (Version(Version), orLaterVersion)
import Distribution.Verbosity (Verbosity)
import Distribution.Simple.PackageIndex
( InstalledPackageIndex, allPackagesByName )
import Distribution.Simple.Utils
( comparing, debug, installDirectoryContents, withTempDirectory )
import Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo_(exposed) )
regenerateHaddockIndex :: Verbosity
-> InstalledPackageIndex -> ProgramConfiguration
-> FilePath
-> IO ()
regenerateHaddockIndex verbosity pkgs conf index = do
(paths, warns) <- haddockPackagePaths pkgs' Nothing
let paths' = [ (interface, html) | (interface, Just html) <- paths]
case warns of
Nothing -> return ()
Just m -> debug verbosity m
(confHaddock, _, _) <-
requireProgramVersion verbosity haddockProgram
(orLaterVersion (Version [0,6] [])) conf
createDirectoryIfMissing True destDir
withTempDirectory verbosity destDir "tmphaddock" $ \tempDir -> do
let flags = [ "--gen-contents"
, "--gen-index"
, "--odir=" ++ tempDir
, "--title=Haskell modules on this system" ]
++ [ "--read-interface=" ++ html ++ "," ++ interface
| (interface, html) <- paths' ]
rawSystemProgram verbosity confHaddock flags
renameFile (tempDir </> "index.html") (tempDir </> destFile)
installDirectoryContents verbosity tempDir destDir
where
(destDir,destFile) = splitFileName index
pkgs' = [ maximumBy (comparing packageVersion) pkgvers'
| (_pname, pkgvers) <- allPackagesByName pkgs
, let pkgvers' = filter exposed pkgvers
, not (null pkgvers') ]
| corngood/cabal | cabal-install/Distribution/Client/Haddock.hs | bsd-3-clause | 2,763 | 0 | 18 | 700 | 560 | 311 | 249 | 48 | 2 |
{-# LANGUAGE Safe, Trustworthy #-}
-- | Basic test to see if Safe flags compiles
module SafeFlags10 where
f :: Int
f = 1
| urbanslug/ghc | testsuite/tests/safeHaskell/flags/SafeFlags10.hs | bsd-3-clause | 124 | 0 | 4 | 27 | 16 | 11 | 5 | 4 | 1 |
{-# LANGUAGE MagicHash #-}
module T8262 where
foo x = Just (1#)
| ryantm/ghc | testsuite/tests/typecheck/should_fail/T8262.hs | bsd-3-clause | 66 | 0 | 6 | 14 | 19 | 11 | 8 | 3 | 1 |
{-# LANGUAGE PolyKinds, KindSignatures #-}
module Foo where
data T (a :: j k) = MkT
| wxwxwwxxx/ghc | testsuite/tests/polykinds/T6039.hs | bsd-3-clause | 87 | 0 | 6 | 19 | 22 | 14 | 8 | 3 | 0 |
module Main
(
main
)
where
import System.Directory ( createDirectoryIfMissing )
import Color ( Color(..), saveRender )
main :: IO ()
main = do
putStrLn "Starting render..."
createDirectoryIfMissing True "output"
saveRender "output/experiment00.bmp" 640 480 testRenderFunction
putStrLn "Written output to output/experiment00.bmp"
testRenderFunction :: Int -> Int -> Int -> Int -> Color
testRenderFunction !x !y !w !h =
Color (fromIntegral x / fromIntegral w)
(fromIntegral y / fromIntegral h)
0.0
| stu-smith/rendering-in-haskell | src/experiment00/Main.hs | mit | 559 | 0 | 8 | 132 | 153 | 75 | 78 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.