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 RankNTypes, DataKinds, TypeFamilies #-}
module FunArgs where
f :: forall a. Ord a
=> Int -- ^ First argument
-> a -- ^ Second argument
-> Bool -- ^ Third argument
-> (a -> a) -- ^ Fourth argument
-> () -- ^ Result
f = undefined
g :: a -- ^ First argument
-> b -- ^ Second argument
-> c -- ^ Third argument
-> d -- ^ Result
g = undefined
h :: forall a b c
. a -- ^ First argument
-> b -- ^ Second argument
-> c -- ^ Third argument
-> forall d. d -- ^ Result
h = undefined
i :: forall a (b :: ()) d. (d ~ '())
=> forall c
. a b c d -- ^ abcd
-> () -- ^ Result
i = undefined
j :: forall proxy (a :: ()) b
. proxy a -- ^ First argument
-> b -- ^ Result
j = undefined
| DavidAlphaFox/ghc | utils/haddock/html-test/src/FunArgs.hs | bsd-3-clause | 775 | 0 | 12 | 262 | 215 | 130 | 85 | 29 | 1 |
-- Mark I lazy wheel-sieve.
-- Colin Runciman ([email protected]); March 1996.
-- See article "Lazy wheel sieves and spirals of primes" (to appear, JFP).
import System.Environment
data Wheel = Wheel Int [Int]
primes :: [Int]
primes = sieve wheels primes squares
sieve (Wheel s ns:ws) ps qs =
[n' | o <- s:[s*2,s*3..(head ps-1)*s],
n <- ns,
n'<- [n+o], noFactor n']
++
sieve ws (tail ps) (tail qs)
where
noFactor = if s<=2 then const True else notDivBy ps qs
notDivBy (p:ps) (q:qs) n =
q > n || n `mod` p > 0 && notDivBy ps qs n
squares :: [Int]
squares = [p*p | p<-primes]
wheels :: [Wheel]
wheels = Wheel 1 [1] : zipWith nextSize wheels primes
nextSize (Wheel s ns) p =
Wheel (s*p) ns'
where
ns' = [n' | o <- [0,s..(p-1)*s],
n <- ns,
n' <- [n+o], n'`mod`p > 0]
main = do
[arg] <- getArgs
print (primes!!((read arg) :: Int))
| beni55/ghcjs | test/nofib/imaginary/wheel-sieve1/Main.hs | mit | 904 | 0 | 14 | 234 | 451 | 240 | 211 | 25 | 2 |
{-# LANGUAGE TypeOperators #-}
module B where
infixr 9 :-
type a :- b = (a,b)
| urbanslug/ghc | testsuite/tests/driver/recomp006/B1.hs | bsd-3-clause | 82 | 0 | 5 | 20 | 24 | 17 | 7 | 4 | 0 |
{-# LANGUAGE DeriveDataTypeable
, FlexibleContexts
, MultiParamTypeClasses
, ScopedTypeVariables
, OverloadedStrings #-}
module LambdaChair.Policy ( LambdaChairPolicy
, withLambdaChairPolicy
-- * Rexport hails interface with groups
, findAll, findAllP
) where
import Prelude hiding (lookup)
import Data.Maybe
import Data.Monoid
import qualified Data.List as List
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as S8
import Data.Typeable
import Control.Monad
import LIO
import LIO.DCLabel
import Hails.Database
import Hails.PolicyModule
import Hails.PolicyModule.Groups
import Hails.PolicyModule.DSL
import Hails.Database.Structured hiding (findAll, findAllP)
import LambdaChair.Models
-- | Internal mappend policy. The type constructor should not be
-- exported to avoid leaking the privilege.
data LambdaChairPolicy = LambdaChairPolicyTCB DCPriv
deriving Typeable
instance PolicyModule LambdaChairPolicy where
initPolicyModule priv = do
setPolicy priv $ do
database $ do
readers ==> True
writers ==> True
admins ==> this
--
collection "pc" $ do
access $ do
readers ==> True
writers ==> True
clearance $ do
secrecy ==> this
integrity ==> True
document $ \doc -> do
let (Just u) = fromDocument doc
readers ==> True
writers ==> (T.unpack $ userName u) \/ root \/ this
--
collection "papers" $ do
access $ do
readers ==> True
writers ==> True
clearance $ do
secrecy ==> this
integrity ==> True
document $ \doc -> do
let (Just p) = fromDocument doc
owners = map T.unpack $ paperOwners p
pc = "#commitee_member" :: String
readers ==> foldr (\/) (pc \/ root \/ this) owners
writers ==> foldr (\/) (root \/ this) owners
--
collection "reviews" $ do
access $ do
readers ==> True
writers ==> True
clearance $ do
secrecy ==> this
integrity ==> True
document $ \doc -> do
r <- fromDocument doc
let author = T.unpack $ reviewAuthor r
rid = "#reviewId=" ++ (maybe "" show $ reviewId r)
rpid = "#reviewPaperId=" ++ (show $ reviewPaper r)
readers ==> author \/ rid \/ rpid \/ root \/ this
writers ==> author \/ root \/ this
field "paper" searchable
--
return $ LambdaChairPolicyTCB priv
where this = privDesc priv
root = principal "root"
instance DCLabeledRecord LambdaChairPolicy Paper where
endorseInstance _ = LambdaChairPolicyTCB emptyPriv
instance DCLabeledRecord LambdaChairPolicy Review where
endorseInstance _ = LambdaChairPolicyTCB emptyPriv
withLambdaChairPolicy :: DBAction a -> DC a
withLambdaChairPolicy act = withPolicyModule $
\(LambdaChairPolicyTCB _) -> act
--
-- Goups
--
instance Groups LambdaChairPolicy where
groupsInstanceEndorse = LambdaChairPolicyTCB emptyPriv
groups _ p pgroup = case () of
_ | group == "#commitee_member" -> do
pc <- findAllP p $ select [] "pc"
return $ map (toPrincipal . userName) pc
_ | reviewPaperId `S8.isPrefixOf` group -> do
pc <- (map userName) `liftM` (findAllP p $ select [] "pc")
let _id = read . S8.unpack $ S8.drop (S8.length reviewPaperId) group
mpaper <- findBy "papers" "_id" (_id :: ObjectId)
case mpaper of
Nothing -> return [pgroup]
Just paper -> return . map toPrincipal $ pc List.\\ paperConflicts paper
_ -> return [pgroup]
where group = principalName pgroup
toPrincipal = principal . T.unpack
reviewPaperId = "#reviewPaperId="
--
-- Port over Hails interface to use groups
--
-- | Same as 'findWhereP', but uses groups when retrieving document.
findWhereWithGroupP :: (DCRecord a, MonadDB m) => DCPriv -> Query -> m (Maybe a)
findWhereWithGroupP p query = liftDB $ do
mldoc <- findOneP p query
c <- liftLIO $ getClearance
case mldoc of
Just ldoc' -> do ldoc <- labelRewrite (undefined :: LambdaChairPolicy) ldoc'
if canFlowToP p (labelOf ldoc) c
then fromDocument `liftM` (liftLIO $ unlabelP p ldoc)
else return Nothing
_ -> return Nothing
-- | Same as Hails\' 'findAll', but uses groups
findAll :: (DCRecord a, MonadDB m)
=> Query -> m [a]
findAll = findAllP emptyPriv
-- | Same as Hails\' 'findAllP', but uses groups
findAllP :: (DCRecord a, MonadDB m)
=> DCPriv -> Query -> m [a]
findAllP p query = liftDB $ do
cursor <- findP p query
cursorToRecords cursor []
where cursorToRecords cur docs = do
mldoc <- nextP p cur
case mldoc of
Just ldoc' -> do
ldoc <- labelRewrite (undefined :: LambdaChairPolicy) ldoc'
c <- liftLIO $ getClearance
if canFlowTo (labelOf ldoc) c
then do md <- fromDocument `liftM` (liftLIO $ unlabelP p ldoc)
cursorToRecords cur $ maybe docs (:docs) md
else cursorToRecords cur docs
_ -> return $ reverse docs
--
-- DCRecord instances
--
instance DCRecord Paper where
fromDocument doc = do
let pid = lookupObjId "_id" doc
owners = fromMaybe [] $ lookup "owners" doc
title <- lookup_ "title" doc
authors <- lookup_ "authors" doc
abstract <- lookup_ "abstract" doc
let body = case lookup "paper" doc of
(Just (d :: BsonDocument)) -> do
fn <- lookup "fileName" d
ct <- lookup "fileContentType" d
c <- lookup "fileContent" d
return $ File { fileName = fn
, fileContentType = ct
, fileContent = unBinary c }
_ -> Nothing
conflicts = fromMaybe [] $ lookup "conflicts" doc
return Paper { paperId = pid
, paperOwners = owners
, paperTitle = title
, paperAuthors = authors
, paperAbstract = abstract
, paperBody = body
, paperConflicts = conflicts }
where lookup_ n d = return $ fromMaybe T.empty $ lookup n d
toDocument p =
let pid = paperId p
pre = if isJust pid
then ["_id" -: fromJust pid]
else []
body = maybe [] (\f -> ["paper" -: toDoc f]) $ paperBody p
toDoc f= [ "fileName" -: fileName f
, "fileContentType" -: fileContentType f
, "fileContent" -: Binary (fileContent f)
] :: BsonDocument
in pre ++ [ "owners" -: paperOwners p
, "title" -: paperTitle p
, "authors" -: paperAuthors p
, "abstract" -: paperAbstract p
, "conflicts" -: paperConflicts p ] ++ body
findWhereP = findWhereWithGroupP
recordCollection _ = "papers"
instance DCRecord Review where
fromDocument doc = do
let rid = lookupObjId "_id" doc
author <- lookup "author" doc
paper <- lookupObjId "paper" doc
body <- lookup_ "body" doc
return Review { reviewId = rid
, reviewPaper = paper
, reviewAuthor = author
, reviewBody = body }
where lookup_ n d = return $ fromMaybe T.empty $ lookup n d
toDocument r =
let rid = reviewId r
pre = if isJust rid
then ["_id" -: fromJust rid]
else []
in pre ++ [ "paper" -: reviewPaper r
, "author" -: reviewAuthor r
, "body" -: reviewBody r ]
findWhereP = findWhereWithGroupP
recordCollection _ = "reviews"
lookupObjId :: Monad m => FieldName -> HsonDocument -> m ObjectId
lookupObjId n d = case lookup n d of
Just i -> return (i :: ObjectId)
_ -> case do { s <- lookup n d; maybeRead s } of
Just i -> return i
_ -> fail $ "lookupObjId: cannot extract id from " ++ show n
where maybeRead = fmap fst . listToMaybe . reads
emptyPriv :: DCPriv
emptyPriv = mempty
| deian/lambdachair | LambdaChair/Policy.hs | mit | 8,646 | 0 | 24 | 3,094 | 2,358 | 1,172 | 1,186 | 200 | 3 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_isbn_verifier (
version,
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [1,1,0,1] []
bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/c19/Documents/projects/exercism/haskell/haskell/isbn-verifier/.stack-work/install/x86_64-osx/lts-9.11/8.0.2/bin"
libdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/isbn-verifier/.stack-work/install/x86_64-osx/lts-9.11/8.0.2/lib/x86_64-osx-ghc-8.0.2/isbn-verifier-1.1.0.1-4knpVDKMCdN6yVDRTVYlC3"
dynlibdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/isbn-verifier/.stack-work/install/x86_64-osx/lts-9.11/8.0.2/lib/x86_64-osx-ghc-8.0.2"
datadir = "/Users/c19/Documents/projects/exercism/haskell/haskell/isbn-verifier/.stack-work/install/x86_64-osx/lts-9.11/8.0.2/share/x86_64-osx-ghc-8.0.2/isbn-verifier-1.1.0.1"
libexecdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/isbn-verifier/.stack-work/install/x86_64-osx/lts-9.11/8.0.2/libexec"
sysconfdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/isbn-verifier/.stack-work/install/x86_64-osx/lts-9.11/8.0.2/etc"
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "isbn_verifier_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "isbn_verifier_libdir") (\_ -> return libdir)
getDynLibDir = catchIO (getEnv "isbn_verifier_dynlibdir") (\_ -> return dynlibdir)
getDataDir = catchIO (getEnv "isbn_verifier_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "isbn_verifier_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "isbn_verifier_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| c19/Exercism-Haskell | isbn-verifier/.stack-work/dist/x86_64-osx/Cabal-1.24.2.0/build/autogen/Paths_isbn_verifier.hs | mit | 2,446 | 0 | 10 | 239 | 410 | 238 | 172 | 33 | 1 |
{-# LANGUAGE UnicodeSyntax, OverloadedStrings #-}
module Web.TinySrv.Monad (
Route
, okay
, okay'
, notFound
, notFound'
, badRequest
, badRequest'
, header
, contentType
, method
, pathList
, pathString
, partialPath
, fullPath
, path
, popPath
, emptyPath
, headerList
, getHeader
, host
, file
, serveFile
, serveDirectory
, runRoutes
) where
import Prelude.Unicode
import Web.TinySrv.Types
import Web.TinySrv.Mime
import Control.Applicative ((<|>))
import Control.Monad.State
import Control.Monad.Trans.Maybe
import Control.Monad (msum)
import qualified Data.ByteString.Char8 as B (ByteString, readFile, pack, unpack, singleton, empty, split, concat)
import Data.List (null, dropWhileEnd)
import System.Directory
import System.FilePath
import System.IO (openBinaryFile, hFileSize, IOMode(ReadMode))
type MaybeState s a = MaybeT (StateT s IO) a
runMaybeState ∷ MaybeState s a → s → IO (Maybe (a, s))
runMaybeState m s = do
(v, st) ← flip runStateT s $ runMaybeT m
case v of
Just x → return $ Just (x, st)
Nothing → return Nothing
type Route a = MaybeState (Request, [Header]) a
-- Response functions --
-- | Returns HTTP 200 response
--
-- > serve 80 [emptyPath >> contentType "text/html" >> okay "Some response"]
okay ∷ HPutable a
⇒ a -- ^ Response body
→ Route Response
okay = return ∘ Response 200
{-# INLINE okay #-}
-- | Returns HTTP 200 response with a ByteString for convenience when using OverloadedStrings
okay' ∷ B.ByteString -- ^ Response body
→ Route Response
okay' = return ∘ Response 200
{-# INLINE okay' #-}
-- | Returns HTTP 404 response
--
-- > serve 80 [ emptyPath >> contentType "text/html" >> okay "Some response"
-- > , contentType "text/html" >> notFound "<h3>404 Not Found</h3>"
-- > ]
notFound ∷ HPutable a
⇒ a -- ^ Response body
→ Route Response
notFound = return ∘ Response 404
{-# INLINE notFound #-}
-- | Returns HTTP 404 response with a ByteString for convenience when using OverloadedStrings
notFound' ∷ B.ByteString -- ^ Response body
→ Route Response
notFound' = return ∘ Response 404
{-# INLINE notFound' #-}
-- | Returns HTTP 400 response
badRequest ∷ HPutable a
⇒ a -- ^ Response body
→ Route Response
badRequest = return ∘ Response 400
{-# INLINE badRequest #-}
-- | Returns HTTP 400 response with a ByteString for convenience when using OverloadedStrings
badRequest' ∷ B.ByteString -- ^ Response body
→ Route Response
badRequest' = return ∘ Response 400
{-# INLINE badRequest' #-}
-- Route functions --
-- | Returns the request headers
headerList ∷ Route [Header]
headerList = reqHeaders ∘ fst <$> get
{-# INLINE headerList #-}
-- | Return the value of the request header if present, or 'Nothing' if not
getHeader ∷ B.ByteString -- ^ Header name
→ Route (Maybe B.ByteString) -- ^ Header value
getHeader n = do
hs ← headerList
case filter (\(Header k _) → k ≡ n) hs of
(Header _ v:xs) → return $ Just v
_ → return Nothing
-- | Set response header
header ∷ B.ByteString -- ^ Header name
→ B.ByteString -- ^ Header value
→ Route ()
header n v = modify (\(r, hs) → (r, Header n v : filter (\(Header k _) → k ≠ n) hs))
{-# INLINE header #-}
-- | Set Content-Type header
--
-- > serve 80 [contentType "application/json" >> okay "{\"a\":1}"]
contentType ∷ B.ByteString → Route ()
contentType = header "Content-Type"
{-# INLINE contentType #-}
-- | Request method guard
method ∷ HTTPMethod -- ^ HTTP method
→ Route ()
method m = get >>= guard ∘ (≡) m ∘ reqMethod ∘ fst
{-# INLINE method #-}
-- | Returns path stack
pathList ∷ Route [B.ByteString]
pathList = get >>= return ∘ reqPath ∘ fst
{-# INLINE pathList #-}
-- | Returns path stack as a string joined with \'/\'
pathString ∷ Route B.ByteString
pathString = get >>= return ∘ addSlashToEmpty ∘ B.concat ∘ concatMap (\x → [B.singleton '/', x]) ∘ reqPath ∘ fst
where
addSlashToEmpty x | x ≡ B.empty = B.singleton '/'
| otherwise = x
{-# INLINEABLE pathString #-}
-- | Checks that the top elements of the stack path match the input, and removes them
--
-- > serve 80 [partialPath "/abc/123/" >> pathString >>= okay]
partialPath ∷ B.ByteString → Route ()
partialPath p = foldl (>>) (return ()) $ map path (filter (≠ B.empty) $ B.split '/' p)
{-# INLINE partialPath #-}
-- | Check that the request path matches the input
fullPath ∷ B.ByteString → Route ()
fullPath p = partialPath p >> emptyPath
{-# INLINE fullPath #-}
-- | Pop the top element from the path stack and check that it matches the input
--
-- > serve 80 [ emptyPath >> okay "This is /"
-- > , path "abc" >> emptyPath >> okay "This is /abc"
-- > , path "abc" >> path "123" >> emptyPath >> okay "This is /abc/123"
-- > ]
path ∷ B.ByteString → Route ()
path s = do
(r, rhs) ← get
guard ∘ not ∘ null $ reqPath r
guard $ head (reqPath r) ≡ s
put (r{reqPath=tail $ reqPath r}, rhs)
{-# INLINEABLE path #-}
-- | Pop the top element off the path stack
popPath ∷ Route B.ByteString
popPath = do
(r, rhs) ← get
guard ∘ not ∘ null $ reqPath r
put (r{reqPath=tail $ reqPath r}, rhs)
return ∘ head $ reqPath r
{-# INLINEABLE popPath #-}
-- | Checks that the path stack is empty
emptyPath ∷ Route ()
emptyPath = get >>= guard ∘ null ∘ reqPath ∘ fst
{-# INLINE emptyPath #-}
-- | Hostname guard
host ∷ B.ByteString -- ^ Hostname
→ Route ()
host h = getHeader "Host" >>= guard ∘ (≡) (Just h)
{-# INLINE host #-}
-- | Sets the Content-Type header based on the file extension, covers common file types and uses application/octet-stream for unknown extensions
detectContentType ∷ FilePath -- ^ Path to file
→ Route ()
detectContentType f = contentType ∘ getMime ∘ B.pack $ takeExtension f
{-# INLINE detectContentType #-}
-- | Create a response from a file
file ∷ FilePath -- ^ Path to file
→ Route Response
file f = do
fh ← liftIO $ openBinaryFile f ReadMode
fs ← liftIO $ hFileSize fh
okay (fs, fh)
{-# INLINE file #-}
-- | Serve a file for the given path
serveFile ∷ FilePath -- ^ Path to file
→ B.ByteString -- ^ Routing path
→ Route Response
serveFile f p = fullPath p >> (method GET <|> method HEAD) >> detectContentType f >> file f
{-# INLINE serveFile #-}
-- | Serve a file or directory
serveDirectory ∷ Bool -- ^ Allow file index for directories
→ FilePath -- ^ Path to the directory
→ B.ByteString -- ^ Routing path
→ Route Response
serveDirectory l d p = do
fullP ← pathString
partialPath p
(method GET <|> method HEAD)
urlP ← pathString
let p' = dropWhileEnd (≡ '/') d ++ B.unpack urlP
fe ← liftIO $ doesFileExist p'
de ← liftIO $ doesDirectoryExist p'
guard (fe ∨ de ∧ l)
if fe
then detectContentType p' >> file p'
else do
cs ← filter (\x → x ≠ "." ∧ x ≠ "..") <$> liftIO (getDirectoryContents p') >>= liftIO ∘ mapM (\x → let y = B.pack x in doesDirectoryExist (dropWhileEnd (≡ '/') d ++ B.unpack urlP ++ '/' : x) >>= \b → return $ if b then B.concat [y, "/"] else y)
contentType "text/html"
okay $ B.concat ["<html><head><title>Index of ", fullP, "</title></head><body><h2>Index of "
, fullP, "</h2><hr>", B.concat $ (\x → ["<a href=\"", fullP, (if fullP ≠ "/" then "/" else "" ∷ B.ByteString), x, "\">", x, "</a><br>"]) =<< if fullP ≠ "/" then ".." : cs else cs
, "</body></html>"]
runRoutes ∷ [Route Response] → (Request, [Header]) → IO (Maybe (Response, [Header]))
runRoutes rs s = do
v ← mapM (`runMaybeState` s) rs >>= return ∘ msum
case v of
Just (r, (_, hs)) → return $ Just (r, hs)
Nothing → return Nothing
| Slowki/TinySrv | src/Web/TinySrv/Monad.hs | mit | 8,196 | 0 | 24 | 2,003 | 2,105 | 1,134 | 971 | 170 | 5 |
{-|
Module : Foreign.Storable.Generic.Plugin.Internal.Error
Copyright : (c) Mateusz Kłoczko, 2016
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : GHC-only
Contains the Error datatype and related pretty print functions.
-}
{-# LANGUAGE CPP #-}
module Foreign.Storable.Generic.Plugin.Internal.Error
( Verbosity(..)
, CrashOnWarning(..)
, Flags(..)
, Error(..)
, pprError
, stringToPpr
) where
#if MIN_VERSION_GLASGOW_HASKELL(9,0,1,0)
import GHC.Types.Id (Id)
import GHC.Types.Var (Var(..))
import GHC.Core (CoreBind(..), Bind(..),CoreExpr(..))
import GHC.Core.Type (Type)
import GHC.Utils.Outputable
#else
import Id (Id)
import Var(Var(..))
import CoreSyn (CoreBind(..), Bind(..),CoreExpr(..))
import Type (Type)
import Outputable
#endif
import Foreign.Storable.Generic.Plugin.Internal.Helpers
-- | How verbose should the messages be.
data Verbosity = None | Some | All
-- | Crash when an recoverable error occurs. For testing purposes.
type CrashOnWarning = Bool
-- | Contains user-specified flags.
data Flags = Flags Verbosity CrashOnWarning
-- | All possible errors.
data Error = TypeNotFound Id -- ^ Could not obtain the type from the id.
| RecBinding CoreBind -- ^ The binding is recursive and won't be substituted.
| CompilationNotSupported CoreBind -- ^ The compilation-substitution is not supported for the given binding.
| CompilationError CoreBind SDoc -- ^ Error during compilation. The CoreBind is to be returned.
| OrderingFailedBinds Int [CoreBind] -- ^ Ordering failed for core bindings.
| OrderingFailedTypes Int [Type] -- ^ Ordering failed for types
| OtherError SDoc -- ^ Any other error.
pprTypeNotFound :: Verbosity -> Id -> SDoc
pprTypeNotFound None _ = empty
pprTypeNotFound Some id
= text "Could not obtain the type from"
$$ nest 4 (ppr id <+> text "::" <+> ppr (varType id) )
pprTypeNotFound All id = pprTypeNotFound Some id
pprRecBinding :: Verbosity -> CoreBind -> SDoc
pprRecBinding None _ = empty
pprRecBinding Some (Rec bs)
= text "The binding is recursive and won't be substituted"
$$ nest 4 (vcat ppr_ids)
where ppr_ids = map (\(id,_) -> ppr id <+> text "::" <+> ppr (varType id) ) bs
pprRecBinding Some (NonRec id _)
= text "RecBinding error for non recursive binding...?"
$$ nest 4 (ppr id <+> text "::" <+> ppr (varType id) )
pprRecBinding All b@(Rec _)
= text "--- The binding is recursive and won't be substituted ---"
$+$ text ""
$+$ nest 4 (ppr b)
$+$ text ""
pprRecBinding All b@(NonRec _ _)
= text "--- RecBinding error for non recursive binding ? ---"
$+$ text ""
$+$ nest 4 (ppr b)
$+$ text ""
pprCompilationNotSupported :: Verbosity -> CoreBind -> SDoc
pprCompilationNotSupported None _ = empty
pprCompilationNotSupported Some bind
= text "Compilation is not supported for bindings of the following format: "
$$ nest 4 (vcat ppr_ids)
where ppr_ids = map (\id -> ppr id <+> text "::" <+> ppr (varType id) ) $ getIdsBind bind
pprCompilationNotSupported All bind
= text "--- Compilation is not supported for bindings of the following format ---"
$+$ text ""
$+$ nest 4 (ppr bind)
$+$ text ""
pprCompilationError :: Verbosity -> CoreBind -> SDoc -> SDoc
pprCompilationError None _ _ = empty
pprCompilationError Some bind sdoc
= text "Compilation failed for the following binding: "
$$ nest 4 (vcat ppr_ids)
$$ nest 4 (text "The error was:" $$ nest 5 sdoc)
where ppr_ids = map (\id -> ppr id <+> text "::" <+> ppr (varType id) ) $ getIdsBind bind
pprCompilationError All bind sdoc
= text "--- Compilation failed for the following binding ---"
$+$ text ""
$+$ nest 4 (text "Error message: ")
$+$ nest 4 sdoc
$+$ text ""
$+$ nest 4 (ppr bind)
$+$ text ""
pprOrderingFailedTypes :: Verbosity -> Int -> [Type] -> SDoc
pprOrderingFailedTypes None _ _ = empty
pprOrderingFailedTypes Some depth types
= text "Type ordering failed at depth" <+> int depth <+> text "for types:"
$$ nest 4 (vcat ppr_types)
where ppr_types = map ppr types
pprOrderingFailedTypes All depth types = pprOrderingFailedTypes Some depth types
pprOrderingFailedBinds :: Verbosity -> Int -> [CoreBind] -> SDoc
pprOrderingFailedBinds None _ _ = empty
pprOrderingFailedBinds Some depth binds
= text "CoreBind ordering failed at depth" <+> int depth <+> text "for bindings:"
$$ nest 4 (vcat ppr_ids)
where ppr_ids = map (\id -> ppr id <+> text "::" <+> ppr (varType id)) $ concatMap getIdsBind binds
pprOrderingFailedBinds All depth binds
= text "--- CoreBind ordering failed at depth" <+> int depth <+> text "for bindings ---"
$+$ text "\n"
$+$ nest 4 (vcat ppr_binds)
$+$ text ""
where ppr_binds = map ppr binds
pprOtherError :: Verbosity -> SDoc -> SDoc
pprOtherError None _ = empty
pprOtherError _ sdoc = sdoc
-- | Print an error according to verbosity flag.
pprError :: Verbosity -> Error -> SDoc
pprError verb (TypeNotFound id ) = pprTypeNotFound verb id
pprError verb (RecBinding bind) = pprRecBinding verb bind
pprError verb (CompilationNotSupported bind) = pprCompilationNotSupported verb bind
pprError verb (CompilationError bind str) = pprCompilationError verb bind str
pprError verb (OrderingFailedBinds d bs) = pprOrderingFailedBinds verb d bs
pprError verb (OrderingFailedTypes d ts) = pprOrderingFailedTypes verb d ts
pprError verb (OtherError sdoc ) = pprOtherError verb sdoc
-- | Change String to SDoc.
-- Each newline is $$ed with nest equal to spaces before.
-- \t is 4.
stringToPpr :: String -> SDoc
stringToPpr str = do
-- Whether to take a letter
let taker ' ' = True
taker '\t' = True
taker _ = False
-- Whether to
to_num ' ' = 1
to_num '\t' = 4
to_num _ = 0
-- Function doing the nesting
let nest_text str = do
let whites = takeWhile taker str
rest = dropWhile taker str
num = sum $ map to_num whites
nest num $ text rest
vcat $ map nest_text $ lines str
| mkloczko/derive-storable-plugin | src/Foreign/Storable/Generic/Plugin/Internal/Error.hs | mit | 6,438 | 2 | 15 | 1,638 | 1,572 | 802 | 770 | 119 | 5 |
module Immediate.Simplify where
import Immediate.Syntax
class Simplify a where
simplify :: a -> a
instance Simplify (Expression a) where
simplify = simplifyForceDefer
instance Simplify Module where
simplify (Module name deps tdefs vdefs) = Module name deps tdefs $ simplify `fmap` vdefs
instance Simplify Vdef where
simplify (Vdef name expr) = Vdef name $ simplify expr
simplifyForceDefer :: Expression a -> Expression a
simplifyForceDefer (Lam name expr) = Lam name $ simplifyForceDefer expr
simplifyForceDefer (App f x) = App (simplifyForceDefer f) (simplifyForceDefer x)
simplifyForceDefer (Let vdefs expr) = Let (simplifyVdef `fmap` vdefs) (simplifyForceDefer expr) where
simplifyVdef (Vdef name expr) = Vdef name $ simplifyForceDefer expr
simplifyForceDefer (Case expr name alts) =
Case (simplifyForceDefer expr) name $ simplifyAlt `fmap` alts where
simplifyAlt (AltDefault expr) = AltDefault $ simplifyForceDefer expr
simplifyAlt (AltLit lit expr) = AltLit lit $ simplifyForceDefer expr
simplifyAlt (AltCon name names expr) = AltCon name names $ simplifyForceDefer expr
simplifyForceDefer (Force (Defer expr)) = simplifyForceDefer expr
simplifyForceDefer (Force expr) = Force $ simplifyForceDefer expr
simplifyForceDefer (Defer (Force expr)) = simplifyForceDefer expr
simplifyForceDefer (Defer expr) = Defer $ simplifyForceDefer expr
simplifyForceDefer l@(Lit _) = l
simplifyForceDefer v@(Var _) = v | edofic/core.js | src/Immediate/Simplify.hs | mit | 1,437 | 0 | 9 | 220 | 505 | 249 | 256 | 26 | 3 |
module Handler.TutorialRaw where
import Import
getTutorialRawR :: UserId -> BlobSHA -> Handler Text
getTutorialRawR uid blob = do
eres <- getFrozenTutorialBlob uid blob
case eres of
Left _ -> notFound
Right pt -> return $ unTutorialContent $ publishedTutorialContent pt
| fpco/schoolofhaskell.com | src/Handler/TutorialRaw.hs | mit | 296 | 0 | 11 | 65 | 83 | 40 | 43 | 8 | 2 |
import Data.List(foldl')
fEvenSum :: [Integer] -> Integer
fEvenSum l = foldl mySum 0 (filter even l)
where mySum acc x = acc + x
myFoldl f z [] = z
myFoldl f z (x:xs) = myFoldl f (f z x) xs
fEvenSum' :: [Integer] -> Integer
fEvenSum' l = myFoldl mySum 0 (filter even l)
where mySum acc x = acc + x
fEvenSum'' :: [Integer] -> Integer
fEvenSum'' l = foldl (\x y -> x + y) 0 (filter even l)
fEvenSum''' :: [Integer] -> Integer
fEvenSum''' l = foldl (+) 0 (filter even l)
fEvenSum'''' :: [Integer] -> Integer
fEvenSum'''' l = foldl' (+) 0 (filter even l)
| gscalzo/HaskellTheHardWay | HellWay/fEvenSum.hs | mit | 590 | 2 | 8 | 149 | 286 | 149 | 137 | 15 | 1 |
-------------------------------------------------------------
--
-- 数学関連の関数群
--
-- Module : MyModule.NumberTheory
-- Coding : Little Schemer
--
-------------------------------------------------------------
module MyModule.NumberTheory where
import Data.List (sort)
import Data.Ratio
import Data.Maybe
import MyModule.Primes (factorize)
import MyModule.Utility (integralToList)
-----------------------------------------
-- 冪乗法
-----------------------------------------
-- 『素因数分解と素数判定』 p.29 参照
--
-- + 関数 f は Monoid 則を満していること。
-- + e の初期値 : 関数 f の単位元
--
-- ex : 2^100 == power (*) 1 2 100
--
power :: Integral a => (t -> t -> t) -> t -> t -> a -> t
power _ e _ 0 = e
power f e a n = power f (if odd n then f a e else e) (f a a) (div n 2)
--
-- a^n (mod m)
--
powerMod :: (Integral a, Integral t) => t -> a -> t -> t
powerMod a n m = power (\x y -> mod (x * y) m) 1 a n
-----------------------------------------
-- 数列関連
-----------------------------------------
--
-- Fibonacci 数列のリスト
--
-- + "seq" を使うと速くなる
--
fibonacciList :: [Integer]
fibonacciList = fib' 0 1
where fib' a b = seq a $ a : fib' b (a + b)
--
-- Fibonacci 数
--
-- + 「Gosper & Salamin のアイデア」を使用。
-- + from 『フィボナッチ数とリュカ数の計算法』
--
fibonacci :: Int -> Integer
fibonacci 0 = 0
fibonacci n = fst $ power calc (0, 1) (1, 0) n
where calc (a, b) (c, d) = (a * (c + d) + b * c, a * c + b * d)
--
-- Fibonacci 数
--
-- +「ビネの公式」を使った方法
-- + 参考 :
-- http://labs.timedia.co.jp/2012/11/fibonacci-general-term-using-rational.html
-- + (1 / 2 + √5 / 2) ^ n - (1 / 2 - √5 / 2) ^ n を計算すると、有理数
-- 項は打ち消しあって、√5 の項のみが残る。
--
fibonacci2 :: Int -> Integer
fibonacci2 0 = 0
fibonacci2 n = truncate . (* 2) . snd $ power f (1, 0) (1 % 2, 1 % 2) n
where f (a1, b1) (a2, b2) = (a1 * a2 + 5 * b1 * b2, a1 * b2 + a2 * b1)
--
-- Lucas 数
--
lucasList :: [Integer]
lucasList = lucas' 2 1
where lucas' a b = seq a $ a : lucas' b (a + b)
--
-- 多角数のリスト
--
-- + "0" から始まるので注意 !!
--
-- ex : polyNumList 3 => [0,1,3,6,10,15,21,28,36,45,55 ..]
--
polyNumList :: Integral a => a -> [a]
polyNumList n = scanl (+) 0 [1, n - 1 ..]
--
-- 多角数の一般項
--
-- + from Wikipedia
--
-- ex : map (polyNum 3) [1 .. 5] => [1,3,6,10,15]
--
polyNum :: Integral a => a -> a -> a
polyNum p n = div (n * ((p - 2) * n - (p - 4))) 2
-----------------------------------------
-- 約数関連
-----------------------------------------
--
-- 約数
--
divisor :: Integral a => a -> [a]
divisor n = sort $ foldr f [1] ns
where
ns = [map (p ^) [0 .. i] | (p, i) <- factorize n]
f ns1 ns2 = [x * y | x <- ns1, y <- ns2]
--
-- 約数の個数
--
numberOfDivisors :: Integral a => a -> Int
numberOfDivisors n = product [i + 1 | (_, i) <- factorize n]
--
-- 約数の和
--
sumOfDivisors :: Integral a => a -> a
sumOfDivisors n = product [f p i | (p, i) <- factorize n]
where f p i = div (p ^ (i + 1) - 1) (p - 1)
--
-- 完全数か ?
--
isPerfect :: Integral a => a -> Bool
isPerfect n = n + n == sumOfDivisors n
--
-- 過剰数か ?
--
isAbundant :: Integral a => a -> Bool
isAbundant n = n + n < sumOfDivisors n
--
-- 不足数か ?
--
isDeficient :: Integral a => a -> Bool
isDeficient n = n + n > sumOfDivisors n
--
-- 友愛数のもう片方を探す
--
-- ex : findAmicableNumber 220 => Jus 284
-- ex : findAmicableNumber 221 => Nothing
--
findAmicableNumber :: Integral a => a -> Maybe a
findAmicableNumber x
| (x /= y) && (sumOfDivisors y - y == x) = Just y
| otherwise = Nothing
where y = sumOfDivisors x - x
--
-- 友愛数のペアのうち、小さい値が引数の範囲内にあるものを返す。
--
-- ex : amicablePairs [2 .. 1200] => [(220,284),(1184,1210)]
--
amicablePairs :: Integral a => [a] -> [(a, a)]
amicablePairs xs = [(x, fromJust y) | x <- xs,
let y = findAmicableNumber x, isJust y, Just x < y]
-----------------------------------------
-- ピタゴラス数
-----------------------------------------
--
-- ピタゴラス数
--
-- + a + b + c = n, a^2 + b^2 = c^2, a < b < c の組を探す
--
-- 1. a + a + a < n よって a <= div n 3
-- 2. a^2 + b^2 = (n - a - b)^2 変形すると、
-- b = n / 2 - (a * n) / (2 * (n - a))
-- 3. a, b ともに整数なら、n は必ず偶数になるので
-- (既約ピタゴラス数の場合、a と b はどちらかは偶数でもう一方は奇数、
-- さらに c は奇数になることが判っている)
-- i ) n/2 は整数。
-- ii) 従って、(a * n) / (2 * (n - a)) も整数。
--
pythagoreanNums :: Integral a => a -> [(a, a, a)]
pythagoreanNums n
| odd n = []
| otherwise = [(a, b, n - a - b) | a <- as, let b = calc a, a < b]
where
as = [a | a <- [1 .. div n 3], rem (a * n) (2 * (n - a)) == 0]
calc a = div (n * (n - 2 * a)) (2 * (n - a))
--
-- 既約ピタゴラス数
--
primitivePythagoreanNums :: Integral a => a -> [(a, a, a)]
primitivePythagoreanNums n =
[(a, b, c) | (a, b, c) <- pythagoreanNums n, gcd a b == 1]
-----------------------------------------
-- 順列と組み合わせ
-----------------------------------------
--
-- 順列の数
--
-- ex : permutationSize 5 3 => 60
--
permutationSize :: Integral a => a -> a -> a
permutationSize = fallingFactorial
--
-- 組み合わせの数
--
-- ex : combinationSize 5 3 => 10
--
combinationSize :: Integral a => a -> a -> a
combinationSize m n = div (fallingFactorial m n) (factorial n)
-----------------------------------------
-- その他
-----------------------------------------
--
-- 平方根の整数部分
--
isqrt :: Integral a => a -> a
isqrt = truncate . sqrt . fromIntegral
--
-- 整数か?(小数点以下は 0 か?)
--
isInteger :: RealFrac a => a -> Bool
isInteger = (== 0) . snd . properFraction
--
-- 下降階乗冪
--
fallingFactorial :: Integral a => a -> a -> a
fallingFactorial m n = product [m - n + 1 .. m]
--
-- 階乗
--
factorial :: Integral a => a -> a
factorial m = product [2 .. m]
--
-- 整数の桁数を求める
--
digits :: (Integral a, Show a) => a -> Int
digits = length . show
-----------------------------------------
-- オイラーのφ関数
-----------------------------------------
--
-- + 正の整数 n に対して、1 から n までの自然数のうち n と互いに素な
-- ものの個数(1 と n は互いに素と考える)
--
-- + factorize n => [(a, i), (b, j), (c, l) ...] の時、
-- phi n = n * (1 - 1 / a) * (1 - 1 / b) * (1 - 1 / c) * ...
-- = n * (a - 1) / a * (b - 1) / b * (c - 1) / c * ...
-- = a ^ (i - 1) * (a - 1) * b ^ (j - 1) * (b - 1) * ...
--
phi :: Integral a => a -> a
phi n = product [p^(i - 1) * (p - 1) | (p, i) <- factorize n]
-----------------------------------------
-- メビウス関数
-----------------------------------------
--
-- + 定義(ただし 1 は 0 個の素因数を持つと考える):
-- μ(n) = 0 (n が平方因子を持つ時)
-- μ(n) = (-1)^k (n が相異なる k 個の素因数に分解されるとき)
--
mobius :: Integral a => a -> a
mobius n
| any (>= 2) is = 0
| even (length is) = 1
| otherwise = -1
where is = [i | (_, i) <- factorize n]
-----------------------------------------
-- 2 進表現のビット数を返す
-----------------------------------------
binarySize :: Integral a => a -> Int
binarySize = length . integralToList 2
-----------------------------------------
-- ペル方程式
-----------------------------------------
--
-- + "x^2 - d * y^ = 1" の解 (x, y) (x > 1, y > 1) を小さい順に返す。
--
-- + from http://www004.upp.so-net.ne.jp/s_honma/pell/pell.htm
--
pell'sEquation :: Integer -> [(Integer, Integer)]
pell'sEquation d = iterate (f (x, y)) (x, y)
where
f (a1, b1) (a2, b2) = (a1 * a2 + d * b1 * b2, a1 * b2 + a2 * b1)
(x, y) = loop 0 1 k0 1 0
where
k0 = (truncate . sqrt . fromIntegral) d
loop g1 h1 k1 y0 y1
| g1 == g2 = g $ f (x1, y1) (x1, y1)
| h1 == h2 = let ns = g $ f (x1, y1) (x2, y2) in f ns ns
| otherwise = loop g2 h2 k2 y1 y2
where
g2 = k1 * h1 - g1
h2 = div (d - g2^2) h1
k2 = div (k0 + g2) h2
y2 = y0 + k1 * y1
x1 = g1 * y1 + h1 * y0
x2 = g2 * y2 + h2 * y1
g (x, y) = (div x h1, div y h1)
| little-schemer/MyModule | NumberTheory.hs | mit | 8,638 | 0 | 16 | 1,910 | 2,536 | 1,409 | 1,127 | 101 | 2 |
-- The Purr platform has the following libraries
-- | Core functionality of Purr
module Purr.Core where
-- | Attachs documentation to an object
_ doc: String -> Function -> Function
-- | Retrieves documentation from an object
a doc -> Maybe String
-- | Alias to `true`
otherwise -> Boolean
-- | Retrieves the internal `tag' of an object
a tag -> String
-- | Predicates
a Number? -> Boolean
a String? -> Boolean
a Boolean? -> Boolean
a Function? -> Boolean
a Ordering? -> Boolean
a Maybe? -> Boolean
a Either? -> Boolean
a List? -> Boolean
a Equality? -> Boolean
a Ordered? -> Boolean
a Representable? -> Boolean
a Bounded? -> Boolean
a Enumerable? -> Boolean
a Indexable? -> Boolean
a Sliceable? -> Boolean
a Semigroup? -> Boolean
a Monoid? -> Boolean
a Functor? -> Boolean
a Applicative? -> Boolean
a Chainable? -> Boolean
-- | Data structures
data Ordering = Less | Equal | Greater
data Maybe = Nothing | a Just
data Either = a Failure | a Success
data List = Nil | a :: List
data DivisionResult { quotient :: Integral, remainder :: Integral }
-- | Protocols
class Equality where
a === a -> Boolean
a =/= a -> Boolean
class Equality => Ordered where
a compare-to: a -> Ordering
a < a -> Boolean
a > a -> Boolean
a <= a -> Boolean
a >= a -> Boolean
a max: a -> a
a min: a -> a
class BooleanAlgebra where
a || a -> a -- Disjunction
a && a -> a -- Conjunction
not(a) -> a -- Negation
class Numeric where
a - a -> a
a * a -> a
a negate -> a
a absolute -> a
class Numeric => Integral where
a divide-by: a -> DivisionResult
a modulus: a -> a
class Numeric => Floating where
a / a -> a
a truncate -> a
a round -> a
a ceiling -> a
a floor -> a
a nan? -> a
a infinite? -> a
a finite? -> a
a negative-zero? -> a
class Representable where
a to-string -> String
class Parseable where
Parseable parse: String -> Either(String, a)
class Bounded where
B a lower-bound -> a
B a upper-bound -> a
class (Bounded, Ordered) => Enumerable where
a successor -> a
a predecessor -> a
a up-to: a -> List a
class Indexable where
I a at: b -> Maybe a
I a includes?: b -> Boolean
class Indexable => Container where
M a at: b put: a -> M a
M a remove-at: b -> M a
class (Bounded, Indexable) => Sliceable where
S a slice-from: b to: b -> S a
class Semigroup where
S a + S a -> S a
class Semigroup => Monoid where
M a empty -> M a
class Functor where
F a map: (a -> b) -> F b
class Functor => Applicative where
A a of: a -> A a
A (a -> b) apply-to: A a -> A b
class Applicative => Chainable where
C a chain: (a -> C b) -> C b
class Applicative => Alternative where
A a none -> A a
A a <|> A a -> A a
class Monoid => Foldable where
F a fold-right: (a, b -> b) from: b -> b
F a fold -> Monoid
F a fold-using: (a -> Monoid) -> Monoid
F a fold: (b, a -> b) from: b -> b
-- | Data structures
module Data.Boolean where
data Boolean = false | true
deriving Equality, Ordered, Representable, Parseable, Bounded, Enumerable, BooleanAlgebra
a Boolean? -> Boolean
Boolean then: (-> b) else: (-> b) -> b
module Data.Char where
type Char = Int
deriving Equality, Ordered, Bounded, Representable, Enumerable
a Char? -> Boolean
Char control? -> Boolean
Char space? -> Boolean
Char lower? -> Boolean
Char upper? -> Boolean
Char alpha? -> Boolean
Char alpha-numeric? -> Boolean
Char digit? -> Boolean
Char octal-digit? -> Boolean
Char hexadecimal-digit? -> Boolean
Char letter? -> Boolean
Char uppercase -> Char
Char lowercase -> Char
Char code -> Int
Int to-char -> Char
module Data.String where
type String = [Char]
deriving Equality, Ordered, Representable, Indexable, Sliceable
, Semigroup, Monoid
a String? -> Boolean
String uppercase -> String
String lowercase -> String
String trim -> String
String trim-left -> String
String trim-right -> String
module Data.Number where -- IEEE 754 Double-Precision foating points
type Number
deriving Equality, Ordered, Numeric, Integral, Floating, Representable, Parseable
, Bounded, Enumerable, Semigroup, Monoid
module Data.List where
data List = Nil | a :: List
deriving Equality, Representable, Bounded, Indexable, Sliceable, Container
, Semigroup, Functor, Applicative, Chainable, Foldable
a List? -> Boolean
module Data.Vector where
type Vector
deriving Equality, Representable, Bounded, Indexable, Sliceable, Container
, Semigroup, Functor, Applicative, Chainable, Foldable
a Vector? -> Boolean
vector: List -> Vector
module Data.Set where
type Set
deriving Equality, Representable, Indexable, Semigroup, Monoid
a Set? -> Boolean
set: List -> Set
Set put: a -> Set
Set remove: a -> Set
module Data.Map where
data MapEntry = Key ~> Value
type Map
deriving Equality, Representable, Indexable, Container, Semigroup, Monoid
, Functor, Applicative, Chainable, Foldable
a Map? -> Boolean
map: List -> Map
module Data.Maybe where
data Maybe = Nothing | a Just
deriving Equality, Representable, Semigroup, Monoid, Functor, Applicative, Chainable, Foldable, Alternative
a Maybe? -> Boolean
module Data.Either where
data Either = a Failure | a Success
deriving Equality, Representable, Semigroup, Monoid, Functor, Applicative, Chainable, Foldable, Alternative
a Either? -> Boolean
module Data.Validation where
data Validation = a Failure | a Success
deriving Equality, Representable, Semigroup, Functor, Applicative, Alternative
a Validation? -> Boolean
module Data.Record where
data Record = { String -> a }
deriving Equality, Representable, Indexable, Container, Semigroup, Monoid, Functor, Applicative,
Chainable, Foldable
a Record? -> Boolean
Record clone -> Record
Record with: Record -> Record
Record without: [String] -> Record
Record rename: String to: String -> Record
Record rename: [(String, String)] -> Record
module Data.Task where
data Task = ((Either -> Unit) -> Unit) Cleanup: Function
deriving Representable, Semigroup, Monoid, Functor, Applicative, Chainable, Alternative
a Task? -> Boolean
task: Function -> Task
task: Function cleanup: Function -> Task
fail: a -> Task
Task run: (a -> Unit) recover: (b -> Unit) -> Unit
Task run: (a -> Unit) -> Unit
module Data.Stream where
-- <TODO>
module Data.Queue where
-- <TODO>
module Data.Deque where
-- <TODO>
module Data.Stack where
-- <TODO>
module Data.Date where
-- <TODO>
module Data.Error where
-- <TODO>
module Data.TimeUnit where
-- <TODO>
module Control.Monad where
[Monad(a)] sequence-with: Monad(a) -> Monad([a])
Monoid(a) when: Boolean -> Monoid
Monoid(a) unless: Boolean -> Monoid
Functor(a) void -> Functor(a)
Monad(Monad(a)) flatten -> Monad(a)
(a -> b) lift-to: Monad(a) -> (Monad(a) -> Monad(b))
(a, b -> c) lift-to: Monad(a) and: Monad(b) -> (Monad(a), Monad(b) -> Monad(c))
(a, b, c -> d) lift-to: Monad(a) and: Monad(b) and: Monad(c) -> (Monad(a), Monad(b), Monad(c) -> Monad(d))
(a, b, c, d -> e) lift-to: Monad(a) and: Monad(b) and: Monad(c) and: Monad(d) -> (Monad(a), Monad(b), Monad(c), Monad(d) -> Monad(e))
module Concurrency.Asyc where
never -> Task
[Task(a, b)] sequentially -> Task(a, [b])
[Task(a, b)] parallel -> Task(a, [b])
Task(a, b) or: Task(a, b) -> Task(a, b)
[Task(a, b)] choose-first -> Task(a, b)
[Task(a, b)] try-all -> Task([a], b)
module Concurrency.Timer where
Int32 delay -> Task(Error, Unit)
Int32 timeout -> Task(Error, Unit)
module Concurrency.Channel where
-- <TODO>
module Debug.Trace where
-- <TODO>
module Io.Console where
Representable display -> Task(_, Unit)
Representable display-error -> Task(_, Unit)
Representable display-warning -> Task(_, Unit)
Representable display-info -> Task(_, Unit)
String write -> Task(_, Unit)
String get-line -> Task(_, String)
module Io.FileSystem.Path where
data Path = Relative | Root | Path \ String
deriving Equality, Representable, Parseable, Semigroup, Monoid
Path parent -> Path
Path filename -> Maybe String
Path extension -> Maybe String
Path relative? -> Boolean
Path absolute? -> Boolean
module Io.FileSystem where
data SymbolicLinkType = Directory | File | Junction
Path rename-to: Path -> Task(Error, Unit)
Path exists? -> Task(Error, Boolean)
Path change-owner: UserID group: GroupID -> Task(Error, Unit)
Path change-mode: Mode -> Task(Error, Unit)
Path link-to: Path -> Task(Error, Unit)
Path link-to: Path type: SymbolicLinkType -> Task(Error, Unit)
Path real-path -> Task(Error, Path)
Path read-link -> Task(Error, String)
Path file? -> Task(Error, Boolean)
Path directory? -> Task(Error, Boolean)
Path remove -> Task(Error, Unit) -- | Can be either File or Directory
Path remove-recursively -> Task(Error, Unit)
Path make-directory -> Task(Error, Unit) -- | Recursive
Path make-directory: Mode -> Task(Error, Unit) -- | Recursive
Path list-directory -> Task(Error, [Path])
Path list-directory-recursively -> Task(Error, [Path])
Path read-as: Encoding -> Task(Error, String)
Path read -> Task(Error, String) -- | assumes utf-8
Path write: String mode: Mode encoding: Encoding -> Task(Error, Unit)
Path write: String -> Task(Error, Unit)
Path append: String mode: Mode encoding: Encoding -> Task(Error, Unit)
Path append: String -> Task(Error, Unit)
module Io.Process where
-- <TODO>
module Io.Shell where
-- <TODO>
module Io.Zip where
-- <TODO>
module Io.Crypto where
-- <TODO>
module Web.Http where
-- <TODO>
module Web.Data where
data Method = OPTIONS | GET | HEAD | POST | PUT | DELETE | TRACE | CONNECT
data Status = Continue
| Switching-Protocols
| Ok
| Created
| Accepted
| Non-Authoritative-Information
| No-Content
| Reset-Content
| Partial-Content
| Multiple-Choices
| Moved-Permanently
| Found
| See-Other
| Not-Modified
| Use-Proxy
| Temporary-Redirect
| Bad-Request
| Unauthorised
| Payment-Required
| Forbidden
| Not-Found
| Method-Not-Allowed
| Not-Acceptable
| Proxy-Authentication-Required
| Request-Timeout
| Conflict
| Gone
| Length-Required
| Precondition-Failed
| Request-Entity-Too-Large
| Request-URI-Too-Long
| Unsupported-Media-Type
| Request-Range-Not-Satisfiable
| Expectation-Failed
| Internal-Server-Error
| Not-Implemented
| Bad-Gateway
| Service-Unavailable
| Gateway-Timeout
| HTTP-Version-Not-Supported
-- <TODO>
module Web.Data.Uri where
-- <TODO>
module Web.Server where
type Application = Request -> Task(Error, Response)
type Middleware = Application -> Application
-- <TODO>
module Database.MySql where
-- <TODO>
module Database.Redis where
-- <TODO>
module Database.Sqlite3 where
-- <TODO>
module Language.Parsing where
-- <TODO>
module Language.Json where
-- <TODO>
module Language.Html where
-- <TODO>
module Language.Sql where
-- <TODO>
module Test.QuickCheck where
-- <TODO>
| igalic/purr | docs/platform.hs | mit | 11,663 | 356 | 38 | 2,938 | 2,241 | 1,524 | 717 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Antemodulum.List.NonEmpty (
groupBy1Transitive,
snocList,
module Export
) where
--------------------------------------------------------------------------------
import Antemodulum.ClassyPrelude
import Data.List.NonEmpty as Export
--------------------------------------------------------------------------------
-- | _O(n)_ 'snoc' onto a list.
snocList :: [a] -> a -> NonEmpty a
snocList xs x = Export.fromList $ xs ++ [x]
-- | Similar to 'Data.List.NonEmpty.groupBy1' but with a function argument that
-- only needs transitivity, not equality.
--
-- See the following on how 'groupBy' expects equality:
-- http://stackoverflow.com/questions/1316365/haskell-surprising-behavior-of-groupby
groupBy1Transitive :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty (NonEmpty a)
groupBy1Transitive cmp = go
where
go (x:|[]) = (x :| []) :| []
go (x:|xs@(x2:rest)) =
case grouped of
[] -> (x :| []) <| go (x2:|rest)
(g:gs) -> let grouping = g :| gs in
case ungrouped of
[] -> grouping :| []
(u:us) -> grouping <| go (u:|us)
where
(grouped, ungrouped) = spanNeighbor cmp (x:xs)
-- | Run a comparison function among neighbors.
spanNeighbor :: (a -> a -> Bool) -> [a] -> ([a],[a])
spanNeighbor p = go False
where
go _ (x1:rest@(x2:_))
| p x1 x2 = let (ys, zs) = go True rest in (x1:ys,zs)
go carry (x1:rest)
| carry = ([x1], rest)
go _ xs = ([], xs)
| docmunch/antemodulum | src/Antemodulum/List/NonEmpty.hs | mit | 1,529 | 0 | 18 | 353 | 494 | 269 | 225 | 27 | 4 |
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GADTs #-}
module Vyom.Term.TupleSym where
import Data.Kind (Type)
import Vyom
-- Literal values
class TupleSym r where
tuple :: r h a -> r h b -> r h (a,b)
first :: r h (a,b) -> r h a
second :: r h (a,b) -> r h b
instance TupleSym Run where
tuple = rop2 (,)
first = rop1 fst
second = rop1 snd
instance TupleSym Pretty where
tuple = sop2 ","
first = sop1 "first"
second = sop1 "second"
instance TupleSym Expr where
tuple = eop2 "Tuple"
first = eop1 "First"
second = eop1 "Second"
deserialise :: TupleSym r => ExtensibleDeserialiser r
deserialise _ self (Node "Tuple" [e1, e2]) env = do
Dyn t1 d1 <- self e1 env
Dyn t2 d2 <- self e2 env
return $ Dyn (App (App (typeRep @(,)) t1) t2) (tuple d1 d2)
deserialise _ _ (Node "Tuple" es) _ = Left $ "Invalid number of arguments, expected 2, found " ++ show (length es)
deserialise _ self (Node "First" [e]) env = do
Dyn t d <- self e env
case t of
App (App tc ta) tb -> do
case (typeRep @Type `eqTypeRep` typeRepKind t, tc `eqTypeRep` typeRep @(,)) of
(Just HRefl, Just HRefl) -> return $ Dyn ta (first d)
_ -> Left $ "Expected type: (" ++ show ta ++ "," ++ show tb ++ "). Found type: " ++ show t
_ -> Left $ "Expected type: (a,b). Found type: " ++ show t
deserialise _ _ (Node "First" es) _ = Left $ "Invalid number of arguments, expected 2, found " ++ show (length es)
deserialise _ self (Node "Second" [e]) env = do
Dyn t d <- self e env
case t of
App (App tc ta) tb -> do
case (typeRep @Type `eqTypeRep` typeRepKind t, tc `eqTypeRep` typeRep @(,)) of
(Just HRefl, Just HRefl) -> return $ Dyn tb (second d)
_ -> Left $ "Expected type: (" ++ show ta ++ "," ++ show tb ++ "). Found type: " ++ show t
_ -> Left $ "Expected type: (a,b). Found type: " ++ show t
deserialise _ _ (Node "Second" es) _ = Left $ "Invalid number of arguments, expected 2, found " ++ show (length es)
deserialise old self e env = old self e env
| ajnsit/vyom | src/Vyom/Term/TupleSym.hs | mit | 2,047 | 0 | 20 | 502 | 874 | 432 | 442 | 47 | 5 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}
module JoScript.Pass.LexerTest (tests) where
import Protolude
import Data.Conduit
import Data.Conduit.List (sourceList)
import qualified Data.Sequence as Seq
import Text.Show.Pretty (ppShow)
import Test.HUnit
import JoScript.Data.Block
import JoScript.Data.Debug
import JoScript.Data.Lexer
import JoScript.Util.Debug (consumeLexerPass)
import JoScript.Data.Config (FileBuildConfig(FileBC), runFileBuildM)
import JoScript.Pass.Lexer (runLexerPass)
import qualified JoScript.Data.Position as Position
tests :: [Test]
tests =
[ TestLabel "JoScript.Pass.Lexer (integers)" lexerUnsignedInteger
, TestLabel "JoScript.Pass.Lexer (floats)" lexerUnsignedFloat
, TestLabel "JoScript.Pass.Lexer (signed integers)" lexerSignedInteger
, TestLabel "JoScript.Pass.Lexer (signed floats)" lexerSignedFloat
]
--------------------------------------------------------------
-- Numbers --
--------------------------------------------------------------
lexerUnsignedInteger = TestCase $ do
tokens <- getLexerReprs [ BpLine "123" ]
assertEqual "line of int should equal" tokens [ LpInteger 123 ]
lexerUnsignedFloat = TestCase $ do
tokens <- getLexerReprs [ BpLine "69.11" ]
assertEqual "line of int should equal" tokens [ LpFloat 69.11 ]
lexerSignedInteger = TestCase $ do
tokens <- getLexerReprs [ BpLine "-123" ]
assertEqual "line of int should equal" tokens [ LpInteger (-123) ]
lexerSignedFloat = TestCase $ do
tokens <- getLexerReprs [ BpLine "-69.11" ]
assertEqual "line of int should equal" tokens [ LpFloat (-69.11) ]
--------------------------------------------------------------
-- Utility --
--------------------------------------------------------------
getLexerReprs :: [BpRepr] -> IO (Seq LpRepr)
getLexerReprs tokens = extract <$> (runParse tokens >>= withSuccess) where
-- drops the trailing new line for each result
extract = fmap (\(Lp repr _) -> repr)
. (\items -> Seq.take ((Seq.length items) - 2) items)
withSuccess :: FileDebug -> IO (Seq LexerPass)
withSuccess (FileDebug { output = PDebugLexer p, error = Nothing }) = pure p
withSuccess (FileDebug { error = Just er }) = failMessage (ppShow er)
withSuccess (FileDebug { output = _____________, error = Nothing }) =
failMessage "unexpected pass debug target"
failMessage m = assertFailure m >> undefined
runParse :: [BpRepr] -> IO FileDebug
runParse ts = runFileBuildM config (runConduitRes conduit) where
conduit = source .| runLexerPass .| consumeLexerPass
config = FileBC "test"
source = sourceList (fmap (\x -> Right (Bp x Position.init)) (ts <> [BpEnd]))
| AKST/jo | source/test/JoScript/Pass/LexerTest.hs | mit | 2,807 | 0 | 17 | 546 | 683 | 369 | 314 | 49 | 3 |
{-# LANGUAGE CPP #-}
module Main ( main
) where
import Hlockx
import Paths_hlockx (version)
import Data.Version (showVersion)
import Foreign.C.Types (CUInt)
import System.Environment
import System.Exit
import System.IO
import System.Console.GetOpt
data Options = Options { optSLock :: Bool
, optKiosk :: Bool
, optTimeout :: CUInt }
startOptions :: Options
#ifdef DEF_SLOCK
startOptions = Options { optSLock = True
#else
startOptions = Options { optSLock = False
#endif
, optTimeout = 2
, optKiosk = False
}
options :: [ OptDescr (Options -> IO Options) ]
options =
[ Option "v" ["version"]
(NoArg
(\_ -> do
prg <- getProgName
hPutStrLn stderr (prg ++ " version " ++ showVersion version)
exitSuccess))
"Print version"
, Option "h" ["help"]
(NoArg
(\_ -> do
prg <- getProgName
hPutStrLn stderr (usageInfo prg options)
exitSuccess))
"Show help"
, Option "t" ["timeout"]
(ReqArg
(\arg opt -> return opt { optTimeout = read arg }) "Seconds")
"Set DPMS timeout (default: 2s)"
, Option "k" ["kiosk"]
(NoArg
(\opt -> return opt { optKiosk = True}))
"Sets kiosk mode (no black screen)"
, Option "s" ["slock"]
(NoArg
(\opt -> return opt { optSLock = True }))
#ifdef DEF_SLOCK
"Enable slock mode (default)"
#else
"Enable slock mode"
#endif
, Option "l" ["lockx"]
(NoArg
(\opt -> return opt { optSLock = False }))
#ifdef DEF_SLOCK
"Enable lockx mode"
#else
"Enable lockx mode (default)"
#endif
]
main :: IO ()
main = do
args <- getArgs
-- Parse options, getting a list of option actions
let (actions, _, _) = getOpt RequireOrder options args
opts <- foldl (>>=) (return startOptions) actions
hlockx (optSLock opts) (optTimeout opts) (optKiosk opts)
| skinner33/hlockx | src/Main.hs | mit | 2,098 | 0 | 16 | 724 | 537 | 296 | 241 | 55 | 1 |
module Main where
import Parser
import System.IO
process :: String -> IO ()
process line = do
let res = parseToplevel line
case res of
Left err -> print err
Right ex -> mapM_ print ex
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
loop
where
loop = do
putStr "ready> "
input <- getLine
case input of
"" -> putStrLn "Goodbye."
input -> do
process input
loop
| e-jigsaw/kaleidoscope | Main.hs | mit | 431 | 0 | 14 | 134 | 156 | 72 | 84 | 21 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfilter.html
module Stratosphere.ResourceProperties.SSMPatchBaselinePatchFilter where
import Stratosphere.ResourceImports
-- | Full data type definition for SSMPatchBaselinePatchFilter. See
-- 'ssmPatchBaselinePatchFilter' for a more convenient constructor.
data SSMPatchBaselinePatchFilter =
SSMPatchBaselinePatchFilter
{ _sSMPatchBaselinePatchFilterKey :: Maybe (Val Text)
, _sSMPatchBaselinePatchFilterValues :: Maybe (ValList Text)
} deriving (Show, Eq)
instance ToJSON SSMPatchBaselinePatchFilter where
toJSON SSMPatchBaselinePatchFilter{..} =
object $
catMaybes
[ fmap (("Key",) . toJSON) _sSMPatchBaselinePatchFilterKey
, fmap (("Values",) . toJSON) _sSMPatchBaselinePatchFilterValues
]
-- | Constructor for 'SSMPatchBaselinePatchFilter' containing required fields
-- as arguments.
ssmPatchBaselinePatchFilter
:: SSMPatchBaselinePatchFilter
ssmPatchBaselinePatchFilter =
SSMPatchBaselinePatchFilter
{ _sSMPatchBaselinePatchFilterKey = Nothing
, _sSMPatchBaselinePatchFilterValues = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfilter.html#cfn-ssm-patchbaseline-patchfilter-key
ssmpbpfKey :: Lens' SSMPatchBaselinePatchFilter (Maybe (Val Text))
ssmpbpfKey = lens _sSMPatchBaselinePatchFilterKey (\s a -> s { _sSMPatchBaselinePatchFilterKey = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfilter.html#cfn-ssm-patchbaseline-patchfilter-values
ssmpbpfValues :: Lens' SSMPatchBaselinePatchFilter (Maybe (ValList Text))
ssmpbpfValues = lens _sSMPatchBaselinePatchFilterValues (\s a -> s { _sSMPatchBaselinePatchFilterValues = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/SSMPatchBaselinePatchFilter.hs | mit | 1,947 | 0 | 12 | 205 | 264 | 151 | 113 | 27 | 1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, ParallelListComp #-}
{-|
Module: Text.PhonotacticLearner.PhonotacticConstraints.FileFormats
Description: Generation of candidate constraint sets.
Copyright: © 2016-2017 George Steel and Peter Jurgec
License: GPL-2+
Maintainer: [email protected]
Functions for saving and loading lexicons and 'ClassGlob' constraint grammars in standard formats.
-}
module Text.PhonotacticLearner.PhonotacticConstraints.FileFormats where
import Control.Monad
import Data.Traversable
import Data.Monoid
import Data.Foldable
import Text.Read
import Data.List
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Array.IArray
import Numeric
import Control.DeepSeq
import Text.PhonotacticLearner.PhonotacticConstraints
import Text.PhonotacticLearner.MaxentGrammar
import Text.PhonotacticLearner.Util.Ring
-- | Given a set of possible segments and a string, break a string into segments.
-- Uses the rules in Fiero orthography (a phonetic writing system using ASCII characters) where the longest possible match is always taken and apostrophes are used as a digraph break.
segmentFiero :: S.Set String -- ^ All possible segments
-> String -- ^ Raw text
-> [String] -- ^ Segmented text
--segmentFiero [] = error "Empty segment list."
segmentFiero allsegs = go msl where
msl = maximum . S.map length $ allsegs
go _ [] = []
go _ ('\'':xs) = go msl xs
go 0 (x:xs) = go msl xs
go len xs | S.member seg allsegs = seg : go msl rest
| otherwise = go (len-1) xs
where (seg,rest) = splitAt len xs
-- | Joins segments together using Fiero rules. Inserts apostrophes where necerssary.
joinFiero :: S.Set String -- ^ All possible segments
-> [String] -- ^ Segmented text
-> String -- ^ Raw text
joinFiero allsegs = go where
msl = maximum . S.map length $ allsegs
go [] = []
go [x] = x
go (x:xs@(y:_)) = let z = x++y
in if any (\s -> isPrefixOf s z && not (isPrefixOf s x)) allsegs
then x ++ ('\'' : go xs)
else x ++ go xs
-- | Structure for reperesenting lexicon entries
data LexRow = LexRow [String] Int
-- | Parse a lexicon from a file. Segmentation of a word uses fiero rules (which will also decode space-separated segments and single-character segments).
-- Words may optionally be followed by a tab character and an integer indicating frequency (1 by default).
parseWordlist :: S.Set String -> T.Text -> [LexRow]
parseWordlist segs rawlist = do
line <- T.lines rawlist
let (rawword : rest) = T.split (== '\t') line
w = segmentFiero segs (T.unpack rawword)
fr = fromMaybe 1 $ do
[f] <- return (rest >>= T.words)
readMaybe (T.unpack f)
guard (w /= [])
return $ LexRow w fr
-- | Collate a list of words and frequencies from raw phonetic text.
collateWordlist :: S.Set String -> T.Text -> [LexRow]
collateWordlist segs rawtext = fmap (uncurry LexRow) . M.assocs . M.fromListWith (+) $ do
rawword <- T.words rawtext
let w = segmentFiero segs (T.unpack rawword)
guard (w /= [])
return (w, 1)
-- | Serializes a list of words and frequerncies to a string for decoding with 'parseWordlist'. Connects segments using Fiero rules.
serWordlist :: S.Set String -> [LexRow] -> T.Text
serWordlist segs = T.unlines . mapMaybe showRow where
showRow (LexRow _ n) | n <= 0 = Nothing
showRow (LexRow w 1) = Just . T.pack $ joinFiero segs w
showRow (LexRow w n) = Just . T.pack $ joinFiero segs w ++ "\t" ++ show n
-- | Serializes a list of words and frequerncies to a string for decoding with 'parseWordlist'. Puts spaces between segments.
serWordlistSpaced :: [LexRow] -> T.Text
serWordlistSpaced = T.unlines . mapMaybe showRow where
showRow (LexRow _ n) | n <= 0 = Nothing
showRow (LexRow w 1) = Just . T.pack $ unwords w
showRow (LexRow w n) = Just . T.pack $ unwords w ++ "\t" ++ show n
-- | Reperesentation of a 'ClassGlob' grammar.
data PhonoGrammar = PhonoGrammar {
lengthDist :: (Array Length Int), -- ^ Distribution of word lengths
constraintSet :: [ClassGlob], -- ^ Set of constraints
weightSet :: Vec -- ^ Set of weights in same order as constraints
} deriving (Eq, Show)
instance NFData PhonoGrammar where
rnf (PhonoGrammar lendist grammar weights) = rnf lendist `seq` rnf grammar `seq` rnf weights
-- | Parse a grammar from a file. Blank lines ans lines begining with # are ignored.
-- The first regular line must contain a list of (Length,Int) pairs and subsequent lines must contain a weight followed by a ClassGlob.
parseGrammar :: T.Text -> Maybe PhonoGrammar
parseGrammar rawgrammar = do
let noncomment l = not (T.null l) && (T.head l /= '#')
(fline:glines) <- return $ filter noncomment (T.lines rawgrammar)
lenlist <- readMaybe (T.unpack fline)
let maxlen = maximum (fmap fst lenlist)
lenarr = accumArray (+) 0 (1,maxlen) (filter ((> 0) . fst) lenlist)
readline l = do
let (wt, ct') = T.breakOn " " l
w::Double <- readMaybe (T.unpack wt)
(' ', ct) <- T.uncons ct'
c::ClassGlob <- readMaybe (T.unpack ct)
return (c,w)
cs <- traverse readline (reverse glines)
return $ PhonoGrammar lenarr (fmap fst cs) (vec (fmap snd cs))
-- | Serialize a grammar without length distribution
serGrammarRules :: [ClassGlob] -> Vec -> T.Text
serGrammarRules grammar weights =
(T.unlines . reverse) [T.pack $ showFFloat (Just 3) w " " ++ show c | c <- grammar | w <- coords weights]
-- | Serialize a grammar including length distribution
serGrammar :: PhonoGrammar -> T.Text
serGrammar (PhonoGrammar lendist grammar weights) =
"# Length Distribution:\n" <> (T.pack . show . assocs $ lendist) <> "\n\n# Constraints:\n" <> serGrammarRules grammar weights
| george-steel/maxent-learner | maxent-learner-hw/src/Text/PhonotacticLearner/PhonotacticConstraints/FileFormats.hs | gpl-2.0 | 5,947 | 1 | 17 | 1,317 | 1,629 | 837 | 792 | 95 | 4 |
module H03 where
k_ésimo :: [a] -> Int -> a
k_ésimo (x:_) 1 = x
k_ésimo (_:xs) k = k_ésimo xs (k - 1)
| dmunguia/H-99 | src/H03.hs | gpl-2.0 | 119 | 3 | 7 | 37 | 75 | 40 | 35 | 4 | 1 |
module Tests.Evaluation where
import Logic.SecPAL.Language
import Logic.SecPAL.Pretty
import Logic.General.Pretty()
import Logic.SecPAL.Parser
import Logic.SecPAL.Proof
import Text.Parsec
import Logic.SecPAL.Evaluable
import Logic.SecPAL.Context
import Tests.Testable
import System.IO.Unsafe (unsafePerformIO)
ppProof :: PShow x => [Proof x] -> String
ppProof [] = ""
ppProof p = ('\n':) . pShow . head $ p
makeAssertionUnsafe :: String -> Assertion
makeAssertionUnsafe x = case parse pAssertionUnsafe "" x of
(Left err) -> error . show $ err
(Right a) -> a
makeAssertion :: String -> Assertion
makeAssertion x = case parse pAssertion "" x of
(Left err) -> error . show $ err
(Right a) -> a
testEvaluationTruths :: [Test]
testEvaluationTruths = [inACTest1, condNoRename1]
testEvaluationFalsehoods :: [Test]
testEvaluationFalsehoods = [falseInACTest1, falseCondNoRename1]
testCanSay :: [Test]
testCanSay = [canSay01, canSayInf1]
testCanSayF :: [Test]
testCanSayF = [canSayInfFalse1]
testRenamingEval :: [Test]
testRenamingEval = [ condRename1, condRename2 , canSayRename1, testESSoSExample ]
testFunctions :: [Test]
testFunctions = [ testHasPermission]--, testHasntPermission, testHasntPermission2 ]
testCanActAs :: [Test]
testCanActAs = [ testCanActAs1 ]
-- An assertion is true if it is in the assertion context
inACTest1 :: Test
inACTest1 =
let
a = makeAssertionUnsafe "Alice says Bob is-cool;"
ctx = stdCtx{ ac=AC [a], d=Infinity }
prf = unsafePerformIO $ ctx ||- a
pPrf = ppProof prf
in
Test{ description = pShow ctx ++" |= "++pShow a ++ pPrf
, result = test . not . null $ prf
}
falseInACTest1 :: Test
falseInACTest1 =
let
a = makeAssertionUnsafe "Alice says Alice is-cool;"
b = makeAssertionUnsafe "Alice says Bob is-cool;"
ctx = stdCtx{ ac=AC [a], d=Infinity }
prf = unsafePerformIO $ ctx ||- b
pPrf = ppProof prf
in
Test{ description = pShow ctx ++" |= "++pShow b++pPrf
, result = test . null $ prf
}
-- Can we use the cond variable without renaming
condNoRename1 :: Test
condNoRename1 =
let
a = makeAssertionUnsafe "Alice says Bob is-cool;"
a' = makeAssertionUnsafe "Alice says Bob is-cool if Bob likes-jazz;"
b = makeAssertionUnsafe "Alice says Bob likes-jazz;"
ctx = stdCtx{ ac=AC [a', b], d=Infinity }
prf = unsafePerformIO $ ctx ||- a
pPrf = ppProof prf
in
Test{ description = pShow ctx ++" |= "++pShow a++pPrf
, result = test . not . null $ prf
}
--
falseCondNoRename1 :: Test
falseCondNoRename1 =
let
a = makeAssertionUnsafe "Alice says Bob is-cool;"
a' = makeAssertionUnsafe "Alice says Bob is-cool if Bob likes-jazz;"
b = makeAssertionUnsafe "Alice says Bob likes-jazz: False;"
ctx = stdCtx{ ac=AC [a', b], d=Infinity }
prf = unsafePerformIO $ ctx ||- a
pPrf = ppProof prf
in
Test{ description = pShow ctx ++" |= "++pShow a++pPrf
, result = test . null $ prf
}
canSay01 :: Test
canSay01 =
let q = makeAssertionUnsafe "Bob says Alice likes-jazz;"
a1 = makeAssertionUnsafe "Bob says Alice can-say 0 Alice likes-jazz;"
a2 = makeAssertionUnsafe "Alice says Alice likes-jazz;"
ctx = stdCtx{ ac=AC [a1,a2], d=Infinity }
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
canSayInf1 :: Test
canSayInf1 =
let q = makeAssertionUnsafe "Bob says Alice likes-jazz;"
a1 = makeAssertionUnsafe "Bob says Alice can-say inf Alice likes-jazz;"
a2 = makeAssertionUnsafe "Alice says Clive can-say 0 Alice likes-jazz;"
a3 = makeAssertionUnsafe "Clive says Alice likes-jazz;"
ctx = stdCtx{ ac=AC [a1,a2,a3], d=Infinity }
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
canSayInfFalse1 :: Test
canSayInfFalse1 =
let q = makeAssertionUnsafe "Bob says Alice likes-jazz;"
a1 = makeAssertionUnsafe "Bob says Alice can-say 0 Alice likes-jazz;"
a2 = makeAssertionUnsafe "Alice says Clive can-say 0 Alice likes-jazz;"
a3 = makeAssertionUnsafe "Clive says Alice likes-jazz;"
ctx = stdCtx{ ac=AC [a1,a2,a3], d=Infinity }
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . null $ prf
}
condRename1 :: Test
condRename1 =
let q = makeAssertionUnsafe "Bob says Alice likes-jazz;"
a1 = makeAssertionUnsafe "Bob says everyone likes-jazz;"
ctx = stdCtx{ ac=AC [a1], d=Infinity }
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
condRename2 :: Test
condRename2 =
let q = makeAssertionUnsafe "Bob says Alice likes-jazz;"
a1 = makeAssertionUnsafe "Bob says everyone likes-jazz if everyone is-human;"
a2 = makeAssertionUnsafe "Bob says Alice is-human;"
ctx = stdCtx{ ac=AC [a1, a2], d=Infinity }
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
canSayRename1 :: Test
canSayRename1 =
let q = makeAssertionUnsafe "Bob says Alice likes-jazz;"
a1 = makeAssertionUnsafe "Bob says anyone can-say 0 anyone likes-jazz;"
a2 = makeAssertionUnsafe "Alice says Alice likes-jazz;"
ctx = stdCtx{ ac=AC [a1, a2], d=Infinity }
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
testESSoSExample :: Test
testESSoSExample =
let q = makeAssertion "Phone says Game is-installable;"
a3 = makeAssertion "Phone says app is-installable if app meets(NotMalware), app meets(NoInfoLeaks);"
a4 = makeAssertion "anyone says app meets(policy) if evidence shows-meets(app, policy);"
a5 = makeAssertion "Phone says NILInferer can-say 0 app meets(NoInfoLeaks);"
a6 = makeAssertion "Phone says Google can-say inf app meets(NotMalware);"
a7 = makeAssertion "Google says AVChecker can-say 0 app meets(NotMalware);"
a8 = makeAssertion "AVChecker says Game meets(NotMalware);"
a9 = makeAssertion "NILInferer says Evidence shows-meets(Game,NoInfoLeaks);" -- Bit simplified
ctx = stdCtx{ac=AC [a3, a4, a5, a6, a7, a8, a9]}
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
testHasPermission :: Test
testHasPermission =
let q = makeAssertion "User says apk#App can-access-internet;"
a1 = makeAssertionUnsafe "anyone says apk#app can-access-internet: permissionsCheck(apk#app, \"INTERNET\") = True;"
ctx = stdCtx{ac=AC [a1]}
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
testHasntPermission :: Test
testHasntPermission =
let q = makeAssertion "User says apk#App cannot-access-internet;"
a1 = makeAssertionUnsafe "anyone says apk#app cannot-access-internet: permissionsCheck(apk#app, \"INTERNET\") = False;"
ctx = stdCtx{ac=AC [a1]}
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . null $ prf
}
testHasntPermission2 :: Test
testHasntPermission2 =
let q = makeAssertion "User says apk#App cannot-dance;"
a1 = makeAssertionUnsafe "anyone says#apk@app cannot-dance: permissionsCheck(apk#app, \"BOOGIE\") = False;"
ctx = stdCtx{ac=AC [a1]}
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
-- Tests for Can-act-as
testCanActAs1 :: Test
testCanActAs1 =
let q = makeAssertion "A says B okay;"
a = makeAssertion "A says B can-act-as C;"
b = makeAssertion "A says C okay;"
ctx = stdCtx{ac=AC [a,b]}
prf = unsafePerformIO $ ctx ||- q
pPrf = ppProof prf
in Test { description = pShow ctx ++ " |= " ++ pShow q ++ pPrf
, result = test . not . null $ prf
}
| bogwonch/SecPAL | tests/Tests/Evaluation.hs | gpl-3.0 | 8,664 | 0 | 12 | 2,179 | 2,336 | 1,263 | 1,073 | 190 | 2 |
{-
This file is part of pia.
pia is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
pia 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 pia. If not, see <http://www.gnu.org/licenses/>.
-}
{- |
Copyright : (c) Simon Woertz 2011-2012
Maintainer : Simon Woertz <[email protected]>
Stability : provisional
-}
module Polynomial (
Monomial(..)
, Polynomial(..)
, Var
, Coeff
, substitute
, subtractPolynomials
, addPolynomials
, normalize
, varsPolynomial
, monotone
, compatible
, linear
, dimension
) where
import Data.List(sort, sortBy, groupBy, group, union, find, intercalate)
import Numeric.LinearAlgebra(Matrix, mXm, ident, atIndex, minElement, rows, cols)
import Numeric.LinearAlgebra.Util(zeros)
import Util
type Coeff = Matrix Double
type Var = String
data Monomial = Monomial {coeff :: Coeff , vars :: [Var]}
newtype Polynomial = Polynomial [Monomial]
instance Show Monomial where
show = showMonomial
showMonomial :: Monomial -> String
showMonomial (Monomial c v) = coefficient `beside` variables where
variables | v == [] = ""
| otherwise = "*" ++ intercalate "*" v
coefficient = unlines (tail (lines . show $ c)) -- drop rol/col information of matrix
instance Eq Monomial where
(==) (Monomial a _ ) (Monomial b _ ) | a == b && a == zeros (rows a) (cols a) = True
(==) a b = ca == cb && a `sameVars` b
where (Monomial ca _) = a
(Monomial cb _) = b
instance Show Polynomial where
show = showPolynomial
showPolynomial :: Polynomial -> String
showPolynomial (Polynomial []) = ""
showPolynomial (Polynomial p) = show' p' where
show' [] = ""
show' [m] = show m
show' (m:ms) = (show m `beside` " +" )`beside` show' ms
dim = dimension (Polynomial p)
nonZero = filter (\m -> coeff m /= zeros dim dim && coeff m /= zeros dim 1) p
p' | nonZero == [] = [zero dim]
| otherwise = nonZero
{-
constant :: Monomial -> Bool
constant m | vars m == [] = True
| otherwise = False
-}
zero :: Int -> Monomial
zero dim = Monomial (zeros dim 1) []
sameVars :: Monomial -> Monomial -> Bool
sameVars (Monomial _ a) (Monomial _ b) | (sort a) == (sort b) = True
| otherwise = False
addPolynomials :: Polynomial -> Polynomial -> Polynomial
addPolynomials (Polynomial a) (Polynomial b) = Polynomial (a ++ b)
-- | 'subtractPolynomials' takes two polynomials and returns a polynomial which is the subtraction of these two
subtractPolynomials :: Polynomial -> Polynomial -> Polynomial
subtractPolynomials (Polynomial a) (Polynomial b) = Polynomial (a ++ (negateMonomials b))
-- |'normalize' takes a polynomial and combines monomials with the same variables and the constant factors e.g.
--
-- >>> normalize (Polynomial [Monomial 1 ["x"], Monomial 3 [], Monomial 2 ["x"], Monomial 1 ["y"], Monomial (-2) []]
-- [ 1.0 ] + [ 3.0 ]*x + [ 1.0 ]*y
--
normalize :: Polynomial -> Polynomial
normalize (Polynomial ms) = Polynomial (map sumMonomials groups)
where groups = groupBy sameVars $ sortBy variables (zero (dimension (Polynomial ms)):ms)
variables (Monomial _ a) (Monomial _ b) = compare (sort a) (sort b)
-- | 'sumMononmials' takes a list of 'Monomial's and sums up the coeffiecients. This only works if every 'Monomial' contains
-- excactly the same variables or none if its a constant factor
sumMonomials :: [Monomial] -> Monomial
sumMonomials m = foldl1 addMonomials m
negateMonomial :: Monomial -> Monomial
negateMonomial (Monomial c vs) = (Monomial (negate c) vs)
negateMonomials :: [Monomial] -> [Monomial]
negateMonomials m = map negateMonomial m
addMonomials :: Monomial -> Monomial -> Monomial
addMonomials a b | sameVars a b = Monomial (ca + cb) va
| otherwise = error "different variables"
where (Monomial ca va) = a
(Monomial cb _) = b
multiplyMonomials :: Monomial -> Monomial -> Monomial
multiplyMonomials (Monomial ca va) (Monomial cb vb) = Monomial (ca `mXm` cb) (va ++ vb)
-- | 'multiplyPolynomials' multiplies every 'Monomial' of the first 'Polynomial' with every 'Monomial' of the second
-- 'Polynomial'
multiplyPolynomials :: Polynomial -> Polynomial -> Polynomial
multiplyPolynomials (Polynomial p1) (Polynomial p2) = Polynomial [a `multiplyMonomials` b | a <- p1, b <- p2]
varsMonomials :: [Monomial] -> [Var]
varsMonomials ((Monomial _ vs):ms) = vs `union` (varsMonomials ms)
varsMonomials [] = []
-- | 'varsPolynomial' takes a polynomial and returns a list of variables which are occur in the polynomial
varsPolynomial :: Polynomial -> [Var]
varsPolynomial (Polynomial ms) = varsMonomials ms
-- | 'substitute' @sigma@ takes a polynomial and a map @sigma@ which contains the substitutions.
-- every variable gets substituted by the corresponding polynomial found in the map
substitute :: Polynomial -> [(Var, Polynomial)] -> Polynomial
substitute (Polynomial p) sigma= foldl1 (addPolynomials) (map substitueMonomial p) where
substitueMonomial (Monomial c vs) = foldl (multiplyPolynomials) (Polynomial [Monomial c []]) (map (var2Poly) vs) where
var2Poly var = maybe (Polynomial [Monomial (ident (dimension (Polynomial p))) [var]]) (snd) (findTuple var)
findTuple var = Data.List.find ((var == ) . fst) sigma
-- | 'compatible' @p@ takes a polynomial and checks if it is compatible, which means there are no negative coefficients
-- in the polynomial and the constant factor is positive
compatible :: Polynomial -> YesNoMaybe
compatible p = case comp of
True -> Yes
False -> case linear p of
True -> No
False -> Maybe
where
comp = all criteria ms
(Polynomial ms) = normalize p
criteria (Monomial c []) = minElement c >= 0 && atIndex c (0,0) > 0 --constant
criteria (Monomial c _) = minElement c >= 0 --coefficient
-- | 'monotone' @p@ takes a polynomial and checks if its monotonically increasing
monotone :: Polynomial -> YesNoMaybe
monotone p = case m of
True -> Yes
False -> case linear p of
True -> No
False -> Maybe
where
m = all criteria ms
(Polynomial ms) = normalize p
criteria (Monomial c [_]) = minElement c >= 0 && atIndex c (0,0) >= 1 -- linear coefficient
criteria (Monomial c _) = minElement c >= 0 --constant or non-linear coefficient
-- | 'dimension' @p@ takes a polynomial and returns the amount of rows (dimension of square matrices) of the first monomial
-- found in the polynomial
dimension :: Polynomial -> Int
dimension (Polynomial p) = rows matrix where
first = head p
matrix = coeff first
-- | 'linear' @p@ takes a polynomial and returns 'False' if the degree of the polynomial is greater then 1. Otherwise it returns 'True'
linear :: Polynomial -> Bool
linear (Polynomial p) = (maximum (lengths ++ [0])) < 2 where
lengths = map (\(Monomial _ v) -> length v) p
| swoertz/pia | src/Polynomial.hs | gpl-3.0 | 7,488 | 0 | 19 | 1,748 | 1,960 | 1,033 | 927 | 111 | 4 |
module FuncTorrent.PeerThreadData
(PeerThread(..),
PeerThreadAction(..),
PeerThreadStatus(..),
Piece,
TransferStats(..)
) where
import Control.Concurrent (MVar, ThreadId)
import Data.IORef (IORef)
import FuncTorrent.Peer
type Piece = Int
data PeerThreadStatus
= PeerCommError
| InitDone
| PeerReady
| PeerBusy
| Downloading
| Seeding
deriving (Eq,Show)
data PeerThreadAction
= InitPeerConnection
| GetPeerStatus
| GetPieces [Piece]
| Seed
| StayIdle
deriving (Eq,Show)
data PeerThread = PeerThread
{ peer :: Peer
, peerTStatus :: MVar PeerThreadStatus
, peerTAction :: MVar PeerThreadAction
, transferStats :: MVar TransferStats
, peerPieces :: MVar [Piece]
, downloadThread :: IORef (Maybe ThreadId)
}
data TransferStats = TransferStats
{ activePieces :: [Piece]
-- | Pieces which were downloaded after the last status fetch from
-- ControlThread
, downloadedInc :: [Piece]
, downloaded :: [Piece]
, queuePieces :: [Piece]
, dataRecieved :: Int
, dataSent :: Int
, totalDataR :: Int
, totalDataS :: Int
}
| jaseemabid/functorrent | src/FuncTorrent/PeerThreadData.hs | gpl-3.0 | 1,204 | 0 | 11 | 337 | 281 | 175 | 106 | 41 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- | Xapian database integration
module HsBooru.Xapian
( XapianM
, XapianDB
, localDB
, memoryDB
, runXM
, xapianStore
, txBegin
, txCommit
, sanitizeTag
) where
import Data.Char
import Data.Foldable
import Data.Time.Clock.POSIX
import System.FilePath.Posix (takeExtension)
import qualified Data.Text as T
import HsBooru.Types
import HsBooru.Xapian.FFI
runXM :: XapianM a -> BooruM a
runXM = ioEither . runXM_
-- * Internal constants
-- Term prefix mapping, for reusable tags
booruPrefix = "B" -- Booru name the post was scraped from
siteIDPrefix = "I" -- The site-specific ID
uploaderPrefix = "U" -- Post uploader, in the format id@site
ratingPrefix = "R" -- File rating, e.g. `safe` or `questionable`
extPrefix = "E" -- File extension, e.g. `png`
filePrefix = "F" -- Filename, so you can search for posts by name
tagPrefix = "" -- Generic content tags
-- Value mapping, for per-document unique identification and sorting
siteIDSlot = 0 -- Site-specific ID
scoreSlot = 1 -- User score assigned to the website
fileNameSlot = 2 -- Name the file is stored under
fileURLSlot = 3 -- URL the file was downloaded from
sourceSlot = 4 -- Website's literal "Source" field, if it has one
uploadedSlot = 5 -- Upload timestamp
-- * Utilities
addTag :: XapianDB -> Document -> Text -> Text -> XapianM ()
addTag db doc prefix (T.map toLower -> tag) = do
let fullTag = prefix <> tag
safeTag | T.null prefix = sanitizeTag tag
| otherwise = fullTag
addTerm doc $ fullTag
unless (safeTag == fullTag) $
addSynonym db safeTag fullTag
-- | Sanitize a tag by reducing it to the groups of of valid characters,
-- separated by _ characters. If the tag has no valid characters, the result is
-- simply "_" itself.
sanitizeTag :: Text -> Text
sanitizeTag tag | null validGroups = "_"
| otherwise = T.intercalate "_" validGroups
where validGroups = filter (not . T.null) $ T.split (not . isAlphaNum) tag
strVal :: Document -> ValueNumber -> Text -> XapianM ()
strVal doc val = addValStr doc val . T.map toLower
encVal :: Real a => Document -> ValueNumber -> a -> XapianM ()
encVal doc val = addValDouble doc val . realToFrac
-- | Encode a post and store it in the xapian database
xapianStore :: XapianDB -> Post -> XapianM ()
xapianStore _ PostDeleted{..} = return ()
xapianStore _ PostFailure{..} = return ()
xapianStore db PostSuccess{..} = do
doc <- newDoc
encVal doc siteIDSlot siteID
encVal doc scoreSlot score
encVal doc uploadedSlot $ utcTimeToPOSIXSeconds uploaded
strVal doc fileNameSlot fileName
strVal doc fileURLSlot fileURL
forM_ source $ strVal doc sourceSlot
addTag db doc booruPrefix $ T.pack postSite
addTag db doc siteIDPrefix $ T.pack (show siteID)
addTag db doc uploaderPrefix $ T.pack (show uploader ++ "@" ++ postSite)
addTag db doc ratingPrefix $ T.pack (show rating)
addTag db doc filePrefix $ fileName
addTag db doc extPrefix $ getExt fileName
forM_ tags $ addTag db doc tagPrefix
void $ addDocument db doc
getExt :: Text -> Text
getExt = T.pack . drop 1 . takeExtension . T.unpack
| haasn/hsbooru | src/HsBooru/Xapian.hs | gpl-3.0 | 3,255 | 0 | 14 | 746 | 842 | 425 | 417 | -1 | -1 |
module Id where
import Data.Text
data Identity = Identity
{ name :: Text } deriving (Eq, Show)
| patrickboe/wheel | src/lib/hs/Id.hs | gpl-3.0 | 100 | 0 | 8 | 22 | 35 | 21 | 14 | 4 | 0 |
{-# 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.BillingAccounts.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This method creates [billing
-- subaccounts](https:\/\/cloud.google.com\/billing\/docs\/concepts#subaccounts).
-- Google Cloud resellers should use the Channel Services APIs,
-- [accounts.customers.create](https:\/\/cloud.google.com\/channel\/docs\/reference\/rest\/v1\/accounts.customers\/create)
-- and
-- [accounts.customers.entitlements.create](https:\/\/cloud.google.com\/channel\/docs\/reference\/rest\/v1\/accounts.customers.entitlements\/create).
-- When creating a subaccount, the current authenticated user must have the
-- \`billing.accounts.update\` IAM permission on the parent account, which
-- is typically given to billing account
-- [administrators](https:\/\/cloud.google.com\/billing\/docs\/how-to\/billing-access).
-- This method will return an error if the parent account has not been
-- provisioned as a reseller account.
--
-- /See:/ <https://cloud.google.com/billing/ Cloud Billing API Reference> for @cloudbilling.billingAccounts.create@.
module Network.Google.Resource.CloudBilling.BillingAccounts.Create
(
-- * REST Resource
BillingAccountsCreateResource
-- * Creating a Request
, billingAccountsCreate
, BillingAccountsCreate
-- * Request Lenses
, bacXgafv
, bacUploadProtocol
, bacAccessToken
, bacUploadType
, bacPayload
, bacCallback
) where
import Network.Google.Billing.Types
import Network.Google.Prelude
-- | A resource alias for @cloudbilling.billingAccounts.create@ method which the
-- 'BillingAccountsCreate' request conforms to.
type BillingAccountsCreateResource =
"v1" :>
"billingAccounts" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] BillingAccount :>
Post '[JSON] BillingAccount
-- | This method creates [billing
-- subaccounts](https:\/\/cloud.google.com\/billing\/docs\/concepts#subaccounts).
-- Google Cloud resellers should use the Channel Services APIs,
-- [accounts.customers.create](https:\/\/cloud.google.com\/channel\/docs\/reference\/rest\/v1\/accounts.customers\/create)
-- and
-- [accounts.customers.entitlements.create](https:\/\/cloud.google.com\/channel\/docs\/reference\/rest\/v1\/accounts.customers.entitlements\/create).
-- When creating a subaccount, the current authenticated user must have the
-- \`billing.accounts.update\` IAM permission on the parent account, which
-- is typically given to billing account
-- [administrators](https:\/\/cloud.google.com\/billing\/docs\/how-to\/billing-access).
-- This method will return an error if the parent account has not been
-- provisioned as a reseller account.
--
-- /See:/ 'billingAccountsCreate' smart constructor.
data BillingAccountsCreate =
BillingAccountsCreate'
{ _bacXgafv :: !(Maybe Xgafv)
, _bacUploadProtocol :: !(Maybe Text)
, _bacAccessToken :: !(Maybe Text)
, _bacUploadType :: !(Maybe Text)
, _bacPayload :: !BillingAccount
, _bacCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BillingAccountsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bacXgafv'
--
-- * 'bacUploadProtocol'
--
-- * 'bacAccessToken'
--
-- * 'bacUploadType'
--
-- * 'bacPayload'
--
-- * 'bacCallback'
billingAccountsCreate
:: BillingAccount -- ^ 'bacPayload'
-> BillingAccountsCreate
billingAccountsCreate pBacPayload_ =
BillingAccountsCreate'
{ _bacXgafv = Nothing
, _bacUploadProtocol = Nothing
, _bacAccessToken = Nothing
, _bacUploadType = Nothing
, _bacPayload = pBacPayload_
, _bacCallback = Nothing
}
-- | V1 error format.
bacXgafv :: Lens' BillingAccountsCreate (Maybe Xgafv)
bacXgafv = lens _bacXgafv (\ s a -> s{_bacXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bacUploadProtocol :: Lens' BillingAccountsCreate (Maybe Text)
bacUploadProtocol
= lens _bacUploadProtocol
(\ s a -> s{_bacUploadProtocol = a})
-- | OAuth access token.
bacAccessToken :: Lens' BillingAccountsCreate (Maybe Text)
bacAccessToken
= lens _bacAccessToken
(\ s a -> s{_bacAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bacUploadType :: Lens' BillingAccountsCreate (Maybe Text)
bacUploadType
= lens _bacUploadType
(\ s a -> s{_bacUploadType = a})
-- | Multipart request metadata.
bacPayload :: Lens' BillingAccountsCreate BillingAccount
bacPayload
= lens _bacPayload (\ s a -> s{_bacPayload = a})
-- | JSONP
bacCallback :: Lens' BillingAccountsCreate (Maybe Text)
bacCallback
= lens _bacCallback (\ s a -> s{_bacCallback = a})
instance GoogleRequest BillingAccountsCreate where
type Rs BillingAccountsCreate = BillingAccount
type Scopes BillingAccountsCreate =
'["https://www.googleapis.com/auth/cloud-billing",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient BillingAccountsCreate'{..}
= go _bacXgafv _bacUploadProtocol _bacAccessToken
_bacUploadType
_bacCallback
(Just AltJSON)
_bacPayload
billingService
where go
= buildClient
(Proxy :: Proxy BillingAccountsCreateResource)
mempty
| brendanhay/gogol | gogol-billing/gen/Network/Google/Resource/CloudBilling/BillingAccounts/Create.hs | mpl-2.0 | 6,353 | 0 | 16 | 1,217 | 728 | 434 | 294 | 104 | 1 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.Wai.Predicate.Accept
( accept
, module Network.Wai.Predicate.MediaType
) where
import Control.Monad
import Data.ByteString (ByteString)
import Data.Monoid hiding (All)
import Data.Maybe
import Data.Predicate
import Data.Singletons.TypeLits (Symbol)
import Network.Wai.Predicate.Error
import Network.Wai.Predicate.Request
import Network.Wai.Predicate.MediaType
import Network.Wai.Predicate.Utility
import qualified Network.Wai.Predicate.Parser.MediaType as M
accept :: HasHeaders r
=> ByteString
-> ByteString
-> Predicate r Error (Media (t :: Symbol) (s :: Symbol))
accept t s r =
let mtypes = M.readMediaTypes "accept" r in
if null mtypes
then return (Media t s 1.0 [])
else case findMediaType t s mtypes of
m:_ -> Okay (1.0 - mediaQuality m) m
[] -> Fail (e406 & setMessage msg)
where
msg = "Expected 'Accept: " <> t <> "/" <> s <> "'."
findMediaType :: ByteString -> ByteString -> [M.MediaType] -> [Media t s]
findMediaType t s = mapMaybe (\m -> do
let mt = M.medType m
ms = M.medSubtype m
guard ((mt == "*" || t == mt) && (ms == "*" || s == ms))
return $ Media t s (M.medQuality m) (M.medParams m))
| twittner/wai-predicates | src/Network/Wai/Predicate/Accept.hs | mpl-2.0 | 1,547 | 0 | 16 | 350 | 448 | 246 | 202 | 35 | 3 |
-- |Common functions between exchanges.
module Exchange where
import Data.Scientific
data Kind = Bid -- ^ Buying order
| Trade -- ^ Completed trade
| Ask -- ^ Selling order
| Rate -- ^ Rate is used instead of trade when not
-- broadcasting full order book
deriving (Show,Ord,Eq)
data Key = Key { kind :: Kind -- ^ Record type
, level :: Scientific -- ^ Security price level in that
-- currency. (Zero in case of Rate).
, currency :: String -- ^ Currency used in prices
, security :: String -- ^ Security, like Bitcoin
, exchange :: String -- ^ Exchange name
} deriving (Show,Ord,Eq)
type Entry = (Key,Scientific)
| koodilehto/kryptoradio | data_sources/exchange/Exchange.hs | agpl-3.0 | 804 | 0 | 8 | 304 | 118 | 77 | 41 | 14 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
module QuantLib.PricingEngines
( module QuantLib.PricingEngines
) where
import QuantLib.Event
class Event e => PricingEngine a e where
peCalculate :: e->a->e
| paulrzcz/hquantlib | src/QuantLib/PricingEngines.hs | lgpl-3.0 | 223 | 0 | 8 | 50 | 51 | 28 | 23 | 6 | 0 |
module Main where
import qualified Control.Monad.Random as R
import qualified Data.List as L
import qualified Data.Map as M
type TransitionMap = M.Map (String, String) Rational
type MarkovChain = M.Map String [(String, Rational)]
addTransition :: TransitionMap -> (String, String) -> TransitionMap
addTransition m k = M.insertWith (+) k 1 m
fromTransitionMap :: TransitionMap -> MarkovChain
fromTransitionMap m =
M.fromList [(k, frequencies k) | k <- ks]
where ks = L.nub $ map fst $ M.keys m
frequencies a = map reduce $ filter (outboundFor a) $ M.toList m
outboundFor a k = fst (fst k) == a
reduce e = (snd (fst e), snd e)
generateSequence :: (R.MonadRandom m) => MarkovChain -> String -> m String
generateSequence m s
| not (null s) && last s == '.' = return s
| otherwise = do
s' <- R.fromList $ m M.! s
ss <- generateSequence m s'
return $ if null s then ss else s ++ " " ++ ss
fromSample :: [String] -> MarkovChain
fromSample ss = fromTransitionMap $ foldl addTransition M.empty $ concatMap pairs ss
where pairs s = let ws = words s in zipWith (,) ("":ws) ws
sample :: [String]
sample = [ "I am a monster."
, "I am a rock star."
, "I want to go to Hawaii."
, "I want to eat a hamburger."
, "I have a really big headache."
, "Haskell is a fun language."
, "Go eat a big hamburger."
, "Markov chains are fun to use."
]
main = do
s <- generateSequence (fromSample sample) ""
print s
| vasily-kartashov/playground | etc/markov.hs | apache-2.0 | 1,553 | 0 | 12 | 426 | 540 | 281 | 259 | 37 | 2 |
module OutClean where
import Treedef
import Util
import System.IO
import System.Exit
import Data.Maybe
------------------------------
-- cleanit
------------------------------
cleanit parseTree = do
h <- openCleanOut
prologue h
cleanServers h parseTree
cleanSegments h parseTree
cleanConnect h
cleanStopServers h parseTree
cleanRemoveServers h parseTree
cleanRemoveSegments h parseTree
closeCleanOut h
------------------------------
-- functions called by cleanup
------------------------------
openCleanOut = openFile "cleanup.ps1" WriteMode
prologue h = do
writeCleanOut h "# add power cli library"
writeCleanOut h "Add-PSSnapin VMWare.VimAutomation.Core"
cleanServers h tree = do
writeCleanOut h ""
writeCleanOut h "#------------------------------"
writeCleanOut h "# virtual servers to be removed"
writeCleanOut h "#------------------------------"
writeCleanOut h ""
ocleanvbl h tree
cleanSegments h tree = do
writeCleanOut h ""
writeCleanOut h "#---------------------------------------"
writeCleanOut h "# virtual network segments to be removed"
writeCleanOut h "#---------------------------------------"
writeCleanOut h ""
ocleansbl h tree
cleanConnect h = do
writeCleanOut h ""
writeCleanOut h "#-------------------"
writeCleanOut h "# connect to vcenter"
writeCleanOut h "#-------------------"
writeCleanOut h ""
writeCleanOut h "Connect-VIServer -Server $vcenter -User $vcenteruser -Password $vcenterpass"
cleanStopServers h tree = do
writeCleanOut h ""
writeCleanOut h "#---------------------"
writeCleanOut h "# stop virtual servers"
writeCleanOut h "#---------------------"
writeCleanOut h ""
ocleansvbl h tree
cleanRemoveServers h tree = do
writeCleanOut h ""
writeCleanOut h "#-----------------------"
writeCleanOut h "# remove virtual servers"
writeCleanOut h "#-----------------------"
writeCleanOut h ""
ocleanrvbl h tree
cleanRemoveSegments h tree = do
writeCleanOut h ""
writeCleanOut h "#------------------------"
writeCleanOut h "# remove virtual segments"
writeCleanOut h "#------------------------"
writeCleanOut h ""
ocleanrsbl h tree
closeCleanOut h = hClose h
writeCleanOut h s = hPutStrLn h s
-----------------------
-- supporting functions
-----------------------
---------------------------------
-- network segments to be removed
---------------------------------
ocleansbl h (BlockList BEmpty b) = ocleansb h b
ocleansbl h (BlockList a b) = do
ocleansbl h a
ocleansb h b
ocleansb h (SBlock a b) =
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ a ++ "\"")
ocleansb h _ = do
return ()
-----------------------
-- servers to be removed
-----------------------
ocleanvbl h (BlockList BEmpty b) = ocleanvb h b
ocleanvbl h (BlockList a b) = do
ocleanvbl h a
ocleanvb h b
ocleanvb h (SWBlock a b c d) = let z = findCNSL "name" b in
if z == Nothing
then
do
putStrLn ("Cleanup: Switch " ++ a ++ " has no name")
exitFailure
else
do
let y = fromJust z
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ y ++ "\"")
ocleanvb h (FBlock a b c d e) = let z = findCNSL "name" b in
if z == Nothing
then
do
putStrLn ("Cleanup: Firewall " ++ a ++ " has no name")
exitFailure
else
do
let y = fromJust z
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ y ++ "\"")
ocleanvb h (FBlock1 a b c d) = let z = findCNSL "name" b in
if z == Nothing
then
do
putStrLn ("Cleanup: Firewall " ++ a ++ " has no name")
exitFailure
else
do
let y = fromJust z
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ y ++ "\"")
ocleanvb h (NBlock a b c) = let z = findCNSL "name" b in
if z == Nothing
then
do
putStrLn ("Cleanup: Node " ++ a ++ " has no name")
exitFailure
else
do
let y = fromJust z
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ y ++ "\"")
ocleanvb h (NBlock1 a b c d) = let z = findCNSL "name" b in
if z == Nothing
then
do
putStrLn ("Cleanup: Node " ++ a ++ " has no name")
exitFailure
else
do
let y = fromJust z
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ y ++ "\"")
ocleanvb h (NBlock2 a b c d) = let z = findCNSL "name" b in
if z == Nothing
then
do
putStrLn ("Cleanup: Node " ++ a ++ " has no name")
exitFailure
else
do
let y = fromJust z
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ y ++ "\"")
ocleanvb h (KBlock a b c d) = let z = findCNSL "name" b in
if z == Nothing
then
do
putStrLn ("Cleanup: Kemp LB " ++ a ++ " has no name")
exitFailure
else
do
let y = fromJust z
writeCleanOut h ("$" ++ a ++ "_name = \"" ++ y ++ "\"")
ocleanvb h _ = do
return ()
---------------
-- stop servers
---------------
ocleansvbl h (BlockList BEmpty b) = ocleansvb h b
ocleansvbl h (BlockList a b) = do
ocleansvbl h a
ocleansvb h b
ocleansvb h (SWBlock a b c d) =
writeCleanOut h ("Stop-VM $" ++ a ++ "_name -Confirm:$false")
ocleansvb h (FBlock a b c d e) =
writeCleanOut h ("Stop-VM $" ++ a ++ "_name -Confirm:$false")
ocleansvb h (FBlock1 a b c d) =
writeCleanOut h ("Stop-VM $" ++ a ++ "_name -Confirm:$false")
ocleansvb h (NBlock a b c) =
writeCleanOut h ("Stop-VM $" ++ a ++ "_name -Confirm:$false")
ocleansvb h (NBlock1 a b c d) =
writeCleanOut h ("Stop-VM $" ++ a ++ "_name -Confirm:$false")
ocleansvb h (NBlock2 a b c d) =
writeCleanOut h ("Stop-VM $" ++ a ++ "_name -Confirm:$false")
ocleansvb h (KBlock a b c d) =
writeCleanOut h ("Stop-VM $" ++ a ++ "_name -Confirm:$false")
ocleansvb h _ = do
return ()
-----------------
-- remove servers
-----------------
ocleanrvbl h (BlockList BEmpty b) = ocleanrvb h b
ocleanrvbl h (BlockList a b) = do
ocleanrvbl h a
ocleanrvb h b
ocleanrvb h (SWBlock a b c d) =
writeCleanOut h ("Remove-VM -VM $" ++ a ++ "_name -Confirm:$false -DeletePermanently:$true")
ocleanrvb h (FBlock a b c d e) =
writeCleanOut h ("Remove-VM -VM $" ++ a ++ "_name -Confirm:$false -DeletePermanently:$true")
ocleanrvb h (FBlock1 a b c d) =
writeCleanOut h ("Remove-VM -VM $" ++ a ++ "_name -Confirm:$false -DeletePermanently:$true")
ocleanrvb h (NBlock a b c) =
writeCleanOut h ("Remove-VM -VM $" ++ a ++ "_name -Confirm:$false -DeletePermanently:$true")
ocleanrvb h (NBlock1 a b c d) =
writeCleanOut h ("Remove-VM -VM $" ++ a ++ "_name -Confirm:$false -DeletePermanently:$true")
ocleanrvb h (NBlock2 a b c d) =
writeCleanOut h ("Remove-VM -VM $" ++ a ++ "_name -Confirm:$false -DeletePermanently:$true")
ocleanrvb h (KBlock a b c d) =
writeCleanOut h ("Remove-VM -VM $" ++ a ++ "_name -Confirm:$false -DeletePermanently:$true")
ocleanrvb h _ = do
return ()
--------------------------
-- remove network segments
--------------------------
ocleanrsbl h (BlockList BEmpty b) = ocleanrsb h b
ocleanrsbl h (BlockList a b) = do
ocleanrsbl h a
ocleanrsb h b
ocleanrsb h (SBlock a b) =
writeCleanOut h ("Remove-VirtualSwitch -VirtualSwitch $" ++ a ++ "_name -Confirm:$false")
ocleanrsb h _ = do
return ()
| shlomobauer/BuildIT | src/OutClean.hs | apache-2.0 | 6,869 | 0 | 15 | 1,365 | 2,274 | 1,070 | 1,204 | 182 | 8 |
{- Copyright 2014 David Farrell <[email protected]>
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
module IRCD.Clients where
import Data.List (sort)
import Data.Char (toUpper)
import qualified Data.Map as M (insert, delete)
import qualified Data.IntMap as IM
import IRCD.Types
firstAvailableID :: Clients -> Int
firstAvailableID = f 1 . sort . IM.keys . byUid
where
f n (x:xs)
| n == x = f (succ n) xs
| otherwise = n
f n _ = n
insertClient :: Client -> Clients -> Clients
insertClient client clients = clients
{ byUid = byUid'
, byNick = byNick'
}
where byUid' = IM.insert (uid client) client (byUid clients)
byNick' = case nick client of
Nothing -> byNick clients
Just nick' -> M.insert (map toUpper nick') client (byNick clients)
deleteClient :: Client -> Clients -> Clients
deleteClient client clients = clients
{ byUid = byUid'
, byNick = byNick'
}
where byUid' = IM.delete (uid client) (byUid clients)
byNick' = case nick client of
Nothing -> byNick clients
Just nick' -> M.delete (map toUpper nick') (byNick clients)
replaceClient :: Client -> Client -> Clients -> Clients
replaceClient old new = insertClient new . deleteClient old
deleteClientByUid :: Int -> Clients -> Clients
deleteClientByUid uid' clients = case uid' `IM.lookup` byUid clients of
Nothing -> clients
Just cli -> deleteClient cli clients
| shockkolate/lambdircd | src/IRCD/Clients.hs | apache-2.0 | 1,966 | 0 | 12 | 453 | 473 | 246 | 227 | 34 | 2 |
module Day3_2 (main) where
import Data.List
main :: IO ()
main = do
input <- getLine
let (santa1Dirs, santa2Dirs) = splitDirections input
housesSanta1 = step santa1Dirs [(0,0)]
housesSanta2 = step santa2Dirs [(0,0)]
combinedHouses = length $ nub $ housesSanta1 ++ housesSanta2
putStrLn (show combinedHouses)
type House = (Int, Int)
splitDirections :: String -> (String, String)
splitDirections dirs =
splitDirections' dirs 0 ([], [])
where splitDirections' [] _index ret = ret
splitDirections' (d:ds) index (s1, s2) =
case mod index 2 of
0 -> splitDirections' ds (index+1) (s1++[d], s2)
1 -> splitDirections' ds (index+1) (s1, s2++[d])
step :: String -> [House] -> [House]
step [] hs = hs
step (dir:dirs) hs = step dirs (nextHouse dir (head hs) : hs)
nextHouse :: Char -> House -> House
nextHouse '^' (x, y) = (x, y-1)
nextHouse 'v' (x, y) = (x, y+1)
nextHouse '<' (x, y) = (x-1, y)
nextHouse '>' (x, y) = (x+1, y)
| ksallberg/adventofcode | 2015/src/Day3_2.hs | bsd-2-clause | 1,033 | 0 | 13 | 272 | 478 | 261 | 217 | 27 | 3 |
module Helpers.Model
( findOrCreate
, joinTables
, joinTables3
) where
import Prelude
import Yesod
import Data.Maybe (catMaybes)
import qualified Data.Map as M
findOrCreate :: ( YesodPersist m
, PersistUnique (YesodPersistBackend m (HandlerT m IO))
, PersistEntity v
, PersistMonadBackend (YesodPersistBackend m (HandlerT m IO)) ~ PersistEntityBackend v
)
=> v -> HandlerT m IO (Key v)
findOrCreate v = return . either entityKey id =<< runDB (insertBy v)
-- |
--
-- My solution to the N+1 problem:
--
-- > runDB $ do
-- > posts <- selectList [] []
-- > users <- selectList [] []
-- >
-- > let records = joinTables postUser posts users
-- >
-- > forM records $ \(post,user) -> do
-- > --
-- > -- ...
-- > --
--
joinTables :: (a -> Key b)
-> [Entity a]
-> [Entity b]
-> [(Entity a, Entity b)]
joinTables f as bs = catMaybes . for as $ \a -> fmap (\b -> (a,b)) $ lookupRelation f a bs
joinTables3 :: (a -> Key b)
-> (a -> Key c)
-> [Entity a]
-> [Entity b]
-> [Entity c]
-> [(Entity a, Entity b, Entity c)]
joinTables3 f g as bs cs = catMaybes . for as $ \a ->
case (lookupRelation f a bs, lookupRelation g a cs) of
(Just b, Just c) -> Just (a,b,c)
_ -> Nothing
lookupRelation :: (a -> Key b) -> Entity a -> [Entity b] -> Maybe (Entity b)
lookupRelation f a bs = let k = f $ entityVal a
vs = M.fromList $ map (\(Entity k' v) -> (k',v)) bs
in fmap (Entity k) $ M.lookup k vs
for :: [a] -> (a -> b) -> [b]
for xs f = map f xs
| pbrisbin/renters-reality | Helpers/Model.hs | bsd-2-clause | 1,745 | 0 | 14 | 616 | 635 | 335 | 300 | -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.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.LO.Corpus
( corpus ) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale LO Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "ສູນ"
]
, examples (NumeralValue 1)
[ "ໜຶ່ງ"
]
, examples (NumeralValue 2)
[ "ສອງ"
]
, examples (NumeralValue 3)
[ "ສາມ"
]
, examples (NumeralValue 4)
[ "ສີ່"
]
, examples (NumeralValue 5)
[ "ຫ້າ"
]
, examples (NumeralValue 6)
[ "ຫົກ"
]
, examples (NumeralValue 7)
[ "ເຈັດ"
]
, examples (NumeralValue 8)
[ "ແປດ"
]
, examples (NumeralValue 9)
[ "ເກົ້າ"
]
, examples (NumeralValue 11)
[ "ສິບເອັດ"
]
, examples (NumeralValue 15)
[ "ສິບຫ້າ"
]
, examples (NumeralValue 17)
[ "ສິບເຈັດ"
]
, examples (NumeralValue 22)
[ "ຊາວສອງ"
]
, examples (NumeralValue 24)
[ "ຊາວສີ່"
]
, examples (NumeralValue 26)
[ "ຊາວຫົກ"
]
, examples (NumeralValue 28)
[ "ຊາວແປດ"
]
, examples (NumeralValue 34)
[ "ສາມສິບສີ່"
]
, examples (NumeralValue 10)
[ "ສິບ"
]
, examples (NumeralValue 20)
[ "ຊາວ"
]
, examples (NumeralValue 50)
[ "ຫ້າສິບ"
]
]
| facebookincubator/duckling | Duckling/Numeral/LO/Corpus.hs | bsd-3-clause | 2,221 | 0 | 9 | 823 | 454 | 251 | 203 | 55 | 1 |
import qualified Data.MemoCombinators as Memo
import Text.Printf (printf)
-- the probability that p2 wins when p1 scores a, and p2 scores b (p1 first).
win :: Int -> Int -> Double
win a b = Memo.memo2 Memo.integral Memo.integral win' a b
where
win' a b | a >= 100 = 0.0
| b >= 100 = 1.0
| otherwise = maximum $ do
t1 <- [1 .. 8]
t2 <- [1 .. 8]
let prob1 = 0.5 ** (fromIntegral t1)
let prob2 = 0.5 ** (fromIntegral t2)
let d1 = 2 ^ (t1 - 1)
let d2 = 2 ^ (t2 - 1)
return $ (prob1 / 2 * (win a (b + d1)) + prob2 / 2 * (win (a + 1) (b + d2)) + (1 - prob2) / 2 * (win (a + 1) b)) / (1 - (1 - prob1) / 2)
main = printf "%.8f\n" $ win 0 0
| foreverbell/project-euler-solutions | src/232.hs | bsd-3-clause | 795 | 0 | 24 | 317 | 352 | 180 | 172 | 15 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
module Web.Auth0.Types where
import Control.Lens.TH
import Control.Monad (mzero)
import Control.Monad.Except (MonadError)
import Control.Monad.Reader (MonadReader)
import Control.Monad.Trans (MonadIO)
import Data.Aeson
import Data.Aeson.Types (Parser)
import Data.ByteString (ByteString)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Time
import Network.HTTP.Nano
import Network.HTTP.Types.URI (urlEncode)
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Lazy as B
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as M
import qualified Data.Text.Encoding as T
type Token = String
type HttpM m r e = (MonadIO m, MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r)
data Auth0 = Auth0 {
_auth0Application :: String,
_auth0Token :: String,
_auth0Secret :: String,
_auth0ClientID :: String
}
data Query where
(:=) :: String -> Term -> Query
(:&) :: Query -> Query -> Query
(:|) :: Query -> Query -> Query
infixl 2 :&
infixl 3 :|
data Term where
TEQ :: IsTerm a => a -> Term
(:<->) :: IsTerm a => a -> a -> Term
newtype Unquoted a = Unquoted a
class IsTerm a where
renderTerm :: a -> B.Builder
instance IsTerm Int where
renderTerm = B.intDec
instance IsTerm Float where
renderTerm = B.floatDec
instance IsTerm Double where
renderTerm = B.doubleDec
instance IsTerm [Char] where
renderTerm x = "\"" <> B.stringUtf8 x <> "\""
instance IsTerm (Unquoted [Char]) where
renderTerm (Unquoted x) = B.stringUtf8 x
buildTerm :: Term -> B.Builder
buildTerm (TEQ x) = renderTerm x
buildTerm (x :<-> y) = "[" <> renderTerm x <> " TO " <> renderTerm y <> "]"
instance ToJSON Query where
toJSON (k := t) = object ["op" .= ("=" :: String), "k" .= k, "t" .= t]
toJSON (a :& b) = object ["op" .= ("&" :: String), "a" .= a, "b" .= b]
toJSON (a :| b) = object ["op" .= ("|" :: String), "a" .= a, "b" .= b]
instance FromJSON Query where
parseJSON = withObject "Query" $ \o -> do
op <- o .: "op" :: Parser String
case op of
"=" -> (:=) <$> o .: "k" <*> o .: "t"
"&" -> (:&) <$> o .: "a" <*> o .: "b"
"|" -> (:|) <$> o .: "a" <*> o .: "b"
_ -> fail "ran into an unknown operator"
instance ToJSON Term where
toJSON (TEQ v) = object
[ "op" .= ("=" :: String)
, "v" .= renderTermAsText v]
toJSON (f :<-> t) = object
[ "op" .= ("<->" :: String)
, "f" .= renderTermAsText f
, "t" .= renderTermAsText t ]
instance FromJSON Term where
parseJSON = withObject "Term" $ \o -> do
op <- o .: "op" :: Parser String
let u :: String -> Unquoted String
u = Unquoted
case op of
"=" -> TEQ . u <$> ((o .: "v") :: Parser String)
"<->" -> (:<->) <$> (u <$> o .: "f") <*> (u <$> o .: "t")
_ -> mzero
infixl 5 `TEQ`
infixl 4 :<->
buildQuery :: Query -> B.Builder
buildQuery (k := t) = B.stringUtf8 k <> ":" <> buildTerm t
buildQuery (q1 :& q2) = "(" <> buildQuery q1 <> ") AND (" <> buildQuery q2 <> ")"
buildQuery (q1 :| q2) = "(" <> buildQuery q1 <> ") OR (" <> buildQuery q2 <> ")"
renderTermAsText :: IsTerm a => a -> Text
renderTermAsText = T.decodeUtf8 . B.toStrict . B.toLazyByteString . renderTerm
-- | Render and URL encode a 'Query'. This function supports Unicode in
-- 'Term's.
renderQueryUrlEncoded :: Query -> ByteString
renderQueryUrlEncoded =
urlEncode False . B.toStrict . B.toLazyByteString . buildQuery
type Profile = Profile' (M.Map String Value) (M.Map String Value)
data Profile' a b = Profile' {
_profileID :: String,
_profileBlocked :: Maybe Bool,
_profileCreated :: Maybe UTCTime,
_profileUpdated :: Maybe UTCTime,
_profileLastLogin :: Maybe UTCTime,
_profileIdentities :: [Identity],
_profileUserMeta :: Maybe a,
_profileAppMeta :: Maybe b,
_profileData :: ProfileData
} deriving Show
data ProfileData = ProfileData {
_profileEmail :: Maybe String,
_profileEmailVerified :: Maybe Bool,
_profilePhoneNumber :: Maybe String,
_profilePhoneNumberVerified :: Maybe Bool,
_profileUsername :: Maybe String,
_profileName :: Maybe String,
_profileNickname :: Maybe String,
_profilePicture :: Maybe String
} deriving Show
data Identity = Identity {
_identityConnection :: Maybe String,
_identityIsSocial :: Maybe Bool,
_identityProvider :: String,
_identityUserID :: String,
_identityProfileData :: Maybe ProfileData
} deriving Show
instance (FromJSON a, FromJSON b) => FromJSON (Profile' a b) where
parseJSON (Object v) =
Profile' <$> v .: "user_id"
<*> v .:? "blocked"
<*> from8601 "created_at"
<*> from8601 "updated_at"
<*> from8601 "last_login"
<*> v .: "identities"
<*> v .:? "user_metadata"
<*> v .:? "app_metadata"
<*> parseProfileData v
where
fmt = iso8601DateFormat (Just "%H:%M:%S%QZ")
from8601 k = do
ms <- v .:? k
return $ do
s <- ms
parseTimeM True defaultTimeLocale fmt s
parseJSON _ = mzero
instance FromJSON ProfileData where
parseJSON (Object v) = parseProfileData v
parseJSON _ = mzero
parseProfileData :: HM.HashMap Text Value -> Parser ProfileData
parseProfileData v =
ProfileData <$> v .:? "email"
<*> v .:? "email_verified"
<*> v .:? "phone_number"
<*> v .:? "phone_verified"
<*> v .:? "username"
<*> v .:? "name"
<*> v .:? "nickname"
<*> v .:? "picture"
instance FromJSON Identity where
parseJSON = withObject "user Identity" $ \o -> do
_identityConnection <- o .:? "connection"
_identityIsSocial <- o .:? "isSocial"
_identityProvider <- o .: "provider"
_identityUserID <- o .: "user_id"
_identityProfileData <- o .:? "profileData"
return Identity {..}
data AuthToken = AuthToken {
_authTokenIDToken :: String,
_authTokenAccessToken :: String
} deriving Show
instance FromJSON AuthToken where
parseJSON (Object v) = AuthToken <$> v .: "id_token" <*> v .: "access_token"
parseJSON _ = mzero
data NewEmailUser = NewEmailUser {
_newEmailUserConnection :: String,
_newEmailUserEmail :: String,
_newEmailUserPassword :: String,
_newEmailUserName :: String,
_newEmailUserNickname :: String
} deriving Show
instance ToJSON NewEmailUser where
toJSON u =
object [
"connection" .= _newEmailUserConnection u,
"email" .= _newEmailUserEmail u,
"password" .= _newEmailUserPassword u,
"name" .= _newEmailUserName u,
"nickname" .= _newEmailUserNickname u,
"email_verified" .= True
]
instance FromJSON NewEmailUser where
parseJSON (Object v) =
NewEmailUser <$> v .: "connection"
<*> v .: "email"
<*> v .: "password"
<*> v .: "name"
<*> v .: "nickname"
parseJSON _ = mzero
data NewPhoneUser = NewPhoneUser {
_newPhoneUserPhone :: String
} deriving Show
instance ToJSON NewPhoneUser where
toJSON u =
object [
"connection" .= ("sms" :: String),
"phone_number" .= _newPhoneUserPhone u,
"phone_verified" .= True
]
instance FromJSON NewPhoneUser where
parseJSON (Object v) = NewPhoneUser <$> v .: "phone"
parseJSON _ = mzero
data TokenInfo a = TokenInfo {
_tokenInfoISS :: String,
_tokenInfoSUB :: String,
_tokenInfoAUD :: String,
_tokenInfoEXP :: Int,
_tokenInfoIAT :: Int,
_tokenInfoAppMetadata :: Maybe a
} deriving Show
instance FromJSON a => FromJSON (TokenInfo a) where
parseJSON (Object v) =
TokenInfo <$> v .: "iss"
<*> v .: "sub"
<*> v .: "aud"
<*> v .: "exp"
<*> v .: "iat"
<*> v .:? "app_metadata"
parseJSON _ = mzero
instance ToJSON a => ToJSON (TokenInfo a) where
toJSON i =
object [
"app_metadata" .= _tokenInfoAppMetadata i,
"iss" .= _tokenInfoISS i,
"sub" .= _tokenInfoSUB i,
"aud" .= _tokenInfoAUD i,
"exp" .= _tokenInfoEXP i,
"iat" .= _tokenInfoIAT i
]
-- | Record representing daily statistics as returned by Auth0 service.
data DailyStats = DailyStats
{ _dailyStatsDate :: Day -- ^ Date
, _dailyStatsLogins :: Int -- ^ Number of logins
} deriving (Show, Eq)
instance FromJSON DailyStats where
parseJSON = withObject "DailyStats" $ \o -> do
_dailyStatsDate <- utctDay <$> (o .: "date")
_dailyStatsLogins <- o .: "logins"
return DailyStats {..}
makeClassy ''Auth0
makeLenses ''Profile'
makeLenses ''ProfileData
makeLenses ''Identity
makeLenses ''AuthToken
makeLenses ''NewEmailUser
makeLenses ''NewPhoneUser
makeLenses ''DailyStats
makeLenses ''TokenInfo
| collegevine/auth0 | src/Web/Auth0/Types.hs | bsd-3-clause | 9,462 | 0 | 20 | 2,712 | 2,703 | 1,446 | 1,257 | 252 | 1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
[lq| type OList a = [a]<{\fld v -> (v >= fld)}> |]
[lq| assert sort3 :: (Ord a) => [a] -> OList a |]
sort3 :: (Ord a) => [a] -> [a]
sort3 = qsort
qsort:: (Ord a) => [a] -> [a]
[lq| qsort:: (Ord a) => xs:[a] -> OList a / [(len xs), 0]|]
qsort [] = []
qsort (x:xs) = qpart x xs [] []
qpart :: (Ord a) => a -> [a] -> [a] -> [a] -> [a]
[lq| qpart :: (Ord a) => x:a -> q:[a] -> r:[{v:a | (v < x)}] -> p:[{v:a |(v >= x)}] -> OList a / [((len p) + (len r) + (len q)), ((len q) + 1)]|]
qpart x [] rlt rge =
app x (qsort rlt) (x:qsort rge)
qpart x (y:ys) rlt rge =
case compare x y of
GT -> qpart x ys (y:rlt) rge
_ -> qpart x ys rlt (y:rge)
[lq| app :: Ord a => x:a -> (OList ({v:a | v < x})) -> (OList ({v:a| v >= x})) -> OList a |]
app :: Ord a => a -> [a] -> [a] -> [a]
app k [] ys = ys
app k (x:xs) ys = x : (app k xs ys)
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/RecQSort.hs | bsd-3-clause | 919 | 0 | 10 | 264 | 368 | 201 | 167 | 22 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Module : $Header$
Copyright : (c) 2016 Deakin Software & Technology Innovation Lab
License : BSD3
Maintainer : Rhys Adams <[email protected]>
Stability : unstable
Portability : portable
Job(s) state views and transformation. Actions are actually scheduled in 'TS'.
-}
module Eclogues.State (
-- * Types
AtomicFailure (..)
-- * View
, getEntities, getEntity
, jobsProgressingOnScheduler
, getContainers, containerUUID, fileUUID
-- * Mutate
, createJob, updateJobs, killJob, patchDepends, deleteJob
, createBox, sealBox, deleteBox
, createContainer, deleteContainer
, addFile
, atomicActs
) where
import Eclogues.Prelude
import Eclogues.API
( Action (..), DependencyPatch (..), JobError (..), StageExpectation (..) )
import Eclogues.Job
( Availability (..), FailureReason (..), RunErrorReason (..), QueueStage (..), Stage (..)
, isActiveStage, isTerminationStage, isQueueStage, seenOnScheduler, sentToScheduler )
import qualified Eclogues.Job as Job
import Eclogues.Monitoring.Cluster (Cluster, stagelessSatisfy)
import Eclogues.Scheduling.Command (ScheduleCommand (..))
import qualified Eclogues.State.Monad as ES
import Eclogues.State.Monad (TS)
import Eclogues.State.Types
( AppState, _ABox, _AJob, _Unsealed, containers, jobs, nodes )
import Control.Monad (filterM)
import Control.Lens (over, both)
import Data.HashMap.Strict (delete, keys, toList)
import Data.List (partition)
import Data.List.NonEmpty (nonEmpty)
import Data.Maybe (catMaybes)
import Data.Set ((\\), fromList, union)
-- TODO: Determine satisfiability before scheduling job
-- | Try to schedule a new job. UUID must be unique; best to randomly generate
-- it.
createJob :: forall m. (TS m, MonadError JobError m) => UUID -> Maybe Cluster -> Job.Spec -> m ()
createJob uuid cluster spec = do
flip unless (throwError $ ContainerMustExist con) . has _Just =<< ES.containerUUID con
ensureNameUnused name
activeDeps <- namesToWaitFor deps
satis <- stagelessSatisfy cluster spec
let jstage = shouldBeWaiting activeDeps
ES.insertJob $ Job.mkStatus spec jstage satis uuid mempty
mapM_ (ES.addRevDep name) deps
queueJob <- mkQueueJob spec uuid
when (jstage == Queued LocalQueue) . ES.schedule $ queueJob
where
deps = spec ^. Job.dependsOn . Job.dependenciesList
name = spec ^. Job.name
con = spec ^. Job.container
createBox :: (TS m, MonadError JobError m) => Job.BoxSpec -> m ()
createBox spec = do
ensureNameUnused name
ES.insertBox $ Job.mkBoxStatus name Job.Unsealed mempty
where
name = spec ^. Job.name
createContainer :: (TS m, MonadError JobError m) => Job.ContainerId -> UUID -> m ()
createContainer name uuid = do
flip when (throwError NameUsed) . has _Just =<< ES.containerUUID name
ES.insertContainer name uuid
addFile :: (TS m, MonadError JobError m) => Job.Name -> Job.FileId -> UUID -> m ()
addFile jn fn uuid = do
js <- existing id jn
mapM_ (const . throwError $ FileAlreadyExists jn fn) =<< ES.fileUUID jn fn
when (Job.anyAvailability js /= MayBecomeAvailable) . throwError $ UploadClosed jn
ES.insertFile jn fn uuid
existing :: (TS m, MonadError JobError m) => Traversal' Job.AnyStatus a -> Job.Name -> m a
existing p name = maybe (throwError NoSuch) pure =<< ES.getEntity p name
-- | Kill a job. Fails if job is already terminated.
killJob :: (TS m, MonadError JobError m) => Job.Name -> m ()
killJob name = existing _AJob name >>= \js -> case js ^. Job.stage of
Killing -> pure ()
s | isTerminationStage s -> pure ()
| otherwise -> do
ES.setJobStage name Killing
ES.schedule $ KillJob (js ^. Job.spec) (js ^. Job.uuid)
patchDepends :: (TS m, MonadError JobError m) => Job.Name -> DependencyPatch -> m ()
patchDepends name (DependencyPatch adding rming) = do
js <- existing _AJob name
alreadyWaiting <- maybe (throwError $ JobMustBe name ExpectWaiting) (pure . Job.toSet) $ js ^? Job.stage . Job._Waiting
let deps = js ^. Job.dependsOn . Job.dependenciesMap
deps' = foldl' (flip delete) (addMap <> deps) rming
js' = js & Job.dependsOn .~ Job.Dependencies deps'
newlyWaiting <- namesToWaitFor addDeps
setAndPerhapsQueue js' . shouldBeWaiting $ (newlyWaiting `union` alreadyWaiting) \\ fromList rming
when (deps' /= deps) . ES.setJobDependsOn name $ Job.Dependencies deps'
mapM_ (ES.addRevDep name) addDeps
mapM_ (ES.removeRevDep name) rming
where
addDeps = adding ^. Job.dependenciesList
addMap = adding ^. Job.dependenciesMap
namesToWaitFor :: (TS m, MonadError JobError m) => [Job.Dependency] -> m (Set Job.Name)
namesToWaitFor = fmap (fromList . fmap (^. Job.depName)) . filterM shouldWaitFor
-- | Determine if an entity's availability is 'Job.MayBecomeAvailable'. Fails if
-- the entity is 'Job.NeverAvailable' and the dependency is non-optional.
shouldWaitFor :: (TS m, MonadError JobError m) => Job.Dependency -> m Bool
shouldWaitFor (Job.Dependency name opt) =
maybe (throwError $ JobMustBe name ExpectExtant) (chk . Job.anyAvailability) =<< ES.getEntity id name
where
chk Available = pure False
chk MayBecomeAvailable = pure True
-- Boxes can't become NeverAvailable, so it's fine to use a job-specific error
chk NeverAvailable
| opt = pure False
| otherwise = throwError $ JobMustBe name ExpectNonFailed
shouldBeWaiting :: Set Job.Name -> Job.Stage
shouldBeWaiting = maybe (Queued LocalQueue) Waiting . Job.nonEmptySet
-- | Delete a job and all its output.
deleteJob :: (TS m, MonadError JobError m) => Job.Name -> m ()
deleteJob name = existing _AJob name >>= \js -> do
ensureNoActiveDependents name
removeRevDepsFromDeps js
ES.deleteJob name
ES.schedule . CleanupJob name $ js ^. Job.uuid
scheduleCleanupFiles js
-- | Seal a box to prevent further uploads. Does nothing if the box is already sealed.
sealBox :: (TS m, MonadError JobError m) => Job.Name -> m ()
sealBox name = existing _ABox name >>= \bs -> when (has (Job.sealed . _Unsealed) bs) $ do
ES.sealBox name
withDependents (const $ triggerDep name) name
deleteBox :: (TS m, MonadError JobError m) => Job.Name -> m ()
deleteBox name = existing _ABox name >>= \bs -> do
ensureNoActiveDependents name
ES.deleteBox name
scheduleCleanupFiles bs
scheduleCleanupFiles :: (TS m, Job.HasFiles a) => a -> m ()
scheduleCleanupFiles a = do
let fs = a ^.. Job.files . each
unless (null fs) . ES.schedule $ CleanupFiles fs
ensureNoActiveDependents :: (TS m, MonadError JobError m) => Job.Name -> m ()
ensureNoActiveDependents = mapM_ (throwError . OutstandingDependants) . nonEmpty . keys <=< ES.getDependents
deleteContainer :: (TS m, MonadError JobError m) => Job.ContainerId -> m UUID
deleteContainer name = do
uuid <- maybe (throwError NoSuch) pure =<< ES.containerUUID name
mapM_ (throwError . OutstandingDependants) . nonEmpty . fmap (^. Job.name) . filter isActive =<< ES.jobsUsingContainer name
ES.deleteContainer name
pure uuid
where
isActive = Job.isActiveStage . (^. Job.stage)
data AtomicFailure = AtomicFailure Action JobError
deriving (Show, Eq)
-- | Atomically apply multiple actions.
atomicActs :: AppState -> Maybe Cluster -> [(UUID, Action)] -> Either AtomicFailure ES.TransitionaryState
atomicActs st0 cl as = invert . ES.runState st0 . runExceptT $ mapM_ (uncurry enact') as
where
invert (res, st') = either Left (const $ Right st') res
enact' u a = withExceptT (AtomicFailure a) $ enact u a
enact u (ActCreateJob spec) = createJob u cl spec
enact _ (ActKillJob name) = killJob name
enact _ (ActPatchJob n pat) = patchDepends n pat
enact _ (ActDeleteJob name) = deleteJob name
enact _ (ActCreateBox spec) = createBox spec
enact _ (ActSealBox name) = sealBox name
enact _ (ActDeleteBox name) = deleteBox name
-- Only check on active jobs; terminated jobs shouldn't change status
-- | All jobs that should be queried on the scheduler.
jobsProgressingOnScheduler :: AppState -> [Job.Status]
jobsProgressingOnScheduler = (^.. jobs . filtered (p . (^. Job.stage)))
where
p = (&&) <$> sentToScheduler <*> isActiveStage
-- | Update the status of a set of jobs with new data from the scheduler,
-- scheduling any new actions required (eg. dependencies).
updateJobs :: forall m. (TS m) => [Job.Status] -> [(Job.Name, Job.Stage)] -> m ()
updateJobs activeStatuses gotStages = mapM_ transition activeStatuses where
transition :: Job.Status -> m ()
transition pst = when (newStage /= oldStage) $ case newStage of
Finished -> setTerminalAndWithDeps (const $ triggerDep name) pst newStage
st | isTerminationStage st -> setTerminalAndWithDeps (cascadeDepFailure name) pst newStage
| otherwise -> ES.setJobStage name newStage
where
name = pst ^. Job.name
oldStage = pst ^. Job.stage
newStage = checkTransition oldStage $ lookup name gotStages
checkTransition :: Job.Stage -> Maybe Job.Stage -> Job.Stage
checkTransition Killing Nothing = Failed UserKilled
checkTransition Killing (Just new)
| Finished <- new = Failed UserKilled
| isTerminationStage new = new
| otherwise = Killing
checkTransition old Nothing
| seenOnScheduler old = RunError SchedulerLost
| otherwise = old
checkTransition old (Just new)
| old == new = old
| isExpectedTransition old new = new
| otherwise = RunError BadSchedulerTransition
cascadeDepFailure :: Job.Name -> Job.Dependency -> Job.Status -> m ()
cascadeDepFailure depName (Job.Dependency _ opt) cst
| opt = triggerDep depName cst
| otherwise = setTerminalAndWithDeps (cascadeDepFailure $ cst ^. Job.name) cst (Failed $ DependencyFailed depName)
setTerminalAndWithDeps :: (Job.Dependency -> Job.Status -> m ()) -> Job.Status -> Job.Stage -> m ()
setTerminalAndWithDeps f s st = do
ES.setJobStage name st
-- Remove this job as a dependency on others
removeRevDepsFromDeps s
withDependents f name
where name = s ^. Job.name
removeRevDepsFromDeps :: (TS m, Job.HasSpec a) => a -> m ()
removeRevDepsFromDeps s = mapM_ (ES.removeRevDep $ s ^. Job.name) $ s ^. Job.dependsOn . Job.dependenciesMap . to keys
-- | Just ignores those that somehow don't exist. The 'Job.Dependency' is a
-- reverse dependency; the name is the name of the dependant.
withDependents :: (TS m) => (Job.Dependency -> Job.Status -> m ()) -> Job.Name -> m ()
withDependents f = mapM_ go . toList <=< ES.getDependents
where go (n, o) = mapM_ (f (Job.Dependency n o)) =<< ES.getJob n
-- | "Inform" a job that one of its dependencies has become 'Job.Available'.
triggerDep :: (TS m)
=> Job.Name -- ^ The dependency
-> Job.Status -- ^ The dependant
-> m ()
triggerDep dep s
| Job.Waiting remaining <- s ^. Job.stage =
setAndPerhapsQueue s . maybe (Queued LocalQueue) Waiting $ Job.delete dep remaining
| otherwise = pure ()
-- 'ES.setJobStage' and potentially queue iff the new stage is different from
-- the current.
setAndPerhapsQueue :: (TS m)
=> Job.Status -- ^ Original status
-> Job.Stage -- ^ New status
-> m ()
setAndPerhapsQueue s st' = when (s ^. Job.stage /= st') $ do
ES.setJobStage (s ^. Job.name) st'
when (st' == Queued LocalQueue) . ES.schedule =<< mkQueueJob (s ^. Job.spec) (s ^. Job.uuid)
mkQueueJob :: forall m. (TS m) => Job.Spec -> UUID -> m ScheduleCommand
mkQueueJob s uuid = do
(depsSucceeded, depsFailed) <- depsBySuccess
pure $ QueueJob s uuid depsFailed depsSucceeded
where
depsBySuccess :: m ([Job.Name], [Job.Name])
depsBySuccess = pure . over both (fmap fst) <$> partition (available . snd) =<< depStatuses
where available = (== Job.Available) . Job.anyAvailability
depStatuses :: m [(Job.Name, Job.AnyStatus)]
depStatuses = catMaybes <$> traverse depStatus depNames
depStatus :: Job.Name -> m (Maybe (Job.Name, Job.AnyStatus))
depStatus n = (fmap . fmap) ((,) n) (ES.getEntity id n)
depNames :: [Job.Name]
depNames = s ^. Job.dependsOn . Job.dependenciesList ^.. each . Job.name
ensureNameUnused :: (TS m, MonadError JobError m) => Job.Name -> m ()
ensureNameUnused n = mapM_ (const $ throwError NameUsed) =<< ES.getEntity id n
getEntities :: Traversal' Job.AnyStatus a -> AppState -> [a]
getEntities p = (^.. nodes . each . p)
getEntity :: (MonadError JobError m) => Traversal' Job.AnyStatus a -> Job.Name -> AppState -> m a
getEntity p n = retrieve $ nodes . ix n . p
getContainers :: AppState -> [Job.ContainerId]
getContainers = keys . (^. containers)
containerUUID :: (MonadError JobError m) => Job.ContainerId -> AppState -> m UUID
containerUUID n = retrieve $ containers . ix n
fileUUID :: (MonadError JobError m) => Job.Name -> Job.FileId -> AppState -> m UUID
fileUUID jn fn = retrieve $ nodes . ix jn . Job.files . ix fn
retrieve :: (MonadError JobError m) => Traversal' b v -> b -> m v
retrieve t = maybe (throwError NoSuch) pure . (^? t)
-- | Whether the first 'Stage' may transition to the second in the lifecycle.
-- Unexpected transitions are treated as scheduler errors
-- ('BadSchedulerTransition').
isExpectedTransition :: Stage -> Stage -> Bool
isExpectedTransition (Queued SentToScheduler) (Queued SchedulerQueue) = True
isExpectedTransition (Queued _) Running = True
isExpectedTransition (Waiting s) Running
| null s = True
isExpectedTransition Running (Queued SchedulerQueue) = True
isExpectedTransition Killing (Failed UserKilled) = True
isExpectedTransition o n | isQueueStage o || o == Running = case n of
Finished -> True
(Failed _) -> True
(RunError _) -> True
_ -> False
isExpectedTransition _ _ = False
| rimmington/eclogues | eclogues-impl/app/api/Eclogues/State.hs | bsd-3-clause | 14,520 | 0 | 17 | 3,335 | 4,520 | 2,288 | 2,232 | -1 | -1 |
module PulseAudio where
import qualified Control.Concurrent as C
import Control.Monad
import qualified Data.ByteString as BS
import Data.Time
import Pipes
import qualified Pipes.Prelude as P
import Sound.Pulse.Simple
import WavePacket
newtype PAByteString = PAByteString BS.ByteString
newtype PAWavePacket = PAWavePacket WavePacket
paRead :: Simple -> Producer PAByteString IO ()
paRead = go
where go s = do
bs <- liftIO $ simpleReadRaw s 4410
yield $ PAByteString bs
go s
paPlay :: Simple -> Consumer PAWavePacket IO ()
paPlay s = for cat (\(PAWavePacket (WavePacket t bs)) -> do
curr <- liftIO getCurrentTime
liftIO $ print $ "Waiting " ++ (show $ timeDiff t curr)
liftIO $ C.threadDelay $ timeDiff t curr
liftIO $ simpleWriteRaw s bs
)
timeDiff :: UTCTime -> UTCTime -> Int
timeDiff t1 t2 = floor (toRational (diffUTCTime t1 t2) * 1000000)
| z0isch/Speakerete | src/PulseAudio.hs | bsd-3-clause | 1,101 | 0 | 13 | 391 | 297 | 155 | 142 | 25 | 1 |
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit
import qualified NormalizationTests as Norm
import qualified SegmentationTests as Segm
main = defaultMain tests
tests :: TestTree
tests = testGroup "tests" [
testGroup "norm" [
testCase "g1" (Norm.g1_check @?= True)
],
testGroup "segm" [
testGroup "graph" [
-- FIXME testProperty "g1" Segm.g1_prop,
testCase "g2" (Segm.g2_check @?= True)
],
testGroup "word" [
testCase "w1" (Segm.w1_check @?= True)
]
]
]
| llelf/prose | tests/Tests.hs | bsd-3-clause | 654 | 0 | 14 | 243 | 137 | 77 | 60 | 15 | 1 |
{-# LANGUAGE CPP #-}
----------------------------------------------------------------------------
--
-- Stg to C--: primitive operations
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmPrim (
cgOpApp,
cgPrimOp, -- internal(ish), used by cgCase to get code for a
-- comparison without also turning it into a Bool.
shouldInlinePrimOp
) where
#include "HsVersions.h"
import StgCmmLayout
import StgCmmForeign
import StgCmmEnv
import StgCmmMonad
import StgCmmUtils
import StgCmmTicky
import StgCmmHeap
import StgCmmProf ( costCentreFrom, curCCS )
import DynFlags
import Platform
import BasicTypes
import MkGraph
import StgSyn
import Cmm
import CmmInfo
import Type ( Type, tyConAppTyCon )
import TyCon
import CLabel
import CmmUtils
import PrimOp
import SMRep
import FastString
import Outputable
import Util
#if __GLASGOW_HASKELL__ >= 709
import Prelude hiding ((<*>))
#endif
import Data.Bits ((.&.), bit)
import Control.Monad (liftM, when)
------------------------------------------------------------------------
-- Primitive operations and foreign calls
------------------------------------------------------------------------
{- Note [Foreign call results]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
A foreign call always returns an unboxed tuple of results, one
of which is the state token. This seems to happen even for pure
calls.
Even if we returned a single result for pure calls, it'd still be
right to wrap it in a singleton unboxed tuple, because the result
might be a Haskell closure pointer, we don't want to evaluate it. -}
----------------------------------
cgOpApp :: StgOp -- The op
-> [StgArg] -- Arguments
-> Type -- Result type (always an unboxed tuple)
-> FCode ReturnKind
-- Foreign calls
cgOpApp (StgFCallOp fcall _) stg_args res_ty
= cgForeignCall fcall stg_args res_ty
-- Note [Foreign call results]
-- tagToEnum# is special: we need to pull the constructor
-- out of the table, and perform an appropriate return.
cgOpApp (StgPrimOp TagToEnumOp) [arg] res_ty
= ASSERT(isEnumerationTyCon tycon)
do { dflags <- getDynFlags
; args' <- getNonVoidArgAmodes [arg]
; let amode = case args' of [amode] -> amode
_ -> panic "TagToEnumOp had void arg"
; emitReturn [tagToClosure dflags tycon amode] }
where
-- If you're reading this code in the attempt to figure
-- out why the compiler panic'ed here, it is probably because
-- you used tagToEnum# in a non-monomorphic setting, e.g.,
-- intToTg :: Enum a => Int -> a ; intToTg (I# x#) = tagToEnum# x#
-- That won't work.
tycon = tyConAppTyCon res_ty
cgOpApp (StgPrimOp primop) args res_ty = do
dflags <- getDynFlags
cmm_args <- getNonVoidArgAmodes args
case shouldInlinePrimOp dflags primop cmm_args of
Nothing -> do -- out-of-line
let fun = CmmLit (CmmLabel (mkRtsPrimOpLabel primop))
emitCall (NativeNodeCall, NativeReturn) fun cmm_args
Just f -- inline
| ReturnsPrim VoidRep <- result_info
-> do f []
emitReturn []
| ReturnsPrim rep <- result_info
-> do dflags <- getDynFlags
res <- newTemp (primRepCmmType dflags rep)
f [res]
emitReturn [CmmReg (CmmLocal res)]
| ReturnsAlg tycon <- result_info, isUnboxedTupleTyCon tycon
-> do (regs, _hints) <- newUnboxedTupleRegs res_ty
f regs
emitReturn (map (CmmReg . CmmLocal) regs)
| otherwise -> panic "cgPrimop"
where
result_info = getPrimOpResultInfo primop
cgOpApp (StgPrimCallOp primcall) args _res_ty
= do { cmm_args <- getNonVoidArgAmodes args
; let fun = CmmLit (CmmLabel (mkPrimCallLabel primcall))
; emitCall (NativeNodeCall, NativeReturn) fun cmm_args }
-- | Interpret the argument as an unsigned value, assuming the value
-- is given in two-complement form in the given width.
--
-- Example: @asUnsigned W64 (-1)@ is 18446744073709551615.
--
-- This function is used to work around the fact that many array
-- primops take Int# arguments, but we interpret them as unsigned
-- quantities in the code gen. This means that we have to be careful
-- every time we work on e.g. a CmmInt literal that corresponds to the
-- array size, as it might contain a negative Integer value if the
-- user passed a value larger than 2^(wORD_SIZE_IN_BITS-1) as the Int#
-- literal.
asUnsigned :: Width -> Integer -> Integer
asUnsigned w n = n .&. (bit (widthInBits w) - 1)
-- TODO: Several primop implementations (e.g. 'doNewByteArrayOp') use
-- ByteOff (or some other fixed width signed type) to represent
-- array sizes or indices. This means that these will overflow for
-- large enough sizes.
-- | Decide whether an out-of-line primop should be replaced by an
-- inline implementation. This might happen e.g. if there's enough
-- static information, such as statically know arguments, to emit a
-- more efficient implementation inline.
--
-- Returns 'Nothing' if this primop should use its out-of-line
-- implementation (defined elsewhere) and 'Just' together with a code
-- generating function that takes the output regs as arguments
-- otherwise.
shouldInlinePrimOp :: DynFlags
-> PrimOp -- ^ The primop
-> [CmmExpr] -- ^ The primop arguments
-> Maybe ([LocalReg] -> FCode ())
shouldInlinePrimOp dflags NewByteArrayOp_Char [(CmmLit (CmmInt n w))]
| asUnsigned w n <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> doNewByteArrayOp res (fromInteger n)
shouldInlinePrimOp dflags NewArrayOp [(CmmLit (CmmInt n w)), init]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] ->
doNewArrayOp res (arrPtrsRep dflags (fromInteger n)) mkMAP_DIRTY_infoLabel
[ (mkIntExpr dflags (fromInteger n),
fixedHdrSize dflags + oFFSET_StgMutArrPtrs_ptrs dflags)
, (mkIntExpr dflags (nonHdrSizeW (arrPtrsRep dflags (fromInteger n))),
fixedHdrSize dflags + oFFSET_StgMutArrPtrs_size dflags)
]
(fromInteger n) init
shouldInlinePrimOp _ CopyArrayOp
[src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] =
Just $ \ [] -> doCopyArrayOp src src_off dst dst_off (fromInteger n)
shouldInlinePrimOp _ CopyMutableArrayOp
[src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] =
Just $ \ [] -> doCopyMutableArrayOp src src_off dst dst_off (fromInteger n)
shouldInlinePrimOp _ CopyArrayArrayOp
[src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] =
Just $ \ [] -> doCopyArrayOp src src_off dst dst_off (fromInteger n)
shouldInlinePrimOp _ CopyMutableArrayArrayOp
[src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] =
Just $ \ [] -> doCopyMutableArrayOp src src_off dst dst_off (fromInteger n)
shouldInlinePrimOp dflags CloneArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneArray mkMAP_FROZEN_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags CloneMutableArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneArray mkMAP_DIRTY_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags FreezeArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneArray mkMAP_FROZEN_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags ThawArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneArray mkMAP_DIRTY_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags NewSmallArrayOp [(CmmLit (CmmInt n w)), init]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] ->
doNewArrayOp res (smallArrPtrsRep (fromInteger n)) mkSMAP_DIRTY_infoLabel
[ (mkIntExpr dflags (fromInteger n),
fixedHdrSize dflags + oFFSET_StgSmallMutArrPtrs_ptrs dflags)
]
(fromInteger n) init
shouldInlinePrimOp _ CopySmallArrayOp
[src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] =
Just $ \ [] -> doCopySmallArrayOp src src_off dst dst_off (fromInteger n)
shouldInlinePrimOp _ CopySmallMutableArrayOp
[src, src_off, dst, dst_off, (CmmLit (CmmInt n _))] =
Just $ \ [] -> doCopySmallMutableArrayOp src src_off dst dst_off (fromInteger n)
shouldInlinePrimOp dflags CloneSmallArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneSmallArray mkSMAP_FROZEN_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags CloneSmallMutableArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneSmallArray mkSMAP_DIRTY_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags FreezeSmallArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneSmallArray mkSMAP_FROZEN_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags ThawSmallArrayOp [src, src_off, (CmmLit (CmmInt n w))]
| wordsToBytes dflags (asUnsigned w n) <= fromIntegral (maxInlineAllocSize dflags) =
Just $ \ [res] -> emitCloneSmallArray mkSMAP_DIRTY_infoLabel res src src_off (fromInteger n)
shouldInlinePrimOp dflags primop args
| primOpOutOfLine primop = Nothing
| otherwise = Just $ \ regs -> emitPrimOp dflags regs primop args
-- TODO: Several primops, such as 'copyArray#', only have an inline
-- implementation (below) but could possibly have both an inline
-- implementation and an out-of-line implementation, just like
-- 'newArray#'. This would lower the amount of code generated,
-- hopefully without a performance impact (needs to be measured).
---------------------------------------------------
cgPrimOp :: [LocalReg] -- where to put the results
-> PrimOp -- the op
-> [StgArg] -- arguments
-> FCode ()
cgPrimOp results op args
= do dflags <- getDynFlags
arg_exprs <- getNonVoidArgAmodes args
emitPrimOp dflags results op arg_exprs
------------------------------------------------------------------------
-- Emitting code for a primop
------------------------------------------------------------------------
emitPrimOp :: DynFlags
-> [LocalReg] -- where to put the results
-> PrimOp -- the op
-> [CmmExpr] -- arguments
-> FCode ()
-- First we handle various awkward cases specially. The remaining
-- easy cases are then handled by translateOp, defined below.
emitPrimOp _ [res] ParOp [arg]
=
-- for now, just implement this in a C function
-- later, we might want to inline it.
emitCCall
[(res,NoHint)]
(CmmLit (CmmLabel (mkForeignLabel (fsLit "newSpark") Nothing ForeignLabelInExternalPackage IsFunction)))
[(CmmReg (CmmGlobal BaseReg), AddrHint), (arg,AddrHint)]
emitPrimOp dflags [res] SparkOp [arg]
= do
-- returns the value of arg in res. We're going to therefore
-- refer to arg twice (once to pass to newSpark(), and once to
-- assign to res), so put it in a temporary.
tmp <- assignTemp arg
tmp2 <- newTemp (bWord dflags)
emitCCall
[(tmp2,NoHint)]
(CmmLit (CmmLabel (mkForeignLabel (fsLit "newSpark") Nothing ForeignLabelInExternalPackage IsFunction)))
[(CmmReg (CmmGlobal BaseReg), AddrHint), ((CmmReg (CmmLocal tmp)), AddrHint)]
emitAssign (CmmLocal res) (CmmReg (CmmLocal tmp))
emitPrimOp dflags [res] GetCCSOfOp [arg]
= emitAssign (CmmLocal res) val
where
val
| gopt Opt_SccProfilingOn dflags = costCentreFrom dflags (cmmUntag dflags arg)
| otherwise = CmmLit (zeroCLit dflags)
emitPrimOp _ [res] GetCurrentCCSOp [_dummy_arg]
= emitAssign (CmmLocal res) curCCS
emitPrimOp dflags [res] ReadMutVarOp [mutv]
= emitAssign (CmmLocal res) (cmmLoadIndexW dflags mutv (fixedHdrSizeW dflags) (gcWord dflags))
emitPrimOp dflags res@[] WriteMutVarOp [mutv,var]
= do -- Without this write barrier, other CPUs may see this pointer before
-- the writes for the closure it points to have occurred.
emitPrimCall res MO_WriteBarrier []
emitStore (cmmOffsetW dflags mutv (fixedHdrSizeW dflags)) var
emitCCall
[{-no results-}]
(CmmLit (CmmLabel mkDirty_MUT_VAR_Label))
[(CmmReg (CmmGlobal BaseReg), AddrHint), (mutv,AddrHint)]
-- #define sizzeofByteArrayzh(r,a) \
-- r = ((StgArrBytes *)(a))->bytes
emitPrimOp dflags [res] SizeofByteArrayOp [arg]
= emit $ mkAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags) (bWord dflags))
-- #define sizzeofMutableByteArrayzh(r,a) \
-- r = ((StgArrBytes *)(a))->bytes
emitPrimOp dflags [res] SizeofMutableByteArrayOp [arg]
= emitPrimOp dflags [res] SizeofByteArrayOp [arg]
-- #define getSizzeofMutableByteArrayzh(r,a) \
-- r = ((StgArrBytes *)(a))->bytes
emitPrimOp dflags [res] GetSizeofMutableByteArrayOp [arg]
= emitAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags) (bWord dflags))
-- #define touchzh(o) /* nothing */
emitPrimOp _ res@[] TouchOp args@[_arg]
= do emitPrimCall res MO_Touch args
-- #define byteArrayContentszh(r,a) r = BYTE_ARR_CTS(a)
emitPrimOp dflags [res] ByteArrayContents_Char [arg]
= emitAssign (CmmLocal res) (cmmOffsetB dflags arg (arrWordsHdrSize dflags))
-- #define stableNameToIntzh(r,s) (r = ((StgStableName *)s)->sn)
emitPrimOp dflags [res] StableNameToIntOp [arg]
= emitAssign (CmmLocal res) (cmmLoadIndexW dflags arg (fixedHdrSizeW dflags) (bWord dflags))
-- #define eqStableNamezh(r,sn1,sn2) \
-- (r = (((StgStableName *)sn1)->sn == ((StgStableName *)sn2)->sn))
emitPrimOp dflags [res] EqStableNameOp [arg1,arg2]
= emitAssign (CmmLocal res) (CmmMachOp (mo_wordEq dflags) [
cmmLoadIndexW dflags arg1 (fixedHdrSizeW dflags) (bWord dflags),
cmmLoadIndexW dflags arg2 (fixedHdrSizeW dflags) (bWord dflags)
])
emitPrimOp dflags [res] ReallyUnsafePtrEqualityOp [arg1,arg2]
= emitAssign (CmmLocal res) (CmmMachOp (mo_wordEq dflags) [arg1,arg2])
-- #define addrToHValuezh(r,a) r=(P_)a
emitPrimOp _ [res] AddrToAnyOp [arg]
= emitAssign (CmmLocal res) arg
-- #define dataToTagzh(r,a) r=(GET_TAG(((StgClosure *)a)->header.info))
-- Note: argument may be tagged!
emitPrimOp dflags [res] DataToTagOp [arg]
= emitAssign (CmmLocal res) (getConstrTag dflags (cmmUntag dflags arg))
{- Freezing arrays-of-ptrs requires changing an info table, for the
benefit of the generational collector. It needs to scavenge mutable
objects, even if they are in old space. When they become immutable,
they can be removed from this scavenge list. -}
-- #define unsafeFreezzeArrayzh(r,a)
-- {
-- SET_INFO((StgClosure *)a,&stg_MUT_ARR_PTRS_FROZEN0_info);
-- r = a;
-- }
emitPrimOp _ [res] UnsafeFreezeArrayOp [arg]
= emit $ catAGraphs
[ setInfo arg (CmmLit (CmmLabel mkMAP_FROZEN0_infoLabel)),
mkAssign (CmmLocal res) arg ]
emitPrimOp _ [res] UnsafeFreezeArrayArrayOp [arg]
= emit $ catAGraphs
[ setInfo arg (CmmLit (CmmLabel mkMAP_FROZEN0_infoLabel)),
mkAssign (CmmLocal res) arg ]
emitPrimOp _ [res] UnsafeFreezeSmallArrayOp [arg]
= emit $ catAGraphs
[ setInfo arg (CmmLit (CmmLabel mkSMAP_FROZEN0_infoLabel)),
mkAssign (CmmLocal res) arg ]
-- #define unsafeFreezzeByteArrayzh(r,a) r=(a)
emitPrimOp _ [res] UnsafeFreezeByteArrayOp [arg]
= emitAssign (CmmLocal res) arg
-- Reading/writing pointer arrays
emitPrimOp _ [res] ReadArrayOp [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [res] IndexArrayOp [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [] WriteArrayOp [obj,ix,v] = doWritePtrArrayOp obj ix v
emitPrimOp _ [res] IndexArrayArrayOp_ByteArray [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [res] IndexArrayArrayOp_ArrayArray [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [res] ReadArrayArrayOp_ByteArray [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [res] ReadArrayArrayOp_MutableByteArray [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [res] ReadArrayArrayOp_ArrayArray [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [res] ReadArrayArrayOp_MutableArrayArray [obj,ix] = doReadPtrArrayOp res obj ix
emitPrimOp _ [] WriteArrayArrayOp_ByteArray [obj,ix,v] = doWritePtrArrayOp obj ix v
emitPrimOp _ [] WriteArrayArrayOp_MutableByteArray [obj,ix,v] = doWritePtrArrayOp obj ix v
emitPrimOp _ [] WriteArrayArrayOp_ArrayArray [obj,ix,v] = doWritePtrArrayOp obj ix v
emitPrimOp _ [] WriteArrayArrayOp_MutableArrayArray [obj,ix,v] = doWritePtrArrayOp obj ix v
emitPrimOp _ [res] ReadSmallArrayOp [obj,ix] = doReadSmallPtrArrayOp res obj ix
emitPrimOp _ [res] IndexSmallArrayOp [obj,ix] = doReadSmallPtrArrayOp res obj ix
emitPrimOp _ [] WriteSmallArrayOp [obj,ix,v] = doWriteSmallPtrArrayOp obj ix v
-- Getting the size of pointer arrays
emitPrimOp dflags [res] SizeofArrayOp [arg]
= emit $ mkAssign (CmmLocal res) (cmmLoadIndexW dflags arg
(fixedHdrSizeW dflags + bytesToWordsRoundUp dflags (oFFSET_StgMutArrPtrs_ptrs dflags))
(bWord dflags))
emitPrimOp dflags [res] SizeofMutableArrayOp [arg]
= emitPrimOp dflags [res] SizeofArrayOp [arg]
emitPrimOp dflags [res] SizeofArrayArrayOp [arg]
= emitPrimOp dflags [res] SizeofArrayOp [arg]
emitPrimOp dflags [res] SizeofMutableArrayArrayOp [arg]
= emitPrimOp dflags [res] SizeofArrayOp [arg]
emitPrimOp dflags [res] SizeofSmallArrayOp [arg] =
emit $ mkAssign (CmmLocal res)
(cmmLoadIndexW dflags arg
(fixedHdrSizeW dflags + bytesToWordsRoundUp dflags (oFFSET_StgSmallMutArrPtrs_ptrs dflags))
(bWord dflags))
emitPrimOp dflags [res] SizeofSmallMutableArrayOp [arg] =
emitPrimOp dflags [res] SizeofSmallArrayOp [arg]
-- IndexXXXoffAddr
emitPrimOp dflags res IndexOffAddrOp_Char args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res IndexOffAddrOp_WideChar args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp dflags res IndexOffAddrOp_Int args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res IndexOffAddrOp_Word args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res IndexOffAddrOp_Addr args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp _ res IndexOffAddrOp_Float args = doIndexOffAddrOp Nothing f32 res args
emitPrimOp _ res IndexOffAddrOp_Double args = doIndexOffAddrOp Nothing f64 res args
emitPrimOp dflags res IndexOffAddrOp_StablePtr args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res IndexOffAddrOp_Int8 args = doIndexOffAddrOp (Just (mo_s_8ToWord dflags)) b8 res args
emitPrimOp dflags res IndexOffAddrOp_Int16 args = doIndexOffAddrOp (Just (mo_s_16ToWord dflags)) b16 res args
emitPrimOp dflags res IndexOffAddrOp_Int32 args = doIndexOffAddrOp (Just (mo_s_32ToWord dflags)) b32 res args
emitPrimOp _ res IndexOffAddrOp_Int64 args = doIndexOffAddrOp Nothing b64 res args
emitPrimOp dflags res IndexOffAddrOp_Word8 args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res IndexOffAddrOp_Word16 args = doIndexOffAddrOp (Just (mo_u_16ToWord dflags)) b16 res args
emitPrimOp dflags res IndexOffAddrOp_Word32 args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp _ res IndexOffAddrOp_Word64 args = doIndexOffAddrOp Nothing b64 res args
-- ReadXXXoffAddr, which are identical, for our purposes, to IndexXXXoffAddr.
emitPrimOp dflags res ReadOffAddrOp_Char args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res ReadOffAddrOp_WideChar args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp dflags res ReadOffAddrOp_Int args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res ReadOffAddrOp_Word args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res ReadOffAddrOp_Addr args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp _ res ReadOffAddrOp_Float args = doIndexOffAddrOp Nothing f32 res args
emitPrimOp _ res ReadOffAddrOp_Double args = doIndexOffAddrOp Nothing f64 res args
emitPrimOp dflags res ReadOffAddrOp_StablePtr args = doIndexOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res ReadOffAddrOp_Int8 args = doIndexOffAddrOp (Just (mo_s_8ToWord dflags)) b8 res args
emitPrimOp dflags res ReadOffAddrOp_Int16 args = doIndexOffAddrOp (Just (mo_s_16ToWord dflags)) b16 res args
emitPrimOp dflags res ReadOffAddrOp_Int32 args = doIndexOffAddrOp (Just (mo_s_32ToWord dflags)) b32 res args
emitPrimOp _ res ReadOffAddrOp_Int64 args = doIndexOffAddrOp Nothing b64 res args
emitPrimOp dflags res ReadOffAddrOp_Word8 args = doIndexOffAddrOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res ReadOffAddrOp_Word16 args = doIndexOffAddrOp (Just (mo_u_16ToWord dflags)) b16 res args
emitPrimOp dflags res ReadOffAddrOp_Word32 args = doIndexOffAddrOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp _ res ReadOffAddrOp_Word64 args = doIndexOffAddrOp Nothing b64 res args
-- IndexXXXArray
emitPrimOp dflags res IndexByteArrayOp_Char args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res IndexByteArrayOp_WideChar args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp dflags res IndexByteArrayOp_Int args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res IndexByteArrayOp_Word args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res IndexByteArrayOp_Addr args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp _ res IndexByteArrayOp_Float args = doIndexByteArrayOp Nothing f32 res args
emitPrimOp _ res IndexByteArrayOp_Double args = doIndexByteArrayOp Nothing f64 res args
emitPrimOp dflags res IndexByteArrayOp_StablePtr args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res IndexByteArrayOp_Int8 args = doIndexByteArrayOp (Just (mo_s_8ToWord dflags)) b8 res args
emitPrimOp dflags res IndexByteArrayOp_Int16 args = doIndexByteArrayOp (Just (mo_s_16ToWord dflags)) b16 res args
emitPrimOp dflags res IndexByteArrayOp_Int32 args = doIndexByteArrayOp (Just (mo_s_32ToWord dflags)) b32 res args
emitPrimOp _ res IndexByteArrayOp_Int64 args = doIndexByteArrayOp Nothing b64 res args
emitPrimOp dflags res IndexByteArrayOp_Word8 args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res IndexByteArrayOp_Word16 args = doIndexByteArrayOp (Just (mo_u_16ToWord dflags)) b16 res args
emitPrimOp dflags res IndexByteArrayOp_Word32 args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp _ res IndexByteArrayOp_Word64 args = doIndexByteArrayOp Nothing b64 res args
-- ReadXXXArray, identical to IndexXXXArray.
emitPrimOp dflags res ReadByteArrayOp_Char args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res ReadByteArrayOp_WideChar args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp dflags res ReadByteArrayOp_Int args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res ReadByteArrayOp_Word args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res ReadByteArrayOp_Addr args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp _ res ReadByteArrayOp_Float args = doIndexByteArrayOp Nothing f32 res args
emitPrimOp _ res ReadByteArrayOp_Double args = doIndexByteArrayOp Nothing f64 res args
emitPrimOp dflags res ReadByteArrayOp_StablePtr args = doIndexByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res ReadByteArrayOp_Int8 args = doIndexByteArrayOp (Just (mo_s_8ToWord dflags)) b8 res args
emitPrimOp dflags res ReadByteArrayOp_Int16 args = doIndexByteArrayOp (Just (mo_s_16ToWord dflags)) b16 res args
emitPrimOp dflags res ReadByteArrayOp_Int32 args = doIndexByteArrayOp (Just (mo_s_32ToWord dflags)) b32 res args
emitPrimOp _ res ReadByteArrayOp_Int64 args = doIndexByteArrayOp Nothing b64 res args
emitPrimOp dflags res ReadByteArrayOp_Word8 args = doIndexByteArrayOp (Just (mo_u_8ToWord dflags)) b8 res args
emitPrimOp dflags res ReadByteArrayOp_Word16 args = doIndexByteArrayOp (Just (mo_u_16ToWord dflags)) b16 res args
emitPrimOp dflags res ReadByteArrayOp_Word32 args = doIndexByteArrayOp (Just (mo_u_32ToWord dflags)) b32 res args
emitPrimOp _ res ReadByteArrayOp_Word64 args = doIndexByteArrayOp Nothing b64 res args
-- WriteXXXoffAddr
emitPrimOp dflags res WriteOffAddrOp_Char args = doWriteOffAddrOp (Just (mo_WordTo8 dflags)) b8 res args
emitPrimOp dflags res WriteOffAddrOp_WideChar args = doWriteOffAddrOp (Just (mo_WordTo32 dflags)) b32 res args
emitPrimOp dflags res WriteOffAddrOp_Int args = doWriteOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res WriteOffAddrOp_Word args = doWriteOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res WriteOffAddrOp_Addr args = doWriteOffAddrOp Nothing (bWord dflags) res args
emitPrimOp _ res WriteOffAddrOp_Float args = doWriteOffAddrOp Nothing f32 res args
emitPrimOp _ res WriteOffAddrOp_Double args = doWriteOffAddrOp Nothing f64 res args
emitPrimOp dflags res WriteOffAddrOp_StablePtr args = doWriteOffAddrOp Nothing (bWord dflags) res args
emitPrimOp dflags res WriteOffAddrOp_Int8 args = doWriteOffAddrOp (Just (mo_WordTo8 dflags)) b8 res args
emitPrimOp dflags res WriteOffAddrOp_Int16 args = doWriteOffAddrOp (Just (mo_WordTo16 dflags)) b16 res args
emitPrimOp dflags res WriteOffAddrOp_Int32 args = doWriteOffAddrOp (Just (mo_WordTo32 dflags)) b32 res args
emitPrimOp _ res WriteOffAddrOp_Int64 args = doWriteOffAddrOp Nothing b64 res args
emitPrimOp dflags res WriteOffAddrOp_Word8 args = doWriteOffAddrOp (Just (mo_WordTo8 dflags)) b8 res args
emitPrimOp dflags res WriteOffAddrOp_Word16 args = doWriteOffAddrOp (Just (mo_WordTo16 dflags)) b16 res args
emitPrimOp dflags res WriteOffAddrOp_Word32 args = doWriteOffAddrOp (Just (mo_WordTo32 dflags)) b32 res args
emitPrimOp _ res WriteOffAddrOp_Word64 args = doWriteOffAddrOp Nothing b64 res args
-- WriteXXXArray
emitPrimOp dflags res WriteByteArrayOp_Char args = doWriteByteArrayOp (Just (mo_WordTo8 dflags)) b8 res args
emitPrimOp dflags res WriteByteArrayOp_WideChar args = doWriteByteArrayOp (Just (mo_WordTo32 dflags)) b32 res args
emitPrimOp dflags res WriteByteArrayOp_Int args = doWriteByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res WriteByteArrayOp_Word args = doWriteByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res WriteByteArrayOp_Addr args = doWriteByteArrayOp Nothing (bWord dflags) res args
emitPrimOp _ res WriteByteArrayOp_Float args = doWriteByteArrayOp Nothing f32 res args
emitPrimOp _ res WriteByteArrayOp_Double args = doWriteByteArrayOp Nothing f64 res args
emitPrimOp dflags res WriteByteArrayOp_StablePtr args = doWriteByteArrayOp Nothing (bWord dflags) res args
emitPrimOp dflags res WriteByteArrayOp_Int8 args = doWriteByteArrayOp (Just (mo_WordTo8 dflags)) b8 res args
emitPrimOp dflags res WriteByteArrayOp_Int16 args = doWriteByteArrayOp (Just (mo_WordTo16 dflags)) b16 res args
emitPrimOp dflags res WriteByteArrayOp_Int32 args = doWriteByteArrayOp (Just (mo_WordTo32 dflags)) b32 res args
emitPrimOp _ res WriteByteArrayOp_Int64 args = doWriteByteArrayOp Nothing b64 res args
emitPrimOp dflags res WriteByteArrayOp_Word8 args = doWriteByteArrayOp (Just (mo_WordTo8 dflags)) b8 res args
emitPrimOp dflags res WriteByteArrayOp_Word16 args = doWriteByteArrayOp (Just (mo_WordTo16 dflags)) b16 res args
emitPrimOp dflags res WriteByteArrayOp_Word32 args = doWriteByteArrayOp (Just (mo_WordTo32 dflags)) b32 res args
emitPrimOp _ res WriteByteArrayOp_Word64 args = doWriteByteArrayOp Nothing b64 res args
-- Copying and setting byte arrays
emitPrimOp _ [] CopyByteArrayOp [src,src_off,dst,dst_off,n] =
doCopyByteArrayOp src src_off dst dst_off n
emitPrimOp _ [] CopyMutableByteArrayOp [src,src_off,dst,dst_off,n] =
doCopyMutableByteArrayOp src src_off dst dst_off n
emitPrimOp _ [] CopyByteArrayToAddrOp [src,src_off,dst,n] =
doCopyByteArrayToAddrOp src src_off dst n
emitPrimOp _ [] CopyMutableByteArrayToAddrOp [src,src_off,dst,n] =
doCopyMutableByteArrayToAddrOp src src_off dst n
emitPrimOp _ [] CopyAddrToByteArrayOp [src,dst,dst_off,n] =
doCopyAddrToByteArrayOp src dst dst_off n
emitPrimOp _ [] SetByteArrayOp [ba,off,len,c] =
doSetByteArrayOp ba off len c
emitPrimOp _ [res] BSwap16Op [w] = emitBSwapCall res w W16
emitPrimOp _ [res] BSwap32Op [w] = emitBSwapCall res w W32
emitPrimOp _ [res] BSwap64Op [w] = emitBSwapCall res w W64
emitPrimOp dflags [res] BSwapOp [w] = emitBSwapCall res w (wordWidth dflags)
-- Population count
emitPrimOp _ [res] PopCnt8Op [w] = emitPopCntCall res w W8
emitPrimOp _ [res] PopCnt16Op [w] = emitPopCntCall res w W16
emitPrimOp _ [res] PopCnt32Op [w] = emitPopCntCall res w W32
emitPrimOp _ [res] PopCnt64Op [w] = emitPopCntCall res w W64
emitPrimOp dflags [res] PopCntOp [w] = emitPopCntCall res w (wordWidth dflags)
-- count leading zeros
emitPrimOp _ [res] Clz8Op [w] = emitClzCall res w W8
emitPrimOp _ [res] Clz16Op [w] = emitClzCall res w W16
emitPrimOp _ [res] Clz32Op [w] = emitClzCall res w W32
emitPrimOp _ [res] Clz64Op [w] = emitClzCall res w W64
emitPrimOp dflags [res] ClzOp [w] = emitClzCall res w (wordWidth dflags)
-- count trailing zeros
emitPrimOp _ [res] Ctz8Op [w] = emitCtzCall res w W8
emitPrimOp _ [res] Ctz16Op [w] = emitCtzCall res w W16
emitPrimOp _ [res] Ctz32Op [w] = emitCtzCall res w W32
emitPrimOp _ [res] Ctz64Op [w] = emitCtzCall res w W64
emitPrimOp dflags [res] CtzOp [w] = emitCtzCall res w (wordWidth dflags)
-- Unsigned int to floating point conversions
emitPrimOp _ [res] Word2FloatOp [w] = emitPrimCall [res]
(MO_UF_Conv W32) [w]
emitPrimOp _ [res] Word2DoubleOp [w] = emitPrimCall [res]
(MO_UF_Conv W64) [w]
-- SIMD primops
emitPrimOp dflags [res] (VecBroadcastOp vcat n w) [e] = do
checkVecCompatibility dflags vcat n w
doVecPackOp (vecElemInjectCast dflags vcat w) ty zeros (replicate n e) res
where
zeros :: CmmExpr
zeros = CmmLit $ CmmVec (replicate n zero)
zero :: CmmLit
zero = case vcat of
IntVec -> CmmInt 0 w
WordVec -> CmmInt 0 w
FloatVec -> CmmFloat 0 w
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags [res] (VecPackOp vcat n w) es = do
checkVecCompatibility dflags vcat n w
when (length es /= n) $
panic "emitPrimOp: VecPackOp has wrong number of arguments"
doVecPackOp (vecElemInjectCast dflags vcat w) ty zeros es res
where
zeros :: CmmExpr
zeros = CmmLit $ CmmVec (replicate n zero)
zero :: CmmLit
zero = case vcat of
IntVec -> CmmInt 0 w
WordVec -> CmmInt 0 w
FloatVec -> CmmFloat 0 w
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecUnpackOp vcat n w) [arg] = do
checkVecCompatibility dflags vcat n w
when (length res /= n) $
panic "emitPrimOp: VecUnpackOp has wrong number of results"
doVecUnpackOp (vecElemProjectCast dflags vcat w) ty arg res
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags [res] (VecInsertOp vcat n w) [v,e,i] = do
checkVecCompatibility dflags vcat n w
doVecInsertOp (vecElemInjectCast dflags vcat w) ty v e i res
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecIndexByteArrayOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexByteArrayOp Nothing ty res args
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecReadByteArrayOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexByteArrayOp Nothing ty res args
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecWriteByteArrayOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doWriteByteArrayOp Nothing ty res args
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecIndexOffAddrOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexOffAddrOp Nothing ty res args
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecReadOffAddrOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexOffAddrOp Nothing ty res args
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecWriteOffAddrOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doWriteOffAddrOp Nothing ty res args
where
ty :: CmmType
ty = vecVmmType vcat n w
emitPrimOp dflags res (VecIndexScalarByteArrayOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexByteArrayOpAs Nothing vecty ty res args
where
vecty :: CmmType
vecty = vecVmmType vcat n w
ty :: CmmType
ty = vecCmmCat vcat w
emitPrimOp dflags res (VecReadScalarByteArrayOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexByteArrayOpAs Nothing vecty ty res args
where
vecty :: CmmType
vecty = vecVmmType vcat n w
ty :: CmmType
ty = vecCmmCat vcat w
emitPrimOp dflags res (VecWriteScalarByteArrayOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doWriteByteArrayOp Nothing ty res args
where
ty :: CmmType
ty = vecCmmCat vcat w
emitPrimOp dflags res (VecIndexScalarOffAddrOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexOffAddrOpAs Nothing vecty ty res args
where
vecty :: CmmType
vecty = vecVmmType vcat n w
ty :: CmmType
ty = vecCmmCat vcat w
emitPrimOp dflags res (VecReadScalarOffAddrOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doIndexOffAddrOpAs Nothing vecty ty res args
where
vecty :: CmmType
vecty = vecVmmType vcat n w
ty :: CmmType
ty = vecCmmCat vcat w
emitPrimOp dflags res (VecWriteScalarOffAddrOp vcat n w) args = do
checkVecCompatibility dflags vcat n w
doWriteOffAddrOp Nothing ty res args
where
ty :: CmmType
ty = vecCmmCat vcat w
-- Prefetch
emitPrimOp _ [] PrefetchByteArrayOp3 args = doPrefetchByteArrayOp 3 args
emitPrimOp _ [] PrefetchMutableByteArrayOp3 args = doPrefetchMutableByteArrayOp 3 args
emitPrimOp _ [] PrefetchAddrOp3 args = doPrefetchAddrOp 3 args
emitPrimOp _ [] PrefetchValueOp3 args = doPrefetchValueOp 3 args
emitPrimOp _ [] PrefetchByteArrayOp2 args = doPrefetchByteArrayOp 2 args
emitPrimOp _ [] PrefetchMutableByteArrayOp2 args = doPrefetchMutableByteArrayOp 2 args
emitPrimOp _ [] PrefetchAddrOp2 args = doPrefetchAddrOp 2 args
emitPrimOp _ [] PrefetchValueOp2 args = doPrefetchValueOp 2 args
emitPrimOp _ [] PrefetchByteArrayOp1 args = doPrefetchByteArrayOp 1 args
emitPrimOp _ [] PrefetchMutableByteArrayOp1 args = doPrefetchMutableByteArrayOp 1 args
emitPrimOp _ [] PrefetchAddrOp1 args = doPrefetchAddrOp 1 args
emitPrimOp _ [] PrefetchValueOp1 args = doPrefetchValueOp 1 args
emitPrimOp _ [] PrefetchByteArrayOp0 args = doPrefetchByteArrayOp 0 args
emitPrimOp _ [] PrefetchMutableByteArrayOp0 args = doPrefetchMutableByteArrayOp 0 args
emitPrimOp _ [] PrefetchAddrOp0 args = doPrefetchAddrOp 0 args
emitPrimOp _ [] PrefetchValueOp0 args = doPrefetchValueOp 0 args
-- Atomic read-modify-write
emitPrimOp dflags [res] FetchAddByteArrayOp_Int [mba, ix, n] =
doAtomicRMW res AMO_Add mba ix (bWord dflags) n
emitPrimOp dflags [res] FetchSubByteArrayOp_Int [mba, ix, n] =
doAtomicRMW res AMO_Sub mba ix (bWord dflags) n
emitPrimOp dflags [res] FetchAndByteArrayOp_Int [mba, ix, n] =
doAtomicRMW res AMO_And mba ix (bWord dflags) n
emitPrimOp dflags [res] FetchNandByteArrayOp_Int [mba, ix, n] =
doAtomicRMW res AMO_Nand mba ix (bWord dflags) n
emitPrimOp dflags [res] FetchOrByteArrayOp_Int [mba, ix, n] =
doAtomicRMW res AMO_Or mba ix (bWord dflags) n
emitPrimOp dflags [res] FetchXorByteArrayOp_Int [mba, ix, n] =
doAtomicRMW res AMO_Xor mba ix (bWord dflags) n
emitPrimOp dflags [res] AtomicReadByteArrayOp_Int [mba, ix] =
doAtomicReadByteArray res mba ix (bWord dflags)
emitPrimOp dflags [] AtomicWriteByteArrayOp_Int [mba, ix, val] =
doAtomicWriteByteArray mba ix (bWord dflags) val
emitPrimOp dflags [res] CasByteArrayOp_Int [mba, ix, old, new] =
doCasByteArray res mba ix (bWord dflags) old new
-- The rest just translate straightforwardly
emitPrimOp dflags [res] op [arg]
| nopOp op
= emitAssign (CmmLocal res) arg
| Just (mop,rep) <- narrowOp op
= emitAssign (CmmLocal res) $
CmmMachOp (mop rep (wordWidth dflags)) [CmmMachOp (mop (wordWidth dflags) rep) [arg]]
emitPrimOp dflags r@[res] op args
| Just prim <- callishOp op
= do emitPrimCall r prim args
| Just mop <- translateOp dflags op
= let stmt = mkAssign (CmmLocal res) (CmmMachOp mop args) in
emit stmt
emitPrimOp dflags results op args
= case callishPrimOpSupported dflags op of
Left op -> emit $ mkUnsafeCall (PrimTarget op) results args
Right gen -> gen results args
type GenericOp = [CmmFormal] -> [CmmActual] -> FCode ()
callishPrimOpSupported :: DynFlags -> PrimOp -> Either CallishMachOp GenericOp
callishPrimOpSupported dflags op
= case op of
IntQuotRemOp | ncg && x86ish -> Left (MO_S_QuotRem (wordWidth dflags))
| otherwise -> Right (genericIntQuotRemOp dflags)
WordQuotRemOp | ncg && x86ish -> Left (MO_U_QuotRem (wordWidth dflags))
| otherwise -> Right (genericWordQuotRemOp dflags)
WordQuotRem2Op | (ncg && x86ish)
|| llvm -> Left (MO_U_QuotRem2 (wordWidth dflags))
| otherwise -> Right (genericWordQuotRem2Op dflags)
WordAdd2Op | (ncg && x86ish)
|| llvm -> Left (MO_Add2 (wordWidth dflags))
| otherwise -> Right genericWordAdd2Op
WordSubCOp | (ncg && x86ish)
|| llvm -> Left (MO_SubWordC (wordWidth dflags))
| otherwise -> Right genericWordSubCOp
IntAddCOp | (ncg && x86ish)
|| llvm -> Left (MO_AddIntC (wordWidth dflags))
| otherwise -> Right genericIntAddCOp
IntSubCOp | (ncg && x86ish)
|| llvm -> Left (MO_SubIntC (wordWidth dflags))
| otherwise -> Right genericIntSubCOp
WordMul2Op | ncg && x86ish
|| llvm -> Left (MO_U_Mul2 (wordWidth dflags))
| otherwise -> Right genericWordMul2Op
_ -> pprPanic "emitPrimOp: can't translate PrimOp " (ppr op)
where
ncg = case hscTarget dflags of
HscAsm -> True
_ -> False
llvm = case hscTarget dflags of
HscLlvm -> True
_ -> False
x86ish = case platformArch (targetPlatform dflags) of
ArchX86 -> True
ArchX86_64 -> True
_ -> False
genericIntQuotRemOp :: DynFlags -> GenericOp
genericIntQuotRemOp dflags [res_q, res_r] [arg_x, arg_y]
= emit $ mkAssign (CmmLocal res_q)
(CmmMachOp (MO_S_Quot (wordWidth dflags)) [arg_x, arg_y]) <*>
mkAssign (CmmLocal res_r)
(CmmMachOp (MO_S_Rem (wordWidth dflags)) [arg_x, arg_y])
genericIntQuotRemOp _ _ _ = panic "genericIntQuotRemOp"
genericWordQuotRemOp :: DynFlags -> GenericOp
genericWordQuotRemOp dflags [res_q, res_r] [arg_x, arg_y]
= emit $ mkAssign (CmmLocal res_q)
(CmmMachOp (MO_U_Quot (wordWidth dflags)) [arg_x, arg_y]) <*>
mkAssign (CmmLocal res_r)
(CmmMachOp (MO_U_Rem (wordWidth dflags)) [arg_x, arg_y])
genericWordQuotRemOp _ _ _ = panic "genericWordQuotRemOp"
genericWordQuotRem2Op :: DynFlags -> GenericOp
genericWordQuotRem2Op dflags [res_q, res_r] [arg_x_high, arg_x_low, arg_y]
= emit =<< f (widthInBits (wordWidth dflags)) zero arg_x_high arg_x_low
where ty = cmmExprType dflags arg_x_high
shl x i = CmmMachOp (MO_Shl (wordWidth dflags)) [x, i]
shr x i = CmmMachOp (MO_U_Shr (wordWidth dflags)) [x, i]
or x y = CmmMachOp (MO_Or (wordWidth dflags)) [x, y]
ge x y = CmmMachOp (MO_U_Ge (wordWidth dflags)) [x, y]
ne x y = CmmMachOp (MO_Ne (wordWidth dflags)) [x, y]
minus x y = CmmMachOp (MO_Sub (wordWidth dflags)) [x, y]
times x y = CmmMachOp (MO_Mul (wordWidth dflags)) [x, y]
zero = lit 0
one = lit 1
negone = lit (fromIntegral (widthInBits (wordWidth dflags)) - 1)
lit i = CmmLit (CmmInt i (wordWidth dflags))
f :: Int -> CmmExpr -> CmmExpr -> CmmExpr -> FCode CmmAGraph
f 0 acc high _ = return (mkAssign (CmmLocal res_q) acc <*>
mkAssign (CmmLocal res_r) high)
f i acc high low =
do roverflowedBit <- newTemp ty
rhigh' <- newTemp ty
rhigh'' <- newTemp ty
rlow' <- newTemp ty
risge <- newTemp ty
racc' <- newTemp ty
let high' = CmmReg (CmmLocal rhigh')
isge = CmmReg (CmmLocal risge)
overflowedBit = CmmReg (CmmLocal roverflowedBit)
let this = catAGraphs
[mkAssign (CmmLocal roverflowedBit)
(shr high negone),
mkAssign (CmmLocal rhigh')
(or (shl high one) (shr low negone)),
mkAssign (CmmLocal rlow')
(shl low one),
mkAssign (CmmLocal risge)
(or (overflowedBit `ne` zero)
(high' `ge` arg_y)),
mkAssign (CmmLocal rhigh'')
(high' `minus` (arg_y `times` isge)),
mkAssign (CmmLocal racc')
(or (shl acc one) isge)]
rest <- f (i - 1) (CmmReg (CmmLocal racc'))
(CmmReg (CmmLocal rhigh''))
(CmmReg (CmmLocal rlow'))
return (this <*> rest)
genericWordQuotRem2Op _ _ _ = panic "genericWordQuotRem2Op"
genericWordAdd2Op :: GenericOp
genericWordAdd2Op [res_h, res_l] [arg_x, arg_y]
= do dflags <- getDynFlags
r1 <- newTemp (cmmExprType dflags arg_x)
r2 <- newTemp (cmmExprType dflags arg_x)
let topHalf x = CmmMachOp (MO_U_Shr (wordWidth dflags)) [x, hww]
toTopHalf x = CmmMachOp (MO_Shl (wordWidth dflags)) [x, hww]
bottomHalf x = CmmMachOp (MO_And (wordWidth dflags)) [x, hwm]
add x y = CmmMachOp (MO_Add (wordWidth dflags)) [x, y]
or x y = CmmMachOp (MO_Or (wordWidth dflags)) [x, y]
hww = CmmLit (CmmInt (fromIntegral (widthInBits (halfWordWidth dflags)))
(wordWidth dflags))
hwm = CmmLit (CmmInt (halfWordMask dflags) (wordWidth dflags))
emit $ catAGraphs
[mkAssign (CmmLocal r1)
(add (bottomHalf arg_x) (bottomHalf arg_y)),
mkAssign (CmmLocal r2)
(add (topHalf (CmmReg (CmmLocal r1)))
(add (topHalf arg_x) (topHalf arg_y))),
mkAssign (CmmLocal res_h)
(topHalf (CmmReg (CmmLocal r2))),
mkAssign (CmmLocal res_l)
(or (toTopHalf (CmmReg (CmmLocal r2)))
(bottomHalf (CmmReg (CmmLocal r1))))]
genericWordAdd2Op _ _ = panic "genericWordAdd2Op"
genericWordSubCOp :: GenericOp
genericWordSubCOp [res_r, res_c] [aa, bb] = do
dflags <- getDynFlags
emit $ catAGraphs
[ -- Put the result into 'res_r'.
mkAssign (CmmLocal res_r) $
CmmMachOp (mo_wordSub dflags) [aa, bb]
-- Set 'res_c' to 1 if 'bb > aa' and to 0 otherwise.
, mkAssign (CmmLocal res_c) $
CmmMachOp (mo_wordUGt dflags) [bb, aa]
]
genericWordSubCOp _ _ = panic "genericWordSubCOp"
genericIntAddCOp :: GenericOp
genericIntAddCOp [res_r, res_c] [aa, bb]
{-
With some bit-twiddling, we can define int{Add,Sub}Czh portably in
C, and without needing any comparisons. This may not be the
fastest way to do it - if you have better code, please send it! --SDM
Return : r = a + b, c = 0 if no overflow, 1 on overflow.
We currently don't make use of the r value if c is != 0 (i.e.
overflow), we just convert to big integers and try again. This
could be improved by making r and c the correct values for
plugging into a new J#.
{ r = ((I_)(a)) + ((I_)(b)); \
c = ((StgWord)(~(((I_)(a))^((I_)(b))) & (((I_)(a))^r))) \
>> (BITS_IN (I_) - 1); \
}
Wading through the mass of bracketry, it seems to reduce to:
c = ( (~(a^b)) & (a^r) ) >>unsigned (BITS_IN(I_)-1)
-}
= do dflags <- getDynFlags
emit $ catAGraphs [
mkAssign (CmmLocal res_r) (CmmMachOp (mo_wordAdd dflags) [aa,bb]),
mkAssign (CmmLocal res_c) $
CmmMachOp (mo_wordUShr dflags) [
CmmMachOp (mo_wordAnd dflags) [
CmmMachOp (mo_wordNot dflags) [CmmMachOp (mo_wordXor dflags) [aa,bb]],
CmmMachOp (mo_wordXor dflags) [aa, CmmReg (CmmLocal res_r)]
],
mkIntExpr dflags (wORD_SIZE_IN_BITS dflags - 1)
]
]
genericIntAddCOp _ _ = panic "genericIntAddCOp"
genericIntSubCOp :: GenericOp
genericIntSubCOp [res_r, res_c] [aa, bb]
{- Similarly:
#define subIntCzh(r,c,a,b) \
{ r = ((I_)(a)) - ((I_)(b)); \
c = ((StgWord)((((I_)(a))^((I_)(b))) & (((I_)(a))^r))) \
>> (BITS_IN (I_) - 1); \
}
c = ((a^b) & (a^r)) >>unsigned (BITS_IN(I_)-1)
-}
= do dflags <- getDynFlags
emit $ catAGraphs [
mkAssign (CmmLocal res_r) (CmmMachOp (mo_wordSub dflags) [aa,bb]),
mkAssign (CmmLocal res_c) $
CmmMachOp (mo_wordUShr dflags) [
CmmMachOp (mo_wordAnd dflags) [
CmmMachOp (mo_wordXor dflags) [aa,bb],
CmmMachOp (mo_wordXor dflags) [aa, CmmReg (CmmLocal res_r)]
],
mkIntExpr dflags (wORD_SIZE_IN_BITS dflags - 1)
]
]
genericIntSubCOp _ _ = panic "genericIntSubCOp"
genericWordMul2Op :: GenericOp
genericWordMul2Op [res_h, res_l] [arg_x, arg_y]
= do dflags <- getDynFlags
let t = cmmExprType dflags arg_x
xlyl <- liftM CmmLocal $ newTemp t
xlyh <- liftM CmmLocal $ newTemp t
xhyl <- liftM CmmLocal $ newTemp t
r <- liftM CmmLocal $ newTemp t
-- This generic implementation is very simple and slow. We might
-- well be able to do better, but for now this at least works.
let topHalf x = CmmMachOp (MO_U_Shr (wordWidth dflags)) [x, hww]
toTopHalf x = CmmMachOp (MO_Shl (wordWidth dflags)) [x, hww]
bottomHalf x = CmmMachOp (MO_And (wordWidth dflags)) [x, hwm]
add x y = CmmMachOp (MO_Add (wordWidth dflags)) [x, y]
sum = foldl1 add
mul x y = CmmMachOp (MO_Mul (wordWidth dflags)) [x, y]
or x y = CmmMachOp (MO_Or (wordWidth dflags)) [x, y]
hww = CmmLit (CmmInt (fromIntegral (widthInBits (halfWordWidth dflags)))
(wordWidth dflags))
hwm = CmmLit (CmmInt (halfWordMask dflags) (wordWidth dflags))
emit $ catAGraphs
[mkAssign xlyl
(mul (bottomHalf arg_x) (bottomHalf arg_y)),
mkAssign xlyh
(mul (bottomHalf arg_x) (topHalf arg_y)),
mkAssign xhyl
(mul (topHalf arg_x) (bottomHalf arg_y)),
mkAssign r
(sum [topHalf (CmmReg xlyl),
bottomHalf (CmmReg xhyl),
bottomHalf (CmmReg xlyh)]),
mkAssign (CmmLocal res_l)
(or (bottomHalf (CmmReg xlyl))
(toTopHalf (CmmReg r))),
mkAssign (CmmLocal res_h)
(sum [mul (topHalf arg_x) (topHalf arg_y),
topHalf (CmmReg xhyl),
topHalf (CmmReg xlyh),
topHalf (CmmReg r)])]
genericWordMul2Op _ _ = panic "genericWordMul2Op"
-- These PrimOps are NOPs in Cmm
nopOp :: PrimOp -> Bool
nopOp Int2WordOp = True
nopOp Word2IntOp = True
nopOp Int2AddrOp = True
nopOp Addr2IntOp = True
nopOp ChrOp = True -- Int# and Char# are rep'd the same
nopOp OrdOp = True
nopOp _ = False
-- These PrimOps turn into double casts
narrowOp :: PrimOp -> Maybe (Width -> Width -> MachOp, Width)
narrowOp Narrow8IntOp = Just (MO_SS_Conv, W8)
narrowOp Narrow16IntOp = Just (MO_SS_Conv, W16)
narrowOp Narrow32IntOp = Just (MO_SS_Conv, W32)
narrowOp Narrow8WordOp = Just (MO_UU_Conv, W8)
narrowOp Narrow16WordOp = Just (MO_UU_Conv, W16)
narrowOp Narrow32WordOp = Just (MO_UU_Conv, W32)
narrowOp _ = Nothing
-- Native word signless ops
translateOp :: DynFlags -> PrimOp -> Maybe MachOp
translateOp dflags IntAddOp = Just (mo_wordAdd dflags)
translateOp dflags IntSubOp = Just (mo_wordSub dflags)
translateOp dflags WordAddOp = Just (mo_wordAdd dflags)
translateOp dflags WordSubOp = Just (mo_wordSub dflags)
translateOp dflags AddrAddOp = Just (mo_wordAdd dflags)
translateOp dflags AddrSubOp = Just (mo_wordSub dflags)
translateOp dflags IntEqOp = Just (mo_wordEq dflags)
translateOp dflags IntNeOp = Just (mo_wordNe dflags)
translateOp dflags WordEqOp = Just (mo_wordEq dflags)
translateOp dflags WordNeOp = Just (mo_wordNe dflags)
translateOp dflags AddrEqOp = Just (mo_wordEq dflags)
translateOp dflags AddrNeOp = Just (mo_wordNe dflags)
translateOp dflags AndOp = Just (mo_wordAnd dflags)
translateOp dflags OrOp = Just (mo_wordOr dflags)
translateOp dflags XorOp = Just (mo_wordXor dflags)
translateOp dflags NotOp = Just (mo_wordNot dflags)
translateOp dflags SllOp = Just (mo_wordShl dflags)
translateOp dflags SrlOp = Just (mo_wordUShr dflags)
translateOp dflags AddrRemOp = Just (mo_wordURem dflags)
-- Native word signed ops
translateOp dflags IntMulOp = Just (mo_wordMul dflags)
translateOp dflags IntMulMayOfloOp = Just (MO_S_MulMayOflo (wordWidth dflags))
translateOp dflags IntQuotOp = Just (mo_wordSQuot dflags)
translateOp dflags IntRemOp = Just (mo_wordSRem dflags)
translateOp dflags IntNegOp = Just (mo_wordSNeg dflags)
translateOp dflags IntGeOp = Just (mo_wordSGe dflags)
translateOp dflags IntLeOp = Just (mo_wordSLe dflags)
translateOp dflags IntGtOp = Just (mo_wordSGt dflags)
translateOp dflags IntLtOp = Just (mo_wordSLt dflags)
translateOp dflags AndIOp = Just (mo_wordAnd dflags)
translateOp dflags OrIOp = Just (mo_wordOr dflags)
translateOp dflags XorIOp = Just (mo_wordXor dflags)
translateOp dflags NotIOp = Just (mo_wordNot dflags)
translateOp dflags ISllOp = Just (mo_wordShl dflags)
translateOp dflags ISraOp = Just (mo_wordSShr dflags)
translateOp dflags ISrlOp = Just (mo_wordUShr dflags)
-- Native word unsigned ops
translateOp dflags WordGeOp = Just (mo_wordUGe dflags)
translateOp dflags WordLeOp = Just (mo_wordULe dflags)
translateOp dflags WordGtOp = Just (mo_wordUGt dflags)
translateOp dflags WordLtOp = Just (mo_wordULt dflags)
translateOp dflags WordMulOp = Just (mo_wordMul dflags)
translateOp dflags WordQuotOp = Just (mo_wordUQuot dflags)
translateOp dflags WordRemOp = Just (mo_wordURem dflags)
translateOp dflags AddrGeOp = Just (mo_wordUGe dflags)
translateOp dflags AddrLeOp = Just (mo_wordULe dflags)
translateOp dflags AddrGtOp = Just (mo_wordUGt dflags)
translateOp dflags AddrLtOp = Just (mo_wordULt dflags)
-- Char# ops
translateOp dflags CharEqOp = Just (MO_Eq (wordWidth dflags))
translateOp dflags CharNeOp = Just (MO_Ne (wordWidth dflags))
translateOp dflags CharGeOp = Just (MO_U_Ge (wordWidth dflags))
translateOp dflags CharLeOp = Just (MO_U_Le (wordWidth dflags))
translateOp dflags CharGtOp = Just (MO_U_Gt (wordWidth dflags))
translateOp dflags CharLtOp = Just (MO_U_Lt (wordWidth dflags))
-- Double ops
translateOp _ DoubleEqOp = Just (MO_F_Eq W64)
translateOp _ DoubleNeOp = Just (MO_F_Ne W64)
translateOp _ DoubleGeOp = Just (MO_F_Ge W64)
translateOp _ DoubleLeOp = Just (MO_F_Le W64)
translateOp _ DoubleGtOp = Just (MO_F_Gt W64)
translateOp _ DoubleLtOp = Just (MO_F_Lt W64)
translateOp _ DoubleAddOp = Just (MO_F_Add W64)
translateOp _ DoubleSubOp = Just (MO_F_Sub W64)
translateOp _ DoubleMulOp = Just (MO_F_Mul W64)
translateOp _ DoubleDivOp = Just (MO_F_Quot W64)
translateOp _ DoubleNegOp = Just (MO_F_Neg W64)
-- Float ops
translateOp _ FloatEqOp = Just (MO_F_Eq W32)
translateOp _ FloatNeOp = Just (MO_F_Ne W32)
translateOp _ FloatGeOp = Just (MO_F_Ge W32)
translateOp _ FloatLeOp = Just (MO_F_Le W32)
translateOp _ FloatGtOp = Just (MO_F_Gt W32)
translateOp _ FloatLtOp = Just (MO_F_Lt W32)
translateOp _ FloatAddOp = Just (MO_F_Add W32)
translateOp _ FloatSubOp = Just (MO_F_Sub W32)
translateOp _ FloatMulOp = Just (MO_F_Mul W32)
translateOp _ FloatDivOp = Just (MO_F_Quot W32)
translateOp _ FloatNegOp = Just (MO_F_Neg W32)
-- Vector ops
translateOp _ (VecAddOp FloatVec n w) = Just (MO_VF_Add n w)
translateOp _ (VecSubOp FloatVec n w) = Just (MO_VF_Sub n w)
translateOp _ (VecMulOp FloatVec n w) = Just (MO_VF_Mul n w)
translateOp _ (VecDivOp FloatVec n w) = Just (MO_VF_Quot n w)
translateOp _ (VecNegOp FloatVec n w) = Just (MO_VF_Neg n w)
translateOp _ (VecAddOp IntVec n w) = Just (MO_V_Add n w)
translateOp _ (VecSubOp IntVec n w) = Just (MO_V_Sub n w)
translateOp _ (VecMulOp IntVec n w) = Just (MO_V_Mul n w)
translateOp _ (VecQuotOp IntVec n w) = Just (MO_VS_Quot n w)
translateOp _ (VecRemOp IntVec n w) = Just (MO_VS_Rem n w)
translateOp _ (VecNegOp IntVec n w) = Just (MO_VS_Neg n w)
translateOp _ (VecAddOp WordVec n w) = Just (MO_V_Add n w)
translateOp _ (VecSubOp WordVec n w) = Just (MO_V_Sub n w)
translateOp _ (VecMulOp WordVec n w) = Just (MO_V_Mul n w)
translateOp _ (VecQuotOp WordVec n w) = Just (MO_VU_Quot n w)
translateOp _ (VecRemOp WordVec n w) = Just (MO_VU_Rem n w)
-- Conversions
translateOp dflags Int2DoubleOp = Just (MO_SF_Conv (wordWidth dflags) W64)
translateOp dflags Double2IntOp = Just (MO_FS_Conv W64 (wordWidth dflags))
translateOp dflags Int2FloatOp = Just (MO_SF_Conv (wordWidth dflags) W32)
translateOp dflags Float2IntOp = Just (MO_FS_Conv W32 (wordWidth dflags))
translateOp _ Float2DoubleOp = Just (MO_FF_Conv W32 W64)
translateOp _ Double2FloatOp = Just (MO_FF_Conv W64 W32)
-- Word comparisons masquerading as more exotic things.
translateOp dflags SameMutVarOp = Just (mo_wordEq dflags)
translateOp dflags SameMVarOp = Just (mo_wordEq dflags)
translateOp dflags SameMutableArrayOp = Just (mo_wordEq dflags)
translateOp dflags SameMutableByteArrayOp = Just (mo_wordEq dflags)
translateOp dflags SameMutableArrayArrayOp= Just (mo_wordEq dflags)
translateOp dflags SameSmallMutableArrayOp= Just (mo_wordEq dflags)
translateOp dflags SameTVarOp = Just (mo_wordEq dflags)
translateOp dflags EqStablePtrOp = Just (mo_wordEq dflags)
translateOp _ _ = Nothing
-- These primops are implemented by CallishMachOps, because they sometimes
-- turn into foreign calls depending on the backend.
callishOp :: PrimOp -> Maybe CallishMachOp
callishOp DoublePowerOp = Just MO_F64_Pwr
callishOp DoubleSinOp = Just MO_F64_Sin
callishOp DoubleCosOp = Just MO_F64_Cos
callishOp DoubleTanOp = Just MO_F64_Tan
callishOp DoubleSinhOp = Just MO_F64_Sinh
callishOp DoubleCoshOp = Just MO_F64_Cosh
callishOp DoubleTanhOp = Just MO_F64_Tanh
callishOp DoubleAsinOp = Just MO_F64_Asin
callishOp DoubleAcosOp = Just MO_F64_Acos
callishOp DoubleAtanOp = Just MO_F64_Atan
callishOp DoubleLogOp = Just MO_F64_Log
callishOp DoubleExpOp = Just MO_F64_Exp
callishOp DoubleSqrtOp = Just MO_F64_Sqrt
callishOp FloatPowerOp = Just MO_F32_Pwr
callishOp FloatSinOp = Just MO_F32_Sin
callishOp FloatCosOp = Just MO_F32_Cos
callishOp FloatTanOp = Just MO_F32_Tan
callishOp FloatSinhOp = Just MO_F32_Sinh
callishOp FloatCoshOp = Just MO_F32_Cosh
callishOp FloatTanhOp = Just MO_F32_Tanh
callishOp FloatAsinOp = Just MO_F32_Asin
callishOp FloatAcosOp = Just MO_F32_Acos
callishOp FloatAtanOp = Just MO_F32_Atan
callishOp FloatLogOp = Just MO_F32_Log
callishOp FloatExpOp = Just MO_F32_Exp
callishOp FloatSqrtOp = Just MO_F32_Sqrt
callishOp _ = Nothing
------------------------------------------------------------------------------
-- Helpers for translating various minor variants of array indexing.
doIndexOffAddrOp :: Maybe MachOp
-> CmmType
-> [LocalReg]
-> [CmmExpr]
-> FCode ()
doIndexOffAddrOp maybe_post_read_cast rep [res] [addr,idx]
= mkBasicIndexedRead 0 maybe_post_read_cast rep res addr rep idx
doIndexOffAddrOp _ _ _ _
= panic "StgCmmPrim: doIndexOffAddrOp"
doIndexOffAddrOpAs :: Maybe MachOp
-> CmmType
-> CmmType
-> [LocalReg]
-> [CmmExpr]
-> FCode ()
doIndexOffAddrOpAs maybe_post_read_cast rep idx_rep [res] [addr,idx]
= mkBasicIndexedRead 0 maybe_post_read_cast rep res addr idx_rep idx
doIndexOffAddrOpAs _ _ _ _ _
= panic "StgCmmPrim: doIndexOffAddrOpAs"
doIndexByteArrayOp :: Maybe MachOp
-> CmmType
-> [LocalReg]
-> [CmmExpr]
-> FCode ()
doIndexByteArrayOp maybe_post_read_cast rep [res] [addr,idx]
= do dflags <- getDynFlags
mkBasicIndexedRead (arrWordsHdrSize dflags) maybe_post_read_cast rep res addr rep idx
doIndexByteArrayOp _ _ _ _
= panic "StgCmmPrim: doIndexByteArrayOp"
doIndexByteArrayOpAs :: Maybe MachOp
-> CmmType
-> CmmType
-> [LocalReg]
-> [CmmExpr]
-> FCode ()
doIndexByteArrayOpAs maybe_post_read_cast rep idx_rep [res] [addr,idx]
= do dflags <- getDynFlags
mkBasicIndexedRead (arrWordsHdrSize dflags) maybe_post_read_cast rep res addr idx_rep idx
doIndexByteArrayOpAs _ _ _ _ _
= panic "StgCmmPrim: doIndexByteArrayOpAs"
doReadPtrArrayOp :: LocalReg
-> CmmExpr
-> CmmExpr
-> FCode ()
doReadPtrArrayOp res addr idx
= do dflags <- getDynFlags
mkBasicIndexedRead (arrPtrsHdrSize dflags) Nothing (gcWord dflags) res addr (gcWord dflags) idx
doWriteOffAddrOp :: Maybe MachOp
-> CmmType
-> [LocalReg]
-> [CmmExpr]
-> FCode ()
doWriteOffAddrOp maybe_pre_write_cast idx_ty [] [addr,idx,val]
= mkBasicIndexedWrite 0 maybe_pre_write_cast addr idx_ty idx val
doWriteOffAddrOp _ _ _ _
= panic "StgCmmPrim: doWriteOffAddrOp"
doWriteByteArrayOp :: Maybe MachOp
-> CmmType
-> [LocalReg]
-> [CmmExpr]
-> FCode ()
doWriteByteArrayOp maybe_pre_write_cast idx_ty [] [addr,idx,val]
= do dflags <- getDynFlags
mkBasicIndexedWrite (arrWordsHdrSize dflags) maybe_pre_write_cast addr idx_ty idx val
doWriteByteArrayOp _ _ _ _
= panic "StgCmmPrim: doWriteByteArrayOp"
doWritePtrArrayOp :: CmmExpr
-> CmmExpr
-> CmmExpr
-> FCode ()
doWritePtrArrayOp addr idx val
= do dflags <- getDynFlags
let ty = cmmExprType dflags val
-- This write barrier is to ensure that the heap writes to the object
-- referred to by val have happened before we write val into the array.
-- See #12469 for details.
emitPrimCall [] MO_WriteBarrier []
mkBasicIndexedWrite (arrPtrsHdrSize dflags) Nothing addr ty idx val
emit (setInfo addr (CmmLit (CmmLabel mkMAP_DIRTY_infoLabel)))
-- the write barrier. We must write a byte into the mark table:
-- bits8[a + header_size + StgMutArrPtrs_size(a) + x >> N]
emit $ mkStore (
cmmOffsetExpr dflags
(cmmOffsetExprW dflags (cmmOffsetB dflags addr (arrPtrsHdrSize dflags))
(loadArrPtrsSize dflags addr))
(CmmMachOp (mo_wordUShr dflags) [idx,
mkIntExpr dflags (mUT_ARR_PTRS_CARD_BITS dflags)])
) (CmmLit (CmmInt 1 W8))
loadArrPtrsSize :: DynFlags -> CmmExpr -> CmmExpr
loadArrPtrsSize dflags addr = CmmLoad (cmmOffsetB dflags addr off) (bWord dflags)
where off = fixedHdrSize dflags + oFFSET_StgMutArrPtrs_ptrs dflags
mkBasicIndexedRead :: ByteOff -- Initial offset in bytes
-> Maybe MachOp -- Optional result cast
-> CmmType -- Type of element we are accessing
-> LocalReg -- Destination
-> CmmExpr -- Base address
-> CmmType -- Type of element by which we are indexing
-> CmmExpr -- Index
-> FCode ()
mkBasicIndexedRead off Nothing ty res base idx_ty idx
= do dflags <- getDynFlags
emitAssign (CmmLocal res) (cmmLoadIndexOffExpr dflags off ty base idx_ty idx)
mkBasicIndexedRead off (Just cast) ty res base idx_ty idx
= do dflags <- getDynFlags
emitAssign (CmmLocal res) (CmmMachOp cast [
cmmLoadIndexOffExpr dflags off ty base idx_ty idx])
mkBasicIndexedWrite :: ByteOff -- Initial offset in bytes
-> Maybe MachOp -- Optional value cast
-> CmmExpr -- Base address
-> CmmType -- Type of element by which we are indexing
-> CmmExpr -- Index
-> CmmExpr -- Value to write
-> FCode ()
mkBasicIndexedWrite off Nothing base idx_ty idx val
= do dflags <- getDynFlags
emitStore (cmmIndexOffExpr dflags off (typeWidth idx_ty) base idx) val
mkBasicIndexedWrite off (Just cast) base idx_ty idx val
= mkBasicIndexedWrite off Nothing base idx_ty idx (CmmMachOp cast [val])
-- ----------------------------------------------------------------------------
-- Misc utils
cmmIndexOffExpr :: DynFlags
-> ByteOff -- Initial offset in bytes
-> Width -- Width of element by which we are indexing
-> CmmExpr -- Base address
-> CmmExpr -- Index
-> CmmExpr
cmmIndexOffExpr dflags off width base idx
= cmmIndexExpr dflags width (cmmOffsetB dflags base off) idx
cmmLoadIndexOffExpr :: DynFlags
-> ByteOff -- Initial offset in bytes
-> CmmType -- Type of element we are accessing
-> CmmExpr -- Base address
-> CmmType -- Type of element by which we are indexing
-> CmmExpr -- Index
-> CmmExpr
cmmLoadIndexOffExpr dflags off ty base idx_ty idx
= CmmLoad (cmmIndexOffExpr dflags off (typeWidth idx_ty) base idx) ty
setInfo :: CmmExpr -> CmmExpr -> CmmAGraph
setInfo closure_ptr info_ptr = mkStore closure_ptr info_ptr
------------------------------------------------------------------------------
-- Helpers for translating vector primops.
vecVmmType :: PrimOpVecCat -> Length -> Width -> CmmType
vecVmmType pocat n w = vec n (vecCmmCat pocat w)
vecCmmCat :: PrimOpVecCat -> Width -> CmmType
vecCmmCat IntVec = cmmBits
vecCmmCat WordVec = cmmBits
vecCmmCat FloatVec = cmmFloat
vecElemInjectCast :: DynFlags -> PrimOpVecCat -> Width -> Maybe MachOp
vecElemInjectCast _ FloatVec _ = Nothing
vecElemInjectCast dflags IntVec W8 = Just (mo_WordTo8 dflags)
vecElemInjectCast dflags IntVec W16 = Just (mo_WordTo16 dflags)
vecElemInjectCast dflags IntVec W32 = Just (mo_WordTo32 dflags)
vecElemInjectCast _ IntVec W64 = Nothing
vecElemInjectCast dflags WordVec W8 = Just (mo_WordTo8 dflags)
vecElemInjectCast dflags WordVec W16 = Just (mo_WordTo16 dflags)
vecElemInjectCast dflags WordVec W32 = Just (mo_WordTo32 dflags)
vecElemInjectCast _ WordVec W64 = Nothing
vecElemInjectCast _ _ _ = Nothing
vecElemProjectCast :: DynFlags -> PrimOpVecCat -> Width -> Maybe MachOp
vecElemProjectCast _ FloatVec _ = Nothing
vecElemProjectCast dflags IntVec W8 = Just (mo_s_8ToWord dflags)
vecElemProjectCast dflags IntVec W16 = Just (mo_s_16ToWord dflags)
vecElemProjectCast dflags IntVec W32 = Just (mo_s_32ToWord dflags)
vecElemProjectCast _ IntVec W64 = Nothing
vecElemProjectCast dflags WordVec W8 = Just (mo_u_8ToWord dflags)
vecElemProjectCast dflags WordVec W16 = Just (mo_u_16ToWord dflags)
vecElemProjectCast dflags WordVec W32 = Just (mo_u_32ToWord dflags)
vecElemProjectCast _ WordVec W64 = Nothing
vecElemProjectCast _ _ _ = Nothing
-- Check to make sure that we can generate code for the specified vector type
-- given the current set of dynamic flags.
checkVecCompatibility :: DynFlags -> PrimOpVecCat -> Length -> Width -> FCode ()
checkVecCompatibility dflags vcat l w = do
when (hscTarget dflags /= HscLlvm) $ do
sorry $ unlines ["SIMD vector instructions require the LLVM back-end."
,"Please use -fllvm."]
check vecWidth vcat l w
where
check :: Width -> PrimOpVecCat -> Length -> Width -> FCode ()
check W128 FloatVec 4 W32 | not (isSseEnabled dflags) =
sorry $ "128-bit wide single-precision floating point " ++
"SIMD vector instructions require at least -msse."
check W128 _ _ _ | not (isSse2Enabled dflags) =
sorry $ "128-bit wide integer and double precision " ++
"SIMD vector instructions require at least -msse2."
check W256 FloatVec _ _ | not (isAvxEnabled dflags) =
sorry $ "256-bit wide floating point " ++
"SIMD vector instructions require at least -mavx."
check W256 _ _ _ | not (isAvx2Enabled dflags) =
sorry $ "256-bit wide integer " ++
"SIMD vector instructions require at least -mavx2."
check W512 _ _ _ | not (isAvx512fEnabled dflags) =
sorry $ "512-bit wide " ++
"SIMD vector instructions require -mavx512f."
check _ _ _ _ = return ()
vecWidth = typeWidth (vecVmmType vcat l w)
------------------------------------------------------------------------------
-- Helpers for translating vector packing and unpacking.
doVecPackOp :: Maybe MachOp -- Cast from element to vector component
-> CmmType -- Type of vector
-> CmmExpr -- Initial vector
-> [CmmExpr] -- Elements
-> CmmFormal -- Destination for result
-> FCode ()
doVecPackOp maybe_pre_write_cast ty z es res = do
dst <- newTemp ty
emitAssign (CmmLocal dst) z
vecPack dst es 0
where
vecPack :: CmmFormal -> [CmmExpr] -> Int -> FCode ()
vecPack src [] _ =
emitAssign (CmmLocal res) (CmmReg (CmmLocal src))
vecPack src (e : es) i = do
dst <- newTemp ty
if isFloatType (vecElemType ty)
then emitAssign (CmmLocal dst) (CmmMachOp (MO_VF_Insert len wid)
[CmmReg (CmmLocal src), cast e, iLit])
else emitAssign (CmmLocal dst) (CmmMachOp (MO_V_Insert len wid)
[CmmReg (CmmLocal src), cast e, iLit])
vecPack dst es (i + 1)
where
-- vector indices are always 32-bits
iLit = CmmLit (CmmInt (toInteger i) W32)
cast :: CmmExpr -> CmmExpr
cast val = case maybe_pre_write_cast of
Nothing -> val
Just cast -> CmmMachOp cast [val]
len :: Length
len = vecLength ty
wid :: Width
wid = typeWidth (vecElemType ty)
doVecUnpackOp :: Maybe MachOp -- Cast from vector component to element result
-> CmmType -- Type of vector
-> CmmExpr -- Vector
-> [CmmFormal] -- Element results
-> FCode ()
doVecUnpackOp maybe_post_read_cast ty e res =
vecUnpack res 0
where
vecUnpack :: [CmmFormal] -> Int -> FCode ()
vecUnpack [] _ =
return ()
vecUnpack (r : rs) i = do
if isFloatType (vecElemType ty)
then emitAssign (CmmLocal r) (cast (CmmMachOp (MO_VF_Extract len wid)
[e, iLit]))
else emitAssign (CmmLocal r) (cast (CmmMachOp (MO_V_Extract len wid)
[e, iLit]))
vecUnpack rs (i + 1)
where
-- vector indices are always 32-bits
iLit = CmmLit (CmmInt (toInteger i) W32)
cast :: CmmExpr -> CmmExpr
cast val = case maybe_post_read_cast of
Nothing -> val
Just cast -> CmmMachOp cast [val]
len :: Length
len = vecLength ty
wid :: Width
wid = typeWidth (vecElemType ty)
doVecInsertOp :: Maybe MachOp -- Cast from element to vector component
-> CmmType -- Vector type
-> CmmExpr -- Source vector
-> CmmExpr -- Element
-> CmmExpr -- Index at which to insert element
-> CmmFormal -- Destination for result
-> FCode ()
doVecInsertOp maybe_pre_write_cast ty src e idx res = do
dflags <- getDynFlags
-- vector indices are always 32-bits
let idx' :: CmmExpr
idx' = CmmMachOp (MO_SS_Conv (wordWidth dflags) W32) [idx]
if isFloatType (vecElemType ty)
then emitAssign (CmmLocal res) (CmmMachOp (MO_VF_Insert len wid) [src, cast e, idx'])
else emitAssign (CmmLocal res) (CmmMachOp (MO_V_Insert len wid) [src, cast e, idx'])
where
cast :: CmmExpr -> CmmExpr
cast val = case maybe_pre_write_cast of
Nothing -> val
Just cast -> CmmMachOp cast [val]
len :: Length
len = vecLength ty
wid :: Width
wid = typeWidth (vecElemType ty)
------------------------------------------------------------------------------
-- Helpers for translating prefetching.
-- | Translate byte array prefetch operations into proper primcalls.
doPrefetchByteArrayOp :: Int
-> [CmmExpr]
-> FCode ()
doPrefetchByteArrayOp locality [addr,idx]
= do dflags <- getDynFlags
mkBasicPrefetch locality (arrWordsHdrSize dflags) addr idx
doPrefetchByteArrayOp _ _
= panic "StgCmmPrim: doPrefetchByteArrayOp"
-- | Translate mutable byte array prefetch operations into proper primcalls.
doPrefetchMutableByteArrayOp :: Int
-> [CmmExpr]
-> FCode ()
doPrefetchMutableByteArrayOp locality [addr,idx]
= do dflags <- getDynFlags
mkBasicPrefetch locality (arrWordsHdrSize dflags) addr idx
doPrefetchMutableByteArrayOp _ _
= panic "StgCmmPrim: doPrefetchByteArrayOp"
-- | Translate address prefetch operations into proper primcalls.
doPrefetchAddrOp ::Int
-> [CmmExpr]
-> FCode ()
doPrefetchAddrOp locality [addr,idx]
= mkBasicPrefetch locality 0 addr idx
doPrefetchAddrOp _ _
= panic "StgCmmPrim: doPrefetchAddrOp"
-- | Translate value prefetch operations into proper primcalls.
doPrefetchValueOp :: Int
-> [CmmExpr]
-> FCode ()
doPrefetchValueOp locality [addr]
= do dflags <- getDynFlags
mkBasicPrefetch locality 0 addr (CmmLit (CmmInt 0 (wordWidth dflags)))
doPrefetchValueOp _ _
= panic "StgCmmPrim: doPrefetchValueOp"
-- | helper to generate prefetch primcalls
mkBasicPrefetch :: Int -- Locality level 0-3
-> ByteOff -- Initial offset in bytes
-> CmmExpr -- Base address
-> CmmExpr -- Index
-> FCode ()
mkBasicPrefetch locality off base idx
= do dflags <- getDynFlags
emitPrimCall [] (MO_Prefetch_Data locality) [cmmIndexExpr dflags W8 (cmmOffsetB dflags base off) idx]
return ()
-- ----------------------------------------------------------------------------
-- Allocating byte arrays
-- | Takes a register to return the newly allocated array in and the
-- size of the new array in bytes. Allocates a new
-- 'MutableByteArray#'.
doNewByteArrayOp :: CmmFormal -> ByteOff -> FCode ()
doNewByteArrayOp res_r n = do
dflags <- getDynFlags
let info_ptr = mkLblExpr mkArrWords_infoLabel
rep = arrWordsRep dflags n
tickyAllocPrim (mkIntExpr dflags (arrWordsHdrSize dflags))
(mkIntExpr dflags (nonHdrSize dflags rep))
(zeroExpr dflags)
let hdr_size = fixedHdrSize dflags
base <- allocHeapClosure rep info_ptr curCCS
[ (mkIntExpr dflags n,
hdr_size + oFFSET_StgArrBytes_bytes dflags)
]
emit $ mkAssign (CmmLocal res_r) base
-- ----------------------------------------------------------------------------
-- Copying byte arrays
-- | Takes a source 'ByteArray#', an offset in the source array, a
-- destination 'MutableByteArray#', an offset into the destination
-- array, and the number of bytes to copy. Copies the given number of
-- bytes from the source array to the destination array.
doCopyByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr
-> FCode ()
doCopyByteArrayOp = emitCopyByteArray copy
where
-- Copy data (we assume the arrays aren't overlapping since
-- they're of different types)
copy _src _dst dst_p src_p bytes =
emitMemcpyCall dst_p src_p bytes 1
-- | Takes a source 'MutableByteArray#', an offset in the source
-- array, a destination 'MutableByteArray#', an offset into the
-- destination array, and the number of bytes to copy. Copies the
-- given number of bytes from the source array to the destination
-- array.
doCopyMutableByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr
-> FCode ()
doCopyMutableByteArrayOp = emitCopyByteArray copy
where
-- The only time the memory might overlap is when the two arrays
-- we were provided are the same array!
-- TODO: Optimize branch for common case of no aliasing.
copy src dst dst_p src_p bytes = do
dflags <- getDynFlags
[moveCall, cpyCall] <- forkAlts [
getCode $ emitMemmoveCall dst_p src_p bytes 1,
getCode $ emitMemcpyCall dst_p src_p bytes 1
]
emit =<< mkCmmIfThenElse (cmmEqWord dflags src dst) moveCall cpyCall
emitCopyByteArray :: (CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr
-> FCode ())
-> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr
-> FCode ()
emitCopyByteArray copy src src_off dst dst_off n = do
dflags <- getDynFlags
dst_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags dst (arrWordsHdrSize dflags)) dst_off
src_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags src (arrWordsHdrSize dflags)) src_off
copy src dst dst_p src_p n
-- | Takes a source 'ByteArray#', an offset in the source array, a
-- destination 'Addr#', and the number of bytes to copy. Copies the given
-- number of bytes from the source array to the destination memory region.
doCopyByteArrayToAddrOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode ()
doCopyByteArrayToAddrOp src src_off dst_p bytes = do
-- Use memcpy (we are allowed to assume the arrays aren't overlapping)
dflags <- getDynFlags
src_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags src (arrWordsHdrSize dflags)) src_off
emitMemcpyCall dst_p src_p bytes 1
-- | Takes a source 'MutableByteArray#', an offset in the source array, a
-- destination 'Addr#', and the number of bytes to copy. Copies the given
-- number of bytes from the source array to the destination memory region.
doCopyMutableByteArrayToAddrOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr
-> FCode ()
doCopyMutableByteArrayToAddrOp = doCopyByteArrayToAddrOp
-- | Takes a source 'Addr#', a destination 'MutableByteArray#', an offset into
-- the destination array, and the number of bytes to copy. Copies the given
-- number of bytes from the source memory region to the destination array.
doCopyAddrToByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> FCode ()
doCopyAddrToByteArrayOp src_p dst dst_off bytes = do
-- Use memcpy (we are allowed to assume the arrays aren't overlapping)
dflags <- getDynFlags
dst_p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags dst (arrWordsHdrSize dflags)) dst_off
emitMemcpyCall dst_p src_p bytes 1
-- ----------------------------------------------------------------------------
-- Setting byte arrays
-- | Takes a 'MutableByteArray#', an offset into the array, a length,
-- and a byte, and sets each of the selected bytes in the array to the
-- character.
doSetByteArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr
-> FCode ()
doSetByteArrayOp ba off len c
= do dflags <- getDynFlags
p <- assignTempE $ cmmOffsetExpr dflags (cmmOffsetB dflags ba (arrWordsHdrSize dflags)) off
emitMemsetCall p c len 1
-- ----------------------------------------------------------------------------
-- Allocating arrays
-- | Allocate a new array.
doNewArrayOp :: CmmFormal -- ^ return register
-> SMRep -- ^ representation of the array
-> CLabel -- ^ info pointer
-> [(CmmExpr, ByteOff)] -- ^ header payload
-> WordOff -- ^ array size
-> CmmExpr -- ^ initial element
-> FCode ()
doNewArrayOp res_r rep info payload n init = do
dflags <- getDynFlags
let info_ptr = mkLblExpr info
tickyAllocPrim (mkIntExpr dflags (hdrSize dflags rep))
(mkIntExpr dflags (nonHdrSize dflags rep))
(zeroExpr dflags)
base <- allocHeapClosure rep info_ptr curCCS payload
arr <- CmmLocal `fmap` newTemp (bWord dflags)
emit $ mkAssign arr base
-- Initialise all elements of the the array
p <- assignTemp $ cmmOffsetB dflags (CmmReg arr) (hdrSize dflags rep)
for <- newLabelC
emitLabel for
let loopBody =
[ mkStore (CmmReg (CmmLocal p)) init
, mkAssign (CmmLocal p) (cmmOffsetW dflags (CmmReg (CmmLocal p)) 1)
, mkBranch for ]
emit =<< mkCmmIfThen
(cmmULtWord dflags (CmmReg (CmmLocal p))
(cmmOffsetW dflags (CmmReg arr)
(hdrSizeW dflags rep + n)))
(catAGraphs loopBody)
emit $ mkAssign (CmmLocal res_r) (CmmReg arr)
-- ----------------------------------------------------------------------------
-- Copying pointer arrays
-- EZY: This code has an unusually high amount of assignTemp calls, seen
-- nowhere else in the code generator. This is mostly because these
-- "primitive" ops result in a surprisingly large amount of code. It
-- will likely be worthwhile to optimize what is emitted here, so that
-- our optimization passes don't waste time repeatedly optimizing the
-- same bits of code.
-- More closely imitates 'assignTemp' from the old code generator, which
-- returns a CmmExpr rather than a LocalReg.
assignTempE :: CmmExpr -> FCode CmmExpr
assignTempE e = do
t <- assignTemp e
return (CmmReg (CmmLocal t))
-- | Takes a source 'Array#', an offset in the source array, a
-- destination 'MutableArray#', an offset into the destination array,
-- and the number of elements to copy. Copies the given number of
-- elements from the source array to the destination array.
doCopyArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff
-> FCode ()
doCopyArrayOp = emitCopyArray copy
where
-- Copy data (we assume the arrays aren't overlapping since
-- they're of different types)
copy _src _dst dst_p src_p bytes =
do dflags <- getDynFlags
emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes)
(wORD_SIZE dflags)
-- | Takes a source 'MutableArray#', an offset in the source array, a
-- destination 'MutableArray#', an offset into the destination array,
-- and the number of elements to copy. Copies the given number of
-- elements from the source array to the destination array.
doCopyMutableArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff
-> FCode ()
doCopyMutableArrayOp = emitCopyArray copy
where
-- The only time the memory might overlap is when the two arrays
-- we were provided are the same array!
-- TODO: Optimize branch for common case of no aliasing.
copy src dst dst_p src_p bytes = do
dflags <- getDynFlags
[moveCall, cpyCall] <- forkAlts [
getCode $ emitMemmoveCall dst_p src_p (mkIntExpr dflags bytes)
(wORD_SIZE dflags),
getCode $ emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes)
(wORD_SIZE dflags)
]
emit =<< mkCmmIfThenElse (cmmEqWord dflags src dst) moveCall cpyCall
emitCopyArray :: (CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> ByteOff
-> FCode ()) -- ^ copy function
-> CmmExpr -- ^ source array
-> CmmExpr -- ^ offset in source array
-> CmmExpr -- ^ destination array
-> CmmExpr -- ^ offset in destination array
-> WordOff -- ^ number of elements to copy
-> FCode ()
emitCopyArray copy src0 src_off dst0 dst_off0 n = do
dflags <- getDynFlags
when (n /= 0) $ do
-- Passed as arguments (be careful)
src <- assignTempE src0
dst <- assignTempE dst0
dst_off <- assignTempE dst_off0
-- Set the dirty bit in the header.
emit (setInfo dst (CmmLit (CmmLabel mkMAP_DIRTY_infoLabel)))
dst_elems_p <- assignTempE $ cmmOffsetB dflags dst
(arrPtrsHdrSize dflags)
dst_p <- assignTempE $ cmmOffsetExprW dflags dst_elems_p dst_off
src_p <- assignTempE $ cmmOffsetExprW dflags
(cmmOffsetB dflags src (arrPtrsHdrSize dflags)) src_off
let bytes = wordsToBytes dflags n
copy src dst dst_p src_p bytes
-- The base address of the destination card table
dst_cards_p <- assignTempE $ cmmOffsetExprW dflags dst_elems_p
(loadArrPtrsSize dflags dst)
emitSetCards dst_off dst_cards_p n
doCopySmallArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff
-> FCode ()
doCopySmallArrayOp = emitCopySmallArray copy
where
-- Copy data (we assume the arrays aren't overlapping since
-- they're of different types)
copy _src _dst dst_p src_p bytes =
do dflags <- getDynFlags
emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes)
(wORD_SIZE dflags)
doCopySmallMutableArrayOp :: CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> WordOff
-> FCode ()
doCopySmallMutableArrayOp = emitCopySmallArray copy
where
-- The only time the memory might overlap is when the two arrays
-- we were provided are the same array!
-- TODO: Optimize branch for common case of no aliasing.
copy src dst dst_p src_p bytes = do
dflags <- getDynFlags
[moveCall, cpyCall] <- forkAlts
[ getCode $ emitMemmoveCall dst_p src_p (mkIntExpr dflags bytes)
(wORD_SIZE dflags)
, getCode $ emitMemcpyCall dst_p src_p (mkIntExpr dflags bytes)
(wORD_SIZE dflags)
]
emit =<< mkCmmIfThenElse (cmmEqWord dflags src dst) moveCall cpyCall
emitCopySmallArray :: (CmmExpr -> CmmExpr -> CmmExpr -> CmmExpr -> ByteOff
-> FCode ()) -- ^ copy function
-> CmmExpr -- ^ source array
-> CmmExpr -- ^ offset in source array
-> CmmExpr -- ^ destination array
-> CmmExpr -- ^ offset in destination array
-> WordOff -- ^ number of elements to copy
-> FCode ()
emitCopySmallArray copy src0 src_off dst0 dst_off n = do
dflags <- getDynFlags
-- Passed as arguments (be careful)
src <- assignTempE src0
dst <- assignTempE dst0
-- Set the dirty bit in the header.
emit (setInfo dst (CmmLit (CmmLabel mkSMAP_DIRTY_infoLabel)))
dst_p <- assignTempE $ cmmOffsetExprW dflags
(cmmOffsetB dflags dst (smallArrPtrsHdrSize dflags)) dst_off
src_p <- assignTempE $ cmmOffsetExprW dflags
(cmmOffsetB dflags src (smallArrPtrsHdrSize dflags)) src_off
let bytes = wordsToBytes dflags n
copy src dst dst_p src_p bytes
-- | Takes an info table label, a register to return the newly
-- allocated array in, a source array, an offset in the source array,
-- and the number of elements to copy. Allocates a new array and
-- initializes it from the source array.
emitCloneArray :: CLabel -> CmmFormal -> CmmExpr -> CmmExpr -> WordOff
-> FCode ()
emitCloneArray info_p res_r src src_off n = do
dflags <- getDynFlags
let info_ptr = mkLblExpr info_p
rep = arrPtrsRep dflags n
tickyAllocPrim (mkIntExpr dflags (arrPtrsHdrSize dflags))
(mkIntExpr dflags (nonHdrSize dflags rep))
(zeroExpr dflags)
let hdr_size = fixedHdrSize dflags
base <- allocHeapClosure rep info_ptr curCCS
[ (mkIntExpr dflags n,
hdr_size + oFFSET_StgMutArrPtrs_ptrs dflags)
, (mkIntExpr dflags (nonHdrSizeW rep),
hdr_size + oFFSET_StgMutArrPtrs_size dflags)
]
arr <- CmmLocal `fmap` newTemp (bWord dflags)
emit $ mkAssign arr base
dst_p <- assignTempE $ cmmOffsetB dflags (CmmReg arr)
(arrPtrsHdrSize dflags)
src_p <- assignTempE $ cmmOffsetExprW dflags src
(cmmAddWord dflags
(mkIntExpr dflags (arrPtrsHdrSizeW dflags)) src_off)
emitMemcpyCall dst_p src_p (mkIntExpr dflags (wordsToBytes dflags n))
(wORD_SIZE dflags)
emit $ mkAssign (CmmLocal res_r) (CmmReg arr)
-- | Takes an info table label, a register to return the newly
-- allocated array in, a source array, an offset in the source array,
-- and the number of elements to copy. Allocates a new array and
-- initializes it from the source array.
emitCloneSmallArray :: CLabel -> CmmFormal -> CmmExpr -> CmmExpr -> WordOff
-> FCode ()
emitCloneSmallArray info_p res_r src src_off n = do
dflags <- getDynFlags
let info_ptr = mkLblExpr info_p
rep = smallArrPtrsRep n
tickyAllocPrim (mkIntExpr dflags (smallArrPtrsHdrSize dflags))
(mkIntExpr dflags (nonHdrSize dflags rep))
(zeroExpr dflags)
let hdr_size = fixedHdrSize dflags
base <- allocHeapClosure rep info_ptr curCCS
[ (mkIntExpr dflags n,
hdr_size + oFFSET_StgSmallMutArrPtrs_ptrs dflags)
]
arr <- CmmLocal `fmap` newTemp (bWord dflags)
emit $ mkAssign arr base
dst_p <- assignTempE $ cmmOffsetB dflags (CmmReg arr)
(smallArrPtrsHdrSize dflags)
src_p <- assignTempE $ cmmOffsetExprW dflags src
(cmmAddWord dflags
(mkIntExpr dflags (smallArrPtrsHdrSizeW dflags)) src_off)
emitMemcpyCall dst_p src_p (mkIntExpr dflags (wordsToBytes dflags n))
(wORD_SIZE dflags)
emit $ mkAssign (CmmLocal res_r) (CmmReg arr)
-- | Takes and offset in the destination array, the base address of
-- the card table, and the number of elements affected (*not* the
-- number of cards). The number of elements may not be zero.
-- Marks the relevant cards as dirty.
emitSetCards :: CmmExpr -> CmmExpr -> WordOff -> FCode ()
emitSetCards dst_start dst_cards_start n = do
dflags <- getDynFlags
start_card <- assignTempE $ cardCmm dflags dst_start
let end_card = cardCmm dflags
(cmmSubWord dflags
(cmmAddWord dflags dst_start (mkIntExpr dflags n))
(mkIntExpr dflags 1))
emitMemsetCall (cmmAddWord dflags dst_cards_start start_card)
(mkIntExpr dflags 1)
(cmmAddWord dflags (cmmSubWord dflags end_card start_card) (mkIntExpr dflags 1))
1 -- no alignment (1 byte)
-- Convert an element index to a card index
cardCmm :: DynFlags -> CmmExpr -> CmmExpr
cardCmm dflags i =
cmmUShrWord dflags i (mkIntExpr dflags (mUT_ARR_PTRS_CARD_BITS dflags))
------------------------------------------------------------------------------
-- SmallArray PrimOp implementations
doReadSmallPtrArrayOp :: LocalReg
-> CmmExpr
-> CmmExpr
-> FCode ()
doReadSmallPtrArrayOp res addr idx = do
dflags <- getDynFlags
mkBasicIndexedRead (smallArrPtrsHdrSize dflags) Nothing (gcWord dflags) res addr
(gcWord dflags) idx
doWriteSmallPtrArrayOp :: CmmExpr
-> CmmExpr
-> CmmExpr
-> FCode ()
doWriteSmallPtrArrayOp addr idx val = do
dflags <- getDynFlags
let ty = cmmExprType dflags val
mkBasicIndexedWrite (smallArrPtrsHdrSize dflags) Nothing addr ty idx val
emit (setInfo addr (CmmLit (CmmLabel mkSMAP_DIRTY_infoLabel)))
------------------------------------------------------------------------------
-- Atomic read-modify-write
-- | Emit an atomic modification to a byte array element. The result
-- reg contains that previous value of the element. Implies a full
-- memory barrier.
doAtomicRMW :: LocalReg -- ^ Result reg
-> AtomicMachOp -- ^ Atomic op (e.g. add)
-> CmmExpr -- ^ MutableByteArray#
-> CmmExpr -- ^ Index
-> CmmType -- ^ Type of element by which we are indexing
-> CmmExpr -- ^ Op argument (e.g. amount to add)
-> FCode ()
doAtomicRMW res amop mba idx idx_ty n = do
dflags <- getDynFlags
let width = typeWidth idx_ty
addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags)
width mba idx
emitPrimCall
[ res ]
(MO_AtomicRMW width amop)
[ addr, n ]
-- | Emit an atomic read to a byte array that acts as a memory barrier.
doAtomicReadByteArray
:: LocalReg -- ^ Result reg
-> CmmExpr -- ^ MutableByteArray#
-> CmmExpr -- ^ Index
-> CmmType -- ^ Type of element by which we are indexing
-> FCode ()
doAtomicReadByteArray res mba idx idx_ty = do
dflags <- getDynFlags
let width = typeWidth idx_ty
addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags)
width mba idx
emitPrimCall
[ res ]
(MO_AtomicRead width)
[ addr ]
-- | Emit an atomic write to a byte array that acts as a memory barrier.
doAtomicWriteByteArray
:: CmmExpr -- ^ MutableByteArray#
-> CmmExpr -- ^ Index
-> CmmType -- ^ Type of element by which we are indexing
-> CmmExpr -- ^ Value to write
-> FCode ()
doAtomicWriteByteArray mba idx idx_ty val = do
dflags <- getDynFlags
let width = typeWidth idx_ty
addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags)
width mba idx
emitPrimCall
[ {- no results -} ]
(MO_AtomicWrite width)
[ addr, val ]
doCasByteArray
:: LocalReg -- ^ Result reg
-> CmmExpr -- ^ MutableByteArray#
-> CmmExpr -- ^ Index
-> CmmType -- ^ Type of element by which we are indexing
-> CmmExpr -- ^ Old value
-> CmmExpr -- ^ New value
-> FCode ()
doCasByteArray res mba idx idx_ty old new = do
dflags <- getDynFlags
let width = (typeWidth idx_ty)
addr = cmmIndexOffExpr dflags (arrWordsHdrSize dflags)
width mba idx
emitPrimCall
[ res ]
(MO_Cmpxchg width)
[ addr, old, new ]
------------------------------------------------------------------------------
-- Helpers for emitting function calls
-- | Emit a call to @memcpy@.
emitMemcpyCall :: CmmExpr -> CmmExpr -> CmmExpr -> Int -> FCode ()
emitMemcpyCall dst src n align = do
emitPrimCall
[ {-no results-} ]
(MO_Memcpy align)
[ dst, src, n ]
-- | Emit a call to @memmove@.
emitMemmoveCall :: CmmExpr -> CmmExpr -> CmmExpr -> Int -> FCode ()
emitMemmoveCall dst src n align = do
emitPrimCall
[ {- no results -} ]
(MO_Memmove align)
[ dst, src, n ]
-- | Emit a call to @memset@. The second argument must fit inside an
-- unsigned char.
emitMemsetCall :: CmmExpr -> CmmExpr -> CmmExpr -> Int -> FCode ()
emitMemsetCall dst c n align = do
emitPrimCall
[ {- no results -} ]
(MO_Memset align)
[ dst, c, n ]
emitBSwapCall :: LocalReg -> CmmExpr -> Width -> FCode ()
emitBSwapCall res x width = do
emitPrimCall
[ res ]
(MO_BSwap width)
[ x ]
emitPopCntCall :: LocalReg -> CmmExpr -> Width -> FCode ()
emitPopCntCall res x width = do
emitPrimCall
[ res ]
(MO_PopCnt width)
[ x ]
emitClzCall :: LocalReg -> CmmExpr -> Width -> FCode ()
emitClzCall res x width = do
emitPrimCall
[ res ]
(MO_Clz width)
[ x ]
emitCtzCall :: LocalReg -> CmmExpr -> Width -> FCode ()
emitCtzCall res x width = do
emitPrimCall
[ res ]
(MO_Ctz width)
[ x ]
| GaloisInc/halvm-ghc | compiler/codeGen/StgCmmPrim.hs | bsd-3-clause | 97,688 | 0 | 19 | 26,089 | 25,127 | 12,567 | 12,560 | -1 | -1 |
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <[email protected]>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
-- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
module Interfaces where
import Common
import Data.List (isPrefixOf)
import Data.Binary
import Rename
import Core
import qualified Syntax
import Decls
import PP
import qualified Core2Kindle
import qualified Kindle
import Termred
import qualified Config
import System.IO
import Codec.Compression.BZip
import qualified Data.ByteString.Lazy
import System.Directory
decodeCFile ti_file = do str <- Data.ByteString.Lazy.readFile ti_file
return(decode(decompress str))
encodeCFile ti_file ifc = Data.ByteString.Lazy.writeFile ti_file (compress(encode ifc))
{-
Reading/writing ti files without compression.
decodeCFile ti_file = decodeFile ti_file
encodeCFile ti_file ifc = encodeFile ti_file ifc
-}
-- Data type of interface file -----------------------------------------------
data IFace = IFace { impsOf :: [(Bool,Name)], -- imported/used modules
defaults :: [Default Scheme], -- exported default declarations
recordEnv :: Map Name [Name], -- exported record types and their selectors,
tsynEnv :: Map Name ([Name],Syntax.Type), -- type synonyms
tEnv :: Types, -- Core type environment
insts :: [Name], -- types for instances
valEnv :: Binds, -- types for exported values (including sels and cons) and some finite eqns
kdeclEnv :: Kindle.Decls -- Kindle form of declarations
}
deriving (Show)
-- Building interface info from data collected during compilation of a module ---------------------------------
{-
Input to ifaceMod is
- from Desugar1: exported record types with their selectors and exported type synomyms.
- from Termred: the entire module in Core form after term reduction
- from Core2Kindle: declarations in Kindle form.
The function checks that the public part is closed (does not mention private data) and computes
the IFace.
-}
ifaceMod :: (Map Name [Name], Map Name ([Name], Syntax.Type)) -> Module -> Kindle.Decls -> IFace
ifaceMod (rs,ss) (Module _ ns xs ds ws bss) kds
| not(null vis2) = errorIds "Private types visible in interface" vis2
| not(null ys) = errorTree "Public default declaration mentions private instance" (head ys)
| otherwise = IFace ns xs' rs ss ds1 ws bs' kds
where Types ke te = ds
Binds r2 ts2 es2 = concatBinds bss
xs' = [d | d@(Default True _ _) <- xs]
ys = [d | d@(Default _ i1 i2) <- xs', isPrivate i1 || isPrivate i2 ]
ds1 = Types (filter exported ke ++ map (\n -> (n,Star)) vis1) (filter exported' te)
bs' = Binds r2 (filter exported ts2) (filter (\ eqn -> fin eqn && exported eqn) (erase es2))
(vis1,vis2) = partition isStateType (nub (localTypes [] (rng (tsigsOf bs'))))
exported (n,_) = isQualified n
exported' p@(n,_) = isQualified n && (not(isAbstract p)) --Constructors/selectors are exported
fin (_,e) = isFinite e && null(filter isPrivate (constrs e))
isPrivate nm@(Name _ _ _ _) = not(isQualified nm)
isPrivate _ = False
isAbstract (_,DData _ _ ((c,_):_)) = isPrivate c
isAbstract (_,DRec _ _ _ ((c,_):_)) = isPrivate c
isAbstract (_,_) = False -- this makes abstract types without selectors/constructors non-private...
-- Building environments in which to compile the current module -----------------------------------------------
{-
Input to initEnvs is a map as built by chaseIFaceFiles;
output is four tuples of data suitable for various compiler passes.
-}
type ImportInfo a = (Bool, a)
type Desugar1Env = (Map Name [Name], Map Name Name, Map Name ([Name], Syntax.Type))
type RenameEnv = (Map Name Name, Map Name Name, Map Name Name)
type CheckEnv = ([Default Scheme], Types, [Name], Binds)
type KindleEnv = Map Name Kindle.Decl
initEnvs :: Map a (ImportInfo IFace) -> M s (Desugar1Env, RenameEnv, CheckEnv, KindleEnv)
initEnvs bms = do ims <- mapM (mkEnv . snd) bms
let (rs,xs,ss,rnL,rnT,rnE,ds,ws,bs,kds)
= foldr mergeMod ([],[],[],[],[],[],Types [] [],[],Binds False [] [],[]) ims
return ((rs,rnL,ss),(rnL,rnT,rnE),(xs,ds,ws,bs),kds)
where mergeMod (rs1,xs1,ss1,rnL1,rnT1,rnE1,ds1,ws1,bs1,kds1)
(rs2,xs2,ss2,rnL2,rnT2,rnE2,ds2,ws2,bs2,kds2)
= (rs1 ++ rs2, xs1 ++ xs2, ss1 ++ ss2, mergeRenamings2 rnL1 rnL2,
mergeRenamings2 rnT1 rnT2, mergeRenamings2 rnE1 rnE2,
catDecls ds1 ds2, ws1++ws2, catBinds bs1 bs2,
kds1 ++ kds2)
mkEnv (unQual,IFace ns xs rs ss ds ws bs kds)
= do ks <- renaming (dom ke)
ts <- renaming (dom te'')
ls' <- renaming ls -- (concatMap snd rs)
return (unMod unQual rs, xs, unMod unQual ss, unMod unQual ls',unMod unQual ks,
unMod unQual ts,ds,ws,Binds r te' es,kds)
where Types ke ds' = ds
Binds r te es = bs
te' = te ++ concatMap (tenvSelCon ke) ds'
te'' = te ++ concatMap (tenvCon ke) ds'
ls = [ s | (_,DRec _ _ _ cs) <- ds', (s,_) <- cs, not (isGenerated s) ]
unMod b ps = if b then [(tag0 (dropMod c),y) | (c,y) <- ps] ++ ps else ps
-- Checking that public part is closed ---------------------------------------------------------
class LocalTypes a where
localTypes :: [Name] -> a -> [Name]
instance LocalTypes a => LocalTypes [a] where
localTypes ns ds = concatMap (localTypes ns) ds
instance LocalTypes b => LocalTypes (a,b) where
localTypes ns (a,b) = localTypes ns b
instance LocalTypes Scheme where
localTypes ns (Scheme r ps ke) = localTypes ns1 r ++ localTypes ns1 ps
where ns1 = ns ++ dom ke
instance LocalTypes Rho where
localTypes ns (R t) = localTypes ns t
localTypes ns (F ss r) = localTypes ns ss ++ localTypes ns r
instance LocalTypes Type where
localTypes ns (TId n)
| n `elem` ns || not (isPrivate n) = []
| otherwise = [n]
localTypes _ (TVar t) = internalError0 ("Interfaces.localTypes: TVar in interface file")
localTypes ns (TFun ts t) = localTypes ns (t : ts)
localTypes ns (TAp t1 t2) = localTypes ns [t1, t2]
instance LocalTypes Decl where
localTypes ns (DData vs ps cs) = localTypes ns1 ps ++ localTypes ns1 cs
where ns1 = ns ++ vs
localTypes ns (DRec _ vs ps ss) = localTypes ns1 ps ++ localTypes ns1 ss
where ns1 = ns ++ vs
localTypes ns (DType vs t) = localTypes (ns ++ vs) t
instance LocalTypes Constr where
localTypes ns (Constr ts ps ke) = localTypes ns1 ts ++ localTypes ns1 ps
where ns1 = ns ++ dom ke
-- Binary -------------------------------------------------------------------------------
instance Binary IFace where
put (IFace a b c d e f g h) = put a >> put b >> put c >> put d >> put e >> put f >> put g >> put h
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> get >>= \f ->
get >>= \g -> get >>= \h -> return (IFace a b c d e f g h)
-- Printing -----------------------------------------------------------------------------
instance Pr IFace where
pr (IFace ns xs rs ss ds1 ws bs kds) =
text "Imported/used modules: " <+> prImports ns $$
text "Default declarations: " <+> hpr ',' xs $$
text ("Record types and their selectors: "++show rs) $$
text "Type synonyms: " <+> hsep (map (prId . fst) ss) $$
text "\nType definitions\n----------------" $$ pr ds1 $$
text "\nTop level bindings\n------------------" $$ pr (simpVars bs) $$
text "\nKindle declarations\n-------------------" $$ vcat (map pr kds)
-- prPair (n,t) = prId n <+> text "::" <+> pr t
where simpVars (Binds rec te eqns) = Binds rec (map sV te) eqns
sV (n,t@(Scheme rh ps ke)) = case zip (filter isTypevar (idents (Scheme rh ps []))) abcSupply of
[] -> (n,t)
s -> (n,subst s t)
where isTypevar n = isGenerated n && not (isStateType n)
listIface clo f = do (ifc,f) <- decodeModule clo f
--writeAPI f ifc
let modul = rmSuffix ".ti" f
htmlfile = modul++".html"
res <- checkUpToDate f htmlfile
if not res then do
writeAPI modul ifc
system (Config.pager clo ++" " ++ htmlfile)
else system (Config.pager clo ++" " ++ htmlfile)
where checkUpToDate tiFile htmlFile = do html_exists <- Directory.doesFileExist htmlFile
if not html_exists then
return False
else do
ti_time <- Directory.getModificationTime tiFile
html_time <- Directory.getModificationTime htmlFile
return (ti_time <= html_time)
writeAPI modul ifc = writeFile (modul ++ ".html") (render(toHTML modul (ifc :: IFace)))
toHTML n (IFace ns xs rs ss ds ws bs _) = text "<html><body>\n" $$
text ("<h2>API for module "++n++"</h2>\n") $$
section ns "Imported modules" prImports $$
section xs "Default declarations" (hpr ',') $$
section ke' "Kind declarations" (pr . flip Types []) $$
section ds' "Type declarations" (pr . Types [] . map addSubs) $$
section te' "Toplevel declarations" (prTop . stripTopdecls) $$
text "</html>"
where section xs header f = if null xs
then empty
else text ("<h4>"++header++"</h4>\n<pre>") $$ f xs $$ text "</pre>"
Types ke ds' = ds
ke' = [(n,k) | (n,k) <- ke, notElem n (dom ds')]
Binds _ te _ = bs
addSubs (n,DData vs _ cs) = (n,DData vs (map (\(_,Constr (s:_) _ _) -> s) cs1) cs2)
where (cs1,cs2) = partition (isGenerated . fst) cs
addSubs (n,DRec b vs _ ss) = (n,DRec b vs (map snd ss1) ss2)
where (ss1, ss2) = partition (isGenerated . fst) (map stripStar ss)
addSubs d = d
stripStar (n,Scheme rh ps ke) = (n,Scheme rh ps (filter (( /= Star) . snd) ke))
te' = map (sV . stripStar) (filter (not . isGenerated . fst) te)
stripTopdecls te = bs1 ++ bs2
where (bs1,bs2) = partition (flip elem ws . fst ) te
decodeModule clo f = (do ifc <- decodeCFile f
putStrLn ("[reading " ++ show f ++ "]")
return (ifc,f)) `catch` (\e -> do let libf = Config.libDir clo ++ "/" ++ f
ifc <- decodeCFile libf
putStrLn ("[reading " ++ show libf ++ "]")
return (ifc,libf))
| UBMLtonGroup/timberc | src/Interfaces.hs | bsd-3-clause | 14,852 | 0 | 24 | 5,842 | 3,789 | 1,983 | 1,806 | 168 | 4 |
{-# LANGUAGE PatternGuards #-}
module System.Console.CmdArgs.Implicit.Reader(Reader(..), reader) where
import Data.Generics.Any
import qualified Data.Generics.Any.Prelude as A
import System.Console.CmdArgs.Explicit
import Data.Char
import Data.Int
import Data.Word
import Data.List
import Data.Maybe
data Reader = Reader
{readerHelp :: String
,readerBool :: Bool
,readerParts :: Int
,readerFixup :: Any -> Any -- If a list, then 'reverse', otherwise nothing, so we can build up using cons in O(n)
,readerRead :: Any -> String -> Either String Any
}
-- reader has an actual value of type Any that can be inspected
-- reader_ has a value of type _|_ instead
readerRead_ r = readerRead r $ error "Invariant broken: reader/reader_"
reader :: Any -> Maybe Reader
reader x | A.isList x && not (A.isString x) = do
r <- reader_ $ A.fromList x
return r{readerRead = \o s -> fmap (`A.cons` o) $ readerRead_ r s, readerFixup = A.reverse}
reader x | isAlgType x, [ctor] <- ctors x, [child] <- children x = do
-- newtype wrapper, just forward it
r <- reader child
let down = head . children
let up o c = recompose o [c]
return r{readerFixup = \x -> up x $ readerFixup r $ down x
,readerRead = \x -> either Left (Right . up x) . readerRead r (down x)
}
reader x = reader_ x
reader_ :: Any -> Maybe Reader
reader_ x | A.isString x = Just $ Reader "ITEM" False 1 id $ const $ Right . Any
reader_ x | typeName x == "Bool" = Just $ Reader "BOOL" True 1 id $ const $ \s ->
maybe (Left $ "Could not read as boolean, " ++ show s) (Right . Any) $ parseBool s
reader_ x | res:_ <- catMaybes
[f "INT" (0::Integer), f "NUM" (0::Float), f "NUM" (0::Double)
,f "INT" (0::Int), f "INT" (0::Int8), f "INT" (0::Int16), f "INT" (0::Int32), f "INT" (0::Int64)
,f "NAT" (0::Word), f "NAT" (0::Word8), f "NAT" (0::Word16), f "NAT" (0::Word32), f "NAT" (0::Word64)
] = Just res
where
ty = typeOf x
f hlp t | typeOf (Any t) /= ty = Nothing
| otherwise = Just $ Reader hlp False 1 id $ const $ \s -> case reads s of
[(x,"")] -> Right $ Any $ x `asTypeOf` t
_ -> Left $ "Could not read as type " ++ show (typeOf $ Any t) ++ ", " ++ show s
reader_ x | A.isList x = do
r <- reader_ $ A.fromList x
return $ r{readerRead = const $ fmap (A.list_ x) . readerRead_ r}
reader_ x | A.isMaybe x = do
r <- reader_ $ A.fromMaybe x
return $ r{readerRead = const $ fmap (A.just_ x) . readerRead_ r}
reader_ x | isAlgType x && length xs > 1 && all ((==) 0 . arity . snd) xs
= Just $ Reader (map toUpper $ typeShell x) (typeName x == "Bool") 1 id $ const $ rd . map toLower
where
xs = [(map toLower c, compose0 x c) | c <- ctors x]
rd s | null ys = Left $ "Could not read " ++ show s ++ ", expected one of: " ++ unwords (map fst xs)
| Just (_,x) <- find ((==) s . fst) ys = Right x
| length ys > 1 = Left $ "Ambiguous read for " ++ show s ++ ", could be any of: " ++ unwords (map fst ys)
| otherwise = Right $ snd $ head ys
where ys = filter (isPrefixOf s . fst) xs
reader_ x | isAlgType x, [c] <- ctors x, x <- compose0 x c = do
let cs = children x
rs <- mapM reader_ cs
let n = sum $ map readerParts rs
return $ Reader (uncommas $ map readerHelp rs) (map readerBool rs == [True]) n id $ const $ \s ->
let ss = commas s in
if n == 1 then fmap (recompose x . return) $ readerRead_ (head $ filter ((==) 1 . readerParts) rs) s
else if length ss /= n then Left "Incorrect number of commas for fields"
else fmap (recompose x) $ sequenceEither $ zipWith readerRead_ rs $ map uncommas $ takes (map readerParts rs) ss
reader_ _ = Nothing
uncommas = intercalate ","
commas = lines . map (\x -> if x == ',' then '\n' else x)
takes [] _ = []
takes (i:is) xs = a : takes is b
where (a,b) = splitAt i xs
sequenceEither = foldr f (Right [])
where f (Left x) _ = Left x
f _ (Left x) = Left x
f (Right x) (Right xs) = Right (x:xs)
| ndmitchell/cmdargs | System/Console/CmdArgs/Implicit/Reader.hs | bsd-3-clause | 4,114 | 0 | 20 | 1,121 | 1,868 | 934 | 934 | 75 | 4 |
module Pad where
import Graphics.UI.GLUT hiding (Red, Green, Blue, rotate)
import Data.Bits ((.|.), (.&.), complement)
--------------------------------
-- Pad
padU,padL,padR,padD,padA,padB,padAll :: Int
padU = 1
padL = 2
padR = 4
padD = 8
padA = 16
padB = 32
padAll = padU .|. padL .|. padR .|. padD .|. padA .|. padB
data Pad = Pad {
pressed :: [Key], -- 現在押されてるキー
btn :: Int, -- 押されてるボタン
obtn :: Int, -- 前回押されてたボタン
trig :: Int, -- 押された瞬間のボタン
rpt :: Int, -- 押され続けてるボタン
rptc :: Int -- リピート用カウンタ
}
newPad :: Pad
newPad = Pad {
pressed = [],
btn = 0,
obtn = 0,
trig = 0,
rpt = 0,
rptc = 0
}
calcPadState :: [Key] -> Int
calcPadState keys = foldl (\r x -> r .|. btnValue x) 0 keys
where
btnValue :: Key -> Int
btnValue (Char 'i') = padU
btnValue (Char 'j') = padL
btnValue (Char 'k') = padD
btnValue (Char 'l') = padR
btnValue (Char ' ') = padA
btnValue (Char 'z') = padB
btnValue (SpecialKey KeyUp) = padU
btnValue (SpecialKey KeyLeft) = padL
btnValue (SpecialKey KeyRight) = padR
btnValue (SpecialKey KeyDown) = padD
btnValue _ = 0
repeatCnt1, repeatCnt2, repeatBtn :: Int
repeatCnt1 = 7 -- リピート初回の時間
repeatCnt2 = 1 -- リピート2回目以降の時間
repeatBtn = padL .|. padR -- リピートで使うボタン
updatePad :: Pad -> Pad
updatePad pad =
pad { btn = btn', obtn = obtn', trig = trg', rpt = rpt', rptc = rptc' }
where
btn' = calcPadState (pressed pad)
obtn' = btn pad
trg' = btn' .&. complement obtn'
tmprptc
| (btn' .&. repeatBtn) /= (obtn' .&. repeatBtn) = 0
| otherwise = rptc pad + 1
bRepeat = tmprptc >= repeatCnt1
rptc'
| bRepeat = repeatCnt1 - repeatCnt2
| otherwise = tmprptc
rpt'
| bRepeat = btn'
| otherwise = trg'
| mokehehe/htetris | Pad.hs | bsd-3-clause | 1,871 | 88 | 12 | 401 | 728 | 411 | 317 | 60 | 11 |
{-# LANGUAGE FlexibleContexts #-}
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module Feldspar.Algorithm.FFT
( fft
, ifft
)
where
import qualified Prelude as P
import Feldspar
import Feldspar.Vector hiding (riffle)
-- | Radix-2 Decimation-In-Frequeny Fast Fourier Transformation of the given complex vector
-- The given vector must be power-of-two sized, (for example 2, 4, 8, 16, 32, etc.)
fft :: Pull1 (Complex Float) -> Pull1 (Complex Float)
fft v = bitRev steps $ fftCore steps v
where steps = ilog2 (length v) - 1
-- | Radix-2 Decimation-In-Frequeny Inverse Fast Fourier Transformation of the given complex vector
-- The given vector must be power-of-two sized, (for example 2, 4, 8, 16, 32, etc.)
ifft :: Pull1 (Complex Float) -> Pull1 (Complex Float)
ifft v = bitRev steps $ ifftCore steps v
where steps = ilog2 (length v) - 1
fftCore :: Data Index -> Pull1 (Complex Float) -> Pull1 (Complex Float)
fftCore n = composeOn stage (reverse (0...n))
where
stage k vec = indexed1 (length vec) ixf
where
ixf i = condition (testBit i k) (twid * (b - a)) (a+b)
where
a = vec !! i
b = vec !! (i `xor` k2)
twid = cis (-pi * i2f (lsbs k i) / i2f k2)
k2 = 1 .<<. k
ifftCore :: Data Index -> Pull1 (Complex Float) -> Pull1 (Complex Float)
ifftCore n = map (/ complex (i2f (2^(n+1))) 0) . composeOn stage (reverse (0...n))
where
stage k vec = indexed1 (length vec) ixf
where
ixf i = condition (testBit i k) (twid * (b - a)) (a+b)
where
a = vec !! i
b = vec !! (i `xor` k2)
twid = cis (pi * i2f (lsbs k i) / i2f k2)
k2 = 1 .<<. k
bitRev :: Type a => Data Index -> Pull1 a -> Pull1 a
bitRev n = composeOn riffle (1...n)
riffle :: Syntax a => Data Index -> Pull DIM1 a -> Pull DIM1 a
riffle k = permute (const $ rotBit k)
-- Helper functions
composeOn :: (Syntax a) => (b -> a -> a) -> Pull DIM1 b -> a -> a
composeOn f v i = fromZero $ fold (flip f) i v
rotBit :: Data Index -> Data Index -> Data Index
rotBit 0 _ = P.error "rotBit: k should be at least 1"
rotBit k i = lefts .|. rights
where
ir = i .>>. 1
rights = ir .&. oneBits k
lefts = (((ir .>>. k) .<<. 1) .|. (i .&. 1)) .<<. k
| emwap/feldspar-language | src/Feldspar/Algorithm/FFT.hs | bsd-3-clause | 3,858 | 0 | 17 | 936 | 925 | 486 | 439 | 41 | 1 |
{-# OPTIONS -#include "autoPrim.h" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Win32.Com.Automation
-- Copyright : (c) Daan Leijen <[email protected]>, Sigbjorn Finne <[email protected]> 1998-99, Sigbjorn Finne <[email protected]> 2000-2009
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- Accessing COM / OLE Automation objects from Haskell clients. This library
-- provides a fairly high-level view of Automation objects and the data values
-- that their methods support. Transparent marshalling of arguments and invocation
-- over Automation objects is supported via the 'Variant' class and a family
-- of @invoke@ methods. This is also extended to cover the properties/fields of
-- such objects.
--
-----------------------------------------------------------------------------
module System.Win32.Com.Automation (
module System.Win32.Com,
IDispatch_, IDispatch, iidIDispatch,
queryIUnknown, queryIDispatch,
createObject, getObject, getActiveObject, getFileObject,
Member, DISPID, getMemberID, VARIANT, sizeofVARIANT,
marshallVARIANT, unmarshallVARIANT, readVARIANT, writeVARIANT,
copyVARIANT, allocVARIANT,
VarIn, VarRes, ArgIn, ArgInOut, ArgOut, ArgRes,
Variant(..), inoutVariant, outVariant,
defaultEmpty, inEmpty, resEmpty, inoutEmpty, outEmpty, inNoArg,
defaultInt, inInt, resInt, inoutInt, outInt,
defaultInt8, inInt8, resInt8, inoutInt8, outInt8,
defaultInt16, inInt16, resInt16, inoutInt16, outInt16,
defaultInt32, inInt32, resInt32, inoutInt32, outInt32,
defaultInt64, inInt64, resInt64, inoutInt64, outInt64,
defaultInteger, inInteger, resInteger, inoutInteger, outInteger,
defaultHRESULT, inHRESULT, resHRESULT, inoutHRESULT, outHRESULT,
defaultWord, inWord, resWord, inoutWord, outWord,
defaultWord8, inWord8, resWord8, inoutWord8, outWord8,
defaultWord16, inWord16, resWord16, inoutWord16, outWord16,
defaultWord32, inWord32, resWord32, inoutWord32, outWord32,
defaultWord64, inWord64, resWord64, inoutWord64, outWord64,
defaultBool, inBool, resBool, inoutBool, outBool,
defaultByte, inByte, resByte, inoutByte, outByte,
defaultChar, inChar, resChar, inoutChar, outChar,
defaultFloat, inFloat, resFloat, inoutFloat, outFloat,
defaultDouble, inDouble, resDouble, inoutDouble, outDouble,
defaultString, inString, resString, inoutString, outString,
defaultIUnknown, inIUnknown, resIUnknown, inoutIUnknown, outIUnknown,
defaultIDispatch, inIDispatch, resIDispatch, inoutIDispatch, outIDispatch,
defaultDate, inDate, resDate, inoutDate, outDate, Date,
defaultError, inError, resError, inoutError, outError,
defaultMaybe, inMaybe, resMaybe, inoutMaybe, outMaybe, inOptional,
defaultCurrency, inCurrency, resCurrency, inoutCurrency, outCurrency, Currency,
defaultSafeArray, inSafeArray, resSafeArray, inoutSafeArray, outSafeArray, SafeArray, mkSafeArray,
defaultEnum, inEnum, resEnum, inoutEnum, outEnum, vtTypeEnum,
inHaskellValue, unsafeResHaskellValue, unsafeOutHaskellValue,
defaultSqlNull, inSqlNull, resSqlNull, inoutSqlNull, outSqlNull,
SqlNull(..),
inGUID, outGUID,
inDefaultValue, noInArg,
propertyGet, propertySet, propertySetGet,
propertyGet2, propertyGet3, propertyGet4,
propertyGetID, propertySetID, propertySetGetID,
propertyGet2ID, propertyGet3ID, propertyGet4ID,
function1, function2, function3, function4, function5, function6,
functionID1, functionID2, functionID3, functionID4, functionID5, functionID6,
method0, method1, method2, method3, method4, method5, method6, method7, method8,
methodID0, methodID1, methodID2, methodID3, methodID4,
methodID5, methodID6, methodID7, methodID8,
unmarshallVariants0, unmarshallVariants1,
unmarshallVariants2, unmarshallVariants3,
unmarshallVariants4, unmarshallVariants5,
unmarshallVariants6, unmarshallVariants7,
unmarshallVariants8,
readVariants0, readVariants1,
readVariants2, readVariants3,
readVariants4, readVariants5,
readVariants6, readVariants7,
readVariants8,
method_0_0, method_1_0, method_2_0, method_3_0, method_4_0,
method_0_1, method_1_1, method_2_1, method_3_1, method_4_1,
method_0_2, method_1_2, method_2_2, method_3_2, method_4_2,
function_0_1, function_1_1, function_2_1, function_3_1, function_4_1,
function_0_2, function_1_2, function_2_2, function_3_2, function_4_2,
propertyGet_0, propertyGet_1, propertyGet_2, propertyGet_3, propertyGet_4,
propertySet_1, propertySet_2, propertySet_3, propertySet_4,
invokePropertyGet, invokePropertySet,
invokeMethod, invokeFunction,
enumVariants,
marshallCurrency, unmarshallCurrency,
readCurrency, writeCurrency,
sizeofCurrency,
VARENUM(..),
marshallVARENUM, unmarshallVARENUM,
readVARENUM, writeVARENUM,
sizeofVARENUM,
sizeofVARIANT_BOOL,
marshallVARIANT_BOOL, unmarshallVARIANT_BOOL,
readVARIANT_BOOL, writeVARIANT_BOOL,
vARIANT_TRUE, vARIANT_FALSE,
marshallVariant, unmarshallVariant,
readVariant, writeVariant,
readVarEnum,
readVarInt,
readVarFloat,
readVarDouble,
readVarString,
readVarBool
, marshallSafeArray
, unmarshallSafeArray
, writeSafeArray
, readSafeArray
, freeSafeArray
, readSA
, clockTimeToDate -- :: Time.ClockTime -> IO Date
) where
import System.Win32.Com.HDirect.HDirect as HDirect
import System.IO.Error ( ioeGetErrorString )
import System.Time ( ClockTime(..) )
import Data.Word ( Word8, Word16, Word32 )
import Data.Int ( Int32, Int16, Int8, Int64 )
import System.Win32.Com
import System.Win32.Com.Base ( stringToBSTR )
import System.Win32.Com.Exception ( dISP_E_UNKNOWNNAME, dISP_E_EXCEPTION )
import System.Win32.Com.Automation.Base
import System.Win32.Com.Automation.SafeArray ( addrToSAFEARRAY, marshallSAFEARRAY, readSAFEARRAY
, writeSAFEARRAY, unmarshallSAFEARRAY, SAFEARRAY
)
import System.Win32.Com.HDirect.WideString
import System.Win32.Com.HDirect.Pointer ( writeSeqAtDec, stackFrame, allocMemory, freeMemory )
import Foreign.Ptr
import Foreign.ForeignPtr ( ForeignPtr )
import Foreign.StablePtr ( newStablePtr )
import System.IO.Unsafe ( unsafePerformIO )
import Data.Bits
import System.IO ( hPutStrLn, stderr )
-- | @createObject progid@ is the Haskell equivalent of
-- VB's @CreateObject@, trying to instantiate a new
-- Automation object via an 'IDispatch' interfac pointer.
createObject :: ProgID -> IO (IDispatch a)
createObject progid
= coCreateObject progid iidIDispatch_unsafe
-- Notice the `unsafe' interface pointer return types used here. The
-- interface pointers returned are compatible with the stubs for
-- *any* IDispatch-derived interface. This makes it more convenient
-- (saves the extra QI / type cast), but means that it is now
-- possible to get run-time errors of the sort:
-- 'method X called but not supported'.
iidIDispatch_unsafe = mkIID "{00020400-0000-0000-C000-000000000046}"
getFileObject :: String -> ProgID -> IO (IDispatch a)
getFileObject fname progid = coGetFileObject fname progid iidIDispatch_unsafe
getActiveObject :: ProgID -> IO (IDispatch a)
getActiveObject progid
= coGetActiveObject progid iidIDispatch_unsafe
getObject :: String -> IO (IDispatch a)
getObject fname = coGetObject fname iidIDispatch_unsafe
{-
The following functions are overloaded versions of the basic functions.
The postfix "_n_m" means n input arguments and m results.
-}
method_0_0 name = method0 name []
method_1_0 name a1 = method0 name [inVariant a1]
method_2_0 name a1 a2 = method0 name [inVariant a1, inVariant a2]
method_3_0 name a1 a2 a3 = method0 name [inVariant a1, inVariant a2, inVariant a3]
method_4_0 name a1 a2 a3 a4 = method0 name [inVariant a1, inVariant a2,
inVariant a3, inVariant a4]
method_0_1 name = method1 name [] outVariant
method_1_1 name a1 = method1 name [inVariant a1] outVariant
method_2_1 name a1 a2 = method1 name [inVariant a1, inVariant a2] outVariant
method_3_1 name a1 a2 a3 = method1 name [inVariant a1, inVariant a2,
inVariant a3] outVariant
method_4_1 name a1 a2 a3 a4 = method1 name [inVariant a1, inVariant a2,
inVariant a3, inVariant a4] outVariant
method_0_2 name = method2 name [] outVariant outVariant
method_1_2 name a1 = method2 name [inVariant a1] outVariant outVariant
method_2_2 name a1 a2 = method2 name [inVariant a1, inVariant a2] outVariant outVariant
method_3_2 name a1 a2 a3 = method2 name [inVariant a1, inVariant a2,
inVariant a3] outVariant outVariant
method_4_2 name a1 a2 a3 a4 = method2 name [inVariant a1, inVariant a2,
inVariant a3, inVariant a4] outVariant outVariant
function_0_1 name = function1 name [] outVariant
function_1_1 name a1 = function1 name [inVariant a1] outVariant
function_2_1 name a1 a2 = function1 name [inVariant a1, inVariant a2] outVariant
function_3_1 name a1 a2 a3 = function1 name [inVariant a1, inVariant a2,
inVariant a3] outVariant
function_4_1 name a1 a2 a3 a4 = function1 name [inVariant a1, inVariant a2,
inVariant a3, inVariant a4] outVariant
function_0_2 name = function2 name [] outVariant outVariant
function_1_2 name a1 = function2 name [inVariant a1] outVariant outVariant
function_2_2 name a1 a2 = function2 name [inVariant a1, inVariant a2]
outVariant outVariant
function_3_2 name a1 a2 a3 = function2 name [inVariant a1, inVariant a2,
inVariant a3] outVariant outVariant
function_4_2 name a1 a2 a3 a4 = function2 name [inVariant a1, inVariant a2,
inVariant a3, inVariant a4]
outVariant outVariant
propertyGet_0 name = propertyGet name [] outVariant
propertyGet_1 name a1 = propertyGet name [inVariant a1] outVariant
propertyGet_2 name a1 a2 = propertyGet name [inVariant a1, inVariant a2] outVariant
propertyGet_3 name a1 a2 a3 = propertyGet name [inVariant a1, inVariant a2,
inVariant a3] outVariant
propertyGet_4 name a1 a2 a3 a4 = propertyGet name [inVariant a1, inVariant a2,
inVariant a3, inVariant a4] outVariant
propertySet_1 name a1 = propertySet name [inVariant a1]
propertySet_2 name a1 a2 = propertySet name [inVariant a1, inVariant a2]
propertySet_3 name a1 a2 a3 = propertySet name [inVariant a1, inVariant a2, inVariant a3]
propertySet_4 name a1 a2 a3 a4 = propertySet name [inVariant a1, inVariant a2,
inVariant a3, inVariant a4]
-- | Automation 'Member' functions or properties are identified
-- by either name or 'DISPID'. The latter saving you from having
-- to do a method name resolution for each invocation.
type Member = String
-- type DISPID = Int
sizeDISPID = 4
-- | @getMemberID memberName obj@ translates the @memberName@ string
-- into the unique 'DISPID' representing that method/property. If unknown,
-- a COM exception is raised.
getMemberID :: Member -> IDispatch a -> IO DISPID
getMemberID name obj = do
bstr <- allocBSTR name
(dispid,hr) <- dispatchGetMemberID (castIface obj) bstr lcidNeutral
`always` freeBSTR bstr
checkHR hr `catchComException` (handleErr hr)
return dispid
where
handleErr hr err
| hr == dISP_E_UNKNOWNNAME = coFail ("method '" ++ name ++ "' called but not supported by object")
| otherwise = errorMember name err
{-
Type definitions for the marshalling functions. Variants are represented
as functions that can read or write a value from or to a variant structure.
-}
-- | @VarIn@ is the marshaller for 'Variant' arguments; a function that
-- takes (a pointer to) a VARIANT structure and fills it in with value
-- it encodes.
type VarIn = VARIANT -> IO ()
-- | @VarRes@ is the unmarshaller for 'Variant results; a function that
-- takes (a pointer to) the VARIANT result and unscrambles its contents
-- into the Haskell value representing that 'Variant' result.
type VarRes a = VARIANT -> IO a
-- | @ArgIn@ is the extension of 'VarIn', returning a 'VarIn' marshaller
-- for some 'Variant'-supported value of type @a@.
type ArgIn a = a -> VarIn
-- | @ArgRes@ is the 'Variant' unmarshaller for results of type @a@, where
-- is one of the 'Variant' supported types.
type ArgRes a = VarRes a
-- | @ArgOut a@ represent an @in-out@ Automation parameter, pairing a marshaller
-- with an unmarshaller for some type. Notice that the input value being marshalled
-- may not have the same type as the output/result value being unmarshalled.
type ArgOut a = (VarIn,ArgRes a)
-- | @ArgInOut a b@ is the general 'in-out' parameter marshaller and result
-- unmarshaller.
type ArgInOut a b = a -> ArgOut b
{-
For each type we define 5 functions; @defaultT@, @inT@,
@resT@, @inoutT@, @outT@ where the last
two functions are defined in terms of the first three.
The @Variant@ class overloads these functions; if an
argument can be more than one type, it will be overloaded
and Haskell takes care of resolving the marshall function to use.
We enable overlapping instance by providing explicit constructor functions
in the class definition.
-}
--Input variants.
class Variant a where
inVariant :: ArgIn a
inVarList :: ArgIn [a]
inVarIUnknown :: ArgIn (IUnknown a)
vtEltType :: a -> VARENUM
resVariant :: ArgRes a
defaultVariant :: a
resVarList :: ArgRes [a]
resVarIUnknown :: ArgRes (IUnknown a)
resVarIDispatch :: ArgRes (IDispatch a)
--Overlapping instance for strings.
instance Variant a => Variant [a] where
inVariant = inVarList
resVariant = resVarList
defaultVariant = []
instance Variant Char where
inVariant = inChar
resVariant = resChar
inVarList = inString
resVarList = resString
vtEltType _ = VT_UI1
-- Overlapping instance for @IDispatch a@ and @IUnknown ()@ variants.
instance Variant a => Variant (IUnknown_ a) where
inVariant = inVarIUnknown
resVariant = resVarIUnknown
defaultVariant = defaultIUnknown
vtEltType _ = VT_UNKNOWN
instance Variant (IDispatch_ a) where
inVarIUnknown = inIDispatch
resVarIUnknown = resIDispatch
vtEltType _ = VT_DISPATCH
instance Variant () where
inVarIUnknown = inIUnknown
resVarIUnknown = resIUnknown
resVarIDispatch = resIDispatch
inVariant = inNoArg
resVariant = resEmpty
defaultVariant = defaultEmpty
vtEltType _ = VT_ERROR
--Normal instances.
instance Variant Bool where
inVariant = inBool
resVariant = resBool
defaultVariant = defaultBool
vtEltType _ = VT_UI4
instance Variant Int where
inVariant = inInt
resVariant = resInt
defaultVariant = defaultInt
vtEltType _ = VT_I4
instance Variant Int32 where
inVariant = inHRESULT
resVariant = resHRESULT
defaultVariant = defaultHRESULT
vtEltType _ = VT_I4
instance Variant Int16 where
inVariant = inInt16
resVariant = resInt16
defaultVariant = defaultInt16
vtEltType _ = VT_I2
instance Variant Int8 where
inVariant = inInt8
resVariant = resInt8
defaultVariant = defaultInt8
vtEltType _ = VT_I1
instance Variant Int64 where
inVariant = inInt64
resVariant = resInt64
defaultVariant = defaultInt64
vtEltType _ = VT_CY -- since VT_I8 isn't supported in VARIANTs.
instance Variant Word8 where
inVariant = inWord8
resVariant = resWord8
defaultVariant = defaultWord8
vtEltType _ = VT_UI1
instance Variant Word16 where
inVariant = inWord16
resVariant = resWord16
defaultVariant = defaultWord16
vtEltType _ = VT_UI2
instance Variant Word32 where
inVariant = inWord32
resVariant = resWord32
defaultVariant = defaultWord32
vtEltType _ = VT_UI4
instance Variant Word64 where
inVariant = inWord64
resVariant = resWord64
defaultVariant = defaultWord64
vtEltType _ = VT_DECIMAL -- since VT_UI8 isn't supported in VARIANTs.
instance Variant Float where
inVariant = inFloat
resVariant = resFloat
defaultVariant = defaultFloat
vtEltType _ = VT_R4
instance Variant Double where
inVariant = inDouble
resVariant = resDouble
defaultVariant = defaultDouble
vtEltType _ = VT_R8
instance (Variant a) => Variant (Maybe a) where
inVariant = inMaybe
resVariant = resMaybe
defaultVariant = defaultMaybe
vtEltType mbx = vtEltType (f mbx)
where
f :: Maybe a -> a
f = undefined
instance Variant (Ptr a) where
inVariant = \ p y -> copyVARIANT y (castPtr p)
resVariant = \ p -> return (castPtr p)
defaultVariant = nullPtr
--Marshallers derived from instance methods:
inoutVariant :: (Variant a, Variant b) => ArgInOut a b
inoutVariant x = (inVariant x,resVariant)
inoutVariant' :: (Variant a) => ArgInOut a a
inoutVariant' = inoutVariant
outVariant :: (Variant a) => ArgOut a
outVariant = (inoutVariant' defaultVariant)
inDefaultValue :: VarIn -> ArgIn a -> ArgIn a
inDefaultValue varin_def argin = \ val var -> do
argin val var
vt <- readVarEnum var
case vt of -- to avoid having to define Eq..
VT_ERROR -> do
primVARIANTClear var
varin_def var
_ -> return ()
defaultMaybe :: Variant a => Maybe a
defaultMaybe = Nothing
inOptional :: VarIn -> ArgIn a -> ArgIn (Maybe a)
inOptional varin_def argin = \val var -> do
case val of
Nothing -> varin_def var
Just v -> argin v var
inMaybe :: Variant a => ArgIn (Maybe a)
inMaybe Nothing = inEmpty ()
inMaybe (Just x) = inVariant x
resMaybe :: Variant a => ArgRes (Maybe a)
resMaybe p =
catchComException
(readVarError p >> return Nothing)
(\ _ -> fmap Just (resVariant p))
inoutMaybe :: Variant a => ArgInOut (Maybe a) (Maybe a)
inoutMaybe o = (inMaybe o,resMaybe)
outMaybe :: Variant a => (VarIn,ArgRes (Maybe a))
outMaybe = inoutMaybe defaultMaybe
data SqlNull = SqlNull
defaultSqlNull :: SqlNull
defaultSqlNull = SqlNull
inSqlNull :: ArgIn SqlNull
inSqlNull SqlNull p = writeVarNull p
resSqlNull :: ArgRes SqlNull
resSqlNull p = readVarNull p >> return SqlNull
inoutSqlNull SqlNull = (inSqlNull SqlNull,resSqlNull)
outSqlNull = inoutSqlNull defaultSqlNull
--Haskell values (stable ptr's).
inHaskellValue :: ArgIn a
inHaskellValue x p = do
stable <- newStablePtr x
writeVarStablePtr stable (castPtr p)
unsafeResHaskellValue :: ArgRes a
unsafeResHaskellValue p = do
stable <- readVarStablePtr p
deRefStablePtr stable
unsafeOutHaskellValue =
( \ p -> writeVarStablePtr undefinedStablePtr p
, unsafeResHaskellValue
)
undefinedStablePtr :: StablePtr a
undefinedStablePtr = unsafePerformIO (newStablePtr undefined)
--Convenience QIs - are they really used?
queryIUnknown :: IID (IUnknown a) -> IUnknown () -> IO (IUnknown a)
queryIUnknown = queryInterface
queryIDispatch :: IID (IUnknown a) -> IDispatch () -> IO (IUnknown a)
queryIDispatch = queryInterface
--The basic marshalling functions for automation types.
defaultEmpty :: ()
defaultEmpty = ()
inNoArg :: ArgIn ()
inNoArg i = writeVarOptional
inEmpty :: ArgIn ()
inEmpty i = writeVarEmpty
noInArg :: VarIn
noInArg = inEmpty ()
resEmpty :: ArgRes ()
resEmpty p = return ()
inoutEmpty e = (inEmpty e,resEmpty)
outEmpty = inoutEmpty defaultEmpty
inGUID :: ArgIn GUID
inGUID g = inString (show g)
inoutGUID i = (inGUID i,resGUID)
outGUID = inoutGUID nullGUID
resGUID :: ArgRes GUID
resGUID p = resString p >>= stringToGUID
--Integers.
defaultInt :: Int
defaultInt = 0
inInt :: ArgIn Int
inInt i = writeVarInt (fromIntegral i)
resInt :: ArgRes Int
resInt p = readVarInt p >>= return.fromIntegral
inoutInt i = (inInt i,resInt)
outInt = inoutInt defaultInt
defaultInt8 :: Int8
defaultInt8 = 0
inInt8 :: ArgIn Int8
inInt8 i = writeVarInt (fromIntegral i)
resInt8 :: ArgRes Int8
resInt8 p = readVarInt p >>= return.fromIntegral
inoutInt8 i = (inInt8 i,resInt8)
outInt8 = inoutInt8 defaultInt8
defaultInt16 :: Int16
defaultInt16 = 0
inInt16 :: ArgIn Int16
inInt16 i = writeVarInt (fromIntegral i)
resInt16 :: ArgRes Int16
resInt16 p = readVarInt p >>= return.fromIntegral
inoutInt16 i = (inInt16 i,resInt16)
outInt16 = inoutInt16 defaultInt16
defaultInt32 :: Int32
defaultInt32 = 0
inInt32 :: ArgIn Int32
inInt32 i = writeVarInt i
resInt32 :: ArgRes Int32
resInt32 p = readVarInt p >>= return
inoutInt32 i = (inInt32 i,resInt32)
outInt32 = inoutInt32 defaultInt32
defaultHRESULT = defaultInt32
inHRESULT = inInt32
resHRESULT = resInt32
inoutHRESULT = inoutInt32
outHRESULT = outInt32
defaultInt64 :: Int64
defaultInt64 = 0
inInt64 :: ArgIn Int64
inInt64 i = inWord64 (fromIntegral i)
resInt64 :: ArgRes Int64
resInt64 p = resWord64 p >>= return.fromIntegral
inoutInt64 i = (inInt64 i,resInt64)
outInt64 = inoutInt64 defaultInt64
defaultInteger = defaultInt64
inInteger = inInt64
resInteger = resInt64
inoutInteger = inoutInt64
outInteger = outInt64
--Words
defaultWord :: Int
defaultWord = 0
inWord :: ArgIn Int
inWord i = writeVarInt (fromIntegral i)
resWord :: ArgRes Int
resWord p = readVarInt p >>= return.fromIntegral
inoutWord i = (inInt i,resInt)
outWord = inoutInt defaultInt
defaultWord8 :: Word8
defaultWord8 = 0
inWord8 :: ArgIn Word8
inWord8 i = writeVarWord (fromIntegral i)
resWord8 :: ArgRes Word8
resWord8 p = readVarWord p >>= return.fromIntegral
inoutWord8 i = (inWord8 i,resWord8)
outWord8 = inoutWord8 defaultWord8
defaultWord16 :: Word16
defaultWord16 = 0
inWord16 :: ArgIn Word16
inWord16 i = writeVarWord (fromIntegral i)
resWord16 :: ArgRes Word16
resWord16 p = readVarWord p >>= return.fromIntegral
inoutWord16 i = (inWord16 i,resWord16)
outWord16 = inoutWord16 defaultWord16
defaultWord32 :: Word32
defaultWord32 = 0
inWord32 :: ArgIn Word32
inWord32 i = writeVarWord i
resWord32 :: ArgRes Word32
resWord32 p = readVarWord p
inoutWord32 i = (inWord32 i,resWord32)
outWord32 = inoutWord32 defaultWord32
defaultWord64 :: Word64
defaultWord64 = 0
inWord64 :: ArgIn Word64
inWord64 f =
let
(hi,lo) = toInteger f `divMod` (toInteger (maxBound :: Int) + 1)
in
writeVarWord64 (fromInteger hi) (fromInteger lo)
resWord64 :: ArgRes Word64
resWord64 =
let
coerceW = fromIntegral
coerceI = fromIntegral
readWord v = do
(hi,lo) <- readVarWord64 v
return (coerceW hi * (coerceI (maxBound :: Int) + 1) + coerceW lo)
in
readWord
inoutWord64 i = (inWord64 i,resWord64)
outWord64 = inoutWord64 defaultWord64
--Bytes (yeah, I know, the name of the type was a bit of a give-away :-)
--type Byte = Char
defaultByte :: Byte
defaultByte = 0
inByte :: ArgIn Byte
inByte i = writeVarByte i
resByte :: ArgRes Byte
resByte = readVarByte
inoutByte i = (inByte i,resByte)
outByte = inoutByte defaultByte
defaultChar :: Char
defaultChar = '\0'
inChar :: ArgIn Char
inChar i = writeVarByte (fromIntegral (fromEnum i))
resChar :: ArgRes Char
resChar p = readVarByte p >>= \ x -> return (toEnum (fromIntegral x))
inoutChar i = (inChar i,resChar)
outChar = inoutChar defaultChar
--Booleans.
defaultBool :: Bool
defaultBool = False
inBool :: ArgIn Bool
inBool b = writeVarBool b
resBool :: ArgRes Bool
resBool = readVarBool
inoutBool b = (inBool b,resBool)
outBool = inoutBool defaultBool
--Floats.
defaultFloat :: Float
defaultFloat = 0.0
inFloat :: ArgIn Float
inFloat f = writeVarFloat f
resFloat :: ArgRes Float
resFloat = readVarFloat
inoutFloat b = (inFloat b,resFloat)
outFloat = inoutFloat defaultFloat
--Doubles.
defaultDouble :: Double
defaultDouble = 0.0
inDouble :: ArgIn Double
inDouble f = writeVarDouble f
resDouble :: ArgRes Double
resDouble = readVarDouble
inoutDouble b = (inDouble b,resDouble)
outDouble = inoutDouble defaultDouble
--Dates.
type Date = Double
defaultDate :: Date
defaultDate = 0.0
inDate :: ArgIn Date
inDate f = writeVarDouble f
resDate :: ArgRes Date
resDate = readVarDouble
inoutDate b = (inDate b,resDate)
outDate = inoutDate defaultDate
--
-- clockTimeToDate relies on a non-standard implementation of Time,
-- i.e., one which exports ClockTime non-abstractly.
--
clockTimeToDate :: ClockTime -> IO Date
clockTimeToDate (TOD secs _)
| secs > fromIntegral (maxBound :: Int) ||
secs < fromIntegral (minBound :: Int) =
ioError (userError "Automation.clockTimeToDate: ClockTime out of range")
| otherwise = primClockToDate (fromIntegral secs)
--Currency:
type Currency
= Int64
defaultCurrency :: Currency
defaultCurrency = 0
-- Note: the Int64/Integer is interpreted literally here,
-- and no account of the implicit scaling that CURRENCY
-- does is taken into account. ToDo: fix.
inCurrency :: ArgIn Currency
inCurrency f =
let
(hi,lo) = f `divMod` (fromIntegral (maxBound :: Int) + 1)
in
writeVarCurrency (fromIntegral (fromIntegral hi)) (fromIntegral (fromIntegral lo))
-- NOTE: this handles the decimal currency type in a shallow way, i.e., in its
-- int64-encoded form. To translate that fixed-point number (15,4) encoding
-- you'll have to do some more work...
resCurrency :: ArgRes Currency
resCurrency v = do
(hi,lo) <- readVarCurrency v
return (coerceI (fromIntegral hi) * (coerceI (maxBound :: Int) + 1) +
coerceI (fromIntegral lo))
where
coerceI = fromIntegral
inoutCurrency b = (inCurrency b, resCurrency)
outCurrency = inoutCurrency defaultCurrency
--Strings.
defaultString :: String
defaultString = ""
inString :: ArgIn String
inString s p = do
pbstr <- nofreeAllocBSTR s
writeVarString (castPtr pbstr) p
resString :: ArgRes String
resString p = readTempVar "String" readVarString p (\ p -> unmarshallBSTR (castPtr p))
inoutString i = (inString i,resString)
outString = inoutString defaultString
--Unknown objects.
defaultIUnknown :: IUnknown a
defaultIUnknown = interfaceNULL
inIUnknown :: ArgIn (IUnknown a)
inIUnknown u p
| isNullInterface u = return ()
| otherwise = do
u # addRef
writeVarUnknown (castIface u) p
resIUnknown :: ArgRes (IUnknown a)
resIUnknown p =
readTempVar "IUnknown" readVarUnknown p (unmarshallIUnknown True{-finalise-})
inoutIUnknown d = (inIUnknown d,resIUnknown)
outIUnknown = inoutIUnknown defaultIUnknown
--Dispatch objects.
defaultIDispatch :: IDispatch a
defaultIDispatch = interfaceNULL
inIDispatch :: ArgIn (IDispatch a)
inIDispatch d p
| isNullInterface d = return ()
| otherwise = do
d # addRef
writeVarDispatch (castIface d) p
resIDispatch :: ArgRes (IDispatch a)
resIDispatch p =
readTempVar "IDispatch" readVarDispatch p (unmarshallIUnknown True{-finalise-})
inoutIDispatch d = (inIDispatch d,resIDispatch)
outIDispatch = inoutIDispatch defaultIDispatch
--Error objects.
defaultError :: Int32
defaultError = 0
inError :: ArgIn Int32
inError d p = writeVarError d p
resError :: ArgRes Int32
resError p = readVarError p
inoutError d = (inError d,resError)
outError = inoutError defaultError
--Generic wrappers for Enum instances
inEnum :: Enum a => ArgIn a
inEnum e = inInt (fromEnum e)
defaultEnum :: Enum a => a
defaultEnum = toEnum 0
resEnum :: Enum a => ArgRes a
resEnum p = readVarInt p >>= return.toEnum.fromIntegral
inoutEnum :: Enum a => ArgInOut a a
inoutEnum i = (inEnum i,resEnum)
outEnum :: Enum a => ArgOut a
outEnum = inoutEnum defaultEnum
vtTypeEnum :: Enum a => a -> VARENUM
vtTypeEnum _ = VT_I4
{- Support for overlapping instances required
to compile this one - let's not demand that
being supported for now.
If you do uncomment this one, you probably
also want to invoke the IDL compiler with
-fno-variant-enum-instances.
instance Enum a => Variant a where
inVariant = inEnum
resVariant = resEnum
defaultVariant = defaultEnum
vtEltType _ = VT_I4
-}
--Setting and Getting properties: @getVisible = propertyGet "Visible" [] outBool@.
propertyGet :: Member -> [VarIn] -> ArgOut a -> IDispatch d -> IO a
propertyGet member argsin argout obj
= do dispid <- obj # getMemberID member
propertyGetID dispid argsin argout obj
propertyGet2 :: Member -> [VarIn] -> ArgOut a1 -> ArgOut a2 -> IDispatch d -> IO (a1,a2)
propertyGet2 member argsin argout1 argout2 obj
= do dispid <- obj # getMemberID member
propertyGet2ID dispid argsin argout1 argout2 obj
propertyGet3 :: Member -> [VarIn] -> ArgOut a1 -> ArgOut a2 -> ArgOut a3 -> IDispatch d -> IO (a1,a2,a3)
propertyGet3 member argsin argout1 argout2 argout3 obj
= do dispid <- obj # getMemberID member
propertyGet3ID dispid argsin argout1 argout2 argout3 obj
propertyGet4 :: Member -> [VarIn] -> ArgOut a1 -> ArgOut a2 -> ArgOut a3 -> ArgOut a4 -> IDispatch d -> IO (a1,a2,a3,a4)
propertyGet4 member argsin argout1 argout2 argout3 argout4 obj
= do dispid <- obj # getMemberID member
propertyGet4ID dispid argsin argout1 argout2 argout3 argout4 obj
propertySet :: Member -> [VarIn] -> IDispatch d -> IO ()
propertySet member argsin obj
= do dispid <- obj # getMemberID member
propertySetID dispid argsin obj
propertySetGet :: Member -> [VarIn] -> ArgOut a -> IDispatch d -> IO a
propertySetGet member argsin argout obj
= do dispid <- obj # getMemberID member
propertySetGetID dispid argsin argout obj
propertyGetID :: DISPID -> [VarIn] -> ArgOut a -> IDispatch d -> IO a
propertyGetID dispid argsin (varin,argres) obj
= do p <- obj # invokePropertyGet dispid argsin [varin]
unmarshallVariants1 argres p
propertyGet2ID :: DISPID -> [VarIn] -> ArgOut a1 -> ArgOut a2 -> IDispatch d -> IO (a1,a2)
propertyGet2ID dispid argsin (varin1,argres1) (varin2,argres2) obj
= do p <- obj # invokePropertyGet dispid argsin [varin1,varin2]
unmarshallVariants2 argres1 argres2 p
propertyGet3ID :: DISPID -> [VarIn] -> ArgOut a1 -> ArgOut a2 -> ArgOut a3 -> IDispatch d -> IO (a1,a2,a3)
propertyGet3ID dispid argsin (varin1,argres1) (varin2,argres2) (varin3,argres3) obj
= do p <- obj # invokePropertyGet dispid argsin [varin1,varin2,varin3]
unmarshallVariants3 argres1 argres2 argres3 p
propertyGet4ID :: DISPID -> [VarIn] -> ArgOut a1 -> ArgOut a2 -> ArgOut a3 -> ArgOut a4 -> IDispatch d -> IO (a1,a2,a3,a4)
propertyGet4ID dispid argsin (varin1,argres1) (varin2,argres2) (varin3,argres3) (varin4,argres4) obj
= do p <- obj # invokePropertyGet dispid argsin [varin1,varin2,varin3,varin4]
unmarshallVariants4 argres1 argres2 argres3 argres4 p
propertySetID :: DISPID -> [VarIn] -> IDispatch d -> IO ()
propertySetID dispid argsin obj
= do p <- obj # invokePropertySet dispid argsin []
unmarshallVariants0 p
propertySetGetID :: DISPID -> [VarIn] -> ArgOut a -> IDispatch d -> IO a
propertySetGetID dispid argsin (varin,argres) obj
= do p <- obj # invokePropertySet dispid argsin [varin]
unmarshallVariants1 argres p
{-
Methods and functions are defined using @method@/@funtion@. The digit
appended to the name gives the number of results.
For example: @confirm msg = function1 "Confirm" [inString msg] outBool@.
-}
method0 :: Member
-> [VarIn]
-> IDispatch i
-> IO ()
method0 member args obj = do
dispid <- obj # getMemberID member
catchMethError member (methodID0 dispid args obj)
method1 :: Member
-> [VarIn]
-> ArgOut a1
-> IDispatch i
-> IO a1
method1 member args argout obj = do
dispid <- obj # getMemberID member
catchMethError member (methodID1 dispid args argout obj)
method2 :: Member
-> [VarIn]
-> ArgOut a1
-> ArgOut a2
-> IDispatch i
-> IO (a1,a2)
method2 member args argout1 argout2 obj = do
dispid <- obj # getMemberID member
catchMethError member (methodID2 dispid args argout1 argout2 obj)
method3 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> IDispatch i -> IO (a1,a2,a3)
method3 member args argout1 argout2 argout3 obj = do
dispid <- obj # getMemberID member
catchMethError member (methodID3 dispid args argout1 argout2 argout3 obj)
method4 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2
-> ArgOut a3 -> ArgOut a4
-> IDispatch i -> IO (a1,a2,a3,a4)
method4 member args argout1 argout2 argout3 argout4 obj = do
dispid <- obj # getMemberID member
catchMethError member $
methodID4 dispid args argout1 argout2 argout3 argout4 obj
method5 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5
-> IDispatch i -> IO (a1,a2,a3,a4,a5)
method5 member args argout1 argout2 argout3 argout4 argout5 obj = do
dispid <- obj # getMemberID member
catchMethError member $
methodID5 dispid args argout1 argout2 argout3 argout4 argout5 obj
method6 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6
-> IDispatch i
-> IO (a1,a2,a3,a4,a5,a6)
method6 member args argout1 argout2 argout3 argout4 argout5 argout6 obj = do
dispid <- obj # getMemberID member
catchMethError member $
methodID6 dispid args argout1 argout2 argout3
argout4 argout5 argout6 obj
method7 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6 -> ArgOut a7
-> IDispatch i -> IO (a1, a2, a3, a4, a5, a6, a7)
method7 member args argout1 argout2 argout3 argout4 argout5 argout6 argout7 obj = do
dispid <- obj # getMemberID member
catchMethError member $
methodID7 dispid args argout1 argout2 argout3
argout4 argout5 argout6 argout7 obj
method8 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6
-> ArgOut a7 -> ArgOut a8
-> IDispatch i
-> IO (a1, a2, a3, a4, a5, a6, a7, a8)
method8 member args argout1 argout2 argout3
argout4 argout5 argout6
argout7 argout8 obj = do
dispid <- obj # getMemberID member
catchMethError member $
methodID8 dispid args argout1 argout2 argout3
argout4 argout5 argout6
argout7 argout8 obj
--Methods invoked on DISPID.
methodID0 :: DISPID
-> [VarIn]
-> IDispatch i
-> IO ()
methodID0 dispid args obj = do
p <- obj # invokeMethod dispid args []
unmarshallVariants0 p
methodID1 :: DISPID
-> [VarIn]
-> ArgOut a1
-> IDispatch i
-> IO a1
methodID1 dispid args (varin,argres) obj = do
p <- obj # invokeMethod dispid args [varin]
unmarshallVariants1 argres p
methodID2 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2
-> IDispatch i
-> IO (a1,a2)
methodID2 dispid args (varin1,argres1) (varin2,argres2) obj = do
p <- obj # invokeMethod dispid args [varin1,varin2]
unmarshallVariants2 argres1 argres2 p
methodID3 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> IDispatch i
-> IO (a1,a2,a3)
methodID3 dispid args (varin1,argres1) (varin2,argres2) (varin3,argres3) obj = do
p <- obj # invokeMethod dispid args [varin1,varin2,varin3]
unmarshallVariants3 argres1 argres2 argres3 p
methodID4 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4
-> IDispatch i
-> IO (a1,a2,a3,a4)
methodID4 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4) obj = do
p <- obj # invokeMethod dispid args [varin1,varin2,varin3,varin4]
unmarshallVariants4 argres1 argres2 argres3 argres4 p
methodID5 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5
-> IDispatch i
-> IO (a1,a2,a3,a4,a5)
methodID5 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4)
(varin5,argres5) obj = do
p <- obj # invokeMethod dispid args [varin1,varin2,varin3,varin4,varin5]
unmarshallVariants5 argres1 argres2 argres3 argres4 argres5 p
methodID6 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6
-> IDispatch i
-> IO (a1,a2,a3,a4,a5,a6)
methodID6 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4)
(varin5,argres5) (varin6,argres6) obj = do
p <- obj # invokeMethod dispid args [varin1,varin2,varin3,varin4,varin5,varin6]
unmarshallVariants6 argres1 argres2 argres3 argres4 argres5 argres6 p
methodID7 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6
-> ArgOut a7
-> IDispatch i
-> IO (a1,a2,a3,a4,a5,a6,a7)
methodID7 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4)
(varin5,argres5) (varin6,argres6)
(varin7,argres7) obj = do
p <- obj # invokeMethod dispid args [varin1,varin2,varin3,varin4,varin5,varin6,varin7]
unmarshallVariants7 argres1 argres2 argres3 argres4 argres5 argres6 argres7 p
methodID8 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6
-> ArgOut a7 -> ArgOut a8
-> IDispatch i
-> IO (a1,a2,a3,a4,a5,a6,a7,a8)
methodID8 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4)
(varin5,argres5) (varin6,argres6)
(varin7,argres7) (varin8,argres8) obj = do
p <- obj # invokeMethod dispid args [varin1,varin2,varin3,varin4,varin5,varin6,varin7,varin8]
unmarshallVariants8 argres1 argres2 argres3 argres4 argres5 argres6 argres7 argres8 p
{-
Functions. Of course @function0@ is missing. The difference with
methods is that functions expect the last @out@ argument to be
a result (@retval@) instead of a real @out@ argument.
-}
function1 :: Member
-> [VarIn]
-> ArgOut a1
-> IDispatch i
-> IO a1
function1 member args argout obj = do
dispid <- obj # getMemberID member
catchMethError member (functionID1 dispid args argout obj)
function2 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2
-> IDispatch i
-> IO (a1,a2)
function2 member args argout1 argout2 obj = do
dispid <- obj # getMemberID member
catchMethError member (functionID2 dispid args argout1 argout2 obj)
function3 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> IDispatch i
-> IO (a1,a2,a3)
function3 member args argout1 argout2 argout3 obj = do
dispid <- obj # getMemberID member
catchMethError member (functionID3 dispid args argout1 argout2 argout3 obj)
function4 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4
-> IDispatch i
-> IO (a1,a2,a3,a4)
function4 member args argout1 argout2 argout3 argout4 obj = do
dispid <- obj # getMemberID member
catchMethError member (functionID4 dispid args argout1 argout2 argout3 argout4 obj)
function5 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5
-> IDispatch i
-> IO (a1,a2,a3,a4,a5)
function5 member args argout1 argout2 argout3
argout4 argout5 obj = do
dispid <- obj # getMemberID member
catchMethError member $
functionID5 dispid args argout1 argout2 argout3 argout4 argout5 obj
function6 :: Member
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6
-> IDispatch i
-> IO (a1,a2,a3,a4,a5,a6)
function6 member args argout1 argout2 argout3
argout4 argout5 argout6 obj = do
dispid <- obj # getMemberID member
catchMethError member $
functionID6 dispid args argout1 argout2 argout3 argout4 argout5 argout6 obj
functionID1 :: DISPID
-> [VarIn]
-> ArgOut a1
-> IDispatch i
-> IO a1
functionID1 dispid args (varin,argres) obj = do
p <- obj # invokeFunction dispid args [varin]
unmarshallVariants1 argres p
functionID2 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2
-> IDispatch i
-> IO (a1,a2)
functionID2 dispid args (varin1,argres1) (varin2,argres2) obj = do
p <- obj # invokeFunction dispid args [varin1,varin2]
unmarshallVariants2 argres1 argres2 p
functionID3 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> IDispatch i
-> IO (a1,a2,a3)
functionID3 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) obj = do
p <- obj # invokeFunction dispid args [varin1,varin2,varin3]
unmarshallVariants3 argres1 argres2 argres3 p
functionID4 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4
-> IDispatch i
-> IO (a1,a2,a3,a4)
functionID4 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4) obj = do
p <- obj # invokeFunction dispid args [varin1,varin2,varin3,varin4]
unmarshallVariants4 argres1 argres2 argres3 argres4 p
functionID5 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5
-> IDispatch i
-> IO (a1,a2,a3,a4,a5)
functionID5 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4)
(varin5,argres5) obj = do
p <- obj # invokeFunction dispid args [varin1,varin2,varin3,varin4,varin5]
unmarshallVariants5 argres1 argres2 argres3 argres4 argres5 p
functionID6 :: DISPID
-> [VarIn]
-> ArgOut a1 -> ArgOut a2 -> ArgOut a3
-> ArgOut a4 -> ArgOut a5 -> ArgOut a6
-> IDispatch i
-> IO (a1,a2,a3,a4,a5,a6)
functionID6 dispid args (varin1,argres1) (varin2,argres2)
(varin3,argres3) (varin4,argres4)
(varin5,argres5) (varin6,argres6) obj = do
p <- obj # invokeFunction dispid args [varin1,varin2,varin3,varin4,varin5,varin6]
unmarshallVariants6 argres1 argres2 argres3 argres4 argres5 argres6 p
--Error reporting:
errorMember :: String -> Either IOError ComException -> IO a
errorMember member err
= coFail ("method '" ++ member ++ "': " ++ (coGetErrorString err))
catchMethError :: Member -> IO a -> IO a
catchMethError member act = catchComException act (errorMember member)
--Unmarshall the @out@ arguments.
unmarshallVariants0 p
= readVariants0 p `always` freeMemVariants 0 p
unmarshallVariants1 a p
= readVariants1 a p `always` freeMemVariants 1 p
unmarshallVariants2 a b p
= readVariants2 a b p `always` freeMemVariants 2 p
unmarshallVariants3 a b c p
= readVariants3 a b c p `always` freeMemVariants 3 p
unmarshallVariants4 a b c d p
= readVariants4 a b c d p `always` freeMemVariants 4 p
unmarshallVariants5 a b c d e p
= readVariants5 a b c d e p `always` freeMemVariants 5 p
unmarshallVariants6 a b c d e f p
= readVariants6 a b c d e f p `always` freeMemVariants 6 p
unmarshallVariants7 a b c d e f g p
= readVariants7 a b c d e f g p `always` freeMemVariants 7 p
unmarshallVariants8 a b c d e f g h p
= readVariants8 a b c d e f g h p `always` freeMemVariants 8 p
readVariants0 :: VARIANT -> IO ()
readVariants0 p = return ()
readVariants1 :: ArgRes a -> VARIANT -> IO a
readVariants1 f p = f p
readVariants2 :: ArgRes a -> ArgRes b -> VARIANT -> IO (a,b)
readVariants2 f g p
= do y <- g p
x <- f (p `addNCastPtr` sizeofVARIANT)
return (x,y)
readVariants3 :: ArgRes a -> ArgRes b -> ArgRes c
-> VARIANT -> IO (a,b,c)
readVariants3 f g h p
= do z <- h p
y <- g (p `addNCastPtr` sizeofVARIANT)
x <- f (p `addNCastPtr` (2*sizeofVARIANT))
return (x,y,z)
readVariants4 :: ArgRes a -> ArgRes b -> ArgRes c -> ArgRes d
-> VARIANT -> IO (a,b,c,d)
readVariants4 f g h i p
= do z <- i p
y <- h (p `addNCastPtr` sizeofVARIANT)
x <- g (p `addNCastPtr` (2*sizeofVARIANT))
w <- f (p `addNCastPtr` (3*sizeofVARIANT))
return (w,x,y,z)
readVariants5 :: ArgRes a -> ArgRes b -> ArgRes c -> ArgRes d -> ArgRes e
-> VARIANT -> IO (a,b,c,d,e)
readVariants5 f g h i j p
= do z <- j p
y <- i (p `addNCastPtr` sizeofVARIANT)
x <- h (p `addNCastPtr` (2*sizeofVARIANT))
w <- g (p `addNCastPtr` (3*sizeofVARIANT))
v <- f (p `addNCastPtr` (4*sizeofVARIANT))
return (v,w,x,y,z)
readVariants6 :: ArgRes a1
-> ArgRes a2
-> ArgRes a3
-> ArgRes a4
-> ArgRes a5
-> ArgRes a6
-> VARIANT
-> IO (a1,a2,a3,a4,a5,a6)
readVariants6 f1 f2 f3 f4 f5 f6 p
= do v6 <- f6 p
v5 <- f5 (p `addNCastPtr` sizeofVARIANT)
v4 <- f4 (p `addNCastPtr` (2*sizeofVARIANT))
v3 <- f3 (p `addNCastPtr` (3*sizeofVARIANT))
v2 <- f2 (p `addNCastPtr` (4*sizeofVARIANT))
v1 <- f1 (p `addNCastPtr` (5*sizeofVARIANT))
return (v1,v2,v3,v4,v5,v6)
readVariants7 :: ArgRes a1 -> ArgRes a2 -> ArgRes a3 -> ArgRes a4 -> ArgRes a5
-> ArgRes a6 -> ArgRes a7
-> VARIANT -> IO (a1,a2,a3,a4,a5,a6,a7)
readVariants7 f1 f2 f3 f4 f5 f6 f7 p
= do v7 <- f7 p
v6 <- f6 (p `addNCastPtr` sizeofVARIANT)
v5 <- f5 (p `addNCastPtr` (2*sizeofVARIANT))
v4 <- f4 (p `addNCastPtr` (3*sizeofVARIANT))
v3 <- f3 (p `addNCastPtr` (4*sizeofVARIANT))
v2 <- f2 (p `addNCastPtr` (5*sizeofVARIANT))
v1 <- f1 (p `addNCastPtr` (6*sizeofVARIANT))
return (v1,v2,v3,v4,v5,v6,v7)
readVariants8:: ArgRes a1 -> ArgRes a2 -> ArgRes a3 -> ArgRes a4 -> ArgRes a5
-> ArgRes a6 -> ArgRes a7 -> ArgRes a8
-> VARIANT -> IO (a1,a2,a3,a4,a5,a6,a7,a8)
readVariants8 f1 f2 f3 f4 f5 f6 f7 f8 p
= do v8 <- f8 p
v7 <- f7 (p `addNCastPtr` sizeofVARIANT)
v6 <- f6 (p `addNCastPtr` (2*sizeofVARIANT))
v5 <- f5 (p `addNCastPtr` (3*sizeofVARIANT))
v4 <- f4 (p `addNCastPtr` (4*sizeofVARIANT))
v3 <- f3 (p `addNCastPtr` (5*sizeofVARIANT))
v2 <- f2 (p `addNCastPtr` (6*sizeofVARIANT))
v1 <- f1 (p `addNCastPtr` (7*sizeofVARIANT))
return (v1,v2,v3,v4,v5,v6,v7,v8)
{- UNUSED:
unmarshallVariantList :: [ArgRes a] -> VARIANT -> IO [a]
unmarshallVariantList fls p =
(go p fls []) `always` freeMemVariants len p
where
len = length fls
go p [] acc = return acc
go p (f:fs) acc = do
v <- f p
go (p `addNCastPtr` sizeofVARIANT) fs (v:acc)
-}
{-
@invokeMethod/Function@ and @propertyGet/Set@ all use the primitive
@primInvokeMethod@.
-}
invokePropertyGet = primInvokeMethod dispPROPERTYGET True
invokePropertySet = primInvokeMethod dispPROPERTYSET False
invokeMethod = primInvokeMethod dispMETHOD False
invokeFunction = primInvokeMethod dispMETHOD True
--Some constants used with the invoke functions.
type DispAction = Word32
dispMETHOD :: Word32
dispMETHOD = 1
dispPROPERTYGET :: Word32
dispPROPERTYGET = 2
dispPROPERTYSET :: Word32
dispPROPERTYSET = 4
dispPROPERTYSETREF :: Word32
dispPROPERTYSETREF = 8
lcidNeutral :: Word32
lcidNeutral = 0
{-
The primitive invokation mechanism. Exceptions are directed to the normal
@coFail@ function.
-}
primInvokeMethod :: DispAction
-> Bool
-> DISPID
-> [VarIn] -> [VarIn]
-> IDispatch d
-> IO (VARIANT)
primInvokeMethod action isfunction dispid argin argout iptr
= let cargsout = fromIntegral (length argout)
cargs = cargsout + fromIntegral (length argin)
in
stackFrame (fromIntegral (sizeofVARIANT * fromIntegral cargs)) $ \ pargs ->
do
pargout <- allocMemory (fromIntegral $ sizeofVARIANT * fromIntegral cargsout)
let pargin = pargs `addNCastPtr` (sizeofVARIANT * fromIntegral cargsout)
writeSeqAtDec (fromIntegral sizeofVARIANT) argin pargin
writeSeqAtDec (fromIntegral sizeofVARIANT) argout pargout
(pinfo,hr) <- dispatchInvoke (castIface iptr)
dispid lcidNeutral isfunction
action (fromIntegral cargs)
cargsout
pargs pargout
if (succeeded hr)
then return pargout
else if hr == dISP_E_EXCEPTION
then do
pstr <- getExcepInfoMessage pinfo
str <- unmarshallString (castPtr pstr)
coFree pstr
freeExcepInfo pinfo
freeMemory pinfo
freeMemVariants cargsout pargout
coFail str
else do
putMessage "invoke failed"
freeMemVariants cargsout pargout
coFailHR hr
--Some helper functions for @Variants@.
readTempVar :: String
-> (VARIANT -> IO (Ptr (Ptr b), Ptr (VARIANT)))
-> VARIANT
-> (Ptr b -> IO d)
-> IO d
readTempVar atTy io p f = do
tg <- readVariantTag p
(x,v) <-
catchComException (io p)
(\ ex -> do
hPutStrLn stderr ("VARIANT error: found type " ++ show (tg, atTy))
throwIOComException ex)
x <- readPtr x -- we always get a ty* back, so dereference it before using.
f x `always` (freeVariants 1 (castPtr v) >> free v)
-- _don't_ use freeMemVariants, as it ends up
-- calling freeMemory (==CoTaskMemFree()),
-- which isn't right ('v' is allocated by malloc()).
freeMemVariants count p = do
freeVariants count p
freeMemory p
{-
Marshall BSTR values. @allocBSTR@ is called @primAllocBSTR@
since it doesn't take care of freeing the string. (If we
just had true foreign objects: @mkPointer xbstr freeBSTR@.)
-}
allocBSTR :: String -> IO (Ptr String)
allocBSTR s = stackString s $ \ _ pstr -> do
ptr <- stringToBSTR (castPtr pstr)
readPtr ptr
nofreeAllocBSTR :: String -> IO (Ptr String)
nofreeAllocBSTR s = stackString s $ \ _ pstr -> do
ptr <- nofreeBstrFromString (castPtr pstr)
return ptr
-- makePointer finalFreeBSTR ptr
nofreeBstrFromString :: Ptr String -> IO (Ptr String)
nofreeBstrFromString str = do
ptr <- stringToBSTR str
readPtr ptr
data EnumVARIANT a = EnumVARIANT
type IEnumVARIANT a = IUnknown (EnumVARIANT a)
iidIEnumVARIANT :: IID (IEnumVARIANT ())
iidIEnumVARIANT = mkIID "{00020404-0000-0000-C000-000000000046}"
newEnum :: IDispatch a -> IO (Int, IEnumVARIANT b)
newEnum ip = do
iunk <-
catchComException (ip # propertyGet "_NewEnum" [] outIUnknown)
(\ _ -> ip # function1 "_NewEnum" [] outIUnknown)
ienum <- iunk # queryInterface iidIEnumVARIANT
len <-
catchComException (ip # propertyGet "length" [] outInt)
(\ _ -> ip # propertyGet "Count" [] outInt)
return (len, castIface ienum)
enumVariants :: Variant a => IDispatch b -> IO (Int, [a])
enumVariants ip = do
(len, ienum) <- newEnum ip
-- enumNext (fromIntegral sizeofVARIANT) resVariant (fromIntegral len) ienum
let
getByOne ie = do
mb <- ie # enumNextOne (fromIntegral sizeofVARIANT) resVariant
case mb of
Nothing -> return []
Just x -> do
-- note: here we have the option of making it on-demand..
xs <- getByOne ie
return (x:xs)
ls <- getByOne ienum
return (len, ls)
--Helpers
always :: IO a -> IO () -> IO a
always io action = do
x <- io `catchComException` (\ e -> action >> throwIOComException e)
action
return x
marshallCurrency = marshallInt64
unmarshallCurrency = unmarshallInt64
readCurrency = readInt64
writeCurrency = writeInt64
sizeofCurrency = sizeofInt64
data VARENUM
= VT_EMPTY
| VT_NULL
| VT_I2
| VT_I4
| VT_R4
| VT_R8
| VT_CY
| VT_DATE
| VT_BSTR
| VT_DISPATCH
| VT_ERROR
| VT_BOOL
| VT_VARIANT
| VT_UNKNOWN
| VT_DECIMAL
| VT_I1
| VT_UI1
| VT_UI2
| VT_UI4
| VT_I8
| VT_UI8
| VT_INT
| VT_UINT
| VT_VOID
| VT_HRESULT
| VT_PTR
| VT_SAFEARRAY
| VT_CARRAY
| VT_USERDEFINED
| VT_LPSTR
| VT_LPWSTR
| VT_FILETIME
| VT_BLOB
| VT_STREAM
| VT_STORAGE
| VT_STREAMED_OBJECT
| VT_STORED_OBJECT
| VT_BLOB_OBJECT
| VT_CF
| VT_CLSID
| VT_BSTR_BLOB
| VT_VECTOR
| VT_ARRAY
| VT_BYREF
| VT_RESERVED
| VT_ILLEGAL
| VT_ILLEGALMASKED
| VT_TYPEMASK
deriving ( Eq, Show )
instance Enum VARENUM where
fromEnum vt =
case vt of
VT_EMPTY -> 0
VT_NULL -> 1
VT_I2 -> 2
VT_I4 -> 3
VT_R4 -> 4
VT_R8 -> 5
VT_CY -> 6
VT_DATE -> 7
VT_BSTR -> 8
VT_DISPATCH -> 9
VT_ERROR -> 10
VT_BOOL -> 11
VT_VARIANT -> 12
VT_UNKNOWN -> 13
VT_DECIMAL -> 14
VT_I1 -> 16
VT_UI1 -> 17
VT_UI2 -> 18
VT_UI4 -> 19
VT_I8 -> 20
VT_UI8 -> 21
VT_INT -> 22
VT_UINT -> 23
VT_VOID -> 24
VT_HRESULT -> 25
VT_PTR -> 26
VT_SAFEARRAY -> 27
VT_CARRAY -> 28
VT_USERDEFINED -> 29
VT_LPSTR -> 30
VT_LPWSTR -> 31
VT_FILETIME -> 64
VT_BLOB -> 65
VT_STREAM -> 66
VT_STORAGE -> 67
VT_STREAMED_OBJECT -> 68
VT_STORED_OBJECT -> 69
VT_BLOB_OBJECT -> 70
VT_CF -> 71
VT_CLSID -> 72
VT_BSTR_BLOB -> 4095
VT_VECTOR -> 4096
VT_ARRAY -> 8192
VT_BYREF -> 16384
VT_RESERVED -> 32768
VT_ILLEGAL -> 65535
VT_ILLEGALMASKED -> 4095
VT_TYPEMASK -> 4095
toEnum v =
case v of
0 -> VT_EMPTY
1 -> VT_NULL
2 -> VT_I2
3 -> VT_I4
4 -> VT_R4
5 -> VT_R8
6 -> VT_CY
7 -> VT_DATE
8 -> VT_BSTR
9 -> VT_DISPATCH
10 -> VT_ERROR
11 -> VT_BOOL
12 -> VT_VARIANT
13 -> VT_UNKNOWN
14 -> VT_DECIMAL
16 -> VT_I1
17 -> VT_UI1
18 -> VT_UI2
19 -> VT_UI4
20 -> VT_I8
21 -> VT_UI8
22 -> VT_INT
23 -> VT_UINT
24 -> VT_VOID
25 -> VT_HRESULT
26 -> VT_PTR
27 -> VT_SAFEARRAY
28 -> VT_CARRAY
29 -> VT_USERDEFINED
30 -> VT_LPSTR
31 -> VT_LPWSTR
64 -> VT_FILETIME
65 -> VT_BLOB
66 -> VT_STREAM
67 -> VT_STORAGE
68 -> VT_STREAMED_OBJECT
69 -> VT_STORED_OBJECT
70 -> VT_BLOB_OBJECT
71 -> VT_CF
72 -> VT_CLSID
4095 -> VT_BSTR_BLOB
4096 -> VT_VECTOR
8192 -> VT_ARRAY
16384 -> VT_BYREF
32768 -> VT_RESERVED
65535 -> VT_ILLEGAL
4095 -> VT_ILLEGALMASKED
4095 -> VT_TYPEMASK
_
| v' .&. 26 == 26 -> VT_PTR -- ho-hum.
| v' .&. 8192 == 8192 -> VT_ARRAY -- ho-hum.
| v' .&. 16384 == 16384 -> toEnum (v-16384) -- drop the VT_BYREF flag.
| otherwise -> error ("unmarshallVARENUM: illegal enum value " ++ show v)
where
v' = (fromIntegral v :: Int32)
unmarshallVARENUM :: Int16 -> IO VARENUM
unmarshallVARENUM v = return (toEnum (fromIntegral v))
marshallVARENUM :: VARENUM -> IO Int16
marshallVARENUM v = return (fromIntegral (fromEnum v))
writeVARENUM :: Ptr Int16 -> VARENUM -> IO ()
writeVARENUM = HDirect.writeenum16 marshallVARENUM
readVARENUM :: Ptr Int16 -> IO VARENUM
readVARENUM = HDirect.readenum16 unmarshallVARENUM
sizeofVARENUM :: Word32
sizeofVARENUM = sizeofInt16
sizeofVARIANT_BOOL :: Word32
sizeofVARIANT_BOOL = sizeofInt16
marshallVARIANT_BOOL :: Bool -> IO Int16
marshallVARIANT_BOOL True = return minBound
marshallVARIANT_BOOL False = return 0
unmarshallVARIANT_BOOL :: Int16 -> IO Bool
unmarshallVARIANT_BOOL 0 = return False
unmarshallVARIANT_BOOL _ = return True
writeVARIANT_BOOL :: Ptr Int16 -> Bool -> IO ()
writeVARIANT_BOOL ptr v = marshallVARIANT_BOOL v >>= writeInt16 ptr
readVARIANT_BOOL :: Ptr Int16 -> IO Bool
readVARIANT_BOOL ptr = do
x <- readInt16 ptr
unmarshallVARIANT_BOOL x
vARIANT_TRUE :: Int
vARIANT_TRUE = -1
vARIANT_FALSE :: Int
vARIANT_FALSE = 0
readVarEnum :: VARIANT -> IO VARENUM
readVarEnum v = do
vt <- readVariantTag v
return (toEnum (fromIntegral vt))
data SafeArray a = SA SAFEARRAY
mkSafeArray :: (Variant a) => SAFEARRAY -> SafeArray a
mkSafeArray s = SA s
defaultSafeArray :: Variant a => SafeArray a
defaultSafeArray = SA (addrToSAFEARRAY nullPtr)
inSafeArray :: Variant a => ArgIn (SafeArray a)
inSafeArray s = inSafe' undefined s
-- type hack.
inSafe' :: Variant a => a -> ArgIn (SafeArray a)
inSafe' b (SA s) p = writeVarSAFEARRAY p s (fromIntegral (fromEnum (vtEltType b)))
inSAFEARRAY :: ArgIn SAFEARRAY
inSAFEARRAY s p = writeVarSAFEARRAY p s (fromIntegral (fromEnum VT_VARIANT))
resSafeArray :: Variant a => ArgRes (SafeArray a)
resSafeArray p = resSafe' undefined p
resSafe' :: Variant a => a -> ArgRes (SafeArray a)
resSafe' vt p = do
x <- readVarSAFEARRAY (castPtr p) (fromIntegral (fromEnum (vtEltType vt)))
s <- doThenFree free (readSAFEARRAY True) (castPtr x)
return (SA s)
resSAFEARRAY :: ArgRes SAFEARRAY
resSAFEARRAY p = do
x <- readVarSAFEARRAY (castPtr p) (fromIntegral (fromEnum VT_VARIANT))
doThenFree free (readSAFEARRAY True) (castPtr x)
inoutSafeArray :: (Variant a) => ArgInOut (SafeArray a) (SafeArray a)
inoutSafeArray d = (inSafeArray d,resSafeArray)
outSafeArray :: Variant a => ArgOut (SafeArray a)
outSafeArray = inoutSafeArray defaultSafeArray
freeSafeArray :: SafeArray a -> IO ()
freeSafeArray (SA s) = return () -- it's a foreignObj..
marshallSafeArray :: SafeArray a -> IO (ForeignPtr SAFEARRAY)
marshallSafeArray (SA s) = marshallSAFEARRAY s
unmarshallSafeArray :: Ptr a -> IO (SafeArray a)
unmarshallSafeArray x = do
s <- unmarshallSAFEARRAY True (castPtr x)
return (SA s)
writeSafeArray :: Ptr (SafeArray a) -> SafeArray a -> IO ()
writeSafeArray ptr (SA s) = writeSAFEARRAY (castPtr ptr) s
readSafeArray :: Variant a => Bool -> Ptr (SafeArray a) -> IO (SafeArray a)
readSafeArray finaliseMe ptr = readSafeArray' finaliseMe ptr undefined
readSafeArray' :: Variant a => Bool -> Ptr (SafeArray a) -> a -> IO (SafeArray a)
readSafeArray' finaliseMe ptr x = do
xx <- readSA finaliseMe ptr (vtEltType x)
return (SA xx)
readSA :: Bool -> Ptr (SafeArray a) -> VARENUM -> IO SAFEARRAY
readSA finaliseMe ptr vt = do
x <- readVarSAFEARRAY (castPtr ptr) (fromIntegral (fromEnum vt))
doThenFree free (readSAFEARRAY finaliseMe) (castPtr x)
instance Variant a => Variant (SafeArray a) where
inVariant = inSafeArray
resVariant = resSafeArray
instance Variant SAFEARRAY where
inVariant = inSAFEARRAY
resVariant = resSAFEARRAY
marshallVariant :: Variant a => a -> IO VARIANT
marshallVariant v = do
x <- allocMemory (fromIntegral sizeofVARIANT)
inVariant v (castPtr x)
return x
writeVariant :: Variant a => VARIANT -> a -> IO ()
writeVariant ptr v = inVariant v ptr
readVariant :: Variant a => VARIANT -> IO a
readVariant ptr = do
ptr' <- readPtr ptr
resVariant ptr'
unmarshallVariant :: Variant a => VARIANT -> IO a
unmarshallVariant ptr = resVariant ptr
| HJvT/com | System/Win32/Com/Automation.hs | bsd-3-clause | 63,021 | 0 | 19 | 17,423 | 17,811 | 9,192 | 8,619 | 1,410 | 3 |
module MRP (
module MRP.Commands,
module MRP.CommandsC,
module MRP.QuasiQuoter
) where
import MRP.Commands
import MRP.CommandsC
import MRP.QuasiQuoter | jfischoff/minimal-resource-protocol | src/MRP.hs | bsd-3-clause | 187 | 0 | 5 | 53 | 39 | 25 | 14 | 7 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2001-2017
--
-- Finding the compiler's base directory.
--
-----------------------------------------------------------------------------
-}
module SysTools.BaseDir (expandTopDir, findTopDir) where
#include "HsVersions.h"
import GhcPrelude
import Panic
import System.FilePath
import Data.List
-- POSIX
#if defined(darwin_HOST_OS) || defined(linux_HOST_OS)
import System.Environment (getExecutablePath)
#endif
-- Windows
#if defined(mingw32_HOST_OS)
#if MIN_VERSION_Win32(2,5,0)
import qualified System.Win32.Types as Win32
#else
import qualified System.Win32.Info as Win32
#endif
import Data.Char
import Exception
import Foreign
import Foreign.C.String
import System.Directory
import System.Win32.Types (DWORD, LPTSTR, HANDLE)
import System.Win32.Types (failIfNull, failIf, iNVALID_HANDLE_VALUE)
import System.Win32.File (createFile,closeHandle, gENERIC_READ, fILE_SHARE_READ, oPEN_EXISTING, fILE_ATTRIBUTE_NORMAL, fILE_FLAG_BACKUP_SEMANTICS )
import System.Win32.DLL (loadLibrary, getProcAddress)
#endif
#if defined(mingw32_HOST_OS)
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
{-
Note [topdir: How GHC finds its files]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC needs various support files (library packages, RTS etc), plus
various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
the root of GHC's support files
On Unix:
- ghc always has a shell wrapper that passes a -B<dir> option
On Windows:
- ghc never has a shell wrapper.
- we can find the location of the ghc binary, which is
$topdir/<foo>/<something>.exe
where <something> may be "ghc", "ghc-stage2", or similar
- we strip off the "<foo>/<something>.exe" to leave $topdir.
from topdir we can find package.conf, ghc-asm, etc.
-}
-- | Expand occurrences of the @$topdir@ interpolation in a string.
expandTopDir :: FilePath -> String -> String
expandTopDir top_dir str
| Just str' <- stripPrefix "$topdir" str
, null str' || isPathSeparator (head str')
= top_dir ++ expandTopDir top_dir str'
expandTopDir top_dir (x:xs) = x : expandTopDir top_dir xs
expandTopDir _ [] = []
-- | Returns a Unix-format path pointing to TopDir.
findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
-> IO String -- TopDir (in Unix format '/' separated)
findTopDir (Just minusb) = return (normalise minusb)
findTopDir Nothing
= do -- Get directory of executable
maybe_exec_dir <- getBaseDir
case maybe_exec_dir of
-- "Just" on Windows, "Nothing" on unix
Nothing -> throwGhcExceptionIO (InstallationError "missing -B<dir> option")
Just dir -> return dir
getBaseDir :: IO (Maybe String)
#if defined(mingw32_HOST_OS)
-- Assuming we are running ghc, accessed by path $(stuff)/<foo>/ghc.exe,
-- return the path $(stuff)/lib.
getBaseDir = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
where
try_size size = allocaArray (fromIntegral size) $ \buf -> do
ret <- c_GetModuleFileName nullPtr buf size
case ret of
0 -> return Nothing
_ | ret < size -> do
path <- peekCWString buf
real <- getFinalPath path -- try to resolve symlinks paths
let libdir = (rootDir . sanitize . maybe path id) real
exists <- doesDirectoryExist libdir
if exists
then return $ Just libdir
else fail path
| otherwise -> try_size (size * 2)
-- getFinalPath returns paths in full raw form.
-- Unfortunately GHC isn't set up to handle these
-- So if the call succeeded, we need to drop the
-- \\?\ prefix.
sanitize s = if "\\\\?\\" `isPrefixOf` s
then drop 4 s
else s
rootDir s = case splitFileName $ normalise s of
(d, ghc_exe)
| lower ghc_exe `elem` ["ghc.exe",
"ghc-stage1.exe",
"ghc-stage2.exe",
"ghc-stage3.exe"] ->
case splitFileName $ takeDirectory d of
-- ghc is in $topdir/bin/ghc.exe
(d', _) -> takeDirectory d' </> "lib"
_ -> fail s
fail s = panic ("can't decompose ghc.exe path: " ++ show s)
lower = map toLower
foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
-- Attempt to resolve symlinks in order to find the actual location GHC
-- is located at. See Trac #11759.
getFinalPath :: FilePath -> IO (Maybe FilePath)
getFinalPath name = do
dllHwnd <- failIfNull "LoadLibrary" $ loadLibrary "kernel32.dll"
-- Note: The API GetFinalPathNameByHandleW is only available starting from Windows Vista.
-- This means that we can't bind directly to it since it may be missing.
-- Instead try to find it's address at runtime and if we don't succeed consider the
-- function failed.
addr_m <- (fmap Just $ failIfNull "getProcAddress" $ getProcAddress dllHwnd "GetFinalPathNameByHandleW")
`catch` (\(_ :: SomeException) -> return Nothing)
case addr_m of
Nothing -> return Nothing
Just addr -> do handle <- failIf (==iNVALID_HANDLE_VALUE) "CreateFile"
$ createFile name
gENERIC_READ
fILE_SHARE_READ
Nothing
oPEN_EXISTING
(fILE_ATTRIBUTE_NORMAL .|. fILE_FLAG_BACKUP_SEMANTICS)
Nothing
let fnPtr = makeGetFinalPathNameByHandle $ castPtrToFunPtr addr
-- First try to resolve the path to get the actual path
-- of any symlinks or other file system redirections that
-- may be in place. However this function can fail, and in
-- the event it does fail, we need to try using the
-- original path and see if we can decompose that.
-- If the call fails Win32.try will raise an exception
-- that needs to be caught. See #14159
path <- (Win32.try "GetFinalPathName"
(\buf len -> fnPtr handle buf len 0) 512
`finally` closeHandle handle)
`catch`
(\(_ :: IOException) -> return name)
return $ Just path
type GetFinalPath = HANDLE -> LPTSTR -> DWORD -> DWORD -> IO DWORD
foreign import WINDOWS_CCONV unsafe "dynamic"
makeGetFinalPathNameByHandle :: FunPtr GetFinalPath -> GetFinalPath
#elif defined(darwin_HOST_OS) || defined(linux_HOST_OS)
-- on unix, this is a bit more confusing.
-- The layout right now is somehting like
--
-- /bin/ghc-X.Y.Z <- wrapper script (1)
-- /bin/ghc <- symlink to wrapper script (2)
-- /lib/ghc-X.Y.Z/bin/ghc <- ghc executable (3)
-- /lib/ghc-X.Y.Z <- $topdir (4)
--
-- As such, we first need to find the absolute location to the
-- binary.
--
-- getExecutablePath will return (3). One takeDirectory will
-- give use /lib/ghc-X.Y.Z/bin, and another will give us (4).
--
-- This of course only works due to the current layout. If
-- the layout is changed, such that we have ghc-X.Y.Z/{bin,lib}
-- this would need to be changed accordingly.
--
getBaseDir = Just . (\p -> p </> "lib") . takeDirectory . takeDirectory <$> getExecutablePath
#else
getBaseDir = return Nothing
#endif
| ezyang/ghc | compiler/main/SysTools/BaseDir.hs | bsd-3-clause | 8,129 | 38 | 23 | 2,392 | 1,072 | 579 | 493 | 25 | 2 |
module VispUsage
( getUsage
) where
import VispUsage.Fetcher
someFunc :: IO ()
someFunc = putStrLn "someFunc"
| ajmccluskey/visp-usage | src/VispUsage.hs | bsd-3-clause | 120 | 0 | 6 | 26 | 32 | 18 | 14 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module ETA.CodeGen.Main where
import ETA.BasicTypes.Module
import ETA.Main.HscTypes
import ETA.Types.Type
import ETA.Types.TyCon
import ETA.StgSyn.StgSyn
import ETA.Main.DynFlags
import ETA.Utils.FastString
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.Id
import ETA.BasicTypes.Name
import ETA.BasicTypes.OccName
import ETA.BasicTypes.DataCon
import ETA.Utils.Util (unzipWith)
import ETA.Prelude.PrelNames (rOOT_MAIN)
import ETA.Util
import ETA.Debug
import ETA.CodeGen.Types
import ETA.CodeGen.Closure
import ETA.CodeGen.Constr
import ETA.CodeGen.Monad
import ETA.CodeGen.Bind
import ETA.CodeGen.Name
import ETA.CodeGen.Rts
import ETA.CodeGen.ArgRep
import ETA.CodeGen.Env
import Codec.JVM
import Data.Maybe (mapMaybe, catMaybes)
import Data.Foldable (fold)
import Data.Monoid ((<>))
import Control.Monad (unless, when)
import Data.Text (Text, pack, cons, append)
codeGen :: HscEnv -> Module -> [TyCon] -> [StgBinding] -> HpcInfo -> IO [ClassFile]
codeGen hscEnv thisMod dataTyCons stgBinds _hpcInfo = do
runCodeGen env state $ do
mapM_ (cgTopBinding dflags) stgBinds
mapM_ cgTyCon dataTyCons
where
(env, state) = initCg dflags thisMod
dflags = hsc_dflags hscEnv
cgTopBinding :: DynFlags -> StgBinding -> CodeGen ()
cgTopBinding dflags (StgNonRec id rhs) = do
debugDoc $ str "generating " <+> ppr id
mod <- getModule
id' <- externaliseId dflags id
let (info, code) = cgTopRhs dflags NonRecursive id' rhs
code
addBinding info
cgTopBinding dflags (StgRec pairs) = do
mod <- getModule
let (binders, rhss) = unzip pairs
debugDoc $ str "generating (rec) " <+> ppr binders
binders' <- mapM (externaliseId dflags) binders
let pairs' = zip binders' rhss
r = unzipWith (cgTopRhs dflags Recursive) pairs'
(infos, codes) = unzip r
addBindings infos
sequence_ codes
cgTopRhs :: DynFlags -> RecFlag -> Id -> StgRhs -> (CgIdInfo, CodeGen ())
cgTopRhs dflags _ binder (StgRhsCon _ con args) =
cgTopRhsCon dflags binder con args
cgTopRhs dflags recflag binder
(StgRhsClosure _ binderInfo freeVars updateFlag _ args body) =
-- fvs should be empty
cgTopRhsClosure dflags recflag binder binderInfo updateFlag args body
cgTopRhsClosure :: DynFlags
-> RecFlag -- member of a recursive group?
-> Id
-> StgBinderInfo
-> UpdateFlag
-> [Id] -- Args
-> StgExpr
-> (CgIdInfo, CodeGen ())
cgTopRhsClosure dflags recflag id binderInfo updateFlag args body
= (cgIdInfo, genCode dflags lfInfo)
where cgIdInfo = mkCgIdInfo dflags id lfInfo
lfInfo = mkClosureLFInfo id TopLevel [] updateFlag args
(modClass, clName, clClass) = getJavaInfo dflags cgIdInfo
isThunk = isLFThunk lfInfo
qClName = closure clName
genCode dflags _
| StgApp f [] <- body, null args, isNonRec recflag
= do cgInfo <- getCgIdInfo f
let loadCode = idInfoLoadCode cgInfo
defineField $ mkFieldDef [Public, Static] qClName closureType
let field = mkFieldRef modClass qClName closureType
deps = catMaybes [getLocField (cgLocation cgInfo)]
addInitStep (fold
[
new indStaticType,
dup indStaticType,
loadCode,
invokespecial $ mkMethodRef stgIndStatic "<init>"
[closureType] void,
putstatic field
]
, field
, deps
-- TODO: Check this works when f is in external module
)
genCode dflags lf = do
(_, CgState { cgClassName }) <- forkClosureBody $
closureCodeBody True id lfInfo
(nonVoidIds args) (length args) body [] False []
let ft = obj cgClassName
-- NOTE: Don't make thunks final so that they can be
-- replaced by their values by the GC
let flags = (if isThunk then [] else [Final]) ++ [Public, Static]
defineField $ mkFieldDef flags qClName closureType
let field = mkFieldRef modClass qClName closureType
addInitStep (fold
[
new ft,
dup ft,
invokespecial $ mkMethodRef cgClassName "<init>" [] void,
putstatic field
]
, field
, []
)
return ()
-- Simplifies the code if the mod is associated to the Id
externaliseId :: DynFlags -> Id -> CodeGen Id
externaliseId dflags id = do
mod <- getModule
return $
if isInternalName name then
setIdName id $ externalise mod
else if isExternalName name && nameModule name == rOOT_MAIN then
setIdName id $ internalise mod
else id
where
internalise mod = mkExternalName uniq mod occ' loc
where occ' = mkOccName ns $ ":" ++ occNameString occ
externalise mod = mkExternalName uniq mod occ' loc
where occ' = mkLocalOcc uniq occ
name = idName id
uniq = nameUnique name
occ = nameOccName name
loc = nameSrcSpan name
ns = occNameSpace occ
cgTyCon :: TyCon -> CodeGen ()
cgTyCon tyCon = unless (null dataCons) $ do
dflags <- getDynFlags
let tyConClass = nameTypeText dflags . tyConName $ tyCon
(_, CgState {..}) <- newTypeClosure tyConClass stgConstr
mapM_ (cgDataCon cgClassName) (tyConDataCons tyCon)
when (isEnumerationTyCon tyCon) $
cgEnumerationTyCon cgClassName tyCon
where dataCons = tyConDataCons tyCon
cgEnumerationTyCon :: Text -> TyCon -> CodeGen ()
cgEnumerationTyCon tyConCl tyCon = do
dflags <- getDynFlags
thisClass <- getClass
let fieldName = nameTypeTable dflags $ tyConName tyCon
loadCodes = [ dup arrayFt
<> iconst jint i
<> new dataFt
<> dup dataFt
<> invokespecial (mkMethodRef dataClass "<init>" [] void)
<> gastore elemFt
| (i, con) <- zip [0..] $ tyConDataCons tyCon
, let dataFt = obj dataClass
dataClass = dataConClass dflags con ]
defineField $ mkFieldDef [Public, Static, Final] fieldName arrayFt
let field = mkFieldRef thisClass fieldName arrayFt
addInitStep (fold
[
iconst jint $ fromIntegral familySize,
new arrayFt,
fold loadCodes,
putstatic field
]
, field
, []
)
where
arrayFt = jarray elemFt
elemFt = obj tyConCl
familySize = tyConFamilySize tyCon
cgDataCon :: Text -> DataCon -> CodeGen ()
cgDataCon typeClass dataCon = do
dflags <- getDynFlags
modClass <- getModClass
let dataConClassName = nameDataText dflags . dataConName $ dataCon
thisClass = qualifiedName modClass dataConClassName
thisFt = obj thisClass
defineTagMethod =
defineMethod . mkMethodDef thisClass [Public] "getTag" [] (ret jint) $
iconst jint conTag
<> greturn jint
-- TODO: Reduce duplication
if isNullaryRepDataCon dataCon then do
newExportedClosure dataConClassName typeClass $ do
defineMethod $ mkDefaultConstructor thisClass typeClass
defineTagMethod
return ()
else
do let initCode :: Code
initCode = go 1 indexedFields
where go _ [] = mempty
go n ((i, ft): xs) = code <> go (n + fieldSize ft) xs
where maybeDup = if i /= numFields then dup thisFt else mempty
code = maybeDup
<> gload ft (fromIntegral n)
<> putfield (mkFieldRef thisClass (constrField i) ft)
fieldDefs :: [FieldDef]
fieldDefs = map (\(i, ft) ->
-- TODO: Find a better way to handle recursion
-- that allows us to use 'final' in most cases.
mkFieldDef [Public] (constrField i) ft)
indexedFields
(ps, os, ns, fs, ls, ds) = go indexedFields [] [] [] [] [] []
go [] ps os ns fs ls ds = (ps, os, ns, fs, ls, ds)
go ((i, ft):ifs) ps os ns fs ls ds =
case ftArgRep ft of
P -> go ifs ((i, code):ps) os ns fs ls ds
O -> go ifs ps ((i, code):os) ns fs ls ds
N -> go ifs ps os ((i, code):ns) fs ls ds
F -> go ifs ps os ns ((i, code):fs) ls ds
L -> go ifs ps os ns fs ((i, code):ls) ds
D -> go ifs ps os ns fs ls ((i, code):ds)
_ -> panic "cgDataCon: V argrep!"
where code = gload thisFt 0
<> getfield (mkFieldRef thisClass (constrField i) ft)
defineGetRep :: ArgRep -> [(Int, Code)] -> CodeGen ()
defineGetRep rep [] = return ()
defineGetRep rep branches =
defineMethod $
mkMethodDef thisClass [Public] method [jint] (ret ft) $
gswitch (gload jint 1) branches
(Just $ barf (append method ": invalid field index!")
<> defaultValue ft)
<> greturn ft
where ft = argRepFt rep
method = append "get" (pack $ show rep)
indexedFields :: [(Int, FieldType)]
indexedFields = indexList fields
numFields :: Int
numFields = length fields
fields :: [FieldType]
fields = repFieldTypes $ dataConRepArgTys dataCon
newExportedClosure dataConClassName typeClass $ do
defineFields fieldDefs
defineTagMethod
defineGetRep P ps
defineGetRep O os
defineGetRep N ns
defineGetRep F fs
defineGetRep L ls
defineGetRep D ds
defineMethod $ mkConstructorDef thisClass typeClass fields initCode
return ()
where conTag = fromIntegral $ getDataConTag dataCon
| alexander-at-github/eta | compiler/ETA/CodeGen/Main.hs | bsd-3-clause | 10,156 | 0 | 22 | 3,391 | 2,943 | 1,486 | 1,457 | -1 | -1 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
module Data.ExprGADT.Dumb.Infer where
-- import Control.Exception
-- import Control.Arrow
-- import Control.Monad.Except
-- import Control.Monad.RWS
-- import Data.ExprGADT.Dumb.Types
-- import Data.Typeable
-- import Data.ExprGADT.Types
-- import Data.List (nub)
-- import Data.Map (Map)
-- import Data.Set (Set)
-- import qualified Data.Map as M
-- import qualified Data.Set as S
-- data Scheme = Forall [TVar] TExpr
-- deriving (Show, Eq)
-- newtype InferState = InferState { count :: Int }
-- newtype Subst = Subst (Map TVar TExpr)
-- instance Monoid Subst where
-- mempty = Subst M.empty
-- mappend (Subst x) (Subst y) = Subst $ fmap apl y `M.union` x
-- where
-- apl = applyTExpr (Subst x)
-- type Constraint = (TExpr, TExpr)
-- type Unifier = (Subst, [Constraint])
-- data Env = Env { envTypes :: Map VName Scheme }
-- instance Monoid Env where
-- mempty = Env M.empty
-- mappend (Env x) (Env y) = Env (M.union x y)
-- data TypeError :: * where
-- TErrUnbound :: VName -> TypeError
-- TErrInfType :: TVar -> TExpr -> TypeError
-- TErrMismatch :: [TExpr] -> [TExpr] -> TypeError
-- TErrUniFail :: TExpr -> TExpr -> TypeError
-- TErrBottom :: TypeError
-- deriving (Show, Typeable)
-- instance Exception TypeError
-- varNames :: [VName]
-- varNames = [ v : if n == 0 then "" else show (n :: Int)
-- | n <- [0..]
-- , v <- "xyzhijklmnpqrstuvw"]
-- runInfer :: Env -> RWST Env [Constraint] [VName] (Either TypeError) TExpr -> Either TypeError (TExpr, [Constraint])
-- runInfer env m = evalRWST m env varNames
-- inferExpr :: Env -> DumbExpr -> Either TypeError Scheme
-- inferExpr env ex = do
-- (ty, cs) <- runInfer env (infer ex)
-- subst <- solver (mempty, cs)
-- return $ closeOver (applyTExpr subst ty)
-- where
-- closeOver = normalize . generalize (Env M.empty)
-- normalize (Forall _ body) = Forall (map snd ord') (normtype body)
-- where
-- ord' = zip (nub (fv body)) (map TV varNames)
-- fv (TEV a) = [a]
-- fv (TEO0 _) = []
-- fv (TEO1 _ e1) = fv e1
-- fv (TEO2 _ e1 e2) = fv e1 ++ fv e2
-- normtype (TEO0 o) = TEO0 o
-- normtype (TEO1 o e1) = TEO1 o (normtype e1)
-- normtype (TEO2 o e1 e2) = TEO2 o (normtype e1) (normtype e2)
-- normtype (TEV v) = case lookup v ord' of
-- Just x -> TEV x
-- Nothing -> error "type variable not in signature, what gives"
-- generalize env' t = Forall as t
-- where
-- as = S.toList $ ftvTExpr t `S.difference` ftvEnv env'
-- ftvEnv = S.unions . map ftvScheme . M.elems . envTypes
-- ftvScheme (Forall as t) = ftvTExpr t `S.difference` S.fromList as
-- infer :: (MonadError TypeError m, MonadReader Env m, MonadState [VName] m, MonadWriter [Constraint] m)
-- => DumbExpr -> m TExpr
-- infer e = case e of
-- DV v -> lookupEnv v
-- DO0 o -> case o of
-- I _ -> pure tInt
-- B _ -> pure tBool
-- Unit -> pure (TEO0 TOUnit)
-- Nil -> do
-- t1 <- fresh
-- tv <- fresh
-- uni (TEO1 TOList t1) tv
-- return tv
-- DO1 o e1 -> do
-- t1 <- infer e1
-- tv <- fresh
-- let u1 = t1 `tFunc` tv
-- u2 <- case o of
-- Abs -> return $ tInt `tFunc` tInt
-- Signum -> return $ tInt `tFunc` tInt
-- Not -> return $ tBool `tFunc` tBool
-- Left' -> do
-- tr <- fresh
-- return $ t1 `tFunc` TEO2 TOEither t1 tr
-- Right' -> do
-- tl <- fresh
-- return $ t1 `tFunc` TEO2 TOEither tl t1
-- Fst -> do
-- tfst <- fresh
-- tsnd <- fresh
-- uni t1 (TEO2 TOTuple tfst tsnd)
-- return $ t1 `tFunc` tfst
-- Snd -> do
-- tfst <- fresh
-- tsnd <- fresh
-- uni t1 (TEO2 TOTuple tfst tsnd)
-- return $ t1 `tFunc` tsnd
-- uni u1 u2
-- return tv
-- DO2 o e1 e2 -> do
-- t1 <- infer e1
-- t2 <- infer e2
-- tv <- fresh
-- let u1 = t1 `tFunc` (t2 `tFunc` tv)
-- u2 <- case o of
-- Plus -> return $ tInt `tFunc` (tInt `tFunc` tInt)
-- Times -> return $ tInt `tFunc` (tInt `tFunc` tInt)
-- Minus -> return $ tInt `tFunc` (tInt `tFunc` tInt)
-- LEquals -> return $ tInt `tFunc` (tInt `tFunc` tBool)
-- And -> return $ tBool `tFunc` (tBool `tFunc` tBool)
-- Or -> return $ tBool `tFunc` (tBool `tFunc` tBool)
-- Tup -> return $ t1 `tFunc` (t2 `tFunc` TEO2 TOTuple t1 t2)
-- Cons -> return $ t1 `tFunc` (TEO1 TOList t1 `tFunc` TEO1 TOList t1)
-- Ap -> do
-- t3 <- fresh
-- uni t1 (TEO2 TOFunc t2 t3)
-- return $ t1 `tFunc` (t2 `tFunc` t3)
-- Div -> return $ tInt `tFunc` (tInt `tFunc` TEO2 TOEither (TEO0 TOUnit) tInt)
-- Mod -> return $ tInt `tFunc` (tInt `tFunc` TEO2 TOEither (TEO0 TOUnit) tInt)
-- uni u1 u2
-- return tv
-- DO3 o e1 e2 e3 -> do
-- t1 <- infer e1
-- t2 <- infer e2
-- t3 <- infer e3
-- tv <- fresh
-- let u1 = t1 `tFunc` (t2 `tFunc` (t3 `tFunc` tv))
-- u2 <- case o of
-- If -> do
-- uni t2 t3
-- return $ tBool `tFunc` (t2 `tFunc` (t2 `tFunc` t2))
-- Case -> do
-- ta <- fresh
-- tb <- fresh
-- tc <- fresh
-- uni t2 (ta `tFunc` tc)
-- uni t3 (tb `tFunc` tc)
-- uni t1 (TEO2 TOEither ta tb)
-- return $ t1 `tFunc` (t2 `tFunc` (t3 `tFunc` tc))
-- UnfoldrN -> do
-- tb <- fresh
-- uni t2 (t3 `tFunc` TEO2 TOTuple tb t3)
-- return $ tInt `tFunc` (t2 `tFunc` (t3 `tFunc` TEO1 TOList tb))
-- Foldr -> do
-- ta <- fresh
-- uni t1 (ta `tFunc` (t2 `tFunc` t2))
-- uni t3 (TEO1 TOList ta)
-- return $ t1 `tFunc` (t2 `tFunc` (t3 `tFunc` t2))
-- uni u1 u2
-- return tv
-- DLambda x e1 -> do
-- tv <- fresh
-- t <- inEnv (x, Forall [] tv) (infer e1)
-- return (tv `tFunc` t)
-- where
-- tInt = TEO0 TOInt
-- tBool = TEO0 TOBool
-- tFunc = TEO2 TOFunc
-- uni :: MonadWriter [Constraint] m => TExpr -> TExpr -> m ()
-- uni t1 t2 = tell [(t1, t2)]
-- lookupEnv :: (MonadState [VName] m, MonadError TypeError m, MonadReader Env m) => VName -> m TExpr
-- lookupEnv x = do
-- Env env <- ask
-- case M.lookup x env of
-- Nothing -> throwError $ TErrUnbound x
-- Just t -> instantiate t
-- instantiate :: MonadState [VName] m => Scheme -> m TExpr
-- instantiate (Forall as t) = do
-- as' <- mapM (const fresh) as
-- let s = Subst $ M.fromList (zip as as')
-- return $ applyTExpr s t
-- inEnv :: MonadReader Env m => (VName, Scheme) -> m a -> m a
-- inEnv (x, sc) = local $ \e' -> remove e' x `extend` (x, sc)
-- extend :: Env -> (VName, Scheme) -> Env
-- extend env (x, s) = env { envTypes = M.insert x s (envTypes env) }
-- remove :: Env -> VName -> Env
-- remove (Env env) x = Env (M.delete x env)
-- fresh :: MonadState [VName] m => m TExpr
-- fresh = state $ \(x:xs) -> (TEV (TV x), xs)
-- applyTExpr :: Subst -> TExpr -> TExpr
-- applyTExpr s@(Subst m) t = case t of
-- TEO0 a -> TEO0 a
-- TEV v -> M.findWithDefault t v m
-- TEO1 o e1 -> TEO1 o (applyTExpr s e1)
-- TEO2 o e1 e2 -> TEO2 o (applyTExpr s e1) (applyTExpr s e2)
-- solver :: MonadError TypeError m => Unifier -> m Subst
-- solver (su, cs) = case cs of
-- [] -> pure su
-- ((t1, t2): cs0) -> do
-- su1 <- unifies t1 t2
-- solver (su1 <> su, map (applyTExpr su1 *** applyTExpr su1) cs0)
-- unifies :: MonadError TypeError m => TExpr -> TExpr -> m Subst
-- unifies t1 t2 | t1 == t2 = pure mempty
-- unifies (TEV v) t = v `bind` t
-- unifies t (TEV v) = v `bind` t
-- unifies (TEO1 _ t1) (TEO1 _ t2) = unifies t1 t2
-- unifies (TEO2 _ t1 t2) (TEO2 _ t3 t4) = unifyMany [t1, t2] [t3, t4]
-- unifies t1 t2 = throwError $ TErrUniFail t1 t2
-- unifyMany :: MonadError TypeError m => [TExpr] -> [TExpr] -> m Subst
-- unifyMany [] [] = pure mempty
-- unifyMany (t1:ts1) (t2:ts2) = do
-- su1 <- unifies t1 t2
-- su2 <- unifyMany (applyTExpr su1 <$> ts1) (applyTExpr su1 <$> ts2)
-- return (su2 <> su1)
-- unifyMany t1 t2 = throwError $ TErrMismatch t1 t2
-- bind :: MonadError TypeError m => TVar -> TExpr -> m Subst
-- bind a t | t == TEV a = pure mempty
-- | occursCheck a t = throwError $ TErrInfType a t
-- | otherwise = pure (Subst (M.singleton a t))
-- where
-- occursCheck a' t' = a' `S.member` ftvTExpr t'
-- ftvTExpr :: TExpr -> Set TVar
-- ftvTExpr t' = case t' of
-- TEV a' -> S.singleton a'
-- TEO0 _ -> S.empty
-- TEO1 _ t1 -> ftvTExpr t1
-- TEO2 _ t1 t2 -> ftvTExpr t1 `S.union` ftvTExpr t2
| mstksg/expr-gadt | src/Data/ExprGADT/Dumb/Infer.hs | bsd-3-clause | 10,567 | 0 | 3 | 4,313 | 235 | 233 | 2 | 5 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}
module
Types.PlanSpec
where
import qualified Control.Arrow.Machine as P
import Control.Arrow.Machine hiding (filter, source)
import Control.Applicative
import qualified Control.Category as Cat
import Control.Arrow
import Control.Monad.State
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Identity (Identity, runIdentity)
import Debug.Trace
import Test.Hspec
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck (Arbitrary, arbitrary, oneof, frequency, sized)
import Common.RandomProc
spec =
do
let pl =
do
x <- await
yield x
yield (x+1)
x <- await
yield x
yield (x+1)
l = [2, 5, 10, 20, 100]
it "can be constructed into ProcessA" $
do
let
result = run (construct pl) l
result `shouldBe` [2, 3, 5, 6]
it "can be repeatedly constructed into ProcessA" $
do
let
result = run (repeatedly pl) l
result `shouldBe` [2, 3, 5, 6, 10, 11, 20, 21, 100, 101]
it "can handle the end with catchP." $
do
let
plCatch =
do
x <- await `catchP` (yield 1 >> stop)
yield x
y <- (yield 2 >> await >> yield 3 >> await) `catchP` (yield 4 >> return 5)
yield y
y <- (await >>= yield >> stop) `catchP` (yield 6 >> return 7)
yield y
run (construct plCatch) [] `shouldBe` [1]
run (construct plCatch) [100] `shouldBe` [100, 2, 4, 5, 6, 7]
run (construct plCatch) [100, 200] `shouldBe` [100, 2, 3, 4, 5, 6, 7]
run (construct plCatch) [100, 200, 300] `shouldBe` [100, 2, 3, 300, 6, 7]
run (construct plCatch) [100, 200, 300, 400] `shouldBe` [100, 2, 3, 300, 400, 6, 7]
| as-capabl/machinecell | test/Types/PlanSpec.hs | bsd-3-clause | 2,070 | 0 | 21 | 633 | 697 | 389 | 308 | 60 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Run
-- Copyright : Duncan Coutts 2009
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides a data type for program invocations and functions to
-- run them.
module Distribution.Simple.Program.Run (
ProgramInvocation(..),
IOEncoding(..),
emptyProgramInvocation,
simpleProgramInvocation,
programInvocation,
multiStageProgramInvocation,
runProgramInvocation,
getProgramInvocationOutput,
getEffectiveEnvironment,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Simple.Program.Types
import Distribution.Simple.Utils
import Distribution.Verbosity
import Distribution.Compat.Environment
import qualified Data.Map as Map
import System.FilePath
import System.Exit
( ExitCode(..), exitWith )
-- | Represents a specific invocation of a specific program.
--
-- This is used as an intermediate type between deciding how to call a program
-- and actually doing it. This provides the opportunity to the caller to
-- adjust how the program will be called. These invocations can either be run
-- directly or turned into shell or batch scripts.
--
data ProgramInvocation = ProgramInvocation {
progInvokePath :: FilePath,
progInvokeArgs :: [String],
progInvokeEnv :: [(String, Maybe String)],
-- Extra paths to add to PATH
progInvokePathEnv :: [FilePath],
progInvokeCwd :: Maybe FilePath,
progInvokeInput :: Maybe String,
progInvokeInputEncoding :: IOEncoding,
progInvokeOutputEncoding :: IOEncoding
}
data IOEncoding = IOEncodingText -- locale mode text
| IOEncodingUTF8 -- always utf8
emptyProgramInvocation :: ProgramInvocation
emptyProgramInvocation =
ProgramInvocation {
progInvokePath = "",
progInvokeArgs = [],
progInvokeEnv = [],
progInvokePathEnv = [],
progInvokeCwd = Nothing,
progInvokeInput = Nothing,
progInvokeInputEncoding = IOEncodingText,
progInvokeOutputEncoding = IOEncodingText
}
simpleProgramInvocation :: FilePath -> [String] -> ProgramInvocation
simpleProgramInvocation path args =
emptyProgramInvocation {
progInvokePath = path,
progInvokeArgs = args
}
programInvocation :: ConfiguredProgram -> [String] -> ProgramInvocation
programInvocation prog args =
emptyProgramInvocation {
progInvokePath = programPath prog,
progInvokeArgs = programDefaultArgs prog
++ args
++ programOverrideArgs prog,
progInvokeEnv = programOverrideEnv prog
}
runProgramInvocation :: Verbosity -> ProgramInvocation -> IO ()
runProgramInvocation verbosity
ProgramInvocation {
progInvokePath = path,
progInvokeArgs = args,
progInvokeEnv = [],
progInvokePathEnv = [],
progInvokeCwd = Nothing,
progInvokeInput = Nothing
} =
rawSystemExit verbosity path args
runProgramInvocation verbosity
ProgramInvocation {
progInvokePath = path,
progInvokeArgs = args,
progInvokeEnv = envOverrides,
progInvokePathEnv = extraPath,
progInvokeCwd = mcwd,
progInvokeInput = Nothing
} = do
pathOverride <- getExtraPathEnv envOverrides extraPath
menv <- getEffectiveEnvironment (envOverrides ++ pathOverride)
exitCode <- rawSystemIOWithEnv verbosity
path args
mcwd menv
Nothing Nothing Nothing
when (exitCode /= ExitSuccess) $
exitWith exitCode
runProgramInvocation verbosity
ProgramInvocation {
progInvokePath = path,
progInvokeArgs = args,
progInvokeEnv = envOverrides,
progInvokePathEnv = extraPath,
progInvokeCwd = mcwd,
progInvokeInput = Just inputStr,
progInvokeInputEncoding = encoding
} = do
pathOverride <- getExtraPathEnv envOverrides extraPath
menv <- getEffectiveEnvironment (envOverrides ++ pathOverride)
(_, errors, exitCode) <- rawSystemStdInOut verbosity
path args
mcwd menv
(Just input) True
when (exitCode /= ExitSuccess) $
die' verbosity $ "'" ++ path ++ "' exited with an error:\n" ++ errors
where
input = case encoding of
IOEncodingText -> (inputStr, False)
IOEncodingUTF8 -> (toUTF8 inputStr, True) -- use binary mode for
-- utf8
getProgramInvocationOutput :: Verbosity -> ProgramInvocation -> IO String
getProgramInvocationOutput verbosity
ProgramInvocation {
progInvokePath = path,
progInvokeArgs = args,
progInvokeEnv = envOverrides,
progInvokePathEnv = extraPath,
progInvokeCwd = mcwd,
progInvokeInput = minputStr,
progInvokeOutputEncoding = encoding
} = do
let utf8 = case encoding of IOEncodingUTF8 -> True; _ -> False
decode | utf8 = fromUTF8 . normaliseLineEndings
| otherwise = id
pathOverride <- getExtraPathEnv envOverrides extraPath
menv <- getEffectiveEnvironment (envOverrides ++ pathOverride)
(output, errors, exitCode) <- rawSystemStdInOut verbosity
path args
mcwd menv
input utf8
when (exitCode /= ExitSuccess) $
die' verbosity $ "'" ++ path ++ "' exited with an error:\n" ++ errors
return (decode output)
where
input =
case minputStr of
Nothing -> Nothing
Just inputStr -> Just $
case encoding of
IOEncodingText -> (inputStr, False)
IOEncodingUTF8 -> (toUTF8 inputStr, True) -- use binary mode for utf8
getExtraPathEnv :: [(String, Maybe String)] -> [FilePath] -> NoCallStackIO [(String, Maybe String)]
getExtraPathEnv _ [] = return []
getExtraPathEnv env extras = do
mb_path <- case lookup "PATH" env of
Just x -> return x
Nothing -> lookupEnv "PATH"
let extra = intercalate [searchPathSeparator] extras
path' = case mb_path of
Nothing -> extra
Just path -> extra ++ searchPathSeparator : path
return [("PATH", Just path')]
-- | Return the current environment extended with the given overrides.
-- If an entry is specified twice in @overrides@, the second entry takes
-- precedence.
--
getEffectiveEnvironment :: [(String, Maybe String)]
-> NoCallStackIO (Maybe [(String, String)])
getEffectiveEnvironment [] = return Nothing
getEffectiveEnvironment overrides =
fmap (Just . Map.toList . apply overrides . Map.fromList) getEnvironment
where
apply os env = foldl' (flip update) env os
update (var, Nothing) = Map.delete var
update (var, Just val) = Map.insert var val
-- | Like the unix xargs program. Useful for when we've got very long command
-- lines that might overflow an OS limit on command line length and so you
-- need to invoke a command multiple times to get all the args in.
--
-- It takes four template invocations corresponding to the simple, initial,
-- middle and last invocations. If the number of args given is small enough
-- that we can get away with just a single invocation then the simple one is
-- used:
--
-- > $ simple args
--
-- If the number of args given means that we need to use multiple invocations
-- then the templates for the initial, middle and last invocations are used:
--
-- > $ initial args_0
-- > $ middle args_1
-- > $ middle args_2
-- > ...
-- > $ final args_n
--
multiStageProgramInvocation
:: ProgramInvocation
-> (ProgramInvocation, ProgramInvocation, ProgramInvocation)
-> [String]
-> [ProgramInvocation]
multiStageProgramInvocation simple (initial, middle, final) args =
let argSize inv = length (progInvokePath inv)
+ foldl' (\s a -> length a + 1 + s) 1 (progInvokeArgs inv)
fixedArgSize = maximum (map argSize [simple, initial, middle, final])
chunkSize = maxCommandLineSize - fixedArgSize
in case splitChunks chunkSize args of
[] -> [ simple ]
[c] -> [ simple `appendArgs` c ]
[c,c'] -> [ initial `appendArgs` c ]
++ [ final `appendArgs` c']
(c:cs) -> [ initial `appendArgs` c ]
++ [ middle `appendArgs` c'| c' <- init cs ]
++ [ final `appendArgs` c'| let c' = last cs ]
where
inv `appendArgs` as = inv { progInvokeArgs = progInvokeArgs inv ++ as }
splitChunks len = unfoldr $ \s ->
if null s then Nothing
else Just (chunk len s)
chunk len (s:_) | length s >= len = error toolong
chunk len ss = chunk' [] len ss
chunk' acc _ [] = (reverse acc,[])
chunk' acc len (s:ss)
| len' < len = chunk' (s:acc) (len-len'-1) ss
| otherwise = (reverse acc, s:ss)
where len' = length s
toolong = "multiStageProgramInvocation: a single program arg is larger "
++ "than the maximum command line length!"
--FIXME: discover this at configure time or runtime on unix
-- The value is 32k on Windows and posix specifies a minimum of 4k
-- but all sensible unixes use more than 4k.
-- we could use getSysVar ArgumentLimit but that's in the unix lib
--
maxCommandLineSize :: Int
maxCommandLineSize = 30 * 1024
| mydaum/cabal | Cabal/Distribution/Simple/Program/Run.hs | bsd-3-clause | 9,600 | 0 | 16 | 2,567 | 1,996 | 1,104 | 892 | 188 | 7 |
{-# LANGUAGE TypeFamilies #-}
-- | Type classes for Toss abstraction.
module Pos.Chain.Ssc.Toss.Class
( MonadTossRead (..)
, MonadTossEnv (..)
, MonadToss (..)
) where
import Universum hiding (id)
import Control.Monad.Except (ExceptT)
import Control.Monad.Trans (MonadTrans)
import Pos.Chain.Genesis as Genesis (Config)
import Pos.Chain.Lrc.Types (RichmenStakes)
import Pos.Chain.Ssc.Commitment (SignedCommitment)
import Pos.Chain.Ssc.CommitmentsMap (CommitmentsMap)
import Pos.Chain.Ssc.Opening (Opening)
import Pos.Chain.Ssc.OpeningsMap (OpeningsMap)
import Pos.Chain.Ssc.SharesMap (InnerSharesMap, SharesMap)
import Pos.Chain.Ssc.VssCertificate (VssCertificate)
import Pos.Chain.Ssc.VssCertificatesMap (VssCertificatesMap)
import Pos.Chain.Update.BlockVersionData (BlockVersionData)
import Pos.Core (EpochIndex, EpochOrSlot, StakeholderId)
import Pos.Util.Wlog (WithLogger)
----------------------------------------------------------------------------
-- Read-only
----------------------------------------------------------------------------
-- | Type class which provides functions necessary for read-only
-- verification of SSC data.
class (Monad m, WithLogger m) =>
MonadTossRead m where
-- | Get 'CommitmentsMap' with all commitments.
getCommitments :: m CommitmentsMap
-- | Get 'OpeningsMap' with all openings.
getOpenings :: m OpeningsMap
-- | Get 'SharesMap' with all shares.
getShares :: m SharesMap
-- | Get 'VssCertificatesMap' with all VSS certificates.
getVssCertificates :: m VssCertificatesMap
-- | Retrieve all stable 'VssCertificate's for given epoch.
getStableCertificates :: Genesis.Config -> EpochIndex -> m VssCertificatesMap
-- | Default implementations for 'MonadTrans'.
default getCommitments :: (MonadTrans t, MonadTossRead m', t m' ~ m) =>
m CommitmentsMap
getCommitments = lift getCommitments
default getOpenings :: (MonadTrans t, MonadTossRead m', t m' ~ m) =>
m OpeningsMap
getOpenings = lift getOpenings
default getShares :: (MonadTrans t, MonadTossRead m', t m' ~ m) =>
m SharesMap
getShares = lift getShares
default getVssCertificates :: (MonadTrans t, MonadTossRead m', t m' ~ m) =>
m VssCertificatesMap
getVssCertificates = lift getVssCertificates
default getStableCertificates :: (MonadTrans t, MonadTossRead m', t m' ~ m) =>
Genesis.Config -> EpochIndex -> m VssCertificatesMap
getStableCertificates genesisConfig = lift . getStableCertificates genesisConfig
instance MonadTossRead m => MonadTossRead (ReaderT s m)
instance MonadTossRead m => MonadTossRead (StateT s m)
instance MonadTossRead m => MonadTossRead (ExceptT s m)
----------------------------------------------------------------------------
-- Environment
----------------------------------------------------------------------------
class Monad m => MonadTossEnv m where
-- | Retrieve richmen for given epoch if they are known.
getRichmen :: EpochIndex -> m (Maybe RichmenStakes)
-- | Retrieve current adopted block data
getAdoptedBVData :: m BlockVersionData
default getRichmen :: (MonadTrans t, MonadTossEnv m', t m' ~ m) =>
EpochIndex -> m (Maybe RichmenStakes)
getRichmen = lift . getRichmen
default getAdoptedBVData :: (MonadTrans t, MonadTossEnv m', t m' ~ m) =>
m BlockVersionData
getAdoptedBVData = lift getAdoptedBVData
instance MonadTossEnv m => MonadTossEnv (ReaderT s m)
instance MonadTossEnv m => MonadTossEnv (StateT s m)
instance MonadTossEnv m => MonadTossEnv (ExceptT s m)
----------------------------------------------------------------------------
-- Writeable
----------------------------------------------------------------------------
-- | Type class which provides function necessary for verification of
-- SSC data with ability to modify state.
class MonadTossRead m =>
MonadToss m where
-- | Put 'SignedCommitment' into state.
putCommitment :: SignedCommitment -> m ()
-- | Put 'Opening' from given stakeholder into state.
putOpening :: StakeholderId -> Opening -> m ()
-- | Put 'InnerShares' from given stakeholder into state.
putShares :: StakeholderId -> InnerSharesMap -> m ()
-- | Put 'VssCertificate' into state.
putCertificate :: VssCertificate -> m ()
-- | Reset Commitments and Openings.
resetCO :: m ()
-- | Reset Shares.
resetShares :: m ()
-- | Delete commitment of given stakeholder.
delCommitment :: StakeholderId -> m ()
-- | Delete opening of given stakeholder.
delOpening :: StakeholderId -> m ()
-- | Delete shares of given stakeholder.
delShares :: StakeholderId -> m ()
-- | This function is called when block with given 'EpochOrSlot' is applied.
setEpochOrSlot :: EpochOrSlot -> m ()
-- | Default implementations for 'MonadTrans'.
default putCommitment :: (MonadTrans t, MonadToss m', t m' ~ m) =>
SignedCommitment -> m ()
putCommitment = lift . putCommitment
default putOpening :: (MonadTrans t, MonadToss m', t m' ~ m) =>
StakeholderId -> Opening -> m ()
putOpening id = lift . putOpening id
default putShares :: (MonadTrans t, MonadToss m', t m' ~ m) =>
StakeholderId -> InnerSharesMap -> m ()
putShares id = lift . putShares id
default putCertificate :: (MonadTrans t, MonadToss m', t m' ~ m) =>
VssCertificate -> m ()
putCertificate = lift . putCertificate
default resetCO :: (MonadTrans t, MonadToss m', t m' ~ m) =>
m ()
resetCO = lift resetCO
default resetShares :: (MonadTrans t, MonadToss m', t m' ~ m) =>
m ()
resetShares = lift resetShares
default delCommitment :: (MonadTrans t, MonadToss m', t m' ~ m) =>
StakeholderId -> m ()
delCommitment = lift . delCommitment
default delOpening :: (MonadTrans t, MonadToss m', t m' ~ m) =>
StakeholderId -> m ()
delOpening = lift . delOpening
default delShares :: (MonadTrans t, MonadToss m', t m' ~ m) =>
StakeholderId -> m ()
delShares = lift . delShares
default setEpochOrSlot :: (MonadTrans t, MonadToss m', t m' ~ m) =>
EpochOrSlot -> m ()
setEpochOrSlot = lift . setEpochOrSlot
instance MonadToss m => MonadToss (ReaderT s m)
instance MonadToss m => MonadToss (StateT s m)
instance MonadToss m => MonadToss (ExceptT s m)
| input-output-hk/pos-haskell-prototype | chain/src/Pos/Chain/Ssc/Toss/Class.hs | mit | 6,575 | 0 | 12 | 1,453 | 1,574 | 831 | 743 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
module AI.Visualizations
( networkHistogram
, weightList
, biasList
) where
import AI.Layer
import AI.Network
import AI.Network.FeedForwardNetwork
import AI.Neuron
import Numeric.LinearAlgebra
import Data.Foldable (foldMap)
import GHC.Float
import Graphics.Histogram
import AI.Trainer
weightList :: FeedForwardNetwork -> [Double]
weightList = toList . flatten . weightMatrix <=< layers
biasList :: FeedForwardNetwork -> [Double]
biasList = toList . biasVector <=< layers
networkHistogram :: FilePath -> (FeedForwardNetwork -> [Double]) -> FeedForwardNetwork -> IO ()
networkHistogram filename listFunction n = do
let hist = histogram binSturges (listFunction n)
plot filename hist
return ()
| jbarrow/LambdaNet | AI/Visualizations.hs | mit | 848 | 0 | 12 | 212 | 203 | 111 | 92 | -1 | -1 |
--------------------------------------------------------------------------
-- Copyright (c) 2007-2013, ETH Zurich.
-- All rights reserved.
--
-- This file is distributed under the terms in the attached LICENSE file.
-- If you do not find this file, copies can be found by writing to:
-- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
--
-- Architectural definitions for Barrelfish on ARMv5 ISA.
--
-- The build target is the XScale with XScale cpu.
--
--------------------------------------------------------------------------
module XScale where
import HakeTypes
import Path
import qualified Config
import qualified ArchDefaults
-------------------------------------------------------------------------
--
-- Architecture specific definitions for ARM
--
-------------------------------------------------------------------------
arch = "xscale"
archFamily = "arm"
compiler = "arm-none-linux-gnueabi-gcc"
objcopy = "arm-none-linux-gnueabi-objcopy"
objdump = "arm-none-linux-gnueabi-objdump"
ar = "arm-none-linux-gnueabi-ar"
ranlib = "arm-none-linux-gnueabi-ranlib"
cxxcompiler = "arm-none-linux-gnueabi-g++"
ourCommonFlags = [ Str "-Wno-packed-bitfield-compat",
Str "-fno-unwind-tables",
Str "-fshort-enums",
Str "-mcpu=xscale",
Str "-mbig-endian",
Str "-mapcs",
Str "-mabi=aapcs-linux",
Str "-msingle-pic-base",
Str "-mpic-register=r10",
Str "-DPIC_REGISTER=R10",
Str "-fpic",
Str "-ffixed-r9",
Str "-DTHREAD_REGISTER=R9" ]
cFlags = ArchDefaults.commonCFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
cxxFlags = ArchDefaults.commonCxxFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
cDefines = ArchDefaults.cDefines options
ourLdFlags = [ Str "-Wl,-section-start,.text=0x400000",
Str "-Wl,-section-start,.data=0x600000",
Str "-mcpu=xscale",
Str "-mbig-endian" ]
ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags
ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags
stdLibs = ArchDefaults.stdLibs arch ++ [ Str "-lgcc" ]
options = (ArchDefaults.options arch archFamily) {
optFlags = cFlags,
optCxxFlags = cxxFlags,
optDefines = cDefines,
optDependencies =
[ PreDep InstallTree arch "/include/errors/errno.h",
PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h",
PreDep InstallTree arch "/include/asmoffsets.h",
PreDep InstallTree arch "/include/romfs_size.h" ],
optLdFlags = ldFlags,
optLdCxxFlags = ldCxxFlags,
optLibs = stdLibs,
optInterconnectDrivers = ["lmp"],
optFlounderBackends = ["lmp"]
}
--
-- Compilers
--
cCompiler = ArchDefaults.cCompiler arch compiler
cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler
makeDepend = ArchDefaults.makeDepend arch compiler
makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler
cToAssembler = ArchDefaults.cToAssembler arch compiler
assembler = ArchDefaults.assembler arch compiler
archive = ArchDefaults.archive arch
linker = ArchDefaults.linker arch compiler
cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler
--
-- The kernel is "different"
--
kernelCFlags = [ Str s | s <- [ "-fno-builtin",
"-fno-unwind-tables",
"-fshort-enums",
"-nostdinc",
"-std=c99",
"-mcpu=xscale",
"-mbig-endian",
"-mapcs",
"-mabi=aapcs-linux",
"-fPIE",
"-U__linux__",
"-Wall",
"-Wshadow",
"-Wstrict-prototypes",
"-Wold-style-definition",
"-Wmissing-prototypes",
"-Wmissing-declarations",
"-Wmissing-field-initializers",
"-Wno-implicit-function-declaration",
"-Wredundant-decls",
"-Werror",
"-imacros deputy/nodeputy.h",
"-fpie",
"-fno-stack-check",
"-ffreestanding",
"-fomit-frame-pointer",
"-mno-long-calls",
"-Wmissing-noreturn",
"-mno-apcs-stack-check",
"-mno-apcs-reentrant",
"-msingle-pic-base",
"-mpic-register=r10",
"-DPIC_REGISTER=R10",
"-ffixed-r9",
"-DTHREAD_REGISTER=R9" ]]
kernelLdFlags = [ Str "-Wl,-N",
NStr "-Wl,-Map,", Out arch "kernel.map",
Str "-fno-builtin",
Str "-nostdlib",
Str "-Wl,--fatal-warnings",
Str "-mcpu=xscale",
Str "-mbig-endian"
]
--
-- Link the kernel (CPU Driver)
--
linkKernel :: Options -> [String] -> [String] -> String -> HRule
linkKernel opts objs libs kbin =
let linkscript = "/kernel/linker.lds"
kbootable = kbin ++ ".bin"
in
Rules [ Rule ([ Str compiler, Str Config.cOptFlags,
NStr "-T", In BuildTree arch linkscript,
Str "-o", Out arch kbin
]
++ (optLdFlags opts)
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
[ Str "-lgcc" ]
),
-- Edit ELF header so qemu-system-arm will treat it as a Linux kernel
Rule [ In SrcTree "src" "/tools/arm-mkbootelf.sh",
Str objdump, In BuildTree arch kbin, Out arch (kbootable)],
-- Generate kernel assembly dump
Rule [ Str (objdump ++ " -d -M reg-names-raw"),
In SrcTree arch kbin, Str ">", Out arch (kbin ++ ".asm")],
Rule [ Str "cpp",
NStr "-I", NoDep SrcTree "src" "/kernel/include/arch/xscale",
Str "-D__ASSEMBLER__",
Str "-P", In SrcTree "src" "/kernel/arch/xscale/linker.lds.in",
Out arch linkscript
]
]
| daleooo/barrelfish | hake/XScale.hs | mit | 6,935 | 8 | 17 | 2,674 | 1,033 | 573 | 460 | 128 | 1 |
module Chapter6Exercises where
import Data.List (sort)
data Person = Person Bool deriving Show
printPerson :: Person -> IO ()
printPerson person = putStrLn (show person)
-- printPerson (Person False)
data Mood = Blah
| Woot deriving (Show, Eq)
settleDown :: Mood -> Mood
settleDown x = if x == Woot
then Blah
else x
-- settleDown Blah
-- settleDown Woot
type Subject = String
type Verb = String
type Object = String
data Sentence =
Sentence Subject Verb Object
deriving (Eq, Show)
s1 = Sentence "dogs" "drool"
s2 = Sentence "Julie" "loves" "dogs"
data Rocks =
Rocks String deriving (Eq, Show)
data Yeah =
Yeah Bool deriving (Eq, Show)
data Papu =
Papu Rocks Yeah
deriving (Eq, Show)
equalityForAll :: Papu -> Papu -> Bool
equalityForAll p p' = p == p'
-- no instance of Ord
-- comparePapus :: Papu -> Papu -> Bool
-- comparePapus p p' = p > p
-- Chapter 6 "Match the types"
-- 1
-- -- i :: Num a => a
-- i :: a
-- --i = 1
-- i = 'c'
--f :: Float
--f :: Num a => a
f :: Fractional a => a
f = 1.0
--f' :: Float
f' :: RealFrac a => a
f' = 1.0
-- freud :: a -> a
freud :: Ord a => a -> a
freud x = x
--freud' :: a -> a
freud' :: Int -> Int
freud' x = x
myX = 1 :: Int
sigmund :: Int -> Int -- fine
-- sigmund :: a -> a -- not fine
sigmund x = myX
myX' = 1 :: Int
sigmund' :: Int -> Int -- fine
-- sigmund' :: Num a => a -> a -- not fine
sigmund' x = myX'
-- jung :: Ord a => [a] -> a
jung :: [Int] -> Int
jung xs = head (sort xs)
-- young :: [Char] -> Char
young :: Ord a => [a] -> a
young xs = head (sort xs)
mySort :: [Char] -> [Char]
mySort = sort
signifier :: [Char] -> Char -- fine
-- signifier :: Ord a => [a] -> a -- not fine
signifier xs = head (mySort xs)
chk :: Eq b => (a -> b) -> a -> b -> Bool
chk f x y = f x == y -- Eq to what?
arith :: Num b
=> (a -> b)
-> Integer
-> a
-> b
arith f x y = f y
| brodyberg/Notes | ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/Chapter6.hs | mit | 1,952 | 0 | 8 | 564 | 621 | 344 | 277 | 58 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
-- | This module is a complete description of the data structure used in Inner Ear
-- to record user actions/choices, in order both to inform the adaptive generation
-- of new ear-training questions for that user, and to provide data for research analysis.
module InnerEar.Types.Data where
import Text.JSON
import Text.JSON.Generic
import Data.Tuple.Select
import Data.Tuple.Curry
import Data.Time.Clock
import Text.Read
import InnerEar.Types.Utility
import InnerEar.Types.ExerciseId
import InnerEar.Types.Handle
-- | Each exercise has unique strictly typed representations so there must be a type for the data
-- specific to each exercise. (And this type, Datum c q a e, like all of the types in this module, is
-- an automatically-derived instance of JSON, to facilitate communication back and forth with a server.)
data Datum c q a e s = -- c is configuration type, q is question type, a is answer type, e is evaluation type, s is exercise store type
Started |
Configured c |
NewQuestion c q a |
ListenedQuestion c q a |
ListenedReference c q a |
Answered a e e c q a | -- their choice, new short- and long-term evaluation plus context
ListenedExplore a c q a | -- for exploratory listening to possible answers
Reflection String |
Store s |
Ended
deriving (Show,Eq,Data,Typeable)
-- | The functions in the definition of an exercise will return some specific type Datum c q a e
-- But to treat the data resulting from all exercises equally we need to be able to convert that
-- to and from a single data type, ExerciseDatum, using the functions toExerciseDatum and toDatum below.
data ExerciseDatum =
ExerciseStarted |
ExerciseConfigured String |
ExerciseNewQuestion String String String |
ExerciseListenedQuestion String String String |
ExerciseListenedReference String String String |
ExerciseAnswered String String String String String String |
ExerciseListenedExplore String String String String |
ExerciseReflection String |
ExerciseStore String |
ExerciseEnded
deriving (Show,Eq,Data,Typeable)
toExerciseDatum :: (Data c,Data q,Data a,Data e,Data s) => Datum c q a e s -> ExerciseDatum
toExerciseDatum Started = ExerciseStarted
toExerciseDatum (Configured c) = ExerciseConfigured $ encodeJSON c
toExerciseDatum (NewQuestion c q a) = ExerciseNewQuestion (encodeJSON c) (encodeJSON q) (encodeJSON a)
toExerciseDatum (ListenedQuestion c q a) = ExerciseListenedQuestion (encodeJSON c) (encodeJSON q) (encodeJSON a)
toExerciseDatum (ListenedReference c q a) = ExerciseListenedReference (encodeJSON c) (encodeJSON q) (encodeJSON a)
toExerciseDatum (Answered ia e1 e2 c q a) = ExerciseAnswered (encodeJSON ia) (encodeJSON e1) (encodeJSON e2) (encodeJSON c) (encodeJSON q) (encodeJSON a)
toExerciseDatum (ListenedExplore a1 c q a2) = ExerciseListenedExplore (encodeJSON a1) (encodeJSON c) (encodeJSON q) (encodeJSON a2)
toExerciseDatum (Reflection r) = ExerciseReflection r
toExerciseDatum (Store s) = ExerciseStore (encodeJSON s)
toExerciseDatum Ended = ExerciseEnded
toDatum :: (JSON c, JSON q, JSON a, JSON e, JSON s) => ExerciseDatum -> Result (Datum c q a e s)
toDatum ExerciseStarted = return Started
toDatum (ExerciseConfigured j) = Configured <$> decode j
toDatum (ExerciseNewQuestion c q a) = NewQuestion <$> decode c <*> decode q <*> decode a
toDatum (ExerciseListenedQuestion c q a) = ListenedQuestion <$> decode c <*> decode q <*> decode a
toDatum (ExerciseListenedReference c q a) = ListenedReference <$> decode c <*> decode q <*> decode a
toDatum (ExerciseAnswered ia e1 e2 c q a) = Answered <$> decode ia <*> decode e1 <*> decode e2 <*> decode c <*> decode q <*> decode a
toDatum (ExerciseListenedExplore a1 c q a2) = ListenedExplore <$> decode a1 <*> decode c <*> decode q <*> decode a2
toDatum (ExerciseReflection r) = return $ Reflection r
toDatum (ExerciseStore s) = Store <$> decode s
toDatum ExerciseEnded = return Ended
toDatum' :: (JSON c, JSON q, JSON a, JSON e, JSON s) => ExerciseDatum -> Maybe (Datum c q a e s)
toDatum' = f . toDatum
where f (Ok x) = Just x
f _ = Nothing
-- | Some events of interest are not tied to a particular ear-training exercise.
-- For these, we have the type SessionDatum.
data SessionDatum = SessionStart | SessionEnd | AuthenticationFailure deriving (Show,Eq,Data,Typeable)
-- A Point of data, then, is either a tuple of (ExerciseId,ExerciseDatum) or SessionDatum
-- These points are what a running exercise widget (created using createExercise with a fully
-- defined Exercise) will both report upwards to the top level of the application, and use
-- in order to adaptively generate new questions.
type Time = UTCTime
data Point = Point {
datum :: Either (ExerciseId,ExerciseDatum) SessionDatum,
time :: Time
} deriving (Eq,Data,Typeable)
instance Show Point where
show (Point d t) = show d ++ " (warning: not showing time)"
datumToPoint :: Either (ExerciseId,ExerciseDatum) SessionDatum -> IO Point
datumToPoint x = getCurrentTime >>= return . Point x
-- | The top level of our data structure is the Record, which is used for passing
-- data about an authenticated user back and forth between the server and the client.
-- When Inner Ear is used without a login/server, Records will play no role.
data Record = Record {
userHandle :: Handle,
point :: Point
} deriving (Show,Eq,Data,Typeable)
data StoreDB = StoreDB {
storeHandle :: Handle,
storeId :: ExerciseId,
storeValue :: String, -- JSON representation of exercise store
storeTime :: Time
} deriving (Eq,Data,Typeable)
instance Show StoreDB where
show x = show (storeHandle x) ++ " " ++ show (storeId x) ++ " " ++ show (storeValue x)
recordToMaybeStoreDB :: Record -> Maybe StoreDB
recordToMaybeStoreDB (Record h (Point (Left (i,ExerciseStore s)) t)) = Just (StoreDB h i s t)
recordToMaybeStoreDB _ = Nothing
| JamieBeverley/InnerEar | src/InnerEar/Types/Data.hs | gpl-3.0 | 5,867 | 0 | 13 | 1,012 | 1,515 | 790 | 725 | 86 | 2 |
{-# 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.EC2.ReplaceNetworkAclAssociation
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Changes which network ACL a subnet is associated with. By default when you
-- create a subnet, it's automatically associated with the default network ACL.
-- For more information about network ACLs, see <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html Network ACLs> in the /AmazonVirtual Private Cloud User Guide/.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceNetworkAclAssociation.html>
module Network.AWS.EC2.ReplaceNetworkAclAssociation
(
-- * Request
ReplaceNetworkAclAssociation
-- ** Request constructor
, replaceNetworkAclAssociation
-- ** Request lenses
, rnaaAssociationId
, rnaaDryRun
, rnaaNetworkAclId
-- * Response
, ReplaceNetworkAclAssociationResponse
-- ** Response constructor
, replaceNetworkAclAssociationResponse
-- ** Response lenses
, rnaarNewAssociationId
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data ReplaceNetworkAclAssociation = ReplaceNetworkAclAssociation
{ _rnaaAssociationId :: Text
, _rnaaDryRun :: Maybe Bool
, _rnaaNetworkAclId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'ReplaceNetworkAclAssociation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rnaaAssociationId' @::@ 'Text'
--
-- * 'rnaaDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'rnaaNetworkAclId' @::@ 'Text'
--
replaceNetworkAclAssociation :: Text -- ^ 'rnaaAssociationId'
-> Text -- ^ 'rnaaNetworkAclId'
-> ReplaceNetworkAclAssociation
replaceNetworkAclAssociation p1 p2 = ReplaceNetworkAclAssociation
{ _rnaaAssociationId = p1
, _rnaaNetworkAclId = p2
, _rnaaDryRun = Nothing
}
-- | The ID of the current association between the original network ACL and the
-- subnet.
rnaaAssociationId :: Lens' ReplaceNetworkAclAssociation Text
rnaaAssociationId =
lens _rnaaAssociationId (\s a -> s { _rnaaAssociationId = a })
rnaaDryRun :: Lens' ReplaceNetworkAclAssociation (Maybe Bool)
rnaaDryRun = lens _rnaaDryRun (\s a -> s { _rnaaDryRun = a })
-- | The ID of the new network ACL to associate with the subnet.
rnaaNetworkAclId :: Lens' ReplaceNetworkAclAssociation Text
rnaaNetworkAclId = lens _rnaaNetworkAclId (\s a -> s { _rnaaNetworkAclId = a })
newtype ReplaceNetworkAclAssociationResponse = ReplaceNetworkAclAssociationResponse
{ _rnaarNewAssociationId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'ReplaceNetworkAclAssociationResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rnaarNewAssociationId' @::@ 'Maybe' 'Text'
--
replaceNetworkAclAssociationResponse :: ReplaceNetworkAclAssociationResponse
replaceNetworkAclAssociationResponse = ReplaceNetworkAclAssociationResponse
{ _rnaarNewAssociationId = Nothing
}
-- | The ID of the new association.
rnaarNewAssociationId :: Lens' ReplaceNetworkAclAssociationResponse (Maybe Text)
rnaarNewAssociationId =
lens _rnaarNewAssociationId (\s a -> s { _rnaarNewAssociationId = a })
instance ToPath ReplaceNetworkAclAssociation where
toPath = const "/"
instance ToQuery ReplaceNetworkAclAssociation where
toQuery ReplaceNetworkAclAssociation{..} = mconcat
[ "AssociationId" =? _rnaaAssociationId
, "DryRun" =? _rnaaDryRun
, "NetworkAclId" =? _rnaaNetworkAclId
]
instance ToHeaders ReplaceNetworkAclAssociation
instance AWSRequest ReplaceNetworkAclAssociation where
type Sv ReplaceNetworkAclAssociation = EC2
type Rs ReplaceNetworkAclAssociation = ReplaceNetworkAclAssociationResponse
request = post "ReplaceNetworkAclAssociation"
response = xmlResponse
instance FromXML ReplaceNetworkAclAssociationResponse where
parseXML x = ReplaceNetworkAclAssociationResponse
<$> x .@? "newAssociationId"
| kim/amazonka | amazonka-ec2/gen/Network/AWS/EC2/ReplaceNetworkAclAssociation.hs | mpl-2.0 | 5,002 | 0 | 9 | 987 | 559 | 339 | 220 | 68 | 1 |
{-|
Module : Examples.Rover.Model
Description : Model for the Rover example
Copyright : (c) 2017 Pascal Poizat
License : Apache-2.0 (see the file LICENSE)
Maintainer : [email protected]
Stability : experimental
Portability : unknown
-}
module Examples.Rover.Model where
import Numeric.Natural
import Data.Map.Strict
import Models.Events
import Models.LabelledTransitionSystem
import Models.Name
import Veca.Model
--
-- The Rover Case Study
--
askVid :: Operation
askVid = mkOperation "askVid"
getVid :: Operation
getVid = mkOperation "getVid"
storeVid :: Operation
storeVid = mkOperation "storeVid"
askPic :: Operation
askPic = mkOperation "askPic"
getPic :: Operation
getPic = mkOperation "getPic"
storePic :: Operation
storePic = mkOperation "storePic"
run :: Operation
run = mkOperation "run"
m1 :: Message
m1 = mkMessage "m1" "{}"
m1s :: Message
m1s = mkMessage "m1s" "{url:String,file:File}"
m4 :: Message
m4 = mkMessage "m4" "{url:String}"
nameController :: VName
nameController = Name ["controller"]
nameStoreUnit :: VName
nameStoreUnit = Name ["storeUnit"]
namePictureUnit :: VName
namePictureUnit = Name ["pictureUnit"]
nameVideoUnit :: VName
nameVideoUnit = Name ["videoUnit"]
nameAcquisitionUnit :: VName
nameAcquisitionUnit = Name ["acquisitionUnit"]
nameRover :: VName
nameRover = Name ["rover"]
c :: VName
c = Name ["c"]
a :: VName
a = Name ["a"]
s :: VName
s = Name ["s"]
p :: VName
p = Name ["p"]
v :: VName
v = Name ["v"]
r :: VName
r = Name ["r"]
n1 :: VName
n1 = Name ["1"]
n2 :: VName
n2 = Name ["2"]
n3 :: VName
n3 = Name ["3"]
n4 :: VName
n4 = Name ["4"]
n5 :: VName
n5 = Name ["5"]
n6 :: VName
n6 = Name ["6"]
n7 :: VName
n7 = Name ["7"]
--
-- Controller
--
controllerUnit :: ComponentInstance
controllerUnit = ComponentInstance c $ BasicComponent nameController sig beh
where
m2 = mkMessage "m2" "{urlVid:String,urlPic:String}"
m3 = mkMessage "m3" "{url:String}"
sig = Signature
[run]
[askVid, askPic]
(fromList [(run, m1), (askVid, m1), (askPic, m1)])
(fromList [(run, Just m2), (askVid, Just m3), (askPic, Just m3)])
beh = LabelledTransitionSystem
mempty
[ receive run
, reply run
, invoke askVid
, result askVid
, invoke askPic
, result askPic
]
(State <$> ["0", "1", "2", "3", "4", "5", "6"])
(State "0")
[State "6"]
[ "0" -| receive run |-> "1"
, "1" -| invoke askVid |-> "2"
, "2" -| result askVid |-> "3"
, "3" -| invoke askPic |-> "4"
, "4" -| result askPic |-> "5"
, "5" -| reply run |-> "6"
]
--
-- Store Unit
--
storeUnit :: ComponentInstance
storeUnit = ComponentInstance s $ BasicComponent nameStoreUnit sig beh
where
sig = Signature [storePic, storeVid]
[]
(fromList [(storePic, m1s), (storeVid, m1s)])
(fromList [(storePic, Nothing), (storeVid, Nothing)])
beh = LabelledTransitionSystem
mempty
[tau (TimeValue 2) (TimeValue 4), receive storePic, receive storeVid]
(State <$> ["0", "1"])
(State "0")
[State "0"]
[ "0" -| receive storePic |-> "1"
, "0" -| receive storeVid |-> "1"
, "1" -| tau (TimeValue 2) (TimeValue 4) |-> "0"
]
--
-- Picture Unit
--
pictureUnit :: ComponentInstance
pictureUnit = ComponentInstance p $ BasicComponent namePictureUnit sig beh
where
m2 = mkMessage "m2" "{data:RawPicture}"
sig = Signature
[askPic]
[getPic, storePic]
(fromList [(askPic, m1), (getPic, m1), (storePic, m1s)])
(fromList [(askPic, Just m4), (getPic, Just m2), (storePic, Nothing)])
beh = LabelledTransitionSystem
mempty
[ receive askPic
, reply askPic
, invoke getPic
, result getPic
, invoke storePic
, tau (TimeValue 2) (TimeValue 4)
]
(State <$> ["0", "1", "2", "3", "4", "5", "6"])
(State "0")
[State "6"]
[ "0" -| receive askPic |-> "1"
, "1" -| invoke getPic |-> "2"
, "2" -| result getPic |-> "3"
, "3" -| tau (TimeValue 2) (TimeValue 4) |-> "4"
, "3" -| tau (TimeValue 2) (TimeValue 4) |-> "5"
, "4" -| invoke storePic |-> "5"
, "5" -| reply askPic |-> "6"
]
--
-- Video Unit
--
vut1 :: VTransition
vut1 = "0" -| receive askVid |-> "1"
vut2 :: VTransition
vut2 = "1" -| invoke getVid |-> "2"
vut3 :: VTransition
vut3 = "2" -| result getVid |-> "3"
vut4 :: VTransition
vut4 = "3" -| tau (TimeValue 2) (TimeValue 4) |-> "4"
vut5 :: VTransition
vut5 = "3" -| tau (TimeValue 2) (TimeValue 4) |-> "5"
vut6 :: VTransition
vut6 = "4" -| invoke storeVid |-> "5"
vut7 :: VTransition
vut7 = "5" -| reply askVid |-> "6"
videoUnit :: ComponentInstance
videoUnit = ComponentInstance v $ BasicComponent nameVideoUnit sig beh
where
m2 = mkMessage "m2" "{data:RawVideo}"
sig = Signature
[askVid]
[getVid, storeVid]
(fromList [(askVid, m1), (getVid, m1), (storeVid, m1s)])
(fromList [(askVid, Just m4), (getVid, Just m2), (storeVid, Nothing)])
beh = LabelledTransitionSystem
mempty
[ receive askVid
, reply askVid
, invoke getVid
, result getVid
, invoke storeVid
, tau (TimeValue 2) (TimeValue 4)
]
(State <$> ["0", "1", "2", "3", "4", "5", "6"])
(State "0")
[State "6"]
[vut1, vut2, vut3, vut4, vut5, vut6, vut7]
--
-- Acquisition Unit
--
acquisitionUnit :: ComponentInstance
acquisitionUnit = ComponentInstance a
$ CompositeComponent nameAcquisitionUnit sig cs inb exb
where
m2a = mkMessage "m2a" "{data:RawPicture}"
m2b = mkMessage "m2b" "{data:RawVideo}"
sig = Signature
[askPic, askVid]
[getPic, getVid, storePic, storeVid]
(fromList
[ (askPic , m1)
, (getPic , m1)
, (storePic, m1s)
, (askVid , m1)
, (getVid , m1)
, (storeVid, m1s)
]
)
(fromList
[ (askPic , Just m4)
, (getPic , Just m2a)
, (storePic, Nothing)
, (askVid , Just m4)
, (getVid , Just m2b)
, (storeVid, Nothing)
]
)
cs = [pictureUnit, videoUnit]
inb = []
exb =
[ n1 @: self # askPic ==> p # askPic
, n2 @: self # askVid ==> v # askVid
, n3 @: p # getPic ==> self # getPic
, n4 @: v # getVid ==> self # getVid
, n5 @: p # storePic ==> self # storePic
, n6 @: v # storeVid ==> self # storeVid
]
--
-- Rover
--
rover :: ComponentInstance
rover = ComponentInstance r (CompositeComponent nameRover sig cs inb exb)
where
m2a = mkMessage "m2a" "{data:RawPicture}"
m2b = mkMessage "m2b" "{data:RawVideo}"
store = mkOperation "store"
sig = Signature
[run]
[getPic, getVid]
(fromList [(run, m1), (getPic, m1), (getVid, m1)])
(fromList [(run, Nothing), (getPic, Just m2a), (getVid, Just m2b)])
cs = [controllerUnit, acquisitionUnit, storeUnit]
inb =
[ n1 @: c # askPic --> a # askPic
, n2 @: c # askVid --> a # askVid
, n3 @: a # storePic --> s # storePic
, n4 @: a # storeVid --> s # storeVid
]
exb =
[ n5 @: self # run ==> c # run
, n6 @: a # getPic ==> self # getPic
, n7 @: a # getVid ==> self # getVid
]
--
-- helpers (to be moved to VECA DSL if useful)
--
mkMessageType :: String -> MessageType
mkMessageType = MessageType
mkMessage :: String -> String -> Message
mkMessage m t = Message (Name [m]) $ mkMessageType t
mkOperation :: String -> Operation
mkOperation o = Operation $ Name [o]
receive :: Operation -> VLabel
receive = EventLabel . CReceive
reply :: Operation -> VLabel
reply = EventLabel . CReply
invoke :: Operation -> VLabel
invoke = EventLabel . CInvoke
result :: Operation -> VLabel
result = EventLabel . CResult
tau :: TimeStep -> TimeStep -> VLabel
tau = InternalLabel
theta :: Timeout -> VLabel
theta = TimeoutLabel
infix 1 |-> --
(|->) :: (a, b) -> a -> Transition b a
(s1, l) |-> s2 = Transition (State s1) l (State s2)
infix 2 -| --
(-|) :: a -> b -> (a, b)
s1 -| l = (s1, l)
infix 2 ==> --
(==>) :: (VName, JoinPoint) -> JoinPoint -> Binding
(i, j1) ==> j2 = Binding External i j1 j2
infix 2 --> --
(-->) :: (VName, JoinPoint) -> JoinPoint -> Binding
(i, j1) --> j2 = Binding Internal i j1 j2
infix 4 # --
(#) :: VName -> Operation -> JoinPoint
n # o = JoinPoint n o
infix 3 @: --
(@:) :: VName -> JoinPoint -> (VName, JoinPoint)
i @: j = (i, j)
| pascalpoizat/veca-haskell | src/Examples/Rover/Model.hs | apache-2.0 | 8,285 | 0 | 13 | 2,032 | 3,000 | 1,665 | 1,335 | 253 | 1 |
module Tests.Language.Interpreter.Loops
( interpreterLoopTests
)
where
import Test.Framework ( Test
, testGroup
)
import Test.Framework.Providers.HUnit ( testCase )
import Test.HUnit ( Assertion )
import TestHelpers.Util ( gfxTest )
import qualified TestHelpers.GfxAst as GA
interpreterLoopTests :: Test
interpreterLoopTests =
testGroup "Loop Tests" [testCase "interprets loop" test_loop_program]
test_loop_program :: Assertion
test_loop_program =
let
program
= "matrix(:rotate, 0.1, 0.2, 0.3)\n\
\loop 3 times with i\n\
\\tmatrix(:rotate, 0.2, 0.2, 0.2)\n\
\\tshape(:cube, i, i, i)\n\n\n"
expectedGfx =
[ GA.MatrixCommand (GA.Rotate 0.1 0.2 0.3)
, GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2)
, GA.ShapeCommand (GA.ShapeGfx "cube" 0 0 0)
, GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2)
, GA.ShapeCommand (GA.ShapeGfx "cube" 1 1 1)
, GA.MatrixCommand (GA.Rotate 0.2 0.2 0.2)
, GA.ShapeCommand (GA.ShapeGfx "cube" 2 2 2)
]
in
gfxTest program expectedGfx
| rumblesan/improviz | test/Tests/Language/Interpreter/Loops.hs | bsd-3-clause | 1,244 | 0 | 13 | 422 | 266 | 144 | 122 | 25 | 1 |
-- |
-- Module : Test.Checks.Property.Collection
-- License : BSD-style
-- Maintainer : Nicolas Di Prima <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- This module contains all the different property tests for the Foundation's
-- collection classes.
--
-- You can either run all the collection property tests with the
-- @collectionProperties@ function or run them individually.
--
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Test.Checks.Property.Collection
( collectionProperties
, -- * properties per class
testEqualityProperties
, testOrderingProperties
, testIsListPropertyies
, testMonoidProperties
, testCollectionProperties
, testSequentialProperties
, fromListP
, toListP
) where
import Foundation
import Foundation.Collection
import Foundation.Check
import Control.Monad (replicateM)
import qualified Prelude (replicate)
-- | convenient function to replicate thegiven Generator of `e` a randomly
-- choosen amount of time.
generateListOfElement :: Gen e -> Gen [e]
generateListOfElement = generateListOfElementMaxN 100
-- | convenient function to generate up to a certain amount of time the given
-- generator.
generateListOfElementMaxN :: Word -> Gen e -> Gen [e]
generateListOfElementMaxN n e = between (0,n) >>= flip replicateM e . fromIntegral
generateNonEmptyListOfElement :: Word -> Gen e -> Gen (NonEmpty [e])
generateNonEmptyListOfElement n e = nonEmpty_ <$> (between (1,n) >>= flip replicateM e . fromIntegral)
-- | internal helper to convert a list of element into a collection
--
fromListP :: (IsList c, Item c ~ Element c) => Proxy c -> [Element c] -> c
fromListP p = \x -> asProxyTypeOf (fromList x) p
fromListNonEmptyP :: Collection a => Proxy a -> NonEmpty [Element a] -> NonEmpty a
fromListNonEmptyP proxy = nonEmpty_ . fromListP proxy . getNonEmpty
-- | internal helper to convert a given Collection into a list of its element
--
toListP :: (IsList c, Item c ~ Element c) => Proxy c -> c -> [Element c]
toListP p x = toList (asProxyTypeOf x p)
-- | test all the diffent classes of a Foundation's collection class
--
-- * testEqualityProperties
-- * testOrderingProperties
-- * testIsListPropertyies
-- * testMonoidProperties
-- * testCollectionProperties
-- * testSequentialProperties
--
collectionProperties :: forall collection
. ( Sequential collection
, Typeable collection, Typeable (Element collection)
, Eq collection, Eq (Element collection)
, Show collection, Show (Element collection)
, Ord collection, Ord (Element collection)
)
=> String
-> Proxy collection
-> Gen (Element collection)
-> Test
collectionProperties name proxy genElement = Group name
[ testEqualityProperties proxy genElement
, testOrderingProperties proxy genElement
, testIsListPropertyies proxy genElement
, testMonoidProperties proxy genElement
, testCollectionProperties proxy genElement
, testSequentialProperties proxy genElement
]
-- | test property equality for the given Collection
--
-- This does to enforce
testEqualityProperties :: forall collection
. ( IsList collection
, Element collection ~ Item collection
, Typeable collection
, Eq collection, Eq (Element collection)
, Show collection, Show (Element collection)
, Ord collection, Ord (Element collection)
)
=> Proxy collection
-> Gen (Element collection)
-> Test
testEqualityProperties proxy genElement = Group "equality"
[ Property "x == x" $ withElements $ \l -> let col = fromListP proxy l in col === col
, Property "x == y" $ with2Elements $ \(l1, l2) ->
(fromListP proxy l1 == fromListP proxy l2) === (l1 == l2)
]
where
withElements f = forAll (generateListOfElement genElement) f
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
testOrderingProperties :: forall collection
. ( IsList collection
, Element collection ~ Item collection
, Typeable collection
, Eq collection, Eq (Element collection)
, Show collection, Show (Element collection)
, Ord collection, Ord (Element collection)
)
=> Proxy collection
-> Gen (Element collection)
-> Test
testOrderingProperties proxy genElement = Group "ordering"
[ Property "x `compare` y" $ with2Elements $ \(l1, l2) ->
(fromListP proxy l1 `compare` fromListP proxy l2) === (l1 `compare` l2)
]
where
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
testIsListPropertyies :: forall collection
. ( IsList collection, Eq collection, Show collection
, Typeable collection, Typeable (Element collection)
, Element collection ~ Item collection
, Eq (Item collection), Show (Item collection)
)
=> Proxy collection
-> Gen (Element collection)
-> Test
testIsListPropertyies proxy genElement = Group "IsList"
[ Property "fromList . toList == id" $ withElements $ \l -> (toList $ fromListP proxy l) === l
]
where
withElements f = forAll (generateListOfElement genElement) f
testMonoidProperties :: forall collection
. ( Monoid collection, IsList collection, Eq collection, Show collection
, Typeable collection, Typeable (Element collection)
, Element collection ~ Item collection
, Eq (Item collection), Show (Item collection)
)
=> Proxy collection
-> Gen (Element collection)
-> Test
testMonoidProperties proxy genElement = Group "Monoid"
[ Property "mempty <> x == x" $ withElements $ \l -> let col = fromListP proxy l in (col <> mempty) === col
, Property "x <> mempty == x" $ withElements $ \l -> let col = fromListP proxy l in (mempty <> col) === col
, Property "x1 <> x2 == x1|x2" $ with2Elements $ \(l1,l2) ->
(fromListP proxy l1 <> fromListP proxy l2) === fromListP proxy (l1 <> l2)
, Property "mconcat [map fromList [e]] = fromList (concat [e])" $ withNElements $ \l ->
mconcat (fmap (fromListP proxy) l) === fromListP proxy (mconcat l)
]
where
withElements f = forAll (generateListOfElement genElement) f
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
withNElements f = forAll (generateListOfElementMaxN 5 (generateListOfElement genElement)) f
-- | test the Foundation's @Collection@ class.
--
testCollectionProperties :: forall collection
. ( Collection collection
, Typeable collection, Typeable (Element collection)
, Show (Element collection), Eq (Element collection)
, Ord (Element collection)
, Ord collection
)
=> Proxy collection
-- ^ a proxy for the collection to test
-> Gen (Element collection)
-- ^ a generator to generate elements for the collection
-> Test
testCollectionProperties proxy genElement = Group "Collection"
[ Property "null mempty" $ (null $ fromListP proxy []) === True
, Property "null . getNonEmpty" $ withNonEmptyElements $ \els ->
(null $ fromListP proxy $ getNonEmpty els) === False
, Property "length" $ withElements $ \l -> (length $ fromListP proxy l) === length l
, Property "elem" $ withListAndElement $ \(l,e) -> elem e (fromListP proxy l) === elem e l
, Property "notElem" $ withListAndElement $ \(l,e) -> notElem e (fromListP proxy l) === notElem e l
, Property "minimum" $ withNonEmptyElements $ \els -> minimum (fromListNonEmptyP proxy els) === minimum els
, Property "maximum" $ withNonEmptyElements $ \els -> maximum (fromListNonEmptyP proxy els) === maximum els
, Property "all" $ withListAndElement $ \(l, e) ->
(all (/= e) (fromListP proxy l) === all (/= e) l) `propertyAnd`
(all (== e) (fromListP proxy l) === all (== e) l)
, Property "any" $ withListAndElement $ \(l, e) ->
(any (/= e) (fromListP proxy l) === any (/= e) l) `propertyAnd`
(any (== e) (fromListP proxy l) === any (== e) l)
]
where
withElements f = forAll (generateListOfElement genElement) f
withListAndElement = forAll ((,) <$> generateListOfElement genElement <*> genElement)
withNonEmptyElements f = forAll (generateNonEmptyListOfElement 80 genElement) f
testSequentialProperties :: forall collection
. ( Sequential collection
, Typeable collection, Typeable (Element collection)
, Eq collection, Eq (Element collection)
, Ord collection, Ord (Element collection)
, Show collection, Show (Element collection)
)
=> Proxy collection
-> Gen (Element collection)
-> Test
testSequentialProperties proxy genElement = Group "Sequential"
[ Property "take" $ withElements2 $ \(l, n) -> toList (take n $ fromListP proxy l) === (take n) l
, Property "drop" $ withElements2 $ \(l, n) -> toList (drop n $ fromListP proxy l) === (drop n) l
, Property "splitAt" $ withElements2 $ \(l, n) -> toList2 (splitAt n $ fromListP proxy l) === (splitAt n) l
, Property "revTake" $ withElements2 $ \(l, n) -> toList (revTake n $ fromListP proxy l) === (revTake n) l
, Property "revDrop" $ withElements2 $ \(l, n) -> toList (revDrop n $ fromListP proxy l) === (revDrop n) l
, Property "revSplitAt" $ withElements2 $ \(l, n) -> toList2 (revSplitAt n $ fromListP proxy l) === (revSplitAt n) l
, Property "break" $ withElements2E $ \(l, c) -> toList2 (break (== c) $ fromListP proxy l) === (break (== c)) l
, Property "breakEnd" $ withElements2E $ \(l, c) -> toList2 (breakEnd (== c) $ fromListP proxy l) === (breakEnd (== c)) l
, Property "breakElem" $ withElements2E $ \(l, c) -> toList2 (breakElem c $ fromListP proxy l) === (breakElem c) l
, Property "span" $ withElements2E $ \(l, c) -> toList2 (span (== c) $ fromListP proxy l) === (span (== c)) l
, Property "spanEnd" $ withElements2E $ \(l, c) -> toList2 (spanEnd (== c) $ fromListP proxy l) === (spanEnd (== c)) l
, Property "filter" $ withElements2E $ \(l, c) -> toList (filter (== c) $ fromListP proxy l) === (filter (== c)) l
, Property "partition" $ withElements2E $ \(l, c) -> toList2 (partition (== c) $ fromListP proxy l) === (partition (== c)) l
, Property "snoc" $ withElements2E $ \(l, c) -> toList (snoc (fromListP proxy l) c) === (l <> [c])
, Property "cons" $ withElements2E $ \(l, c) -> toList (cons c (fromListP proxy l)) === (c : l)
, Property "unsnoc" $ withElements $ \l -> fmap toListFirst (unsnoc (fromListP proxy l)) === unsnoc l
, Property "uncons" $ withElements $ \l -> fmap toListSecond (uncons (fromListP proxy l)) === uncons l
, Property "head" $ withNonEmptyElements $ \els -> head (fromListNonEmptyP proxy els) === head els
, Property "last" $ withNonEmptyElements $ \els -> last (fromListNonEmptyP proxy els) === last els
, Property "tail" $ withNonEmptyElements $ \els -> toList (tail $ fromListNonEmptyP proxy els) === tail els
, Property "init" $ withNonEmptyElements $ \els -> toList (init $ fromListNonEmptyP proxy els) === init els
, Property "splitOn" $ withElements2E $ \(l, ch) ->
fmap toList (splitOn (== ch) (fromListP proxy l)) === splitOn (== ch) l
, testSplitOn proxy (const True) mempty
, Property "intercalate c (splitOn (c ==) col) == col" $ withElements2E $ \(c, ch) ->
intercalate [ch] (splitOn (== ch) c) === c
, Property "intercalate c (splitOn (c ==) (col ++ [c]) == (col ++ [c])" $ withElements2E $ \(c, ch) ->
intercalate [ch] (splitOn (== ch) $ snoc c ch) === (snoc c ch)
, Property "intercalate c (splitOn (c ==) (col ++ [c,c]) == (col ++ [c,c])" $ withElements2E $ \(c, ch) ->
intercalate [ch] (splitOn (== ch) $ snoc (snoc c ch) ch) === (snoc (snoc c ch) ch)
, Property "intersperse" $ withElements2E $ \(l, c) ->
toList (intersperse c (fromListP proxy l)) === intersperse c l
, Property "intercalate" $ withElements2E $ \(l, c) ->
let ls = Prelude.replicate 5 l
cs = Prelude.replicate 5 c
in toList (intercalate (fromListP proxy cs) (fromListP proxy <$> ls)) === intercalate cs ls
, Property "sortBy" $ withElements $ \l ->
(sortBy compare $ fromListP proxy l) === fromListP proxy (sortBy compare l)
, Property "reverse" $ withElements $ \l ->
(reverse $ fromListP proxy l) === fromListP proxy (reverse l)
-- stress slicing
, Property "take . take" $ withElements3 $ \(l, n1, n2) -> toList (take n2 $ take n1 $ fromListP proxy l) === (take n2 $ take n1 l)
, Property "drop . take" $ withElements3 $ \(l, n1, n2) -> toList (drop n2 $ take n1 $ fromListP proxy l) === (drop n2 $ take n1 l)
, Property "drop . drop" $ withElements3 $ \(l, n1, n2) -> toList (drop n2 $ drop n1 $ fromListP proxy l) === (drop n2 $ drop n1 l)
, Property "drop . take" $ withElements3 $ \(l, n1, n2) -> toList (drop n2 $ take n1 $ fromListP proxy l) === (drop n2 $ take n1 l)
, Property "second take . splitAt" $ withElements3 $ \(l, n1, n2) ->
(toList2 $ (second (take n1) . splitAt n2) $ fromListP proxy l) === (second (take n1) . splitAt n2) l
, Property "splitAt == (take, drop)" $ withCollection2 $ \(col, n) ->
splitAt n col === (take n col, drop n col)
, Property "revSplitAt == (revTake, revDrop)" $ withCollection2 $ \(col, n) ->
revSplitAt n col === (revTake n col, revDrop n col)
, Group "isSuffixOf"
[ Property "collection + sub" $ withElements2 $ \(l1, n) ->
let c1 = fromListP proxy l1 in isSuffixOf (revTake n c1) c1 === isSuffixOf (revTake n l1) l1
, Property "2 collections" $ with2Elements $ \(l1, l2) -> isSuffixOf (fromListP proxy l1) (fromListP proxy l2) === isSuffixOf l1 l2
, Property "collection + empty" $ withElements $ \l1 ->
isSuffixOf (fromListP proxy []) (fromListP proxy l1) === isSuffixOf [] l1
]
, Group "isPrefixOf"
[ Property "collection + sub" $ withElements2 $ \(l1, n) ->
let c1 = fromListP proxy l1 in isPrefixOf (take n c1) c1 === isPrefixOf (take n l1) l1
, Property "2 collections" $ with2Elements $ \(l1, l2) -> isPrefixOf (fromListP proxy l1) (fromListP proxy l2) === isPrefixOf l1 l2
, Property "collection + empty" $ withElements $ \l1 ->
isPrefixOf (fromListP proxy []) (fromListP proxy l1) === isPrefixOf [] l1
]
, Group "isInfixOf"
[ Property "b isInfixOf 'a b c'" $ with3Elements $ \(a, b, c) ->
isInfixOf (toCol b) (toCol a <> toCol b <> toCol c)
, Property "the reverse is typically not an infix" $ withElements $ \a' ->
let a = toCol a'; rev = reverse a in isInfixOf rev a === (a == rev)
]
]
{-
, testProperty "imap" $ \(CharMap (LUString u) i) ->
(imap (addChar i) (fromList u) :: String) `assertEq` fromList (Prelude.map (addChar i) u)
]
-}
where
toCol = fromListP proxy
toList2 (x,y) = (toList x, toList y)
toListFirst (x,y) = (toList x, y)
toListSecond (x,y) = (x, toList y)
withElements f = forAll (generateListOfElement genElement) f
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
with3Elements f = forAll ((,,) <$> generateListOfElement genElement <*> generateListOfElement genElement <*> generateListOfElement genElement) f
withElements2 f = forAll ((,) <$> generateListOfElement genElement <*> arbitrary) f
withElements3 f = forAll ((,,) <$> generateListOfElement genElement <*> arbitrary <*> arbitrary) f
withElements2E f = forAll ((,) <$> generateListOfElement genElement <*> genElement) f
withNonEmptyElements f = forAll (generateNonEmptyListOfElement 80 genElement) f
withCollection2 f = forAll ((,) <$> (fromListP proxy <$> generateListOfElement genElement) <*> arbitrary) f
testSplitOn :: ( Sequential a
, Show a, Show (Element a)
, Typeable a
, Eq (Element a)
, Eq a, Ord a, Ord (Item a), Show a
)
=> Proxy a -> (Element a -> Bool) -> a
-> Test
testSplitOn _ predicate col = Property "splitOn (const True) mempty == [mempty]" $
(splitOn predicate col) === [col]
| vincenthz/hs-foundation | foundation/tests/Test/Checks/Property/Collection.hs | bsd-3-clause | 17,710 | 0 | 17 | 5,074 | 5,581 | 2,854 | 2,727 | 231 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE CPP #-}
#ifdef DEBUG_CONFLICT_SETS
{-# LANGUAGE ImplicitParams #-}
#endif
module Distribution.Solver.Modular.Dependency (
-- * Variables
Var(..)
, simplifyVar
, varPI
, showVar
-- * Conflict sets
, ConflictSet
, CS.showCS
-- * Constrained instances
, CI(..)
, merge
-- * Flagged dependencies
, FlaggedDeps
, FlaggedDep(..)
, Dep(..)
, showDep
, flattenFlaggedDeps
, QualifyOptions(..)
, qualifyDeps
, unqualifyDeps
-- ** Setting/forgetting components
, forgetCompOpenGoal
, setCompFlaggedDeps
-- * Reverse dependency map
, RevDepMap
-- * Goals
, Goal(..)
, GoalReason(..)
, QGoalReason
, ResetVar(..)
, goalToVar
, goalVarToConflictSet
, varToConflictSet
, goalReasonToVars
-- * Open goals
, OpenGoal(..)
, close
) where
import Prelude hiding (pi)
import Data.Map (Map)
import qualified Data.List as L
import Language.Haskell.Extension (Extension(..), Language(..))
import Distribution.Text
import Distribution.Solver.Modular.ConflictSet (ConflictSet)
import Distribution.Solver.Modular.Flag
import Distribution.Solver.Modular.Package
import Distribution.Solver.Modular.Var
import Distribution.Solver.Modular.Version
import qualified Distribution.Solver.Modular.ConflictSet as CS
import Distribution.Solver.Types.ComponentDeps (Component(..))
import Distribution.Solver.Types.PackagePath
#ifdef DEBUG_CONFLICT_SETS
import GHC.Stack (CallStack)
#endif
{-------------------------------------------------------------------------------
Constrained instances
-------------------------------------------------------------------------------}
-- | Constrained instance. If the choice has already been made, this is
-- a fixed instance, and we record the package name for which the choice
-- is for convenience. Otherwise, it is a list of version ranges paired with
-- the goals / variables that introduced them.
data CI qpn = Fixed I (Var qpn) | Constrained [VROrigin qpn]
deriving (Eq, Show, Functor)
showCI :: CI QPN -> String
showCI (Fixed i _) = "==" ++ showI i
showCI (Constrained vr) = showVR (collapse vr)
-- | Merge constrained instances. We currently adopt a lazy strategy for
-- merging, i.e., we only perform actual checking if one of the two choices
-- is fixed. If the merge fails, we return a conflict set indicating the
-- variables responsible for the failure, as well as the two conflicting
-- fragments.
--
-- Note that while there may be more than one conflicting pair of version
-- ranges, we only return the first we find.
--
-- TODO: Different pairs might have different conflict sets. We're
-- obviously interested to return a conflict that has a "better" conflict
-- set in the sense the it contains variables that allow us to backjump
-- further. We might apply some heuristics here, such as to change the
-- order in which we check the constraints.
merge ::
#ifdef DEBUG_CONFLICT_SETS
(?loc :: CallStack) =>
#endif
Ord qpn => CI qpn -> CI qpn -> Either (ConflictSet qpn, (CI qpn, CI qpn)) (CI qpn)
merge c@(Fixed i g1) d@(Fixed j g2)
| i == j = Right c
| otherwise = Left (CS.union (varToConflictSet g1) (varToConflictSet g2), (c, d))
merge c@(Fixed (I v _) g1) (Constrained rs) = go rs -- I tried "reverse rs" here, but it seems to slow things down ...
where
go [] = Right c
go (d@(vr, g2) : vrs)
| checkVR vr v = go vrs
| otherwise = Left (CS.union (varToConflictSet g1) (varToConflictSet g2), (c, Constrained [d]))
merge c@(Constrained _) d@(Fixed _ _) = merge d c
merge (Constrained rs) (Constrained ss) = Right (Constrained (rs ++ ss))
{-------------------------------------------------------------------------------
Flagged dependencies
-------------------------------------------------------------------------------}
-- | Flagged dependencies
--
-- 'FlaggedDeps' is the modular solver's view of a packages dependencies:
-- rather than having the dependencies indexed by component, each dependency
-- defines what component it is in.
--
-- However, top-level goals are also modelled as dependencies, but of course
-- these don't actually belong in any component of any package. Therefore, we
-- parameterize 'FlaggedDeps' and derived datatypes with a type argument that
-- specifies whether or not we have a component: we only ever instantiate this
-- type argument with @()@ for top-level goals, or 'Component' for everything
-- else (we could express this as a kind at the type-level, but that would
-- require a very recent GHC).
--
-- Note however, crucially, that independent of the type parameters, the list
-- of dependencies underneath a flag choice or stanza choices _always_ uses
-- Component as the type argument. This is important: when we pick a value for
-- a flag, we _must_ know what component the new dependencies belong to, or
-- else we don't be able to construct fine-grained reverse dependencies.
type FlaggedDeps comp qpn = [FlaggedDep comp qpn]
-- | Flagged dependencies can either be plain dependency constraints,
-- or flag-dependent dependency trees.
data FlaggedDep comp qpn =
-- | Dependencies which are conditional on a flag choice.
Flagged (FN qpn) FInfo (TrueFlaggedDeps qpn) (FalseFlaggedDeps qpn)
-- | Dependencies which are conditional on whether or not a stanza
-- (e.g., a test suite or benchmark) is enabled.
| Stanza (SN qpn) (TrueFlaggedDeps qpn)
-- | Dependencies for which are always enabled, for the component
-- 'comp' (or requested for the user, if comp is @()@).
| Simple (Dep qpn) comp
deriving (Eq, Show)
-- | Conversatively flatten out flagged dependencies
--
-- NOTE: We do not filter out duplicates.
flattenFlaggedDeps :: FlaggedDeps Component qpn -> [(Dep qpn, Component)]
flattenFlaggedDeps = concatMap aux
where
aux :: FlaggedDep Component qpn -> [(Dep qpn, Component)]
aux (Flagged _ _ t f) = flattenFlaggedDeps t ++ flattenFlaggedDeps f
aux (Stanza _ t) = flattenFlaggedDeps t
aux (Simple d c) = [(d, c)]
type TrueFlaggedDeps qpn = FlaggedDeps Component qpn
type FalseFlaggedDeps qpn = FlaggedDeps Component qpn
-- | Is this dependency on an executable
type IsExe = Bool
-- | A dependency (constraint) associates a package name with a
-- constrained instance.
--
-- 'Dep' intentionally has no 'Functor' instance because the type variable
-- is used both to record the dependencies as well as who's doing the
-- depending; having a 'Functor' instance makes bugs where we don't distinguish
-- these two far too likely. (By rights 'Dep' ought to have two type variables.)
data Dep qpn = Dep IsExe qpn (CI qpn) -- dependency on a package (possibly for executable
| Ext Extension -- dependency on a language extension
| Lang Language -- dependency on a language version
| Pkg PN VR -- dependency on a pkg-config package
deriving (Eq, Show)
showDep :: Dep QPN -> String
showDep (Dep is_exe qpn (Fixed i v) ) =
(if P qpn /= v then showVar v ++ " => " else "") ++
showQPN qpn ++
(if is_exe then " (exe) " else "") ++ "==" ++ showI i
showDep (Dep is_exe qpn (Constrained [(vr, v)])) =
showVar v ++ " => " ++ showQPN qpn ++
(if is_exe then " (exe) " else "") ++ showVR vr
showDep (Dep is_exe qpn ci ) =
showQPN qpn ++ (if is_exe then " (exe) " else "") ++ showCI ci
showDep (Ext ext) = "requires " ++ display ext
showDep (Lang lang) = "requires " ++ display lang
showDep (Pkg pn vr) = "requires pkg-config package "
++ display pn ++ display vr
++ ", not found in the pkg-config database"
-- | Options for goal qualification (used in 'qualifyDeps')
--
-- See also 'defaultQualifyOptions'
data QualifyOptions = QO {
-- | Do we have a version of base relying on another version of base?
qoBaseShim :: Bool
-- Should dependencies of the setup script be treated as independent?
, qoSetupIndependent :: Bool
}
deriving Show
-- | Apply built-in rules for package qualifiers
--
-- Although the behaviour of 'qualifyDeps' depends on the 'QualifyOptions',
-- it is important that these 'QualifyOptions' are _static_. Qualification
-- does NOT depend on flag assignment; in other words, it behaves the same no
-- matter which choices the solver makes (modulo the global 'QualifyOptions');
-- we rely on this in 'linkDeps' (see comment there).
--
-- NOTE: It's the _dependencies_ of a package that may or may not be independent
-- from the package itself. Package flag choices must of course be consistent.
qualifyDeps :: QualifyOptions -> QPN -> FlaggedDeps Component PN -> FlaggedDeps Component QPN
qualifyDeps QO{..} (Q pp@(PackagePath ns q) pn) = go
where
go :: FlaggedDeps Component PN -> FlaggedDeps Component QPN
go = map go1
go1 :: FlaggedDep Component PN -> FlaggedDep Component QPN
go1 (Flagged fn nfo t f) = Flagged (fmap (Q pp) fn) nfo (go t) (go f)
go1 (Stanza sn t) = Stanza (fmap (Q pp) sn) (go t)
go1 (Simple dep comp) = Simple (goD dep comp) comp
-- Suppose package B has a setup dependency on package A.
-- This will be recorded as something like
--
-- > Dep "A" (Constrained [(AnyVersion, Goal (P "B") reason])
--
-- Observe that when we qualify this dependency, we need to turn that
-- @"A"@ into @"B-setup.A"@, but we should not apply that same qualifier
-- to the goal or the goal reason chain.
goD :: Dep PN -> Component -> Dep QPN
goD (Ext ext) _ = Ext ext
goD (Lang lang) _ = Lang lang
goD (Pkg pkn vr) _ = Pkg pkn vr
goD (Dep is_exe dep ci) comp
| is_exe = Dep is_exe (Q (PackagePath ns (Exe pn dep)) dep) (fmap (Q pp) ci)
| qBase dep = Dep is_exe (Q (PackagePath ns (Base pn)) dep) (fmap (Q pp) ci)
| qSetup comp = Dep is_exe (Q (PackagePath ns (Setup pn)) dep) (fmap (Q pp) ci)
| otherwise = Dep is_exe (Q (PackagePath ns inheritedQ) dep) (fmap (Q pp) ci)
-- If P has a setup dependency on Q, and Q has a regular dependency on R, then
-- we say that the 'Setup' qualifier is inherited: P has an (indirect) setup
-- dependency on R. We do not do this for the base qualifier however.
--
-- The inherited qualifier is only used for regular dependencies; for setup
-- and base deppendencies we override the existing qualifier. See #3160 for
-- a detailed discussion.
inheritedQ :: Qualifier
inheritedQ = case q of
Setup _ -> q
Exe _ _ -> q
Unqualified -> q
Base _ -> Unqualified
-- Should we qualify this goal with the 'Base' package path?
qBase :: PN -> Bool
qBase dep = qoBaseShim && unPackageName dep == "base"
-- Should we qualify this goal with the 'Setup' package path?
qSetup :: Component -> Bool
qSetup comp = qoSetupIndependent && comp == ComponentSetup
-- | Remove qualifiers from set of dependencies
--
-- This is used during link validation: when we link package @Q.A@ to @Q'.A@,
-- then all dependencies @Q.B@ need to be linked to @Q'.B@. In order to compute
-- what to link these dependencies to, we need to requalify @Q.B@ to become
-- @Q'.B@; we do this by first removing all qualifiers and then calling
-- 'qualifyDeps' again.
unqualifyDeps :: FlaggedDeps comp QPN -> FlaggedDeps comp PN
unqualifyDeps = go
where
go :: FlaggedDeps comp QPN -> FlaggedDeps comp PN
go = map go1
go1 :: FlaggedDep comp QPN -> FlaggedDep comp PN
go1 (Flagged fn nfo t f) = Flagged (fmap unq fn) nfo (go t) (go f)
go1 (Stanza sn t) = Stanza (fmap unq sn) (go t)
go1 (Simple dep comp) = Simple (goD dep) comp
goD :: Dep QPN -> Dep PN
goD (Dep is_exe qpn ci) = Dep is_exe (unq qpn) (fmap unq ci)
goD (Ext ext) = Ext ext
goD (Lang lang) = Lang lang
goD (Pkg pn vr) = Pkg pn vr
unq :: QPN -> PN
unq (Q _ pn) = pn
{-------------------------------------------------------------------------------
Setting/forgetting the Component
-------------------------------------------------------------------------------}
forgetCompOpenGoal :: OpenGoal Component -> OpenGoal ()
forgetCompOpenGoal = mapCompOpenGoal $ const ()
setCompFlaggedDeps :: Component -> FlaggedDeps () qpn -> FlaggedDeps Component qpn
setCompFlaggedDeps = mapCompFlaggedDeps . const
{-------------------------------------------------------------------------------
Auxiliary: Mapping over the Component goal
We don't export these, because the only type instantiations for 'a' and 'b'
here should be () or Component. (We could express this at the type level
if we relied on newer versions of GHC.)
-------------------------------------------------------------------------------}
mapCompOpenGoal :: (a -> b) -> OpenGoal a -> OpenGoal b
mapCompOpenGoal g (OpenGoal d gr) = OpenGoal (mapCompFlaggedDep g d) gr
mapCompFlaggedDeps :: (a -> b) -> FlaggedDeps a qpn -> FlaggedDeps b qpn
mapCompFlaggedDeps = L.map . mapCompFlaggedDep
mapCompFlaggedDep :: (a -> b) -> FlaggedDep a qpn -> FlaggedDep b qpn
mapCompFlaggedDep _ (Flagged fn nfo t f) = Flagged fn nfo t f
mapCompFlaggedDep _ (Stanza sn t ) = Stanza sn t
mapCompFlaggedDep g (Simple pn a ) = Simple pn (g a)
{-------------------------------------------------------------------------------
Reverse dependency map
-------------------------------------------------------------------------------}
-- | A map containing reverse dependencies between qualified
-- package names.
type RevDepMap = Map QPN [(Component, QPN)]
{-------------------------------------------------------------------------------
Goals
-------------------------------------------------------------------------------}
-- | A goal is just a solver variable paired with a reason.
-- The reason is only used for tracing.
data Goal qpn = Goal (Var qpn) (GoalReason qpn)
deriving (Eq, Show, Functor)
-- | Reason why a goal is being added to a goal set.
data GoalReason qpn =
UserGoal
| PDependency (PI qpn)
| FDependency (FN qpn) Bool
| SDependency (SN qpn)
deriving (Eq, Show, Functor)
type QGoalReason = GoalReason QPN
class ResetVar f where
resetVar :: Var qpn -> f qpn -> f qpn
instance ResetVar CI where
resetVar v (Fixed i _) = Fixed i v
resetVar v (Constrained vrs) = Constrained (L.map (\ (x, y) -> (x, resetVar v y)) vrs)
instance ResetVar Dep where
resetVar v (Dep is_exe qpn ci) = Dep is_exe qpn (resetVar v ci)
resetVar _ (Ext ext) = Ext ext
resetVar _ (Lang lang) = Lang lang
resetVar _ (Pkg pn vr) = Pkg pn vr
instance ResetVar Var where
resetVar = const
goalToVar :: Goal a -> Var a
goalToVar (Goal v _) = v
-- | Compute a singleton conflict set from a goal, containing just
-- the goal variable.
--
-- NOTE: This is just a call to 'varToConflictSet' under the hood;
-- the 'GoalReason' is ignored.
goalVarToConflictSet :: Goal qpn -> ConflictSet qpn
goalVarToConflictSet (Goal g _gr) = varToConflictSet g
-- | Compute a singleton conflict set from a 'Var'
varToConflictSet :: Var qpn -> ConflictSet qpn
varToConflictSet = CS.singleton
-- | A goal reason is mostly just a variable paired with the
-- decision we made for that variable (except for user goals,
-- where we cannot really point to a solver variable). This
-- function drops the decision and recovers the list of
-- variables (which will be empty or contain one element).
--
goalReasonToVars :: GoalReason qpn -> [Var qpn]
goalReasonToVars UserGoal = []
goalReasonToVars (PDependency (PI qpn _)) = [P qpn]
goalReasonToVars (FDependency qfn _) = [F qfn]
goalReasonToVars (SDependency qsn) = [S qsn]
{-------------------------------------------------------------------------------
Open goals
-------------------------------------------------------------------------------}
-- | For open goals as they occur during the build phase, we need to store
-- additional information about flags.
data OpenGoal comp = OpenGoal (FlaggedDep comp QPN) QGoalReason
deriving (Eq, Show)
-- | Closes a goal, i.e., removes all the extraneous information that we
-- need only during the build phase.
close :: OpenGoal comp -> Goal QPN
close (OpenGoal (Simple (Dep _ qpn _) _) gr) = Goal (P qpn) gr
close (OpenGoal (Simple (Ext _) _) _ ) =
error "Distribution.Solver.Modular.Dependency.close: called on Ext goal"
close (OpenGoal (Simple (Lang _) _) _ ) =
error "Distribution.Solver.Modular.Dependency.close: called on Lang goal"
close (OpenGoal (Simple (Pkg _ _) _) _ ) =
error "Distribution.Solver.Modular.Dependency.close: called on Pkg goal"
close (OpenGoal (Flagged qfn _ _ _ ) gr) = Goal (F qfn) gr
close (OpenGoal (Stanza qsn _) gr) = Goal (S qsn) gr
{-------------------------------------------------------------------------------
Version ranges paired with origins
-------------------------------------------------------------------------------}
type VROrigin qpn = (VR, Var qpn)
-- | Helper function to collapse a list of version ranges with origins into
-- a single, simplified, version range.
collapse :: [VROrigin qpn] -> VR
collapse = simplifyVR . L.foldr ((.&&.) . fst) anyVR
| sopvop/cabal | cabal-install/Distribution/Solver/Modular/Dependency.hs | bsd-3-clause | 17,406 | 0 | 14 | 3,643 | 3,609 | 1,938 | 1,671 | 204 | 9 |
{-# LANGUAGE CPP,OverloadedStrings #-}
{-# OPTIONS_GHC -F -pgmF htfpp #-}
-- |
-- Module : Language.Haskell.BuildWrapper.ImportsTests
-- Copyright : (c) JP Moresmau 2013
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : beta
-- Portability : portable
--
-- Test import cleaning and such
module Language.Haskell.BuildWrapper.ImportsTests where
import Language.Haskell.BuildWrapper.Base hiding (writeFile)
import Language.Haskell.BuildWrapper.CMDTests
import System.FilePath
import Test.Framework
import Test.HUnit (Assertion)
test_CleanImportsNothing :: Assertion
test_CleanImportsNothing = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"f :: IO()",
"f=putStrLn \"hello\""
]
(ics,ns)<-cleanImports api root rel False
assertBool $ null ns
assertBool $ null ics
test_CleanImportsFunction :: Assertion
test_CleanImportsFunction = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.Unique",
"f = newUnique"
]
(ics,ns)<-cleanImports api root rel False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 19)) "import Data.Unique (newUnique)"] ics
test_CleanImportsRemove :: Assertion
test_CleanImportsRemove = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.Unique",
"f = putStrLn \"hello\""
]
(ics,ns)<-cleanImports api root rel False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 19)) ""] ics
test_CleanImportsFunctionType :: Assertion
test_CleanImportsFunctionType = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.Unique",
"f :: IO Unique",
"f = newUnique"
]
(ics,ns)<-cleanImports api root rel False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 19)) "import Data.Unique (newUnique, Unique)"] ics
test_CleanImportsConstructor :: Assertion
test_CleanImportsConstructor = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"data MyData=MyCons Int"
]
let rel2="src"</>"B"</>"C.hs"
write api root rel2 $ unlines [
"module B.C where",
"",
"import A",
"f = MyCons 2"
]
(ics,ns)<-cleanImports api root rel2 False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 9)) "import A (MyData (MyCons))"] ics
test_CleanImportsConstructorTyped :: Assertion
test_CleanImportsConstructorTyped = do
let api=cabalAPI
root<-createTestProject
let cf=testCabalFile root
writeFile cf $ unlines ["name: "++testProjectName,
"version:0.1",
"cabal-version: >= 1.8",
"build-type: Simple",
"",
"library",
" hs-source-dirs: src",
" exposed-modules: A",
" other-modules: B.C",
" build-depends: base"]
synchronize api root False
configure api root Target
let rel2="src"</>"B"</>"C.hs"
write api root rel2 $ unlines [
"module B.C where",
"",
"import System.Exit",
"f r= case r of",
" ExitFailure _ ->True",
" _->False"
]
(ics,ns)<-cleanImports api root rel2 False
assertBool $ null ns
#if __GLASGOW_HASKELL__ != 704
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 19)) "import System.Exit (ExitCode (ExitFailure))"] ics
#endif
test_CleanImportsFunctionInExport :: Assertion
test_CleanImportsFunctionInExport = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"data MyData=MyCons Int",
"myUnCons (MyCons i)=i"
]
let rel2="src"</>"B"</>"C.hs"
write api root rel2 $ unlines [
"module B.C (f,myUnCons) where",
"",
"import A",
"f = MyCons 2"
]
(ics,ns)<-cleanImports api root rel2 False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 9)) "import A (MyData (MyCons), myUnCons)"] ics
test_CleanImportsConstructorQualified :: Assertion
test_CleanImportsConstructorQualified = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"data MyData=MyCons Int"
]
let rel2="src"</>"B"</>"C.hs"
write api root rel2 $ unlines [
"module B.C where",
"",
"import qualified A as MyA",
"f = MyA.MyCons 2"
]
(ics,ns)<-cleanImports api root rel2 False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 26)) "import qualified A as MyA (MyData (MyCons))"] ics
test_CleanImportsFunctionReExported :: Assertion
test_CleanImportsFunctionReExported = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.Char",
"f = toUpper"
]
(ics,ns)<-cleanImports api root rel False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 17)) "import Data.Char (toUpper)"] ics
test_CleanImportsFunctionReExportedInExport :: Assertion
test_CleanImportsFunctionReExportedInExport = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A (f,toLower) where",
"",
"import Data.Char",
"f = toUpper"
]
(ics,ns)<-cleanImports api root rel False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 17)) "import Data.Char (toLower, toUpper)"] ics
test_CleanImportsFunctionReExportedWithOthers :: Assertion
test_CleanImportsFunctionReExportedWithOthers = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.Char",
"import Data.List",
"f = toUpper",
"f2 = unzip5",
"f3 = isSeparator"
]
(ics,ns)<-cleanImports api root rel False
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 17))
"import Data.Char (isSeparator, toUpper)",
ImportClean (InFileSpan (InFileLoc 4 1) (InFileLoc 4 17))
"import Data.List (unzip5)"]
ics
test_CleanImportsFormat :: Assertion
test_CleanImportsFormat = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.Char",
"import qualified Data.Unique as U",
"f = toUpper",
"f2 = U.newUnique",
"f3 = isSeparator"
]
(ics,ns)<-cleanImports api root rel True
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 17))
"import Data.Char (isSeparator, toUpper)",
ImportClean (InFileSpan (InFileLoc 4 1) (InFileLoc 4 34))
"import qualified Data.Unique as U (newUnique)"]
ics
test_CleanImportsInfix :: Assertion
test_CleanImportsInfix = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
let cf=testCabalFile root
writeFile cf $ unlines ["name: "++testProjectName,
"version:0.1",
"cabal-version: >= 1.8",
"build-type: Simple",
"",
"library",
" hs-source-dirs: src",
" exposed-modules: A",
" other-modules: B.C",
" build-depends: base, filepath"]
synchronize api root False
configure api root Target
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import System.FilePath",
"f = \"dir\" </> \"file\""
]
(ics,ns)<-cleanImports api root rel True
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 23))
"import System.FilePath ((</>))"
]
ics
test_CleanImportsHiding :: Assertion
test_CleanImportsHiding = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
let cf=testCabalFile root
writeFile cf $ unlines ["name: "++testProjectName,
"version:0.1",
"cabal-version: >= 1.8",
"build-type: Simple",
"",
"library",
" hs-source-dirs: src",
" exposed-modules: A",
" other-modules: B.C",
" build-depends: base, bytestring"]
synchronize api root False
configure api root Target
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.ByteString.Lazy.Char8 hiding (writeFile)",
"f s= writeFile \"file\" s"
]
(ics,ns)<-cleanImports api root rel True
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 53))
""
]
ics
test_CleanImportsPrelude :: Assertion
test_CleanImportsPrelude = do
let api=cabalAPI
root<-createTestProject
synchronize api root False
let rel="src"</>"A.hs"
-- use api to write temp file
write api root rel $ unlines [
"module A where",
"",
"import Data.List",
"f = map id"
]
(ics,ns)<-cleanImports api root rel True
assertBool $ null ns
assertEqual [ImportClean (InFileSpan (InFileLoc 3 1) (InFileLoc 3 17))
""]
ics
| achirkin/BuildWrapper | test/Language/Haskell/BuildWrapper/ImportsTests.hs | bsd-3-clause | 13,355 | 0 | 13 | 5,432 | 2,750 | 1,358 | 1,392 | 295 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- http://orbt.io/QHBm.png
module Main where
import Text.Hastache
import Web.Scotty.Trans as S
import Web.Scotty.Hastache
main :: IO ()
main = scottyH' 3000 $ do
setTemplatesDir "templates"
get "/:word" $ do
beam <- param "word"
setH "action" $ MuVariable (beam :: String)
hastache "greet.html"
| superduper/scotty-hastache | examples/hastachetest.hs | bsd-3-clause | 349 | 0 | 13 | 65 | 98 | 50 | 48 | 12 | 1 |
module Main where
import Properties
import UnitTests
import Test.Framework.Runners.Console (defaultMain)
main = defaultMain $ [UnitTests.tests, Properties.tests]
| joshcough/HaskellStarter | test/Main.hs | mit | 164 | 0 | 7 | 18 | 41 | 26 | 15 | 5 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-orphans -O0 #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE QuasiQuotes, TemplateHaskell, CPP, GADTs, TypeFamilies, OverloadedStrings, FlexibleContexts, EmptyDataDecls, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
module EmbedTest (specs,
#ifndef WITH_NOSQL
embedMigrate
#endif
) where
import Init
import Control.Exception (Exception, throw)
import Data.Typeable (Typeable)
import qualified Data.Text as T
import qualified Data.Set as S
import qualified Data.Map as M
#if WITH_NOSQL
#ifdef WITH_MONGODB
import Database.Persist.MongoDB
import Database.MongoDB (genObjectId)
import Database.MongoDB (Value(String))
#endif
import EntityEmbedTest
import System.Process (readProcess)
#endif
import Data.List.NonEmpty hiding (insert, length)
data TestException = TestException
deriving (Show, Typeable, Eq)
instance Exception TestException
instance PersistFieldSql a => PersistFieldSql (NonEmpty a) where
sqlType _ = SqlString
instance PersistField a => PersistField (NonEmpty a) where
toPersistValue = toPersistValue . toList
fromPersistValue pv = case fromPersistValue pv of
Left e -> Left e
Right [] -> Left "PersistField: NonEmpty found unexpected Empty List"
Right (l:ls) -> Right (l:|ls)
#if WITH_NOSQL
mkPersist persistSettings [persistUpperCase|
# ifdef WITH_MONGODB
HasObjectId
oid ObjectId
name Text
deriving Show Eq Read Ord
HasArrayWithObjectIds
name Text
arrayWithObjectIds [HasObjectId]
deriving Show Eq Read Ord
HasArrayWithEntities
hasEntity (Entity ARecord)
arrayWithEntities [AnEntity]
deriving Show Eq Read Ord
# endif
#else
share [mkPersist sqlSettings, mkMigrate "embedMigrate"] [persistUpperCase|
#endif
OnlyName
name Text
deriving Show Eq Read Ord
HasEmbed
name Text
embed OnlyName
deriving Show Eq Read Ord
HasEmbeds
name Text
embed OnlyName
double HasEmbed
deriving Show Eq Read Ord
HasListEmbed
name Text
list [HasEmbed]
deriving Show Eq Read Ord
HasSetEmbed
name Text
set (S.Set HasEmbed)
deriving Show Eq Read Ord
HasMap
name Text
map (M.Map T.Text T.Text)
deriving Show Eq Read Ord
HasList
list [HasListId]
deriving Show Eq Read Ord
EmbedsHasMap
name Text Maybe
embed HasMap
deriving Show Eq Read Ord
InList
one Int
two Int
deriving Show Eq
ListEmbed
nested [InList]
one Int
two Int
deriving Show Eq
User
ident Text
password Text Maybe
profile Profile
deriving Show Eq Read Ord
Profile
firstName Text
lastName Text
contact Contact Maybe
deriving Show Eq Read Ord
Contact
phone Int
email T.Text
deriving Show Eq Read Ord
Account
userIds (NonEmpty (Key User))
name Text Maybe
customDomains [Text] -- we may want to allow multiple cust domains. use [] instead of maybe
deriving Show Eq Read Ord
HasNestedList
list [IntList]
deriving Show Eq
IntList
ints [Int]
deriving Show Eq
-- We would like to be able to use OnlyNameId
-- But (Key OnlyName) works
MapIdValue
map (M.Map T.Text (Key OnlyName))
deriving Show Eq Read Ord
-- Self refrences are only allowed as a nullable type:
-- a Maybe or a List
SelfList
reference [SelfList]
SelfMaybe
reference SelfMaybe Maybe
-- This failes
-- SelfDirect
-- reference SelfDirect
|]
#ifdef WITH_NOSQL
cleanDB :: (PersistQuery backend, PersistEntityBackend HasMap ~ backend, MonadIO m) => ReaderT backend m ()
cleanDB = do
deleteWhere ([] :: [Filter HasEmbed])
deleteWhere ([] :: [Filter HasEmbeds])
deleteWhere ([] :: [Filter HasListEmbed])
deleteWhere ([] :: [Filter HasSetEmbed])
deleteWhere ([] :: [Filter User])
deleteWhere ([] :: [Filter HasMap])
deleteWhere ([] :: [Filter HasList])
deleteWhere ([] :: [Filter EmbedsHasMap])
deleteWhere ([] :: [Filter ListEmbed])
deleteWhere ([] :: [Filter ARecord])
deleteWhere ([] :: [Filter Account])
deleteWhere ([] :: [Filter HasNestedList])
db :: Action IO () -> Assertion
db = db' cleanDB
#endif
unlessM :: MonadIO m => IO Bool -> m () -> m ()
unlessM predicate body = do
b <- liftIO predicate
unless b body
specs :: Spec
specs = describe "embedded entities" $ do
it "simple entities" $ db $ do
let container = HasEmbeds "container" (OnlyName "2")
(HasEmbed "embed" (OnlyName "1"))
contK <- insert container
Just res <- selectFirst [HasEmbedsName ==. "container"] []
res @== Entity contK container
it "query for equality of embeded entity" $ db $ do
let container = HasEmbed "container" (OnlyName "2")
contK <- insert container
Just res <- selectFirst [HasEmbedEmbed ==. OnlyName "2"] []
res @== Entity contK container
it "Set" $ db $ do
let container = HasSetEmbed "set" $ S.fromList
[ HasEmbed "embed" (OnlyName "1")
, HasEmbed "embed" (OnlyName "2")
]
contK <- insert container
Just res <- selectFirst [HasSetEmbedName ==. "set"] []
res @== Entity contK container
it "Set empty" $ db $ do
let container = HasSetEmbed "set empty" $ S.fromList []
contK <- insert container
Just res <- selectFirst [HasSetEmbedName ==. "set empty"] []
res @== Entity contK container
it "exception" $ flip shouldThrow (== TestException) $ db $ do
let container = HasSetEmbed "set" $ S.fromList
[ HasEmbed "embed" (OnlyName "1")
, HasEmbed "embed" (OnlyName "2")
]
contK <- insert container
Just res <- selectFirst [HasSetEmbedName ==. throw TestException] []
res @== Entity contK container
it "ListEmbed" $ db $ do
let container = HasListEmbed "list"
[ HasEmbed "embed" (OnlyName "1")
, HasEmbed "embed" (OnlyName "2")
]
contK <- insert container
Just res <- selectFirst [HasListEmbedName ==. "list"] []
res @== Entity contK container
it "ListEmbed empty" $ db $ do
let container = HasListEmbed "list empty" []
contK <- insert container
Just res <- selectFirst [HasListEmbedName ==. "list empty"] []
res @== Entity contK container
it "List empty" $ db $ do
let container = HasList []
contK <- insert container
Just res <- selectFirst [] []
res @== Entity contK container
it "NonEmpty List wrapper" $ db $ do
let con = Contact 123456 "[email protected]"
let prof = Profile "fstN" "lstN" (Just con)
uid <- insert $ User "foo" (Just "pswd") prof
let container = Account (uid:|[]) (Just "Account") []
contK <- insert container
Just res <- selectFirst [AccountUserIds ==. (uid:|[])] []
res @== Entity contK container
it "Map" $ db $ do
let container = HasMap "2 items" $ M.fromList [
("k1","v1")
, ("k2","v2")
]
contK <- insert container
Just res <- selectFirst [HasMapName ==. "2 items"] []
res @== Entity contK container
it "Map empty" $ db $ do
let container = HasMap "empty" $ M.fromList []
contK <- insert container
Just res <- selectFirst [HasMapName ==. "empty"] []
res @== Entity contK container
it "Embeds a Map" $ db $ do
let container = EmbedsHasMap (Just "non-empty map") $ HasMap "2 items" $ M.fromList [
("k1","v1")
, ("k2","v2")
]
contK <- insert container
Just res <- selectFirst [EmbedsHasMapName ==. Just "non-empty map"] []
res @== Entity contK container
it "Embeds a Map empty" $ db $ do
let container = EmbedsHasMap (Just "empty map") $ HasMap "empty" $ M.fromList []
contK <- insert container
Just res <- selectFirst [EmbedsHasMapName ==. (Just "empty map")] []
res @== Entity contK container
it "Embeds a Map with ids as values" $ db $ do
onId <- insert $ OnlyName "nombre"
onId2 <- insert $ OnlyName "nombre2"
let midValue = MapIdValue $ M.fromList [("foo", onId),("bar",onId2)]
mK <- insert midValue
Just mv <- get mK
mv @== midValue
#ifdef WITH_NOSQL
#ifdef WITH_MONGODB
it "List" $ db $ do
k1 <- insert $ HasList []
k2 <- insert $ HasList [k1]
let container = HasList [k1, k2]
contK <- insert container
Just res <- selectFirst [HasListList `anyEq` k2] []
res @== Entity contK container
it "can embed an Entity" $ db $ do
let foo = ARecord "foo"
bar = ARecord "bar"
_ <- insertMany [foo, bar]
arecords <- selectList ([ARecordName ==. "foo"] ||. [ARecordName ==. "bar"]) []
length arecords @== 2
kfoo <- insert foo
let hasEnts = HasArrayWithEntities (Entity kfoo foo) arecords
kEnts <- insert hasEnts
Just retrievedHasEnts <- get kEnts
retrievedHasEnts @== hasEnts
it "can embed objects with ObjectIds" $ db $ do
oid <- liftIO $ genObjectId
let hoid = HasObjectId oid "oid"
hasArr = HasArrayWithObjectIds "array" [hoid]
k <- insert hasArr
Just v <- get k
v @== hasArr
describe "mongoDB filters" $ do
it "mongo single nesting filters" $ db $ do
let usr = User "foo" (Just "pswd") prof
prof = Profile "fstN" "lstN" (Just con)
con = Contact 123456 "[email protected]"
uId <- insert usr
Just r1 <- selectFirst [UserProfile &->. ProfileFirstName `nestEq` "fstN"] []
r1 @== (Entity uId usr)
Just r2 <- selectFirst [UserProfile &~>. ProfileContact ?&->. ContactEmail `nestEq` "[email protected]", UserIdent ==. "foo"] []
r2 @== (Entity uId usr)
it "mongo embedded array filters" $ db $ do
let container = HasListEmbed "list" [
(HasEmbed "embed" (OnlyName "1"))
, (HasEmbed "embed" (OnlyName "2"))
]
contK <- insert container
let contEnt = Entity contK container
Just meq <- selectFirst [HasListEmbedList `anyEq` HasEmbed "embed" (OnlyName "1")] []
meq @== contEnt
Just neq1 <- selectFirst [HasListEmbedList ->. HasEmbedName `nestEq` "embed"] []
neq1 @== contEnt
Just nne1 <- selectFirst [HasListEmbedList ->. HasEmbedName `nestNe` "notEmbed"] []
nne1 @== contEnt
Just neq2 <- selectFirst [HasListEmbedList ~>. HasEmbedEmbed &->. OnlyNameName `nestEq` "1"] []
neq2 @== contEnt
Just nbq1 <- selectFirst [HasListEmbedList ->. HasEmbedName `nestBsonEq` String "embed"] []
nbq1 @== contEnt
Just nbq2 <- selectFirst [HasListEmbedList ~>. HasEmbedEmbed &->. OnlyNameName `nestBsonEq` String "1"] []
nbq2 @== contEnt
it "regexp match" $ db $ do
let container = HasListEmbed "list" [
(HasEmbed "embed" (OnlyName "abcd"))
, (HasEmbed "embed" (OnlyName "efgh"))
]
contK <- insert container
let mkReg t = (t, "ims")
Just res <- selectFirst [HasListEmbedName =~. mkReg "ist"] []
res @== (Entity contK container)
it "nested anyEq" $ db $ do
let top = HasNestedList [IntList [1,2]]
k <- insert top
Nothing <- selectFirst [HasNestedListList ->. IntListInts `nestEq` ([]::[Int])] []
Nothing <- selectFirst [HasNestedListList ->. IntListInts `nestAnyEq` 3] []
Just res <- selectFirst [HasNestedListList ->. IntListInts `nestAnyEq` 2] []
res @== (Entity k top)
describe "mongoDB updates" $ do
it "mongo single nesting updates" $ db $ do
let usr = User "foo" (Just "pswd") prof
prof = Profile "fstN" "lstN" (Just con)
con = Contact 123456 "[email protected]"
uid <- insert usr
let newName = "fstN2"
usr1 <- updateGet uid [UserProfile &->. ProfileFirstName `nestSet` newName]
(profileFirstName $ userProfile usr1) @== newName
let newEmail = "[email protected]"
let newIdent = "bar"
usr2 <- updateGet uid [UserProfile &~>. ProfileContact ?&->. ContactEmail `nestSet` newEmail, UserIdent =. newIdent]
(userIdent usr2) @== newIdent
(fmap contactEmail . profileContact . userProfile $ usr2) @== Just newEmail
it "mongo embedded array updates" $ db $ do
let container = HasListEmbed "list" [
(HasEmbed "embed" (OnlyName "1"))
, (HasEmbed "embed" (OnlyName "2"))
]
contk <- insert container
let contEnt = Entity contk container
pushed <- updateGet contk [HasListEmbedList `push` HasEmbed "embed" (OnlyName "3")]
(Prelude.map (onlyNameName . hasEmbedEmbed) $ hasListEmbedList pushed) @== ["1","2","3"]
-- same, don't add anything
addedToSet <- updateGet contk [HasListEmbedList `addToSet` HasEmbed "embed" (OnlyName "3")]
(Prelude.map (onlyNameName . hasEmbedEmbed) $ hasListEmbedList addedToSet) @== ["1","2","3"]
pulled <- updateGet contk [HasListEmbedList `pull` HasEmbed "embed" (OnlyName "3")]
(Prelude.map (onlyNameName . hasEmbedEmbed) $ hasListEmbedList pulled) @== ["1","2"]
-- now it is new
addedToSet2 <- updateGet contk [HasListEmbedList `addToSet` HasEmbed "embed" (OnlyName "3")]
(Prelude.map (onlyNameName . hasEmbedEmbed) $ hasListEmbedList addedToSet2) @== ["1","2","3"]
allPulled <- updateGet contk [eachOp pull HasListEmbedList
[ HasEmbed "embed" (OnlyName "3")
, HasEmbed "embed" (OnlyName "2")
] ]
(Prelude.map (onlyNameName . hasEmbedEmbed) $ hasListEmbedList allPulled) @== ["1"]
allPushed <- updateGet contk [eachOp push HasListEmbedList
[ HasEmbed "embed" (OnlyName "4")
, HasEmbed "embed" (OnlyName "5")
] ]
(Prelude.map (onlyNameName . hasEmbedEmbed) $ hasListEmbedList allPushed) @== ["1","4","5"]
it "re-orders json inserted from another source" $ db $ do
let cname = T.unpack $ collectionName (error "ListEmbed" :: ListEmbed)
liftIO $ putStrLn =<< readProcess "mongoimport" ["-d", T.unpack dbName, "-c", cname] "{ \"nested\": [{ \"one\": 1, \"two\": 2 }, { \"two\": 2, \"one\": 1}], \"two\": 2, \"one\": 1, \"_id\" : { \"$oid\" : \"50184f5a92d7ae0000001e89\" } }"
-- liftIO $ putStrLn =<< readProcess "mongo" ["--eval", "printjson(db." ++ cname ++ ".find().toArray())", T.unpack dbName] ""
lists <- selectList [] []
fmap entityVal lists @== [ListEmbed [InList 1 2, InList 1 2] 1 2]
#endif
#endif
| pseudonom/persistent | persistent-test/src/EmbedTest.hs | mit | 14,607 | 6 | 19 | 3,854 | 4,144 | 1,990 | 2,154 | 116 | 1 |
{-# LANGUAGE TypeInType, GADTs #-}
module T13988 where
import Data.Kind
data Foo (a :: k) where
MkFoo :: (k ~ Type) => Foo (a :: k)
| ezyang/ghc | testsuite/tests/ghci/scripts/T13988.hs | bsd-3-clause | 137 | 0 | 8 | 31 | 46 | 29 | 17 | -1 | -1 |
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation: bindings
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmBind (
cgTopRhsClosure,
cgBind,
emitBlackHoleCode,
pushUpdateFrame, emitUpdateFrame
) where
#include "HsVersions.h"
import StgCmmExpr
import StgCmmMonad
import StgCmmEnv
import StgCmmCon
import StgCmmHeap
import StgCmmProf (curCCS, ldvEnterClosure, enterCostCentreFun, enterCostCentreThunk,
initUpdFrameProf)
import StgCmmTicky
import StgCmmLayout
import StgCmmUtils
import StgCmmClosure
import StgCmmForeign (emitPrimCall)
import MkGraph
import CoreSyn ( AltCon(..) )
import SMRep
import Cmm
import CmmInfo
import CmmUtils
import CLabel
import StgSyn
import CostCentre
import Id
import IdInfo
import Name
import Module
import ListSetOps
import Util
import BasicTypes
import Outputable
import FastString
import Maybes
import DynFlags
import Control.Monad
------------------------------------------------------------------------
-- Top-level bindings
------------------------------------------------------------------------
-- For closures bound at top level, allocate in static space.
-- They should have no free variables.
cgTopRhsClosure :: DynFlags
-> RecFlag -- member of a recursive group?
-> Id
-> CostCentreStack -- Optional cost centre annotation
-> StgBinderInfo
-> UpdateFlag
-> [Id] -- Args
-> StgExpr
-> (CgIdInfo, FCode ())
cgTopRhsClosure dflags rec id ccs _ upd_flag args body =
let closure_label = mkLocalClosureLabel (idName id) (idCafInfo id)
cg_id_info = litIdInfo dflags id lf_info (CmmLabel closure_label)
lf_info = mkClosureLFInfo dflags id TopLevel [] upd_flag args
in (cg_id_info, gen_code dflags lf_info closure_label)
where
-- special case for a indirection (f = g). We create an IND_STATIC
-- closure pointing directly to the indirectee. This is exactly
-- what the CAF will eventually evaluate to anyway, we're just
-- shortcutting the whole process, and generating a lot less code
-- (#7308)
--
-- Note: we omit the optimisation when this binding is part of a
-- recursive group, because the optimisation would inhibit the black
-- hole detection from working in that case. Test
-- concurrent/should_run/4030 fails, for instance.
--
gen_code dflags _ closure_label
| StgApp f [] <- body, null args, isNonRec rec
= do
cg_info <- getCgIdInfo f
let closure_rep = mkStaticClosureFields dflags
indStaticInfoTable ccs MayHaveCafRefs
[unLit (idInfoToAmode cg_info)]
emitDataLits closure_label closure_rep
return ()
gen_code dflags lf_info closure_label
= do { -- LAY OUT THE OBJECT
let name = idName id
; mod_name <- getModuleName
; let descr = closureDescription dflags mod_name name
closure_info = mkClosureInfo dflags True id lf_info 0 0 descr
caffy = idCafInfo id
info_tbl = mkCmmInfo closure_info -- XXX short-cut
closure_rep = mkStaticClosureFields dflags info_tbl ccs caffy []
-- BUILD THE OBJECT, AND GENERATE INFO TABLE (IF NECESSARY)
; emitDataLits closure_label closure_rep
; let fv_details :: [(NonVoid Id, VirtualHpOffset)]
(_, _, fv_details) = mkVirtHeapOffsets dflags (isLFThunk lf_info)
(addIdReps [])
-- Don't drop the non-void args until the closure info has been made
; forkClosureBody (closureCodeBody True id closure_info ccs
(nonVoidIds args) (length args) body fv_details)
; return () }
unLit (CmmLit l) = l
unLit _ = panic "unLit"
------------------------------------------------------------------------
-- Non-top-level bindings
------------------------------------------------------------------------
cgBind :: StgBinding -> FCode ()
cgBind (StgNonRec name rhs)
= do { (info, fcode) <- cgRhs name rhs
; addBindC info
; init <- fcode
; emit init }
-- init cannot be used in body, so slightly better to sink it eagerly
cgBind (StgRec pairs)
= do { r <- sequence $ unzipWith cgRhs pairs
; let (id_infos, fcodes) = unzip r
; addBindsC id_infos
; (inits, body) <- getCodeR $ sequence fcodes
; emit (catAGraphs inits <*> body) }
{- Note [cgBind rec]
Recursive let-bindings are tricky.
Consider the following pseudocode:
let x = \_ -> ... y ...
y = \_ -> ... z ...
z = \_ -> ... x ...
in ...
For each binding, we need to allocate a closure, and each closure must
capture the address of the other closures.
We want to generate the following C-- code:
// Initialization Code
x = hp - 24; // heap address of x's closure
y = hp - 40; // heap address of x's closure
z = hp - 64; // heap address of x's closure
// allocate and initialize x
m[hp-8] = ...
m[hp-16] = y // the closure for x captures y
m[hp-24] = x_info;
// allocate and initialize y
m[hp-32] = z; // the closure for y captures z
m[hp-40] = y_info;
// allocate and initialize z
...
For each closure, we must generate not only the code to allocate and
initialize the closure itself, but also some initialization Code that
sets a variable holding the closure pointer.
We could generate a pair of the (init code, body code), but since
the bindings are recursive we also have to initialise the
environment with the CgIdInfo for all the bindings before compiling
anything. So we do this in 3 stages:
1. collect all the CgIdInfos and initialise the environment
2. compile each binding into (init, body) code
3. emit all the inits, and then all the bodies
We'd rather not have separate functions to do steps 1 and 2 for
each binding, since in pratice they share a lot of code. So we
have just one function, cgRhs, that returns a pair of the CgIdInfo
for step 1, and a monadic computation to generate the code in step
2.
The alternative to separating things in this way is to use a
fixpoint. That's what we used to do, but it introduces a
maintenance nightmare because there is a subtle dependency on not
being too strict everywhere. Doing things this way means that the
FCode monad can be strict, for example.
-}
cgRhs :: Id
-> StgRhs
-> FCode (
CgIdInfo -- The info for this binding
, FCode CmmAGraph -- A computation which will generate the
-- code for the binding, and return an
-- assignent of the form "x = Hp - n"
-- (see above)
)
cgRhs id (StgRhsCon cc con args)
= withNewTickyCounterThunk False (idName id) $ -- False for "not static"
buildDynCon id True cc con args
{- See Note [GC recovery] in compiler/codeGen/StgCmmClosure.hs -}
cgRhs name (StgRhsClosure cc bi fvs upd_flag _srt args body)
= do dflags <- getDynFlags
mkRhsClosure dflags name cc bi (nonVoidIds fvs) upd_flag args body
------------------------------------------------------------------------
-- Non-constructor right hand sides
------------------------------------------------------------------------
mkRhsClosure :: DynFlags -> Id -> CostCentreStack -> StgBinderInfo
-> [NonVoid Id] -- Free vars
-> UpdateFlag
-> [Id] -- Args
-> StgExpr
-> FCode (CgIdInfo, FCode CmmAGraph)
{- mkRhsClosure looks for two special forms of the right-hand side:
a) selector thunks
b) AP thunks
If neither happens, it just calls mkClosureLFInfo. You might think
that mkClosureLFInfo should do all this, but it seems wrong for the
latter to look at the structure of an expression
Note [Selectors]
~~~~~~~~~~~~~~~~
We look at the body of the closure to see if it's a selector---turgid,
but nothing deep. We are looking for a closure of {\em exactly} the
form:
... = [the_fv] \ u [] ->
case the_fv of
con a_1 ... a_n -> a_i
Note [Ap thunks]
~~~~~~~~~~~~~~~~
A more generic AP thunk of the form
x = [ x_1...x_n ] \.. [] -> x_1 ... x_n
A set of these is compiled statically into the RTS, so we just use
those. We could extend the idea to thunks where some of the x_i are
global ids (and hence not free variables), but this would entail
generating a larger thunk. It might be an option for non-optimising
compilation, though.
We only generate an Ap thunk if all the free variables are pointers,
for semi-obvious reasons.
-}
---------- Note [Selectors] ------------------
mkRhsClosure dflags bndr _cc _bi
[NonVoid the_fv] -- Just one free var
upd_flag -- Updatable thunk
[] -- A thunk
(StgCase (StgApp scrutinee [{-no args-}])
_ _ _ _ -- ignore uniq, etc.
(AlgAlt _)
[(DataAlt _, params, _use_mask,
(StgApp selectee [{-no args-}]))])
| the_fv == scrutinee -- Scrutinee is the only free variable
&& maybeToBool maybe_offset -- Selectee is a component of the tuple
&& offset_into_int <= mAX_SPEC_SELECTEE_SIZE dflags -- Offset is small enough
= -- NOT TRUE: ASSERT(is_single_constructor)
-- The simplifier may have statically determined that the single alternative
-- is the only possible case and eliminated the others, even if there are
-- other constructors in the datatype. It's still ok to make a selector
-- thunk in this case, because we *know* which constructor the scrutinee
-- will evaluate to.
--
-- srt is discarded; it must be empty
cgRhsStdThunk bndr lf_info [StgVarArg the_fv]
where
lf_info = mkSelectorLFInfo bndr offset_into_int
(isUpdatable upd_flag)
(_, _, params_w_offsets) = mkVirtConstrOffsets dflags (addIdReps params)
-- Just want the layout
maybe_offset = assocMaybe params_w_offsets (NonVoid selectee)
Just the_offset = maybe_offset
offset_into_int = the_offset - fixedHdrSize dflags
---------- Note [Ap thunks] ------------------
mkRhsClosure dflags bndr _cc _bi
fvs
upd_flag
[] -- No args; a thunk
(StgApp fun_id args)
| args `lengthIs` (arity-1)
&& all (isGcPtrRep . idPrimRep . unsafe_stripNV) fvs
&& isUpdatable upd_flag
&& arity <= mAX_SPEC_AP_SIZE dflags
&& not (gopt Opt_SccProfilingOn dflags)
-- not when profiling: we don't want to
-- lose information about this particular
-- thunk (e.g. its type) (#949)
-- Ha! an Ap thunk
= cgRhsStdThunk bndr lf_info payload
where
lf_info = mkApLFInfo bndr upd_flag arity
-- the payload has to be in the correct order, hence we can't
-- just use the fvs.
payload = StgVarArg fun_id : args
arity = length fvs
---------- Default case ------------------
mkRhsClosure dflags bndr cc _ fvs upd_flag args body
= do { let lf_info = mkClosureLFInfo dflags bndr NotTopLevel fvs upd_flag args
; (id_info, reg) <- rhsIdInfo bndr lf_info
; return (id_info, gen_code lf_info reg) }
where
gen_code lf_info reg
= do { -- LAY OUT THE OBJECT
-- If the binder is itself a free variable, then don't store
-- it in the closure. Instead, just bind it to Node on entry.
-- NB we can be sure that Node will point to it, because we
-- haven't told mkClosureLFInfo about this; so if the binder
-- _was_ a free var of its RHS, mkClosureLFInfo thinks it *is*
-- stored in the closure itself, so it will make sure that
-- Node points to it...
; let
is_elem = isIn "cgRhsClosure"
bndr_is_a_fv = (NonVoid bndr) `is_elem` fvs
reduced_fvs | bndr_is_a_fv = fvs `minusList` [NonVoid bndr]
| otherwise = fvs
-- MAKE CLOSURE INFO FOR THIS CLOSURE
; mod_name <- getModuleName
; dflags <- getDynFlags
; let name = idName bndr
descr = closureDescription dflags mod_name name
fv_details :: [(NonVoid Id, VirtualHpOffset)]
(tot_wds, ptr_wds, fv_details)
= mkVirtHeapOffsets dflags (isLFThunk lf_info)
(addIdReps (map unsafe_stripNV reduced_fvs))
closure_info = mkClosureInfo dflags False -- Not static
bndr lf_info tot_wds ptr_wds
descr
-- BUILD ITS INFO TABLE AND CODE
; forkClosureBody $
-- forkClosureBody: (a) ensure that bindings in here are not seen elsewhere
-- (b) ignore Sequel from context; use empty Sequel
-- And compile the body
closureCodeBody False bndr closure_info cc (nonVoidIds args)
(length args) body fv_details
-- BUILD THE OBJECT
-- ; (use_cc, blame_cc) <- chooseDynCostCentres cc args body
; let use_cc = curCCS; blame_cc = curCCS
; emit (mkComment $ mkFastString "calling allocDynClosure")
; let toVarArg (NonVoid a, off) = (NonVoid (StgVarArg a), off)
; let info_tbl = mkCmmInfo closure_info
; hp_plus_n <- allocDynClosure (Just bndr) info_tbl lf_info use_cc blame_cc
(map toVarArg fv_details)
-- RETURN
; return (mkRhsInit dflags reg lf_info hp_plus_n) }
-------------------------
cgRhsStdThunk
:: Id
-> LambdaFormInfo
-> [StgArg] -- payload
-> FCode (CgIdInfo, FCode CmmAGraph)
cgRhsStdThunk bndr lf_info payload
= do { (id_info, reg) <- rhsIdInfo bndr lf_info
; return (id_info, gen_code reg)
}
where
gen_code reg -- AHA! A STANDARD-FORM THUNK
= withNewTickyCounterStdThunk False (idName bndr) $ -- False for "not static"
do
{ -- LAY OUT THE OBJECT
mod_name <- getModuleName
; dflags <- getDynFlags
; let (tot_wds, ptr_wds, payload_w_offsets)
= mkVirtHeapOffsets dflags (isLFThunk lf_info) (addArgReps payload)
descr = closureDescription dflags mod_name (idName bndr)
closure_info = mkClosureInfo dflags False -- Not static
bndr lf_info tot_wds ptr_wds
descr
-- ; (use_cc, blame_cc) <- chooseDynCostCentres cc [{- no args-}] body
; let use_cc = curCCS; blame_cc = curCCS
; tickyEnterStdThunk closure_info
-- BUILD THE OBJECT
; let info_tbl = mkCmmInfo closure_info
; hp_plus_n <- allocDynClosure (Just bndr) info_tbl lf_info
use_cc blame_cc payload_w_offsets
-- RETURN
; return (mkRhsInit dflags reg lf_info hp_plus_n) }
mkClosureLFInfo :: DynFlags
-> Id -- The binder
-> TopLevelFlag -- True of top level
-> [NonVoid Id] -- Free vars
-> UpdateFlag -- Update flag
-> [Id] -- Args
-> LambdaFormInfo
mkClosureLFInfo dflags bndr top fvs upd_flag args
| null args =
mkLFThunk (idType bndr) top (map unsafe_stripNV fvs) upd_flag
| otherwise =
mkLFReEntrant top (map unsafe_stripNV fvs) args (mkArgDescr dflags args)
------------------------------------------------------------------------
-- The code for closures
------------------------------------------------------------------------
closureCodeBody :: Bool -- whether this is a top-level binding
-> Id -- the closure's name
-> ClosureInfo -- Lots of information about this closure
-> CostCentreStack -- Optional cost centre attached to closure
-> [NonVoid Id] -- incoming args to the closure
-> Int -- arity, including void args
-> StgExpr
-> [(NonVoid Id, VirtualHpOffset)] -- the closure's free vars
-> FCode ()
{- There are two main cases for the code for closures.
* If there are *no arguments*, then the closure is a thunk, and not in
normal form. So it should set up an update frame (if it is
shared). NB: Thunks cannot have a primitive type!
* If there is *at least one* argument, then this closure is in
normal form, so there is no need to set up an update frame.
The Macros for GrAnSim are produced at the beginning of the
argSatisfactionCheck (by calling fetchAndReschedule).
There info if Node points to closure is available. -- HWL -}
closureCodeBody top_lvl bndr cl_info cc _args arity body fv_details
| arity == 0 -- No args i.e. thunk
= withNewTickyCounterThunk (isStaticClosure cl_info) (closureName cl_info) $
emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl [] $
\(_, node, _) -> thunkCode cl_info fv_details cc node arity body
where
lf_info = closureLFInfo cl_info
info_tbl = mkCmmInfo cl_info
closureCodeBody top_lvl bndr cl_info cc args arity body fv_details
= -- Note: args may be [], if all args are Void
withNewTickyCounterFun (closureName cl_info) args $ do {
; let
lf_info = closureLFInfo cl_info
info_tbl = mkCmmInfo cl_info
-- Emit the main entry code
; emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl args $
\(_offset, node, arg_regs) -> do
-- Emit slow-entry code (for entering a closure through a PAP)
{ mkSlowEntryCode bndr cl_info arg_regs
; dflags <- getDynFlags
; let node_points = nodeMustPointToIt dflags lf_info
node' = if node_points then Just node else Nothing
-- Emit new label that might potentially be a header
-- of a self-recursive tail call. See Note
-- [Self-recursive tail calls] in StgCmmExpr
; loop_header_id <- newLabelC
; emitLabel loop_header_id
; when node_points (ldvEnterClosure cl_info (CmmLocal node))
-- Extend reader monad with information that
-- self-recursive tail calls can be optimized into local
-- jumps
; withSelfLoop (bndr, loop_header_id, arg_regs) $ do
{
-- Main payload
; entryHeapCheck cl_info node' arity arg_regs $ do
{ -- ticky after heap check to avoid double counting
tickyEnterFun cl_info
; enterCostCentreFun cc
(CmmMachOp (mo_wordSub dflags)
[ CmmReg (CmmLocal node) -- See [NodeReg clobbered with loopification]
, mkIntExpr dflags (funTag dflags cl_info) ])
; fv_bindings <- mapM bind_fv fv_details
-- Load free vars out of closure *after*
-- heap check, to reduce live vars over check
; when node_points $ load_fvs node lf_info fv_bindings
; void $ cgExpr body
}}}
}
-- Note [NodeReg clobbered with loopification]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Previously we used to pass nodeReg (aka R1) here. With profiling, upon
-- entering a closure, enterFunCCS was called with R1 passed to it. But since R1
-- may get clobbered inside the body of a closure, and since a self-recursive
-- tail call does not restore R1, a subsequent call to enterFunCCS received a
-- possibly bogus value from R1. The solution is to not pass nodeReg (aka R1) to
-- enterFunCCS. Instead, we pass node, the callee-saved temporary that stores
-- the original value of R1. This way R1 may get modified but loopification will
-- not care.
-- A function closure pointer may be tagged, so we
-- must take it into account when accessing the free variables.
bind_fv :: (NonVoid Id, VirtualHpOffset) -> FCode (LocalReg, WordOff)
bind_fv (id, off) = do { reg <- rebindToReg id; return (reg, off) }
load_fvs :: LocalReg -> LambdaFormInfo -> [(LocalReg, WordOff)] -> FCode ()
load_fvs node lf_info = mapM_ (\ (reg, off) ->
do dflags <- getDynFlags
let tag = lfDynTag dflags lf_info
emit $ mkTaggedObjectLoad dflags reg node off tag)
-----------------------------------------
-- The "slow entry" code for a function. This entry point takes its
-- arguments on the stack. It loads the arguments into registers
-- according to the calling convention, and jumps to the function's
-- normal entry point. The function's closure is assumed to be in
-- R1/node.
--
-- The slow entry point is used for unknown calls: eg. stg_PAP_entry
mkSlowEntryCode :: Id -> ClosureInfo -> [LocalReg] -> FCode ()
-- If this function doesn't have a specialised ArgDescr, we need
-- to generate the function's arg bitmap and slow-entry code.
-- Here, we emit the slow-entry code.
mkSlowEntryCode bndr cl_info arg_regs -- function closure is already in `Node'
| Just (_, ArgGen _) <- closureFunInfo cl_info
= do dflags <- getDynFlags
let node = idToReg dflags (NonVoid bndr)
slow_lbl = closureSlowEntryLabel cl_info
fast_lbl = closureLocalEntryLabel dflags cl_info
-- mkDirectJump does not clobber `Node' containing function closure
jump = mkJump dflags NativeNodeCall
(mkLblExpr fast_lbl)
(map (CmmReg . CmmLocal) (node : arg_regs))
(initUpdFrameOff dflags)
emitProcWithConvention Slow Nothing slow_lbl (node : arg_regs) jump
| otherwise = return ()
-----------------------------------------
thunkCode :: ClosureInfo -> [(NonVoid Id, VirtualHpOffset)] -> CostCentreStack
-> LocalReg -> Int -> StgExpr -> FCode ()
thunkCode cl_info fv_details _cc node arity body
= do { dflags <- getDynFlags
; let node_points = nodeMustPointToIt dflags (closureLFInfo cl_info)
node' = if node_points then Just node else Nothing
; ldvEnterClosure cl_info (CmmLocal node) -- NB: Node always points when profiling
-- Heap overflow check
; entryHeapCheck cl_info node' arity [] $ do
{ -- Overwrite with black hole if necessary
-- but *after* the heap-overflow check
; tickyEnterThunk cl_info
; when (blackHoleOnEntry cl_info && node_points)
(blackHoleIt node)
-- Push update frame
; setupUpdate cl_info node $
-- We only enter cc after setting up update so
-- that cc of enclosing scope will be recorded
-- in update frame CAF/DICT functions will be
-- subsumed by this enclosing cc
do { tickyEnterThunk cl_info
; enterCostCentreThunk (CmmReg nodeReg)
; let lf_info = closureLFInfo cl_info
; fv_bindings <- mapM bind_fv fv_details
; load_fvs node lf_info fv_bindings
; void $ cgExpr body }}}
------------------------------------------------------------------------
-- Update and black-hole wrappers
------------------------------------------------------------------------
blackHoleIt :: LocalReg -> FCode ()
-- Only called for closures with no args
-- Node points to the closure
blackHoleIt node_reg
= emitBlackHoleCode (CmmReg (CmmLocal node_reg))
emitBlackHoleCode :: CmmExpr -> FCode ()
emitBlackHoleCode node = do
dflags <- getDynFlags
-- Eager blackholing is normally disabled, but can be turned on with
-- -feager-blackholing. When it is on, we replace the info pointer
-- of the thunk with stg_EAGER_BLACKHOLE_info on entry.
-- If we wanted to do eager blackholing with slop filling, we'd need
-- to do it at the *end* of a basic block, otherwise we overwrite
-- the free variables in the thunk that we still need. We have a
-- patch for this from Andy Cheadle, but not incorporated yet. --SDM
-- [6/2004]
--
-- Previously, eager blackholing was enabled when ticky-ticky was
-- on. But it didn't work, and it wasn't strictly necessary to bring
-- back minimal ticky-ticky, so now EAGER_BLACKHOLING is
-- unconditionally disabled. -- krc 1/2007
-- Note the eager-blackholing check is here rather than in blackHoleOnEntry,
-- because emitBlackHoleCode is called from CmmParse.
let eager_blackholing = not (gopt Opt_SccProfilingOn dflags)
&& gopt Opt_EagerBlackHoling dflags
-- Profiling needs slop filling (to support LDV
-- profiling), so currently eager blackholing doesn't
-- work with profiling.
when eager_blackholing $ do
emitStore (cmmOffsetW dflags node (fixedHdrSize dflags))
(CmmReg (CmmGlobal CurrentTSO))
emitPrimCall [] MO_WriteBarrier []
emitStore node (CmmReg (CmmGlobal EagerBlackholeInfo))
setupUpdate :: ClosureInfo -> LocalReg -> FCode () -> FCode ()
-- Nota Bene: this function does not change Node (even if it's a CAF),
-- so that the cost centre in the original closure can still be
-- extracted by a subsequent enterCostCentre
setupUpdate closure_info node body
| not (lfUpdatable (closureLFInfo closure_info))
= body
| not (isStaticClosure closure_info)
= if not (closureUpdReqd closure_info)
then do tickyUpdateFrameOmitted; body
else do
tickyPushUpdateFrame
dflags <- getDynFlags
let
bh = blackHoleOnEntry closure_info &&
not (gopt Opt_SccProfilingOn dflags) &&
gopt Opt_EagerBlackHoling dflags
lbl | bh = mkBHUpdInfoLabel
| otherwise = mkUpdInfoLabel
pushUpdateFrame lbl (CmmReg (CmmLocal node)) body
| otherwise -- A static closure
= do { tickyUpdateBhCaf closure_info
; if closureUpdReqd closure_info
then do -- Blackhole the (updatable) CAF:
{ upd_closure <- link_caf node True
; pushUpdateFrame mkBHUpdInfoLabel upd_closure body }
else do {tickyUpdateFrameOmitted; body}
}
-----------------------------------------------------------------------------
-- Setting up update frames
-- Push the update frame on the stack in the Entry area,
-- leaving room for the return address that is already
-- at the old end of the area.
--
pushUpdateFrame :: CLabel -> CmmExpr -> FCode () -> FCode ()
pushUpdateFrame lbl updatee body
= do
updfr <- getUpdFrameOff
dflags <- getDynFlags
let
hdr = fixedHdrSize dflags * wORD_SIZE dflags
frame = updfr + hdr + sIZEOF_StgUpdateFrame_NoHdr dflags
--
emitUpdateFrame dflags (CmmStackSlot Old frame) lbl updatee
withUpdFrameOff frame body
emitUpdateFrame :: DynFlags -> CmmExpr -> CLabel -> CmmExpr -> FCode ()
emitUpdateFrame dflags frame lbl updatee = do
let
hdr = fixedHdrSize dflags * wORD_SIZE dflags
off_updatee = hdr + oFFSET_StgUpdateFrame_updatee dflags
--
emitStore frame (mkLblExpr lbl)
emitStore (cmmOffset dflags frame off_updatee) updatee
initUpdFrameProf frame
-----------------------------------------------------------------------------
-- Entering a CAF
--
-- See Note [CAF management] in rts/sm/Storage.c
link_caf :: LocalReg -- pointer to the closure
-> Bool -- True <=> updatable, False <=> single-entry
-> FCode CmmExpr -- Returns amode for closure to be updated
-- This function returns the address of the black hole, so it can be
-- updated with the new value when available.
link_caf node _is_upd = do
{ dflags <- getDynFlags
-- Call the RTS function newCAF, returning the newly-allocated
-- blackhole indirection closure
; let newCAF_lbl = mkForeignLabel (fsLit "newCAF") Nothing
ForeignLabelInExternalPackage IsFunction
; bh <- newTemp (bWord dflags)
; emitRtsCallGen [(bh,AddrHint)] newCAF_lbl
[ (CmmReg (CmmGlobal BaseReg), AddrHint),
(CmmReg (CmmLocal node), AddrHint) ]
False
-- see Note [atomic CAF entry] in rts/sm/Storage.c
; updfr <- getUpdFrameOff
; let target = entryCode dflags (closureInfoPtr dflags (CmmReg (CmmLocal node)))
; emit =<< mkCmmIfThen
(cmmEqWord dflags (CmmReg (CmmLocal bh)) (zeroExpr dflags))
-- re-enter the CAF
(mkJump dflags NativeNodeCall target [] updfr)
; return (CmmReg (CmmLocal bh)) }
------------------------------------------------------------------------
-- Profiling
------------------------------------------------------------------------
-- For "global" data constructors the description is simply occurrence
-- name of the data constructor itself. Otherwise it is determined by
-- @closureDescription@ from the let binding information.
closureDescription :: DynFlags
-> Module -- Module
-> Name -- Id of closure binding
-> String
-- Not called for StgRhsCon which have global info tables built in
-- CgConTbls.lhs with a description generated from the data constructor
closureDescription dflags mod_name name
= showSDocDump dflags (char '<' <>
(if isExternalName name
then ppr name -- ppr will include the module name prefix
else pprModule mod_name <> char '.' <> ppr name) <>
char '>')
-- showSDocDump, because we want to see the unique on the Name.
| lukexi/ghc-7.8-arm64 | compiler/codeGen/StgCmmBind.hs | bsd-3-clause | 30,736 | 8 | 26 | 9,165 | 4,572 | 2,391 | 2,181 | 372 | 3 |
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Instance(elabInstance) where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.DSL
import Idris.Error
import Idris.Delaborate
import Idris.Imports
import Idris.Coverage
import Idris.DataOpts
import Idris.Providers
import Idris.Primitives
import Idris.Inliner
import Idris.PartialEval
import Idris.DeepSeq
import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting)
import IRTS.Lang
import Idris.Elab.Type
import Idris.Elab.Data
import Idris.Elab.Utils
import Idris.Elab.Term
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.Typecheck
import Idris.Core.CaseTree
import Idris.Docstrings
import Prelude hiding (id, (.))
import Control.Category
import Control.Applicative hiding (Const)
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import Data.List
import Data.Maybe
import Debug.Trace
import qualified Data.Map as Map
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Char(isLetter, toLower)
import Data.List.Split (splitOn)
import Util.Pretty(pretty, text)
elabInstance :: ElabInfo -> SyntaxInfo ->
Docstring (Either Err PTerm) ->
[(Name, Docstring (Either Err PTerm))] ->
ElabWhat -> -- phase
FC -> [(Name, PTerm)] -> -- constraints
Name -> -- the class
FC -> -- precise location of class name
[PTerm] -> -- class parameters (i.e. instance)
PTerm -> -- full instance type
Maybe Name -> -- explicit name
[PDecl] -> Idris ()
elabInstance info syn doc argDocs what fc cs n nfc ps t expn ds = do
i <- getIState
(n, ci) <- case lookupCtxtName n (idris_classes i) of
[c] -> return c
[] -> ifail $ show fc ++ ":" ++ show n ++ " is not a type class"
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
let emptyclass = null (class_methods ci)
when (what /= EDefns) $ do
nty <- elabType' True info syn doc argDocs fc [] iname NoFC t
-- if the instance type matches any of the instances we have already,
-- and it's not a named instance, then it's overlapping, so report an error
case expn of
Nothing -> do mapM_ (maybe (return ()) overlapping . findOverlapping i (class_determiners ci) (delab i nty))
(map fst $ class_instances ci)
addInstance intInst True n iname
Just _ -> addInstance intInst False n iname
when (what /= ETypes && (not (null ds && not emptyclass))) $ do
let ips = zip (class_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 superclassInstances = map (substInstance ips pnames) (class_default_superclasses ci)
undefinedSuperclassInstances <- filterM (fmap not . isOverlapping i) superclassInstances
mapM_ (rec_elabDecl info EAll info) undefinedSuperclassInstances
let all_meths = map (nsroot . fst) (class_methods ci)
let mtys = map (\ (n, (op, t)) ->
let t_in = substMatchesShadow ips pnames t
mnamemap = map (\n -> (n, PRef fc [] (decorate ns iname n)))
all_meths
t' = substMatchesShadow mnamemap pnames t_in in
(decorate ns iname n,
op, coninsert cs t', t'))
(class_methods ci)
logLvl 3 (show (mtys, ips))
logLvl 5 ("Before defaults: " ++ show ds ++ "\n" ++ show (map fst (class_methods ci)))
let ds_defs = insertDefaults i iname (class_defaults ci) ns ds
logLvl 3 ("After defaults: " ++ show ds_defs ++ "\n")
let ds' = reorderDefs (map fst (class_methods ci)) $ ds_defs
logLvl 1 ("Reordered: " ++ show ds' ++ "\n")
mapM_ (warnMissing ds' ns iname) (map fst (class_methods ci))
mapM_ (checkInClass (map fst (class_methods ci))) (concatMap defined ds')
let wbTys = map mkTyDecl mtys
let wbVals = map (decorateid (decorate ns iname)) ds'
let wb = wbTys ++ wbVals
logLvl 3 $ "Method types " ++ showSep "\n" (map (show . showDeclImp verbosePPOption . mkTyDecl) mtys)
logLvl 3 $ "Instance is " ++ show ps ++ " implicits " ++
show (concat (nub wparams))
-- Bring variables in instance head into scope
let headVars = nub $ mapMaybe (\p -> case p of
PRef _ _ n ->
case lookupTy n (tt_ctxt ist) of
[] -> Just n
_ -> Nothing
_ -> Nothing) ps
-- let lhs = PRef fc iname
let lhs = PApp fc (PRef fc [] iname)
(map (\n -> pimp n (PRef fc [] n) True) headVars)
let rhs = PApp fc (PRef fc [] (instanceCtorName ci))
(map (pexp . mkMethApp) mtys)
logLvl 5 $ "Instance LHS " ++ show lhs ++ " " ++ show headVars
logLvl 5 $ "Instance RHS " ++ show rhs
let idecls = [PClauses fc [Dictionary] iname
[PClause fc iname lhs [] rhs wb]]
logLvl 1 (show idecls)
push_estack iname True
mapM_ (rec_elabDecl info EAll info) idecls
pop_estack
ist <- getIState
checkInjectiveArgs fc n (class_determiners ci) (lookupTyExact iname (tt_ctxt ist))
addIBC (IBCInstance intInst (isNothing expn) n iname)
where
intInst = case ps of
[PConstant NoFC (AType (ATInt ITNative))] -> True
_ -> False
mkiname n' ns ps' expn' =
case expn' of
Nothing -> case ns of
Nothing -> SN (sInstanceN n' (map show ps'))
Just m -> sNS (SN (sInstanceN n' (map show ps'))) m
Just nm -> nm
substInstance ips pnames (PInstance doc argDocs syn _ cs n nfc ps t expn ds)
= PInstance doc argDocs syn fc cs n nfc (map (substMatchesShadow ips pnames) ps) (substMatchesShadow ips pnames t) expn ds
isOverlapping i (PInstance doc argDocs syn _ _ n nfc ps t expn _)
= case lookupCtxtName n (idris_classes 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 class, just let elabInstance 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, _) <-
tclift $ elaborate ctxt (idris_datatypes 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
ctxt <- getContext
(cty, _) <- recheckC fc id [] tyT
let nty = normalise ctxt [] cty
return $ any (isJust . findOverlapping i (class_determiners ci) (delab i nty)) (map fst $ class_instances ci)
findOverlapping i dets t n
| take 2 (show n) == "@@" = 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 instance: " ++ 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
mkMethApp (n, _, _, ty)
= lamBind 0 ty (papp fc (PRef fc [] n) (methArgs 0 ty))
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 (UN n) = NS (SN (MethodN (UN n))) ns
decorate ns iname (NS (UN n) s) = NS (SN (MethodN (UN n))) 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
coninsert :: [(Name, PTerm)] -> PTerm -> PTerm
coninsert cs (PPi p@(Imp _ _ _ _) n fc t sc) = PPi p n fc t (coninsert cs sc)
coninsert cs sc = conbind cs sc
-- Reorder declarations to be in the same order as defined in the
-- class 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 ()
checkInClass ns meth
| any (eqRoot meth) ns = return ()
| otherwise = tclift $ tfail (At fc (Msg $
show meth ++ " not a method of class " ++ 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
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
| TimRichter/Idris-dev | src/Idris/Elab/Instance.hs | bsd-3-clause | 14,083 | 52 | 23 | 5,077 | 5,022 | 2,545 | 2,477 | 276 | 38 |
-----------------------------------------------------------------------------
-- |
-- Module : PwPfConversion
-- Copyright : (c) Jose Proenca 2005
-- License : GPL
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Translations between pointwise and point-free expressions, expressed in
-- the modules "PWCore" and "PointFree".
--
-----------------------------------------------------------------------------
module PwPfConversion (
-- * Translation from "Pointfree" to "PWCore"
pf2core,
-- * Translation from "PWCore" to "Pointfree"
core2Pf
) where
import PWCore
import Pointfree
{- | Applies a simple transformation from a 'PFTerm' to a 'PWTerm', in an automated manner.
-}
pf2core :: PFTerm -> PWTerm
pf2core BANG = Abstr "x" Unit
pf2core ID = Abstr "x" (Var' "x")
pf2core APP = Abstr "x" ((Fst $ Var'"x") :@:
(Snd $ Var' "x"))
pf2core (Curry t1) = Abstr "x" (Abstr "y"
((pf2core t1):@:((Var' "y"):><:(Var' "x"))) )
pf2core (t1 :.: t2) = Abstr "x" ((pf2core t1):@:((pf2core t2):@:(Var' "x")))
pf2core (t1 :\/: t2) = Abstr "x" (Case (Var' "x")
("y" , (pf2core t1):@:(Var' "y"))
("z" , (pf2core t2):@:(Var' "z")))
pf2core (t1 :/\: t2) = Abstr "x" ((pf2core t1):><:(pf2core t2))
pf2core FST = Abstr "x" (Fst $ Var' "x")
pf2core SND = Abstr "x" (Snd $ Var' "x")
pf2core INL = Abstr "x" (Inl $ Var' "x")
pf2core INR = Abstr "x" (Inr $ Var' "x")
pf2core (IN str) = Abstr "x" (In str $ Var' "x")
pf2core (OUT str) = Abstr "x" (Out str $ Var' "x")
pf2core FIX = Abstr "x" (Fix $ Var' "x")
pf2core (Macro x) = Var' x
-- | A context will be a left-nested pair, where the most to the
-- right value will be a never used constant
type Context = PWTerm
-- | Calculates a "path" to a variable in a context by composing the
-- "fst" and "snd" functions
path :: Context -> PWTerm -> PFTerm
path (t:><:(Var' y)) (Var' x)
| x == y = SND
| otherwise = (path t (Var' x)) :.: FST
path _ (Var' x) = Macro x
-- | Given a Context, it calculates the translation from Core
-- to Point-free
core2pf :: Context -> PWTerm -> PFTerm
{- | Applies the conversion of a pointwise expression of type @A@ and obtains
a pointfree expression of type @1->A@, to which is applied a poinfree macro
to get the correct type again.
-}
-- (unpnt f = app . (f . bang /\ id))
core2Pf :: PWTerm -> PFTerm
core2Pf t = APP :.: (((core2pf Unit t) :.: BANG) :/\: ID)
-- paramorphisms for Int
core2pf cont ((((Fix (Abstr r1 (Abstr n1 (Abstr f1 (Abstr z1
(Case (Out typ (Var' n2))
(_,Var' z2)
(y1,(Var' f2 :@: Var' y2) :@: (((Var' r2 :@: Var' y3) :@: Var' f3)
:@: Var' z3)))))))) :@: n) :@: f) :@: z)
| r1==r2 && n1==n2 && f1==f2 && f2==f3 &&
z1==z2 && z2==z3 && y1==y2 && y2==y3 &&
isClosed f && isClosed z =
(PARA typ (unpoint $ g(f,z))) :.: (core2pf cont n)
where
unpoint f = APP :.: ((f :.: BANG) :/\: ID)
g (f,z) = let y = getFV f; x = getFV (z:><:Var' y)
in core2pf Unit $
Abstr x $
Case (Var' x) ("_",z)
(y,f :@: (Snd$Var' y) :@: (Fst$Var' y))
----------------------------- pred ^ - recursive result ^
-- paramorphisms for [a]
core2pf cont ((((Fix (Abstr r1 (Abstr l1 (Abstr f1 (Abstr z1
(Case (Out typ (Var' l2))
(_,Var' z2)
(y1,Var' f2 :@: (Fst (Var' y2)) :@: (Snd (Var' y3)) :@:
(Var' r2 :@: (Snd (Var' y4)) :@: Var' f3 :@: Var' z3))))))))
:@: n) :@: f) :@: z)
| r1==r2 && l1==l2 && f1==f2 && f2==f3 &&
z1==z2 && z2==z3 && y1==y2 && y2==y3 && y3==y4 &&
isClosed f && isClosed z =
(PARA typ (unpoint $ g(f,z))) :.: (core2pf cont n)
where
unpoint f = APP :.: ((f :.: BANG) :/\: ID)
g (f,z) = let y = getFV f; x = getFV (z:><:Var' y)
in core2pf Unit $
Abstr x $
Case (Var' x) ("_",z)
(y,f :@: (Fst$Var' y) :@: (Snd$Snd$Var' y) :@: (Fst$Snd$Var' y))
------------------------- head ^ --------- tail ^ --- recursive result ^
core2pf _ Unit = BANG
core2pf cont var@(Var' x) = path cont var
core2pf cont (t1:><:t2) = (core2pf cont t1):/\:(core2pf cont t2)
core2pf cont (Fst t) = FST :.: (core2pf cont t)
core2pf cont (Snd t) = SND :.: (core2pf cont t)
core2pf cont (Abstr x t) = Curry (core2pf (cont:><:(Var' x)) t)
core2pf cont (t1:@:t2) = APP :.: ((core2pf cont t1):/\:(core2pf cont t2))
core2pf cont (Inl t) = INL :.: (core2pf cont t)
core2pf cont (Inr t) = INR :.: (core2pf cont t)
core2pf cont (Case t (x,u) (y,v)) =
APP :.: ((Curry (((core2pf (cont:><:(Var' x)) u) :\/:
(core2pf (cont:><:(Var' y)) v)) :.: (Macro "distr")))
:/\: (core2pf cont t))
core2pf cont (In str t) = IN str :.: (core2pf cont t)
core2pf cont (Out str t) = OUT str :.: (core2pf cont t)
core2pf cont (Fix t) = FIX :.: (core2pf cont t)
-- get the free variables
getFV :: PWTerm -> String
getFV = (\x->x++"_").maximum.getVars
getVars :: PWTerm -> [String]
getVars (Var' str) = [str]
getVars Unit = []
getVars (t1:><:t2) = (getVars t1) ++ (getVars t2)
getVars (Abstr str t) = str:(getVars t)
getVars (t1:@:t2) = (getVars t1) ++ (getVars t2)
getVars (Case t1 (str1,t2) (str2,t3)) =
str1:str2:(getVars t1++getVars t2++getVars t3)
getVars (Fst t) = getVars t
getVars (Snd t) = getVars t
getVars (Inl t) = getVars t
getVars (Inr t) = getVars t
getVars (In _ t) = getVars t
getVars (Out _ t) = getVars t
getVars (Fix t) = getVars t
isClosed :: PWTerm -> Bool
isClosed t = closed t []
where
closed Unit _ = True
closed (Var' str) ac = str `elem` ac
closed (t1:><:t2) ac = (closed t1 ac) && (closed t2 ac)
closed (Abstr str t) ac = closed t (str:ac)
closed (t1:@:t2) ac = (closed t1 ac) && (closed t2 ac)
closed (Case t1 (str1,t2) (str2,t3)) ac =
(closed t1 ac) && (closed t2 (str1:ac)) && (closed t3 (str2:ac))
closed (Fst t) ac = closed t ac
closed (Snd t) ac = closed t ac
closed (Inl t) ac = closed t ac
closed (Inr t) ac = closed t ac
closed (In _ t) ac = closed t ac
closed (Out _ t) ac = closed t ac
closed (Fix t) ac = closed t ac
| forste/haReFork | refactorer/PwPf/PwPfConversion.hs | bsd-3-clause | 6,416 | 0 | 36 | 1,768 | 2,813 | 1,439 | 1,374 | 114 | 13 |
{-# LANGUAGE MagicHash, UnboxedTuples, MultiParamTypeClasses, TypeFamilies,
FunctionalDependencies, KindSignatures, PolyKinds, DataKinds,
UndecidableInstances #-}
module T14185 where
import GHC.Types
import GHC.Prim
class Unbox (t :: *) (r :: TYPE k) | t -> r, r -> t where
unbox :: t -> r
box :: r -> t
instance Unbox Int Int# where
unbox (I# i) = i
box i = I# i
instance Unbox Char Char# where
unbox (C# c) = c
box c = C# c
instance (Unbox a a', Unbox b b') => Unbox (a,b) (# a', b' #) where
unbox (a,b) = (# unbox a, unbox b #)
box (# a, b #) = (box a, box b)
testInt :: Int
testInt = box (unbox 1)
testTup :: (Int, Char)
testTup = box (unbox (1, 'a'))
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T14185.hs | bsd-3-clause | 684 | 0 | 8 | 156 | 280 | 152 | 128 | 22 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
module Test10276 where
f1 = [| bar |]
f2 = [e| bar |]
class QQExp a b where
qqExp x = [||fst $ runState $$(qqExpM x)
((0,M.empty) :: (Int,M.Map L.Name [L.Operand]))||]
class QQExp2 a b where
qqExp x = [e||fst $ runState $$(qqExpM x)
((0,M.empty) :: (Int,M.Map L.Name [L.Operand]))||]
| ezyang/ghc | testsuite/tests/ghc-api/annotations/Test10276.hs | bsd-3-clause | 402 | 3 | 15 | 113 | 176 | 102 | 74 | -1 | -1 |
module T7702Plugin ( plugin ) where
import GhcPlugins
-- A plugin that does nothing but tickle CoreM's writer.
plugin :: Plugin
plugin = defaultPlugin { installCoreToDos = install }
where
install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
install _ todos = do
reinitializeGlobals
putMsgS "T7702Plugin"
-- 1 million times, so the allocation in this plugin dominates allocation due
-- to other compiler flags and the test framework can easily catch the difference
-- can't use replicateM_ because it causes its own problems
nothingX100000 ; nothingX100000 ; nothingX100000 ; nothingX100000 ; nothingX100000
nothingX100000 ; nothingX100000 ; nothingX100000 ; nothingX100000 ; nothingX100000
return todos
-- this will result in a call to plusWriter in CoreM's
-- >>= implementation, which was causing the space leak
nothing :: CoreM ()
nothing = liftIO (return ())
nothingX10 :: CoreM ()
nothingX10 = do
nothing ; nothing ; nothing ; nothing ; nothing
nothing ; nothing ; nothing ; nothing ; nothing
nothingX100 :: CoreM ()
nothingX100 = do
nothingX10 ; nothingX10 ; nothingX10 ; nothingX10 ; nothingX10
nothingX10 ; nothingX10 ; nothingX10 ; nothingX10 ; nothingX10
nothingX1000 :: CoreM ()
nothingX1000 = do
nothingX100 ; nothingX100 ; nothingX100 ; nothingX100 ; nothingX100
nothingX100 ; nothingX100 ; nothingX100 ; nothingX100 ; nothingX100
nothingX10000 :: CoreM ()
nothingX10000 = do
nothingX1000 ; nothingX1000 ; nothingX1000 ; nothingX1000 ; nothingX1000
nothingX1000 ; nothingX1000 ; nothingX1000 ; nothingX1000 ; nothingX1000
nothingX100000 :: CoreM ()
nothingX100000 = do
nothingX10000 ; nothingX10000 ; nothingX10000 ; nothingX10000 ; nothingX10000
nothingX10000 ; nothingX10000 ; nothingX10000 ; nothingX10000 ; nothingX10000
| urbanslug/ghc | testsuite/tests/simplCore/should_compile/T7702plugin/T7702Plugin.hs | bsd-3-clause | 1,918 | 0 | 10 | 425 | 417 | 211 | 206 | 33 | 1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
-- !!! class/instance mumble that failed Lint at one time
--
module ShouldCompile where
class Foo a where
op :: Int -> a -> Bool
data Wibble a b c = MkWibble a b c
instance (Foo a, Foo b, Foo c) => Foo (Wibble a b c) where
op x y = error "xxx"
| urbanslug/ghc | testsuite/tests/simplCore/should_compile/simpl002.hs | bsd-3-clause | 306 | 0 | 8 | 69 | 97 | 53 | 44 | 7 | 0 |
{-# Language TemplateHaskell #-}
module Optimizer where
import Language.Haskell.TH
explode :: Name -> ExpQ -> ExpQ
explode name f =
do TyConI (DataD _ _ _ _ constructors _) <- reify name
xName <- newName "x"
lam1E (varP xName)
(caseE (varE xName)
[ match (conP constructorName [])
(normalB (appE f (conE constructorName)))
[]
| NormalC constructorName [] <- constructors
])
| glguy/advent2016 | asmprog-final/Optimizer.hs | isc | 495 | 0 | 17 | 181 | 158 | 78 | 80 | 13 | 1 |
{-# LANGUAGE
TemplateHaskell
, GeneralizedNewtypeDeriving
, DeriveGeneric
#-}
module Cido.Types.User where
import Happstack.Server.Internal.Types (FromReqURI(..))
import Text.Email.Validate (EmailAddress)
import GHC.Generics
import Data.Aeson
import Text.Read (readMaybe)
import Data.Time (UTCTime)
import Data.Text (Text)
import Data.UUID (UUID)
import Hasql.Postgres
import Hasql.Backend
import Util ()
newtype UserId = UserId { unUserId :: UUID }
deriving
(Show, Eq, Ord, Generic, CxValue Postgres, ToJSON, FromJSON)
newtype EmailAddr = EmailAddr { unEmailAddr :: EmailAddress }
deriving
(Show, Eq, Ord, Generic, CxValue Postgres, ToJSON, FromJSON)
newtype HashedPassword = HashedPassword { unHashedPassword :: Text }
deriving
(Show, Eq, Ord, Generic, CxValue Postgres, FromJSON)
newtype RawPassword = RawPassword { unRawPassword :: Text }
deriving
(Show, Eq, Ord, Generic, CxValue Postgres, FromJSON)
instance FromReqURI UserId where
fromReqURI = readMaybe
instance Read UserId where
readsPrec d r = map f (readsPrec d r) where f (i, s) = (UserId i, s)
instance ToJSON RawPassword where
toJSON _ = Null
instance ToJSON HashedPassword where
toJSON _ = Null
data User = User
{ id :: UserId
, email :: EmailAddr
, password :: HashedPassword
, created_at :: UTCTime
, updated_at :: UTCTime
} deriving (Show, Eq, Ord, Generic)
instance FromJSON User
instance ToJSON User
| L8D/cido-api | lib/Cido/Types/User.hs | mit | 1,559 | 0 | 9 | 379 | 450 | 257 | 193 | 45 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Codec.Soten.PostProcess.ConvertToLHTest where
import Test.Hspec
import Control.Lens ((&), (^.), (.~))
import qualified Data.Vector as V
import Linear
import Codec.Soten.PostProcess.ConvertToLH
import Codec.Soten.Scene
import Codec.Soten.Scene.Anim
import Codec.Soten.Scene.Mesh
import Codec.Soten.Scene.Material
transformMatrix, flipedTransMatrix :: M44 Float
transformMatrix = V4 (V4 0 1 1 1) (V4 0 1 1 1) (V4 0 1 1 1) (V4 0 1 1 1)
flipedTransMatrix = V4
(V4 0 1 (-1) 1)
(V4 0 1 (-1) 1)
(V4 0 (-1) 1 (-1))
(V4 0 1 (-1) 1)
rootNode, nodeWithTransform :: Node
nodeWithTransform = newNode & nodeTransformation .~ Just transformMatrix
rootNode = nodeWithTransform & nodeChildren .~ V.singleton nodeWithTransform
mesh :: Mesh
mesh = newMesh
& meshVertices .~ V.singleton (V3 1 2 3)
& meshNormals .~ V.singleton (V3 4 5 6)
& meshTangents .~ V.singleton (V3 7 8 9)
& meshBitangents .~ V.singleton (V3 1 3 6)
& meshBones .~ V.singleton bone
bone :: Bone
bone = newBone & boneOffsetMatrix .~ transformMatrix
material :: Material
material = addProperty newMaterial property
where
property = MaterialTexMapAxis TextureTypeNone (V3 (-1) (-2) (-3))
animation :: Animation
animation = newAnimation & animationChannels .~ V.singleton animNode
where
animNode :: NodeAnim
animNode = newNodeAnim
& nodeAnimPositionKeys .~ V.singleton vecKey
& nodeAnimRotationKeys .~ V.singleton quatKey
vecKey = VectorKey 0.1 (V3 (-1) (-2) 3)
quatKey = QuatKey 0.2 (Quaternion 1 (V3 (-1) (-2) 3))
originScene, scene :: Scene
originScene = newScene
& sceneRootNode .~ rootNode
& sceneMeshes .~ V.singleton mesh
& sceneMaterials .~ V.singleton material
& sceneAnimations .~ V.singleton animation
scene = apply originScene
convertToLHTest :: Spec
convertToLHTest =
describe "Convert to Left Handed post process" $ do
context "Converts a node" $ do
let fixedRootNode = scene ^. sceneRootNode
it "Itself" $
(fixedRootNode ^. nodeTransformation) `shouldBe` Just flipedTransMatrix
it "And its children" $ do
let nodeChild = V.head (fixedRootNode ^. nodeChildren)
(nodeChild ^. nodeTransformation) `shouldBe` Just flipedTransMatrix
context "Converts a mesh" $ do
let fixedMesh = V.head (scene ^. sceneMeshes)
it "Vertices coordicates" $
V.head (fixedMesh ^. meshVertices) `shouldBe` V3 1 2 (-3)
it "Normals coordicates" $
V.head (fixedMesh ^. meshNormals) `shouldBe` V3 4 5 (-6)
it "Tangents" $
V.head (fixedMesh ^. meshTangents) `shouldBe` V3 7 8 (-9)
it "Bitangents" $
V.head (fixedMesh ^. meshBitangents) `shouldBe` V3 (-1) (-3) 6
it "Bones" $ do
let fixedBone = V.head (fixedMesh ^. meshBones)
(fixedBone ^. boneOffsetMatrix) `shouldBe` flipedTransMatrix
context "Materials" $ do
let fixedMaterial = V.head (scene ^. sceneMaterials)
it "Texture map axis" $
V.head (fixedMaterial ^. materialProperties) `shouldBe`
MaterialTexMapAxis TextureTypeNone (V3 1 2 3)
context "Animation nodes" $ do
let fixedAnimation = V.head (scene ^. sceneAnimations)
fixedNodeAnim = V.head (fixedAnimation ^. animationChannels)
it "Position keys" $
V.head (fixedNodeAnim ^. nodeAnimPositionKeys) `shouldBe`
VectorKey 0.1 (V3 1 2 3)
it "Rotation keys" $
V.head (fixedNodeAnim ^. nodeAnimRotationKeys) `shouldBe`
QuatKey 0.2 (Quaternion 1 (V3 1 2 3))
| triplepointfive/soten | test/Codec/Soten/PostProcess/ConvertToLHTest.hs | mit | 3,610 | 0 | 19 | 836 | 1,237 | 638 | 599 | 85 | 1 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, FlexibleInstances #-}
-- | If you are interested in the IHaskell library for the purpose of
-- augmenting the IHaskell notebook or writing your own display mechanisms
-- and widgets, this module contains all functions you need.
--
-- In order to create a display mechanism for a particular data type, write
-- a module named (for example) @IHaskell.Display.YourThing@ in a package named @ihaskell-yourThing@.
-- (Note the capitalization - it's important!) Then, in that module, add an
-- instance of @IHaskellDisplay@ for your data type. Similarly, to create
-- a widget, add an instance of @IHaskellWidget@.
--
-- An example of creating a display is provided in the <http://gibiansky.github.io/IHaskell/demo.html demo notebook>.
--
module IHaskell.Display (
-- * Rich display and interactive display typeclasses and types
IHaskellDisplay(..),
Display(..),
DisplayData(..),
IHaskellWidget(..),
-- ** Interactive use functions
printDisplay,
-- * Constructors for displays
plain, html, png, jpg, svg, latex, javascript, many,
-- ** Image and data encoding functions
Width, Height, Base64(..),
encode64, base64,
-- ** Utilities
switchToTmpDir,
-- * Internal only use
displayFromChan,
serializeDisplay,
Widget(..),
) where
import ClassyPrelude
import Data.Serialize as Serialize
import Data.ByteString hiding (map, pack)
import Data.String.Utils (rstrip)
import qualified Data.ByteString.Base64 as Base64
import qualified Data.ByteString.Char8 as Char
import Data.Aeson (Value)
import System.Directory(getTemporaryDirectory, setCurrentDirectory)
import Control.Concurrent.STM.TChan
import System.IO.Unsafe (unsafePerformIO)
import IHaskell.Types
type Base64 = Text
-- | these instances cause the image, html etc. which look like:
--
-- > Display
-- > [Display]
-- > IO [Display]
-- > IO (IO Display)
--
-- be run the IO and get rendered (if the frontend allows it) in the pretty
-- form.
instance IHaskellDisplay a => IHaskellDisplay (IO a) where
display = (display =<<)
instance IHaskellDisplay Display where
display = return
instance IHaskellDisplay DisplayData where
display disp = return $ Display [disp]
instance IHaskellDisplay a => IHaskellDisplay [a] where
display disps = do
displays <- mapM display disps
return $ ManyDisplay displays
-- | Encode many displays into a single one. All will be output.
many :: [Display] -> Display
many = ManyDisplay
-- | Generate a plain text display.
plain :: String -> DisplayData
plain = DisplayData PlainText . pack . rstrip
-- | Generate an HTML display.
html :: String -> DisplayData
html = DisplayData MimeHtml . pack
-- | Generate an SVG display.
svg :: String -> DisplayData
svg = DisplayData MimeSvg . pack
-- | Generate a LaTeX display.
latex :: String -> DisplayData
latex = DisplayData MimeLatex . pack
-- | Generate a Javascript display.
javascript :: String -> DisplayData
javascript = DisplayData MimeJavascript . pack
-- | Generate a PNG display of the given width and height. Data must be
-- provided in a Base64 encoded manner, suitable for embedding into HTML.
-- The @base64@ function may be used to encode data into this format.
png :: Width -> Height -> Base64 -> DisplayData
png width height = DisplayData (MimePng width height)
-- | Generate a JPG display of the given width and height. Data must be
-- provided in a Base64 encoded manner, suitable for embedding into HTML.
-- The @base64@ function may be used to encode data into this format.
jpg :: Width -> Height -> Base64 -> DisplayData
jpg width height = DisplayData (MimeJpg width height)
-- | Convert from a string into base 64 encoded data.
encode64 :: String -> Base64
encode64 str = base64 $ Char.pack str
-- | Convert from a ByteString into base 64 encoded data.
base64 :: ByteString -> Base64
base64 = decodeUtf8 . Base64.encode
-- | For internal use within IHaskell.
-- Serialize displays to a ByteString.
serializeDisplay :: Display -> ByteString
serializeDisplay = Serialize.encode
-- | Items written to this chan will be included in the output sent
-- to the frontend (ultimately the browser), the next time IHaskell
-- has an item to display.
{-# NOINLINE displayChan #-}
displayChan :: TChan Display
displayChan = unsafePerformIO newTChanIO
-- | Take everything that was put into the 'displayChan' at that point
-- out, and make a 'Display' out of it.
displayFromChan :: IO (Maybe Display)
displayFromChan =
Just . many <$> unfoldM (atomically $ tryReadTChan displayChan)
-- | This is unfoldM from monad-loops. It repeatedly runs an IO action
-- until it return Nothing, and puts all the Justs in a list.
-- If you find yourself using more functionality from monad-loops, just add
-- the package dependency instead of copying more code from it.
unfoldM :: IO (Maybe a) -> IO [a]
unfoldM f = maybe (return []) (\r -> (r:) <$> unfoldM f) =<< f
-- | Write to the display channel. The contents will be displayed in the
-- notebook once the current execution call ends.
printDisplay :: IHaskellDisplay a => a -> IO ()
printDisplay disp = display disp >>= atomically . writeTChan displayChan
-- | Convenience function for client libraries. Switch to a temporary
-- directory so that any files we create aren't visible. On Unix, this is
-- usually /tmp.
switchToTmpDir = void (try switchDir :: IO (Either SomeException ()))
where
switchDir =
getTemporaryDirectory >>=
setCurrentDirectory
| aostiles/LiveHaskell | src/IHaskell/Display.hs | mit | 5,475 | 0 | 10 | 952 | 852 | 497 | 355 | 72 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE PolyKinds #-}
module Data.Type.Function
( Id
, Const
, (:.:)
, Flip
, (:$:)
, (:&:)
, On
) where
type Id (x :: b) = x
type Const (x :: a) (y :: b) = x
type ((f :: b -> c) :.: (g :: a -> b)) (x :: a) = f (g x)
type Flip (f :: a -> b -> c) (x :: b) (y :: a) = f y x
type (f :: a -> b) :$: (x :: a) = f x
type (x :: a) :&: (f :: a -> b) = f x
type On (f :: b -> b -> c) (g :: a -> b) (x :: a) (y :: a) = f (g x) (g y)
| nickspinale/data-type-util | Data/Type/Function.hs | mit | 499 | 2 | 8 | 173 | 278 | 176 | 102 | 17 | 0 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.SVGPathSegList (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.SVGPathSegList
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.SVGPathSegList
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/SVGPathSegList.hs | mit | 355 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-|
Module : PostgREST.QueryBuilder
Description : PostgREST SQL generating functions.
This module provides functions to consume data types that
represent database objects (e.g. Relation, Schema, SqlQuery)
and produces SQL Statements.
Any function that outputs a SQL fragment should be in this module.
-}
module PostgREST.QueryBuilder (
addRelations
, addJoinConditions
, callProc
, createReadStatement
, createWriteStatement
, operators
, pgFmtIdent
, pgFmtLit
, requestToQuery
, requestToCountQuery
, sourceCTEName
, unquoted
, ResultsWithCount
) where
import qualified Hasql.Query as H
import qualified Hasql.Encoders as HE
import qualified Hasql.Decoders as HD
import qualified Data.Aeson as JSON
import PostgREST.RangeQuery (NonnegRange, rangeLimit, rangeOffset, allRange)
import Data.Functor.Contravariant (contramap)
import qualified Data.HashMap.Strict as HM
import Data.Text (intercalate, unwords, replace, isInfixOf, toLower, split)
import qualified Data.Text as T (map, takeWhile, null)
import qualified Data.Text.Encoding as T
import Data.Tree (Tree(..))
import qualified Data.Vector as V
import PostgREST.Types
import qualified Data.Map as M
import Text.InterpolatedString.Perl6 (qc)
import Text.Regex.TDFA ((=~))
import qualified Data.ByteString.Char8 as BS
import Data.Scientific ( FPFormat (..)
, formatScientific
, isInteger
)
import Protolude hiding (from, intercalate, ord, cast)
import Unsafe (unsafeHead)
import PostgREST.ApiRequest (PreferRepresentation (..))
{-| The generic query result format used by API responses. The location header
is represented as a list of strings containing variable bindings like
@"k1=eq.42"@, or the empty list if there is no location header.
-}
type ResultsWithCount = (Maybe Int64, Int64, [BS.ByteString], BS.ByteString)
standardRow :: HD.Row ResultsWithCount
standardRow = (,,,) <$> HD.nullableValue HD.int8 <*> HD.value HD.int8
<*> HD.value header <*> HD.value HD.bytea
where
header = HD.array $ HD.arrayDimension replicateM $ HD.arrayValue HD.bytea
noLocationF :: Text
noLocationF = "array[]::text[]"
{-| Read and Write api requests use a similar response format which includes
various record counts and possible location header. This is the decoder
for that common type of query.
-}
decodeStandard :: HD.Result ResultsWithCount
decodeStandard =
HD.singleRow standardRow
decodeStandardMay :: HD.Result (Maybe ResultsWithCount)
decodeStandardMay =
HD.maybeRow standardRow
{-| JSON and CSV payloads from the client are given to us as
UniformObjects (objects who all have the same keys),
and we turn this into an old fasioned JSON array
-}
encodeUniformObjs :: HE.Params UniformObjects
encodeUniformObjs =
contramap (JSON.Array . V.map JSON.Object . unUniformObjects) (HE.value HE.json)
createReadStatement :: SqlQuery -> SqlQuery -> Bool -> Bool -> Bool ->
H.Query () ResultsWithCount
createReadStatement selectQuery countQuery isSingle countTotal asCsv =
unicodeStatement sql HE.unit decodeStandard True
where
sql = [qc|
WITH {sourceCTEName} AS ({selectQuery}) SELECT {cols}
FROM ( SELECT * FROM {sourceCTEName}) _postgrest_t |]
countResultF = if countTotal then "("<>countQuery<>")" else "null"
cols = intercalate ", " [
countResultF <> " AS total_result_set",
"pg_catalog.count(_postgrest_t) AS page_total",
noLocationF <> " AS header",
bodyF <> " AS body"
]
bodyF
| asCsv = asCsvF
| isSingle = asJsonSingleF
| otherwise = asJsonF
createWriteStatement :: QualifiedIdentifier -> SqlQuery -> SqlQuery -> Bool ->
PreferRepresentation -> [Text] -> Bool -> Payload ->
H.Query UniformObjects (Maybe ResultsWithCount)
createWriteStatement _ _ _ _ _ _ _ (PayloadParseError _) = undefined
createWriteStatement _ _ mutateQuery _ None
_ _ (PayloadJSON (UniformObjects _)) =
unicodeStatement sql encodeUniformObjs decodeStandardMay True
where
sql = [qc|
WITH {sourceCTEName} AS ({mutateQuery})
SELECT '', 0, {noLocationF}, '' |]
createWriteStatement qi _ mutateQuery isSingle HeadersOnly
pKeys _ (PayloadJSON (UniformObjects _)) =
unicodeStatement sql encodeUniformObjs decodeStandardMay True
where
sql = [qc|
WITH {sourceCTEName} AS ({mutateQuery} RETURNING {fromQi qi}.*)
SELECT {cols}
FROM (SELECT 1 FROM {sourceCTEName}) _postgrest_t |]
cols = intercalate ", " [
"'' AS total_result_set",
"pg_catalog.count(_postgrest_t) AS page_total",
if isSingle then locationF pKeys else noLocationF,
"''"
]
createWriteStatement qi selectQuery mutateQuery isSingle Full
pKeys asCsv (PayloadJSON (UniformObjects _)) =
unicodeStatement sql encodeUniformObjs decodeStandardMay True
where
sql = [qc|
WITH {sourceCTEName} AS ({mutateQuery} RETURNING {fromQi qi}.*)
SELECT {cols}
FROM ({selectQuery}) _postgrest_t |]
cols = intercalate ", " [
"'' AS total_result_set", -- when updateing it does not make sense
"pg_catalog.count(_postgrest_t) AS page_total",
if isSingle then locationF pKeys else noLocationF <> " AS header",
bodyF <> " AS body"
]
bodyF
| asCsv = asCsvF
| isSingle = asJsonSingleF
| otherwise = asJsonF
addRelations :: Schema -> [Relation] -> Maybe ReadRequest -> ReadRequest -> Either Text ReadRequest
addRelations schema allRelations parentNode (Node readNode@(query, (name, _, alias)) forest) =
case parentNode of
(Just (Node (Select{from=[parentNodeTable]}, (_, _, _)) _)) ->
Node <$> readNode' <*> forest'
where
forest' = updateForest $ hush node'
node' = Node <$> readNode' <*> pure forest
readNode' = addRel readNode <$> rel
rel :: Either Text Relation
rel = note ("no relation between " <> parentNodeTable <> " and " <> name)
$ findRelation schema name parentNodeTable
where
findRelation s nodeTableName parentNodeTableName =
find (\r ->
s == tableSchema (relTable r) && -- match schema for relation table
s == tableSchema (relFTable r) && -- match schema for relation foriegn table
(
-- (request) => projects { ..., clients{...} }
-- will match
-- (relation type) => parent
-- (entity) => clients {id}
-- (foriegn entity) => projects {client_id}
(
nodeTableName == tableName (relTable r) && -- match relation table name
parentNodeTableName == tableName (relFTable r) -- match relation foreign table name
) ||
-- (request) => projects { ..., client_id{...} }
-- will match
-- (relation type) => parent
-- (entity) => clients {id}
-- (foriegn entity) => projects {client_id}
(
parentNodeTableName == tableName (relFTable r) &&
length (relFColumns r) == 1 &&
nodeTableName `colMatches` (colName . unsafeHead . relFColumns) r
)
-- (request) => project_id { ..., client_id{...} }
-- will match
-- (relation type) => parent
-- (entity) => clients {id}
-- (foriegn entity) => projects {client_id}
-- this case works becasue before reaching this place
-- addRelation will turn project_id to project so the above condition will match
)
) allRelations
where n `colMatches` rc = (toS ("^" <> rc <> "_?(?:|[iI][dD]|[fF][kK])$") :: BS.ByteString) =~ (toS n :: BS.ByteString)
addRel :: (ReadQuery, (NodeName, Maybe Relation, Maybe Alias)) -> Relation -> (ReadQuery, (NodeName, Maybe Relation, Maybe Alias))
addRel (query', (n, _, a)) r = (query' {from=fromRelation}, (n, Just r, a))
where fromRelation = map (\t -> if t == n then tableName (relTable r) else t) (from query')
_ -> n' <$> updateForest (Just (n' forest))
where
n' = Node (query, (name, Just r, alias))
t = Table schema name True -- !!! TODO find another way to get the table from the query
r = Relation t [] t [] Root Nothing Nothing Nothing
where
updateForest :: Maybe ReadRequest -> Either Text [ReadRequest]
updateForest n = mapM (addRelations schema allRelations n) forest
addJoinConditions :: Schema -> ReadRequest -> Either Text ReadRequest
addJoinConditions schema (Node nn@(query, (n, r, a)) forest) =
case r of
Just Relation{relType=Root} -> Node nn <$> updatedForest -- this is the root node
Just rel@Relation{relType=Child} -> Node (addCond query (getJoinConditions rel),(n,r,a)) <$> updatedForest
Just Relation{relType=Parent} -> Node nn <$> updatedForest
Just rel@Relation{relType=Many, relLTable=(Just linkTable)} ->
Node (qq, (n, r, a)) <$> updatedForest
where
query' = addCond query (getJoinConditions rel)
qq = query'{from=tableName linkTable : from query'}
_ -> Left "unknown relation"
where
updatedForest = mapM (addJoinConditions schema) forest
addCond query' con = query'{flt_=con ++ flt_ query'}
type ProcResults = (Maybe Int64, Int64, JSON.Value)
callProc :: QualifiedIdentifier -> JSON.Object -> SqlQuery -> SqlQuery -> NonnegRange -> Bool -> Bool -> H.Query () (Maybe ProcResults)
callProc qi params selectQuery countQuery _ countTotal isSingle =
unicodeStatement sql HE.unit decodeProc True
where
sql = [qc|
WITH {sourceCTEName} AS ({_callSql})
SELECT
{countResultF} AS total_result_set,
pg_catalog.count(_postgrest_t) AS page_total,
case
when pg_catalog.count(1) > 1 then
{bodyF}
else
coalesce(((array_agg(row_to_json(_postgrest_t)))[1]->{_procName})::character varying, {bodyF})
end as body
FROM ({selectQuery}) _postgrest_t;
|]
-- FROM (select * from {sourceCTEName} {limitF range}) t;
countResultF = if countTotal then "("<>countQuery<>")" else "null::bigint" :: Text
_args = intercalate "," $ map _assignment (HM.toList params)
_procName = pgFmtLit $ qiName qi
_assignment (n,v) = pgFmtIdent n <> ":=" <> insertableValue v
_callSql = [qc|select * from {fromQi qi}({_args}) |] :: Text
_countExpr = if countTotal
then [qc|(select pg_catalog.count(1) from {sourceCTEName})|]
else "null::bigint" :: Text
decodeProc = HD.maybeRow procRow
procRow = (,,) <$> HD.nullableValue HD.int8 <*> HD.value HD.int8
<*> HD.value HD.json
bodyF
| isSingle = asJsonSingleF
| otherwise = asJsonF
operators :: [(Text, SqlFragment)]
operators = [
("eq", "="),
("gte", ">="), -- has to be before gt (parsers)
("gt", ">"),
("lte", "<="), -- has to be before lt (parsers)
("lt", "<"),
("neq", "<>"),
("like", "like"),
("ilike", "ilike"),
("in", "in"),
("notin", "not in"),
("isnot", "is not"), -- has to be before is (parsers)
("is", "is"),
("@@", "@@"),
("@>", "@>"),
("<@", "<@")
]
pgFmtIdent :: SqlFragment -> SqlFragment
pgFmtIdent x = "\"" <> replace "\"" "\"\"" (trimNullChars $ toS x) <> "\""
pgFmtLit :: SqlFragment -> SqlFragment
pgFmtLit x =
let trimmed = trimNullChars x
escaped = "'" <> replace "'" "''" trimmed <> "'"
slashed = replace "\\" "\\\\" escaped in
if "\\" `isInfixOf` escaped
then "E" <> slashed
else slashed
requestToCountQuery :: Schema -> DbRequest -> SqlQuery
requestToCountQuery _ (DbMutate _) = undefined
requestToCountQuery schema (DbRead (Node (Select _ _ conditions _ _, (mainTbl, _, _)) _)) =
unwords [
"SELECT pg_catalog.count(1)",
"FROM ", fromQi qi,
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi) localConditions )) `emptyOnNull` localConditions
]
where
qi = if mainTbl == sourceCTEName
then QualifiedIdentifier "" mainTbl
else QualifiedIdentifier schema mainTbl
fn Filter{value=VText _} = True
fn Filter{value=VForeignKey _ _} = False
localConditions = filter fn conditions
requestToQuery :: Schema -> Bool -> DbRequest -> SqlQuery
requestToQuery _ _ (DbMutate (Insert _ (PayloadParseError _))) = undefined
requestToQuery _ _ (DbMutate (Update _ (PayloadParseError _) _)) = undefined
requestToQuery schema isParent (DbRead (Node (Select colSelects tbls conditions ord range, (nodeName, maybeRelation, _)) forest)) =
query
where
-- TODO! the following helper functions are just to remove the "schema" part when the table is "source" which is the name
-- of our WITH query part
mainTbl = fromMaybe nodeName (tableName . relTable <$> maybeRelation)
tblSchema tbl = if tbl == sourceCTEName then "" else schema
qi = QualifiedIdentifier (tblSchema mainTbl) mainTbl
toQi t = QualifiedIdentifier (tblSchema t) t
query = unwords [
"SELECT ", intercalate ", " (map (pgFmtSelectItem qi) colSelects ++ selects),
"FROM ", intercalate ", " (map (fromQi . toQi) tbls),
unwords joins,
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions,
orderF (fromMaybe [] ord),
if isParent then "" else limitF range
]
orderF ts =
if null ts
then ""
else "ORDER BY " <> clause
where
clause = intercalate "," (map queryTerm ts)
queryTerm :: OrderTerm -> Text
queryTerm t = " "
<> toS (pgFmtField qi $ otTerm t) <> " "
<> maybe "" show (otDirection t) <> " "
<> maybe "" show (otNullOrder t) <> " "
(joins, selects) = foldr getQueryParts ([],[]) forest
getQueryParts :: Tree ReadNode -> ([SqlFragment], [SqlFragment]) -> ([SqlFragment], [SqlFragment])
getQueryParts (Node n@(_, (name, Just Relation{relType=Child,relTable=Table{tableName=table}}, alias)) forst) (j,s) = (j,sel:s)
where
sel = "COALESCE(("
<> "SELECT array_to_json(array_agg(row_to_json("<>pgFmtIdent table<>"))) "
<> "FROM (" <> subquery <> ") " <> pgFmtIdent table
<> "), '[]') AS " <> pgFmtIdent (fromMaybe name alias)
where subquery = requestToQuery schema False (DbRead (Node n forst))
getQueryParts (Node n@(_, (name, Just r@Relation{relType=Parent,relTable=Table{tableName=table}}, alias)) forst) (j,s) = (joi:j,sel:s)
where
node_name = fromMaybe name alias
local_table_name = table <> "_" <> node_name
replaceTableName localTableName (Filter a b (VForeignKey (QualifiedIdentifier "" _) c)) = Filter a b (VForeignKey (QualifiedIdentifier "" localTableName) c)
replaceTableName _ x = x
sel = "row_to_json(" <> pgFmtIdent local_table_name <> ".*) AS " <> pgFmtIdent node_name
joi = " LEFT OUTER JOIN ( " <> subquery <> " ) AS " <> pgFmtIdent local_table_name <>
" ON " <> intercalate " AND " ( map (pgFmtCondition qi . replaceTableName local_table_name) (getJoinConditions r) )
where subquery = requestToQuery schema True (DbRead (Node n forst))
getQueryParts (Node n@(_, (name, Just Relation{relType=Many,relTable=Table{tableName=table}}, alias)) forst) (j,s) = (j,sel:s)
where
sel = "COALESCE (("
<> "SELECT array_to_json(array_agg(row_to_json("<>pgFmtIdent table<>"))) "
<> "FROM (" <> subquery <> ") " <> pgFmtIdent table
<> "), '[]') AS " <> pgFmtIdent (fromMaybe name alias)
where subquery = requestToQuery schema False (DbRead (Node n forst))
--the following is just to remove the warning
--getQueryParts is not total but requestToQuery is called only after addJoinConditions which ensures the only
--posible relations are Child Parent Many
getQueryParts _ _ = undefined --error "undefined getQueryParts"
requestToQuery schema _ (DbMutate (Insert mainTbl (PayloadJSON (UniformObjects rows)))) =
let qi = QualifiedIdentifier schema mainTbl
cols = map pgFmtIdent $ fromMaybe [] (HM.keys <$> (rows V.!? 0))
colsString = intercalate ", " cols
insInto = unwords [ "INSERT INTO" , fromQi qi,
if T.null colsString then "" else "(" <> colsString <> ")"
]
vals = unwords $ if T.null colsString
then ["DEFAULT VALUES"]
else ["SELECT", colsString, "FROM json_populate_recordset(null::" , fromQi qi, ", $1)"] in
insInto <> vals
requestToQuery schema _ (DbMutate (Update mainTbl (PayloadJSON (UniformObjects rows)) conditions)) =
case rows V.!? 0 of
Just obj ->
let assignments = map
(\(k,v) -> pgFmtIdent k <> "=" <> insertableValue v) $ HM.toList obj in
unwords [
"UPDATE ", fromQi qi,
" SET " <> intercalate "," assignments <> " ",
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions
]
Nothing -> undefined
where
qi = QualifiedIdentifier schema mainTbl
requestToQuery schema _ (DbMutate (Delete mainTbl conditions)) =
query
where
qi = QualifiedIdentifier schema mainTbl
query = unwords [
"DELETE FROM ", fromQi qi,
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions
]
sourceCTEName :: SqlFragment
sourceCTEName = "pg_source"
unquoted :: JSON.Value -> Text
unquoted (JSON.String t) = t
unquoted (JSON.Number n) =
toS $ formatScientific Fixed (if isInteger n then Just 0 else Nothing) n
unquoted (JSON.Bool b) = show b
unquoted v = toS $ JSON.encode v
-- private functions
asCsvF :: SqlFragment
asCsvF = asCsvHeaderF <> " || '\n' || " <> asCsvBodyF
where
asCsvHeaderF =
"(SELECT coalesce(string_agg(a.k, ','), '')" <>
" FROM (" <>
" SELECT json_object_keys(r)::TEXT as k" <>
" FROM ( " <>
" SELECT row_to_json(hh) as r from " <> sourceCTEName <> " as hh limit 1" <>
" ) s" <>
" ) a" <>
")"
asCsvBodyF = "coalesce(string_agg(substring(_postgrest_t::text, 2, length(_postgrest_t::text) - 2), '\n'), '')"
asJsonF :: SqlFragment
asJsonF = "coalesce(array_to_json(array_agg(row_to_json(_postgrest_t))), '[]')::character varying"
asJsonSingleF :: SqlFragment --TODO! unsafe when the query actually returns multiple rows, used only on inserting and returning single element
asJsonSingleF = "coalesce(string_agg(row_to_json(_postgrest_t)::text, ','), '')::character varying "
locationF :: [Text] -> SqlFragment
locationF pKeys =
"(" <>
" WITH s AS (SELECT row_to_json(ss) as r from " <> sourceCTEName <> " as ss limit 1)" <>
" SELECT array_agg(json_data.key || '=' || coalesce('eq.' || json_data.value, 'is.null'))" <>
" FROM s, json_each_text(s.r) AS json_data" <>
(
if null pKeys
then ""
else " WHERE json_data.key IN ('" <> intercalate "','" pKeys <> "')"
) <> ")"
limitF :: NonnegRange -> SqlFragment
limitF r = if r == allRange
then ""
else "LIMIT " <> limit <> " OFFSET " <> offset
where
limit = maybe "ALL" show $ rangeLimit r
offset = show $ rangeOffset r
fromQi :: QualifiedIdentifier -> SqlFragment
fromQi t = (if s == "" then "" else pgFmtIdent s <> ".") <> pgFmtIdent n
where
n = qiName t
s = qiSchema t
getJoinConditions :: Relation -> [Filter]
getJoinConditions (Relation t cols ft fcs typ lt lc1 lc2) =
case typ of
Child -> zipWith (toFilter tN ftN) cols fcs
Parent -> zipWith (toFilter tN ftN) cols fcs
Many -> zipWith (toFilter tN ltN) cols (fromMaybe [] lc1) ++ zipWith (toFilter ftN ltN) fcs (fromMaybe [] lc2)
Root -> undefined --error "undefined getJoinConditions"
where
s = if typ == Parent then "" else tableSchema t
tN = tableName t
ftN = tableName ft
ltN = fromMaybe "" (tableName <$> lt)
toFilter :: Text -> Text -> Column -> Column -> Filter
toFilter tb ftb c fc = Filter (colName c, Nothing) "=" (VForeignKey (QualifiedIdentifier s tb) (ForeignKey fc{colTable=(colTable fc){tableName=ftb}}))
unicodeStatement :: Text -> HE.Params a -> HD.Result b -> Bool -> H.Query a b
unicodeStatement = H.statement . T.encodeUtf8
emptyOnNull :: Text -> [a] -> Text
emptyOnNull val x = if null x then "" else val
insertableValue :: JSON.Value -> SqlFragment
insertableValue JSON.Null = "null"
insertableValue v = (<> "::unknown") . pgFmtLit $ unquoted v
whiteList :: Text -> SqlFragment
whiteList val = fromMaybe
(toS (pgFmtLit val) <> "::unknown ")
(find ((==) . toLower $ val) ["null","true","false"])
pgFmtColumn :: QualifiedIdentifier -> Text -> SqlFragment
pgFmtColumn table "*" = fromQi table <> ".*"
pgFmtColumn table c = fromQi table <> "." <> pgFmtIdent c
pgFmtField :: QualifiedIdentifier -> Field -> SqlFragment
pgFmtField table (c, jp) = pgFmtColumn table c <> pgFmtJsonPath jp
pgFmtSelectItem :: QualifiedIdentifier -> SelectItem -> SqlFragment
pgFmtSelectItem table (f@(_, jp), Nothing, alias) = pgFmtField table f <> pgFmtAs jp alias
pgFmtSelectItem table (f@(_, jp), Just cast, alias) = "CAST (" <> pgFmtField table f <> " AS " <> cast <> " )" <> pgFmtAs jp alias
pgFmtCondition :: QualifiedIdentifier -> Filter -> SqlFragment
pgFmtCondition table (Filter (col,jp) ops val) =
notOp <> " " <> sqlCol <> " " <> pgFmtOperator opCode <> " " <>
if opCode `elem` ["is","isnot"] then whiteList (getInner val) else sqlValue
where
headPredicate:rest = split (=='.') ops
hasNot caseTrue caseFalse = if headPredicate == "not" then caseTrue else caseFalse
opCode = hasNot (headDef "eq" rest) headPredicate
notOp = hasNot headPredicate ""
sqlCol = case val of
VText _ -> pgFmtColumn table col <> pgFmtJsonPath jp
VForeignKey qi _ -> pgFmtColumn qi col
sqlValue = valToStr val
getInner v = case v of
VText s -> s
_ -> ""
valToStr v = case v of
VText s -> pgFmtValue opCode s
VForeignKey (QualifiedIdentifier s _) (ForeignKey Column{colTable=Table{tableName=ft}, colName=fc}) -> pgFmtColumn qi fc
where qi = QualifiedIdentifier (if ft == sourceCTEName then "" else s) ft
_ -> ""
pgFmtValue :: Text -> Text -> SqlFragment
pgFmtValue opCode val =
case opCode of
"like" -> unknownLiteral $ T.map star val
"ilike" -> unknownLiteral $ T.map star val
"in" -> "(" <> intercalate ", " (map unknownLiteral $ split (==',') val) <> ") "
"notin" -> "(" <> intercalate ", " (map unknownLiteral $ split (==',') val) <> ") "
"@@" -> "to_tsquery(" <> unknownLiteral val <> ") "
_ -> unknownLiteral val
where
star c = if c == '*' then '%' else c
unknownLiteral = (<> "::unknown ") . pgFmtLit
pgFmtOperator :: Text -> SqlFragment
pgFmtOperator opCode = fromMaybe "=" $ M.lookup opCode operatorsMap
where
operatorsMap = M.fromList operators
pgFmtJsonPath :: Maybe JsonPath -> SqlFragment
pgFmtJsonPath (Just [x]) = "->>" <> pgFmtLit x
pgFmtJsonPath (Just (x:xs)) = "->" <> pgFmtLit x <> pgFmtJsonPath ( Just xs )
pgFmtJsonPath _ = ""
pgFmtAs :: Maybe JsonPath -> Maybe Alias -> SqlFragment
pgFmtAs Nothing Nothing = ""
pgFmtAs (Just xx) Nothing = case lastMay xx of
Just alias -> " AS " <> pgFmtIdent alias
Nothing -> ""
pgFmtAs _ (Just alias) = " AS " <> pgFmtIdent alias
trimNullChars :: Text -> Text
trimNullChars = T.takeWhile (/= '\x0')
| NotBrianZach/postgrest | src/PostgREST/QueryBuilder.hs | mit | 24,324 | 0 | 26 | 6,275 | 6,469 | 3,457 | 3,012 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.StorageErrorCallback
(newStorageErrorCallback, newStorageErrorCallbackSync,
newStorageErrorCallbackAsync, StorageErrorCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageErrorCallback Mozilla StorageErrorCallback documentation>
newStorageErrorCallback ::
(MonadIO m) =>
(Maybe DOMException -> IO ()) -> m StorageErrorCallback
newStorageErrorCallback callback
= liftIO
(StorageErrorCallback <$>
syncCallback1 ThrowWouldBlock
(\ error ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageErrorCallback Mozilla StorageErrorCallback documentation>
newStorageErrorCallbackSync ::
(MonadIO m) =>
(Maybe DOMException -> IO ()) -> m StorageErrorCallback
newStorageErrorCallbackSync callback
= liftIO
(StorageErrorCallback <$>
syncCallback1 ContinueAsync
(\ error ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageErrorCallback Mozilla StorageErrorCallback documentation>
newStorageErrorCallbackAsync ::
(MonadIO m) =>
(Maybe DOMException -> IO ()) -> m StorageErrorCallback
newStorageErrorCallbackAsync callback
= liftIO
(StorageErrorCallback <$>
asyncCallback1
(\ error ->
fromJSValUnchecked error >>= \ error' -> callback error')) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/StorageErrorCallback.hs | mit | 2,472 | 0 | 13 | 515 | 532 | 316 | 216 | 45 | 1 |
{-# htermination (minimumMyBool :: (List MyBool) -> MyBool) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
foldl :: (a -> b -> a) -> a -> (List b) -> a;
foldl f z Nil = z;
foldl f z (Cons x xs) = foldl f (f z x) xs;
foldl1 :: (a -> a -> a) -> (List a) -> a;
foldl1 f (Cons x xs) = foldl f x xs;
ltEsMyBool :: MyBool -> MyBool -> MyBool
ltEsMyBool MyFalse MyFalse = MyTrue;
ltEsMyBool MyFalse MyTrue = MyTrue;
ltEsMyBool MyTrue MyFalse = MyFalse;
ltEsMyBool MyTrue MyTrue = MyTrue;
min0 x y MyTrue = y;
otherwise :: MyBool;
otherwise = MyTrue;
min1 x y MyTrue = x;
min1 x y MyFalse = min0 x y otherwise;
min2 x y = min1 x y (ltEsMyBool x y);
minMyBool :: MyBool -> MyBool -> MyBool
minMyBool x y = min2 x y;
minimumMyBool :: (List MyBool) -> MyBool
minimumMyBool = foldl1 minMyBool;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/minimum_2.hs | mit | 874 | 0 | 9 | 214 | 372 | 200 | 172 | 23 | 1 |
module FunMap (
FunMap(),
empty,
singleton,
(!),
at,
mapKeys,
mapKeys',
mapKeysR,
mapKeysR',
insert,
delete,
toList
) where
import Control.Monad ((>=>))
-- | A simple map between key and values.
--
-- It's implemented as a function.
data FunMap k v = FunMap (k -> Maybe v)
instance (Show k, Show v, Enum k) => Show (FunMap k v) where
show = ("fromList " ++) . show . toList
instance Functor (FunMap k) where
fmap g (FunMap f) = FunMap (fmap g . f)
-- | Creates an empty FunMap
empty :: FunMap k v
empty = FunMap f
where f _ = Nothing
-- | Creates a FunMap with a single element inside it.
singleton :: (Eq k) => k -> v -> FunMap k v
singleton key value = FunMap f
where f x | x == key = Just value
| otherwise = Nothing
-- | Inserts an element into the FunMap.
--
-- Overwrites earlier elements if they share the same keys.
insert :: (Eq k) => k -> v -> FunMap k v -> FunMap k v
insert key value (FunMap f) = FunMap g
where g x | x == key = Just value
| otherwise = f x
-- | Deletes an element out of the FunMap.
delete :: (Eq k) => k -> FunMap k v -> FunMap k v
delete key (FunMap f) = FunMap g
where g x | x == key = Nothing
| otherwise = f x
-- | Returns an element from the FunMap if it's in there.
--
-- Throws an error if it isn't.
at :: FunMap k v -> k -> v
FunMap f `at` x = maybe err id $ f x
where err = error "Error: element with key" ++ x ++ "not found in the FunMap."
-- | Safe way to return an element from the FunMap.
(!) :: FunMap k v -> k -> Maybe v
FunMap f ! x = f x
-- | Maps a function over the keys.
--
-- The supplied function must be bijective.
mapKeys :: (k2 -> k1) -> FunMap k1 v -> FunMap k2 v
mapKeys g (FunMap f) = FunMap (f . g)
-- | Maps a function over the keys.
--
-- The supplied function must be bijective with regards to k1 and k2, so it doesn't matter if a lot of values get mapped to Nothing. Also the domain of k1 should be as small as possible.
mapKeys' :: (k2 -> Maybe k1) -> FunMap k1 v -> FunMap k2 v
mapKeys' g (FunMap f) = FunMap (g >=> f)
-- | Maps a function over the keys
--
-- The supplied function must be bijective and also the domain of k1 should be as small as possible.
mapKeysR :: (Enum k1, Eq k2) => (k1 -> k2) -> FunMap k1 v -> FunMap k2 v
mapKeysR g (FunMap f) = FunMap (f . invertFunction g)
-- | Maps a function over the keys
--
-- The supplied function must be bijective with regards to k1 and k2, so it doesn't matter if a lot of values get mapped to Nothing. Also the domain of k1 should be as small as possible.
mapKeysR' :: (Enum k1, Eq k2) => (k1 -> Maybe k2) -> FunMap k1 v -> FunMap k2 v
mapKeysR' g (FunMap f) = FunMap (invertFunction' g >=> f)
-- | Converts a FunMap to a list
toList :: (Enum k) => FunMap k v -> [(k, v)]
toList (FunMap f) = [ (x, value) | x <- enumAll, Just value <- [f x] ]
-- ##########################
-- #### Help functions ####
-- ##########################
-- | Inverts a bijective function in the mathematical sense.
invertFunction :: (Enum a, Eq b) => (a -> b) -> (b -> a)
invertFunction f x = case lookup x $ fmap (\y -> (f y, y)) enumAll of
Just result -> result
Nothing -> error "Error: Unable to invert function"
-- | Inverts a bijective function in the mathetamical sense.
invertFunction' :: (Enum a, Eq b) => (a -> Maybe b) -> (b -> Maybe a)
invertFunction' f x = lookup x [ (r, e) | e <- enumAll, Just r <- [f e] ]
enumAll :: (Enum e) => [e]
enumAll = enumFrom (toEnum 0)
| Purlox/FunMap | Source/Data/FunMap.hs | mit | 3,615 | 0 | 11 | 963 | 1,156 | 604 | 552 | 59 | 2 |
module Unison.Codebase.TermEdit where
import Unison.Hashable (Hashable)
import qualified Unison.Hashable as H
import Unison.Reference (Reference)
import qualified Unison.Typechecker as Typechecker
import Unison.Type (Type)
import Unison.Var (Var)
data TermEdit = Replace Reference Typing | Deprecate
deriving (Eq, Ord, Show)
references :: TermEdit -> [Reference]
references (Replace r _) = [r]
references Deprecate = []
-- Replacements with the Same type can be automatically propagated.
-- Replacements with a Subtype can be automatically propagated but may result in dependents getting more general types, so requires re-inference.
-- Replacements of a Different type need to be manually propagated by the programmer.
data Typing = Same | Subtype | Different
deriving (Eq, Ord, Show)
instance Hashable Typing where
tokens Same = [H.Tag 0]
tokens Subtype = [H.Tag 1]
tokens Different = [H.Tag 2]
instance Hashable TermEdit where
tokens (Replace r t) = [H.Tag 0] ++ H.tokens r ++ H.tokens t
tokens Deprecate = [H.Tag 1]
toReference :: TermEdit -> Maybe Reference
toReference (Replace r _) = Just r
toReference Deprecate = Nothing
isTypePreserving :: TermEdit -> Bool
isTypePreserving e = case e of
Replace _ Same -> True
Replace _ Subtype -> True
_ -> False
isSame :: TermEdit -> Bool
isSame e = case e of
Replace _ Same -> True
_ -> False
typing :: Var v => Type v loc -> Type v loc -> Typing
typing newType oldType | Typechecker.isEqual newType oldType = Same
| Typechecker.isSubtype newType oldType = Subtype
| otherwise = Different
| unisonweb/platform | parser-typechecker/src/Unison/Codebase/TermEdit.hs | mit | 1,634 | 0 | 10 | 341 | 490 | 255 | 235 | 37 | 3 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Betfair.APING.Requests.Logout
( logout
, Logout(..)
) where
import Control.Exception.Safe
import Data.Aeson
import Data.Aeson.TH
import Protolude
import Text.PrettyPrint.GenericPretty
--
import Betfair.APING.API.Context
import Betfair.APING.API.GetResponse
import Betfair.APING.API.Headers
import Betfair.APING.Types.Token (Token)
import Network.HTTP.Conduit
data Logout = Logout
{ token :: Token
, product :: Text
, status :: Status
-- not converting this to type Error as I get a "" on success
-- ,error :: Error
, error :: Text
} deriving (Eq, Read, Show, Generic, Pretty)
data Status
= SUCCESS
| FAIL
deriving (Eq, Read, Show, Generic, Pretty)
data Error
= INPUT_VALIDATION_ERROR
| INTERNAL_ERROR
| NO_SESSION
deriving (Eq, Read, Show, Generic, Pretty)
instance Exception Logout
$(deriveJSON defaultOptions {omitNothingFields = True} ''Logout)
$(deriveJSON defaultOptions {omitNothingFields = True} ''Status)
$(deriveJSON defaultOptions {omitNothingFields = True} ''Error)
logoutRequest :: Context -> IO Request
logoutRequest c =
(fmap
(\req ->
req
{ requestHeaders = headers (cAppKey c) (Just (cToken c))
, method = "POST"
}) .
parseUrlThrow)
"https://identitysso.betfair.com/api/logout"
logout :: Context -> IO Logout
logout c = checkStatus =<< getDecodedResponse c =<< logoutRequest c
checkStatus :: Logout -> IO Logout
checkStatus k
| status k == FAIL = throwM k
| otherwise = return k
| joe9/betfair-api | src/Betfair/APING/Requests/Logout.hs | mit | 1,688 | 0 | 17 | 330 | 451 | 251 | 200 | 53 | 1 |
module Invertible where
| vladfi1/hs-misc | Invertible.hs | mit | 26 | 0 | 2 | 5 | 4 | 3 | 1 | 1 | 0 |
-- safeSqrt x = sqrtBool (x >= 0) x
-- sqrtBool True x = Just (sqrt x)
-- sqrtBool False _ = Nothing
safeSqrt x
| x >= 0 = Just (sqrt 0)
| otherwise = Nothing
| threetreeslight/learning-haskell | practice/guards.hs | mit | 165 | 0 | 8 | 43 | 40 | 19 | 21 | 3 | 1 |
-- ====================
-- Complete the following functions and submit your file to Canvas.
-- ====================
-- Do not change the names of the functions.
-- Do not change the number of arguments in the functions.
-- If your file cannot be loaded by the Haskell compiler, your submission may be cancelled.
-- Then, submit only code that works.
-- ====================
-- Grading instructions:
-- There is a series of test cases for each function. In order to state that your function
-- "works as described", your output must be similar to the expected one in each case.
-- === invert ===
invert :: [t] -> [t]
invert [] = []
invert (x:y) = invert y ++ [x]
-- === or ===
listor :: [Int] -> [Int] -> [Int]
listor [] [] = []
listor (1:y) (1:w) = [1] ++ listor y w
listor (1:y) (0:w) = [1] ++ listor y w
listor (0:y) (0:w) = [0] ++ listor y w
listor (0:y) (1:w) = [1] ++ listor y w
listor (_:y) (_:w) = error "not 0 or 1"
-- === multiples ===
multiples :: [Int] -> Int -> [Int]
multiples (x:y) z =
if
mod x z == 0
then
[x] ++ multiples y z
else
multiples y z
multiples [] _ = []
-- === differences ===
differences :: [Int] -> [Int]
differences (x:y) = differences2 ([x]++y) (y++[x])
differences [] = []
differences2 :: [Int] -> [Int] -> [Int]
differences2 (x:y) (z:w) = [abs (z-x)] ++ differences2 y w
differences2 [] [] = []
-- === toBinaryString ===
toBinaryString :: Int -> [Char]
toBinaryString 0 = "0"
toBinaryString x = invert (aux x)
aux :: Int -> [Char]
aux 0 = ""
aux x = if rem x 2 == 0
then '0' : aux (div x 2)
else ('1' : aux (div x 2))
-- === modulo ===
modulo :: Int -> Int -> Int
modulo x y =
if
x >= y
then
modulo (x-y) y
else
x
-- === evaluate ===
evaluate :: [Double] -> Double -> Double
evaluate x y = auxpoly (invert x) y 0
auxpoly :: [Double] -> Double -> Integer -> Double
auxpoly [] x y = 0
auxpoly (a:b) x y = a * (x^y) + (auxpoly b x (y+1))
-- === cleanString ===
cleanString :: [Char] -> [Char]
cleanString [] = []
cleanString (x:[]) = [x]
cleanString (x:y:z) =
if
x == y
then
cleanString( y : z)
else
x : cleanString (y:z)
-- === iSort ===
iSort :: [Int] -> [Int]
iSort [] = []
iSort [x] = [x]
iSort (x:y) = iSortAux x (iSort y)
iSortAux :: Int -> [Int] -> [Int]
iSortAux x [] = [x]
iSortAux x (y:z) =
if x < y
then
x : (y : z)
else
y : (iSortAux x z)
-- === Test cases ===
main = do
print "=== invert ==="
print $ invert ([] :: [Int])-- []
print $ invert [1, 2, 3, 4, 5] -- [5,4,3,2,1]
print $ invert "hello world!" -- "!dlrow olleh"
print "=== listor ==="
print $ listor [1, 1, 0] [0, 1, 0] -- [1,1,0]
print $ listor [1, 0, 1, 0] [0, 0, 1, 1] -- [1,0,1,1]
print $ listor [1, 0, 1, 0, 1] [1, 1, 1, 0, 0] -- [1,1,1,0,1]
print "=== multiples ==="
print $ multiples [2, 4, 5, 6] 2 -- [2,4,6]
print $ multiples [9, 27, 8, 15, 4] 3 -- [9,27,15]
print $ multiples [9, 8, 17, 5] 6 -- []
print "=== differences ==="
print $ differences [1, 2, 4, 8, 20] -- [1,2,4,12,19]
print $ differences [5, 9, 13, 27, 100, 91, 4] -- [4,4,14,73,9,87,1]
print $ differences [99] -- [0]
print $ differences [] -- []
print "=== toBinaryString ==="
print $ toBinaryString 0 -- "0"
print $ toBinaryString 1 -- "1"
print $ toBinaryString 7 -- "111"
print $ toBinaryString 32 -- "100000"
print $ toBinaryString 1024 -- "10000000000"
print "=== modulo ==="
print $ modulo 10 2 -- 0
print $ modulo 15 4 -- 3
print $ modulo 20 9 -- 2
print $ modulo 77 10 -- 7
print "=== evaluate ==="
print $ evaluate ([] :: [Double]) 100 -- 0.0
print $ evaluate [2, 3.1, 10, 0] 2 -- 48.4
print $ evaluate [10, 0] 2 -- 20.0
print $ evaluate [1, 2, 3, 4, 5] 3 -- 179.0
print "=== cleanString ==="
print $ cleanString ([] :: String) -- ""
print $ cleanString "yyzzza" -- "yza"
print $ cleanString "aaaabbbccd" -- "abcd"
print "=== iSort ==="
print $ iSort [] -- []
print $ iSort [1] -- [1]
print $ iSort [1, 6, 3, 10, 2, 14] -- [1,2,3,6,10,14] | Am3ra/CS | CS4/languages/HW09.hs | mit | 4,175 | 0 | 10 | 1,132 | 1,751 | 935 | 816 | 102 | 2 |
module {{moduleName}}.Swallow.Test
(swallowSuite)
where
import Test.Tasty (testGroup, TestTree)
import Test.Tasty.HUnit
import $module.Swallow
swallowSuite :: TestTree
swallowSuite = testGroup "Swallow"
[testCase "swallow test" testSwallow]
testSwallow :: Assertion
testSwallow = "something" @=? swallow "some" "thing"
| mankyKitty/holy-haskell-project-starter | scaffold/test/ModuleName/Swallow/Test.hs | mit | 329 | 3 | 7 | 43 | 83 | 49 | 34 | -1 | -1 |
module Main where
import Data.List (replicate)
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Maybe (fromJust)
main :: IO ()
main = do
putStrLn $ "Part 1: " ++ show (part1 myRound)
putStrLn $ "Part 2: " ++ show (part2 myRound)
putStrLn "all done"
myInput :: Int
myInput = 3014603
myRound :: [Elf]
myRound = [1..myInput]
type Elf = Int
test :: [Elf]
test = [1..5]
part1 :: [Elf] -> [Elf]
part1 as = reduce as []
reduce :: [Elf] -> [Elf] -> [Elf]
reduce [elf] [] = [elf]
reduce [] acc = reduce (reverse acc) []
reduce [elf] acc = reduce (elf : reverse acc) []
reduce (a : _ : as) acc = reduce as (a : acc)
part2 :: [Elf] -> Elf
part2 = fromJust . part2' . Seq.fromList
part2' :: Seq Elf -> Maybe Elf
part2' = part2'' . Seq.viewl
part2'' :: Seq.ViewL Elf -> Maybe Elf
part2'' Seq.EmptyL = Nothing
part2'' (x Seq.:< xs)
| Seq.null xs = Just x
| otherwise =
part2' $ (l Seq.>< Seq.drop 1 r) Seq.|> x
where (l,r) = Seq.splitAt (mid xs) xs
mid xs = (length xs - 1) `div` 2
| CarstenKoenig/AdventOfCode2016 | Day19/Main.hs | mit | 1,042 | 0 | 11 | 240 | 510 | 269 | 241 | 36 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
import Language.PureScript.Binding
import qualified Data.Text.Lazy.IO as T
data A = A Int Double String
data B = B { number :: [Int], first :: String }
data C = C1 { a :: A, name :: String, admin :: Bool }
| C2 Int B
data D a = D a
data E = E Int
derivePureScript ''A
derivePureScript ''B
derivePureScript ''C
derivePureScript ''D
derivePureScript ''E
main :: IO ()
main = T.writeFile "foreign.purs" $ mkModule "Foreign" (Proxy :: Proxy (C :- D :- TNil))
| philopon/haskell-purescript-binding | examples/example.hs | mit | 587 | 0 | 11 | 112 | 200 | 110 | 90 | 19 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Widgets.Setting where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Ref
import Data.Default
import Data.Dependent.Map (DSum (..))
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid ((<>))
import GHCJS.DOM
import GHCJS.DOM.Element
import GHCJS.DOM.HTMLElement
import GHCJS.DOM.HTMLInputElement
import GHCJS.DOM.HTMLLabelElement
import GHCJS.DOM.HTMLSelectElement
import GHCJS.DOM.Node (nodeAppendChild)
import GHCJS.DOM.Types (Element (..))
import GHCJS.Foreign
import GHCJS.Types
import Reflex
import Reflex
import Reflex.Dom
import Reflex.Dom
import Reflex.Host.Class
import Formats
import LocalStorage
import Widgets.Misc (icon)
#ifdef __GHCJS__
#define JS(name, js, type) foreign import javascript unsafe js name :: type
#else
#define JS(name, js, type) name :: type ; name = undefined
#endif
JS(makeCheckbox, "jQuery($1)['checkbox']()", HTMLElement -> IO ())
JS(makeDropdown, "dropdownOnChange($1, $2)", HTMLElement -> JSFun (JSString -> IO ()) -> IO ())
JS(dropdownSetValue,"jQuery($1)['dropdown']('set text', $2)", HTMLElement -> JSString -> IO ())
data Setting t =
Setting {_setting_value :: Dynamic t Bool}
data Selection t =
Selection {_selection_value :: Dynamic t String
,_selection_setValue :: Event t String}
data SelectionConfig t =
SelectionConfig {_selectionConfig_initialValue :: String
,_selectionConfig_label :: String
,_selectionConfig_options :: Dynamic t (Map String String)
,_selectionConfig_setValue :: Event t String}
instance Reflex t => Default (SelectionConfig t) where
def =
SelectionConfig {_selectionConfig_initialValue = ""
,_selectionConfig_label = ""
,_selectionConfig_options = constDyn mempty
,_selectionConfig_setValue = never}
setting :: MonadWidget t m => String -> Bool -> m (Setting t)
setting labelText initial =
do val <- liftIO (getPref labelText initial)
(parent,(input,_)) <-
elAttr' "div" ("class" =: "ui toggle checkbox") $
do el "label" (text labelText)
elAttr' "input"
("type" =: "checkbox" <>
if val
then "checked" =: "checked"
else mempty) $
return ()
liftIO (makeCheckbox $ _el_element parent)
eClick <-
wrapDomEvent (_el_element parent)
elementOnclick $
liftIO $
do checked <-
htmlInputElementGetChecked
(castToHTMLInputElement $ _el_element input)
setPref labelText $ show checked
return checked
dValue <- holdDyn val eClick
return (Setting dValue)
selection :: MonadWidget t m
=> SelectionConfig t -> m (Selection t)
selection (SelectionConfig k0 labelText options eSet) =
do (eRaw,_) <-
elAttr' "div" ("class" =: "ui dropdown compact search button") $
do elClass "span" "text" (text labelText)
icon "dropdown"
divClass "menu" $
do optionsWithDefault <-
mapDyn (`Map.union` (k0 =: "")) options
listWithKey optionsWithDefault $
\k v ->
elAttr "div"
("data-value" =: k <> "class" =: "item")
(dynText v)
postGui <- askPostGui
runWithActions <- askRunWithActions
(eRecv,eRecvTriggerRef) <- newEventWithTriggerRef
onChangeFun <-
liftIO $
syncCallback1
AlwaysRetain
True
(\kStr ->
do let val = fromJSString kStr
maybe (return ())
(\t ->
postGui $
runWithActions
[t :=>
Just val]) =<<
readRef eRecvTriggerRef)
liftIO $
makeDropdown (_el_element eRaw)
onChangeFun
let readKey opts mk =
fromMaybe k0 $
do k <- mk
guard $
Map.member k opts
return k
performEvent_ $
fmap (liftIO .
dropdownSetValue (_el_element eRaw) .
toJSString .
flip (Map.findWithDefault "md") sourceFormats .
extToSource)
eSet
dValue <-
combineDyn readKey options =<<
holdDyn (Just k0)
(leftmost [fmap Just eSet,eRecv])
return (Selection dValue never)
instance HasValue (Setting t) where
type Value (Setting t) = Dynamic t Bool
value = _setting_value
instance HasValue (Selection t) where
type Value (Selection t) = Dynamic t String
value = _selection_value
| davidar/markup.rocks | src/Widgets/Setting.hs | mit | 5,345 | 7 | 22 | 1,931 | 1,222 | 638 | 584 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Server (runServer)
main :: IO ()
main = runServer
| kylesnowschwartz/shop-share | server/app/Main.hs | mit | 123 | 0 | 6 | 30 | 28 | 17 | 11 | 5 | 1 |
module Points where
import Graphics.Rendering.OpenGL
points :: Int -> [(GLfloat,GLfloat,GLfloat)]
points n = [ (sin (4*pi*k/n'), cos (4*pi*k/n'), 2 * k / n' - 1) | k <- [1..n'] ]
where n' = fromIntegral n
| smanilov/petulant-octo-tribble | Points.hs | mit | 212 | 0 | 11 | 42 | 122 | 68 | 54 | 5 | 1 |
{-# LANGUAGE Rank2Types #-}
module TeX.Parser.Conditional
( expandConditional
-- for tests:
, conditionalHead, evaluateHead, runConditionalBody
, ConditionalHead(IfTrue, IfFalse, IfNum)
, Relation(LessThan, GreaterThan, EqualTo)
)
where
import Prelude ( Integer, Show, Eq, Bool(True, False)
, return, fail, reverse
, (>>), (+), (-), ($), (<), (==), (>), (>>=)
)
import Control.Applicative ((<*))
import Text.Parsec ((<|>), (<?>), anyToken, lookAhead)
import TeX.Alias
import TeX.Parser.Assignment
import TeX.Parser.Parser
import TeX.Parser.Prim
import TeX.Parser.Util
import TeX.Token
import TeX.Category
data Relation = LessThan | EqualTo | GreaterThan
deriving (Show, Eq)
relation :: Expander -> TeXParser Relation
relation expand =
(expand (exactToken (CharToken '<' Other)) >> return LessThan) <|>
(expand (exactToken (CharToken '=' Other)) >> return EqualTo) <|>
(expand (exactToken (CharToken '>' Other)) >> return GreaterThan) <?>
"relation"
data ConditionalHead =
IfNum Integer Relation Integer
| IfTrue
| IfFalse
deriving (Show, Eq)
conditionalHead :: Expander -> TeXParser ConditionalHead
conditionalHead expand =
ifnum <|> iftrue <|> iffalse
where
iftrue =
(exactToken (ControlSequence "iftrue") <|> aliasFor AliasIfTrue) >> (return IfTrue)
ifnum = do
_ <- exactToken (ControlSequence "ifnum")
left <- number expand
rel <- relation expand
right <- number expand
return $ IfNum left rel right
iffalse =
(exactToken (ControlSequence "iffalse") <|> aliasFor AliasIfFalse) >> (return IfFalse)
evaluateHead :: ConditionalHead -> TeXParser Bool
evaluateHead (IfNum left rel right) =
case rel of
LessThan -> return $ left < right
EqualTo -> return $ left == right
GreaterThan -> return $ left > right
evaluateHead IfTrue = return True
evaluateHead IfFalse = return False
ifToken :: TeXParser Token
ifToken =
(exactToken (ControlSequence "iftrue")) <|>
(aliasFor AliasIfTrue) <|>
(exactToken (ControlSequence "iffalse")) <|>
(aliasFor AliasIfFalse) <|>
(exactToken (ControlSequence "ifnum")) <?>
"if token"
elseToken :: TeXParser Token
elseToken =
(exactToken (ControlSequence "else")) <?> "else token"
fiToken :: TeXParser Token
fiToken =
(exactToken (ControlSequence "fi")) <?> "fi token"
expandUntil :: Expander -> TeXParser Token -> TeXParser [Token]
expandUntil expand stop =
untilRec []
where
untilRec :: [Token] -> TeXParser [Token]
untilRec revList =
((expand (lookAhead stop) >> (return $ reverse revList)) <|>
(assignment expand >> untilRec revList) <|>
(expand (categoryToken BeginGroup) >> beginGroup >> untilRec revList) <|>
(expand (categoryToken EndGroup) >> endGroup >> untilRec revList) <|>
(expand anyToken >>= (\tok -> untilRec (tok:revList))))
ignoreUntil :: TeXParser Token -> TeXParser ()
ignoreUntil stop =
ignoreUntilRec 0
where
stopLevel :: Integer -> TeXParser ()
stopLevel 0 = return ()
stopLevel _ = fail "not at level 0"
ignoreUntilRec :: Integer -> TeXParser ()
ignoreUntilRec level =
(stopLevel level >> (lookAhead stop) >> return ()) <|>
(ifToken >> ignoreUntilRec (level + 1)) <|>
(fiToken >> ignoreUntilRec (level - 1)) <|>
(anyToken >> ignoreUntilRec level)
runConditionalBody :: Expander -> Bool -> TeXParser [Token]
runConditionalBody expand True = do
body <- expandUntil expand (elseToken <|> fiToken)
((fiToken >> return body) <|>
(elseToken >> ignoreUntil fiToken >> fiToken >> return body))
runConditionalBody expand False = do
ignoreUntil (elseToken <|> fiToken)
((fiToken >> return []) <|>
(elseToken >> expandUntil expand fiToken <* fiToken))
expandConditional :: Expander -> TeXParser [Token]
expandConditional expand = do
head <- conditionalHead expand
value <- evaluateHead head
runConditionalBody expand value
| xymostech/tex-parser | src/TeX/Parser/Conditional.hs | mit | 3,947 | 0 | 16 | 786 | 1,327 | 699 | 628 | 107 | 3 |
-- file: ch4/exB1.hs
-- A function that converts a `String` to an `Int`
-- Daniel Brice
import Data.Char (digitToInt)
safeDigitToInt :: Char -> Int
safeDigitToInt '.' = error "safeDigitToInt: '.' is not an allowed input."
safeDigitToInt dig = digitToInt dig
safeAsInt :: String -> Int
safeAsInt ('-' : xs) = (- 1) * (safeAsInt xs)
safeAsInt "" = error "safeAsInt: \"\" is not an allowed input."
safeAsInt xs = foldl step 0 xs
where
step acc dig = acc * 10 + (safeDigitToInt dig)
| friedbrice/RealWorldHaskell | ch4/exB1.hs | gpl-2.0 | 504 | 0 | 9 | 109 | 136 | 70 | 66 | 9 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.Transform.Fourier.SRDIF
-- Copyright : (c) Matthew Donadio 2003
-- License : GPL
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Split-Radix Decimation in Frequency FFT
--
-----------------------------------------------------------------------------
module Numeric.Transform.Fourier.SRDIF (fft_srdif) where
import DSP.Basic (interleave)
import Data.Array
import Data.Complex
-------------------------------------------------------------------------------
-- | Split-Radix Decimation in Frequency FFT
{-# specialize fft_srdif :: Array Int (Complex Float) -> Int -> (Array Int (Complex Float) -> Array Int (Complex Float)) -> Array Int (Complex Float) #-}
{-# specialize fft_srdif :: Array Int (Complex Double) -> Int -> (Array Int (Complex Double) -> Array Int (Complex Double)) -> Array Int (Complex Double) #-}
fft_srdif :: (Ix a, Integral a, RealFloat b) => Array a (Complex b) -- ^ x[n]
-> a -- ^ N
-> (Array a (Complex b) -> Array a (Complex b)) -- ^ FFT function
-> Array a (Complex b) -- ^ X[k]
fft_srdif x n fft = listArray (0,n-1) $ c
where c2k = elems $ fft $ listArray (0,n2-1) x2k
c4k1 = elems $ fft $ listArray (0,n4-1) x4k1
c4k3 = elems $ fft $ listArray (0,n4-1) x4k3
c = interleave c2k $ interleave c4k1 c4k3
x2k = [ x!i + x!(i+n2) | i <- [0..n2-1] ]
x4k1 = [ (x!i - x!(i+n2) - j * (x!(i+n4) - x!(i+n34))) * w!i | i <- [0..n4-1] ]
x4k3 = [ (x!i - x!(i+n2) + j * (x!(i+n4) - x!(i+n34))) * w!(3*i) | i <- [0..n4-1] ]
j = 0 :+ 1
wn = cis (-2 * pi / fromIntegral n)
w = listArray (0,n-1) $ iterate (* wn) 1
n2 = n `div` 2
n4 = n `div` 4
n34 = 3 * n4
| tolysz/dsp | Numeric/Transform/Fourier/SRDIF.hs | gpl-2.0 | 1,908 | 0 | 17 | 478 | 605 | 336 | 269 | 24 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.