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 OverloadedStrings #-} module Site.Blog ( rules ) where import Control.Monad import Data.Monoid import Hakyll import System.FilePath import Site.Config import Site.Compilers -- | Blog post page blogPostPage :: Tags -> Pipeline String String blogPostPage tags = prePandoc >=> pandoc >=> saveSnapshot "content" >=> postRender >=> postPandoc cxt where postRender = loadAndApplyTemplate postT cxt cxt = postContext <> tagsField "postTags" tags -- | Blog archive page. blogArchivePage :: Tags -- ^ classify based on year -> Tags -- ^ classify based on tags. -> Pipeline String String blogArchivePage yearlyPosts tags = prePandoc >=> pandoc >=> archiveRender >=> postPandoc cxt where archiveRender = loadAndApplyTemplate archiveIndexT cxt cxt = constField "title" "Posts Archive" <> siteContext <> tagCloudField "tagcloud" tagCloudMin tagCloudMax tags <> tagListField "oldPosts" yearlyPosts tagListField key tgs = field key $ \ _ -> renderTagList tgs -- | Generating feeds. compileFeeds :: Compiler [Item String] compileFeeds = loadAllSnapshots postsPat "content" >>= fmap (take postsOnFeed) . recentFirst >>= mapM relativizeUrls -- | Generating a tags page makeTagRules :: Identifier -> String -> Pattern -> Rules () makeTagRules template tag pat = do route idRoute compile $ makeItem "" >>= prePandoc >>= pandoc >>= loadAndApplyTemplate template tagContext >>= postPandoc tagContext where tagContext = postContext <> constField "tag" tag <> listField "posts" postContext tagPosts tagPosts = loadPosts pat -- | This function generates the year of the post from its -- identifier. This is used in building the archives. getYear :: Identifier -> String getYear = takeWhile (/= '-') . takeFileName . toFilePath rules :: Rules () rules = do -- -- Classify posts based on tags. -- postTags <- buildTags "posts/*" $ fromCapture "posts/tags/*.html" -- Generate the tags page tagsRules postTags $ makeTagRules tagT -- -- Compiling individual posts. -- match postsPat $ do route $ setExtension "html" compilePipeline $ blogPostPage postTags -- -- Create atom/rss feeds feeds. -- let feedContext = postContext <> bodyField "description" in do create ["posts/feeds/atom.xml"] $ do route idRoute compile $ compileFeeds >>= renderAtom feedConfig feedContext create ["posts/feeds/rss.xml"] $ do route idRoute compile $ compileFeeds >>= renderRss feedConfig feedContext -- -- Creating the archive. -- let yearTag ident = return [getYear ident] in do dateTags <- buildTagsWith yearTag "posts/*" $ fromCapture "posts/archive/*.html" tagsRules dateTags $ makeTagRules archiveT -- Creating the index page of the archive create ["posts/archive/index.html"] $ do route idRoute compile $ makeItem "" >>= blogArchivePage dateTags postTags
piyush-kurur-pages/website
Site/Blog.hs
bsd-3-clause
3,238
0
16
906
696
338
358
67
1
----------------------------------------------------------------------------- -- | -- Module : Data.Permute.IO -- Copyright : Copyright (c) , Patrick Perry <[email protected]> -- License : BSD3 -- Maintainer : Patrick Perry <[email protected]> -- Stability : experimental -- -- Mutable permutations in the 'IO' monad. module Data.Permute.IO ( -- * Permutations IOPermute, -- * Overloaded mutable permutation interface module Data.Permute.MPermute ) where import Data.Permute.IOBase( IOPermute ) import Data.Permute.MPermute
patperry/permutation
lib/Data/Permute/IO.hs
bsd-3-clause
568
0
5
97
47
35
12
5
0
-- Copyright (c) 2015-2020 Rudy Matela. -- Distributed under the 3-Clause BSD licence (see the file LICENSE). {-# LANGUAGE TemplateHaskell, CPP #-} import Test -- import Test.LeanCheck -- already exported by Test import Test.LeanCheck.Derive import System.Exit (exitFailure) import Data.List (elemIndices,sort) import Test.LeanCheck.Utils data D0 = D0 deriving Show data D1 a = D1 a deriving Show data D2 a b = D2 a b deriving Show data D3 a b c = D3 a b c deriving Show data C1 a = C11 a | C10 deriving Show data C2 a b = C22 a b | C21 a | C20 deriving Show data I a b = a :+ b deriving Show deriveListable ''D0 deriveListable ''D1 deriveListable ''D2 deriveListable ''D3 deriveListable ''C1 deriveListable ''C2 deriveListable ''I -- recursive datatypes data Peano = Zero | Succ Peano deriving Show data List a = a :- List a | Nil deriving Show data Bush a = Bush a :-: Bush a | Leaf a deriving (Show, Eq) data Tree a = Node (Tree a) a (Tree a) | Null deriving (Show, Eq) deriveListable ''Peano deriveListable ''List deriveListable ''Bush deriveListable ''Tree -- Nested datatype cascade data Nested = Nested N0 (N1 Int) (N2 Int Int) data N0 = R0 Int data N1 a = R1 a data N2 a b = R2 a b deriveListableCascading ''Nested -- Recursive nested datatype cascade data RN = RN RN0 (RN1 Int) (RN2 Int RN) data RN0 = Nest0 Int | Recurse0 RN data RN1 a = Nest1 a | Recurse1 RN data RN2 a b = Nest2 a b | Recurse2 RN deriveListableCascading ''RN -- Type synonyms data Pair a = Pair a a type Alias a = Pair a -- deriveListable ''Alias -- this will fail deriveListableCascading ''Alias deriveListableIfNeeded ''Alias -- only works because instance already exists -- Nested type synonyms data Triple a = Triple a a a type Tralias a = Triple a data Pairiple a = Pairriple (Tralias a) (Tralias a) deriveListableCascading ''Pairiple -- Those should have no effect (instance already exists): {- uncommenting those should generate warnings deriveListable ''Bool deriveListable ''Maybe deriveListable ''Either -} -- Those should not generate warnings deriveListableIfNeeded ''Bool deriveListableIfNeeded ''Maybe deriveListableIfNeeded ''Either main :: IO () main = do max <- getMaxTestsFromArgs 200 case elemIndices False (tests max) of [] -> putStrLn "Tests passed!" is -> do putStrLn ("Failed tests:" ++ show is) exitFailure tests :: Int -> [Bool] tests n = [ True , map unD0 list =| n |= list , map unD1 list =| n |= (list :: [Int]) , map unD2 list =| n |= (list :: [(Int,Int)]) , map unD3 list =| n |= (list :: [(Int,Int,Int)]) , map unD1 list == (list :: [()]) , map unD2 list == (list :: [((),())]) , map unD3 list == (list :: [((),(),())]) , map unD1 list == (list :: [Bool]) , map unD2 list == (list :: [(Bool,Bool)]) , map unD3 list == (list :: [(Bool,Bool,Bool)]) , map peanoToNat list =| n |= list , map listToList list =| n |= (list :: [[Bool]]) , map listToList list =| n |= (list :: [[Int]]) , mapT peanoToNat tiers =| 6 |= tiers , mapT listToList tiers =| 6 |= (tiers :: [[ [Bool] ]]) , mapT listToList tiers =| 6 |= (tiers :: [[ [Int] ]]) , take 6 (list :: [Bush Bool]) == [ Leaf False , Leaf True , Leaf False :-: Leaf False , Leaf False :-: Leaf True , Leaf True :-: Leaf False , Leaf True :-: Leaf True ] , take 6 (list :: [Tree Bool]) == [ Null , Node Null False Null , Node Null True Null , Node Null False (Node Null False Null) , Node Null False (Node Null True Null) , Node Null True (Node Null False Null) ] , (tiers :: [[ Bool ]]) =| 6 |= $(deriveTiers ''Bool) , (tiers :: [[ [Int] ]]) =| 6 |= $(deriveTiers ''[]) , (tiers :: [[ [Bool] ]]) =| 6 |= $(deriveTiers ''[]) , (tiers :: [[ Maybe Int ]]) =| 6 |= $(deriveTiers ''Maybe) , (tiers :: [[ Maybe Bool ]]) =| 6 |= $(deriveTiers ''Maybe) , ([]:tiers :: [[Either Bool Int]]) =$ map sort . take 6 $= $(deriveTiers ''Either) , (list :: [ Bool ]) =| n |= $(deriveList ''Bool) , (list :: [ [Int] ]) =| n |= $(deriveList ''[]) , (list :: [ [Bool] ]) =| n |= $(deriveList ''[]) , (list :: [ Maybe Int ]) =| n |= $(deriveList ''Maybe) , (list :: [ Maybe Bool ]) =| n |= $(deriveList ''Maybe) ] where unD0 (D0) = () unD1 (D1 x) = (x) unD2 (D2 x y) = (x,y) unD3 (D3 x y z) = (x,y,z) peanoToNat :: Peano -> Nat peanoToNat Zero = 0 peanoToNat (Succ n) = 1 + peanoToNat n listToList :: List a -> [a] listToList Nil = [] listToList (x :- xs) = x : listToList xs
rudymatela/leancheck
test/derive.hs
bsd-3-clause
4,696
0
15
1,215
1,909
1,031
878
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>Plug-n-Hack | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_ur_PK/helpset_ur_PK.hs
apache-2.0
972
78
68
158
419
212
207
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ViewPatterns #-} module Stack.Types.Compiler where import Control.DeepSeq import Control.DeepSeq.Generics (genericRnf) import Data.Aeson import Data.Binary (Binary) import Data.Monoid ((<>)) import qualified Data.Text as T import GHC.Generics (Generic) import Stack.Types.Version -- | Variety of compiler to use. data WhichCompiler = Ghc | Ghcjs deriving (Show, Eq, Ord) -- | Specifies a compiler and its version number(s). -- -- Note that despite having this datatype, stack isn't in a hurry to -- support compilers other than GHC. -- -- NOTE: updating this will change its binary serialization. The -- version number in the 'BinarySchema' instance for 'MiniBuildPlan' -- should be updated. data CompilerVersion = GhcVersion {-# UNPACK #-} !Version | GhcjsVersion {-# UNPACK #-} !Version -- GHCJS version {-# UNPACK #-} !Version -- GHC version deriving (Generic, Show, Eq, Ord) instance Binary CompilerVersion instance NFData CompilerVersion where rnf = genericRnf instance ToJSON CompilerVersion where toJSON = toJSON . compilerVersionName instance FromJSON CompilerVersion where parseJSON (String t) = maybe (fail "Failed to parse compiler version") return (parseCompilerVersion t) parseJSON _ = fail "Invalid CompilerVersion, must be String" parseCompilerVersion :: T.Text -> Maybe CompilerVersion parseCompilerVersion t | Just t' <- T.stripPrefix "ghc-" t , Just v <- parseVersionFromString $ T.unpack t' = Just (GhcVersion v) | Just t' <- T.stripPrefix "ghcjs-" t , [tghcjs, tghc] <- T.splitOn "_ghc-" t' , Just vghcjs <- parseVersionFromString $ T.unpack tghcjs , Just vghc <- parseVersionFromString $ T.unpack tghc = Just (GhcjsVersion vghcjs vghc) | otherwise = Nothing compilerVersionName :: CompilerVersion -> T.Text compilerVersionName (GhcVersion vghc) = "ghc-" <> versionText vghc compilerVersionName (GhcjsVersion vghcjs vghc) = "ghcjs-" <> versionText vghcjs <> "_ghc-" <> versionText vghc whichCompiler :: CompilerVersion -> WhichCompiler whichCompiler GhcVersion {} = Ghc whichCompiler GhcjsVersion {} = Ghcjs isWantedCompiler :: VersionCheck -> CompilerVersion -> CompilerVersion -> Bool isWantedCompiler check (GhcVersion wanted) (GhcVersion actual) = checkVersion check wanted actual isWantedCompiler check (GhcjsVersion wanted wantedGhc) (GhcjsVersion actual actualGhc) = checkVersion check wanted actual && checkVersion check wantedGhc actualGhc isWantedCompiler _ _ _ = False compilerExeName :: WhichCompiler -> String compilerExeName Ghc = "ghc" compilerExeName Ghcjs = "ghcjs" haddockExeName :: WhichCompiler -> String haddockExeName Ghc = "haddock" haddockExeName Ghcjs = "haddock-ghcjs"
akhileshs/stack
src/Stack/Types/Compiler.hs
bsd-3-clause
2,898
0
11
565
673
349
324
62
1
module E.Eta( ArityType(ATop,ABottom), etaExpandAp, annotateArity, deleteArity, etaExpandDef, etaExpandDef', etaExpandProgram, getArityInfo, etaAnnotateProgram, etaReduce ) where import Control.Monad.Identity import Control.Monad.State import Control.Monad.Writer import Data.Typeable import DataConstructors import E.Annotate import E.E import E.Inline import E.Program import E.Subst import E.TypeCheck import E.Values import GenUtil hiding(replicateM_) import Info.Types import Name.Id import Support.FreeVars import Util.NameMonad import Util.SetLike import qualified Info.Info as Info import qualified Stats data ArityType = AFun Bool ArityType | ABottom | ATop deriving(Eq,Ord,Typeable) instance Show ArityType where showsPrec _ ATop = ("ArT" ++) showsPrec _ ABottom = ("ArB" ++) showsPrec _ (AFun False r) = ('\\':) . shows r showsPrec _ (AFun True r) = ("\\o" ++) . shows r arity at = f at 0 where f (AFun _ a) n = f a $! (1 + n) f x n | n `seq` x `seq` True = (x,n) f _ _ = error "Eta.arity: bad." getArityInfo tvr | Just at <- Info.lookup (tvrInfo tvr) = arity at | otherwise = (ATop,0) isOneShot x = getProperty prop_ONESHOT x arityType :: E -> ArityType arityType e = f e where f EError {} = ABottom f (ELam x e) = AFun (isOneShot x) (f e) f (EAp a b) = case f a of AFun _ xs | isCheap b -> xs _ -> ATop f ec@ECase { eCaseScrutinee = scrut } = case foldr1 andArityType (map f $ caseBodies ec) of xs@(AFun True _) -> xs xs | isCheap scrut -> xs _ -> ATop f (ELetRec ds e) = case f e of xs@(AFun True _) -> xs xs | all isCheap (snds ds) -> xs _ -> ATop f (EVar tvr) | Just at <- Info.lookup (tvrInfo tvr) = at f _ = ATop andArityType ABottom at2 = at2 andArityType ATop at2 = ATop andArityType (AFun t1 at1) (AFun t2 at2) = AFun (t1 && t2) (andArityType at1 at2) andArityType at1 at2 = andArityType at2 at1 annotateArity e nfo = annotateArity' (arityType e) nfo annotateArity' at nfo = Info.insert (Arity n (b == ABottom)) $ Info.insert at nfo where (b,n) = arity at -- delety any arity information deleteArity nfo = Info.delete (undefined :: Arity) $ Info.delete (undefined :: Arity) nfo expandPis :: DataTable -> E -> E expandPis dataTable e = f (followAliases dataTable e) where f (EPi v r) = EPi v (f (followAliases dataTable r)) f e = e {- fromPi' :: DataTable -> E -> (E,[TVr]) fromPi' dataTable e = f [] (followAliases dataTable e) where f as (EPi v e) = f (v:as) (followAliases dataTable e) f as e = (e,reverse as) -} -- this annotates, but only expands top-level definitions etaExpandProgram :: Stats.MonadStats m => Program -> m Program --etaExpandProgram prog = runNameMT (programMapDs f (etaAnnotateProgram prog)) where etaExpandProgram prog = runNameMT (programMapDs f prog) where f (t,e) = do etaExpandDef' (progDataTable prog) 0 t e -- this annotates a program with its arity information, iterating until a fixpoint is reached. etaAnnotateProgram :: Program -> Program etaAnnotateProgram prog = runIdentity $ programMapRecGroups mempty pass iletann pass f prog where pass _ = return iletann e nfo = return $ annotateArity e nfo letann e nfo = case Info.lookup nfo of Nothing -> put True >> return (annotateArity e nfo) Just at -> do let at' = arityType e when (at /= at') (put True) return $ annotateArity' at' nfo f (rg,ts) = do let (ts',fs) = runState (annotateCombs mempty pass letann pass ts) False if fs then f (rg,ts') else return ts' -- | eta reduce as much as possible etaReduce :: E -> E etaReduce e = f e where f (ELam t (EAp x (EVar t'))) | t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x f e = e -- | only reduce if all lambdas can be discarded. otherwise leave them in place {- etaReduce' :: E -> (E,Int) etaReduce' e = case f e 0 of (ELam {},_) -> (e,0) x -> x where f (ELam t (EAp x (EVar t'))) n | n `seq` True, t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x (n + 1) f e n = (e,n) -} etaExpandDef' dataTable n t e = etaExpandDef dataTable n t e >>= \x -> case x of Nothing -> return (tvrInfo_u (annotateArity e) t,e) Just x -> return x --collectIds :: E -> IdSet --collectIds e = execWriter $ annotate mempty (\id nfo -> tell (singleton id) >> return nfo) (\_ -> return) (\_ -> return) e -- | eta expand a definition etaExpandDef :: (NameMonad Id m,Stats.MonadStats m) => DataTable -> Int -- ^ eta expand at least this far, independent of calculated amount -> TVr -> E -> m (Maybe (TVr,E)) etaExpandDef _ _ _ e | isAtomic e = return Nothing -- will be inlined etaExpandDef dataTable min t e = ans where --fvs = foldr insert (freeVars (b,map getType rs,(tvrType t,e))) (map tvrIdent rs) `mappend` collectIds e --(b,rs) = fromLam e at = arityType e zeroName = case fromAp e of (EVar v,_) -> "use.{" ++ tvrShowName v _ -> "random" --nameSupply = [ n | n <- [2,4 :: Int ..], n `notMember` fvs ] nameSupply = undefined ans = do -- note that we can't use the type in the tvr, because it will not have the right free typevars. (ne,flag) <- f min at e (expandPis dataTable $ infertype dataTable e) nameSupply if flag then return (Just (tvrInfo_u (annotateArity' at) t,ne)) else return Nothing f min (AFun _ a) (ELam tvr e) (EPi tvr' rt) _ns = do (ne,flag) <- f (min - 1) a e (subst tvr' (EVar tvr) rt) _ns return (ELam tvr ne,flag) f min (AFun _ a) e (EPi tt rt) _nns = do if tvrIdent t == emptyId then Stats.mtick ("EtaExpand." ++ zeroName) else Stats.mtick ("EtaExpand.def.{" ++ tvrShowName t) n <- newName let nv = tt { tvrIdent = n } eb = EAp e (EVar nv) (ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns return (ELam nv ne,True) f min a e (EPi tt rt) _nns | min > 0 = do if tvrIdent t == emptyId then Stats.mtick ("EtaExpand.min." ++ zeroName) else Stats.mtick ("EtaExpand.min.def.{" ++ tvrShowName t) n <- newName let nv = tt { tvrIdent = n } eb = EAp e (EVar nv) (ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns return (ELam nv ne,True) f _ _ e _ _ = do return (e,False) -- | eta expand a use of a value etaExpandAp :: (NameMonad Id m,Stats.MonadStats m) => DataTable -> TVr -> [E] -> m (Maybe E) etaExpandAp dataTable tvr xs = do r <- etaExpandDef dataTable 0 tvr { tvrIdent = emptyId} (foldl EAp (EVar tvr) xs) return (fmap snd r) {- etaExpandAp _ _ [] = return Nothing -- so simple renames don't get eta-expanded etaExpandAp dataTable t as | Just (Arity n err) <- Info.lookup (tvrInfo t) = case () of () | n > length as -> do let e = foldl EAp (EVar t) as let (_,ts) = fromPi' dataTable (infertype dataTable e) ets = (take (n - length as) ts) mticks (length ets) ("EtaExpand.use.{" ++ tvrShowName t) let tvrs = f mempty [ (tvrIdent t,t { tvrIdent = n }) | n <- [2,4 :: Int ..], not $ n `Set.member` freeVars (e,ets) | t <- ets ] f map ((n,t):rs) = t { tvrType = substMap map (tvrType t)} : f (Map.insert n (EVar t) map) rs f _ [] = [] return (Just $ foldr ELam (foldl EAp e (map EVar tvrs)) tvrs) | err && length as > n -> do let ot = infertype dataTable (foldl EAp (EVar t) as) mticks (length as - n) ("EtaExpand.bottoming.{" ++ tvrShowName t) return $ Just (prim_unsafeCoerce ot (foldl EAp (EVar t) (take n as))) -- we can drop any extra arguments applied to something that bottoms out. | otherwise -> return Nothing etaExpandAp _ t as = return Nothing -}
m-alvarez/jhc
src/E/Eta.hs
mit
7,993
12
16
2,189
2,373
1,206
1,167
-1
-1
module LiftOneLevel.LetIn1 where --A definition can be lifted from a where or let into the surronding binding group. --Lifting a definition widens the scope of the definition. --In this example, lift 'sq' in 'sumSquares' --This example aims to test lifting a definition from a let clause to a where clause, --and the elimination of the keywords 'let' and 'in' sumSquares x y = let sq 0=0 sq z=z^pow in sq x + sq y where pow=2 anotherFun 0 y = sq y where sq x = x^2
RefactoringTools/HaRe
test/testdata/LiftOneLevel/LetIn1.hs
bsd-3-clause
536
0
9
158
91
47
44
7
2
{-# LANGUAGE PatternGuards #-} module Idris.Elab.Transform 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.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) elabTransform :: ElabInfo -> FC -> Bool -> PTerm -> PTerm -> Idris (Term, Term) elabTransform info fc safe lhs_in@(PApp _ (PRef _ _ tf) _) rhs_in = do ctxt <- getContext i <- getIState let lhs = addImplPat i lhs_in logLvl 5 ("Transform LHS input: " ++ showTmImpls lhs) (ElabResult lhs' dlhs [] ctxt' newDecls highlights, _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "transLHS") infP initEState (erun fc (buildTC i info ETransLHS [] (sUN "transform") (infTerm lhs))) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights let lhs_tm = orderPats (getInferTerm lhs') let lhs_ty = getInferType lhs' let newargs = pvars i lhs_tm (clhs_tm_in, clhs_ty) <- recheckC_borrowing False False [] fc id [] lhs_tm let clhs_tm = renamepats pnames clhs_tm_in logLvl 3 ("Transform LHS " ++ show clhs_tm) logLvl 3 ("Transform type " ++ show clhs_ty) let rhs = addImplBound i (map fst newargs) rhs_in logLvl 5 ("Transform RHS input: " ++ showTmImpls rhs) ((rhs', defer, ctxt', newDecls), _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "transRHS") clhs_ty initEState (do pbinds i lhs_tm setNextName (ElabResult _ _ _ ctxt' newDecls highlights) <- erun fc (build i info ERHS [] (sUN "transform") rhs) erun fc $ psolve lhs_tm tt <- get_term let (rhs', defer) = runState (collectDeferred Nothing [] ctxt tt) [] return (rhs', defer, ctxt', newDecls)) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights (crhs_tm_in, crhs_ty) <- recheckC_borrowing False False [] fc id [] rhs' let crhs_tm = renamepats pnames crhs_tm_in logLvl 3 ("Transform RHS " ++ show crhs_tm) -- Types must always convert case converts ctxt [] clhs_ty crhs_ty of OK _ -> return () Error e -> ierror (At fc (CantUnify False (clhs_tm, Nothing) (crhs_tm, Nothing) e [] 0)) -- In safe mode, values must convert (Thinks: This is probably not -- useful as is, perhaps it should require a proof of equality instead) when safe $ case converts ctxt [] clhs_tm crhs_tm of OK _ -> return () Error e -> ierror (At fc (CantUnify False (clhs_tm, Nothing) (crhs_tm, Nothing) e [] 0)) case unApply (depat clhs_tm) of (P _ tfname _, _) -> do addTrans tfname (clhs_tm, crhs_tm) addIBC (IBCTrans tf (clhs_tm, crhs_tm)) _ -> ierror (At fc (Msg "Invalid transformation rule (must be function application)")) return (clhs_tm, crhs_tm) where depat (Bind n (PVar t) sc) = depat (instantiate (P Bound n t) sc) depat x = x renamepats (n' : ns) (Bind n (PVar t) sc) = Bind n' (PVar t) (renamepats ns sc) -- all Vs renamepats _ sc = sc -- names for transformation variables. Need to ensure these don't clash -- with any other names when applying rules, so rename here. pnames = map (\i -> sMN i ("tvar" ++ show i)) [0..] elabTransform info fc safe lhs_in rhs_in = ierror (At fc (Msg "Invalid transformation rule (must be function application)"))
osa1/Idris-dev
src/Idris/Elab/Transform.hs
bsd-3-clause
4,686
0
19
1,319
1,439
742
697
97
6
{- | Module : Orville.PostgreSQL.Internal.EntityOperations Copyright : Flipstone Technology Partners 2021 License : MIT -} module Orville.PostgreSQL.Internal.EntityOperations ( insertEntity, insertAndReturnEntity, insertEntities, insertAndReturnEntities, updateEntity, updateAndReturnEntity, deleteEntity, deleteAndReturnEntity, findEntitiesBy, findFirstEntityBy, findEntity, ) where import Control.Exception (Exception, throwIO) import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.List.NonEmpty (NonEmpty ((:|))) import Data.Maybe (listToMaybe) import qualified Orville.PostgreSQL.Internal.Execute as Execute import qualified Orville.PostgreSQL.Internal.Insert as Insert import qualified Orville.PostgreSQL.Internal.MonadOrville as MonadOrville import qualified Orville.PostgreSQL.Internal.PrimaryKey as PrimaryKey import qualified Orville.PostgreSQL.Internal.ReturningOption as ReturningOption import qualified Orville.PostgreSQL.Internal.Select as Select import qualified Orville.PostgreSQL.Internal.SelectOptions as SelectOptions import qualified Orville.PostgreSQL.Internal.TableDefinition as TableDef import qualified Orville.PostgreSQL.Internal.Update as Update {- | Inserts a entity into the specified table. -} insertEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> writeEntity -> m () insertEntity entityTable entity = insertEntities entityTable (entity :| []) {- | Inserts a entity into the specified table, returning the data inserted into the database. You can use this function to obtain any column values filled in by the database, such as auto-incrementing ids. -} insertAndReturnEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> writeEntity -> m readEntity insertAndReturnEntity entityTable entity = do returnedEntities <- insertAndReturnEntities entityTable (entity :| []) case returnedEntities of [returnedEntity] -> pure returnedEntity _ -> liftIO . throwIO . RowCountExpectationError $ "Expected exactly one row to be returned in RETURNING clause, but got " <> show (length returnedEntities) {- | Inserts a non-empty list of entities into the specified table -} insertEntities :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> NonEmpty writeEntity -> m () insertEntities tableDef = Insert.executeInsert . Insert.insertToTable tableDef {- | Inserts a non-empty list of entities into the specified table, returning the data that was inserted into the database. You can use this function to obtain any column values filled in by the database, such as auto-incrementing ids. -} insertAndReturnEntities :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> NonEmpty writeEntity -> m [readEntity] insertAndReturnEntities tableDef = Insert.executeInsertReturnEntities . Insert.insertToTableReturning tableDef {- | Updates the row with the given key in with the data given by 'writeEntity' -} updateEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> writeEntity -> m () updateEntity tableDef key = Update.executeUpdate . Update.updateToTable tableDef key {- | Updates the row with the given key in with the data given by 'writeEntity', returning updated row from the database. If no row matches the given key, 'Nothing' will be returned. You can use this function to obtain any column values computer by the database during update, including columns with triggers attached to them. -} updateAndReturnEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> writeEntity -> m (Maybe readEntity) updateAndReturnEntity tableDef key = Update.executeUpdateReturnEntity . Update.updateToTableReturning tableDef key {- | Deletes the row with the given key -} deleteEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> m () deleteEntity tableDef key = Execute.executeVoid $ TableDef.mkDeleteExpr ReturningOption.WithoutReturning tableDef key {- | Deletes the row with the given key, returning the row that was deleted. If no row matches the given key, 'Nothing' is returned. -} deleteAndReturnEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> m (Maybe readEntity) deleteAndReturnEntity tableDef key = fmap listToMaybe $ Execute.executeAndDecode (TableDef.mkDeleteExpr ReturningOption.WithReturning tableDef key) (TableDef.tableMarshaller tableDef) {- | Finds all the entities in the given table according to the specified 'SelectOptions.SelectOptions', which may include where conditions to match, ordering specifications, etc. -} findEntitiesBy :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> SelectOptions.SelectOptions -> m [readEntity] findEntitiesBy entityTable selectOptions = Select.executeSelect $ Select.selectTable entityTable selectOptions {- | Like 'findEntitiesBy, but adds a 'LIMIT 1' to the query and then returns the first item from the list. Usually when you use this you will want to provide an order by clause in the 'SelectOptions.SelectOptions' because the database will not guarantee ordering. -} findFirstEntityBy :: MonadOrville.MonadOrville m => TableDef.TableDefinition key writeEntity readEntity -> SelectOptions.SelectOptions -> m (Maybe readEntity) findFirstEntityBy entityTable selectOptions = listToMaybe <$> findEntitiesBy entityTable (SelectOptions.limit 1 <> selectOptions) {- | Finds a single entity by the table's primary key value. -} findEntity :: MonadOrville.MonadOrville m => TableDef.TableDefinition (TableDef.HasKey key) writeEntity readEntity -> key -> m (Maybe readEntity) findEntity entityTable key = let primaryKeyCondition = PrimaryKey.primaryKeyEquals (TableDef.tablePrimaryKey entityTable) key in findFirstEntityBy entityTable (SelectOptions.where_ primaryKeyCondition) {- | INTERNAL: This should really never get thrown in the real world. It would be thrown if the returning clause from an insert statement for a single record returned 0 records or more than 1 record. -} newtype RowCountExpectationError = RowCountExpectationError String deriving (Show) instance Exception RowCountExpectationError
flipstone/orville
orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/EntityOperations.hs
mit
6,679
0
13
1,084
1,060
563
497
124
2
import qualified Data.Array.Unboxed as A import Data.Char ones :: A.Array Int String ones = A.listArray (0,9) ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tens :: A.Array Int String tens = A.listArray (1,9) ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] teens :: A.Array Int String teens = A.listArray (11,19) ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] oneThousand :: String oneThousand = "one thousand" writeOut :: Int -> String writeOut n | length showN == 1 = ones A.! n | length showN == 2 = writeOutDouble showN | length showN == 3 = writeOutTriple showN | n == 1000 = oneThousand where showN = show n writeOutDouble num@(a:b:[]) | a == '0' = ones A.! (read $ return b) | b == '0' = tens A.! (read $ return a) | a == '1' = teens A.! read num | otherwise = tens A.! (read $ return a) ++ "-" ++ ones A.! (read $ return b) writeOutTriple (a:b:c:[]) = ones A.! (read $ return a) ++ " hundred" ++ if b /= '0' || c /= '0' then " and " ++ writeOutDouble (b:c:[]) else "" solve m n = sum $ map (length . filter isAlpha . writeOut) [m..n]
jwtouron/haskell-play
ProjectEuler/Problem17.hs
mit
1,455
0
14
491
573
302
271
26
2
module MyHttp (RequestType (..), Request(..), Response(..), Context(..), ServerPart, choose) where --import Control.Monad --import Control.Applicative data RequestType = Get | Post deriving (Eq) data Request = Request { route :: String , reqtype :: RequestType } data Response = Response { content :: String , statusCode :: Int } instance Show Response where show (Response cntnt stts) = "Status Code: " ++ show stts ++ "\n" ++ "Content: " ++ cntnt data Context = Context { request :: Request , response :: Response } type ServerPart = Context -> Maybe Context choose :: [ServerPart] -> ServerPart choose [] _ = Nothing choose (x:xs) context = case x context of Just c -> Just c Nothing -> choose xs context {-- instance MonadPlus (ServerPart m) where mzero = Nothing mplus = choose --}
nicolocodev/learnhappstack
4_Filters/MyHttp.hs
mit
845
0
10
189
250
143
107
21
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {- | Module : Database.Couch.Explicit.Database Description : Database-oriented requests to CouchDB, with explicit parameters Copyright : Copyright (c) 2015, Michael Alan Dorman License : MIT Maintainer : [email protected] Stability : experimental Portability : POSIX This module is intended to be @import qualified@. /No attempt/ has been made to keep names of types or functions from clashing with obvious or otherwise commonly-used names, or even other modules within this package. The functions here are derived from (and presented in the same order as) the <http://docs.couchdb.org/en/1.6.1/api/database/index.html Database API documentation>. For each function, we attempt to link back to the original documentation, as well as make a notation as to how complete and correct we feel our implementation is. Each function takes a 'Database.Couch.Types.Context'---which, among other things, holds the name of the database---as its final parameter, and returns a 'Database.Couch.Types.Result'. -} module Database.Couch.Explicit.Database where import Control.Monad (return, when) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Except (throwE) import Data.Aeson (FromJSON, ToJSON, Value (Object), object, toJSON) import Data.Bool (Bool (True)) import Data.Function (($), (.)) import Data.Functor (fmap) import Data.HashMap.Strict (fromList) import Data.Int (Int) import Data.Maybe (Maybe (Just), catMaybes, fromJust, isJust) import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Database.Couch.Internal (standardRequest, structureRequest) import Database.Couch.RequestBuilder (RequestBuilder, addPath, selectDb, selectDoc, setHeaders, setJsonBody, setMethod, setQueryParam) import Database.Couch.ResponseParser (responseStatus, toOutputType) import Database.Couch.Types (Context, DbAllDocs, DbBulkDocs, DbChanges, DocId, DocRevMap, Error (NotFound, Unknown), Result, ToQueryParameters, bdAllOrNothing, bdFullCommit, bdNewEdits, cLastEvent, toQueryParameters) import Network.HTTP.Types (statusCode) {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#head--db Check that the requested database exists> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.exists ctx >>= asBool Status: __Complete__ -} exists :: (FromJSON a, MonadIO m) => Context -> m (Result a) exists = structureRequest request parse where request = do selectDb setMethod "HEAD" parse = do -- Check status codes by hand because we don't want 404 to be an error, just False s <- responseStatus case statusCode s of 200 -> toOutputType $ object [("ok", toJSON True)] 404 -> throwE NotFound _ -> throwE Unknown {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#get--db Get most basic meta-information> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.meta ctx Status: __Complete__ -} meta :: (FromJSON a, MonadIO m) => Context -> m (Result a) meta = standardRequest request where request = selectDb {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#put--db Create a database> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.meta ctx Status: __Complete__ -} create :: (FromJSON a, MonadIO m) => Context -> m (Result a) create = standardRequest request where request = do selectDb setMethod "PUT" {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#delete--db Delete a database> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.delete ctx >>= asBool Status: __Complete__ -} delete :: (FromJSON a, MonadIO m) => Context -> m (Result a) delete = standardRequest request where request = do selectDb setMethod "DELETE" {- | <http://docs.couchdb.org/en/1.6.1/api/database/common.html#post--db Create a new document in a database> The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.createDoc True someObject ctx >>= asBool Status: __Complete__ -} createDoc :: (FromJSON a, MonadIO m, ToJSON b) => Bool -- ^ Whether to create the document in batch mode -> b -- ^ The document to create -> Context -> m (Result a) createDoc batch doc = standardRequest request where request = do selectDb setMethod "POST" when batch (setQueryParam [("batch", Just "ok")]) setJsonBody doc {- | <http://docs.couchdb.org/en/1.6.1/api/database/bulk-api.html#get--db-_all_docs Get a list of all database documents> The return value is a list of objects whose fields often vary, so it is easily decoded as a 'Data.List.List' of 'Data.Aeson.Value': >>> value :: Result [Value] <- Database.allDocs dbAllDocs ctx Status: __Complete__ -} allDocs :: (FromJSON a, MonadIO m) => DbAllDocs -- ^ Parameters governing retrieval ('Database.Couch.Types.dbAllDocs' is an empty default) -> Context -> m (Result a) allDocs = standardRequest . allDocsBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/bulk-api.html#post--db-_all_docs Get a list of some database documents> The return value is a list of objects whose fields often vary, so it is easily decoded as a 'Data.List.List' of 'Data.Aeson.Value': >>> value :: Result [Value] <- Database.someDocs ["a", "b", "c"] ctx Status: __Complete__ -} someDocs :: (FromJSON a, MonadIO m) => DbAllDocs -- ^ Parameters governing retrieval ('Database.Couch.Types.dbAllDocs' is an empty default) -> [DocId] -- ^ List of ids documents to retrieve -> Context -> m (Result a) someDocs param ids = standardRequest request where request = do setMethod "POST" allDocsBase param let parameters = Object (fromList [("keys", toJSON ids)]) setJsonBody parameters {- | <http://docs.couchdb.org/en/1.6.1/api/database/bulk-api.html#post--db-_bulk_docs Create or update a list of documents> The return value is a list of objects whose fields often vary, so it is easily decoded as a 'Data.List.List' of 'Data.Aeson.Value': >>> value :: Result [Value] <- Database.bulkDocs dbBulkDocs ["a", "b", "c"] ctx Status: __Complete__ -} bulkDocs :: (FromJSON a, MonadIO m, ToJSON a) => DbBulkDocs -- ^ Parameters coverning retrieval ('Database.Couch.Types.dbBulkDocs' is an empty default) -> [a] -- ^ List of documents to add or update -> Context -> m (Result a) bulkDocs param docs = standardRequest request where request = do setMethod "POST" -- TODO: We need a way to set a header when we have a value for it [refactor] when (isJust $ bdFullCommit param) (setHeaders [("X-Couch-Full-Commit", if fromJust $ bdFullCommit param then "true" else "false")]) selectDb addPath "_bulk_docs" -- TODO: We need a way to construct a json body from parameters [refactor] let parameters = Object ((fromList . catMaybes) [ Just ("docs", toJSON docs) , boolToParam "all_or_nothing" bdAllOrNothing , boolToParam "new_edits" bdNewEdits ]) setJsonBody parameters boolToParam k s = do v <- s param return (k, if v then "true" else "false") {- | <http://docs.couchdb.org/en/1.6.1/api/database/changes.html#get--db-_changes Get a list of all document modifications> This call does not stream out results; so while it allows you to specify parameters for streaming, it's a dirty, dirty lie. The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.changes ctx Status: __Limited__ -} changes :: (FromJSON a, MonadIO m) => DbChanges -- ^ Arguments governing changes contents ('Database.Couch.Types.dbChanges' is an empty default) -> Context -> m (Result a) changes param = standardRequest request where request = do -- TODO: We need a way to set a header when we have a value for it [refactor] when (isJust $ cLastEvent param) (setHeaders [("Last-Event-Id", encodeUtf8 . fromJust $ cLastEvent param)]) selectDb addPath "_changes" {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_compact Compact a database> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.compact ctx >>= asBool Status: __Complete__ -} compact :: (FromJSON a, MonadIO m) => Context -> m (Result a) compact = standardRequest compactBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_compact-ddoc Compact the views attached to a particular design document> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.compactDesignDoc "ddoc" ctx >>= asBool Status: __Complete__ -} compactDesignDoc :: (FromJSON a, MonadIO m) => DocId -- ^ The 'DocId' of the design document to compact -> Context -> m (Result a) compactDesignDoc doc = standardRequest request where request = do compactBase selectDoc doc {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_ensure_full_commit Ensure that all changes to the database have made it to disk> The return value is an object that can hold an "instance_start_time" key, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.sync ctx >>= asBool Status: __Complete__ -} sync :: (FromJSON a, MonadIO m) => Context -> m (Result a) sync = standardRequest request where request = do setMethod "POST" selectDb addPath "_ensure_full_commit" {- | <http://docs.couchdb.org/en/1.6.1/api/database/compact.html#post--db-_view_cleanup Cleanup any stray view definitions> The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Bool <- Database.cleanup ctx >>= asBool Status: __Complete__ -} cleanup :: (FromJSON a, MonadIO m) => Context -> m (Result a) cleanup = standardRequest request where request = do setMethod "POST" selectDb addPath "_view_cleanup" {- | <http://docs.couchdb.org/en/1.6.1/api/database/security.html#get--db-_security Get security information for database> The return value is an object that has with a standard set of fields ("admin" and "members" keys, which each contain "users" and "roles"), the system does not prevent you from adding (and even using in validation functions) additional fields, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.getSecurity ctx Status: __Complete__ -} getSecurity :: (FromJSON a, MonadIO m) => Context -> m (Result a) getSecurity = standardRequest securityBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/security.html#post--db-_security Set security information for database> The input value is an object that has with a standard set of fields ("admin" and "members" keys, which each contain "users" and "roles"), but the system does not prevent you from adding (and even using in validation functions) additional fields, so we don't specify a specific type, and you can roll your own: The return value is an object that should only contain a single key "ok", so it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator: >>> value :: Result Value <- Database.setSecurity (object [("users", object [("harry")])]) ctx >>= asBool Status: __Complete__ -} setSecurity :: (FromJSON b, MonadIO m, ToJSON a) => a -- ^ The security document content -> Context -> m (Result b) setSecurity doc = standardRequest request where request = do setMethod "PUT" securityBase setJsonBody doc {- | <http://docs.couchdb.org/en/1.6.1/api/database/temp-views.html#post--db-_temp_view Create a temporary view> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.tempView "function (doc) { emit (1); }" (Just "_count") Nothing ctx Status: __Complete__ -} tempView :: (FromJSON a, MonadIO m) => Text -- ^ The text of your map function -> Maybe Text -- ^ The text of your optional reduce function -> Context -> m (Result a) tempView map reduce = standardRequest request where request = do setMethod "POST" selectDb -- TODO: We need a way to construct a json body from parameters [refactor] let parameters = Object (fromList $ catMaybes [ Just ("map", toJSON map) , fmap (("reduce",) . toJSON) reduce ]) addPath "_temp_view" setJsonBody parameters {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#post--db-_purge Purge document revisions from the database> The return value is an object with two fields "purge_seq" and "purged", which contains an object with no fixed keys, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.purge $ DocRevMap [(DocId "junebug", [DocRev "1-1"])] Nothing ctx However, the content of "purged" is effectively a 'Database.Couch.Types.DocRevMap', so the output can be parsed into an (Int, DocRevMap) pair using: >>> (,) <$> (getKey "purge_seq" >>= toOutputType) <*> (getKey "purged" >>= toOutputType) Status: __Complete__ -} purge :: (FromJSON a, MonadIO m) => DocRevMap -- ^ A 'Database.Couch.Types.DocRevMap' of documents and versions to purge -> Context -> m (Result a) purge docRevs = standardRequest request where request = do docRevBase docRevs addPath "_purge" {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#post--db-_missing_revs Find document revisions not present in the database> The return value is an object with one field "missed_revs", which contains an object with no fixed keys, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.missingRevs $ DocRevMap [(DocId "junebug", [DocRev "1-1"])] ctx However, the content of "missed_revs" is effectively a 'Database.Couch.Types.DocRevMap', so it can be parsed into a 'Database.Couch.Types.DocRevMap' using: >>> getKey "missed_revs" >>= toOutputType Status: __Complete__ -} missingRevs :: (FromJSON a, MonadIO m) => DocRevMap -- ^ A 'Database.Couch.Types.DocRevMap' of documents and versions available -> Context -> m (Result a) missingRevs docRevs = standardRequest request where request = do docRevBase docRevs addPath "_missing_revs" {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#post--db-_revs_diff Find document revisions not present in the database> The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value': >>> value :: Result Value <- Database.revsDiff $ DocRevMap [(DocId "junebug", [DocRev "1-1"])] ctx Status: __Complete__ -} revsDiff :: (FromJSON a, MonadIO m) => DocRevMap -- ^ A 'Database.Couch.Types.DocRevMap' of documents and versions available -> Context -> m (Result a) revsDiff docRevs = standardRequest request where request = do docRevBase docRevs addPath "_revs_diff" {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#get--db-_revs_limit Get the revision limit setting> The return value is a JSON numeric value that can easily be decoded to an 'Int': >>> value :: Result Integer <- Database.getRevsLimit ctx Status: __Complete__ -} getRevsLimit :: (FromJSON a, MonadIO m) => Context -> m (Result a) getRevsLimit = standardRequest revsLimitBase {- | <http://docs.couchdb.org/en/1.6.1/api/database/misc.html#put--db-_revs_limit Set the revision limit> Status: __Complete__ -} setRevsLimit :: (FromJSON a, MonadIO m) => Int -- ^ The value at which to set the limit -> Context -> m (Result a) setRevsLimit limit = standardRequest request where request = do setMethod "PUT" revsLimitBase setJsonBody limit -- * Internal combinators -- | Base bits for all _all_docs requests allDocsBase :: ToQueryParameters a => a -> RequestBuilder () allDocsBase param = do selectDb addPath "_all_docs" setQueryParam $ toQueryParameters param -- | Base bits for all our _compact requests compactBase :: RequestBuilder () compactBase = do setMethod "POST" selectDb addPath "_compact" -- | Base bits for our revision examination functions docRevBase :: ToJSON a => a -> RequestBuilder () docRevBase docRevs = do setMethod "POST" selectDb let parameters = toJSON docRevs setJsonBody parameters -- | Base bits for our revisions limit functions revsLimitBase :: RequestBuilder () revsLimitBase = do selectDb addPath "_revs_limit" -- | Base bits for our security functions securityBase :: RequestBuilder () securityBase = do selectDb addPath "_security"
mdorman/couch-simple
src/lib/Database/Couch/Explicit/Database.hs
mit
19,367
0
20
4,913
2,234
1,158
1,076
266
3
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, ScopedTypeVariables #-} module Main (main) where import ClassyPrelude import Network.HTTP.Types (status400) import Network.Wai (Application, responseLBS) import Network.Wai.Handler.Warp (run) import Network.Wai.Handler.WebSockets (websocketsOr) import qualified Control.Concurrent.Chan.Unagi as Unagi import qualified Data.Aeson as Aeson import qualified Network.WebSockets as Ws data Msg = Echo | Broadcast LByteString parseMsg :: LByteString -> Maybe Msg parseMsg msg = do Aeson.Object obj <- Aeson.decode msg Aeson.String typ <- lookup "type" obj case typ of "echo" -> Just Echo "broadcast" -> let res = Aeson.encode (insertMap "type" "broadcastResult" obj) in Just (Broadcast res) _ -> Nothing -- Don't flood stdout after the benchmark silentLoop :: IO () -> IO () silentLoop = handleAny (const $ pure ()) . forever wsApp :: Unagi.InChan LByteString -> Ws.ServerApp wsApp writeEnd pconn = do conn <- Ws.acceptRequest pconn readEnd <- Unagi.dupChan writeEnd void $ fork $ silentLoop (Unagi.readChan readEnd >>= Ws.sendTextData conn) silentLoop $ do msg <- Ws.receiveData conn case parseMsg msg of Nothing -> Ws.sendClose conn ("Invalid message" :: LByteString) Just Echo -> Ws.sendTextData conn msg Just (Broadcast res) -> do Unagi.writeChan writeEnd msg Ws.sendTextData conn res backupApp :: Application backupApp _ resp = resp $ responseLBS status400 [] "Not a WebSocket request" main :: IO () main = do (writeEnd, _) <- Unagi.newChan run 3000 $ websocketsOr Ws.defaultConnectionOptions (wsApp writeEnd) backupApp
palkan/websocket-shootout
haskell/warp/Main.hs
mit
1,672
0
16
317
523
264
259
42
3
{-# LANGUAGE DeriveLift #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} module Luck.Template ( mkGenQ , TProxy (..) , tProxy1 , tProxy2 , tProxy3 , Flags (..) , defFlags ) where import Common.SrcLoc (SrcLoc(..)) import Common.Types import Outer.AST import Luck.Main import Language.Haskell.TH.Syntax (Lift(..), Q, runIO) import qualified Language.Haskell.TH as TH import System.Random import Data.Data (Data) import Data.Functor.Identity import qualified Test.QuickCheck.Gen as QC import Paths_luck import qualified Data.ByteString as BS -- * Luck to Haskell -- | Import a Luck generator as a Haskell value generator at compile time. -- -- > {-# LANGUAGE TemplateHaskell #-} -- > {- - @MyType@ should be an instance of @Data@; -- > - the definitions of types involved in @MyType@ -- > should match those in the Luck program; -- > - The target predicate (i.e., the last function) should have type -- > @MyType -> Bool@. -- > -} -- > luckyGen :: QC.Gen (Maybe MyType) -- > luckyGen = $(mkGenQ defFlags{_fileName="path/to/MyLuckPrg.luck"}) tProxy1 -- -- Depending on the arity of the predicate, use 'tProxy1', 'tProxy2', 'tProxy3', -- or the 'TProxy' constructors. (The type of the 'TProxy' argument -- contains the result type of the generator.) -- -- For example, for a 4-ary predicate of type -- @A -> B -> C -> D -> Bool@, -- we can create the following generator: -- -- > luckGen :: QC.Gen (A, (B, (C, (D, ())))) -- > luckGen = $(mkGenQ defFlags{_fileName="path/to/MyLuckPrg.luck"}) -- > (TProxyS . TProxyS . TProxyS . TProxyS $ TProxy0) mkGenQ :: Flags -> Q TH.Exp mkGenQ flags = do ast <- runIO $ getOAST flags [| \proxy -> stdGenToGen (runIdentity (parse $(lift flags) $(lift ast) (Cont proxy))) |] stdGenToGen :: (StdGen -> a) -> QC.Gen a stdGenToGen f = QC.MkGen $ \qcGen _ -> f' qcGen where f' = f . mkStdGen . fst . next tProxy1 :: Data a => TProxy a tProxy1 = TProxyF (\(a, ()) -> a) (TProxyS TProxy0) tProxy2 :: (Data a, Data b) => TProxy (a, b) tProxy2 = TProxyF (\(a, (b, ())) -> (a, b)) (TProxyS . TProxyS $ TProxy0) tProxy3 :: (Data a, Data b, Data c) => TProxy (a, b, c) tProxy3 = TProxyF (\(a, (b, (c, ()))) -> (a, b, c)) (TProxyS . TProxyS . TProxyS $ TProxy0) deriving instance Lift RunMode deriving instance Lift Flags deriving instance Lift ConDecl deriving instance Lift Decl deriving instance Lift Exp deriving instance Lift TyVarId' deriving instance Lift Pat deriving instance Lift Literal deriving instance Lift Alt deriving instance Lift Op1 deriving instance Lift Op2 deriving instance Lift SrcLoc deriving instance (Lift c, Lift v) => Lift (TcType c v)
QuickChick/Luck
luck/src/Luck/Template.hs
mit
2,723
0
11
510
624
367
257
53
1
module Parse ( program , expr ) where import Control.Applicative hiding (many, (<|>)) import Data.Char import Text.ParserCombinators.Parsec import qualified PowAST as Ast -- We have many fun !! program :: Parser Ast.Program program = do funs <- many fun _ <- eof return funs fun :: Parser Ast.Fun fun = do sc <- lexeme scoping fn <- lexeme $ funName _ <- lexeme $ char '⊂' ps <- lexeme $ params _ <- lexeme $ char '⊃' bd <- lexeme compoundStatement return $ Ast.Fun fn sc ps bd scoping :: Parser Ast.Scoping scoping = (symbol "static" >> return Ast.StaticScoping) <|> (symbol "dynamic" >> return Ast.DynamicScoping) name :: Parser String name = do -- NOTE: Maybe allow name to start with numbers -- [a-zA-Z_][a-zA-Z0-9_]* first <- satisfy (orUnderscore isAlpha) rest <- many $ satisfy (orUnderscore isAlphaNum) return $ [first] ++ rest funName :: Parser Ast.FunName funName = name lexeme :: Parser a -> Parser a lexeme parser = parser <* spaces symbol :: String -> Parser String symbol = lexeme . string params :: Parser [Ast.Param] params = sepByCommas identifier arguments :: Parser Ast.Args arguments = sepByCommas expr sepByCommas :: Parser a -> Parser [a] sepByCommas = (flip sepBy) (symbol ",") identifier :: Parser Ast.Id identifier = lexeme $ do _ <- char '~' id <- name return id statement :: Parser Ast.Statement statement = try statement' <|> conditional <|> loop where statement' = do e <- expr _ <- symbol ":" return e parens :: Parser a -> Parser a parens p = symbol "(" *> p <* symbol ")" expr :: Parser Ast.Expr expr = giveback <|> write <|> conditional <|> loop <|> binOpChain where binOpChain = assignment assignment = chainr1 equal (symbol "←" >> return Ast.Assign) equal = chainl1 notEqual (symbol "=" >> return Ast.Equal) notEqual = chainl1 lessgreater (symbol "≠" >> return Ast.NotEqual) lessgreater = chainl1 strConcat binOp where binOp = (try $ (symbol ">=" <|> symbol "≥") >> return Ast.GreaterEq) <|> (try $ (symbol "<=" <|> symbol "≤") >> return Ast.LessEq) <|> (symbol "<" >> return Ast.Less) <|> (symbol ">" >> return Ast.Greater) strConcat = chainl1 plusminus binOp where binOp = symbol "↔" >> return Ast.StrConcat plusminus = chainl1 timesdivide binOp where binOp = (symbol "+" >> return Ast.Plus) <|> (symbol "-" >> return Ast.Minus) timesdivide = chainl1 parseRealThing binOp where binOp = (symbol "*" >> return Ast.Times) <|> (symbol "/" >> return Ast.Divide) parseRealThing = try arrayIndex <|> (parens expr) <|> arrayLit <|> numbers <|> trool <|> string <|> variable <|> call trool = (symbol "⊥" >> return (Ast.TroolLit Ast.No)) <|> (symbol "⊤" >> return (Ast.TroolLit Ast.Yes)) <|> (symbol "⟛" >> return (Ast.TroolLit Ast.CouldHappen)) -- TODO: Add escaping?! string = do char '|' s <- many $ noneOf "|" symbol "|" return $ Ast.StrLit s arrayIndex = do ns <- numbers e <- parens expr return $ Ast.ArrayIndex ns e arrayLit = do symbol "#" exprs <- sepByCommas expr return $ Ast.ArrayLit exprs write = do symbol "✎" e <- expr return $ Ast.Write e variable = do id <- identifier return $ Ast.Var id numbers = do ns <- lexeme $ many1 digit return $ Ast.IntLit (read ns) giveback = do _ <- symbol "giveback" <|> symbol "↜" expr' <- expr return $ Ast.GiveBack expr' call = do symbol "⊂" args <- arguments symbol "⊃" symbol "↝" funName <- lexeme name return $ Ast.Call args funName loop :: Parser Ast.Expr loop = do symbol "⟳" condition <- expr symbol "?" body <- compoundStatement return $ Ast.While condition body -- TODO: Make this less ugly! conditional :: Parser Ast.Expr conditional = try conditionalWithElse <|> conditionalWithoutElse where conditionalWithoutElse = do symbol "¿" condition <- expr symbol "?" thenBranch <- compoundStatement return $ Ast.If condition thenBranch [] conditionalWithElse = do symbol "¿" condition <- expr symbol "?" thenBranch <- compoundStatement symbol "!" elseBranch <- compoundStatement return $ Ast.If condition thenBranch elseBranch compoundStatement :: Parser [Ast.Statement] compoundStatement = do symbol "/" body <- many statement symbol "\\" return body orUnderscore :: (Char -> Bool) -> Char -> Bool orUnderscore f c = f c || c == '_'
rloewe/petulant-octo-wallhack
Parse.hs
mit
4,931
0
17
1,464
1,636
776
860
156
1
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-} {- -} module Main ( main ) where {- Standard Library Modules Imported -} import qualified Control.Monad.Trans as Monad.Trans import Data.Char ( isSpace ) import qualified Data.Maybe as Maybe import Data.Maybe ( mapMaybe , isJust ) import System.FilePath ( combine ) import Text.XHtml ( (<<) , (!) , (+++) , Html , HTML ( .. ) , HtmlAttr , strAttr ) import qualified Text.XHtml as Xhtml {- External Library Modules Imported -} import Network.CGI ( CGI , CGIResult , getInput ) import qualified Network.CGI as Cgi {- Local Modules Imported -} import qualified Ipc.Cli as Cli import Ipc.Ipc ( CliOptions , StateResult , getStatesSpaceResult , getStatesSizeReport , getPassageTimeResult , getPassageEndResult , getSteadyResult ) import Ipc.DrawGraph ( plotSimpleGraphPNG , makeSimpleGraph , SimpleLine ( .. ) ) import Language.Pepa.Syntax ( ParsedModel ) import qualified Language.Pepa.FileParser as FileParser import Language.Pepa.MainControl ( MainControl , closeMainControlWith ) import Language.Pepa.Compile.GenMatrix ( SteadyState , showSteadyResults ) import Language.Pepa.Compile.Uniformise ( PassageResult , PassageEndResult , pdfResult , cdfResult , formatCsvPassageResultCdf , formatCsvPassageResultPdf ) {- End of Imports -} {- The main program is pretty simple we just run the CGI action. -} main :: IO () main = Cgi.runCGI $ Cgi.handleErrors cgiMain {- To be able to produce graphs which we can then display in the output webpage we require that our main function, that is the one which creates the page be in the IO monad. -} cgiMain :: CGI CGIResult cgiMain = do visitInfo <- getAnalysisData page <- Monad.Trans.liftIO $ createPage visitInfo Cgi.output $ Xhtml.renderHtml page {- We are in the IO monad here to allow us to create files, mostly graphs, which can be incorporated into the results page. Obviously this big failure in this code so far is that we just 'error' on parse errors in the fields (which are turned into input options), so this needs a bit of a refactor. There are two ways to achieve this, either we just turn all the fields into a list of strings and call the main function of IPC which will interpret those strings as command-line options (and return an error in the 'MainControl' monad if there are parse errors). OR we allow this function to create an error page if there are any parse errors. Or a third option, perhaps we do both, that is call 'toCliIpc' to get the command-line options but then still process them on our own. -} createPage :: Visit -> IO Html createPage FirstVisit = -- FirstVisit, this means the user comes without any arguments -- so we return the default page. return $ makePepaPage demoPageTitle startingInputForm createPage (ExampleVisit formInfo) = -- The user has clicked on an example return $ makePepaPage demoPageTitle inputForm where inputForm = generalInputForm Nothing formInfo createPage (ReRunVisit modelString formInfo) = -- The user has run an analysis and pressed the "Start Again" -- button. So we should set up the input form to repeat the -- analysis because most likely they only want to make a small -- modification. return $ makePepaPage demoPageTitle inputForm where inputForm = generalInputForm (Just modelString) formInfo createPage (ResultVisit modelString formInfo) = -- Okay we are go, this is a result generating visit, this means -- the user has clicked on the 'Submit' button case Cli.toCli "0.1" "ipcweb" Cli.baseCliOptions allArgs of (Cli.CliValid options _) -> do results <- generatePage options modelString formInfo return $ makePepaPage resultsPageTitle results -- There was an error in processing the command-line arguments -- since we build up the command-line arguments this probably means -- the user has a parse error in some field, for example a syntax-error -- in a probe definition (Cli.CliError _ _ errorString) -> return $ makePepaPage resultsPageTitle $ generateErrorPage modelString formInfo errorString -- This actually should never happen since 'CliInfo' is only returned -- if @--version@ or @--help@ is supplied which it shouldn't be. (Cli.CliInfo _ _ infoString) -> return $ makePepaPage resultsPageTitle $ generateResultsPage modelString formInfo (toHtml infoString) where -- The generation of the results page depends upon the kind of analysis generatePage = case analysisKind of AkSteady -> generateSteadyResultsPage AkPassage -> generatePassageResultsPage AkPassageEnd -> generatePassageEndResultsPage AkStatesSize -> generateStatesResultPage AkTransient -> generateTransientResultsPage analysisKind = fiAnalysisKind formInfo -- This represents all the command-line arguments which will be interpreted -- by the same routines as in the ipc command-line compiler. We do this so -- that we have the parsing of the option arguments (such as the argument -- to a --probe option) without re-doing all of that work here. -- Instead what we do is build up a string list which would be the -- the same as that returned by 'System.Environment.getArgs' allArgs = concat [ defaultOpts , normaliseOpts , probeOptions , startActOpts , stopActOpts , startTimeOpts , stopTimeOpts , timeStepOpts , lineWidthOpts ] -- The default options are things which we wish to be true for all -- analyses initiated from the web interface. defaultOpts = [ "--limit", "1000" ] normaliseOpts = if fiNormalise formInfo then [] else [ "--no-normalise" ] probeOptions = mkOption "--probe" $ fiProbeDef formInfo startActOpts = mkOption "--source" $ fiStartActs formInfo stopActOpts = mkOption "--target" $ fiStopActs formInfo startTimeOpts = mkOption "--start-time" $ fiStartTime formInfo stopTimeOpts = mkOption "--stop-time" $ fiStopTime formInfo timeStepOpts = mkOption "--time-step" $ fiTimeStep formInfo lineWidthOpts = mkOption "--line-width" $ fiLineWidth formInfo -- Most of the options take an argument this is a utility to turn -- a maybe string into an option string pair. So if, for example -- the probe field is non empty and filled with @probe-string@ -- then we turn it into the list -- @[ "--probe", probe-string ]@ mkOption :: String -> Maybe String -> [ String ] mkOption _ Nothing = [] mkOption s (Just a) | all isSpace a = [] | otherwise = [ s, a ] {- The 'Visit' data structure holds information obtained from the cgi form about the state of the user's session. Either the user is first visiting the form, or they have input data and now wish to obtain results. Or they have already obtained results and wish to return to the start, however in this case we can at least fill out the fields with their original query since most users will make a similar query the next time. -} data Visit = FirstVisit | ExampleVisit FormInfo | ReRunVisit String FormInfo | ResultVisit String FormInfo -- The structure for storing the data that should be -- given by the user, that is the data from the input form. data FormInfo = FormInfo { fiProbeDef :: Maybe String , fiExampleName :: Maybe String , fiStartActs :: Maybe String , fiStopActs :: Maybe String , fiStartTime :: Maybe String , fiStopTime :: Maybe String , fiTimeStep :: Maybe String , fiAnalysisKind :: AnalysisKind , fiNormalise :: Bool , fiLineWidth :: Maybe String } -- This should probably be specified somewhere in the command-line options data AnalysisKind = AkPassage | AkPassageEnd | AkSteady | AkTransient | AkStatesSize -- The cgi action to collect the inputs from the form defined by -- 'startingInputForm' getAnalysisData :: CGI Visit getAnalysisData = do mmodel <- getInputString inputPepaModel moldmodel <- getInputString inputOldPepaModel mexample <- getInputString inputExampleName mprobe <- getInputString inputProbeDefinition manalysis <- getInputString inputAnalysisKind mnormalise <- getInputString inputNormalise mlineWidth <- getInputString inputLineWidth mstarts <- getInputString inputStartActions mstops <- getInputString inputStopActions mstarttime <- getInputString inputStartTime mstoptime <- getInputString inputStopTime mtimestep <- getInputString inputTimeStep let formInfo = FormInfo { fiProbeDef = mprobe , fiExampleName = mexample , fiAnalysisKind = parseMAnalysis manalysis , fiStartActs = mstarts , fiStopActs = mstops , fiStartTime = mstarttime , fiStopTime = mstoptime , fiTimeStep = mtimestep , fiNormalise = isJust mnormalise , fiLineWidth = mlineWidth } return $ createVisit formInfo mmodel moldmodel mexample where createVisit :: FormInfo -> Maybe String -> Maybe String -> Maybe String -> Visit createVisit _ Nothing Nothing Nothing = -- There is no model, no old-model and no example selected -- so this is a first time visit FirstVisit createVisit formInfo Nothing Nothing (Just _) = -- The user has clicked on an example visit ExampleVisit formInfo createVisit formInfo Nothing (Just m) _example = -- There is an old-model but no current input model -- so this is a re-run visit, we are returning to -- the input form but can fill in the previous -- values for the user to modify. ReRunVisit m formInfo createVisit formInfo (Just m) _oldmodel _example = -- Go go, this is a click on the form, a model to analyse ResultVisit m formInfo -- When we click on the input form all of the fields are supplied. -- That is all of the fields in the form are encoded into the uri. -- Even those which are the empty string. This is not what we want, -- we want an empty field to be given as 'Nothing' so this is a utility -- function which reads in a form-input and changes a (Just "") into -- Nothing. The input is the name of the field. getInputString :: String -> CGI (Maybe String) getInputString s = do res <- Cgi.getInput s case res of (Just "") -> return Nothing _ -> return res -- The analysis kind we actually parse here rather than turn into an -- ipc option. This is because we will do different things depending -- on the different kind of analysis which we are performing. parseMAnalysis :: Maybe String -> AnalysisKind parseMAnalysis = maybe AkStatesSize parseAnalysisKind {- Parse an analysis kind -} parseAnalysisKind :: String -> AnalysisKind parseAnalysisKind "steady" = AkSteady parseAnalysisKind "passage" = AkPassage parseAnalysisKind "passage-end" = AkPassageEnd parseAnalysisKind "transient" = AkTransient parseAnalysisKind "state-size" = AkStatesSize parseAnalysisKind _ = AkSteady -- hmm {- Unparse an analysis kind. It *must* be the case that @s == (unparseAnalysisKind . parseAnalysisKind) s@ This is actually currently untrue because of the last case in 'parseAnalysisKind' however it is at least true for all valid analysis-kind strings. -} unparseAnalysisKind :: AnalysisKind -> String unparseAnalysisKind AkSteady = "steady" unparseAnalysisKind AkPassage = "passage" unparseAnalysisKind AkPassageEnd = "passage-end" unparseAnalysisKind AkTransient = "transient" unparseAnalysisKind AkStatesSize = "state-size" -- All of the cgi value identifiers. inputPepaModel :: String inputPepaModel = "input-pepa-model" inputOldPepaModel :: String inputOldPepaModel = "old-pepa-model" inputExampleName :: String inputExampleName = "pepa-example-name" inputProbeDefinition :: String inputProbeDefinition = "input-probe-definition" inputStartActions :: String inputStartActions = "input-start-actions" inputStopActions :: String inputStopActions = "input-stop-actions" inputAnalysisKind :: String inputAnalysisKind = "analysis-kind" inputNormalise :: String inputNormalise = "input-normalise" inputLineWidth :: String inputLineWidth = "input-line-width" inputStartTime :: String inputStartTime = "input-start-time" inputStopTime :: String inputStopTime = "input-stop-time" inputTimeStep :: String inputTimeStep = "input-time-step" -- Example Pepa Models -- the type of a pepa example is the html which should explain the model -- together with the string representation of the model. type PepaExample = (Html, String) -- Here we are mapping the example name to an Html part and the -- model itself. The Html part will generally describe the model -- and suggest some analyses which can be done over it. examplePepaModels :: [ (String, PepaExample ) ] examplePepaModels = [ ( "simple-example" , simplePepaExample ) , ( "simple-cache-example" , cachePepaExample ) , ( "simple-aggregate-example" , simpleAggregateExample ) ] -- The simple PEPA example we define out of the list so that we can -- refer to it outside of 'Maybe' should the lookup of the example name fail simplePepaExample :: PepaExample simplePepaExample = ( Xhtml.paragraph << ("This is a very straightforward example") , unlines [ "// rate specifications" , "ra = 1.0 ;" , "rb = 2.0 ;" , "" , "// Process definitions" , "P1 = (a, 1.0) . P2 ;" , "P2 = (b, 2.0) . P1 ;" , "" , "// System Equation" , "P1 || P1" ] ) -- The simple PEPA example we define out of the list so that we can -- refer to it outside of 'Maybe' should the lookup of the example name fail cachePepaExample :: PepaExample cachePepaExample = ( Xhtml.concatHtml $ map (Xhtml.paragraph <<) [ unlines [ "This is an example of a network with a cache" , "There is a single user who can make a request" , "to a service provider. For each request the service" , "may have cached the response and can therefore reply" , "quickly. For some requests though the service must" , "query the network - such requests are expected to take" , "longer." ] , unlines [ "An example query on this model may be a passage-time" , "query between a request and response. To achieve this" , "select the \"passage\" analysis kind and enter" , "\"req\" for the start actions and \"cached,network\"" , "for the stop actions." ] ] , unlines [ "r = 1.0 ;" , "" , "User = (req, r) . Wait ;" , "Wait = (cached, infty) . User" , " + (network, infty) . User" , " ;" , "Service = (req, infty) . InCache" , " + (req, infty) . Fetch" , " ;" , "InCache = (cached, r) . Service ;" , "Fetch = (fetch, r/2) . (network, r/5) . (delay, r) . Service ;" , "" , "User <req, cached, network> Service" ] ) simpleAggregateExample :: PepaExample simpleAggregateExample = ( Xhtml.concatHtml $ map (Xhtml.paragraph <<) [ unlines [ "This is an example of a PEPA model with an" , "array of processes. We can aggregate the states" , "of the array allowing the solving of this model" , "for larger array lengths than would be possible" , "without aggregation." ] , unlines [ "One can still ask about the response-time of a" , "single client without manually splitting up the" , "array of clients." , "By providing the probe: " , "\"Client::compute:start, respond:stop\"" , "we measure the response time as observed by a" , "single client. This can then be used to analyse" , "the effect on each client's observed response time" , "that the addition of clients makes." ] ] , unlines [ "r_request = 0.5 ;" , "r_compute = 0.01 ;" , "r_respond = 1.0 ;" , "" , "Client = (compute, r_compute) . ClientReq ;" , "ClientReq = (request, r_request) . ClientWait ;" , "ClientWait = (respond, infty) . Client ;" , "" , "Server = (request, infty) . ServerResp ;" , "ServerResp = (respond, r_respond) . Server ;" , "" , "Server[2] <request, respond> Client[5]" ] ) -- If there are no inputs then this is the first page that the user will see. startingInputForm :: Html startingInputForm = generalInputForm Nothing defaultFormInfo -- The absolute default form info where essentially nothing is filled in defaultFormInfo :: FormInfo defaultFormInfo = FormInfo { fiProbeDef = Nothing , fiExampleName = Just "simple-example" , fiStartActs = Nothing , fiStopActs = Nothing , fiAnalysisKind = AkSteady , fiNormalise = False , fiStartTime = Nothing , fiStopTime = Nothing , fiTimeStep = Nothing , fiLineWidth = Nothing } -- Generates the starting input form from a given 'FormInfo'. -- If this is a first visit then the given FormInfo will be the default -- starting form info, but if this is the a return caused by hitting the -- "return to start" button after the results page then we can fill in -- the form data for the user to modify since their query will likely be -- similar to the first one. generalInputForm :: Maybe String -> FormInfo -> Html generalInputForm mModelString formInfo = mkTable [] [ mkRow [] [ formCell, examplesCell ] ] where formCell = mkCell [] [ inputForm ] examplesCell = mkCell [ Xhtml.valign "top" ] [ Xhtml.paragraph << examplesHtml ] inputForm = Xhtml.form << formElements formElements = [ explainExample , Xhtml.paragraph ("Input PEPA model: " +++ textarea) , Xhtml.paragraph (Xhtml.concatHtml analysisKinds) , Xhtml.paragraph normalise , Xhtml.paragraph probeField , Xhtml.paragraph startActionsField , Xhtml.paragraph stopActionsField , Xhtml.paragraph startTimeField , Xhtml.paragraph stopTimeField , Xhtml.paragraph timeStepField , Xhtml.paragraph lineWidthField , Xhtml.submit "" "Submit" ] -- pepaModel is the final model that we decide to put into the -- text area. It is, in decreasing order of preference -- 1) The pepa model that the user has already analysed and then -- hit the 'Start Again' button. -- 2) An example model from the list if the user has selected one -- 3) The first-time simple example, this is displayed on the user's -- first visit. pepaModel = snd pepaPair -- The explainExample is a little portion of html which will explain to -- the user about the selected example. If the model selected is actually -- the previous model then this is all it will say. explainExample = fst pepaPair -- So the pepaPair is either a pepaExample or the previous model string together -- with a small portion of html explaining that it is the previous model. pepaPair = case mModelString of Nothing -> pepaExample Just m -> ( previousParagraph, m) previousParagraph = Xhtml.paragraph << "Here is your previous model" -- So this is the pepa example that the user selected or the simplest -- pepa example if the user has not selected one. If the user has not -- selected one then the simplest example will only be used if this is -- a first time visit. pepaExample = Maybe.fromMaybe simplePepaExample $ do name <- fiExampleName formInfo lookup name examplePepaModels textarea = ( Xhtml.textarea $ toHtml pepaModel ) ! textareaAttrs textareaAttrs = [ Xhtml.name inputPepaModel , Xhtml.cols "60" , Xhtml.rows "20" ] probeField = mkTextField "A probe definition: " inputProbeDefinition (fiProbeDef formInfo) normalise = (toHtml "Normalise: " ) +++ normaliseCheck normaliseCheck = (Xhtml.checkbox inputNormalise "normalise") ! [ Xhtml.checked ] startActionsField = mkTextField "Start actions(default 'start'): " inputStartActions (fiStartActs formInfo) stopActionsField = mkTextField "Stop actions(default 'stop'): " inputStopActions (fiStopActs formInfo) startTimeField = mkTextField "Start time (default 0.0): " inputStartTime (fiStartTime formInfo) stopTimeField = mkTextField "Stop time (default 10.0): " inputStopTime (fiStopTime formInfo) timeStepField = mkTextField "Time step (default 0.1): " inputTimeStep (fiTimeStep formInfo) lineWidthField = mkTextField "Graph Line Width (default 1.0): " inputLineWidth (fiLineWidth formInfo) -- Create a text field given the label to put next to it, the form id -- string and a possible default/old value for the field. mkTextField :: String -> String -> Maybe String -> Html mkTextField label name Nothing = label +++ (Xhtml.textfield name) mkTextField label name (Just value) = label +++ ((Xhtml.textfield name) ! [ Xhtml.value value ]) analysisKinds = [ toHtml "Please select the kind of analysis" , analysisKindRadio "steady" , toHtml "steady" , analysisKindRadio "passage" , toHtml "passage" , analysisKindRadio "passage-end" , toHtml "passage-end" , analysisKindRadio "state-size" , toHtml "state-size" ] -- Create a radio button for the analysis kind, we use the name of -- the analysis kind from the given formInfo to determine whether this -- should be checked or not. Exactly one should be checked. analysisKindRadio :: String -> Html analysisKindRadio s | s == oldAnalysisString = radio ! [ Xhtml.checked ] | otherwise = radio where radio = Xhtml.radio inputAnalysisKind s -- The string of the old analysis kind, we use this to determine which -- field should be initially checked. oldAnalysisString = unparseAnalysisKind $ fiAnalysisKind formInfo -- The html displaying the list of examples the user may click on examplesHtml = mkelem "div" [ strAttr "id" "examplescontainer" ] [ examplesUlist ] -- The list of examples is an unordered list. examplesUlist = mkelem "ul" [ strAttr "id" "exampleslist" ] exampleItems -- Todo: the current item should be made up like this: -- <li id="active"> -- <a href="http://www.dcs.ed.ac.uk/pepa" id="current" name="current">Home</a></li> exampleItems = map mkExampleLink examplePepaModels -- Make an example link using the name of the example to determine both the -- url and the string to display as the link. mkExampleLink :: (String, PepaExample) -> Html mkExampleLink (name, (_html, _model)) = mkLinkListItem url name where url = concat [ demoUrl , "?" , Cgi.formEncode values ] values = [ (inputExampleName, name) ] -- A generic function to generate a results page, we take in the -- the form-info to pass back on clicking the 'start again' button. generateResultsPage :: String -> FormInfo -> Html -> Html generateResultsPage modelString formInfo results = ( Xhtml.paragraph << results ) +++ resetButton where resetButton = mkButtonLink "Start Again" url url = concat [ demoUrl , "?" , Cgi.formEncode values ] -- 'values' here is an encoding of all the 'formInput' which achieved -- these results. This means when the user clicks 'Start Again' the form -- is set up how they had it before, since often the user will want to -- perform a similar analysis with some of the fields slightly modified -- for example they may re-perform the same passage-time measurement but -- for a longer time range. values = [ ( inputOldPepaModel, modelString ) , ( inputAnalysisKind, analysisString ) ] ++ formValues analysisString = unparseAnalysisKind $ fiAnalysisKind formInfo -- Most of the form values are stored as a @Maybe String@ so we -- pair them up with their form-names and lift the maybe to the whole -- pair. We then use 'mapMaybe' to filter out the undefined ones. formValues = mapMaybe liftSnd formInputs formInputs = [ (inputProbeDefinition, fiProbeDef formInfo) , (inputStartActions, fiStartActs formInfo) , (inputStopActions, fiStopActs formInfo) , (inputStartTime, fiStartTime formInfo) , (inputStopTime, fiStopTime formInfo) , (inputTimeStep, fiTimeStep formInfo) , (inputLineWidth, fiLineWidth formInfo) ] -- Utility function to lift the 'Maybe' from the second value of a -- pair to the whole pair, potentially throwing away the first value. liftSnd :: (a, Maybe b) -> Maybe (a, b) liftSnd (_, Nothing) = Nothing liftSnd (a, Just b) = Just (a,b) -- A generic function to generate an error page with a 'start-again' -- button which passes back the form info passed in. generateErrorPage :: String -> FormInfo -> String -> Html generateErrorPage modelString formInfo = (generateResultsPage modelString formInfo ) . toHtml -- A function all of the below page generators can use to parse in -- the PEPA model. parsePepaFile :: String -> MainControl ParsedModel parsePepaFile = FileParser.mainControlParse FileParser.pepaFile {-| Generate the results pages for a state-space size query. -} generateStatesResultPage :: CliOptions a -> String -> FormInfo -> IO Html generateStatesResultPage options modelString formInfo = return $ generateResultsPage modelString formInfo results where results = closeMainControlWith displayResults displayError spaceResult spaceResult = parseResult >>= getStatesSpaceResult options parseResult = parsePepaFile modelString displayResults :: StateResult -> Html displayResults = toHtml . getStatesSizeReport {-| Generate the results page for a passage-time query. -} generatePassageResultsPage :: CliOptions a -> String -> FormInfo -> IO Html generatePassageResultsPage [] modelString formInfo = return errorPage where errorPage = generateErrorPage modelString formInfo errorString errorString = unlines [ "You have asked for a passage-time analysis" , "however you have not supplied a probe" , "or specified start/stop actions to" , "define the source and target states" ] generatePassageResultsPage options modelString formInfo = -- The closing of the 'MainControl' must live within the IO monad -- because, in the case that there are results to show we write -- out the graph files. do results <- closeMainControlWith displayResults (return . displayError) passageResult -- Finally generate the results page return $ generateResultsPage modelString formInfo results where -- Analyse the model obtaining the passage-time results. This lives -- in the 'MainControl' monad because we may still cause an error -- at this point, for example if the set of source states is empty. passageResult = parseResult >>= getPassageTimeResult options -- Parse the PEPA model parseResult = parsePepaFile modelString -- The width of lines in the graphs lineWidth = Cli.getGraphLineWidth options -- Display the results of the passage-time analysis -- This involves writing out graph files and creating image elements -- to those graph files. The writing out of the graph files is the -- reason that this must live in the IO monad. displayResults :: PassageResult -> IO Html displayResults pt = do plotSimpleGraphPNG pdfGraph pdfGraphFile plotSimpleGraphPNG cdfGraph cdfGraphFile -- Generate csv files and links to those files fileLinksUrl <- linkPassageCsvFileList [ ("main", pt) ] return $ graphHtml +++ fileLinksUrl where pdfGraph = makeSimpleGraph pdfGraphTitle [] pdfGraphLines cdfGraph = makeSimpleGraph cdfGraphTitle [] cdfGraphLines graphHtml = Xhtml.concatHtml [ pdfGraphHtml , cdfGraphHtml ] pdfGraphHtml = Xhtml.paragraph << pdfImage pdfImage = mkelem "img" pdfAttributes [] pdfAttributes = [ strAttr "src" pdfGraphUrl , strAttr "alt" "PDF GRAPH" ] -- At least the directory of this should be abstracted away somewhere pdfGraphUrl = generatedFilesUrl "pdf.png" pdfGraphFile = generatedFilesDir "pdf.png" pdfGraphTitle = Just "Probability density function graph" pdfGraphLines = [ SimpleLine { simpleLineTitle = Just "pdf" , simpleLinePoints = pdfResult pt , simpleLineWidth = lineWidth } ] cdfGraphHtml = Xhtml.paragraph << cdfImage cdfImage = mkelem "img" cdfAttributes [] cdfAttributes = [ strAttr "src" cdfGraphUrl , strAttr "alt" "PDF GRAPH" ] -- At least the directory of this should be abstracted away somewhere cdfGraphUrl = generatedFilesUrl "cdf.png" cdfGraphFile = generatedFilesDir "cdf.png" cdfGraphTitle = Just "Cumulative distribution function graph" cdfGraphLines = [ SimpleLine { simpleLineTitle = Just "cdf" , simpleLinePoints = cdfResult pt , simpleLineWidth = lineWidth } ] {-| Passage-end results are still a fairly new feature of ipc in general let alone ipcweb. This function returns the passage-end result from the given model or as usual may instead display an error. -} generatePassageEndResultsPage :: CliOptions a -> String -> FormInfo -> IO Html generatePassageEndResultsPage [] modelString formInfo = return $ generateErrorPage modelString formInfo $ unlines [ "You have asked for a passage-time analysis" , "however you have not supplied a probe" , "or specified start/stop actions to" , "define the source and target states" ] generatePassageEndResultsPage options modelString formInfo = -- The closing of the 'MainControl' must live within the IO monad -- because, in the case that there are results to show we write -- out the graph files. do results <- closeMainControlWith displayResults (return . displayError) passEndResult -- Finally generate the results page return $ generateResultsPage modelString formInfo results where -- Generate the passage-end results from the parsed model, done inside -- the 'MainControl' monad as we may still encounter an error even -- after the static analysis of the model. passEndResult = parseResult >>= getPassageEndResult options -- Parse the PEPA model parseResult = parsePepaFile modelString -- The width of lines in the graphs lineWidth = Cli.getGraphLineWidth options -- We must write out two graphs, this is why this lives in the -- IO monad. displayResults :: PassageEndResult -> IO Html displayResults per = do plotSimpleGraphPNG pdfGraph pdfGraphFile plotSimpleGraphPNG cdfGraph cdfGraphFile -- generate individual csv files and links to those files fileLinksHtml <- linkPassageCsvFileList per return $ graphHtml +++ fileLinksHtml where pdfGraph = makeSimpleGraph pdfGraphTitle [] pdfGraphLines cdfGraph = makeSimpleGraph cdfGraphTitle [] cdfGraphLines graphHtml = Xhtml.concatHtml [ pdfGraphHtml , cdfGraphHtml ] pdfGraphHtml = Xhtml.paragraph << pdfImage pdfImage = mkelem "img" pdfAttributes [] pdfAttributes = [ strAttr "src" pdfGraphUrl , strAttr "alt" "PDF GRAPH" ] pdfGraphUrl = generatedFilesUrl "pdf.png" pdfGraphFile = generatedFilesDir "pdf.png" pdfGraphTitle = Just "Probability density function graph" pdfGraphLines = map mkPdfLine per mkPdfLine :: (String, PassageResult) -> SimpleLine mkPdfLine (name, passageResult) = SimpleLine { simpleLineTitle = Just ("pdf-" ++ name) , simpleLinePoints = pdfResult passageResult , simpleLineWidth = lineWidth } cdfGraphHtml = Xhtml.paragraph << cdfImage cdfImage = mkelem "img" cdfAttributes [] cdfAttributes = [ strAttr "src" cdfGraphUrl , strAttr "alt" "PDF GRAPH" ] cdfGraphUrl = generatedFilesUrl "cdf.png" cdfGraphFile = generatedFilesDir "cdf.png" cdfGraphTitle = Just "Cumulative distribution function graph" cdfGraphLines = map makeCdfLine per makeCdfLine :: (String, PassageResult) -> SimpleLine makeCdfLine (name, passageResult) = SimpleLine { simpleLineTitle = Just ("cdf-" ++ name) , simpleLinePoints = cdfResult passageResult , simpleLineWidth = lineWidth } {- Displays a set of passage time results as a list of links to comma-separated value files. What would be much neater is instead of writing out the file eagerly produce a link that when pressed calls this cgi script with arguments such that it generates the file and allows you to download it. Though maybe that's not much better since the data would have to be somehow inbedded into the return webpage such that the link could generate the file but still. -} linkPassageCsvFileList :: [(String, PassageResult)] -> IO Html linkPassageCsvFileList results = do fileLinkItems <- mapM linkPassageCsvFiles results return $ makeListHtml $ concat fileLinkItems where makeListHtml :: [ Html ] -> Html makeListHtml fileLinks = mkParagraph [ toHtml fileDesc, mkelem "ul" [] fileLinks ] fileDesc = unlines [ "These are links to the individual" , "comma-separated-value files which can be" , "used to re-create the graphs above" ] {- Displays passage-time results as links to comma-separated files which this function also writes out. This returns a list of html items which are *list items* hence you must wrap the returned html items in a list. This allows you to link to multiple passage results in the same list (as is done for passage-end calculations). -} linkPassageCsvFiles :: (String, PassageResult) -> IO [ Html ] linkPassageCsvFiles (name, pt) = do writeFile pdfFile pdfLines writeFile cdfFile cdfLines return fileLinks where fileLinks = [ mkLinkListItem pdfUrl pdfName , mkLinkListItem cdfUrl cdfName ] pdfUrl = generatedFilesUrl pdfName pdfFile = generatedFilesDir pdfName pdfName = name ++ "-pdf.csv" pdfLines = formatCsvPassageResultPdf pt cdfUrl = generatedFilesUrl cdfName cdfFile = generatedFilesDir cdfName cdfName = name ++ "-cdf.csv" cdfLines = formatCsvPassageResultCdf pt -- Given a file name create a filename for the default location -- of generated files. generatedFilesDir :: FilePath -> FilePath generatedFilesDir = combine "/public/homepages/aclark6/web/generated_graphs/" -- Given a file name create a url for the default location of -- generated files. generatedFilesUrl :: String -> String generatedFilesUrl name = "http://homepages.inf.ed.ac.uk/aclark6/generated_graphs/" ++ name {-| Generate the page for the steady state results. -} generateSteadyResultsPage :: CliOptions a -> String -> FormInfo -> IO Html generateSteadyResultsPage options modelString formInfo = return $ generateResultsPage modelString formInfo results where -- Obtain from the 'MainControl' structure the steady-state results -- or of course the error if there were any. results = closeMainControlWith displayResults displayError steadyResult -- Run steady-state analysis over the parsed model, this is done inside -- the 'MainControl' monad as it may fail. steadyResult = parseResult >>= getSteadyResult options -- Parse the PEPA model into the 'MainControl' monad. parseResult = parsePepaFile modelString -- The function to display the steady state results if there -- are any (that is if we have not made an error. displayResults :: SteadyState -> Html displayResults steadystate = (Xhtml.paragraph << (Xhtml.linesToHtml reportLines) ) where reportLines = lines $ showSteadyResults steadystate {-| A common function to display an error from the 'MainControl' monad in html. This is called if the analysis fails to produce results for the user to view. -} displayError :: String -> Html displayError = toHtml {-| Generate the web-page for transient analysis of the given model. -} generateTransientResultsPage :: CliOptions a -> String -> FormInfo -> IO Html generateTransientResultsPage _options modelString formInfo = return $ generateResultsPage modelString formInfo results where results = toHtml errString errString = "We are sorry transient analysis is not yet implemented" {-| The base url of the demo. -} demoUrl :: String demoUrl = "http://homepages.inf.ed.ac.uk/cgi/aclark6/ipcweb.cgi" {-| The title of the start page of the demo. -} demoPageTitle :: String demoPageTitle = "International PEPA Compiler Web Demo" {-| The title of a results page -} resultsPageTitle :: String resultsPageTitle = demoPageTitle ++ " - Results" -- The main ipc web page stored as an xml arrow makePepaPage :: String -> Html -> Html makePepaPage titleString body = mkelem "html" [] [ mkelem "head" [] headElements , mkelem "body" [ strAttr "class" "PEPA" , strAttr "bgcolor" "#FFFFFF" , strAttr "link" "#FF0000" , strAttr "vlink" "#FF0000" , strAttr "alink" "#FF0000" ] [ heading, bodyAndNav ] ] where -- The main body of the page is together with the navigation list -- as table with one row and two cells within that row. bodyAndNav = mkTable [] [ mkRow [] [ navCell, bodyCell ] ] navCell = mkCell [ Xhtml.valign "top" ] [ navigation ] bodyCell = mkCell [] [ body ] -- The navigation list that should normally appear on the left of the -- page. navigation = mkelem "div" [ strAttr "id" "navcontainer" ] [ navList ] navList = mkelem "ul" [ strAttr "id" "navlist" ] navItems -- Todo: the current item should be made up like this: -- <li id="active"> -- <a href="http://www.dcs.ed.ac.uk/pepa" id="current" name="current">Home</a></li> navItems = [ pepaHomeItem "" "PEPA home" , pepaHomeItem "news" "PEPA news" , pepaHomeItem "about" "About PEPA" , pepaHomeItem "people" "People" , pepaHomeItem "papers" "Papers" , pepaHomeItem "tools" "Tools" , pepaHomeItem "examples" "Examples" , pepaClubItem "talks.html" "PEPA-Club" ] -- Creates a navigation list item assuming that the base url is that -- of the main PEPA home page. pepaHomeItem :: String -> String -> Html pepaHomeItem url = mkLinkListItem (pepaHomeUrl ++ url) -- Creates a navigation list item assuming that the base url is that -- of the PEPA-club home page. pepaClubItem :: String -> String -> Html pepaClubItem url = mkLinkListItem (pepaClubUrl ++ url) -- The base urls for the PEPA home and PEPA club sites. pepaHomeUrl = "http://www.dcs.ed.ac.uk/pepa/" pepaClubUrl = "http://homepages.inf.ed.ac.uk/aclark6/pepaclub/" headElements = [ mkelem "title" [] [ toHtml titleString ] , mkelem "meta" [ strAttr "http-equiv" "Content-Type" , strAttr "content" "text/html; charset=us-ascii" ] [] , mkelem "link" [ strAttr "rel" "SHORTCUT ICON" , strAttr "href""http://www.dcs.ed.ac.uk/pepa/favicon3.ico" ] [] , mkelem "link" [ strAttr "rel" "stylesheet" , strAttr "type" "text/css" , strAttr "href" cssUrl ] [] , mkelem "link" [ strAttr "rel" "alternate" , strAttr "type" "application/rss+xml" , strAttr "href" rssUrl , strAttr "title" "PEPA RSS feed" ] [] ] cssUrl = "http://www.dcs.ed.ac.uk/pepa/pepa.css" rssUrl = "http://www.dcs.ed.ac.uk/pepa/news/feed.rss" heading = {-Xhtml.center-} headingTable headingTable = mkTable [ strAttr "align" "center" , strAttr "width" "100%" , strAttr "cellpadding" "8" , strAttr "summary" "banner" ] [ mkRow [] [ mkCell [] [ pepaLogoSmall ] , mkCell [] [ titleTable ] , mkCell [] [ pepaLogoSmall ] ] ] titleTable = mkTable [ strAttr "align" "center" , strAttr "width" "100%" , strAttr "summary" perfEvalProAlg ] [ titleTableRow1, titleTableRow2 ] perfEvalProAlg = "Performance Evaluation Process Algebra" titleTableRow1 = mkRow [ strAttr "align" "center" ] [ mkCell [] [ pepa ] ] titleTableRow2 = mkRow [ strAttr "align" "center" ] [ mkCell [] [ h1Title ] ] h1Title = mkH1 [mkItalics [mkFontifiedText "#FF0000" "4" titleText]] titleText = "International PEPA Compiler - Web Demo" pepa = mkFontifiedText "#FF0000" "6" "PEPA" -------- -- | The small pepa logo as an html element. pepaLogoSmall :: Html pepaLogoSmall = mkelem "img" attributes [] where attributes = [ strAttr "src" "http://www.dcs.ed.ac.uk/pepa/pepasmall.gif" , strAttr "width" "43" , strAttr "height" "28" , strAttr "alt" "PEPA" ] ----- Utility functions for generating the web pages -- | 'mkelem' a convenient way to make an arbitrary tagged -- element with a given set of attributes. mkelem :: String -> [ HtmlAttr ] -> [ Html ] -> Html mkelem s attrs elems = ( Xhtml.tag s $ Xhtml.concatHtml elems ) ! attrs -- | Creates a paragraph element mkParagraph :: [ Html ] -> Html mkParagraph = mkelem "p" [] -- | Create a table element, the rows are up to the user to -- provide in the contents of the element. mkTable :: [ HtmlAttr ] -> [ Html ] -> Html mkTable = mkelem "table" -- | Creates a row element, the cells are up to the user to -- provide as the content of the row element. mkRow :: [ HtmlAttr ] -> [ Html ] -> Html mkRow = mkelem "tr" -- | Creates a cell element mkCell :: [ HtmlAttr ] -> [ Html ] -> Html mkCell = mkelem "td" -- | Creates an italics element mkItalics :: [ Html ] -> Html mkItalics = mkelem "i" [] -- | A convenient synonym for creating some text in given colour -- and font size. mkFontifiedText :: String -> String -> String -> Html mkFontifiedText colour size text = mkFont [ strAttr "color" colour , strAttr "size" size ] [ toHtml text ] -- | Creates a font element. mkFont :: [ HtmlAttr ] -> [ Html ] -> Html mkFont = mkelem "font" -- | Creates a header1 element mkH1 :: [ Html ] -> Html mkH1 = mkelem "h1" [] -- | Creates a link with the given url as the target. -- The contents can be any html. mkLink :: String -> [ Html ] -> Html mkLink url = mkelem "a" [ strAttr "href" url ] -- | Often we wish to make a list of links, this provides an easy -- way to make such a list item given the url and the name which -- should be displayed as the link. mkLinkListItem :: String -> String -> Html mkLinkListItem url name = mkelem "li" [] [ mkLink url [ toHtml name ] ] -- | Create a button whose target is the given url. mkButtonLink :: String -> String -> Html mkButtonLink text url = mkLink url [ mkelem "button" [] [ toHtml text ] ]
allanderek/ipclib
web/interface/IpcWeb.hs
gpl-2.0
47,248
0
13
14,152
6,462
3,528
2,934
679
9
{-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} import Control.Monad.Free import System.IO ---------- type Name = String data DialogueF a where AskName :: String -> (Name -> a) -> DialogueF a SayHello :: String -> (() -> a) -> DialogueF a instance Functor DialogueF where fmap f = \case AskName s g -> AskName s (f . g) SayHello s g -> SayHello s (f . g) type Dialogue = Free DialogueF askName :: String -> Dialogue String askName s = liftF $ AskName s id sayHello :: String -> Dialogue () sayHello s = liftF $ SayHello s id ---------- myDialogue :: Dialogue () myDialogue = do xs <- askName "What is your name? " if (null xs) then return () else do sayHello $ "Hello, " ++ xs ++ ".\n" myDialogue ---------- evalDialogue :: Dialogue a -> IO a evalDialogue = \case Pure x -> return x -- x :: a Free y -> case y of -- y :: DialogueF (Dialogue a) AskName s g -> do -- g :: String -> Dialogue a putStr $ s hFlush stdout l <- getLine evalDialogue (g l) SayHello s g -> do -- g :: () -> Dialogue a putStr $ s hFlush stdout evalDialogue (g ()) ---------- main :: IO () main = do evalDialogue myDialogue ----------
artuuge/free-running
helloFree.hs
gpl-2.0
1,231
0
16
340
429
213
216
41
3
-- This file is part of KSQuant2. -- Copyright (c) 2010 - 2011, Kilian Sprotte. All rights reserved. -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE FlexibleContexts #-} module Main (main) where import qualified Types as T (Err , DivChoicesSeq , BestDivsSeq , QuantGrid ) import qualified Options as O (Options(..), PureMain) import qualified Utils as U (stickToLast , repeatList , rationalPairToTimePair , appendNewline) import IOHandler (handleIO) import MainUtils ( unwrapLeft , getSimple , measureStream' , measuresUntilTime , addInlineOptions , scoreToLily , scoreToEnp , scoreToDurs) import qualified Interval as Iv (ascendingIntervals , ascendingIntervals2points , groupPointsByIntervalls , getAscendingIntervals) import qualified Measure as M (Ms , measuresLeafIntervals , measuresDivideLeafs , measuresTieOrRest , E(L,R,D) , measuresTransformLeafs , measureNumLeaf , Score) import qualified Lisp as L (LispVal() , fromSexp , toSexp , mapcar' , parseLisp) import DursInput (dursInputToSFScore) import qualified SimpleFormat as SF (Score, sexp2event) import qualified SimpleFormat2 as SF2 (Events , qeventFromEvent , qeventNotes , qeventExpressions , Score , scoreEnd , voiceToSimpleFormat2 , withoutEndMarker , QEvents) import qualified AbstractScore as A (Score) import qualified Quantize as Qu (bestDiv, quantizeIv) import AdjoinTies (adjoinTies) import MeasureSiblingMerge (measureSiblingMerge) import Data.List ((\\)) type Parser = String -> T.Err ParseResult type Processor = ParseResult -> T.Err M.Score type Filter = M.Score -> T.Err M.Score type Formatter = M.Score -> T.Err String data ParseResult = SFInput L.LispVal | DursInput L.LispVal getProcessor :: O.Options -> Processor getProcessor opts (SFInput parseResult) = do simple <- getSimple parseResult :: T.Err L.LispVal let sf_score = simple2sf_score simple :: SF.Score opts' <- addInlineOptions opts parseResult process_sf_score opts' sf_score getProcessor opts (DursInput parseResult) = do let sf_score = dursInputToSFScore parseResult process_sf_score opts sf_score getParser :: O.Options -> T.Err Parser getParser O.Options { O.optInputFormat = "sf" } = Right parseAsSFInput getParser O.Options { O.optInputFormat = "durs" } = Right parseAsDursInput getParser O.Options { O.optInputFormat = f } = Left $ "unknown input format " ++ f getFilter :: O.Options -> T.Err Filter getFilter O.Options { O.optMeasureSiblingMerge = True } = Right (Right . fmap (map measureSiblingMerge)) getFilter _ = Right Right getFormatter :: O.Options -> T.Err Formatter getFormatter O.Options { O.optOutputFormat = "enp" } = Right (Right . U.appendNewline . scoreToEnp) getFormatter O.Options { O.optOutputFormat = "ly" } = Right (Right . U.appendNewline . scoreToLily) getFormatter O.Options { O.optOutputFormat = "durs" } = Right (Right . U.appendNewline . scoreToDurs) getFormatter O.Options { O.optOutputFormat = f } = Left $ "unknown output format " ++ f parseAsSFInput :: Parser parseAsSFInput input = do forms <- L.parseLisp input let (first_form:_) = forms return $ SFInput first_form parseAsDursInput :: Parser parseAsDursInput input = do forms <- L.parseLisp input return $ DursInput (L.toSexp forms) computeBestDivs :: M.Ms -> T.DivChoicesSeq -> SF2.Events -> T.BestDivsSeq computeBestDivs measures divChoicesSeq input = let input' = Iv.ascendingIntervals input beats_intervals = Iv.ascendingIntervals (map U.rationalPairToTimePair (M.measuresLeafIntervals measures)) beats_intervals' = Iv.getAscendingIntervals beats_intervals points = Iv.ascendingIntervals2points input' groups = Iv.groupPointsByIntervalls beats_intervals points in zipWith3 Qu.bestDiv divChoicesSeq beats_intervals' groups computeQEvents :: T.QuantGrid -> SF2.Events -> SF2.QEvents computeQEvents quant_grid input = let quant_grid' = Iv.ascendingIntervals (map U.rationalPairToTimePair quant_grid) quant_grid_asc = Iv.ascendingIntervals quant_grid in map (Qu.quantizeIv SF2.qeventFromEvent quant_grid_asc quant_grid') input quantifyVoice :: M.Ms -> T.DivChoicesSeq -> SF2.Events -> M.Ms quantifyVoice measures divChoicesSeq voice = let getNotes (M.L dur tie label _ _) qevent = M.L dur tie label (SF2.qeventNotes qevent) (SF2.qeventExpressions qevent) getNotes (M.R _ _) _ = error "getNotes: R" getNotes M.D{} _ = error "getNotes: D" measuresTieOrRest' a b m = M.measuresTieOrRest m a b measuresTransformLeafs' a b c m = M.measuresTransformLeafs a m b c in let input = SF2.withoutEndMarker voice bestDivs = computeBestDivs measures divChoicesSeq input measures' = M.measuresDivideLeafs measures (map toInteger bestDivs) quant_grid = M.measuresLeafIntervals measures' qevents = computeQEvents quant_grid input transformMeasures = (map adjoinTies . measuresTransformLeafs' getNotes qevents quant_grid . measuresTieOrRest' qevents quant_grid) in transformMeasures measures' quantifyVoiceOrErr :: M.Ms -> T.DivChoicesSeq -> SF2.Events -> T.Err M.Ms quantifyVoiceOrErr measures divChoicesSeq voice = Right (quantifyVoice measures divChoicesSeq voice) mkTrans :: O.Options -> SF2.Score -> T.Err (SF2.Score -> A.Score (T.Err M.Ms)) mkTrans opts sf2 = do let O.Options { O.optMaxDiv = maxdiv , O.optForbiddenDivs = forbid , O.optTimeSignatures = ts , O.optMetronomes = ms } = opts let sf2end = SF2.scoreEnd sf2 let tsmetro = (ts, ms) measures <- measuresUntilTime sf2end (measureStream' tsmetro) let divs = zipWith (\m f -> [1..m] \\ f) (U.stickToLast maxdiv) (U.stickToLast forbid) let beatDivs = U.repeatList divs (map M.measureNumLeaf measures) let trans = quantifyVoiceOrErr measures beatDivs return $ fmap trans simple2sf_score :: L.LispVal -> SF.Score simple2sf_score simple = let lispVal2Score :: L.LispVal -> A.Score L.LispVal lispVal2Score = L.fromSexp score = lispVal2Score simple :: A.Score L.LispVal sf_score = fmap (L.mapcar' SF.sexp2event) score :: SF.Score in sf_score sf_score2sf2_score :: SF.Score -> SF2.Score sf_score2sf2_score = fmap SF2.voiceToSimpleFormat2 process_sf_score :: O.Options -> SF.Score -> T.Err M.Score process_sf_score opts sf_score = do let sf2_score = sf_score2sf2_score sf_score :: SF2.Score trans <- mkTrans opts sf2_score :: T.Err (SF2.Score -> A.Score (T.Err M.Ms)) let mscore = trans sf2_score :: A.Score (T.Err M.Ms) unwrapLeft mscore processInput :: O.PureMain processInput opts input = do parse <- getParser opts let process = getProcessor opts filt <- getFilter opts format <- getFormatter opts parseResult <- parse input processResult <- process parseResult filterResult <- filt processResult format filterResult main :: IO () main = handleIO processInput
kisp/ksquant2
Main.hs
gpl-3.0
8,618
0
14
2,447
2,094
1,088
1,006
176
3
-- | Tests for the persistence layer module Tweet.Test.Store ( testToken , testUser , testTweet , testMark ) where {- - Warning to future generations: - testing DB functionality with QuickCheck was not necessarily a good idea. - Should add some HUnit tests here. -} import Control.Monad import Control.Monad.Reader import Database.HDBC (IConnection) import Test.QuickCheck import Test.QuickCheck.Monadic import Tweet.Spam import Tweet.Store import Tweet.Store.Connection import Tweet.Types prop_parseTest :: (Eq a, FromSQL a, ToSQL a) => a -> Bool prop_parseTest a = Just a == (parseSQL . prepSQL $ a) insertTest :: (ToSQL a, IConnection c) => a -> ReaderT c IO Bool insertTest a = liftM (==1) $ insert a selectTest :: (IConnection c, Eq a, FromSQL a, ToSQL a) => a -> ReaderT c IO Bool selectTest a = do _ <- insert a a' <- select a return $ all (a==) a' markTest :: (IConnection c, FromSQL a, ToSQL a, Spam a, Show a) => a -> ReaderT c IO Bool markTest a = do _ <- insert a _ <- mark True a a' <- select a case a' of [a''] -> return $ isSpam a'' == Just True _ -> return False prop :: IConnection c => (a -> ReaderT c IO Bool) -> c -> a -> Property prop f c t = monadicIO $ do result <- run $ runReaderT (f t) c assert result -- | Check saving and loading tokens testToken :: IO () testToken = withConnection $ \conn -> do quickCheck (prop_parseTest :: Token -> Bool) quickCheck (prop insertTest conn :: Token -> Property) quickCheck (prop selectTest conn :: Token -> Property) -- | Check saving and loading users testUser :: IO () testUser = withConnection $ \conn -> do quickCheck (prop_parseTest :: User -> Bool) quickCheck (prop insertTest conn :: User -> Property) quickCheck (prop selectTest conn :: User -> Property) -- | Check saving and loading tweets testTweet :: IO () testTweet = withConnection $ \conn -> do quickCheck (prop insertTest conn :: Tweet -> Property) quickCheck (prop selectTest conn :: Tweet -> Property) -- | Check marking tweets and users as spam testMark :: IO () testMark = withConnection $ \conn -> do quickCheck (prop markTest conn :: User -> Property) quickCheck (prop markTest conn :: Tweet -> Property)
cbowdon/TweetFilter
Tweet/Test/Store.hs
gpl-3.0
2,256
0
12
495
782
398
384
53
2
{-# LANGUAGE BangPatterns, OverloadedStrings #-} {- | Module : Milkman.IO.Burmeister License : GPL-3 Stability : experimental Portability : unknown I/O for the burmeister context format -} module Milkman.IO.Burmeister ( parseBurmeister , showBurmeister ) where import Control.Applicative ((<|>)) import Data.Attoparsec.Text import Data.Text ( Text , pack ) import qualified Data.Text as T import Milkman.Context ( Context , attributes , incidence , mkContext , objects ) -- |Parse a formal context in burmeister format parseBurmeister :: Monad m => Parser (m Context) parseBurmeister = do (no, na) <- parseHeader objs <- count no takeLine atts <- count na takeLine cs <- count no $ parseRow na return $! mkContext objs atts cs -- |Parse the header of a burmeister context description parseHeader :: Parser (Int, Int) parseHeader = do _ <- char 'B' endOfLine endOfLine no <- decimal endOfLine na <- decimal endOfLine endOfLine return (no, na) -- |Parse a row of the incidence relation parseRow :: Int -> Parser [Bool] parseRow na = do cs <- count na parseCross endOfLine return cs -- |Parse a single cross of teh incidence relation parseCross :: Parser Bool parseCross = do c <- anyChar case c of 'X' -> return True '.' -> return False _ -> fail "not a cross." -- |Read until end of input or end of line takeLine :: Parser Text takeLine = do l <- takeTill isEndOfLine endOfLine <|> endOfInput return $! l -- |Output a given context in burmeister context format showBurmeister :: Context -> Text showBurmeister c = T.unlines $ [ "B" , "" , pack $ show no , pack $ show na , "" ] ++ os ++ as ++ is where (gs, os) = unzip $ objects c (ms, as) = unzip $ attributes c (no, na) = (length gs, length ms) i = go [] $ incidence c is = map (T.concat . map showCross) i go :: [[Bool]] -> [Bool] -> [[Bool]] go rs [] = rs go !rs !rest = go (rs ++ [Prelude.take na rest]) $ drop na rest showCross :: Bool -> Text showCross True = "X" showCross False = "."
mmarx/milkman
src/Milkman/IO/Burmeister.hs
gpl-3.0
2,467
0
13
877
656
337
319
66
3
-- Copyright 2016, 2017 Robin Raymond -- -- This file is part of Purple Muon -- -- Purple Muon is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Purple Muon 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 Purple Muon. If not, see <http://www.gnu.org/licenses/>. {-| Module : PurpleMuon.Input.Util Description : Some utility functions for input management Copyright : (c) Robin Raymond, 2016-2017 License : GPL-3 Maintainer : [email protected] Portability : POSIX -} module PurpleMuon.Input.Util ( updateKeyboardState , getKeyboardState , standardKeyMap ) where import Protolude import qualified SDL import PurpleMuon.Input.Types as PIT -- | Update the current state of the keyboard updateKeyboardState :: (MonadIO m, MonadState PIT.Controls m) => PIT.KeyMap -> m () updateKeyboardState km = getKeyboardState km >>= put -- | Get the current state of the keyboard getKeyboardState :: MonadIO m => PIT.KeyMap -> m PIT.Controls getKeyboardState (PIT.KeyMap a b c d e f g h) = do ks <- SDL.getKeyboardState let [i,j,k,l,m,n,o,p] = fmap ks [a,b,c,d,e,f,g,h] return $ PIT.Controls i j k l m n o p -- | Standard keymap standardKeyMap :: PIT.KeyMap standardKeyMap = PIT.KeyMap { PIT.km_accel = SDL.ScancodeUp , PIT.km_turn_left = SDL.ScancodeLeft , PIT.km_turn_right = SDL.ScancodeRight , PIT.km_decel = SDL.ScancodeDown , PIT.km_fire1 = SDL.ScancodeSpace , PIT.km_fire2 = SDL.ScancodeS , PIT.km_fire3 = SDL.ScancodeD , PIT.km_fire4 = SDL.ScancodeF }
r-raymond/purple-muon
src/PurpleMuon/Input/Util.hs
gpl-3.0
2,081
0
11
471
350
205
145
-1
-1
-- Author: Viacheslav Lotsmanov -- License: GPLv3 https://raw.githubusercontent.com/unclechu/xmonadrc/master/LICENSE {-# LANGUAGE PackageImports #-} module FocusHook (focusManageHook) where import "xmonad" XMonad ( className, title , (-->), (=?), (<&&>) , ManageHook , composeAll ) -- local imports import XMonad.Hooks.ManageHelpers (isDialog, composeOne, (-?>)) import XMonad.Hooks.EwmhDesktops (activated) import XMonad.Hooks.Focus ( FocusHook , keepFocus , switchFocus , new , focused , liftQuery , manageFocus ) focusManageHook :: ManageHook focusManageHook = manageFocus $ composeOne [ liftQuery activated -?> activateFocusHook , Just <$> newFocusHook ] newFocusHook :: FocusHook newFocusHook = composeOne $ raiseNewAndKeep [ className =? "Gmrun" , title =? "gpaste-zenity" , className =? "Gpaste-gui.pl" , className =? "Gnome-calculator" , title =? "Place Cursor At [C]" ] ++ withDialogs [ className =? "Firefox" , className =? "Tor Browser" -- Prevent lost focus for all messangers -- but allow dialog windows of these applications -- to grab focus. , className =? "Gajim" , className =? "Hexchat" , className =? "utox" , className =? "qTox" , className =? "Gnome-ring" , className =? "Thunderbird" , className =? "Keepassx" ] ++ -- Default behavior for new window, just usual switching focus. [ return True -?> switchFocus ] where withDialogs = foldr ((++) . f) [] where f c = [ new (c <&&> isDialog) -?> switchFocus , focused c -?> keepFocus ] -- Always switch to new window even -- if focus is kept by another window -- and keep focus for this window. raiseNewAndKeep = foldr ((++) . f) [] where f c = [ new c -?> switchFocus , focused c -?> keepFocus ] activateFocusHook :: FocusHook activateFocusHook = composeAll $ keepFocusFor [ className =? "Gmrun" , className =? "Firefox" , className =? "Tor Browser" -- Prevent lost focus for all messangers , className =? "Gajim" , className =? "Hexchat" , className =? "utox" , className =? "qTox" , className =? "Gnome-ring" , className =? "Thunderbird" , className =? "Keepassx" , title =? "gpaste-zenity" , className =? "Gpaste-gui.pl" ] where keepFocusFor = foldr ((:) . f) [] f cond = focused cond --> keepFocus
unclechu/xmonadrc
xmonad/src/FocusHook.hs
gpl-3.0
3,113
0
13
1,277
533
310
223
60
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module HsPredictor.SQL.Models.League where -- 3rd party import Database.Persist.TH (mkMigrate, mkPersist, persistLowerCase, share, sqlSettings) -- | Template haskell: database model. share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Teams name String Name name deriving Show Results date Int homeTeam TeamsId awayTeam TeamsId resultHome Int resultAway Int odds1x Double oddsx Double oddsx2 Double deriving Show StatsTable team TeamsId win Int draw Int loss Int Team team deriving Show MD5 hash String Hash hash deriving Show |]
jacekm-git/HsPredictor
library/HsPredictor/SQL/Models/League.hs
gpl-3.0
950
0
7
266
64
43
21
11
0
{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-| Module : Database/Hedsql/TH/Instances.hs Description : Template haskell instances generator. Copyright : (c) Leonard Monnier, 2016 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : portable Generate instances using template haskell. -} module Database.Hedsql.TH.Instances ( mkSelectionConstr , mkSelectionConstrs ) where import Data.List import Language.Haskell.TH {-| Create a 'SelectionConstr' instance for a tuple of size 'n'. For n=2: instance SelectionConstr (a1, a2) (Selection [(b1, b2)] db) => ( ToColRef a1 (ColRef b1 db) , ToColRef a2 (ColRef b2 db) ) where selection (x1, x2) = Selection [ ColRefWrap (colRef x1) , ColRefWrap (colRef x2) ] -} mkSelectionConstr :: Int -- ^ n. -> Q Dec mkSelectionConstr n = instanceD (scTQ n "a" "b" "db") (scCxtQ n "a" "b") [pure $ scFunD n "x"] {-| Create 'SelectionConstr' instances for tuple up to size 'n' starting at 2. -} mkSelectionConstrs :: Int -- ^ n. -> Q [Dec] mkSelectionConstrs n = mapM mkSelectionConstr [2..n] {-| Create the constraint head of the SelectionConstr (sc) instance. For tuples sizes = 2, a = "a" and b = "b": > SelectionConstr (a1, a2) (Selection [(b1, b2)] db) -} scCxtQ :: Int -- ^ Tuples sizes. -> String -- ^ a. -> String -- ^ b. -> Q Type scCxtQ n a b = [t| $(nameConT "SelectionConstr") ($(pure $ tupleTs n a)) ( $(nameConT "Selection") [$(pure $ tupleTs n b)] $(nameVarT "db") ) |] {-| Create the type constraints of the SelectionConstr (sc) instance. For tuple size = 2, a = "a", b = "b" and c = "db": @ ( ToColRef a1 (ColRef b1 db) , ToColRef a2 (ColRef b2 db) ) @ -} scTQ :: Int -- ^ Tuple size. -> String -- ^ a. -> String -- ^ b. -> String -- ^ c. -> Q [Pred] scTQ n a b c = mapM (\x -> singleScTQ (a ++ show x) (b ++ show x) c) [1..n] {-| Create a single SelectConstr (sc) instance type. For a = "a", b = "b" and c = "db": > ToColRef a (ColRef b db) -} singleScTQ :: String -- ^ a. -> String -- ^ b. -> String -- ^ c. -> Q Type singleScTQ a b c = [t| $(nameConT "ToColRef") $(nameVarT a) ( $(nameConT "ColRef") $(nameVarT b) $(nameVarT c) ) |] {-| Create the function of the SelectionConstr (sc) instance. For tuple size = 2 and name = "x": @ selection (x1, x2) = Selection [ColRefWrap (colRef x1), ColRefWrap (colRef x2)] @ -} scFunD :: Int -- ^ Tuple size. -> String -- ^ Name. -> Dec scFunD n name = FunD (mkName "selection") [Clause [tupleP n name] (scBody n name) []] {-| Create the selection function of a SelectConstr instance (sc): For tuple size=2 and name="x": @ selection (x1, x2) = Selection [ColRefWrap (colRef x1), ColRefWrap (colRef x2)] @ -} scBody :: Int -- ^ Tuple size. -> String -- ^ name. -> Body scBody n = NormalB . AppE (ConE $ mkName "Selection") . scExprs n {-| Create a list of colRefWrap expressions. For tuple size=2 and name="x": > [ColRefWrap (colRef x1), ColRefWrap (colRef x2)]] -} scExprs :: Int -- ^ Tuple size. -> String -- ^ Name. -> Exp scExprs n name = ListE $ map (scExpr . (++) name . show) [1..n] {-| Create a ColRefWrap expression for the 'selection' function a 'SelectConstr' instance (sc). For name="x": > ColRefWrap (colRef x) -} scExpr :: String -> Exp scExpr name = ConE (mkName "ColRefWrap") `AppE` ( VarE (mkName "colRef") `AppE` VarE (mkName name) ) -------------------------------------------------------------------------------- -- Generic functions which could be re-used in other modules -------------------------------------------------------------------------------- {-| Create a tuple type such as for tuple size=2 and name = "a": > (a1, a2) -} tupleTs :: Int -- ^ Tuple size. -> String -- ^ Name. -> Type tupleTs n a = foldl' AppT (TupleT n) $ map (VarT . mkName . (++) a . show) [1..n] {-| Create a tuple pattern such as for tuple size n=2 and name="x": > (x1, x2) -} tupleP :: Int -- ^ Tuple size. -> String -- ^ Name. -> Pat tupleP n name = TupP $ map (VarP . mkName . (++) name . show) [1..n] {-| Create a variable type name which can then be used in a type splice @[t|..|]@. -} nameVarT :: String -> Q Type nameVarT = return . VarT . mkName {-| Create a constructor type name which can then be used in a type splice @[t|..|]@. -} nameConT :: String -> Q Type nameConT = return . ConT . mkName
momomimachli/Hedsql
src/Database/Hedsql/TH/Instances.hs
gpl-3.0
4,775
0
11
1,238
715
394
321
85
1
{-# LANGUAGE GeneralizedNewtypeDeriving, RankNTypes #-} -- |This module is the one to use when you want to use XCP over ethernet. -- Usage goes somewhat like this: -- -- @ -- import Network.XcpEth -- import Data.Int -- -- main = do -- am <- loadAddressMap "myAddresses" -- a <- runXcpEth $ do -- connect "192.168.0.1" 12345 "192.168.0.2" 12345 -- a <- getVariable (0::Float) "myOwnVariable" -- setVariable "myOtherVariable" (42::Int8) -- return a -- disconnect -- putStrLn $ "Received " ++ show a -- @ -- -- If you want to add other transport layer protocols, -- just look at 'Xcp' and add the parts of the XCP message -- that are specific to your transport layer protocol to the XCP packets -- you get from 'Xcp'. module Network.XcpEth ( -- * XcpEth Monad XcpEth ,runXcpEth -- * XcpEth operations ,connect ,disconnect ,setVariable ,getVariable ,logString -- * Reading strings with 'XcpCommand's ,readCommands -- * Name to address maps and operations ,AddressMap ,loadAddressMap ,setAddressMap ,module Network ,module Network.Udp ,throwError ,ToByteString -- * Other Types ,IPAddress) where import Network (PortNumber, Socket) import Network.Udp import Network.Socket (SockAddr(..), inet_addr, close) import Network.Socket.ByteString import Network.Xcp import Control.Applicative import Control.Monad (when, liftM) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Except import Control.Monad.Trans.RWS import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as LB import Data.ByteString (ByteString) import Data.ByteString.Builder import Data.Monoid import Data.Word import Data.Int import qualified Data.Map as M import Foreign.Storable type IPAddress = String type AddressMap = M.Map String Word32 loadAddressMapIO :: FilePath -> IO AddressMap loadAddressMapIO fp = do f <- readFile fp let a l = let (addr:name:_) = words l in (name, read ('0':'x':addr)) return $ M.fromList $ map a (lines f) -- | Sets the address map to use by subsequent actions. setAddressMap :: AddressMap -> XcpEth () setAddressMap am = XcpEth $ modify $ \s -> s { xcpStateConfig = (xcpStateConfig s) { xcpConfigAddressMap = am } } -- | Reads a mapping from memory addresses to names from a simple text file. -- Each line is expected of the form -- /address/ /name/. loadAddressMap :: FilePath -> XcpEth () loadAddressMap fp = XcpEth (liftIO (loadAddressMapIO fp)) >>= setAddressMap -- | Commands for running lists of commands. data XcpCommand = ReadNames FilePath | Connect IPAddress Int IPAddress Int | Disconnect | SetInt8 String Int8 | SetUInt8 String Word8 | SetInt16 String Int16 | SetUInt16 String Word16 | SetInt32 String Int32 | SetUInt32 String Word32 | SetFloat String Float | GetInt8 String | GetUInt8 String | GetInt16 String | GetUInt16 String | GetInt32 String | GetUInt32 String | GetFloat String deriving (Show, Read) compileCommand :: XcpCommand -> XcpEth () compileCommand a = case a of ReadNames fp -> loadAddressMap fp Connect myIp myPort destIp destPort -> connect myIp (fromIntegral myPort) destIp (fromIntegral destPort) Disconnect -> disconnect SetInt8 name a -> setVariable name a SetUInt8 name a -> setVariable name a SetInt16 name a -> setVariable name a SetUInt16 name a -> setVariable name a SetInt32 name a -> setVariable name a SetUInt32 name a -> setVariable name a SetFloat name a -> setVariable name a GetInt8 name -> getAndPrint (0::Int8) name GetUInt8 name -> getAndPrint (0::Word8) name GetInt16 name -> getAndPrint (0::Int16) name GetUInt16 name -> getAndPrint (0::Word16) name GetInt32 name -> getAndPrint (0::Int32) name GetUInt32 name -> getAndPrint (0::Word32) name GetFloat name -> getAndPrint (0::Float) name readCommand :: String -> XcpEth () readCommand s = compileCommand $ read s readCommands :: [String] -> XcpEth () readCommands = mapM_ readCommand -- | Gets a variable from the connected slave and prints the result to the console. getAndPrint :: (ToByteString a, Show a) => a -> String -> XcpEth () getAndPrint dummy name = do a <- getVariable dummy name XcpEth $ liftIO $ putStrLn $ name ++ " = " ++ show a data XcpConfig = XcpConfig { xcpConfigMyIP :: IPAddress , xcpConfigMyPort :: PortNumber , xcpConfigTargetIP :: IPAddress , xcpConfigTargetPort :: PortNumber , xcpConfigAddressMap :: AddressMap } data XcpState = XcpState { xcpStateMasterCounter :: Word16 , xcpStateSlaveCounter :: Word16 , xcpStateSocket :: Maybe Socket , xcpStateConfig :: XcpConfig } -- | The XcpEth monad. It is used to encapsulate sending commands -- from the host to the slave and receiving results. newtype XcpEth a = XcpEth { unXcpEth :: RWST () [String] XcpState (ExceptT String IO) a } deriving (Monad, Applicative, Functor) defaultXcpConfig = XcpConfig "192.168.1.1" 21845 "192.168.1.2" 21845 M.empty -- | Run an action and return either an error message, or the resulting value and -- log strings, if any. runXcpEth :: XcpEth a -> IO (Either String (a,[String])) runXcpEth act = let s = XcpState 0 0 Nothing defaultXcpConfig in runExceptT (runRWST (unXcpEth act) () s >>= \(a,_,w) -> return (a,w)) -- Event and Service from the slave to the master are not implemented here. -- | Wrap a bytestring containing an XCP packet in more information to yield -- a XCP message that can be sent to the slave over UDP. wrapXcpEth :: Word16 -- ^ Message counter -> LB.ByteString -- ^ XCP packet -> XcpEth B.ByteString -- ^ Returns the XCP message with ethernet head and tail. wrapXcpEth ctr bs = do let len = LB.length bs when (len > 2^16-1) $ throwError "wrapXcpEth: XCP packet is too long." let xcpMessage = word16LE (fromIntegral len) `mappend` word16LE ctr `mappend` lazyByteString bs return . LB.toStrict . toLazyByteString $ xcpMessage -- | Increment the host message counter. incCtr :: XcpEth () incCtr = XcpEth . modify $ \s -> s { xcpStateMasterCounter = xcpStateMasterCounter s + 1 } -- | Send the given XCP packet and receive the result from the slave. -- The packet is wrapped using 'wrapXcpEth'. sendXcp :: LB.ByteString -> XcpEth XcpResult sendXcp bs = do st@(XcpState ctr slaveCtr msock cfg) <- XcpEth get let XcpConfig ip port targetIP targetPort _ = cfg sock <- maybe (throwError "sendXcp: Not connected.") (return) msock xcpMessage <- wrapXcpEth ctr bs targetHostAddr <- XcpEth . liftIO $ inet_addr targetIP let targetAddr = SockAddrInet targetPort targetHostAddr -- XcpEth $ tell [bytesToString (B.unpack xcpMessage)] n <- XcpEth . liftIO $ sendTo sock xcpMessage targetAddr incCtr (res, addr) <- XcpEth . liftIO $ recvFrom sock (1024 * 10) -- XcpEth $ tell [bytesToString (B.unpack res)] return $ byteStringToResult res -- | Connect to the given slave IP and portnumber, and send -- an XCP /connect/ packet. connect :: IPAddress -- ^ Host IP (this computer). -> PortNumber -- ^ Host port number. -> IPAddress -- ^ Slave IP address. -> PortNumber -- ^ Slave port number. -> XcpEth () connect myIp myPort destIp destPort = do conf <- XcpEth $ gets xcpStateConfig let conf' = XcpConfig myIp myPort destIp destPort (xcpConfigAddressMap conf) mySocket <- XcpEth $ liftIO $ udpSocket myIp myPort XcpEth $ modify $ \s -> s { xcpStateConfig = conf', xcpStateSocket = Just mySocket } -- XcpEth $ tell $ [myIp ++ " -> " ++ destIp] res <- sendXcp xcpConnect case res of XcpResult _ _ _ -> XcpEth $ tell ["connect ok"] XcpErr _ _ _ _ -> XcpEth $ tell ["connect failed"] -- | Sends a /disconnect/ XCP packet to the slave and closes the UDP socket. disconnect :: XcpEth () disconnect = do res <- sendXcp xcpDisconnect case res of XcpResult _ _ _ -> do XcpEth $ tell ["disconnect ok"] ms <- XcpEth $ gets xcpStateSocket maybe (return ()) (\s -> XcpEth . liftIO $ close s) ms XcpEth $ modify $ \s -> s { xcpStateSocket = Nothing } XcpErr _ _ _ _ -> XcpEth $ tell ["disconnect failed"] -- | Stores a log message in the internal log. logString :: String -> XcpEth () logString a = XcpEth $ tell [a] -- | Set a variable in the slave memory. setVariable :: ToByteString a => String -- ^ Name of the variable to set. -> a -- ^ Value to set. Must be of the correct type, otherwise funny things may happen on the slave. -> XcpEth () setVariable name value = do addr <- address name res <- sendXcp $ xcpSet addr value case res of XcpErr _ _ _ _ -> throwError "get failed." XcpResult _ _ _ -> return () -- | Look up the slave memory address in the internal 'AddressMap', given the variable's name. address :: String -- ^ Name of the variable. -> XcpEth Word32 address name = do am <- xcpConfigAddressMap <$> XcpEth (gets xcpStateConfig) maybe (throwError $ "Could not find name " ++ name) (return) $ M.lookup name am -- | Get the value of a variable in the slave memory. getVariable :: ToByteString a => a -- ^ Just a dummy to fix the type of the variable to retrieve. -> String -- ^ Name of the variable. -> XcpEth a -- ^ Returns the retrieved value received from the slave. getVariable dummy name = do addr <- address name let sz = sizeOf dummy res <- sendXcp $ xcpGet addr $ fromIntegral sz case res of XcpErr _ _ _ _ -> throwError "get failed." XcpResult payload _ _ -> let ma = fromBytes dummy (B.unpack payload) in maybe (throwError "get failed: could not convert result.") return ma throwError :: forall a. String -> XcpEth a throwError s = XcpEth $ lift $ throwE s
cgo/xcp
Network/XcpEth.hs
gpl-3.0
10,963
0
17
3,258
2,482
1,295
1,187
191
17
module XMonad.Hooks.Fizzixnerd where import XMonad import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.ManageHelpers import XMonad.Hooks.UrgencyHook import XMonad.Hooks.FadeInactive import XMonad.Hooks.EwmhDesktops import XMonad.Layout.BoringWindows import XMonad.Layout.Minimize import XMonad.Layout.Maximize import XMonad.Layout.SimpleDecoration import XMonad.Layout.ImageButtonDecoration import XMonad.Layout.WindowSwitcherDecoration import XMonad.Layout.DraggingVisualizer import XMonad.Util.Timer import qualified XMonad.Util.ExtensibleState as XS import XMonad.Actions.UpdateFocus import XMonad.Actions.Fizzixnerd import Data.Monoid -- TIMERHOOK -- From: http://stackoverflow.com/questions/11045239/can-xmonads-loghook-be-run-at-set-intervals-rather-than-in-merely-response-to data TidState = TID TimerId deriving Typeable instance ExtensionClass TidState where initialValue = TID 0 clockStartupHook = startTimer 1 >>= XS.put . TID clockEventHook e = do (TID t) <- XS.get handleTimer t e $ do startTimer 1 >>= XS.put . TID ask >>= logHook.config return Nothing return $ All True -- STARTUPHOOk myStartupHook = runCompton >> waitHalfSecond >> runGnomeDo >> runDock >> adjustEventInput -- >> clockStartupHook -- WINDOW RULES ignoreGnomeDo = className =? "Do" --> doIgnore ignoreCairoDock = className =? "Cairo-dock" --> doIgnore ignoreDocky = className =? "Docky" --> doIgnore floatNMConnectionEditor = className =? "Nm-connection-editor" --> doFloat fullscreenFullscreen = isFullscreen --> doFullFloat -- LOGHOOK myLogHook = fadeInactiveLogHook 0.8 -- LAYOUTHOOK myLayoutHook = boringAuto $ maximize $ minimize $ windowSwitcherDecorationWithImageButtons (shrinkText) defaultThemeWithImageButtons $ draggingVisualizer $ layoutHook defaultConfig -- MANAGEHOOK myManageHook = manageDocks <+> ignoreGnomeDo <+> ignoreCairoDock <+> ignoreDocky <+> floatNMConnectionEditor <+> fullscreenFullscreen -- HANDLEEVENTHOOK myhandleEventHook = docksEventHook <+> focusOnMouseMove <+> clockEventHook
Fizzixnerd/xmonad-config
site-haskell/src/XMonad/Hooks/Fizzixnerd.hs
gpl-3.0
2,353
0
12
531
415
233
182
57
1
{-# LANGUAGE OverloadedStrings #-} import qualified Data.Text as T import qualified Data.Text.IO import qualified Data.Attoparsec.Text as AT import qualified Data.Attoparsec.Combinator as ATC --import Control.Monad import Control.Applicative ((<*)) --import Data.DateTime as D readValue :: AT.Parser T.Text readValue = ATC.manyTill AT.anyChar (AT.try $ AT.char ';') >>= (return . T.pack) readValues :: AT.Parser [T.Text] readValues = ATC.manyTill readValue (AT.try AT.endOfLine) skipLine :: AT.Parser T.Text skipLine = (AT.takeTill AT.isEndOfLine) <* (AT.takeWhile AT.isEndOfLine) -- Nagłówek pliku .cvs zawiera dodatkowe informacje w postaci: -- #Klucz -- wartość parseHeaderData :: T.Text -> AT.Parser [T.Text] parseHeaderData name = do AT.string name AT.takeWhile AT.isEndOfLine res <- readValues AT.takeWhile AT.isEndOfLine return res ---- #Data operacji; #Data księgowania; #Opis operacji; #Tytuł; #Nadawca/Odbiorca; #Numer konta; #Kwota; #Saldo po operacji; ---- 2010-09-13; 2010-09-13; PRZELEW WEWNĘTRZNY WYCHODZĄCY; "TYTUŁ PRZELEWU"; "IMIĘ NAZWISKO UL ICA 12/34 56-789 MIASTO"; '12345678901234567890123456'; -10,00; 90,00; --newtype Entry = Entry { data_operacji :: D.DateTime, -- data_ksiegowania :: D.DateTime, -- opis :: T.Text, -- tutul :: T.Text, -- kto :: T.Text, -- nr_konta :: T.Text, -- kwota :: } deriving (Eq, Show) oneCSVLine :: AT.Parser [T.Text] oneCSVLine = do res <- readValues AT.takeWhile AT.isEndOfLine return res mbankCSVParser :: AT.Parser T.Text mbankCSVParser = do ATC.count 6 skipLine -- nagłówek [_klient] <- parseHeaderData "#Klient;" skipLine -- śmieć [_okres_od, _okres_do] <- parseHeaderData "#Za okres:;" [_rodzaj_rachunku] <- parseHeaderData "#Rodzaj rachunku;" [_waluta] <- parseHeaderData "#Waluta;" [_nr_rachunku] <- parseHeaderData "#Numer rachunku;" [_data_nast_kapitalizacji] <- parseHeaderData "#Data następnej kapitalizacji;" [_oprocentowanie_rachunku] <- parseHeaderData "#Oprocentowanie rachunku;" [_limit_kredytu] <- parseHeaderData "#Limit kredytu;" [_oprocentowanie_kredytu] <- parseHeaderData "#Oprocentowanie kredytu;" [_, _uznania_liczba, _uznania_wartosc] <- parseHeaderData "#Podsumowanie obrotów na rachunku;#Liczba operacji;#Wartość operacji" [_, _obciazenia_liczba, _obciazenia_wartosc] <- parseHeaderData "" [_, _lacznie_liczba, _lacznie_wartosc] <- parseHeaderData "" ["#Saldo początkowe", _saldo_poczatkowe] <- parseHeaderData "" _headers <- parseHeaderData "" _res <- oneCSVLine return _nr_rachunku main :: IO () main = do file <- Data.Text.IO.readFile "ekonto.csv" let res = AT.parseOnly mbankCSVParser file --either putStrLn putStrLn res either putStrLn Data.Text.IO.putStrLn res
kgadek/mbank_analyser
test.hs
gpl-3.0
3,226
0
11
868
613
315
298
49
1
import System.Environment determineRes :: String -> String determineRes "mlaptop" = "1440x900" determineRes "house_pc" = "1280x1024" determineRes "maths_laptop" = "1280x800" determineRes "house_laptop" = "1366x768" determineRes "home_pc" = "1680x1050" determineRes "small" = "650x650" determineRes "art_laptop" = "1536x864" determineRes "library_pc" = "1024x768" determineRes "claptop" = "1280x800" determineRes "" = "err: empty" determineRes x = x ++ " given, err" main = do remoteHostname <- getEnv "REMOTE_HOSTNAME" putStr $ determineRes remoteHostname
zackp30/dotfiles
home/bin/exp-screenres.hs
gpl-3.0
564
0
8
75
132
65
67
16
1
module Pfds.Ch05.Dequeue where import Prelude hiding (head, tail, last, init) class Dequeue q where empty :: q a isEmpty :: q a -> Bool cons :: a -> q a -> q a head :: q a -> a tail :: q a -> q a snoc :: q a -> a -> q a last :: q a -> a init :: q a -> q a data BatchedDequeue a = BD [a] [a] deriving (Show) split :: [a] -> ([a], [a]) split l = splitAt (((length l) + 1) `div` 2) l check [] [] = BD [] [] check [] r = BD (reverse b) a where (a, b) = split r --check f [] = BD b (reverse a) check f [] = BD a (reverse b) where (a, b) = split f check f r = BD f r instance Dequeue BatchedDequeue where empty = BD [] [] isEmpty (BD f r) = null f && null r cons x (BD f r) = check (x:f) r head (BD [] []) = error "Empty Queue" head (BD [] [x]) = x head (BD (x:f) r) = x tail (BD [] []) = error "Empty Queue" tail (BD [] [x]) = BD [] [] tail (BD (x:f) r) = check f r snoc (BD f r) x = check f (x:r) last (BD [] []) = error "Empty Queue" last (BD [x] []) = x last (BD f (x:r)) = x init (BD [] []) = error "Empty Queue" init (BD (x:r) []) = BD [] r init (BD f (x:r)) = check f r --force a = seq (\a -> undefined) a q = snoc (BD [] []) 1 q' = snoc q 2 q'' = snoc (snoc q' 3) 4 who = snoc ( tail $ tail q'' ) 13 whoa = snoc (snoc (snoc ( tail $ tail q'' ) 13) 15) 16
heyduck/pfds
src/Pfds/Ch05/Dequeue.hs
gpl-3.0
1,334
0
12
397
862
439
423
43
1
module Main where import Data.Word import Data.Char import Test.Hspec import Test.QuickCheck import Brnfckr.Parse import Brnfckr.Eval import Paths_brnfckr helloWorld, loop, singleOp :: String loop = "[>.<],[>.<-]" singleOp = ",.-+><" helloWorld = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+." main :: IO () main = do bottlesBF <- getDataFileName "programs/bottles.bf" >>= readFile bottlesOut <- getDataFileName "programs/bottles.out" >>= readFile hspec $ do describe "Parsing" $ do it "unbalanced parens0" $ parseBrainFuck "[" `shouldBe` Left (UnbalancedBracket "[") it "unbalanced parens0" $ parseBrainFuck "]" `shouldBe` Left (UnbalancedBracket "]") it "unbalanced parens1" $ parseBrainFuck "+++++[>+++++++>++<<-]>.>.[" `shouldBe` Left (UnbalancedBracket "[") describe "Parsing errors bubble up while running" $ do it "unbalanced parens0" $ (fst . fst) (runBrainFuck "[" "") `shouldBe` Left (UnbalancedBracket "[") it "unbalanced parens0" $ (fst . fst) (runBrainFuck "]" "") `shouldBe` Left (UnbalancedBracket "]") it "unbalanced parens1" $ (fst . fst) (runBrainFuck "+++++[>+++++++>++<<-]>.>.[" "") `shouldBe` Left (UnbalancedBracket "[") describe "error handling" $ it "insufficient input" $ executeString "," "" `shouldBe` Nothing describe "basic programs" $ do it "output until inclusive 0" $ let s = map (chr . fromIntegral) $ [1 :: Word8 .. 255] ++ [0] in executeString "+[,.]" s `shouldBe` Just s it "output n exclamation marks" $ property $ \w -> let plusThirtyThree = replicate (ord '!') '+' in executeString (">" ++ plusThirtyThree ++ "<,[>.<-]") [chr $ fromIntegral w] `shouldBe` Just (replicate (fromIntegral (w :: Word8)) '!') it "memory 0 initialized" $ executeString ".>." "" `shouldBe` Just (toChars [0, 0 :: Word8]) it "memory operations" $ executeString ".>.+.<." "" `shouldBe` Just (toChars [0, 0, 1, 0 :: Word8]) it "input output" $ property $ \w -> executeString ".,." [toChar w] `shouldBe` Just (toChars [0, w :: Word8]) it "loops" $ property $ \w -> executeString "[>.<],[>.<-]" [toChar w] `shouldBe` Just (toChars $ replicate (fromIntegral w) (0 :: Word8)) describe "complex programs" $ do it "Hello World!" $ executeString helloWorldBF "" `shouldBe` Just "Hello World!" it "Numbers" $ executeString numbersBF [chr 10] `shouldBe` Just "1, 1, 2, 3, 5, 8, 13, 21, 34, 55" it "Bottles of beer" $ executeString bottlesBF "" `shouldBe` Just bottlesOut where helloWorldBF = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+." numbersBF = ",>+>>>>++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<+>>[-]]<<<<<<<]>>>>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]" toChar = chr . fromIntegral toChars = map toChar
johntyree/brnfckr
src/tests/TestMain.hs
gpl-3.0
3,402
0
23
618
861
430
431
45
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/. module Main where import Test.Tasty import qualified Tests.Wai.Route as WaiRoute main :: IO () main = defaultMain $ testGroup "Tests" [ WaiRoute.tests ]
twittner/wai-routing
test/TestSuite.hs
mpl-2.0
358
0
8
63
50
31
19
5
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.GamesManagement.Types -- 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) -- module Network.Google.GamesManagement.Types ( -- * Service Configuration gamesManagementService -- * OAuth Scopes , plusLoginScope , gamesScope -- * GamesPlayerExperienceInfoResource , GamesPlayerExperienceInfoResource , gamesPlayerExperienceInfoResource , gpeirCurrentExperiencePoints , gpeirCurrentLevel , gpeirNextLevel , gpeirLastLevelUpTimestampMillis -- * PlayerName , PlayerName , playerName , pnGivenName , pnFamilyName -- * PlayerScoreResetAllResponse , PlayerScoreResetAllResponse , playerScoreResetAllResponse , psrarResults , psrarKind -- * GamesPlayedResource , GamesPlayedResource , gamesPlayedResource , gprAutoMatched , gprTimeMillis -- * GamesPlayerLevelResource , GamesPlayerLevelResource , gamesPlayerLevelResource , gplrMaxExperiencePoints , gplrMinExperiencePoints , gplrLevel -- * PlayerScoreResetResponse , PlayerScoreResetResponse , playerScoreResetResponse , psrrKind , psrrResetScoreTimeSpans , psrrDefinitionId -- * ScoresResetMultipleForAllRequest , ScoresResetMultipleForAllRequest , scoresResetMultipleForAllRequest , srmfarKind , srmfarLeaderboardIds -- * QuestsResetMultipleForAllRequest , QuestsResetMultipleForAllRequest , questsResetMultipleForAllRequest , qrmfarKind , qrmfarQuestIds -- * HiddenPlayerList , HiddenPlayerList , hiddenPlayerList , hplNextPageToken , hplKind , hplItems -- * EventsResetMultipleForAllRequest , EventsResetMultipleForAllRequest , eventsResetMultipleForAllRequest , ermfarKind , ermfarEventIds -- * AchievementResetMultipleForAllRequest , AchievementResetMultipleForAllRequest , achievementResetMultipleForAllRequest , armfarKind , armfarAchievementIds -- * HiddenPlayer , HiddenPlayer , hiddenPlayer , hpKind , hpHiddenTimeMillis , hpPlayer -- * AchievementResetAllResponse , AchievementResetAllResponse , achievementResetAllResponse , ararResults , ararKind -- * Player , Player , player , pBannerURLLandscape , pLastPlayedWith , pAvatarImageURL , pKind , pExperienceInfo , pName , pOriginalPlayerId , pDisplayName , pTitle , pBannerURLPortrait , pPlayerId , pProFileSettings -- * ProFileSettings , ProFileSettings , proFileSettings , pfsProFileVisible , pfsKind -- * AchievementResetResponse , AchievementResetResponse , achievementResetResponse , arrUpdateOccurred , arrKind , arrCurrentState , arrDefinitionId ) where import Network.Google.GamesManagement.Types.Product import Network.Google.GamesManagement.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v1management' of the Google Play Game Services Management API. This contains the host and root path used as a starting point for constructing service requests. gamesManagementService :: ServiceConfig gamesManagementService = defaultService (ServiceId "gamesManagement:v1management") "www.googleapis.com" -- | Know the list of people in your circles, your age range, and language plusLoginScope :: Proxy '["https://www.googleapis.com/auth/plus.login"] plusLoginScope = Proxy; -- | Share your Google+ profile information and view and manage your game -- activity gamesScope :: Proxy '["https://www.googleapis.com/auth/games"] gamesScope = Proxy;
rueshyna/gogol
gogol-games-management/gen/Network/Google/GamesManagement/Types.hs
mpl-2.0
4,106
0
7
902
382
262
120
105
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Content.Accounttax.Custombatch -- 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) -- -- Retrieves and updates tax settings of multiple accounts in a single -- request. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.accounttax.custombatch@. module Network.Google.Resource.Content.Accounttax.Custombatch ( -- * REST Resource AccounttaxCustombatchResource -- * Creating a Request , accounttaxCustombatch , AccounttaxCustombatch -- * Request Lenses , ac1Xgafv , ac1UploadProtocol , ac1AccessToken , ac1UploadType , ac1Payload , ac1Callback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.accounttax.custombatch@ method which the -- 'AccounttaxCustombatch' request conforms to. type AccounttaxCustombatchResource = "content" :> "v2.1" :> "accounttax" :> "batch" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] AccounttaxCustomBatchRequest :> Post '[JSON] AccounttaxCustomBatchResponse -- | Retrieves and updates tax settings of multiple accounts in a single -- request. -- -- /See:/ 'accounttaxCustombatch' smart constructor. data AccounttaxCustombatch = AccounttaxCustombatch' { _ac1Xgafv :: !(Maybe Xgafv) , _ac1UploadProtocol :: !(Maybe Text) , _ac1AccessToken :: !(Maybe Text) , _ac1UploadType :: !(Maybe Text) , _ac1Payload :: !AccounttaxCustomBatchRequest , _ac1Callback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccounttaxCustombatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ac1Xgafv' -- -- * 'ac1UploadProtocol' -- -- * 'ac1AccessToken' -- -- * 'ac1UploadType' -- -- * 'ac1Payload' -- -- * 'ac1Callback' accounttaxCustombatch :: AccounttaxCustomBatchRequest -- ^ 'ac1Payload' -> AccounttaxCustombatch accounttaxCustombatch pAc1Payload_ = AccounttaxCustombatch' { _ac1Xgafv = Nothing , _ac1UploadProtocol = Nothing , _ac1AccessToken = Nothing , _ac1UploadType = Nothing , _ac1Payload = pAc1Payload_ , _ac1Callback = Nothing } -- | V1 error format. ac1Xgafv :: Lens' AccounttaxCustombatch (Maybe Xgafv) ac1Xgafv = lens _ac1Xgafv (\ s a -> s{_ac1Xgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ac1UploadProtocol :: Lens' AccounttaxCustombatch (Maybe Text) ac1UploadProtocol = lens _ac1UploadProtocol (\ s a -> s{_ac1UploadProtocol = a}) -- | OAuth access token. ac1AccessToken :: Lens' AccounttaxCustombatch (Maybe Text) ac1AccessToken = lens _ac1AccessToken (\ s a -> s{_ac1AccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ac1UploadType :: Lens' AccounttaxCustombatch (Maybe Text) ac1UploadType = lens _ac1UploadType (\ s a -> s{_ac1UploadType = a}) -- | Multipart request metadata. ac1Payload :: Lens' AccounttaxCustombatch AccounttaxCustomBatchRequest ac1Payload = lens _ac1Payload (\ s a -> s{_ac1Payload = a}) -- | JSONP ac1Callback :: Lens' AccounttaxCustombatch (Maybe Text) ac1Callback = lens _ac1Callback (\ s a -> s{_ac1Callback = a}) instance GoogleRequest AccounttaxCustombatch where type Rs AccounttaxCustombatch = AccounttaxCustomBatchResponse type Scopes AccounttaxCustombatch = '["https://www.googleapis.com/auth/content"] requestClient AccounttaxCustombatch'{..} = go _ac1Xgafv _ac1UploadProtocol _ac1AccessToken _ac1UploadType _ac1Callback (Just AltJSON) _ac1Payload shoppingContentService where go = buildClient (Proxy :: Proxy AccounttaxCustombatchResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Accounttax/Custombatch.hs
mpl-2.0
4,946
0
18
1,153
713
416
297
106
1
-- -*-haskell-*- -- GIMP Toolkit (GTK) Widget SourceView -- -- Author : Peter Gavin -- derived from sourceview bindings by Axel Simon and Duncan Coutts -- -- Created: 18 December 2008 -- -- Copyright (C) 2004-2008 Peter Gavin, Duncan Coutts, Axel Simon -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- | -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable (depends on GHC) -- module Graphics.UI.Gtk.SourceView.SourceStyle ( SourceStyle(..), ) where data SourceStyle = SourceStyle { sourceStyleBackground :: Maybe String , sourceStyleBold :: Maybe Bool , sourceStyleForeground :: Maybe String , sourceStyleItalic :: Maybe Bool , sourceStyleLineBackground :: Maybe String , sourceStyleStrikethrough :: Maybe Bool , sourceStyleUnderline :: Maybe Bool }
thiagoarrais/gtk2hs
gtksourceview2/Graphics/UI/Gtk/SourceView/SourceStyle.hs
lgpl-2.1
1,350
0
9
270
116
79
37
11
0
{-# LANGUAGE MultiParamTypeClasses, UnboxedTuples #-} module Math.Topology.KnotTh.Knotted.Crossings.Projection ( ProjectionCrossing(..) , projection ) where import Control.DeepSeq import Data.Bits ((.&.)) import Math.Topology.KnotTh.Algebra.Dihedral.D4 import Math.Topology.KnotTh.Knotted import Math.Topology.KnotTh.Knotted.Threads data ProjectionCrossing = ProjectionCrossing deriving (Eq, Show, Read) instance NFData ProjectionCrossing where rnf c = c `seq` () instance RotationAction ProjectionCrossing where rotationOrder _ = 4 rotateBy !_ = id instance MirrorAction ProjectionCrossing where mirrorIt = id instance GroupAction D4 ProjectionCrossing where transform _ = id instance TransposeAction ProjectionCrossing where transposeIt = id instance Crossing ProjectionCrossing where globalTransformations _ = Nothing crossingCode _ _ = (# 0, 0 #) crossingCodeWithGlobal _ _ _ = (# 0, 0 #) crossingCodeWithGlobal' _ _ _ _ = 0 instance OrientedCrossing ProjectionCrossing where strandContinuation _ x = (x + 2) .&. 3 instance ThreadedCrossing ProjectionCrossing projection :: (Knotted k) => k a -> k ProjectionCrossing projection = fmap (const ProjectionCrossing)
mishun/tangles
src/Math/Topology/KnotTh/Knotted/Crossings/Projection.hs
lgpl-3.0
1,240
0
8
214
315
175
140
32
1
module Cal where import Data.List import Data.Time import Data.Time.Calendar import Data.Time.Calendar.WeekDate import Control.Monad data DayOfWeek = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Show, Enum, Bounded) data Month = January | February | March | April | May | June | July | August | September | October | November | December deriving (Show, Read, Enum, Bounded) type Year = Integer type DayOfMonth = Int currentMonthCal :: IO String currentMonthCal = do currentTime <- getCurrentTime (y, m, _) <- return . toGregorian . utctDay $ currentTime return . unlines . (monthCal True y) $ toEnum (m - 1) yearCal :: Year -> String yearCal y = unlines $ (center 60 $ show y) : "" : (concatMap mergeMonths $ grouped 3 . map (monthCal False y) $ months) where months :: [Month] months = enumFrom . toEnum $ 0 mergeMonths :: [[String]] -> [String] mergeMonths = foldl1 (zipWith ((++) . (++ " "))) yearLine :: [String] -> String yearLine = intercalate " " monthCal :: Bool -> Year -> Month -> [String] monthCal displayYear year month = header : dayNames : monthDays year month where header = center 20 $ if displayYear then show month ++ " " ++ show year else show month dayNames :: String dayNames = intercalate " " $ map (take 2 . show) days where days :: [DayOfWeek] days = enumFrom . toEnum $ 0 monthDays :: Year -> Month -> [String] monthDays y m = map (intercalate " ") $ grouped 7 $ marginLeft ++ days ++ marginRight where marginLeft = replicate (fromEnum $ firstWeekDay y m) " " marginRight = replicate (42 - (length marginLeft + lastDay y m)) " " days = map showDayOfMonth [1..lastDay y m] lastDay :: Year -> Month -> DayOfMonth lastDay y m = day where (_, _, day) = toGregorian $ fromGregorian y (fromEnum m + 1) 31 firstWeekDay :: Year -> Month -> DayOfWeek firstWeekDay y m = dayOfWeek day where (_, _, day) = toWeekDate $ fromGregorian y (fromEnum m + 1) 1 dayOfWeek :: Int -> DayOfWeek dayOfWeek 7 = Sunday dayOfWeek i = toEnum i showDayOfMonth :: DayOfMonth -> String showDayOfMonth i | i < 10 = ' ' : show i | otherwise = show i center :: Int -> String -> String center width str = replicate marginLeft ' ' ++ str ++ replicate marginRight ' ' where totalMargin = max 0 (width - length str) marginLeft = div totalMargin 2 marginRight = totalMargin - marginLeft grouped :: Int -> [a] -> [[a]] grouped i as = case splitAt i as of ([], _) -> [] (p, tl) -> p : grouped i tl
blouerat/cal
Cal.hs
unlicense
2,599
0
12
632
1,014
536
478
56
2
module HelperSequences.A000037Spec (main, spec) where import Test.Hspec import HelperSequences.A000037 (a000037) main :: IO () main = hspec spec spec :: Spec spec = describe "A000037" $ it "correctly computes the first 20 elements" $ take 20 (map a000037 [1..]) `shouldBe` expectedValue where expectedValue = [2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24]
peterokagey/haskellOEIS
test/HelperSequences/A000037Spec.hs
apache-2.0
379
0
10
59
160
95
65
10
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} module Language.C.Obfuscate.CPS where import Data.Char import Data.List (nubBy) import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import qualified Language.C.Syntax.AST as AST import qualified Language.C.Data.Node as N import Language.C.Syntax.Constants import Language.C.Data.Ident import Language.C.Obfuscate.Var import Language.C.Obfuscate.ASTUtils import Language.C.Obfuscate.CFG import Language.C.Obfuscate.SSA -- import for testing import Language.C (parseCFile, parseCFilePre) import Language.C.System.GCC (newGCC) import Language.C.Pretty (pretty) import Text.PrettyPrint.HughesPJ (render, text, (<+>), hsep) import System.IO.Unsafe (unsafePerformIO) -- TODO LIST: -- 1. check whether k vs kParam (done) -- 2. id, loop an loop lambda (done) -- 3. pop and push (done) -- 4. function signatures (done) -- 5. max stack size -- 6. curr_stack_size + 1 or - 1 testCPS = do { let opts = [] ; ast <- errorOnLeftM "Parse Error" $ parseCFile (newGCC "gcc") Nothing opts "test/sort.c" -- -} "test/fibiter.c" ; case ast of { AST.CTranslUnit (AST.CFDefExt fundef:_) nodeInfo -> case runCFG fundef of { CFGOk (_, state) -> do { -- putStrLn $ show $ buildDTree (cfg state) ; -- putStrLn $ show $ buildDF (cfg state) ; let (SSA scopedDecls labelledBlocks sdom _ _) = buildSSA (cfg state) (formalArgs state) visitors = allVisitors sdom labelledBlocks exits = allExits labelledBlocks -- ; putStrLn $ show $ visitors -- ; putStrLn $ show $ exits ; let cps = ssa2cps fundef (buildSSA (cfg state) (formalArgs state)) ; putStrLn $ prettyCPS $ cps ; -- putStrLn $ render $ pretty (cps_ctxt cps) ; -- mapM_ (\d -> putStrLn $ render $ pretty d) (cps_funcsigs cps) ; -- mapM_ (\f -> putStrLn $ render $ pretty f) ((cps_funcs cps) ++ [cps_main cps]) } ; CFGError s -> error s } ; _ -> error "not fundec" } } prettyCPS :: CPS -> String prettyCPS cps = let declExts = map (\d -> AST.CDeclExt d) ([(cps_ctxt cps)] ++ (cps_funcsigs cps)) funDeclExts = map (\f -> AST.CFDefExt f) ((cps_funcs cps) ++ [cps_main cps]) in render $ pretty (AST.CTranslUnit (declExts ++ funDeclExts) N.undefNode) {- Source Language SSA (Prog) p ::= t x (\bar{t x}) {\bar{d}; \bar{b} } (Decl) d ::= t x (Block) b ::= l: {s} | l: {\bar{i} ; s} (Stmts) s ::= x = e; s | goto l; | return e; | e; s | if e { s } else { s } (Phi) i ::= x = \phi(\bar{g}) (Exp) e ::= v | e (\bar{e}) (Labelled argument) g ::= (l:e) (Label) l ::= l0 | ... | ln (Value) v ::= x | c (Type) t ::= int | bool | t* | t[] | | void (Loop environment) \Delta ::= (l_if, e_cond, l_true, l_false) -} -- was imported from SSA {- Target Language CPS (Prog) P ::= T X (\bar{T X}) {\bar{D}; \bar{B} } (Block) B ::= S (Decl) D ::= T X | P /* nested functions */ (Stmts) S ::= X = E ; S | return E; | E; S | if E { S } else { S } (Exp) E ::= V | E(\bar{E}) (Value) V :: = X | C | (\bar{T X}):T => {\bar{D}; \bar{B}} (Variable) X ::= x | y | k | ... (Type) T :: = int | bool | T * | T => T | T[] | void -} -- ^ a CPS function declaration AST data CPS = CPS { cps_decls :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function decls , cps_stmts :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function stmts , cps_funcsigs :: [AST.CDeclaration N.NodeInfo] -- ^ the signatures decls of the auxillary functions , cps_funcs :: [AST.CFunctionDef N.NodeInfo] -- ^ the auxillary functions , cps_ctxt :: AST.CDeclaration N.NodeInfo -- ^ the context for the closure , cps_main :: AST.CFunctionDef N.NodeInfo -- ^ the main function } deriving Show -- global names kParamName = "kParam" ctxtParamName = "ctxtParam" condParamName = "condParam" visitorParamName = "visitorParam" exitParamName = "exitParam" currStackSizeName = "curr_stack_size" {- class CPSize ssa cps where cps_trans :: ssa -> cps instance CPSize a b => CPSize [a] [b] where cps_trans as = map cps_trans as instance CPSize (Ident, LabeledBlock) (AST.CFunctionDef N.NodeInfo) where cps_trans (label, lb) = undefined {- translation d => D t => T x => X ---------------------- t x => T X -} instance CPSize (AST.CDeclaration N.NodeInfo) (AST.CDeclaration N.NodeInfo) where cps_trans decl = case decl of { AST.CDecl tyspec tripls nodeInfo -> let tyspec' = cps_trans tyspec tripls' = map (\(mb_decltr, mb_init, mb_size) -> let mb_decltr' = case mb_decltr of { Nothing -> Nothing ; Just decltr -> Just decltr -- todo } mb_init' = case mb_init of { Nothing -> Nothing ; Just init -> Just init -- todo } mb_size' = case mb_size of { Nothing -> Nothing ; Just size -> Just size -- todo } in (mb_decltr', mb_init', mb_size') ) tripls in AST.CDecl tyspec' tripls' nodeInfo -- ; AST.CStaticAssert e lit nodeInfo -> undefined } -} {- translation t => T ----------- int => int ----------- bool => bool t => t ------------- t* => T* t => T ------------ t[] => T* ------------- void => void -} {- instance CPSize (AST.CDeclarationSpecifier N.NodeInfo) (AST.CDeclarationSpecifier N.NodeInfo) where cps_trans tyspec = tyspec -- todo: unroll it -} {- data CDeclarationSpecifier a = CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef | CTypeSpec (CTypeSpecifier a) -- ^ type name | CTypeQual (CTypeQualifier a) -- ^ type qualifier | CFunSpec (CFunctionSpecifier a) -- ^ function specifier | CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-}) -} {- --------- (Var) x => X -} {- instance CPSize (AST.CDeclarator N.NodeInfo) (AST.CDeclarator N.NodeInfo) where cps_trans declr@(AST.CDeclr mb_ident derivedDecltrs mb_cstrLtr attrs nodeInfo) = declr -} -- fn, K, \bar{\Delta} |- \bar{b} => \bar{P} --translating the labeled blocks to function decls {- fn, K, \bar{\Delta}, \bar{b} |- b_i => P_i --------------------------------------------- fn, K, \bar{\Delta} |- \bar{b} => \bar{P} -} type ContextName = String type Visitors = M.Map Ident Ident -- ^ last label of the visitor -> label of the loop type Exits = M.Map Ident Ident -- ^ label of the exit -> label of the loop cps_trans_lbs :: Bool -> -- ^ is return void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ top level function name -- ^ \bar{\Delta} become part of the labelled block flag (loop) Visitors -> Exits -> M.Map Ident LabeledBlock -> -- ^ \bar{b} [AST.CFunctionDef N.NodeInfo] cps_trans_lbs isReturnVoid localVars fargs ctxtName fname visitors exits lb_map = map (\(id,lb) -> cps_trans_lb isReturnVoid localVars fargs ctxtName fname lb_map id visitors exits lb) (M.toList lb_map) {- fn, \bar{\Delta}, \bar{b} |- b => P -} cps_trans_lb :: Bool -> -- ^ is return void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ top level function name -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} Ident -> -- ^ label for the current block Visitors -> Exits -> LabeledBlock -> -- ^ the block AST.CFunctionDef N.NodeInfo {- fn, k, \bar{\Delta}, \bar{b} |- s => S ----------------------------------------------------------------- (LabBlk) fn, \bar{\Delta}, \bar{b} |- l_i : {s} => void fn_i(void => void k) { S } fn, k, \bar{\Delta}, \bar{b} |- s => S --------------------------------------------------------------------------- (PhiBlk) fn, \bar{\Delta}, \bar{b} |- l_i : {\bar{i}; s} => void fn_i(void => void k) { S } -} cps_trans_lb isReturnVoid localVars fargs ctxtName fname lb_map ident visitors exits lb = let fname' = fname `app` ident tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)] declrs = [] k = iid kParamName paramK = AST.CDecl tyVoid -- void (*k)(ctxt *) [(Just (AST.CDeclr (Just k) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode paramCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode paramDeclr = [paramK, paramCtxt] decltrs = [AST.CFunDeclr (Right ([paramK, paramCtxt],False)) [] N.undefNode] mb_strLitr = Nothing attrs = [] pop | ident `M.member` exits = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "pop"))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) ] | otherwise = [] stmt' = AST.CCompound [] (pop ++ (cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident (lb_loop lb) visitors exits (lb_stmts lb))) N.undefNode in AST.CFunDef tyVoid (AST.CDeclr (Just fname') decltrs mb_strLitr attrs N.undefNode) declrs stmt' N.undefNode cps_trans_stmts :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ K -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} Ident -> -- ^ label for the current block Bool -> -- ^ whether label \in \Delta (is it a loop block) Visitors -> Exits -> [AST.CCompoundBlockItem N.NodeInfo] -> -- ^ stmts [AST.CCompoundBlockItem N.NodeInfo] cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmts = -- todo: maybe pattern match the CCompound constructor here? concatMap (\stmt -> cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmt) stmts -- fn, K, \bar{\Delta}, \bar{b} |-_l s => S cps_trans_stmt :: Bool -> -- ^ is return type void S.Set Ident -> -- ^ local vars S.Set Ident -> -- ^ formal args ContextName -> Ident -> -- ^ fname Ident -> -- ^ K -- ^ \bar{\Delta} become part of the labelled block flag (loop) M.Map Ident LabeledBlock -> -- ^ \bar{b} Ident -> -- ^ label for the current block Bool -> -- ^ whether label \in \Delta (is it a loop block) Visitors -> Exits -> AST.CCompoundBlockItem N.NodeInfo -> [AST.CCompoundBlockItem N.NodeInfo] {- l_i : { \bar{i} ; s } \in \bar{b} l, l_i |- \bar{i} => x1 = e1; ...; xn =en; ----------------------------------------------------------------------------- (GT1) fn, K, \bar{\Delta}, \bar{b} |-_l goto l_i => x1 = e1; ...; xn = en ; fnl_{i}(k) -} -- note that our target is C, hence besides k, the function call include argument such as context cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CGoto li nodeInfo)) = case M.lookup li lb_map of { Just lb | not (null (lb_phis lb)) -> let asgmts = cps_trans_phis ctxtName ident li (lb_phis lb) fname' = fname `app` li args = [ cvar k , cvar (iid ctxtParamName)] funcall = case M.lookup ident visitors of -- in case it is the last block of descending from the loop-if then branch, we call (*k)(ctxt) instead { Just loop_lbl | li == loop_lbl -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar k) [cvar (iid ctxtParamName)] N.undefNode)) N.undefNode) ; _ -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar fname') args N.undefNode)) N.undefNode) } in asgmts ++ [ funcall ] {- l_i : { s } \in \bar{b} ----------------------------------------------------------------------------- (GT2) fn, K, \bar{\Delta}, \bar{b} |-_l goto l_i => fnl_{i}(k) -} | otherwise -> let fname' = fname `app` li args = [ cvar k , cvar (iid ctxtParamName) ] funcall = case M.lookup ident visitors of -- in case it is the last block of descending from the loop-if then branch, we call (*k)(ctxt) instead { Just loop_lbl | li == loop_lbl -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar k) [cvar (iid ctxtParamName)] N.undefNode)) N.undefNode) ; _ -> AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar fname') args N.undefNode)) N.undefNode) } in [ funcall ] ; Nothing -> error "cps_trans_stmt failed at a non existent label." } cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CExpr (Just e) nodeInfo)) = case e of -- todo: deal with array element assignment, we need to assign the array first. we should do it at the block level { AST.CAssign op lval rval ni -> {- x => X; e => E; fn, K, \bar{\Delta}, \bar{b} |-_l s => S ----------------------------------------------------------------------------- (SeqAssign) fn, K, \bar{\Delta}, \bar{b} |-_l x = e;s => X = E;S -} let e' = cps_trans_exp localVars fargs ctxtName e in [AST.CBlockStmt (AST.CExpr (Just e') nodeInfo)] ; _ -> {- e => E; fn, K, \bar{\Delta}, \bar{b} |-_l s => S ----------------------------------------------------------------------------- (SeqE) fn, K, \bar{\Delta}, \bar{b} |-_l e;s => E;S -} let e' = cps_trans_exp localVars fargs ctxtName e in [AST.CBlockStmt (AST.CExpr (Just e') nodeInfo)] } {- ----------------------------------------------------------------------------- (returnNil) fn, K, \bar{\Delta}, \bar{b} |-_l return; => id(); -} -- C does not support higher order function. -- K is passed in as a formal arg -- K is a pointer to function -- updated: change from K(); to id(); because of return in a loop, (see noreturn.c) cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CReturn Nothing nodeInfo)) = let funcall = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "id"))) [(cvar (iid ctxtParamName))] N.undefNode)) N.undefNode) in [ funcall ] {- e => E ----------------------------------------------------------------------------- (returnE) fn, K, \bar{\Delta}, \bar{b} |-_l return e; => x_r = E; id() -} -- C does not support higher order function. -- x_r and K belong to the contxt -- K is a pointer to function cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CReturn (Just e) nodeInfo)) | isReturnVoid = let funcall = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "id"))) [(cvar (iid ctxtParamName))] N.undefNode)) N.undefNode) in [ funcall ] | otherwise = let funcall = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid "id"))) [(cvar (iid ctxtParamName))] N.undefNode)) N.undefNode) e' = cps_trans_exp localVars fargs ctxtName e assign = ((cvar (iid ctxtParamName)) .->. (iid "func_result")) .=. e' in [ AST.CBlockStmt (AST.CExpr (Just assign) nodeInfo), funcall ] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CIf exp trueStmt mbFalseStmt nodeInfo)) {- l \in \Delta e => E ------------------------------------------------------------------------------------------------------- (IfLoop) fn, K, \bar{\Delta}, \bar{b} |-_l if (e) { goto l1 } else { goto l2 } => loop(() => E, f_l1 ,f_l2, k) ; -} -- in C, f_l1 and f_l2 need to be passed in as address & -- we need to 1. insert pop(ctxt) in f_l2 -- 2. let f_l3 be the closest descendant of f_l1 that call f_l(k,ctxt), replace the call by (*k)(ctxt) -- for 1, we can create a map to keep track of all the l2 -- for 2, we can perform a check at any l3 where it contains a "goto l;", look up l we find l1 is the true branch visitor -- we need to check whether l1 sdom l3, if so, replace "goto l" by (*k()) | inDelta = let exp' = cps_trans_exp localVars fargs ctxtName exp (lbl_tr, lb_tr) = case trueStmt of { AST.CGoto lbl _ -> case M.lookup lbl lb_map of { Nothing -> error "cps_trans_stmt error: label block is not found in the true statement in a loop." ; Just lb -> (lbl, lb) } ; _ -> error "cps_trans_stmt error: the true statement in a looping if statement does not contain goto" } asgmts_tr = cps_trans_phis ctxtName ident lbl_tr (lb_phis lb_tr) (lbl_fl, lb_fl) = case mbFalseStmt of { Just (AST.CGoto lbl _) -> case M.lookup lbl lb_map of { Nothing -> error "cps_trans_stmt error: label block is not found in the false statement in a loop." ; Just lb -> (lbl, lb) } ; _ -> error "cps_trans_stmt error: the false statement in a looping if statement does not contain goto" } asgmts_fl = cps_trans_phis ctxtName ident lbl_fl (lb_phis lb_fl) -- supposed to push asgmts_tr and asgmnts_fl to before f_l1 and f_l2, but does not work here. push_args :: [AST.CExpression N.NodeInfo] push_args = [ AST.CUnary AST.CAdrOp (cvar $ fname `app` (iid "cond") `app` ident) N.undefNode , AST.CUnary AST.CAdrOp (cvar (fname `app` lbl_tr)) N.undefNode , AST.CUnary AST.CAdrOp (cvar (fname `app` lbl_fl)) N.undefNode , cvar k , cvar (iid ctxtParamName) ] push = fname `app` (iid "push") call_push = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar push) push_args N.undefNode)) N.undefNode) loop = fname `app` iid "loop__entry" loop_args = [ (cvar (iid ctxtParamName) .->. (iid "loop_conds")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , (cvar (iid ctxtParamName) .->. (iid "loop_visitors")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , (cvar (iid ctxtParamName) .->. (iid "loop_exits")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , (cvar (iid ctxtParamName) .->. (iid "loop_ks")) .!!. (cvar (iid ctxtParamName) .->. (iid currStackSizeName)) , cvar (iid ctxtParamName) ] call_loop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar loop) loop_args N.undefNode)) N.undefNode) in [ call_push, call_loop ] {- l \not \in \Delta e => E fn, K, \bar{\Delta}, \bar{b} |-_l s1 => S1 fn, K, \bar{\Delta}, \bar{b} |-_l s2 => S2 --------------------------------------------------------------------------------------------- (IfNotLoop) fn, K, \bar{\Delta}, \bar{b} |-_l if (e) { s1 } else { s2 } => if (E) { S1 } else { S2 } ; -} | otherwise = let trueStmt' = case trueStmt of { AST.CCompound ids items ni -> AST.CCompound ids (cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits items) ni ; _ -> case cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt trueStmt) of { [ AST.CBlockStmt trueStmt'' ] -> trueStmt'' ; items -> AST.CCompound [] items N.undefNode } } mbFalseStmt' = case mbFalseStmt of { Nothing -> Nothing ; Just (AST.CCompound ids items ni) -> Just $ AST.CCompound ids (cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits items) ni ; Just falseStmt -> Just $ case cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt falseStmt) of { [ AST.CBlockStmt falseStmt'' ] -> falseStmt'' ; items -> AST.CCompound [] items N.undefNode } } exp' = cps_trans_exp localVars fargs ctxtName exp in [AST.CBlockStmt (AST.CIf exp' trueStmt' mbFalseStmt' nodeInfo)] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits (AST.CBlockStmt (AST.CCompound ids stmts nodeInfo)) = -- todo: do we need to do anything with the ids (local labels)? let stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmts in [AST.CBlockStmt (AST.CCompound ids stmts' nodeInfo)] cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k lb_map ident inDelta visitors exits stmt = error ("cps_trans_stmt error: unhandled case" ++ (show stmt)) -- (render $ pretty stmt)) cps_trans_phis :: ContextName -> Ident -> -- ^ source block label (where goto is invoked) Ident -> -- ^ destination block label (where goto is jumping to) [( Ident -- ^ var being redefined , [(Ident, Maybe Ident)])] -> -- ^ incoming block x renamed variables [AST.CCompoundBlockItem N.NodeInfo] cps_trans_phis ctxtName src_lb dest_lb ps = map (cps_trans_phi ctxtName src_lb dest_lb) ps {- --------------------------------------- l_s, l_d |- \bar{i} => \bar{x = e} -} cps_trans_phi :: ContextName -> Ident -> -- ^ source block label (where goto is invoked) Ident -> -- ^ destination block label (where goto is jumping to) (Ident, [(Ident, Maybe Ident)]) -> AST.CCompoundBlockItem N.NodeInfo cps_trans_phi ctxtName src_lb dest_lb (var, pairs) = case lookup src_lb pairs of -- look for the matching label according to the source label { Nothing -> error "cps_trans_phi failed: can't find the source label from the incoming block labels." ; Just redefined_lb -> -- lbl in which the var is redefined (it could be the precedence of src_lb) let lhs = (cvar (iid ctxtParamName)) .->. (var `app` dest_lb) rhs = (cvar (iid ctxtParamName)) .->. case redefined_lb of { Just l -> (var `app` l) ; Nothing -> var } in AST.CBlockStmt (AST.CExpr (Just (lhs .=. rhs)) N.undefNode) -- todo check var has been renamed with label } -- e => E {- --------- (ExpVal) v => V e => E, e_i => E_i -------------------------- (ExpApp) e(\bar{e}) => E(\bar{E}) -} -- it seems just to be identical -- for C target, we need to rename x to ctxt->x cps_trans_exp :: S.Set Ident -> S.Set Ident -> ContextName -> AST.CExpression N.NodeInfo -> AST.CExpression N.NodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAssign op lhs rhs nodeInfo) = AST.CAssign op (cps_trans_exp localVars fargs ctxtName lhs) (cps_trans_exp localVars fargs ctxtName rhs) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComma es nodeInfo) = AST.CComma (map (cps_trans_exp localVars fargs ctxtName) es) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCond e1 Nothing e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) Nothing (cps_trans_exp localVars fargs ctxtName e3) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCond e1 (Just e2) e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) (Just $ cps_trans_exp localVars fargs ctxtName e2) (cps_trans_exp localVars fargs ctxtName e3) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CBinary op e1 e2 nodeInfo) = AST.CBinary op (cps_trans_exp localVars fargs ctxtName e1) (cps_trans_exp localVars fargs ctxtName e2) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCast decl e nodeInfo) = AST.CCast decl (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CUnary op e nodeInfo) = AST.CUnary op (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CSizeofExpr e nodeInfo) = AST.CSizeofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CSizeofType decl nodeInfo) = AST.CSizeofType decl nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAlignofExpr e nodeInfo) = AST.CAlignofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CAlignofType decl nodeInfo) = AST.CAlignofType decl nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComplexReal e nodeInfo) = AST.CComplexReal (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CComplexImag e nodeInfo) = AST.CComplexImag (cps_trans_exp localVars fargs ctxtName e) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CIndex arr idx nodeInfo) = AST.CIndex (cps_trans_exp localVars fargs ctxtName arr) (cps_trans_exp localVars fargs ctxtName idx) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CCall f args nodeInfo) = AST.CCall (cps_trans_exp localVars fargs ctxtName f) (map (cps_trans_exp localVars fargs ctxtName) args) nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CMember e ident deref nodeInfo) = AST.CMember (cps_trans_exp localVars fargs ctxtName e) ident deref nodeInfo cps_trans_exp localVars fargs ctxtName (AST.CVar id _) = case unApp id of { Nothing -> cvar id ; Just id' | id' `S.member` (localVars `S.union` fargs) -> -- let io = unsafePerformIO $ print (localVars `S.union` fargs) >> print id' -- in io `seq` (cvar (iid ctxtParamName)) .->. id | otherwise -> cvar id -- global } cps_trans_exp localVars fargs ctxtName (AST.CConst c) = AST.CConst c cps_trans_exp localVars fargs ctxtName (AST.CCompoundLit decl initList nodeInfo) = AST.CCompoundLit decl initList nodeInfo -- todo check this cps_trans_exp localVars fargs ctxtName (AST.CStatExpr stmt nodeInfo ) = AST.CStatExpr stmt nodeInfo -- todo GNU C compount statement as expr cps_trans_exp localVars fargs ctxtName (AST.CLabAddrExpr ident nodeInfo ) = AST.CLabAddrExpr ident nodeInfo -- todo cps_trans_exp localVars fargs ctxtName (AST.CBuiltinExpr builtin ) = AST.CBuiltinExpr builtin -- todo build in expression {- top level translation p => P t => T x => X ti => Ti xi => Xi di => Di \bar{b} |- \bar{\Delta} k, \bar{\Delta} |- \bar{b} => \bar{P} P1 = void f1 (void => void k) { B1 } ------------------------------------------------------------------------ |- t x (\bar{t x}) {\bar{d};\bar{b}} => T X (\bar{T X}) {\bar{D}; T rx; \bar{P}; f1(id); return rx; } -} -- our target language C differs from the above specification. -- 1. the top function's type signature is not captured within SSA -- 2. \Delta is captured as the loop flag in LabaledBlock -- 3. there is no lambda expression, closure needs to be created as a context -- aux function that has type (void => void) => void should be in fact -- (void => void, ctxt*) => void -- 4. \bar{D} should be the context malloc and initialization -- 5. all the formal args should be copied to context ssa2cps :: (AST.CFunctionDef N.NodeInfo) -> SSA -> CPS ssa2cps fundef (SSA scopedDecls labelledBlocks sdom local_decl_vars fargs) = let -- scraping the information from the top level function under obfuscation funName = case getFunName fundef of { Just s -> s ; Nothing -> "unanmed" } formalArgDecls :: [AST.CDeclaration N.NodeInfo] formalArgDecls = getFormalArgs fundef formalArgIds :: [Ident] formalArgIds = concatMap (\declaration -> getFormalArgIds declaration) formalArgDecls (returnTy,ptrArrs) = getFunReturnTy fundef isReturnVoid = isVoidDeclSpec returnTy ctxtStructName = funName ++ "Ctxt" -- the context struct declaration context = mkContext ctxtStructName labelledBlocks formalArgDecls scopedDecls returnTy ptrArrs local_decl_vars fargs ctxtName = map toLower ctxtStructName -- alias name is inlower case and will be used in the the rest of the code -- finding the visitor labels and the exit labels visitors = allVisitors sdom labelledBlocks exits = allExits labelledBlocks -- all the conditional function conds = allLoopConds local_decl_vars fargs ctxtName funName labelledBlocks -- loop_cps, loop_lambda, id and pop and push loop_cps = loopCPS ctxtName funName lambda_loop_cps = lambdaLoopCPS ctxtName funName id_cps = idCPS ctxtName funName push_cps = pushCPS ctxtName funName pop_cps = popCPS ctxtName funName -- all the "nested/helper" function declarations -- todo: packing all the variable into a record ps = cps_trans_lbs isReturnVoid local_decl_vars fargs ctxtName (iid funName) {- (iid "id") -} visitors exits labelledBlocks -- all function signatures funcSignatures = map funSig (ps ++ conds ++ [loop_cps, lambda_loop_cps, id_cps, push_cps, pop_cps, fundef]) -- include the source func, in case of recursion main_decls = -- 1. malloc the context obj in the main func -- ctxtTy * ctxt = (ctxtTy *) malloc(sizeof(ctxtTy)); [ AST.CBlockDecl (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Just (AST.CInitExpr (AST.CCast (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode) (AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CSizeofType (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [] N.undefNode) N.undefNode] N.undefNode) N.undefNode) N.undefNode),Nothing)] N.undefNode) ] main_stmts = -- 2. initialize the counter-part in the context of the formal args -- forall arg. ctxt->arg_label0 = arg [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (arg `app` (iid $ labPref ++ "0" ))) .=. (AST.CVar arg N.undefNode))) N.undefNode) | arg <- formalArgIds] ++ -- 3. initialize the collection which are the local vars, e.g. a locally declared array -- int a[3]; -- will be reinitialized as ctxt->a_0 = (int *)malloc(sizeof(int)*3); [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (var `app` (iid $ labPref ++ "0" ))) .=. rhs)) N.undefNode) | scopedDecl <- scopedDecls , isJust (containerDeclToInit scopedDecl) , let (Just (var,rhs)) = containerDeclToInit scopedDecl ] ++ -- 4. initialize the context->curr_stack_size = 0; [ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (iid currStackSizeName) .=. (AST.CConst (AST.CIntConst (cInteger 0) N.undefNode))))) N.undefNode) ] ++ -- 3. calling block 0 [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (AST.CVar ((iid funName) `app` (iid (labPref ++ "0" ))) N.undefNode) [ AST.CUnary AST.CAdrOp (AST.CVar ((iid funName) `app` (iid "id")) N.undefNode) N.undefNode , AST.CVar (iid ctxtParamName) N.undefNode ] N.undefNode)) N.undefNode) , if isReturnVoid then AST.CBlockStmt (AST.CReturn Nothing N.undefNode) else AST.CBlockStmt (AST.CReturn (Just $ (cvar (iid ctxtParamName)) .->. (iid "func_result")) N.undefNode) ] main_func = case fundef of { AST.CFunDef tySpecfs declarator decls _ nodeInfo -> AST.CFunDef tySpecfs declarator decls (AST.CCompound [] (main_decls ++ main_stmts) N.undefNode) nodeInfo } in CPS main_decls main_stmts funcSignatures (ps ++ conds ++ [loop_cps, lambda_loop_cps, id_cps, push_cps, pop_cps]) context main_func -- ^ turn a scope declaration into a rhs initalization. -- ^ refer to local_array.c containerDeclToInit :: AST.CDeclaration N.NodeInfo -> Maybe (Ident, AST.CExpression N.NodeInfo) containerDeclToInit (AST.CDecl typespecs tripls nodeInfo0) = case tripls of { (Just decl@(AST.CDeclr (Just arrName) [arrDecl] _ _ _), _, _):_ -> case arrDecl of { AST.CArrDeclr _ (AST.CArrSize _ size) _ -> let ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode) [AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode cast = AST.CCast ptrToTy malloc N.undefNode in Just (arrName, cast) ; _ -> Nothing } ; _ -> Nothing } -- ^ get all visitor labels from te labeledblocks map allVisitors :: SDom -> M.Map NodeId LabeledBlock -> M.Map NodeId NodeId allVisitors sdom lbs = M.fromList $ -- l is a visitor label if (1) succ of l, say l1 is loop, (2) l2, the then-branch label of l1 is sdom'ing l [ (l, succ) | (l, lblk) <- M.toList lbs , succ <- lb_succs lblk , case M.lookup succ lbs of { Nothing -> False ; Just lblk' -> (lb_loop lblk') && (domBy sdom (lb_succs lblk' !! 0) l) } ] -- ^ get all exit labels from the labeledblocks map allExits :: M.Map NodeId LabeledBlock -> M.Map NodeId NodeId allExits lbs = M.fromList $ [ ((lb_succs lblk) !! 1, l) | (l, lblk) <- M.toList lbs , (lb_loop lblk) && (length (lb_succs lblk) > 1) ] -- ^ retrieve all condional test from the loops and turn them into functions allLoopConds :: S.Set Ident -> S.Set Ident -> ContextName -> String -> M.Map NodeId LabeledBlock -> [AST.CFunctionDef N.NodeInfo] allLoopConds local_vars fargs ctxtName fname lbs = concatMap (\(id,lb) -> loopCond local_vars fargs ctxtName fname (id,lb)) (M.toList lbs) loopCond :: S.Set Ident -> S.Set Ident -> ContextName -> String -> (NodeId, LabeledBlock) -> [AST.CFunctionDef N.NodeInfo] loopCond local_vars fargs ctxtName fname (l,blk) | lb_loop blk = let stmts = lb_stmts blk conds = [ cps_trans_exp local_vars fargs ctxtName e | AST.CBlockStmt (AST.CIf e tt ff _) <- stmts ] formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode decls = [ fun [AST.CTypeSpec boolTy] (iid fname `app` iid "cond" `app` l) [formalArgCtxt] [AST.CBlockStmt (AST.CReturn (Just cond) N.undefNode)] | cond <- conds ] in decls | otherwise = [] -- ^ push {- void push(int (*cond)(struct SortCtxt *), void (*visitor)(void (*k)(struct SortCtxt*), struct SortCtxt*), void (*exit)(void (*k)(struct SortCtxt*), struct SortCtxt*), void (*k)(struct SortCtxt*), sortctxt *ctxt) { ctxt->curr_stack_size = ctxt->curr_stack_size + 1; ctxt->loop_conds[ctxt->curr_stack_size] = cond; ctxt->loop_visitors[ctxt->curr_stack_size] = visitor; ctxt->loop_exits[ctxt->curr_stack_size] = exit; ctxt->loop_ks[ctxt->curr_stack_size] = k; } -} pushCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo pushCPS ctxtName fname = let cond = iid condParamName formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) [(Just (AST.CDeclr (Just cond) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode visitor = iid visitorParamName formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*X)(void (*k)(ctxt*), ctxt*) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([ AST.CDecl [AST.CTypeSpec voidTy] [(Just (AST.CDeclr (Just k) [AST.CPtrDeclr [] N.undefNode ,AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False)) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode , AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ],False)) [] N.undefNode ] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode formalArgVisitor = formalArgX visitor exit = iid exitParamName formalArgExit = formalArgX exit k = iid kParamName formalArgK = AST.CDecl [AST.CTypeSpec voidTy] -- void (*k)(ctxt *) [(Just (AST.CDeclr (Just k) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "push") [formalArgCond, formalArgVisitor, formalArgExit, formalArgK, formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid currStackSizeName)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid currStackSizeName)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_conds")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar cond))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_visitors")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar visitor))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_exits")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar exit))) N.undefNode) , AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid "loop_ks")) .!!. (cvar ctxt .->. (iid currStackSizeName))) .=. (cvar k))) N.undefNode) ] {- void pop(sortctxt *ctxt) { ctxt->curr_stack_size = ctxt->curr_stack_size - 1; } -} popCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo popCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "pop") [formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid currStackSizeName)) .=. (AST.CBinary AST.CSubOp (cvar ctxt .->. (iid currStackSizeName)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode) ] -- ^ loop_cps {- void loop_cps(int (*cond)(sortctxt*), void (*visitor)(void (*k)(sortctxt*), sortctxt*), void (*exit)(void (*k)(sortctxt*), sortctxt*), void (*k)(sortctxt *), sortctxt* ctxt) { if ((*cond)(ctxt)) { (*visitor)(&lambda_loop_cps, ctxt); } else { (*exit)(k,ctxt); } } -} loopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo loopCPS ctxtName fname = let cond = iid condParamName formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) [(Just (AST.CDeclr (Just cond) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode visitor = iid visitorParamName formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*X)(void (*k)(ctxt*), ctxt*) [(Just (AST.CDeclr (Just x) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([ AST.CDecl [AST.CTypeSpec voidTy] [(Just (AST.CDeclr (Just k) [AST.CPtrDeclr [] N.undefNode ,AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False)) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode , AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ],False)) [] N.undefNode ] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode formalArgVisitor = formalArgX visitor exit = iid exitParamName formalArgExit = formalArgX exit k = iid kParamName formalArgK = AST.CDecl [AST.CTypeSpec voidTy] -- void (*k)(ctxt *) [(Just (AST.CDeclr (Just k) [ AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode], False) ) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "loop__entry") [formalArgCond, formalArgVisitor, formalArgExit, formalArgK, formalArgCtxt] [ AST.CBlockStmt (AST.CIf (funCall (ind (cvar cond)) [(cvar ctxt)]) (AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar visitor)) [ adr (cvar (iid fname `app` iid "lambda_loop")) , cvar ctxt ]) N.undefNode ) ] N.undefNode) (Just (AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar exit)) [ cvar k , cvar ctxt ]) N.undefNode) ] N.undefNode)) N.undefNode) ] {- void lambda_loop_cps(sortctxt* ctxt) { loop_cps(ctxt->loop_conds[ctxt->loop_stack_size], ctxt->loop_visitors[ctxt->loop_stack_size], ctxt->loop_exits[ctxt->loop_stack_size], ctxt->loop_ks[ctxt->loop_stack_size], ctxt); } -} lambdaLoopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo lambdaLoopCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "lambda_loop") [formalArgCtxt] [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid "loop__entry")) [ ((cvar ctxt) .->. (iid "loop_conds")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , ((cvar ctxt) .->. (iid "loop_visitors")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , ((cvar ctxt) .->. (iid "loop_exits")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , ((cvar ctxt) .->. (iid "loop_ks")) .!!. ((cvar ctxt) .->. (iid currStackSizeName)) , (cvar ctxt) ] N.undefNode)) N.undefNode) ] {- void id(sortctxt *ctxt) { return; } -} idCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo idCPS ctxtName fname = let ctxt = iid ctxtParamName formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt [(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode in fun [AST.CTypeSpec voidTy] (iid fname `app` iid "id") [formalArgCtxt] [ AST.CBlockStmt (AST.CReturn Nothing N.undefNode) ] -- ^ generate function signature declaration from function definition funSig :: AST.CFunctionDef N.NodeInfo -> AST.CDeclaration N.NodeInfo funSig (AST.CFunDef tySpecfs declarator op_decls stmt nodeInfo) = AST.CDecl tySpecfs [(Just declarator, Nothing, Nothing)] N.undefNode -- ^ making the context struct declaration mkContext :: String -> -- ^ context name M.Map Ident LabeledBlock -> -- ^ labeled blocks [AST.CDeclaration N.NodeInfo] -> -- ^ formal arguments [AST.CDeclaration N.NodeInfo] -> -- ^ local variable declarations [AST.CDeclarationSpecifier N.NodeInfo] -> -- ^ return Type [AST.CDerivedDeclarator N.NodeInfo] -> -- ^ the pointer or array postfix S.Set Ident -> S.Set Ident -> AST.CDeclaration N.NodeInfo mkContext name labeledBlocks formal_arg_decls local_var_decls returnType ptrArrs local_decl_vars fargs = let structName = iid name ctxtAlias = AST.CDeclr (Just (internalIdent (map toLower name))) [] Nothing [] N.undefNode attrs = [] stackSize = 20 isReturnVoid = isVoidDeclSpec returnType unaryFuncStack ty fname = AST.CDecl [AST.CTypeSpec ty] -- void (*loop_ks[2])(struct FuncCtxt*); -- todo : these are horrible to read, can be simplified via some combinators [(Just (AST.CDeclr (Just $ iid fname) [ AST.CArrDeclr [] (AST.CArrSize False (AST.CConst (AST.CIntConst (cInteger stackSize) N.undefNode))) N.undefNode , AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode) ,Nothing,Nothing)] N.undefNode binaryFuncStack fname = AST.CDecl [AST.CTypeSpec voidTy] [(Just (AST.CDeclr (Just $ iid fname) [ AST.CArrDeclr [] (AST.CArrSize False (AST.CConst (AST.CIntConst (cInteger stackSize) N.undefNode))) N.undefNode , AST.CPtrDeclr [] N.undefNode , AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CVoidType N.undefNode)] [(Just (AST.CDeclr (Just (iid kParamName)) [AST.CPtrDeclr [] N.undefNode, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode, AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode) ,Nothing,Nothing)] N.undefNode ksStack = unaryFuncStack voidTy "loop_ks" condStack = unaryFuncStack intTy "loop_conds" visitorStack = binaryFuncStack "loop_visitors" exitStack = binaryFuncStack "loop_exits" currStackSize = AST.CDecl [AST.CTypeSpec intTy] [(Just (AST.CDeclr (Just $ iid currStackSizeName) [] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode funcResult | isReturnVoid = [] | otherwise = [AST.CDecl returnType [(Just (AST.CDeclr (Just $ iid "func_result") ptrArrs Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode] decls' = -- formal_arg_decls ++ -- note: we remove local decl duplicate, maybe we should let different label block to have different type decl in the ctxt, see test/scoped_dup_var.c concatMap (\d -> renameDeclWithLabeledBlocks d labeledBlocks local_decl_vars fargs) (nubBy declLHSEq $ map (cps_trans_declaration . dropConstTyQual) (formal_arg_decls ++ local_var_decls)) ++ [ksStack, condStack, visitorStack, exitStack, currStackSize] ++ funcResult tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode) structDef = AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) (Just decls') attrs N.undefNode) N.undefNode) in AST.CDecl [tyDef, structDef] [(Just ctxtAlias, Nothing, Nothing)] N.undefNode -- eq for the declaration nub, see the above declLHSEq (AST.CDecl declSpecifiers1 trips1 _) (AST.CDecl declSpecifiers2 trips2 _) = let getIds trips = map (\(mb_decl, mb_init, mb_size) -> case mb_decl of { Just (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) -> mb_id ; Nothing -> Nothing }) trips in (getIds trips1) == (getIds trips2) -- we need to drop the constant type specifier since we need to initialize them in block 0, see test/const.c dropConstTyQual :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo dropConstTyQual decl = case decl of { AST.CDecl declSpecifiers trips ni -> AST.CDecl (filter (not . isConst) declSpecifiers) trips ni } where isConst (AST.CTypeQual (AST.CConstQual _)) = True isConst _ = False -- renameDeclWithLabels :: AST.CDeclaration N.NodeInfo -> [Ident] -> [AST.CDeclaration N.NodeInfo] -- renameDeclWithLabels decl labels = map (renameDeclWithLabel decl) labels renameDeclWithLabeledBlocks :: AST.CDeclaration N.NodeInfo -> M.Map Ident LabeledBlock -> S.Set Ident -> S.Set Ident -> [AST.CDeclaration N.NodeInfo] renameDeclWithLabeledBlocks decl labeledBlocks local_decl_vars fargs = let idents = getFormalArgIds decl in do { ident <- idents ; (lb,blk) <- M.toList labeledBlocks ; if (null (lb_preds blk)) || -- it's the entry block (ident `elem` (lb_lvars blk)) || -- the var is in the lvars (ident `elem` (map fst (lb_phis blk))) || -- the var is in the phi (ident `elem` (lb_containers blk)) -- the var is one of the lhs container ids such as array or members then return (renameDeclWithLabel decl lb local_decl_vars fargs) else [] } renameDeclWithLabel decl label local_decl_vars fargs = let rnState = RSt label M.empty [] [] local_decl_vars fargs in case renamePure rnState decl of { (decl', rstate', containers) -> decl' } {- translation t => T ----------- int => int ----------- bool => bool t => t ------------- t* => T* t => T ------------ t[] => T* ------------- void => void -} cps_trans_declaration :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo cps_trans_declaration (AST.CDecl declSpecifiers trips ni) = AST.CDecl (map cps_trans_declspec declSpecifiers) (map (\(mb_decl, mb_init, mb_size) -> let mb_decl' = case mb_decl of { Nothing -> Nothing ; Just decl -> Just (cps_trans_decltr decl) } in (mb_decl', mb_init, mb_size)) trips) ni -- lhs of a declaration cps_trans_declspec :: AST.CDeclarationSpecifier N.NodeInfo -> AST.CDeclarationSpecifier N.NodeInfo cps_trans_declspec (AST.CStorageSpec storageSpec) = AST.CStorageSpec storageSpec -- auto, register, static, extern etc cps_trans_declspec (AST.CTypeSpec tySpec) = AST.CTypeSpec tySpec -- simple type, void, int, bool etc cps_trans_declspec (AST.CTypeQual tyQual) = AST.CTypeQual tyQual -- qual, CTypeQual, CVolatQual, etc -- cps_trans_declspec (AST.CFunSpec funSpec) = AST.CFunSpec funSpec -- todo -- cps_trans_declspec (AST.CAlignSpec alignSpec) = AST.CAlignSpec alignSpec -- todo -- rhs (after the variable) cps_trans_decltr :: AST.CDeclarator N.NodeInfo -> AST.CDeclarator N.NodeInfo cps_trans_decltr (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) = AST.CDeclr mb_id (map cps_trans_derived_decltr derivedDeclarators) mb_strLit attrs nInfo cps_trans_derived_decltr :: AST.CDerivedDeclarator N.NodeInfo -> AST.CDerivedDeclarator N.NodeInfo cps_trans_derived_decltr (AST.CPtrDeclr tyQuals ni) = AST.CPtrDeclr tyQuals ni cps_trans_derived_decltr (AST.CArrDeclr tyQuals arrSize ni) = AST.CPtrDeclr tyQuals ni cps_trans_derived_decltr (AST.CFunDeclr either_id_decls attrs ni) = AST.CFunDeclr either_id_decls attrs ni {- data CDeclarationSpecifier a = CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef | CTypeSpec (CTypeSpecifier a) -- ^ type name | CTypeQual (CTypeQualifier a) -- ^ type qualifier | CFunSpec (CFunctionSpecifier a) -- ^ function specifier | CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-}) -}
luzhuomi/cpp-obs
Language/C/Obfuscate/CPS_old.hs
apache-2.0
58,743
803
20
16,794
12,515
7,063
5,452
542
14
module HERMIT.Set.Life where import Data.Set as Set import Data.List as List (nub,(\\)) import Life.Types -- Standard implementation type Board = LifeBoard Config [Pos] -- The new data structure to be used in the implementation type Board' = LifeBoard Config (Set Pos) -- Transformations required by hermit for worker/wrapper conversions -- repb and absb change the underlying board field {-# NOINLINE repb #-} repb :: [Pos] -> Set Pos repb = fromList {-# NOINLINE absb #-} absb :: Set Pos -> [Pos] absb = toList -- repB and absB change the entire Board structure {-# NOINLINE repB #-} repB :: Board -> Board' repB b = LifeBoard (config b) $ repb (board b) {-# NOINLINE absB #-} absB :: Board' -> Board absB b = LifeBoard (config b) $ absb (board b) -- rep for "alive" repBx :: (Board -> Scene) -> Board' -> Scene repBx f b = f (absB b) -- abs for "alive" absBx :: (Board' -> Scene) -> Board -> Scene absBx f b = f (repB b) --"isAlive", "isEmpty" repBpb :: (Board -> Pos -> Bool) -> Board' -> Pos -> Bool repBpb f b p = f (absB b) p absBpb :: (Board' -> Pos -> Bool) -> Board -> Pos -> Bool absBpb f b p = f (repB b) p --"liveneighbs" repBpi :: (Board -> Pos -> Int) -> Board' -> Pos -> Int repBpi f b p = f (absB b) p absBpi :: (Board' -> Pos -> Int) -> Board -> Pos -> Int absBpi f b p = f (repB b) p -- rep for "empty" repcB :: (Config -> Board) -> Config -> Board' repcB f c = repB (f c) -- abs for "empty" abscB :: (Config -> Board') -> Config -> Board abscB f c = absB (f c) -- rep for "inv" reppBB :: (Pos -> Board -> Board) -> Pos -> Board' -> Board' reppBB f x b = repB (f x (absB b)) -- abs for "inv" abspBB :: (Pos -> Board' -> Board') -> Pos -> Board -> Board abspBB f x b = absB (f x (repB b)) -- rep for "births", "survivors", "next" repBB :: (Board -> Board) -> Board' -> Board' repBB f b = repB (f (absB b)) -- abs for "births", "survivors", "next" absBB :: (Board' -> Board') -> Board -> Board absBB f b = absB (f (repB b)) -- GHC Rules for HERMIT -- Simplification rules {-# RULES "repb/absb-fusion" [~] forall b. repb (absb b) = b "LifeBoard-reduce" [~] forall b. LifeBoard (config b) (board b) = b #-} --Code replacement rules {-# RULES "empty-l/empty-s" [~] repb [] = Set.empty "not-elem/notMember" [~] forall p b. not (elem p (absb b)) = notMember p b "elem/member" [~] forall p b. elem p (absb b) = member p b "cons/insert" [~] forall p b. p : (absb b) = absb (insert p b) "filter/delete" [~] forall p b. Prelude.filter ((/=) p) (absb b) = absb (delete p b) "filter-l/filter-s" [~] forall f b. Prelude.filter f (absb b) = absb (Set.filter f b) "nub-concatMap/unions" [~] forall f b. nub (concatMap f (absb b)) = absb (unions (toList (Set.map (fromList . f) b))) "concat/union" [~] forall b1 b2. absb b1 ++ absb b2 = absb (union b1 b2) #-}
ku-fpg/better-life
HERMIT/Set/Life.hs
bsd-2-clause
2,793
0
9
580
773
414
359
-1
-1
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Computations in logarithmic scale. module NLP.Nerf2.LogReal ( LogReal , fromLogReal , logToLogReal , logFromLogReal ) where import Prelude hiding (sum, product) import Data.Vector.Generic.Base import Data.Vector.Generic.Mutable import Data.Binary (Binary) import qualified Data.Vector.Unboxed as U newtype LogReal = LogReal Double deriving ( Show, Read, Eq, Ord, Binary , Vector U.Vector, MVector U.MVector, U.Unbox ) foreign import ccall unsafe "math.h log1p" log1p :: Double -> Double zero :: Double zero = -(1/0) isZero :: Double -> Bool isZero = (zero==) instance Num LogReal where LogReal x * LogReal y = LogReal $ x + y LogReal x + LogReal y | isZero x = LogReal $ y | x > y = LogReal $ x + log1p(exp(y - x)) | otherwise = LogReal $ y + log1p(exp(x - y)) LogReal _ - LogReal _ = error "LogReal: (-) not supported" negate _ = error "LogReal: negate not supported" abs = id signum (LogReal x) | x > zero = 1 | otherwise = 0 fromInteger x | x == 0 = LogReal zero | x > 0 = LogReal . log . fromInteger $ x | otherwise = error "LogReal: fromInteger on negative argument" instance Fractional LogReal where LogReal x / LogReal y = LogReal $ x - y fromRational x | x == 0 = LogReal zero | x > 0 = LogReal . log . fromRational $ x | otherwise = error "LogReal: fromRational on negative argument" -- This is simply a polymorphic version of the 'LogReal' data -- constructor. We present it mainly because we hide the constructor -- in order to make the type a bit more opaque. If the polymorphism -- turns out to be a performance liability because the rewrite rules -- can't remove it, then we need to rethink all four -- constructors\/destructors. -- -- | Constructor which assumes the argument is already in the -- log-domain. logToLogReal :: Double -> LogReal logToLogReal = LogReal -- | Return our log-domain value back into normal-domain. fromLogReal :: LogReal -> Double fromLogReal (LogReal x) = exp x -- | Return the log-domain value itself without conversion. logFromLogReal :: LogReal -> Double logFromLogReal (LogReal x) = x
kawu/nerf-proto
src/NLP/Nerf2/LogReal.hs
bsd-2-clause
2,300
0
12
546
602
311
291
49
1
----------------------------------------------------------------------------- -- | -- Module : ByteFields -- Copyright : (c) Conrad Parker 2006 -- License : BSD-style -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Utilities for handling byte-aligned fields -- ----------------------------------------------------------------------------- module Codec.Container.Ogg.ByteFields ( be64At, be32At, be16At, le64At, le32At, le16At, u8At, le64Fill, le32Fill, le16Fill, u8Fill ) where import Data.Int (Int64) import Data.Word import qualified Data.ByteString.Lazy as L beNAt :: Integral a => Int64 -> Int64 -> L.ByteString -> a beNAt len off s = fromTwosComp $ reverse $ L.unpack (L.take len (L.drop off s)) be64At :: Integral a => Int64 -> L.ByteString -> a be64At = beNAt 8 be32At :: Integral a => Int64 -> L.ByteString -> a be32At = beNAt 4 be16At :: Integral a => Int64 -> L.ByteString -> a be16At = beNAt 2 leNAt :: Integral a => Int64 -> Int64 -> L.ByteString -> a leNAt len off s = fromTwosComp $ L.unpack (L.take len (L.drop off s)) le64At :: Integral a => Int64 -> L.ByteString -> a le64At = leNAt 8 le32At :: Integral a => Int64 -> L.ByteString -> a le32At = leNAt 4 le16At :: Integral a => Int64 -> L.ByteString -> a le16At = leNAt 2 u8At :: Integral a => Int64 -> L.ByteString -> a u8At = leNAt 1 -- Generate a ByteString containing the given number leNFill :: Integral a => Int -> a -> L.ByteString leNFill n x | l < n = L.pack $ (i ++ (take (n-l) $ repeat 0x00)) | l > n = error "leNFill too short" | otherwise = L.pack $ i where l = length i i = toTwosComp x le64Fill :: Integral a => a -> L.ByteString le64Fill = leNFill 8 le32Fill :: Integral a => a -> L.ByteString le32Fill = leNFill 4 le16Fill :: Integral a => a -> L.ByteString le16Fill = leNFill 2 u8Fill :: Integral a => a -> L.ByteString u8Fill = leNFill 1 -- | Convert to twos complement, unsigned, little endian toTwosComp :: Integral a => a -> [Word8] toTwosComp x = g $ f x where f y = (fromIntegral y) `divMod` 256 :: (Integer, Integer) g (0,b) = [fromIntegral b] g (a,b) = [fromIntegral b] ++ (g $ f a) -- | Convert from twos complement, unsigned, little endian fromTwosComp :: Integral a => [Word8] -> a fromTwosComp x = foldr (\a b -> fromIntegral a + b*256) 0 x
kfish/hogg
Codec/Container/Ogg/ByteFields.hs
bsd-3-clause
2,417
6
13
528
839
441
398
55
2
{-# LANGUAGE CPP #-} {- Copyright (c) 2008 David Roundy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 Distribution.Franchise.Buildable ( Buildable(..), BuildRule(..), Dependency(..), build, buildWithArgs, buildTarget, bin, etc, man, install, installDoc, installData, installHtml, defaultRule, buildName, build', rm, clean, distclean, addToRule, addDependencies, addTarget, rule, simpleTarget, getBuildable, (|<-), getTarget, Target(..), phony, extraData ) where import Data.List ( sort, isSuffixOf, (\\) ) import System.Environment ( getArgs ) import System.Directory ( doesFileExist, removeFile, getModificationTime ) import Control.Concurrent ( readChan, writeChan, newChan ) import Control.Monad ( when, mplus ) import Distribution.Franchise.Util import Distribution.Franchise.ConfigureState import Distribution.Franchise.StringSet import Distribution.Franchise.Trie import Distribution.Franchise.GhcState ( getBinDir, getEtcDir, getManDir, getDataDir, getDocDir, getHtmlDir ) import Distribution.Franchise.Flags ( FranchiseFlag, handleArgs ) data Dependency = [String] :< [String] infix 2 :< data BuildRule = BuildRule { make :: Dependency -> C (), postinst :: Dependency -> Maybe (C ()), clean0 :: Dependency -> [String] } data Buildable = Dependency :<- BuildRule instance Eq Buildable where (xs:<_:<-_) == (ys:<_:<-_) = fromListS xs == fromListS ys (|<-) :: Dependency -> BuildRule -> Buildable (|<-) = (:<-) infix 1 :<- infix 1 |<- defaultRule :: BuildRule defaultRule = BuildRule (const $ return ()) (const $ Just $ return ()) cleanIt extraData :: String -> String extraData x = "config.d/"++x cleanIt :: Dependency -> [String] cleanIt (_:<[]) = [] cleanIt (xs:<_) = filter (not . isPhony) xs isPhony :: String -> Bool isPhony ('*':r) = case reverse r of ('*':_) -> True _ -> False isPhony _ = False phony :: String -> String phony x | isPhony x = x phony x = '*':x++"*" unphony :: String -> String unphony x = if isPhony x then init $ tail x else x rm :: String -> C () rm f | "/" `isSuffixOf` f = return () rm f = do noRm <- getNoRemove f' <- processFilePath f if not $ null noRm then putV $ "#rm "++f else do io $ removeFile f' putV $ "rm "++f `catchC` \_ -> return () depName :: Dependency -> [String] depName (n :< _) = n buildName :: Buildable -> [String] buildName (d:<-_) = depName d -- | 'build' is at the heart of any Setup.hs build script, and drives -- the entire build process. Its first argument is a list of flags -- you want the Setup.hs script to accept, and the second argument is -- the actual function that configures the build. build :: [C FranchiseFlag] -> C () -> IO () build opts mkbuild = do args <- getArgs buildWithArgs args opts mkbuild #ifndef FRANCHISE_VERSION #define FRANCHISE_VERSION "franchise (unknown)" #endif addPaths :: String -> [FilePath] -> C () addPaths v ps = do ps' <- mapM processFilePath ps addExtraUnique v ps' clean :: [FilePath] -> C () clean = addPaths "to-clean" distclean :: [FilePath] -> C () distclean = addPaths "to-distclean" (</>) :: FilePath -> FilePath -> FilePath "" </> x = x x </> ('/':y) = x </> y x </> y = reverse (dropWhile (=='/') $ reverse x) ++ '/':y -- | add the specified install to the install target. This function -- respects the DESTDIR environment variable, and should therefore be -- used for installing. install :: FilePath -- ^ file or directory to be installed -> FilePath -- ^ install location as an absolute path -> C () install x y = do x' <- processFilePath x addDependencies (phony "build") [x] destdir <- maybe "" id `fmap` getExtraData "destdir" addExtraUnique "to-install" [(x',destdir</>y)] installHelper :: C FilePath -> (FilePath -> FilePath) -> FilePath -> C () installHelper getdir cleanp x = do dir <- getdir install x (dir++"/"++cleanp x) -- | request that the given file be installed in the sysconfdir. This -- location may be modified at configure time via the environment -- variable PREFIX or SYSCONFDIR. etc :: FilePath -> C () etc = installHelper getEtcDir id -- | request that the given file be installed in the bindir. This -- location may be modified at configure time via the environment -- variable PREFIX or BINDIR. bin :: FilePath -> C () bin = installHelper getBinDir basename -- | request that the given file be installed in the mandir in the -- specified section. This location may be modified at configure time -- via the environment variable PREFIX, DATADIR or MANDIR. man :: Int -> FilePath -> C () man section = installHelper (getManDir section) basename -- | install the specified HTML file in an appropriate place for -- documentation. This location may be modified at configure time via -- the environment variables PREFIX, DATADIR, DOCDIR or HTMLDIR. installHtml :: FilePath -> C () installHtml = installHelper getHtmlDir id -- | install the specified file in the documentation location. This -- location may be modified at configure time via the environment -- variable PREFIX, DATADIR or DOCDIR. installDoc :: FilePath -> C () installDoc = installHelper getDocDir id -- | install in the data path. This location may be modified at -- configure time via the environment variable PREFIX or DATADIR. installData :: FilePath -> C () installData = installHelper getDataDir id buildWithArgs :: [String] -> [C FranchiseFlag] -> C () -> IO () buildWithArgs args opts mkbuild = runC $ do putV $ "compiled with franchise version "++FRANCHISE_VERSION rule [phony "clean"] [] $ do toclean <- getExtra "to-clean" mapM_ rm_rf toclean rule [phony "distclean"] [] $ do toclean <- getExtra "to-clean" dist <- getExtra "to-distclean" mapM_ rm_rf (toclean++dist) rule [phony "copy"] [phony "build"] $ do is <- getExtra "to-install" let inst (x, y) = do mkdir (dirname y) cp x y mapM_ inst is rule [phony "uncopy"] [] $ do is <- getExtra "to-install" mapM_ (rm_rf . snd) (is :: [(String,String)]) rule [phony "register"] [] $ return () whenC amInWindows $ do rule ["register.bat", phony "register-script"] [] $ saveAsScript "register.bat" $ build' CannotModifyState (phony "register") rule ["unregister.bat", phony "unregister-script"] [] $ saveAsScript "unregister.bat" $ build' CannotModifyState (phony "unregister") unlessC amInWindows $ do rule ["register.sh", phony "register-script"] [] $ saveAsScript "register.sh" $ build' CannotModifyState (phony "register") rule ["unregister.sh", phony "unregister-script"] [] $ saveAsScript "unregister.sh" $ build' CannotModifyState (phony "unregister") rule [phony "unregister"] [] $ return () rule [phony "install"] [phony "build"] $ do build' CannotModifyState (phony "copy") build' CannotModifyState (phony "register") rule [phony "uninstall"] [] $ do build' CannotModifyState (phony "unregister") build' CannotModifyState (phony "uncopy") if "configure" `elem` args then return () else (do readConfigureState "config.d" putV "reusing old configuration") `catchC` \e -> do putD e putV "Couldn't read old config.d" rm_rf "config.d" putExtra "commandLine" args distclean ["config.d", "franchise.log"] targets <- handleArgs opts runHooks mkbuild writeConfigureState "config.d" putD "Done writinf to config.d" when ("configure" `elem` args) $ putS "configure successful!" mapM_ buildtarget targets where buildtarget t = do mt <- sloppyTarget t case mt of [] -> fail $ "No such target: "++t ["*register*"] -> do putS "{register}" x <- getExtraData "gen-script" let realtarg = maybe "*register*" (const "*register-script*") x build' CannotModifyState realtarg ["*unregister*"] -> do putS "{unregister}" x <- getExtraData "gen-script" let realtarg = maybe "*unregister*" (const "*unregister-script*") x build' CannotModifyState realtarg ["*clean*"] -> do putS "{clean}" build' CannotModifyState "*clean*" clearAllBuilt ["*distclean*"] -> do putS "{distclean}" build' CannotModifyState "*distclean*" clearAllBuilt [tt] -> do putS $ "["++unphony tt++"]" build' CannotModifyState tt ts -> fail $ unlines ["No such target: "++t, "Perhaps you meant one of "++ unwords (map unphony ts)++"?"] needsWork :: String -> C Bool needsWork t = do isb <- isBuilt t if isb then do putD $ t++" is already built!" return False else do mtt <- getTarget t case mtt of Nothing -> do putD $ "marking "++t++" as built since it has no rule" setBuilt t return False Just (Target _ ds _) | nullS ds -> return True -- no dependencies means it always needs work! Just (Target ts ds _) -> do mmt <- (Just `fmap` io (mapM getModificationTime $ filter (not . isPhony) $ t:toListS ts)) `catchC` \_ -> return Nothing case mmt of Nothing -> do putD $ "need work because "++t++ " doesn't exist (or a friend)" return True Just [] -> do putD $ "need work because "++ t ++ " is a phony target." return True Just mt -> do anylater <- anyM (latertime mt) $ toListS ds if anylater then return () else do putD $ unwords $ "Marking":t: "as built since it's older than": toListS ds setBuilt t return anylater where latertime mt y = do ye <- io $ doesFileExist y if not ye then do putD $ "Need work cuz "++y++" don't exist" return True else do mty <- io $ getModificationTime y if mty > maximum mt then putD $ "I need work since "++y++ " is newer than " ++ t else return () return (mty > maximum mt) anyM _ [] = return False anyM f (z:zs) = do b <- f z if b then return True else anyM f zs buildTarget :: String -> C () buildTarget = build' CannotModifyState build' :: CanModifyState -> String -> C () build' cms b = unlessC (isBuilt b) $ -- short circuit if we're already built! do --put $S unwords ("I'm thinking of recompiling...": buildName b) origw <- toListS `fmap` findWork b case origw of [] -> putD "I see nothing here to recompile" _ -> putD $ "I want to recompile all of "++ unwords origw case length origw of 0 -> putD $ "Nothing to recompile for "++b++"." l -> putD $ unwords $ ["Need to recompile ",show l,"for"]++b:["."] chan <- io $ newChan tis <- targetImportances let buildthem _ [] = return () buildthem inprogress w = do putD $ unwords ("I am now wanting to compile":w) loadavgstr <- cat "/proc/loadavg" `catchC` \_ -> return "" let loadavg = case reads loadavgstr of ((n,_):_) -> max 0.0 (n :: Double) _ -> 0.0 fixNumJobs nj = if nj > 1 && loadavg >= 0.5+fromIntegral nj then do putV $ "Throttling jobs with load "++ show loadavg return 1 else return nj njobs <- getNumJobs >>= fixNumJobs (canb'',depb') <- partitionM (canBuildNow (w `addsS` inprogress)) w canb' <- if njobs > 1 then filterDupTargets $ map snd $ sort $ map (\t -> (maybe 0 negate$lookupT t tis,t)) canb'' else filterDupTargets canb'' putD $ unwords $ "I can now build: ": canb' let jobs = max 0 (njobs - lengthS inprogress) canb = take jobs canb' depb = drop jobs canb' ++ (canb'' \\ canb') ++ depb' buildone ttt = forkC cms $ do Just (Target ts xs0 makettt) <- getTarget ttt stillneedswork <- if any (`elemS` ts) $ toListS inprogress then do putD "Already in progress..." return False else needsWork ttt if stillneedswork then do putD $ unlines ["I am making "++ ttt, " This depends on "++ unwords (toListS xs0)] makettt `catchC` \e -> do putV $ errorBuilding e ttt io $ writeChan chan $ Left e io $ writeChan chan $ Right (ttt, ts) else do putD $ "I get to skip one! " ++ ttt io $ writeChan chan $ Right (ttt, ts) case filter (".o" `isSuffixOf`) canb of [] -> return () [_] -> return () tb -> putD $ "I can now build "++ unwords tb mapM_ buildone canb md <- io $ readChan chan case md of Left e -> do putV $ errorBuilding e b fail $ errorBuilding e b Right (d,ts) -> do putD $ "Done building "++ show d mapM_ setBuilt $ d : toListS ts buildthem (delS d (addsS canb $ inprogress)) (depb \\ toListS ts) errorBuilding e "config.d/commandLine" = "configure failed:\n"++e errorBuilding e f | ".depend" `isSuffixOf` f = e errorBuilding e bn = "Error building "++unphony bn++'\n':e filterDupTargets [] = return [] filterDupTargets (t:ts) = do Just (Target xs _ _) <- getTarget t ts' <- filterDupTargets $ filter (not . (`elemS` xs)) ts return (t:ts') buildthem emptyS origw targetImportances :: C (Trie Int) targetImportances = do ts <- getTargets let invertedDeps = foldl invertDep emptyT $ toListT ts invertDep ids (t,Target _ dd _) =inv (toListS dd) ids where inv [] x = x inv (d:ds) x = inv ds $ alterT d addit x addit (Just ss) = Just $ addS t ss addit Nothing = Just $ addS t emptyS gti x [] = x gti ti (t:rest) = case lookupT t ti of Just _ -> gti ti rest _ -> case toListS `fmap` lookupT t invertedDeps of Nothing -> gti (insertT t 0 ti) rest Just ds -> case mapM (`lookupT` ti) ds of Just dsv -> gti (insertT t (1+maximum (0:dsv)) ti) rest Nothing -> gti ti (ds++t:rest) return $ gti emptyT $ toListS $ keysT ts partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a],[a]) partitionM _ [] = return ([],[]) partitionM f (x:xs) = do amok <- f x (ok,notok) <- partitionM f xs return $ if amok then (x:ok,notok) else (ok,x:notok) canBuildNow :: StringSet -> String -> C Bool canBuildNow needwork t = do mt <- getTarget t case (delS t . dependencies) `fmap` mt of Just d -> return $ not $ any (`elemS` needwork) $ toListS d _ -> return True getBuildable :: String -> C (Maybe Buildable) getBuildable t = do allts <- getTargets case lookupT t allts of Just (Target ts ds how) -> return $ Just (t:toListS ts :< toListS ds :<- defaultRule { make = const how }) Nothing -> case lookupT (phony t) allts of Nothing -> return Nothing Just (Target ts ds how) -> return $ Just (phony t:toListS ts :< toListS ds :<- defaultRule { make = const how }) getTarget :: String -> C (Maybe Target) getTarget t = do allts <- getTargets return $ lookupT t allts `mplus` lookupT (phony t) allts clarifyTarget :: String -> C (Maybe String) clarifyTarget t = do allts <- getTargets case lookupT t allts of Just _ -> return $ Just t _ -> case lookupT (phony t) allts of Just _ -> return $ Just (phony t) _ -> return Nothing sloppyTarget :: String -> C [String] sloppyTarget "configure" = return [] sloppyTarget t = do allts <- getTargets return $ if t `elemS` keysT allts then [t] else if phony t `elemS` keysT allts then [phony t] else sloppyLookupKey t allts ++ sloppyLookupKey ('*':t) allts findWork :: String -> C StringSet findWork zzz = do putD $ "findWork called on "++zzz fw emptyS emptyS zzz where fw :: StringSet -> StringSet -> String -> C StringSet fw nw _ t | t `elemS` nw = return nw fw nw done t | t `elemS` done = return nw fw nw done t = do amb <- isBuilt t if amb then return nw else do mt <- getTarget t case mt of Nothing -> return nw Just (Target _ ds _) | nullS ds -> -- no dependencies means it always needs work! return $ addS t nw Just (Target _ ds00 _) -> do let ds0 = toListS ds00 nwds <- lookAtDeps nw ds0 if any (`elemS` nwds) ds0 then return $ addS t nwds else do tooold <- needsWork t if tooold then return $ addS t nwds else return nwds where lookAtDeps nw' [] = return nw' lookAtDeps nw' (d:ds) = do nw2 <- fw nw' (t `addS` done) d lookAtDeps nw2 ds simpleTarget :: String -> C a -> C () simpleTarget outname myrule = addTarget $ [outname] :< [] :<- defaultRule { make = const (myrule >> return ()) } addTarget :: Buildable -> C () addTarget (ts :< ds :<- r) = do withd <- rememberDirectory mapM_ clearBuilt ts ts' <- mapM processFilePathOrTarget ts ds' <- fromListS `fmap` mapM processFilePathOrTarget ds let fixt t = (t, delS t allts) allts = fromListS ts' ts'' = map fixt ts' addt (t,otherTs) = modifyTargets $ insertT t (Target otherTs ds' $ withd $ make r (ts:<ds)) clean $ clean0 r (ts:<ds) case postinst r (ts:<ds) of Just inst -> addToRule (phony "register") $ withd inst Nothing -> return () mapM_ addt ts'' -- | If you want to create a new target, you can do this using 'rule', -- which creates a build target with certain dependencies and a rule -- to do any extra actual building. rule :: [String] -- ^ list of targets simultaneously built by this rule -> [String] -- ^ list of dependencies -> C () -- ^ rule to build this target -> C () rule n deps j = addTarget $ n :< deps |<- defaultRule { make = const j } -- | Add a bit more work to be done when building target. This will -- be done /before/ the function that is already present, and thus may -- be used to prepare the environment in some way. {-# NOINLINE addToRule #-} addToRule :: String -> C () -> C () addToRule t j | unphony t == "install" = addToRule (phony "register") j addToRule targ j = do withd <- rememberDirectory modifyTargets $ adjustT' targ $ \ (Target a b c) -> Target a b (withd j >> c) where adjustT' t f m = case lookupT t m of Just _ -> adjustT t f m Nothing -> adjustT (phony t) f m -- | Add some dependencies to the specified target. If the target -- does not exist, it is created as a phony target. This is pretty -- simple, but you may care to see also the regression tests described -- in <../27-addDependencies.html> for examples. addDependencies :: String -- ^ target -> [String] -- ^ new dependencies -> C () addDependencies t ds = do ots <- maybe [] (toListS . fellowTargets) `fmap` getTarget t ds0 <- maybe emptyS dependencies `fmap` getTarget t rul <- maybe (return ()) buildrule `fmap` getTarget t t' <- maybe (phony t) id `fmap` clarifyTarget t ds' <- fromListS `fmap` mapM processFilePathOrTarget ds let ds'' = ds0 `unionS` ds' fixt tar = (tar, delS tar allts) allts = fromListS (t':ots) ts'' = map fixt (t':ots) addt (thisT,otherTs) = modifyTargets $ insertT thisT (Target otherTs ds'' rul) mapM_ clearBuilt (t':ots) mapM_ addt ts''
droundy/franchise
Distribution/Franchise/Buildable.hs
bsd-3-clause
26,012
0
28
10,619
6,621
3,258
3,363
460
15
-- | Defines various function in the context of user interaction, -- most importantly the verbosity settings and logging mechanism module Language.Java.Paragon.Interaction (setVerbosity, getVerbosity, verbosePrint, --enableXmlOutput, getXmlOutput, -- Not used right now setCheckNull, checkNull, normalPrint, detailPrint, finePrint, debugPrint, tracePrint, panic, formatData, versionString, libraryBase, typeCheckerBase ) where import Data.IORef import Control.Monad import System.IO.Unsafe (unsafePerformIO) -- Trust me, I know what I'm doing... :-D -- Comment out to get rid of dependency on haskell-src-exts: import Language.Haskell.Exts.Parser import Language.Haskell.Exts.Pretty import Language.Java.Paragon.Monad.Base ------------------------------------------------------------- -- Verbosity in feedback {-# NOINLINE unsafeVerbosityGlobalVar #-} unsafeVerbosityGlobalVar :: IORef Int -- ^Stores the verbosity level as an Int in an IO Reference. -- Set to 1 by default. unsafeVerbosityGlobalVar = unsafePerformIO $ newIORef 1 -- | Read verbosity level from IO reference getVerbosity :: IO Int getVerbosity = readIORef unsafeVerbosityGlobalVar -- | Set the verbosity as an IO reference, i.e. 'unsafeVerbosityGlobalVar' setVerbosity :: Int -> IO () setVerbosity k = writeIORef unsafeVerbosityGlobalVar k -- | Conditional print function, comparing given and global verbosity levels verbosePrint :: MonadIO m => Int -> String -> m () verbosePrint n str = liftIO $ do k <- getVerbosity when (n <= k) $ putStrLn str -- | Mapping print functions to call to the 'verbosePrint' function with -- increasing verbosity normalPrint, detailPrint, finePrint, debugPrint, tracePrint :: MonadIO m => String -> m () normalPrint = verbosePrint 1 -- ^Feedback to the user in the normal case detailPrint = verbosePrint 2 -- ^Report individual members finePrint = verbosePrint 3 -- ^Report verbosely (default for -v) debugPrint = verbosePrint 4 -- ^Include DEBUG output tracePrint = verbosePrint 5 -- ^State and env changes -- This trace function uses haskell-src-exts to get nice formating. -- To avoid depending on this package, comment out this version and the imports above, and -- comment in the version using show below. formatData :: Show a => a -> String formatData s = case parseExp (show s) of ParseOk x -> prettyPrintStyleMode -- ribbonsPerLine adjust how eager the printer is to break lines eg in records. Style{ mode = PageMode, lineLength = 150, ribbonsPerLine = 2.5 } defaultMode x ParseFailed{} -> show s -- formatData = show unsafeCheckNullGlobalVar :: IORef Bool unsafeCheckNullGlobalVar = unsafePerformIO $ newIORef False checkNull :: IO Bool checkNull = readIORef unsafeCheckNullGlobalVar setCheckNull :: Bool -> IO () setCheckNull b = writeIORef unsafeCheckNullGlobalVar b ------------------------------------------------------------- -- Generate XML output -- [Currently unused] {- {-# NOINLINE unsafeXmlOutputGlobalVar #-} unsafeXmlOutputGlobalVar :: IORef Bool unsafeXmlOutputGlobalVar = unsafePerformIO $ newIORef False getXmlOutput :: IO Bool getXmlOutput = readIORef unsafeXmlOutputGlobalVar enableXmlOutput :: IO () enableXmlOutput = writeIORef unsafeXmlOutputGlobalVar True -} --xmlOutput :: IORef XMLNode --xmlOutput = unsafePerformIO $ newIORef $ -- XMLNode "parac" [XMLAttribute "version" versionString] [] --insertXMLNode :: XMLNode -> IO () --insertXMLNode n = readIORef (xmlOutput) >>= \x -> writeIORef xmlOutput (insertNode x n) ------------------------------------------------------------- -- | A function for generating bug report guidelines panic :: String -> String -> a panic cause extra = error $ "Panic! " ++ cause ++ " caused the impossible, \ \and the world is now about to end in 3.. 2.. 1.. \n\ \Please report as a bug at: " ++ issueTracker ++ if not (null extra) then "\nExtra information: " ++ extra else "" issueTracker :: String issueTracker = "http://code.google.com/p/paragon-java/issues/entry" versionString :: String versionString = "0.1.31" -- | Module paths for use in error reports libraryBase, typeCheckerBase :: String libraryBase = "Language.Java.Paragon" typeCheckerBase = libraryBase ++ ".TypeCheck"
bvdelft/parac2
src/Language/Java/Paragon/Interaction.hs
bsd-3-clause
4,416
0
11
836
587
336
251
54
2
module Sexy.Instances.Cons () where import Sexy.Instances.Cons.List ()
DanBurton/sexy
src/Sexy/Instances/Cons.hs
bsd-3-clause
72
0
4
8
20
14
6
2
0
-- 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 GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Duration.FR.Rules ( rules ) where import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Duration.Helpers import Duckling.Numeral.Types (NumeralData(..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Regex.Types import qualified Duckling.TimeGrain.Types as TG import Duckling.Types ruleNumeralQuotes :: Rule ruleNumeralQuotes = Rule { name = "<integer> + '\"" , pattern = [ Predicate isNatural , regex "(['\"])" ] , prod = \tokens -> case tokens of (Token Numeral NumeralData{TNumeral.value = v}: Token RegexMatch (GroupMatch (x:_)): _) -> case x of "'" -> Just . Token Duration . duration TG.Minute $ floor v "\"" -> Just . Token Duration . duration TG.Second $ floor v _ -> Nothing _ -> Nothing } ruleUneUnitofduration :: Rule ruleUneUnitofduration = Rule { name = "une <unit-of-duration>" , pattern = [ regex "une|la|le?" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_: Token TimeGrain grain: _) -> Just . Token Duration $ duration grain 1 _ -> Nothing } ruleUnQuartDHeure :: Rule ruleUnQuartDHeure = Rule { name = "un quart d'heure" , pattern = [ regex "(1/4\\s?h(eure)?|(un|1) quart d'heure)" ] , prod = \_ -> Just . Token Duration $ duration TG.Minute 15 } ruleUneDemiHeure :: Rule ruleUneDemiHeure = Rule { name = "une demi heure" , pattern = [ regex "(1/2\\s?h(eure)?|(1|une) demi(e)?(\\s|-)heure)" ] , prod = \_ -> Just . Token Duration $ duration TG.Minute 30 } ruleTroisQuartsDHeure :: Rule ruleTroisQuartsDHeure = Rule { name = "trois quarts d'heure" , pattern = [ regex "(3/4\\s?h(eure)?|(3|trois) quart(s)? d'heure)" ] , prod = \_ -> Just . Token Duration $ duration TG.Minute 45 } ruleDurationEnviron :: Rule ruleDurationEnviron = Rule { name = "environ <duration>" , pattern = [ regex "environ" ] , prod = \tokens -> case tokens of -- TODO(jodent) +precision approximate (_:token:_) -> Just token _ -> Nothing } rules :: [Rule] rules = [ ruleUneUnitofduration , ruleUnQuartDHeure , ruleUneDemiHeure , ruleTroisQuartsDHeure , ruleDurationEnviron , ruleNumeralQuotes ]
facebookincubator/duckling
Duckling/Duration/FR/Rules.hs
bsd-3-clause
2,562
0
18
591
635
361
274
72
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Main where import Control.Monad.Trans.Either (EitherT) import Network.Wai (Application) import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.RequestLogger (logStdoutDev) import Servant ( (:>), Get, Capture, JSON, Proxy(..), ServantErr, ServerT, serve ) type EchoAPI = "echo" :> Capture "echoIn" String :> Get '[Servant.JSON] String echoAPI :: ServerT EchoAPI (EitherT ServantErr IO) echoAPI = echo echo :: String -> EitherT ServantErr IO String echo echoIn = return echoIn app :: Application app = serve (Proxy :: Proxy EchoAPI) echoAPI main :: IO () main = run 32323 $ logStdoutDev app
zekna/toy-haskell
echo.hs
bsd-3-clause
683
0
10
108
217
125
92
18
1
{-# LANGUAGE OverloadedStrings #-} module Xlsx.SimpleSpec (main, spec) where import Test.Hspec import Xlsx.Simple import Codec.Xlsx import Xlsx.Simple.Internal import Codec.Xlsx.Writer import Data.Time import Data.Time.LocalTime import Control.Applicative testFileName = "testD.xlsx" testSheetName = "testSheet" testBbtext :: CellData testBbtext = bbText "testBbte" testIbtext :: CellData testIbtext = ibText "estIbtex" testNbtext :: CellData testNbtext = nbText "stNbtext" testBgrtext :: CellData testBgrtext = bgrText "stBgrtex" testIgrtext :: CellData testIgrtext = igrText "stIgrtex" testNgrtext :: CellData testNgrtext = ngrText "stNgrtex" testBrtext :: CellData testBrtext = brText "stBrtext" testIrtext :: CellData testIrtext = irText "stIrtext" testNrtext :: CellData testNrtext = nrText "stNrtext" testBgtext :: CellData testBgtext = bgText "stBgtext" testIgtext :: CellData testIgtext = igText "stIgtext" testIntext :: CellData testIntext = inText "stIntext" testBbdouble :: CellData testBbdouble = bbDouble 2.781828 testIbdouble :: CellData testIbdouble = ibDouble 2.781828 testNbdouble :: CellData testNbdouble = nbDouble 2.781828 testBgrdouble :: CellData testBgrdouble = bgrDouble 2.781828 testIgrdouble :: CellData testIgrdouble = igrDouble 2.781828 testNgrdouble :: CellData testNgrdouble = ngrDouble 2.781828 testBrdouble :: CellData testBrdouble = brDouble 2.781828 testIrdouble :: CellData testIrdouble = irDouble 2.781828 testNrdouble :: CellData testNrdouble = nrDouble 2.781828 testBgdouble :: CellData testBgdouble = bgDouble 2.781828 testIgdouble :: CellData testIgdouble = igDouble 2.781828 testIndouble :: CellData testIndouble = inDouble 2.781828 main :: IO () main = hspec spec spec :: Spec spec = do describe "writeXlsxFile" $ do it "should print test data to xlsx file and exit" $ do t <- getCurrentTime let sheet3 = testSheet3 <*> [utcToLocalTime (hoursToTimeZone (-6)) t] writeXlsxFile testFileName testSheetName ([testSheet] ++ [allNumStyles] ++ [testSheet2] ++ [sheet3]) True `shouldBe` True testSheet3 = [bbDate ,ibDate ,nbDate ,bgrDate ,igrDate ,ngrDate ,brDate ,irDate ,nrDate ,bgDate ,igDate ,inDate ] allStyles = xText <$> [ 1 .. 100] <*> ["Test text"] allNumStyles = xDouble <$> [1 .. 100] <*> [1.1] testSheet2 = allStyles testSheet = [testBbtext ,testBbtext ,testIbtext ,testIbtext ,testNbtext ,testNbtext ,testBgrtext ,testBgrtext ,testIgrtext ,testIgrtext ,testNgrtext ,testNgrtext ,testBrtext ,testBrtext ,testIrtext ,testIrtext ,testNrtext ,testNrtext ,testBgtext ,testBgtext ,testIgtext ,testIgtext ,testIntext ,testIntext ,testBbdouble ,testBbdouble ,testIbdouble ,testIbdouble ,testNbdouble ,testNbdouble ,testBgrdouble ,testBgrdouble ,testIgrdouble ,testIgrdouble ,testNgrdouble ,testNgrdouble ,testBrdouble ,testBrdouble ,testIrdouble ,testIrdouble ,testNrdouble ,testNrdouble ,testBgdouble ,testBgdouble ,testIgdouble ,testIgdouble ,testIndouble ,testIndouble] ;
plow-technologies/xlsx-simple
test/Xlsx/SimpleSpec.hs
bsd-3-clause
4,502
0
22
1,931
753
434
319
133
1
module WhileAS where type VarIdent = String type Label = Int -- type Selector = String type Prog = Stat -- type Prog = Prog [Dec] [Stat] -- Contains name, a list of input vars, output var, body respectively and of course -- the two labels ln and lx data Dec = Proc [VarIdent] VarIdent VarIdent Label Stat Label data AExp = Var VarIdent | IntLit Integer | AOp String AExp AExp -- | Var VarIdent (Maybe Selector) -- | Nil | Dummy deriving (Eq, Show) data BExp = BUnOp String BExp | BoolLit Bool | BOp String BExp BExp | RelOp String AExp AExp -- | POp VarIdent (Maybe Selector) deriving (Eq, Show) data Stat = Assign VarIdent AExp Label | Skip Label | Seq [Stat] | If BExp Label Stat Stat | While BExp Label Stat -- | Call VarIdent [AExp] VarIdent Label Label -- | Malloc VarIdent (Maybe Selector) Label deriving (Show, Eq)
FranklinChen/hugs98-plus-Sep2006
packages/parsec/examples/while/WhileAS.hs
bsd-3-clause
871
0
7
205
192
114
78
24
0
{-# LANGUAGE TemplateHaskell, TypeOperators #-} -- | For more information: http://www.ietf.org/rfc/rfc2109.txt module Network.Protocol.Cookie {- todo: test please -} ( -- * Cookie datatype. Cookie (Cookie) , empty , cookie , setCookie -- * Accessing cookies. , name , value , comment , commentURL , discard , domain , maxAge , expires , path , port , secure , version -- * Collection of cookies. , Cookies , unCookies , cookies , setCookies , pickCookie , fromList , toList ) where import Prelude hiding ((.), id) import Control.Category import Control.Monad (join) import Data.Record.Label import Data.Maybe import Data.Char import Safe import Data.List import Network.Protocol.Uri.Query import qualified Data.Map as M -- | The `Cookie` data type containg one key/value pair with all the -- (potentially optional) meta-data. data Cookie = Cookie { _name :: String , _value :: String , _comment :: Maybe String , _commentURL :: Maybe String , _discard :: Bool , _domain :: Maybe String , _maxAge :: Maybe Int , _expires :: Maybe String , _path :: Maybe String , _port :: [Int] , _secure :: Bool , _version :: Int } deriving Eq $(mkLabelsNoTypes [''Cookie]) -- | Access name/key of a cookie. name :: Cookie :-> String -- | Access value of a cookie. value :: Cookie :-> String -- | Access comment of a cookie. comment :: Cookie :-> Maybe String -- | Access comment-URL of a cookie. commentURL :: Cookie :-> Maybe String -- | Access discard flag of a cookie. discard :: Cookie :-> Bool -- | Access domain of a cookie. domain :: Cookie :-> Maybe String -- | Access max-age of a cookie. maxAge :: Cookie :-> Maybe Int -- | Access expiration of a cookie. expires :: Cookie :-> Maybe String -- | Access path of a cookie. path :: Cookie :-> Maybe String -- | Access port of a cookie. port :: Cookie :-> [Int] -- | Access secure flag of a cookie. secure :: Cookie :-> Bool -- | Access version of a cookie. version :: Cookie :-> Int -- | Create an empty cookie. empty :: Cookie empty = Cookie "" "" Nothing Nothing False Nothing Nothing Nothing Nothing [] False 0 -- Cookie show instance. instance Show Cookie where showsPrec _ = showsSetCookie -- Show a semicolon separated list of attribute/value pairs. Only meta pairs -- with significant values will be pretty printed. showsSetCookie :: Cookie -> ShowS showsSetCookie c = pair (getL name c) (getL value c) . opt "comment" (getL comment c) . opt "commentURL" (getL commentURL c) . bool "discard" (getL discard c) . opt "domain" (getL domain c) . opt "maxAge" (fmap show (getL maxAge c)) . opt "expires" (getL expires c) . opt "path" (getL path c) . lst "port" (map show (getL port c)) . bool "secure" (getL secure c) . opt "version" (optval (getL version c)) where attr a = showString a val v = showString ("=" ++ v) end = showString "; " single a = attr a . end pair a v = attr a . val v . end opt a = maybe id (pair a) lst _ [] = id lst a xs = pair a (intercalate "," xs) bool _ False = id bool a True = single a optval 0 = Nothing optval i = Just (show i) showCookie :: Cookie -> String showCookie c = _name c ++ "=" ++ _value c parseSetCookie :: String -> Cookie parseSetCookie s = let p = fw (keyValues ";" "=") s in Cookie { _name = (fromMaybe "" . fmap fst . headMay) p , _value = (fromMaybe "" . join . fmap snd . headMay) p , _comment = ( join . lookup "comment") p , _commentURL = ( join . lookup "commentURL") p , _discard = (maybe False (const True) . join . lookup "discard") p , _domain = ( join . lookup "commentURL") p , _maxAge = (join . fmap readMay . join . lookup "commentURL") p , _expires = ( join . lookup "expires") p , _path = ( join . lookup "path") p , _port = (maybe [] (readDef [-1]) . join . lookup "port") p , _secure = (maybe False (const True) . join . lookup "secure") p , _version = (maybe 1 (readDef 1) . join . lookup "version") p } parseCookie :: String -> Cookie parseCookie s = let p = fw (values "=") s in empty { _name = atDef "" p 0 , _value = atDef "" p 1 } -- | Cookie parser and pretty printer as a lens. To be used in combination with -- the /Set-Cookie/ header field. setCookie :: String :<->: Cookie setCookie = parseSetCookie :<->: show -- | Cookie parser and pretty printer as a lens. To be used in combination with -- the /Cookie/ header field. cookie :: String :<->: Cookie cookie = parseCookie :<->: showCookie -- | A collection of multiple cookies. These can all be set in one single HTTP -- /Set-Cookie/ header field. data Cookies = Cookies { _unCookies :: M.Map String Cookie } deriving Eq $(mkLabelsNoTypes [''Cookies]) -- | Access raw cookie mapping from collection. unCookies :: Cookies :-> M.Map String Cookie instance Show Cookies where showsPrec _ = showsSetCookies showsSetCookies :: Cookies -> ShowS showsSetCookies = is (showString ", ") . map (shows . snd) . M.toList . getL unCookies where is _ [] = id is s (x:xs) = foldl (\a b -> a.s.b) x xs -- | Cookies parser and pretty printer as a lens. setCookies :: String :<->: Cookies setCookies = (fromList :<->: toList) . (map parseSetCookie :<->: map show) . values "," -- | Label for printing and parsing collections of cookies. cookies :: String :<->: Cookies cookies = (fromList :<->: toList) . (map parseCookie :<->: map showCookie) . values ";" -- | Case-insensitive way of getting a cookie out of a collection by name. pickCookie :: String -> Cookies :-> Maybe Cookie pickCookie n = lookupL (map toLower n) . unCookies where lookupL k = lens (M.lookup k) (flip M.alter k . const) -- | Convert a list to a cookies collection. fromList :: [Cookie] -> Cookies fromList = Cookies . M.fromList . map (\a -> (map toLower (getL name a), a)) -- | Get the cookies as a list. toList :: Cookies -> [Cookie] toList = map snd . M.toList . getL unCookies
sebastiaanvisser/salvia-protocol
src/Network/Protocol/Cookie.hs
bsd-3-clause
6,411
0
17
1,769
1,829
972
857
149
4
module MonadLoopsExample where import Control.Monad (liftM) import Control.Monad.Loops (whileM_, unfoldM) -- | Print prompt and read lines with retry prompts until the password -- is correctly entered, then print congratulations. logIn :: IO () logIn = do putStrLn "% Enter password:" go putStrLn "$ Congratulations!" where -- Use recursion for loop go = do guess <- getLine if guess /= "secret" then do putStrLn "% Wrong password!" putStrLn "% Try again:" go else return () -- | No explicit recursion logIn2 :: IO () logIn2 = do putStrLn "% Enter password:" whileM_ (do guess <- getLine return (guess /= "secret") ) (do putStrLn "% Wrong password!" putStrLn "% Try again:" ) putStrLn "$ Congratulations!" -- | With $ syntax. logIn3 :: IO () logIn3 = do putStrLn "% Enter password:" whileM_ (do guess <- getLine return (guess /= "secret") ) $ do putStrLn "% Wrong password!" putStrLn "% Try again:" putStrLn "$ Congratulations!" -- | With lifting. logIn4 :: IO () logIn4 = do putStrLn "% Enter password:" whileM_ (liftM (\guess -> guess /= "secret") getLine) $ do putStrLn "% Wrong password!" putStrLn "% Try again:" putStrLn "$ Congratulations!" -- | With operator sectioning and <$>. logIn5 :: IO () logIn5 = do putStrLn "% Enter password:" whileM_ ((/= "secret") <$> getLine) $ do putStrLn "% Wrong password!" putStrLn "% Try again:" putStrLn "$ Congratulations!" -- | Read and collect lines from stdin until encountering "quit". readLinesUntilQuit :: IO [String] readLinesUntilQuit = do line <- getLine if line /= "quit" then do -- recursive call, to loop restOfLines <- readLinesUntilQuit return (line : restOfLines) else return [] -- | No explicit recursion. readLinesUntilQuit2 :: IO [String] readLinesUntilQuit2 = unfoldM maybeReadLine -- | Read a single line and check whether it's "quit". maybeReadLine :: IO (Maybe String) maybeReadLine = do line <- getLine return (if line /= "quit" then Just line else Nothing) readLinesUntilQuit3 :: IO [String] readLinesUntilQuit3 = unfoldM (notQuit <$> getLine) notQuit :: String -> Maybe String notQuit line = if line /= "quit" then Just line else Nothing
FranklinChen/twenty-four-days2015-of-hackage
src/MonadLoopsExample.hs
bsd-3-clause
2,428
0
14
662
585
283
302
73
2
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE DataKinds #-} module Lib where import Types import Network.Label import Text.Read as T import System.FilePath.Posix import Numeric import Data.List divs :: Integral a => a -> a -> Bool a `divs` b = b `mod` a == 0 count :: (a -> Bool) -> [a] -> Int count p = length . filter p splitDigits :: Int -> (Int, Int, Int) splitDigits x = (d100, d10, d1) where (d100, r) = x `divMod` 100 (d10, d1) = r `divMod` 10 toWidget :: Widget a => WLabel a -> a toWidget (WLabel l) = case parseLabel l fromLabel of Left str -> error str Right a -> a read' :: String -> Int read' x = case T.readMaybe x of Just x -> x Nothing -> error$ "error parsing " ++ x labelPath :: GameState g => Path g -> g labelPath = delabel . parse pmap :: (FilePath -> FilePath) -> Path a -> Path a pmap f (Path p) = Path$ f p showAndLabel :: GameState g => Path g -> String showAndLabel p = show (pmap takeBaseName p) ++ "\t\t" ++ show (labelPath p) showE :: Double -> ShowS showE = showEFloat (Just 4) median :: Ord a => [a] -> a median [] = undefined median [x] = x median xs = let i = length xs `div` 2 in sort xs !! i median' :: [Double] -> Double median' [] = undefined median' [x] = x median' xs = let l = length xs i = l `div` 2 s = sort xs in if odd l then s !! i else (s !! i + s !! (i-1)) / 2 roundF x = fromInteger (round x :: Integer) ceilF x = fromInteger (ceiling x :: Integer) floorF x = fromInteger (floor x :: Integer)
jonascarpay/visor
src/Lib.hs
bsd-3-clause
1,638
0
12
505
706
369
337
50
2
-- | Accessors (lenses and functions) to operate on the 'PostFiltset' of a -- clatch-like type. module Penny.Clatch.Access.PostFiltset where import Control.Lens (Lens', _2, _1) import Penny.Clatch.Types -- | Operate on the 'PostFiltset'. -- -- @ -- 'postFiltset' :: 'Lens'' 'Clatch' 'PostFiltset' -- @ postFiltset :: Lens' (a, (b, (c, (d, (e, (f, (PostFiltset, g))))))) PostFiltset postFiltset = _2 . _2 . _2 . _2 . _2 . _2 . _1
massysett/penny
penny/lib/Penny/Clatch/Access/PostFiltset.hs
bsd-3-clause
433
0
12
74
118
75
43
5
1
-- | A pure implementation of the emulator {-# LANGUAGE GeneralizedNewtypeDeriving, Rank2Types #-} module Emulator.Monad.ST ( STEmulator , runSTEmulator ) where import Control.Monad.Reader (ReaderT, ask, runReaderT) import Control.Monad.ST (ST, runST) import Control.Monad.Trans (lift) import Emulator.Monad import Memory (Memory) import qualified Memory as Memory newtype STEmulator s a = STEmulator (ReaderT (Memory s) (ST s) a) deriving (Functor, Monad) instance MonadEmulator (STEmulator s) where load address = STEmulator $ do mem <- ask lift $ Memory.load mem address store address word = STEmulator $ do mem <- ask lift $ Memory.store mem address word runSTEmulator :: (forall s. STEmulator s a) -> a runSTEmulator emu = -- If you wonder why this isn't defined as `runST . run`... type magic. let x = run emu in runST x where run :: STEmulator s a -> ST s a run (STEmulator reader) = do mem <- Memory.new runReaderT reader mem
jaspervdj/dcpu16-hs
src/Emulator/Monad/ST.hs
bsd-3-clause
1,033
0
11
247
305
163
142
27
1
{-# language CPP #-} -- | = Name -- -- VK_KHR_swapchain - device extension -- -- == VK_KHR_swapchain -- -- [__Name String__] -- @VK_KHR_swapchain@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 2 -- -- [__Revision__] -- 70 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_surface@ -- -- [__Contact__] -- -- - James Jones -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_swapchain] @cubanismo%0A<<Here describe the issue or question you have about the VK_KHR_swapchain extension>> > -- -- - Ian Elliott -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_swapchain] @ianelliottus%0A<<Here describe the issue or question you have about the VK_KHR_swapchain extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2017-10-06 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- -- - Interacts with Vulkan 1.1 -- -- [__Contributors__] -- -- - Patrick Doane, Blizzard -- -- - Ian Elliott, LunarG -- -- - Jesse Hall, Google -- -- - Mathias Heyer, NVIDIA -- -- - James Jones, NVIDIA -- -- - David Mao, AMD -- -- - Norbert Nopper, Freescale -- -- - Alon Or-bach, Samsung -- -- - Daniel Rakos, AMD -- -- - Graham Sellers, AMD -- -- - Jeff Vigil, Qualcomm -- -- - Chia-I Wu, LunarG -- -- - Jason Ekstrand, Intel -- -- - Matthaeus G. Chajdas, AMD -- -- - Ray Smith, ARM -- -- == Description -- -- The @VK_KHR_swapchain@ extension is the device-level companion to the -- @VK_KHR_surface@ extension. It introduces -- 'Vulkan.Extensions.Handles.SwapchainKHR' objects, which provide the -- ability to present rendering results to a surface. -- -- == New Object Types -- -- - 'Vulkan.Extensions.Handles.SwapchainKHR' -- -- == New Commands -- -- - 'acquireNextImageKHR' -- -- - 'createSwapchainKHR' -- -- - 'destroySwapchainKHR' -- -- - 'getSwapchainImagesKHR' -- -- - 'queuePresentKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'acquireNextImage2KHR' -- -- - 'getDeviceGroupPresentCapabilitiesKHR' -- -- - 'getDeviceGroupSurfacePresentModesKHR' -- -- - 'getPhysicalDevicePresentRectanglesKHR' -- -- == New Structures -- -- - 'PresentInfoKHR' -- -- - 'SwapchainCreateInfoKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'AcquireNextImageInfoKHR' -- -- - 'DeviceGroupPresentCapabilitiesKHR' -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_bind_memory2.BindImageMemoryInfo': -- -- - 'BindImageMemorySwapchainInfoKHR' -- -- - Extending 'Vulkan.Core10.Image.ImageCreateInfo': -- -- - 'ImageSwapchainCreateInfoKHR' -- -- - Extending 'PresentInfoKHR': -- -- - 'DeviceGroupPresentInfoKHR' -- -- - Extending 'SwapchainCreateInfoKHR': -- -- - 'DeviceGroupSwapchainCreateInfoKHR' -- -- == New Enums -- -- - 'SwapchainCreateFlagBitsKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'DeviceGroupPresentModeFlagBitsKHR' -- -- == New Bitmasks -- -- - 'SwapchainCreateFlagsKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'DeviceGroupPresentModeFlagsKHR' -- -- == New Enum Constants -- -- - 'KHR_SWAPCHAIN_EXTENSION_NAME' -- -- - 'KHR_SWAPCHAIN_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.ImageLayout.ImageLayout': -- -- - 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR' -- -- - Extending 'Vulkan.Core10.Enums.ObjectType.ObjectType': -- -- - 'Vulkan.Core10.Enums.ObjectType.OBJECT_TYPE_SWAPCHAIN_KHR' -- -- - Extending 'Vulkan.Core10.Enums.Result.Result': -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PRESENT_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR' -- -- - Extending 'SwapchainCreateFlagBitsKHR': -- -- - 'SWAPCHAIN_CREATE_PROTECTED_BIT_KHR' -- -- - 'SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR' -- -- == Issues -- -- 1) Does this extension allow the application to specify the memory -- backing of the presentable images? -- -- __RESOLVED__: No. Unlike standard images, the implementation will -- allocate the memory backing of the presentable image. -- -- 2) What operations are allowed on presentable images? -- -- __RESOLVED__: This is determined by the image usage flags specified when -- creating the presentable image’s swapchain. -- -- 3) Does this extension support MSAA presentable images? -- -- __RESOLVED__: No. Presentable images are always single-sampled. -- Multi-sampled rendering must use regular images. To present the -- rendering results the application must manually resolve the multi- -- sampled image to a single-sampled presentable image prior to -- presentation. -- -- 4) Does this extension support stereo\/multi-view presentable images? -- -- __RESOLVED__: Yes. The number of views associated with a presentable -- image is determined by the @imageArrayLayers@ specified when creating a -- swapchain. All presentable images in a given swapchain use the same -- array size. -- -- 5) Are the layers of stereo presentable images half-sized? -- -- __RESOLVED__: No. The image extents always match those requested by the -- application. -- -- 6) Do the “present” and “acquire next image” commands operate on a -- queue? If not, do they need to include explicit semaphore objects to -- interlock them with queue operations? -- -- __RESOLVED__: The present command operates on a queue. The image -- ownership operation it represents happens in order with other operations -- on the queue, so no explicit semaphore object is required to synchronize -- its actions. -- -- Applications may want to acquire the next image in separate threads from -- those in which they manage their queue, or in multiple threads. To make -- such usage easier, the acquire next image command takes a semaphore to -- signal as a method of explicit synchronization. The application must -- later queue a wait for this semaphore before queuing execution of any -- commands using the image. -- -- 7) Does 'acquireNextImageKHR' block if no images are available? -- -- __RESOLVED__: The command takes a timeout parameter. Special values for -- the timeout are 0, which makes the call a non-blocking operation, and -- @UINT64_MAX@, which blocks indefinitely. Values in between will block -- for up to the specified time. The call will return when an image becomes -- available or an error occurs. It may, but is not required to, return -- before the specified timeout expires if the swapchain becomes out of -- date. -- -- 8) Can multiple presents be queued using one 'queuePresentKHR' call? -- -- __RESOLVED__: Yes. 'PresentInfoKHR' contains a list of swapchains and -- corresponding image indices that will be presented. When supported, all -- presentations queued with a single 'queuePresentKHR' call will be -- applied atomically as one operation. The same swapchain must not appear -- in the list more than once. Later extensions may provide applications -- stronger guarantees of atomicity for such present operations, and\/or -- allow them to query whether atomic presentation of a particular group of -- swapchains is possible. -- -- 9) How do the presentation and acquire next image functions notify the -- application the targeted surface has changed? -- -- __RESOLVED__: Two new result codes are introduced for this purpose: -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' - Presentation will -- still succeed, subject to the window resize behavior, but the -- swapchain is no longer configured optimally for the surface it -- targets. Applications should query updated surface information and -- recreate their swapchain at the next convenient opportunity. -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' - Failure. The -- swapchain is no longer compatible with the surface it targets. The -- application must query updated surface information and recreate the -- swapchain before presentation will succeed. -- -- These can be returned by both 'acquireNextImageKHR' and -- 'queuePresentKHR'. -- -- 10) Does the 'acquireNextImageKHR' command return a semaphore to the -- application via an output parameter, or accept a semaphore to signal -- from the application as an object handle parameter? -- -- __RESOLVED__: Accept a semaphore to signal as an object handle. This -- avoids the need to specify whether the application must destroy the -- semaphore or whether it is owned by the swapchain, and if the latter, -- what its lifetime is and whether it can be reused for other operations -- once it is received from 'acquireNextImageKHR'. -- -- 11) What types of swapchain queuing behavior should be exposed? Options -- include swap interval specification, mailbox\/most recent vs. FIFO queue -- management, targeting specific vertical blank intervals or absolute -- times for a given present operation, and probably others. For some of -- these, whether they are specified at swapchain creation time or as -- per-present parameters needs to be decided as well. -- -- __RESOLVED__: The base swapchain extension will expose 3 possible -- behaviors (of which, FIFO will always be supported): -- -- - Immediate present: Does not wait for vertical blanking period to -- update the current image, likely resulting in visible tearing. No -- internal queue is used. Present requests are applied immediately. -- -- - Mailbox queue: Waits for the next vertical blanking period to update -- the current image. No tearing should be observed. An internal -- single-entry queue is used to hold pending presentation requests. If -- the queue is full when a new presentation request is received, the -- new request replaces the existing entry, and any images associated -- with the prior entry become available for reuse by the application. -- -- - FIFO queue: Waits for the next vertical blanking period to update -- the current image. No tearing should be observed. An internal queue -- containing @numSwapchainImages@ - 1 entries is used to hold pending -- presentation requests. New requests are appended to the end of the -- queue, and one request is removed from the beginning of the queue -- and processed during each vertical blanking period in which the -- queue is non-empty -- -- Not all surfaces will support all of these modes, so the modes supported -- will be returned using a surface information query. All surfaces must -- support the FIFO queue mode. Applications must choose one of these modes -- up front when creating a swapchain. Switching modes can be accomplished -- by recreating the swapchain. -- -- 12) Can 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_MAILBOX_KHR' -- provide non-blocking guarantees for 'acquireNextImageKHR'? If so, what -- is the proper criteria? -- -- __RESOLVED__: Yes. The difficulty is not immediately obvious here. -- Naively, if at least 3 images are requested, mailbox mode should always -- have an image available for the application if the application does not -- own any images when the call to 'acquireNextImageKHR' was made. However, -- some presentation engines may have more than one “current” image, and -- would still need to block in some cases. The right requirement appears -- to be that if the application allocates the surface’s minimum number of -- images + 1 then it is guaranteed non-blocking behavior when it does not -- currently own any images. -- -- 13) Is there a way to create and initialize a new swapchain for a -- surface that has generated a 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- return code while still using the old swapchain? -- -- __RESOLVED__: Not as part of this specification. This could be useful to -- allow the application to create an “optimal” replacement swapchain and -- rebuild all its command buffers using it in a background thread at a low -- priority while continuing to use the “suboptimal” swapchain in the main -- thread. It could probably use the same “atomic replace” semantics -- proposed for recreating direct-to-device swapchains without incurring a -- mode switch. However, after discussion, it was determined some platforms -- probably could not support concurrent swapchains for the same surface -- though, so this will be left out of the base KHR extensions. A future -- extension could add this for platforms where it is supported. -- -- 14) Should there be a special value for -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@maxImageCount@ -- to indicate there are no practical limits on the number of images in a -- swapchain? -- -- __RESOLVED__: Yes. There will often be cases where there is no practical -- limit to the number of images in a swapchain other than the amount of -- available resources (i.e., memory) in the system. Trying to derive a -- hard limit from things like memory size is prone to failure. It is -- better in such cases to leave it to applications to figure such soft -- limits out via trial\/failure iterations. -- -- 15) Should there be a special value for -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@currentExtent@ -- to indicate the size of the platform surface is undefined? -- -- __RESOLVED__: Yes. On some platforms (Wayland, for example), the surface -- size is defined by the images presented to it rather than the other way -- around. -- -- 16) Should there be a special value for -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@maxImageExtent@ -- to indicate there is no practical limit on the surface size? -- -- __RESOLVED__: No. It seems unlikely such a system would exist. 0 could -- be used to indicate the platform places no limits on the extents beyond -- those imposed by Vulkan for normal images, but this query could just as -- easily return those same limits, so a special “unlimited” value does not -- seem useful for this field. -- -- 17) How should surface rotation and mirroring be exposed to -- applications? How do they specify rotation and mirroring transforms -- applied prior to presentation? -- -- __RESOLVED__: Applications can query both the supported and current -- transforms of a surface. Both are specified relative to the device’s -- “natural” display rotation and direction. The supported transforms -- indicate which orientations the presentation engine accepts images in. -- For example, a presentation engine that does not support transforming -- surfaces as part of presentation, and which is presenting to a surface -- that is displayed with a 90-degree rotation, would return only one -- supported transform bit: -- 'Vulkan.Extensions.VK_KHR_surface.SURFACE_TRANSFORM_ROTATE_90_BIT_KHR'. -- Applications must transform their rendering by the transform they -- specify when creating the swapchain in @preTransform@ field. -- -- 18) Can surfaces ever not support @VK_MIRROR_NONE@? Can they support -- vertical and horizontal mirroring simultaneously? Relatedly, should -- @VK_MIRROR_NONE@[_BIT] be zero, or bit one, and should applications be -- allowed to specify multiple pre and current mirror transform bits, or -- exactly one? -- -- __RESOLVED__: Since some platforms may not support presenting with a -- transform other than the native window’s current transform, and -- prerotation\/mirroring are specified relative to the device’s natural -- rotation and direction, rather than relative to the surface’s current -- rotation and direction, it is necessary to express lack of support for -- no mirroring. To allow this, the @MIRROR_NONE@ enum must occupy a bit in -- the flags. Since @MIRROR_NONE@ must be a bit in the bitmask rather than -- a bitmask with no values set, allowing more than one bit to be set in -- the bitmask would make it possible to describe undefined transforms such -- as @VK_MIRROR_NONE_BIT@ | @VK_MIRROR_HORIZONTAL_BIT@, or a transform -- that includes both “no mirroring” and “horizontal mirroring” -- simultaneously. Therefore, it is desirable to allow specifying all -- supported mirroring transforms using only one bit. The question then -- becomes, should there be a @VK_MIRROR_HORIZONTAL_AND_VERTICAL_BIT@ to -- represent a simultaneous horizontal and vertical mirror transform? -- However, such a transform is equivalent to a 180 degree rotation, so -- presentation engines and applications that wish to support or use such a -- transform can express it through rotation instead. Therefore, 3 -- exclusive bits are sufficient to express all needed mirroring -- transforms. -- -- 19) Should support for sRGB be required? -- -- __RESOLVED__: In the advent of UHD and HDR display devices, proper color -- space information is vital to the display pipeline represented by the -- swapchain. The app can discover the supported format\/color-space pairs -- and select a pair most suited to its rendering needs. Currently only the -- sRGB color space is supported, future extensions may provide support for -- more color spaces. See issues 23 and 24. -- -- 20) Is there a mechanism to modify or replace an existing swapchain with -- one targeting the same surface? -- -- __RESOLVED__: Yes. This is described above in the text. -- -- 21) Should there be a way to set prerotation and mirroring using native -- APIs when presenting using a Vulkan swapchain? -- -- __RESOLVED__: Yes. The transforms that can be expressed in this -- extension are a subset of those possible on native platforms. If a -- platform exposes a method to specify the transform of presented images -- for a given surface using native methods and exposes more transforms or -- other properties for surfaces than Vulkan supports, it might be -- impossible, difficult, or inconvenient to set some of those properties -- using Vulkan KHR extensions and some using the native interfaces. To -- avoid overwriting properties set using native commands when presenting -- using a Vulkan swapchain, the application can set the pretransform to -- “inherit”, in which case the current native properties will be used, or -- if none are available, a platform-specific default will be used. -- Platforms that do not specify a reasonable default or do not provide -- native mechanisms to specify such transforms should not include the -- inherit bits in the @supportedTransforms@ bitmask they return in -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'. -- -- 22) Should the content of presentable images be clipped by objects -- obscuring their target surface? -- -- __RESOLVED__: Applications can choose which behavior they prefer. -- Allowing the content to be clipped could enable more efficient -- presentation methods on some platforms, but some applications might rely -- on the content of presentable images to perform techniques such as -- partial updates or motion blurs. -- -- 23) What is the purpose of specifying a -- 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR' along with -- 'Vulkan.Core10.Enums.Format.Format' when creating a swapchain? -- -- __RESOLVED__: While Vulkan itself is color space agnostic (e.g. even the -- meaning of R, G, B and A can be freely defined by the rendering -- application), the swapchain eventually will have to present the images -- on a display device with specific color reproduction characteristics. If -- any color space transformations are necessary before an image can be -- displayed, the color space of the presented image must be known to the -- swapchain. A swapchain will only support a restricted set of color -- format and -space pairs. This set can be discovered via -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceFormatsKHR'. -- As it can be expected that most display devices support the sRGB color -- space, at least one format\/color-space pair has to be exposed, where -- the color space is -- 'Vulkan.Extensions.VK_KHR_surface.COLOR_SPACE_SRGB_NONLINEAR_KHR'. -- -- 24) How are sRGB formats and the sRGB color space related? -- -- __RESOLVED__: While Vulkan exposes a number of SRGB texture formats, -- using such formats does not guarantee working in a specific color space. -- It merely means that the hardware can directly support applying the -- non-linear transfer functions defined by the sRGB standard color space -- when reading from or writing to images of those formats. Still, it is -- unlikely that a swapchain will expose a @*_SRGB@ format along with any -- color space other than -- 'Vulkan.Extensions.VK_KHR_surface.COLOR_SPACE_SRGB_NONLINEAR_KHR'. -- -- On the other hand, non-@*_SRGB@ formats will be very likely exposed in -- pair with a SRGB color space. This means, the hardware will not apply -- any transfer function when reading from or writing to such images, yet -- they will still be presented on a device with sRGB display -- characteristics. In this case the application is responsible for -- applying the transfer function, for instance by using shader math. -- -- 25) How are the lifetimes of surfaces and swapchains targeting them -- related? -- -- __RESOLVED__: A surface must outlive any swapchains targeting it. A -- 'Vulkan.Extensions.Handles.SurfaceKHR' owns the binding of the native -- window to the Vulkan driver. -- -- 26) How can the client control the way the alpha component of swapchain -- images is treated by the presentation engine during compositing? -- -- __RESOLVED__: We should add new enum values to allow the client to -- negotiate with the presentation engine on how to treat image alpha -- values during the compositing process. Since not all platforms can -- practically control this through the Vulkan driver, a value of -- 'Vulkan.Extensions.VK_KHR_surface.COMPOSITE_ALPHA_INHERIT_BIT_KHR' is -- provided like for surface transforms. -- -- 27) Is 'createSwapchainKHR' the right function to return -- 'Vulkan.Core10.Enums.Result.ERROR_NATIVE_WINDOW_IN_USE_KHR', or should -- the various platform-specific 'Vulkan.Extensions.Handles.SurfaceKHR' -- factory functions catch this error earlier? -- -- __RESOLVED__: For most platforms, the -- 'Vulkan.Extensions.Handles.SurfaceKHR' structure is a simple container -- holding the data that identifies a native window or other object -- representing a surface on a particular platform. For the surface factory -- functions to return this error, they would likely need to register a -- reference on the native objects with the native display server somehow, -- and ensure no other such references exist. Surfaces were not intended to -- be that heavyweight. -- -- Swapchains are intended to be the objects that directly manipulate -- native windows and communicate with the native presentation mechanisms. -- Swapchains will already need to communicate with the native display -- server to negotiate allocation and\/or presentation of presentable -- images for a native surface. Therefore, it makes more sense for -- swapchain creation to be the point at which native object exclusivity is -- enforced. Platforms may choose to enforce further restrictions on the -- number of 'Vulkan.Extensions.Handles.SurfaceKHR' objects that may be -- created for the same native window if such a requirement makes sense on -- a particular platform, but a global requirement is only sensible at the -- swapchain level. -- -- == Examples -- -- Note -- -- The example code for the @VK_KHR_surface@ and @VK_KHR_swapchain@ -- extensions was removed from the appendix after revision 1.0.29. This WSI -- example code was ported to the cube demo that is shipped with the -- official Khronos SDK, and is being kept up-to-date in that location -- (see: -- <https://github.com/KhronosGroup/Vulkan-Tools/blob/master/cube/cube.c>). -- -- == Version History -- -- - Revision 1, 2015-05-20 (James Jones) -- -- - Initial draft, based on LunarG KHR spec, other KHR specs, -- patches attached to bugs. -- -- - Revision 2, 2015-05-22 (Ian Elliott) -- -- - Made many agreed-upon changes from 2015-05-21 KHR TSG meeting. -- This includes using only a queue for presentation, and having an -- explicit function to acquire the next image. -- -- - Fixed typos and other minor mistakes. -- -- - Revision 3, 2015-05-26 (Ian Elliott) -- -- - Improved the Description section. -- -- - Added or resolved issues that were found in improving the -- Description. For example, pSurfaceDescription is used -- consistently, instead of sometimes using pSurface. -- -- - Revision 4, 2015-05-27 (James Jones) -- -- - Fixed some grammatical errors and typos -- -- - Filled in the description of imageUseFlags when creating a -- swapchain. -- -- - Added a description of swapInterval. -- -- - Replaced the paragraph describing the order of operations on a -- queue for image ownership and presentation. -- -- - Revision 5, 2015-05-27 (James Jones) -- -- - Imported relevant issues from the (abandoned) -- vk_wsi_persistent_swapchain_images extension. -- -- - Added issues 6 and 7, regarding behavior of the acquire next -- image and present commands with respect to queues. -- -- - Updated spec language and examples to align with proposed -- resolutions to issues 6 and 7. -- -- - Revision 6, 2015-05-27 (James Jones) -- -- - Added issue 8, regarding atomic presentation of multiple -- swapchains -- -- - Updated spec language and examples to align with proposed -- resolution to issue 8. -- -- - Revision 7, 2015-05-27 (James Jones) -- -- - Fixed compilation errors in example code, and made related spec -- fixes. -- -- - Revision 8, 2015-05-27 (James Jones) -- -- - Added issue 9, and the related VK_SUBOPTIMAL_KHR result code. -- -- - Renamed VK_OUT_OF_DATE_KHR to VK_ERROR_OUT_OF_DATE_KHR. -- -- - Revision 9, 2015-05-27 (James Jones) -- -- - Added inline proposed resolutions (marked with [JRJ]) to some -- XXX questions\/issues. These should be moved to the issues -- section in a subsequent update if the proposals are adopted. -- -- - Revision 10, 2015-05-28 (James Jones) -- -- - Converted vkAcquireNextImageKHR back to a non-queue operation -- that uses a VkSemaphore object for explicit synchronization. -- -- - Added issue 10 to determine whether vkAcquireNextImageKHR -- generates or returns semaphores, or whether it operates on a -- semaphore provided by the application. -- -- - Revision 11, 2015-05-28 (James Jones) -- -- - Marked issues 6, 7, and 8 resolved. -- -- - Renamed VkSurfaceCapabilityPropertiesKHR to -- VkSurfacePropertiesKHR to better convey the mutable nature of -- the information it contains. -- -- - Revision 12, 2015-05-28 (James Jones) -- -- - Added issue 11 with a proposed resolution, and the related issue -- 12. -- -- - Updated various sections of the spec to match the proposed -- resolution to issue 11. -- -- - Revision 13, 2015-06-01 (James Jones) -- -- - Moved some structures to VK_EXT_KHR_swap_chain to resolve the -- specification’s issues 1 and 2. -- -- - Revision 14, 2015-06-01 (James Jones) -- -- - Added code for example 4 demonstrating how an application might -- make use of the two different present and acquire next image KHR -- result codes. -- -- - Added issue 13. -- -- - Revision 15, 2015-06-01 (James Jones) -- -- - Added issues 14 - 16 and related spec language. -- -- - Fixed some spelling errors. -- -- - Added language describing the meaningful return values for -- vkAcquireNextImageKHR and vkQueuePresentKHR. -- -- - Revision 16, 2015-06-02 (James Jones) -- -- - Added issues 17 and 18, as well as related spec language. -- -- - Removed some erroneous text added by mistake in the last update. -- -- - Revision 17, 2015-06-15 (Ian Elliott) -- -- - Changed special value from \"-1\" to \"0\" so that the data -- types can be unsigned. -- -- - Revision 18, 2015-06-15 (Ian Elliott) -- -- - Clarified the values of VkSurfacePropertiesKHR::minImageCount -- and the timeout parameter of the vkAcquireNextImageKHR function. -- -- - Revision 19, 2015-06-17 (James Jones) -- -- - Misc. cleanup. Removed resolved inline issues and fixed typos. -- -- - Fixed clarification of VkSurfacePropertiesKHR::minImageCount -- made in version 18. -- -- - Added a brief \"Image Ownership\" definition to the list of -- terms used in the spec. -- -- - Revision 20, 2015-06-17 (James Jones) -- -- - Updated enum-extending values using new convention. -- -- - Revision 21, 2015-06-17 (James Jones) -- -- - Added language describing how to use -- VK_IMAGE_LAYOUT_PRESENT_SOURCE_KHR. -- -- - Cleaned up an XXX comment regarding the description of which -- queues vkQueuePresentKHR can be used on. -- -- - Revision 22, 2015-06-17 (James Jones) -- -- - Rebased on Vulkan API version 126. -- -- - Revision 23, 2015-06-18 (James Jones) -- -- - Updated language for issue 12 to read as a proposed resolution. -- -- - Marked issues 11, 12, 13, 16, and 17 resolved. -- -- - Temporarily added links to the relevant bugs under the remaining -- unresolved issues. -- -- - Added issues 19 and 20 as well as proposed resolutions. -- -- - Revision 24, 2015-06-19 (Ian Elliott) -- -- - Changed special value for VkSurfacePropertiesKHR::currentExtent -- back to “-1” from “0”. This value will never need to be -- unsigned, and “0” is actually a legal value. -- -- - Revision 25, 2015-06-23 (Ian Elliott) -- -- - Examples now show use of function pointers for extension -- functions. -- -- - Eliminated extraneous whitespace. -- -- - Revision 26, 2015-06-25 (Ian Elliott) -- -- - Resolved Issues 9 & 10 per KHR TSG meeting. -- -- - Revision 27, 2015-06-25 (James Jones) -- -- - Added oldSwapchain member to VkSwapchainCreateInfoKHR. -- -- - Revision 28, 2015-06-25 (James Jones) -- -- - Added the “inherit” bits to the rotation and mirroring flags and -- the associated issue 21. -- -- - Revision 29, 2015-06-25 (James Jones) -- -- - Added the “clipped” flag to VkSwapchainCreateInfoKHR, and the -- associated issue 22. -- -- - Specified that presenting an image does not modify it. -- -- - Revision 30, 2015-06-25 (James Jones) -- -- - Added language to the spec that clarifies the behavior of -- vkCreateSwapchainKHR() when the oldSwapchain field of -- VkSwapchainCreateInfoKHR is not NULL. -- -- - Revision 31, 2015-06-26 (Ian Elliott) -- -- - Example of new VkSwapchainCreateInfoKHR members, “oldSwapchain” -- and “clipped”. -- -- - Example of using VkSurfacePropertiesKHR::{min|max}ImageCount to -- set VkSwapchainCreateInfoKHR::minImageCount. -- -- - Rename vkGetSurfaceInfoKHR()\'s 4th parameter to “pDataSize”, -- for consistency with other functions. -- -- - Add macro with C-string name of extension (just to header file). -- -- - Revision 32, 2015-06-26 (James Jones) -- -- - Minor adjustments to the language describing the behavior of -- “oldSwapchain” -- -- - Fixed the version date on my previous two updates. -- -- - Revision 33, 2015-06-26 (Jesse Hall) -- -- - Add usage flags to VkSwapchainCreateInfoKHR -- -- - Revision 34, 2015-06-26 (Ian Elliott) -- -- - Rename vkQueuePresentKHR()\'s 2nd parameter to “pPresentInfo”, -- for consistency with other functions. -- -- - Revision 35, 2015-06-26 (Jason Ekstrand) -- -- - Merged the VkRotationFlagBitsKHR and VkMirrorFlagBitsKHR enums -- into a single VkSurfaceTransformFlagBitsKHR enum. -- -- - Revision 36, 2015-06-26 (Jason Ekstrand) -- -- - Added a VkSurfaceTransformKHR enum that is not a bitmask. Each -- value in VkSurfaceTransformKHR corresponds directly to one of -- the bits in VkSurfaceTransformFlagBitsKHR so transforming from -- one to the other is easy. Having a separate enum means that -- currentTransform and preTransform are now unambiguous by -- definition. -- -- - Revision 37, 2015-06-29 (Ian Elliott) -- -- - Corrected one of the signatures of vkAcquireNextImageKHR, which -- had the last two parameters switched from what it is elsewhere -- in the specification and header files. -- -- - Revision 38, 2015-06-30 (Ian Elliott) -- -- - Corrected a typo in description of the vkGetSwapchainInfoKHR() -- function. -- -- - Corrected a typo in header file comment for -- VkPresentInfoKHR::sType. -- -- - Revision 39, 2015-07-07 (Daniel Rakos) -- -- - Added error section describing when each error is expected to be -- reported. -- -- - Replaced bool32_t with VkBool32. -- -- - Revision 40, 2015-07-10 (Ian Elliott) -- -- - Updated to work with version 138 of the @vulkan.h@ header. This -- includes declaring the VkSwapchainKHR type using the new -- VK_DEFINE_NONDISP_HANDLE macro, and no longer extending -- VkObjectType (which was eliminated). -- -- - Revision 41 2015-07-09 (Mathias Heyer) -- -- - Added color space language. -- -- - Revision 42, 2015-07-10 (Daniel Rakos) -- -- - Updated query mechanism to reflect the convention changes done -- in the core spec. -- -- - Removed “queue” from the name of -- VK_STRUCTURE_TYPE_QUEUE_PRESENT_INFO_KHR to be consistent with -- the established naming convention. -- -- - Removed reference to the no longer existing VkObjectType enum. -- -- - Revision 43, 2015-07-17 (Daniel Rakos) -- -- - Added support for concurrent sharing of swapchain images across -- queue families. -- -- - Updated sample code based on recent changes -- -- - Revision 44, 2015-07-27 (Ian Elliott) -- -- - Noted that support for VK_PRESENT_MODE_FIFO_KHR is required. -- That is ICDs may optionally support IMMEDIATE and MAILBOX, but -- must support FIFO. -- -- - Revision 45, 2015-08-07 (Ian Elliott) -- -- - Corrected a typo in spec file (type and variable name had wrong -- case for the imageColorSpace member of the -- VkSwapchainCreateInfoKHR struct). -- -- - Corrected a typo in header file (last parameter in -- PFN_vkGetSurfacePropertiesKHR was missing “KHR” at the end of -- type: VkSurfacePropertiesKHR). -- -- - Revision 46, 2015-08-20 (Ian Elliott) -- -- - Renamed this extension and all of its enumerations, types, -- functions, etc. This makes it compliant with the proposed -- standard for Vulkan extensions. -- -- - Switched from “revision” to “version”, including use of the -- VK_MAKE_VERSION macro in the header file. -- -- - Made improvements to several descriptions. -- -- - Changed the status of several issues from PROPOSED to RESOLVED, -- leaving no unresolved issues. -- -- - Resolved several TODOs, did miscellaneous cleanup, etc. -- -- - Revision 47, 2015-08-20 (Ian Elliott—​porting a 2015-07-29 change -- from James Jones) -- -- - Moved the surface transform enums to VK_WSI_swapchain so they -- could be reused by VK_WSI_display. -- -- - Revision 48, 2015-09-01 (James Jones) -- -- - Various minor cleanups. -- -- - Revision 49, 2015-09-01 (James Jones) -- -- - Restore single-field revision number. -- -- - Revision 50, 2015-09-01 (James Jones) -- -- - Update Example #4 to include code that illustrates how to use -- the oldSwapchain field. -- -- - Revision 51, 2015-09-01 (James Jones) -- -- - Fix example code compilation errors. -- -- - Revision 52, 2015-09-08 (Matthaeus G. Chajdas) -- -- - Corrected a typo. -- -- - Revision 53, 2015-09-10 (Alon Or-bach) -- -- - Removed underscore from SWAP_CHAIN left in -- VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR. -- -- - Revision 54, 2015-09-11 (Jesse Hall) -- -- - Described the execution and memory coherence requirements for -- image transitions to and from -- VK_IMAGE_LAYOUT_PRESENT_SOURCE_KHR. -- -- - Revision 55, 2015-09-11 (Ray Smith) -- -- - Added errors for destroying and binding memory to presentable -- images -- -- - Revision 56, 2015-09-18 (James Jones) -- -- - Added fence argument to vkAcquireNextImageKHR -- -- - Added example of how to meter a host thread based on -- presentation rate. -- -- - Revision 57, 2015-09-26 (Jesse Hall) -- -- - Replace VkSurfaceDescriptionKHR with VkSurfaceKHR. -- -- - Added issue 25 with agreed resolution. -- -- - Revision 58, 2015-09-28 (Jesse Hall) -- -- - Renamed from VK_EXT_KHR_device_swapchain to -- VK_EXT_KHR_swapchain. -- -- - Revision 59, 2015-09-29 (Ian Elliott) -- -- - Changed vkDestroySwapchainKHR() to return void. -- -- - Revision 60, 2015-10-01 (Jeff Vigil) -- -- - Added error result VK_ERROR_SURFACE_LOST_KHR. -- -- - Revision 61, 2015-10-05 (Jason Ekstrand) -- -- - Added the VkCompositeAlpha enum and corresponding structure -- fields. -- -- - Revision 62, 2015-10-12 (Daniel Rakos) -- -- - Added VK_PRESENT_MODE_FIFO_RELAXED_KHR. -- -- - Revision 63, 2015-10-15 (Daniel Rakos) -- -- - Moved surface capability queries to VK_EXT_KHR_surface. -- -- - Revision 64, 2015-10-26 (Ian Elliott) -- -- - Renamed from VK_EXT_KHR_swapchain to VK_KHR_swapchain. -- -- - Revision 65, 2015-10-28 (Ian Elliott) -- -- - Added optional pResult member to VkPresentInfoKHR, so that -- per-swapchain results can be obtained from vkQueuePresentKHR(). -- -- - Revision 66, 2015-11-03 (Daniel Rakos) -- -- - Added allocation callbacks to create and destroy functions. -- -- - Updated resource transition language. -- -- - Updated sample code. -- -- - Revision 67, 2015-11-10 (Jesse Hall) -- -- - Add reserved flags bitmask to VkSwapchainCreateInfoKHR. -- -- - Modify naming and member ordering to match API style -- conventions, and so the VkSwapchainCreateInfoKHR image property -- members mirror corresponding VkImageCreateInfo members but with -- an \'image\' prefix. -- -- - Make VkPresentInfoKHR::pResults non-const; it is an output array -- parameter. -- -- - Make pPresentInfo parameter to vkQueuePresentKHR const. -- -- - Revision 68, 2016-04-05 (Ian Elliott) -- -- - Moved the “validity” include for vkAcquireNextImage to be in its -- proper place, after the prototype and list of parameters. -- -- - Clarified language about presentable images, including how they -- are acquired, when applications can and cannot use them, etc. As -- part of this, removed language about “ownership” of presentable -- images, and replaced it with more-consistent language about -- presentable images being “acquired” by the application. -- -- - 2016-08-23 (Ian Elliott) -- -- - Update the example code, to use the final API command names, to -- not have so many characters per line, and to split out a new -- example to show how to obtain function pointers. This code is -- more similar to the LunarG “cube” demo program. -- -- - 2016-08-25 (Ian Elliott) -- -- - A note was added at the beginning of the example code, stating -- that it will be removed from future versions of the appendix. -- -- - Revision 69, 2017-09-07 (Tobias Hector) -- -- - Added interactions with Vulkan 1.1 -- -- - Revision 70, 2017-10-06 (Ian Elliott) -- -- - Corrected interactions with Vulkan 1.1 -- -- == See Also -- -- 'PresentInfoKHR', 'SwapchainCreateFlagBitsKHR', -- 'SwapchainCreateFlagsKHR', 'SwapchainCreateInfoKHR', -- 'Vulkan.Extensions.Handles.SwapchainKHR', 'acquireNextImageKHR', -- 'createSwapchainKHR', 'destroySwapchainKHR', 'getSwapchainImagesKHR', -- 'queuePresentKHR' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_swapchain Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_KHR_swapchain ( createSwapchainKHR , withSwapchainKHR , destroySwapchainKHR , getSwapchainImagesKHR , acquireNextImageKHR , acquireNextImageKHRSafe , queuePresentKHR , getDeviceGroupPresentCapabilitiesKHR , getDeviceGroupSurfacePresentModesKHR , acquireNextImage2KHR , acquireNextImage2KHRSafe , getPhysicalDevicePresentRectanglesKHR , SwapchainCreateInfoKHR(..) , PresentInfoKHR(..) , DeviceGroupPresentCapabilitiesKHR(..) , ImageSwapchainCreateInfoKHR(..) , BindImageMemorySwapchainInfoKHR(..) , AcquireNextImageInfoKHR(..) , DeviceGroupPresentInfoKHR(..) , DeviceGroupSwapchainCreateInfoKHR(..) , DeviceGroupPresentModeFlagsKHR , DeviceGroupPresentModeFlagBitsKHR( DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR , DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR , DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR , DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR , .. ) , SwapchainCreateFlagsKHR , SwapchainCreateFlagBitsKHR( SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR , SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR , SWAPCHAIN_CREATE_PROTECTED_BIT_KHR , .. ) , KHR_SWAPCHAIN_SPEC_VERSION , pattern KHR_SWAPCHAIN_SPEC_VERSION , KHR_SWAPCHAIN_EXTENSION_NAME , pattern KHR_SWAPCHAIN_EXTENSION_NAME , SurfaceKHR(..) , SwapchainKHR(..) , PresentModeKHR(..) , ColorSpaceKHR(..) , CompositeAlphaFlagBitsKHR(..) , CompositeAlphaFlagsKHR , SurfaceTransformFlagBitsKHR(..) , SurfaceTransformFlagsKHR ) where import Vulkan.CStruct.Utils (FixedArray) import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Data.Typeable (eqT) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (castPtr) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showString) import Numeric (showHex) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Data.String (IsString) import Data.Type.Equality ((:~:)(Refl)) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Word (Word32) import Data.Word (Word64) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.CStruct.Extends (forgetExtensions) import Vulkan.CStruct.Utils (lowerArrayPtr) import Vulkan.NamedType ((:::)) import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.CStruct.Extends (Chain) import Vulkan.Extensions.VK_KHR_surface (ColorSpaceKHR) import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagBitsKHR) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkAcquireNextImage2KHR)) import Vulkan.Dynamic (DeviceCmds(pVkAcquireNextImageKHR)) import Vulkan.Dynamic (DeviceCmds(pVkCreateSwapchainKHR)) import Vulkan.Dynamic (DeviceCmds(pVkDestroySwapchainKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetDeviceGroupPresentCapabilitiesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetDeviceGroupSurfacePresentModesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetSwapchainImagesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkQueuePresentKHR)) import Vulkan.Core10.Handles (Device_T) import {-# SOURCE #-} Vulkan.Extensions.VK_KHR_display_swapchain (DisplayPresentInfoKHR) import Vulkan.CStruct.Extends (Extends) import Vulkan.CStruct.Extends (Extendss) import Vulkan.CStruct.Extends (Extensible(..)) import Vulkan.Core10.FundamentalTypes (Extent2D) import Vulkan.Core10.Handles (Fence) import Vulkan.Core10.Handles (Fence(..)) import Vulkan.Core10.FundamentalTypes (Flags) import Vulkan.Core10.Enums.Format (Format) import Vulkan.Core10.Handles (Image) import Vulkan.Core10.Handles (Image(..)) import {-# SOURCE #-} Vulkan.Core12.Promoted_From_VK_KHR_image_format_list (ImageFormatListCreateInfo) import Vulkan.Core10.Enums.ImageUsageFlagBits (ImageUsageFlags) import Vulkan.Dynamic (InstanceCmds(pVkGetPhysicalDevicePresentRectanglesKHR)) import Vulkan.Core10.APIConstants (MAX_DEVICE_GROUP_SIZE) import Vulkan.CStruct.Extends (PeekChain) import Vulkan.CStruct.Extends (PeekChain(..)) import Vulkan.Core10.Handles (PhysicalDevice) import Vulkan.Core10.Handles (PhysicalDevice(..)) import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice)) import Vulkan.Core10.Handles (PhysicalDevice_T) import Vulkan.CStruct.Extends (PokeChain) import Vulkan.CStruct.Extends (PokeChain(..)) import {-# SOURCE #-} Vulkan.Extensions.VK_GGP_frame_token (PresentFrameTokenGGP) import {-# SOURCE #-} Vulkan.Extensions.VK_KHR_present_id (PresentIdKHR) import Vulkan.Extensions.VK_KHR_surface (PresentModeKHR) import {-# SOURCE #-} Vulkan.Extensions.VK_KHR_incremental_present (PresentRegionsKHR) import {-# SOURCE #-} Vulkan.Extensions.VK_GOOGLE_display_timing (PresentTimesInfoGOOGLE) import Vulkan.Core10.Handles (Queue) import Vulkan.Core10.Handles (Queue(..)) import Vulkan.Core10.Handles (Queue(Queue)) import Vulkan.Core10.Handles (Queue_T) import Vulkan.Core10.FundamentalTypes (Rect2D) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core10.Handles (Semaphore) import Vulkan.Core10.Handles (Semaphore(..)) import Vulkan.Core10.Enums.SharingMode (SharingMode) import Vulkan.CStruct.Extends (SomeStruct) import Vulkan.Core10.Enums.StructureType (StructureType) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_full_screen_exclusive (SurfaceFullScreenExclusiveInfoEXT) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_full_screen_exclusive (SurfaceFullScreenExclusiveWin32InfoEXT) import Vulkan.Extensions.Handles (SurfaceKHR) import Vulkan.Extensions.Handles (SurfaceKHR(..)) import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagBitsKHR) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_display_control (SwapchainCounterCreateInfoEXT) import {-# SOURCE #-} Vulkan.Extensions.VK_AMD_display_native_hdr (SwapchainDisplayNativeHdrCreateInfoAMD) import Vulkan.Extensions.Handles (SwapchainKHR) import Vulkan.Extensions.Handles (SwapchainKHR(..)) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.APIConstants (pattern MAX_DEVICE_GROUP_SIZE) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PRESENT_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Extensions.VK_KHR_surface (ColorSpaceKHR(..)) import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagBitsKHR(..)) import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagsKHR) import Vulkan.Extensions.VK_KHR_surface (PresentModeKHR(..)) import Vulkan.Extensions.Handles (SurfaceKHR(..)) import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagBitsKHR(..)) import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagsKHR) import Vulkan.Extensions.Handles (SwapchainKHR(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCreateSwapchainKHR :: FunPtr (Ptr Device_T -> Ptr (SomeStruct SwapchainCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr SwapchainKHR -> IO Result) -> Ptr Device_T -> Ptr (SomeStruct SwapchainCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr SwapchainKHR -> IO Result -- | vkCreateSwapchainKHR - Create a swapchain -- -- = Description -- -- If the @oldSwapchain@ parameter of @pCreateInfo@ is a valid swapchain, -- which has exclusive full-screen access, that access is released from -- @oldSwapchain@. If the command succeeds in this case, the newly created -- swapchain will automatically acquire exclusive full-screen access from -- @oldSwapchain@. -- -- Note -- -- This implicit transfer is intended to avoid exiting and entering -- full-screen exclusive mode, which may otherwise cause unwanted visual -- updates to the display. -- -- In some cases, swapchain creation /may/ fail if exclusive full-screen -- mode is requested for application control, but for some -- implementation-specific reason exclusive full-screen access is -- unavailable for the particular combination of parameters provided. If -- this occurs, 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- will be returned. -- -- Note -- -- In particular, it will fail if the @imageExtent@ member of @pCreateInfo@ -- does not match the extents of the monitor. Other reasons for failure may -- include the app not being set as high-dpi aware, or if the physical -- device and monitor are not compatible in this mode. -- -- When the 'Vulkan.Extensions.Handles.SurfaceKHR' in -- 'SwapchainCreateInfoKHR' is a display surface, then the -- 'Vulkan.Extensions.Handles.DisplayModeKHR' in display surface’s -- 'Vulkan.Extensions.VK_KHR_display.DisplaySurfaceCreateInfoKHR' is -- associated with a particular 'Vulkan.Extensions.Handles.DisplayKHR'. -- Swapchain creation /may/ fail if that -- 'Vulkan.Extensions.Handles.DisplayKHR' is not acquired by the -- application. In this scenario -- 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' is returned. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCreateSwapchainKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkCreateSwapchainKHR-pCreateInfo-parameter# @pCreateInfo@ -- /must/ be a valid pointer to a valid 'SwapchainCreateInfoKHR' -- structure -- -- - #VUID-vkCreateSwapchainKHR-pAllocator-parameter# If @pAllocator@ is -- not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkCreateSwapchainKHR-pSwapchain-parameter# @pSwapchain@ /must/ -- be a valid pointer to a 'Vulkan.Extensions.Handles.SwapchainKHR' -- handle -- -- == Host Synchronization -- -- - Host access to @pCreateInfo->surface@ /must/ be externally -- synchronized -- -- - Host access to @pCreateInfo->oldSwapchain@ /must/ be externally -- synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_NATIVE_WINDOW_IN_USE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'SwapchainCreateInfoKHR', -- 'Vulkan.Extensions.Handles.SwapchainKHR' createSwapchainKHR :: forall a io . (Extendss SwapchainCreateInfoKHR a, PokeChain a, MonadIO io) => -- | @device@ is the device to create the swapchain for. Device -> -- | @pCreateInfo@ is a pointer to a 'SwapchainCreateInfoKHR' structure -- specifying the parameters of the created swapchain. (SwapchainCreateInfoKHR a) -> -- | @pAllocator@ is the allocator used for host memory allocated for the -- swapchain object when there is no more specific allocator available (see -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation>). ("allocator" ::: Maybe AllocationCallbacks) -> io (SwapchainKHR) createSwapchainKHR device createInfo allocator = liftIO . evalContT $ do let vkCreateSwapchainKHRPtr = pVkCreateSwapchainKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkCreateSwapchainKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateSwapchainKHR is null" Nothing Nothing let vkCreateSwapchainKHR' = mkVkCreateSwapchainKHR vkCreateSwapchainKHRPtr pCreateInfo <- ContT $ withCStruct (createInfo) pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) pPSwapchain <- ContT $ bracket (callocBytes @SwapchainKHR 8) free r <- lift $ traceAroundEvent "vkCreateSwapchainKHR" (vkCreateSwapchainKHR' (deviceHandle (device)) (forgetExtensions pCreateInfo) pAllocator (pPSwapchain)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pSwapchain <- lift $ peek @SwapchainKHR pPSwapchain pure $ (pSwapchain) -- | A convenience wrapper to make a compatible pair of calls to -- 'createSwapchainKHR' and 'destroySwapchainKHR' -- -- To ensure that 'destroySwapchainKHR' is always called: pass -- 'Control.Exception.bracket' (or the allocate function from your -- favourite resource management library) as the last argument. -- To just extract the pair pass '(,)' as the last argument. -- withSwapchainKHR :: forall a io r . (Extendss SwapchainCreateInfoKHR a, PokeChain a, MonadIO io) => Device -> SwapchainCreateInfoKHR a -> Maybe AllocationCallbacks -> (io SwapchainKHR -> (SwapchainKHR -> io ()) -> r) -> r withSwapchainKHR device pCreateInfo pAllocator b = b (createSwapchainKHR device pCreateInfo pAllocator) (\(o0) -> destroySwapchainKHR device o0 pAllocator) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkDestroySwapchainKHR :: FunPtr (Ptr Device_T -> SwapchainKHR -> Ptr AllocationCallbacks -> IO ()) -> Ptr Device_T -> SwapchainKHR -> Ptr AllocationCallbacks -> IO () -- | vkDestroySwapchainKHR - Destroy a swapchain object -- -- = Description -- -- The application /must/ not destroy a swapchain until after completion of -- all outstanding operations on images that were acquired from the -- swapchain. @swapchain@ and all associated 'Vulkan.Core10.Handles.Image' -- handles are destroyed, and /must/ not be acquired or used any more by -- the application. The memory of each 'Vulkan.Core10.Handles.Image' will -- only be freed after that image is no longer used by the presentation -- engine. For example, if one image of the swapchain is being displayed in -- a window, the memory for that image /may/ not be freed until the window -- is destroyed, or another swapchain is created for the window. Destroying -- the swapchain does not invalidate the parent -- 'Vulkan.Extensions.Handles.SurfaceKHR', and a new swapchain /can/ be -- created with it. -- -- When a swapchain associated with a display surface is destroyed, if the -- image most recently presented to the display surface is from the -- swapchain being destroyed, then either any display resources modified by -- presenting images from any swapchain associated with the display surface -- /must/ be reverted by the implementation to their state prior to the -- first present performed on one of these swapchains, or such resources -- /must/ be left in their current state. -- -- If @swapchain@ has exclusive full-screen access, it is released before -- the swapchain is destroyed. -- -- == Valid Usage -- -- - #VUID-vkDestroySwapchainKHR-swapchain-01282# All uses of presentable -- images acquired from @swapchain@ /must/ have completed execution -- -- - #VUID-vkDestroySwapchainKHR-swapchain-01283# If -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @swapchain@ was created, a compatible set of callbacks -- /must/ be provided here -- -- - #VUID-vkDestroySwapchainKHR-swapchain-01284# If no -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @swapchain@ was created, @pAllocator@ /must/ be @NULL@ -- -- == Valid Usage (Implicit) -- -- - #VUID-vkDestroySwapchainKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkDestroySwapchainKHR-swapchain-parameter# If @swapchain@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @swapchain@ /must/ be -- a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-vkDestroySwapchainKHR-pAllocator-parameter# If @pAllocator@ is -- not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkDestroySwapchainKHR-commonparent# Both of @device@, and -- @swapchain@ that are valid handles of non-ignored parameters /must/ -- have been created, allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Extensions.Handles.SwapchainKHR' destroySwapchainKHR :: forall io . (MonadIO io) => -- | @device@ is the 'Vulkan.Core10.Handles.Device' associated with -- @swapchain@. Device -> -- | @swapchain@ is the swapchain to destroy. SwapchainKHR -> -- | @pAllocator@ is the allocator used for host memory allocated for the -- swapchain object when there is no more specific allocator available (see -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation>). ("allocator" ::: Maybe AllocationCallbacks) -> io () destroySwapchainKHR device swapchain allocator = liftIO . evalContT $ do let vkDestroySwapchainKHRPtr = pVkDestroySwapchainKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkDestroySwapchainKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkDestroySwapchainKHR is null" Nothing Nothing let vkDestroySwapchainKHR' = mkVkDestroySwapchainKHR vkDestroySwapchainKHRPtr pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ traceAroundEvent "vkDestroySwapchainKHR" (vkDestroySwapchainKHR' (deviceHandle (device)) (swapchain) pAllocator) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetSwapchainImagesKHR :: FunPtr (Ptr Device_T -> SwapchainKHR -> Ptr Word32 -> Ptr Image -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Ptr Word32 -> Ptr Image -> IO Result -- | vkGetSwapchainImagesKHR - Obtain the array of presentable images -- associated with a swapchain -- -- = Description -- -- If @pSwapchainImages@ is @NULL@, then the number of presentable images -- for @swapchain@ is returned in @pSwapchainImageCount@. Otherwise, -- @pSwapchainImageCount@ /must/ point to a variable set by the user to the -- number of elements in the @pSwapchainImages@ array, and on return the -- variable is overwritten with the number of structures actually written -- to @pSwapchainImages@. If the value of @pSwapchainImageCount@ is less -- than the number of presentable images for @swapchain@, at most -- @pSwapchainImageCount@ structures will be written, and -- 'Vulkan.Core10.Enums.Result.INCOMPLETE' will be returned instead of -- 'Vulkan.Core10.Enums.Result.SUCCESS', to indicate that not all the -- available presentable images were returned. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetSwapchainImagesKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetSwapchainImagesKHR-swapchain-parameter# @swapchain@ -- /must/ be a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-vkGetSwapchainImagesKHR-pSwapchainImageCount-parameter# -- @pSwapchainImageCount@ /must/ be a valid pointer to a @uint32_t@ -- value -- -- - #VUID-vkGetSwapchainImagesKHR-pSwapchainImages-parameter# If the -- value referenced by @pSwapchainImageCount@ is not @0@, and -- @pSwapchainImages@ is not @NULL@, @pSwapchainImages@ /must/ be a -- valid pointer to an array of @pSwapchainImageCount@ -- 'Vulkan.Core10.Handles.Image' handles -- -- - #VUID-vkGetSwapchainImagesKHR-commonparent# Both of @device@, and -- @swapchain@ /must/ have been created, allocated, or retrieved from -- the same 'Vulkan.Core10.Handles.Instance' -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.INCOMPLETE' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Image', -- 'Vulkan.Extensions.Handles.SwapchainKHR' getSwapchainImagesKHR :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the swapchain to query. SwapchainKHR -> io (Result, ("swapchainImages" ::: Vector Image)) getSwapchainImagesKHR device swapchain = liftIO . evalContT $ do let vkGetSwapchainImagesKHRPtr = pVkGetSwapchainImagesKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkGetSwapchainImagesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetSwapchainImagesKHR is null" Nothing Nothing let vkGetSwapchainImagesKHR' = mkVkGetSwapchainImagesKHR vkGetSwapchainImagesKHRPtr let device' = deviceHandle (device) pPSwapchainImageCount <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkGetSwapchainImagesKHR" (vkGetSwapchainImagesKHR' device' (swapchain) (pPSwapchainImageCount) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pSwapchainImageCount <- lift $ peek @Word32 pPSwapchainImageCount pPSwapchainImages <- ContT $ bracket (callocBytes @Image ((fromIntegral (pSwapchainImageCount)) * 8)) free r' <- lift $ traceAroundEvent "vkGetSwapchainImagesKHR" (vkGetSwapchainImagesKHR' device' (swapchain) (pPSwapchainImageCount) (pPSwapchainImages)) lift $ when (r' < SUCCESS) (throwIO (VulkanException r')) pSwapchainImageCount' <- lift $ peek @Word32 pPSwapchainImageCount pSwapchainImages' <- lift $ generateM (fromIntegral (pSwapchainImageCount')) (\i -> peek @Image ((pPSwapchainImages `advancePtrBytes` (8 * (i)) :: Ptr Image))) pure $ ((r'), pSwapchainImages') foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkAcquireNextImageKHRUnsafe :: FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result foreign import ccall "dynamic" mkVkAcquireNextImageKHRSafe :: FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result -- | acquireNextImageKHR with selectable safeness acquireNextImageKHRSafeOrUnsafe :: forall io . (MonadIO io) => (FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain from which an image is being -- acquired. SwapchainKHR -> -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. ("timeout" ::: Word64) -> -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. Semaphore -> -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. Fence -> io (Result, ("imageIndex" ::: Word32)) acquireNextImageKHRSafeOrUnsafe mkVkAcquireNextImageKHR device swapchain timeout semaphore fence = liftIO . evalContT $ do let vkAcquireNextImageKHRPtr = pVkAcquireNextImageKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkAcquireNextImageKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquireNextImageKHR is null" Nothing Nothing let vkAcquireNextImageKHR' = mkVkAcquireNextImageKHR vkAcquireNextImageKHRPtr pPImageIndex <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkAcquireNextImageKHR" (vkAcquireNextImageKHR' (deviceHandle (device)) (swapchain) (timeout) (semaphore) (fence) (pPImageIndex)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pImageIndex <- lift $ peek @Word32 pPImageIndex pure $ (r, pImageIndex) -- | vkAcquireNextImageKHR - Retrieve the index of the next available -- presentable image -- -- == Valid Usage -- -- - #VUID-vkAcquireNextImageKHR-swapchain-01285# @swapchain@ /must/ not -- be in the retired state -- -- - #VUID-vkAcquireNextImageKHR-semaphore-01286# If @semaphore@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled -- -- - #VUID-vkAcquireNextImageKHR-semaphore-01779# If @semaphore@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ not have any -- uncompleted signal or wait operations pending -- -- - #VUID-vkAcquireNextImageKHR-fence-01287# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled and -- /must/ not be associated with any other queue command that has not -- yet completed execution on that queue -- -- - #VUID-vkAcquireNextImageKHR-semaphore-01780# @semaphore@ and @fence@ -- /must/ not both be equal to 'Vulkan.Core10.APIConstants.NULL_HANDLE' -- -- - #VUID-vkAcquireNextImageKHR-swapchain-01802# If the number of -- currently acquired images is greater than the difference between the -- number of images in @swapchain@ and the value of -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@minImageCount@ -- as returned by a call to -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- with the @surface@ used to create @swapchain@, @timeout@ /must/ not -- be @UINT64_MAX@ -- -- - #VUID-vkAcquireNextImageKHR-semaphore-03265# @semaphore@ /must/ have -- a 'Vulkan.Core12.Enums.SemaphoreType.SemaphoreType' of -- 'Vulkan.Core12.Enums.SemaphoreType.SEMAPHORE_TYPE_BINARY' -- -- == Valid Usage (Implicit) -- -- - #VUID-vkAcquireNextImageKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkAcquireNextImageKHR-swapchain-parameter# @swapchain@ /must/ -- be a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-vkAcquireNextImageKHR-semaphore-parameter# If @semaphore@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @semaphore@ /must/ be -- a valid 'Vulkan.Core10.Handles.Semaphore' handle -- -- - #VUID-vkAcquireNextImageKHR-fence-parameter# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @fence@ /must/ be a valid -- 'Vulkan.Core10.Handles.Fence' handle -- -- - #VUID-vkAcquireNextImageKHR-pImageIndex-parameter# @pImageIndex@ -- /must/ be a valid pointer to a @uint32_t@ value -- -- - #VUID-vkAcquireNextImageKHR-semaphore-parent# If @semaphore@ is a -- valid handle, it /must/ have been created, allocated, or retrieved -- from @device@ -- -- - #VUID-vkAcquireNextImageKHR-fence-parent# If @fence@ is a valid -- handle, it /must/ have been created, allocated, or retrieved from -- @device@ -- -- - #VUID-vkAcquireNextImageKHR-commonparent# Both of @device@, and -- @swapchain@ that are valid handles of non-ignored parameters /must/ -- have been created, allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- - Host access to @semaphore@ /must/ be externally synchronized -- -- - Host access to @fence@ /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.TIMEOUT' -- -- - 'Vulkan.Core10.Enums.Result.NOT_READY' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Fence', -- 'Vulkan.Core10.Handles.Semaphore', -- 'Vulkan.Extensions.Handles.SwapchainKHR' acquireNextImageKHR :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain from which an image is being -- acquired. SwapchainKHR -> -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. ("timeout" ::: Word64) -> -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. Semaphore -> -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. Fence -> io (Result, ("imageIndex" ::: Word32)) acquireNextImageKHR = acquireNextImageKHRSafeOrUnsafe mkVkAcquireNextImageKHRUnsafe -- | A variant of 'acquireNextImageKHR' which makes a *safe* FFI call acquireNextImageKHRSafe :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain from which an image is being -- acquired. SwapchainKHR -> -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. ("timeout" ::: Word64) -> -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. Semaphore -> -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. Fence -> io (Result, ("imageIndex" ::: Word32)) acquireNextImageKHRSafe = acquireNextImageKHRSafeOrUnsafe mkVkAcquireNextImageKHRSafe foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkQueuePresentKHR :: FunPtr (Ptr Queue_T -> Ptr (SomeStruct PresentInfoKHR) -> IO Result) -> Ptr Queue_T -> Ptr (SomeStruct PresentInfoKHR) -> IO Result -- | vkQueuePresentKHR - Queue an image for presentation -- -- = Description -- -- Note -- -- There is no requirement for an application to present images in the same -- order that they were acquired - applications can arbitrarily present any -- image that is currently acquired. -- -- == Valid Usage -- -- - #VUID-vkQueuePresentKHR-pSwapchains-01292# Each element of -- @pSwapchains@ member of @pPresentInfo@ /must/ be a swapchain that is -- created for a surface for which presentation is supported from -- @queue@ as determined using a call to -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- -- - #VUID-vkQueuePresentKHR-pSwapchains-01293# If more than one member -- of @pSwapchains@ was created from a display surface, all display -- surfaces referenced that refer to the same display /must/ use the -- same display mode -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-01294# When a semaphore wait -- operation referring to a binary semaphore defined by the elements of -- the @pWaitSemaphores@ member of @pPresentInfo@ executes on @queue@, -- there /must/ be no other queues waiting on the same semaphore -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-01295# All elements of the -- @pWaitSemaphores@ member of @pPresentInfo@ /must/ be semaphores that -- are signaled, or have -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-semaphores-signaling semaphore signal operations> -- previously submitted for execution -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-03267# All elements of the -- @pWaitSemaphores@ member of @pPresentInfo@ /must/ be created with a -- 'Vulkan.Core12.Enums.SemaphoreType.SemaphoreType' of -- 'Vulkan.Core12.Enums.SemaphoreType.SEMAPHORE_TYPE_BINARY' -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-03268# All elements of the -- @pWaitSemaphores@ member of @pPresentInfo@ /must/ reference a -- semaphore signal operation that has been submitted for execution and -- any semaphore signal operations on which it depends (if any) /must/ -- have also been submitted for execution -- -- Any writes to memory backing the images referenced by the -- @pImageIndices@ and @pSwapchains@ members of @pPresentInfo@, that are -- available before 'queuePresentKHR' is executed, are automatically made -- visible to the read access performed by the presentation engine. This -- automatic visibility operation for an image happens-after the semaphore -- signal operation, and happens-before the presentation engine accesses -- the image. -- -- Queueing an image for presentation defines a set of /queue operations/, -- including waiting on the semaphores and submitting a presentation -- request to the presentation engine. However, the scope of this set of -- queue operations does not include the actual processing of the image by -- the presentation engine. -- -- Note -- -- The origin of the native orientation of the surface coordinate system is -- not specified in the Vulkan specification; it depends on the platform. -- For most platforms the origin is by default upper-left, meaning the -- pixel of the presented 'Vulkan.Core10.Handles.Image' at coordinates -- (0,0) would appear at the upper left pixel of the platform surface -- (assuming -- 'Vulkan.Extensions.VK_KHR_surface.SURFACE_TRANSFORM_IDENTITY_BIT_KHR', -- and the display standing the right way up). -- -- If 'queuePresentKHR' fails to enqueue the corresponding set of queue -- operations, it /may/ return -- 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' or -- 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY'. If it does, the -- implementation /must/ ensure that the state and contents of any -- resources or synchronization primitives referenced is unaffected by the -- call or its failure. -- -- If 'queuePresentKHR' fails in such a way that the implementation is -- unable to make that guarantee, the implementation /must/ return -- 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST'. -- -- However, if the presentation request is rejected by the presentation -- engine with an error 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR', -- 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT', -- or 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR', the set of queue -- operations are still considered to be enqueued and thus any semaphore -- wait operation specified in 'PresentInfoKHR' will execute when the -- corresponding queue operation is complete. -- -- Calls to 'queuePresentKHR' /may/ block, but /must/ return in finite -- time. -- -- If any @swapchain@ member of @pPresentInfo@ was created with -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT', -- 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- will be returned if that swapchain does not have exclusive full-screen -- access, possibly for implementation-specific reasons outside of the -- application’s control. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkQueuePresentKHR-queue-parameter# @queue@ /must/ be a valid -- 'Vulkan.Core10.Handles.Queue' handle -- -- - #VUID-vkQueuePresentKHR-pPresentInfo-parameter# @pPresentInfo@ -- /must/ be a valid pointer to a valid 'PresentInfoKHR' structure -- -- == Host Synchronization -- -- - Host access to @queue@ /must/ be externally synchronized -- -- - Host access to @pPresentInfo->pWaitSemaphores@[] /must/ be -- externally synchronized -- -- - Host access to @pPresentInfo->pSwapchains@[] /must/ be externally -- synchronized -- -- == Command Properties -- -- \' -- -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> | -- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+ -- | - | - | Any | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'PresentInfoKHR', 'Vulkan.Core10.Handles.Queue' queuePresentKHR :: forall a io . (Extendss PresentInfoKHR a, PokeChain a, MonadIO io) => -- | @queue@ is a queue that is capable of presentation to the target -- surface’s platform on the same device as the image’s swapchain. Queue -> -- | @pPresentInfo@ is a pointer to a 'PresentInfoKHR' structure specifying -- parameters of the presentation. (PresentInfoKHR a) -> io (Result) queuePresentKHR queue presentInfo = liftIO . evalContT $ do let vkQueuePresentKHRPtr = pVkQueuePresentKHR (case queue of Queue{deviceCmds} -> deviceCmds) lift $ unless (vkQueuePresentKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkQueuePresentKHR is null" Nothing Nothing let vkQueuePresentKHR' = mkVkQueuePresentKHR vkQueuePresentKHRPtr pPresentInfo <- ContT $ withCStruct (presentInfo) r <- lift $ traceAroundEvent "vkQueuePresentKHR" (vkQueuePresentKHR' (queueHandle (queue)) (forgetExtensions pPresentInfo)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pure $ (r) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetDeviceGroupPresentCapabilitiesKHR :: FunPtr (Ptr Device_T -> Ptr DeviceGroupPresentCapabilitiesKHR -> IO Result) -> Ptr Device_T -> Ptr DeviceGroupPresentCapabilitiesKHR -> IO Result -- | vkGetDeviceGroupPresentCapabilitiesKHR - Query present capabilities from -- other physical devices -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.Device', 'DeviceGroupPresentCapabilitiesKHR' getDeviceGroupPresentCapabilitiesKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device. -- -- #VUID-vkGetDeviceGroupPresentCapabilitiesKHR-device-parameter# @device@ -- /must/ be a valid 'Vulkan.Core10.Handles.Device' handle Device -> io (DeviceGroupPresentCapabilitiesKHR) getDeviceGroupPresentCapabilitiesKHR device = liftIO . evalContT $ do let vkGetDeviceGroupPresentCapabilitiesKHRPtr = pVkGetDeviceGroupPresentCapabilitiesKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkGetDeviceGroupPresentCapabilitiesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetDeviceGroupPresentCapabilitiesKHR is null" Nothing Nothing let vkGetDeviceGroupPresentCapabilitiesKHR' = mkVkGetDeviceGroupPresentCapabilitiesKHR vkGetDeviceGroupPresentCapabilitiesKHRPtr pPDeviceGroupPresentCapabilities <- ContT (withZeroCStruct @DeviceGroupPresentCapabilitiesKHR) r <- lift $ traceAroundEvent "vkGetDeviceGroupPresentCapabilitiesKHR" (vkGetDeviceGroupPresentCapabilitiesKHR' (deviceHandle (device)) (pPDeviceGroupPresentCapabilities)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pDeviceGroupPresentCapabilities <- lift $ peekCStruct @DeviceGroupPresentCapabilitiesKHR pPDeviceGroupPresentCapabilities pure $ (pDeviceGroupPresentCapabilities) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetDeviceGroupSurfacePresentModesKHR :: FunPtr (Ptr Device_T -> SurfaceKHR -> Ptr DeviceGroupPresentModeFlagsKHR -> IO Result) -> Ptr Device_T -> SurfaceKHR -> Ptr DeviceGroupPresentModeFlagsKHR -> IO Result -- | vkGetDeviceGroupSurfacePresentModesKHR - Query present capabilities for -- a surface -- -- = Description -- -- The modes returned by this command are not invariant, and /may/ change -- in response to the surface being moved, resized, or occluded. These -- modes /must/ be a subset of the modes returned by -- 'getDeviceGroupPresentCapabilitiesKHR'. -- -- == Valid Usage -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-surface-06212# -- @surface@ /must/ be supported by all physical devices associated -- with @device@, as reported by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- or an equivalent platform-specific mechanism -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-surface-parameter# -- @surface@ /must/ be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' -- handle -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-pModes-parameter# -- @pModes@ /must/ be a valid pointer to a -- 'DeviceGroupPresentModeFlagsKHR' value -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-commonparent# Both of -- @device@, and @surface@ /must/ have been created, allocated, or -- retrieved from the same 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @surface@ /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.Device', 'DeviceGroupPresentModeFlagsKHR', -- 'Vulkan.Extensions.Handles.SurfaceKHR' getDeviceGroupSurfacePresentModesKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device. Device -> -- | @surface@ is the surface. SurfaceKHR -> io (("modes" ::: DeviceGroupPresentModeFlagsKHR)) getDeviceGroupSurfacePresentModesKHR device surface = liftIO . evalContT $ do let vkGetDeviceGroupSurfacePresentModesKHRPtr = pVkGetDeviceGroupSurfacePresentModesKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkGetDeviceGroupSurfacePresentModesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetDeviceGroupSurfacePresentModesKHR is null" Nothing Nothing let vkGetDeviceGroupSurfacePresentModesKHR' = mkVkGetDeviceGroupSurfacePresentModesKHR vkGetDeviceGroupSurfacePresentModesKHRPtr pPModes <- ContT $ bracket (callocBytes @DeviceGroupPresentModeFlagsKHR 4) free r <- lift $ traceAroundEvent "vkGetDeviceGroupSurfacePresentModesKHR" (vkGetDeviceGroupSurfacePresentModesKHR' (deviceHandle (device)) (surface) (pPModes)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pModes <- lift $ peek @DeviceGroupPresentModeFlagsKHR pPModes pure $ (pModes) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkAcquireNextImage2KHRUnsafe :: FunPtr (Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result foreign import ccall "dynamic" mkVkAcquireNextImage2KHRSafe :: FunPtr (Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result -- | acquireNextImage2KHR with selectable safeness acquireNextImage2KHRSafeOrUnsafe :: forall io . (MonadIO io) => (FunPtr (Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> -- | @device@ is the device associated with @swapchain@. Device -> -- | @pAcquireInfo@ is a pointer to a 'AcquireNextImageInfoKHR' structure -- containing parameters of the acquire. ("acquireInfo" ::: AcquireNextImageInfoKHR) -> io (Result, ("imageIndex" ::: Word32)) acquireNextImage2KHRSafeOrUnsafe mkVkAcquireNextImage2KHR device acquireInfo = liftIO . evalContT $ do let vkAcquireNextImage2KHRPtr = pVkAcquireNextImage2KHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkAcquireNextImage2KHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquireNextImage2KHR is null" Nothing Nothing let vkAcquireNextImage2KHR' = mkVkAcquireNextImage2KHR vkAcquireNextImage2KHRPtr pAcquireInfo <- ContT $ withCStruct (acquireInfo) pPImageIndex <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkAcquireNextImage2KHR" (vkAcquireNextImage2KHR' (deviceHandle (device)) pAcquireInfo (pPImageIndex)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pImageIndex <- lift $ peek @Word32 pPImageIndex pure $ (r, pImageIndex) -- | vkAcquireNextImage2KHR - Retrieve the index of the next available -- presentable image -- -- == Valid Usage -- -- - #VUID-vkAcquireNextImage2KHR-swapchain-01803# If the number of -- currently acquired images is greater than the difference between the -- number of images in the @swapchain@ member of @pAcquireInfo@ and the -- value of -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@minImageCount@ -- as returned by a call to -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- with the @surface@ used to create @swapchain@, the @timeout@ member -- of @pAcquireInfo@ /must/ not be @UINT64_MAX@ -- -- == Valid Usage (Implicit) -- -- - #VUID-vkAcquireNextImage2KHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkAcquireNextImage2KHR-pAcquireInfo-parameter# @pAcquireInfo@ -- /must/ be a valid pointer to a valid 'AcquireNextImageInfoKHR' -- structure -- -- - #VUID-vkAcquireNextImage2KHR-pImageIndex-parameter# @pImageIndex@ -- /must/ be a valid pointer to a @uint32_t@ value -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.TIMEOUT' -- -- - 'Vulkan.Core10.Enums.Result.NOT_READY' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'AcquireNextImageInfoKHR', 'Vulkan.Core10.Handles.Device' acquireNextImage2KHR :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @pAcquireInfo@ is a pointer to a 'AcquireNextImageInfoKHR' structure -- containing parameters of the acquire. ("acquireInfo" ::: AcquireNextImageInfoKHR) -> io (Result, ("imageIndex" ::: Word32)) acquireNextImage2KHR = acquireNextImage2KHRSafeOrUnsafe mkVkAcquireNextImage2KHRUnsafe -- | A variant of 'acquireNextImage2KHR' which makes a *safe* FFI call acquireNextImage2KHRSafe :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @pAcquireInfo@ is a pointer to a 'AcquireNextImageInfoKHR' structure -- containing parameters of the acquire. ("acquireInfo" ::: AcquireNextImageInfoKHR) -> io (Result, ("imageIndex" ::: Word32)) acquireNextImage2KHRSafe = acquireNextImage2KHRSafeOrUnsafe mkVkAcquireNextImage2KHRSafe foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetPhysicalDevicePresentRectanglesKHR :: FunPtr (Ptr PhysicalDevice_T -> SurfaceKHR -> Ptr Word32 -> Ptr Rect2D -> IO Result) -> Ptr PhysicalDevice_T -> SurfaceKHR -> Ptr Word32 -> Ptr Rect2D -> IO Result -- | vkGetPhysicalDevicePresentRectanglesKHR - Query present rectangles for a -- surface on a physical device -- -- = Description -- -- If @pRects@ is @NULL@, then the number of rectangles used when -- presenting the given @surface@ is returned in @pRectCount@. Otherwise, -- @pRectCount@ /must/ point to a variable set by the user to the number of -- elements in the @pRects@ array, and on return the variable is -- overwritten with the number of structures actually written to @pRects@. -- If the value of @pRectCount@ is less than the number of rectangles, at -- most @pRectCount@ structures will be written, and -- 'Vulkan.Core10.Enums.Result.INCOMPLETE' will be returned instead of -- 'Vulkan.Core10.Enums.Result.SUCCESS', to indicate that not all the -- available rectangles were returned. -- -- The values returned by this command are not invariant, and /may/ change -- in response to the surface being moved, resized, or occluded. -- -- The rectangles returned by this command /must/ not overlap. -- -- == Valid Usage -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-surface-06523# -- @surface@ /must/ be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' -- handle -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-surface-06211# -- @surface@ /must/ be supported by @physicalDevice@, as reported by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- or an equivalent platform-specific mechanism -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-physicalDevice-parameter# -- @physicalDevice@ /must/ be a valid -- 'Vulkan.Core10.Handles.PhysicalDevice' handle -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-surface-parameter# -- @surface@ /must/ be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' -- handle -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-pRectCount-parameter# -- @pRectCount@ /must/ be a valid pointer to a @uint32_t@ value -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-pRects-parameter# If -- the value referenced by @pRectCount@ is not @0@, and @pRects@ is not -- @NULL@, @pRects@ /must/ be a valid pointer to an array of -- @pRectCount@ 'Vulkan.Core10.FundamentalTypes.Rect2D' structures -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-commonparent# Both of -- @physicalDevice@, and @surface@ /must/ have been created, allocated, -- or retrieved from the same 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @surface@ /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.INCOMPLETE' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.PhysicalDevice', -- 'Vulkan.Core10.FundamentalTypes.Rect2D', -- 'Vulkan.Extensions.Handles.SurfaceKHR' getPhysicalDevicePresentRectanglesKHR :: forall io . (MonadIO io) => -- | @physicalDevice@ is the physical device. PhysicalDevice -> -- | @surface@ is the surface. SurfaceKHR -> io (Result, ("rects" ::: Vector Rect2D)) getPhysicalDevicePresentRectanglesKHR physicalDevice surface = liftIO . evalContT $ do let vkGetPhysicalDevicePresentRectanglesKHRPtr = pVkGetPhysicalDevicePresentRectanglesKHR (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) lift $ unless (vkGetPhysicalDevicePresentRectanglesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPhysicalDevicePresentRectanglesKHR is null" Nothing Nothing let vkGetPhysicalDevicePresentRectanglesKHR' = mkVkGetPhysicalDevicePresentRectanglesKHR vkGetPhysicalDevicePresentRectanglesKHRPtr let physicalDevice' = physicalDeviceHandle (physicalDevice) pPRectCount <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkGetPhysicalDevicePresentRectanglesKHR" (vkGetPhysicalDevicePresentRectanglesKHR' physicalDevice' (surface) (pPRectCount) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pRectCount <- lift $ peek @Word32 pPRectCount pPRects <- ContT $ bracket (callocBytes @Rect2D ((fromIntegral (pRectCount)) * 16)) free _ <- traverse (\i -> ContT $ pokeZeroCStruct (pPRects `advancePtrBytes` (i * 16) :: Ptr Rect2D) . ($ ())) [0..(fromIntegral (pRectCount)) - 1] r' <- lift $ traceAroundEvent "vkGetPhysicalDevicePresentRectanglesKHR" (vkGetPhysicalDevicePresentRectanglesKHR' physicalDevice' (surface) (pPRectCount) ((pPRects))) lift $ when (r' < SUCCESS) (throwIO (VulkanException r')) pRectCount' <- lift $ peek @Word32 pPRectCount pRects' <- lift $ generateM (fromIntegral (pRectCount')) (\i -> peekCStruct @Rect2D (((pPRects) `advancePtrBytes` (16 * (i)) :: Ptr Rect2D))) pure $ ((r'), pRects') -- | VkSwapchainCreateInfoKHR - Structure specifying parameters of a newly -- created swapchain object -- -- = Description -- -- Upon calling 'createSwapchainKHR' with an @oldSwapchain@ that is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @oldSwapchain@ is -- retired — even if creation of the new swapchain fails. The new swapchain -- is created in the non-retired state whether or not @oldSwapchain@ is -- 'Vulkan.Core10.APIConstants.NULL_HANDLE'. -- -- Upon calling 'createSwapchainKHR' with an @oldSwapchain@ that is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', any images from @oldSwapchain@ -- that are not acquired by the application /may/ be freed by the -- implementation, which /may/ occur even if creation of the new swapchain -- fails. The application /can/ destroy @oldSwapchain@ to free all memory -- associated with @oldSwapchain@. -- -- Note -- -- Multiple retired swapchains /can/ be associated with the same -- 'Vulkan.Extensions.Handles.SurfaceKHR' through multiple uses of -- @oldSwapchain@ that outnumber calls to 'destroySwapchainKHR'. -- -- After @oldSwapchain@ is retired, the application /can/ pass to -- 'queuePresentKHR' any images it had already acquired from -- @oldSwapchain@. E.g., an application may present an image from the old -- swapchain before an image from the new swapchain is ready to be -- presented. As usual, 'queuePresentKHR' /may/ fail if @oldSwapchain@ has -- entered a state that causes -- 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' to be returned. -- -- The application /can/ continue to use a shared presentable image -- obtained from @oldSwapchain@ until a presentable image is acquired from -- the new swapchain, as long as it has not entered a state that causes it -- to return 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR'. -- -- == Valid Usage -- -- - #VUID-VkSwapchainCreateInfoKHR-surface-01270# @surface@ /must/ be a -- surface that is supported by the device as determined using -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-minImageCount-01272# @minImageCount@ -- /must/ be less than or equal to the value returned in the -- @maxImageCount@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface if the returned @maxImageCount@ is not zero -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-02839# If @presentMode@ -- is not -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR' -- nor -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR', -- then @minImageCount@ /must/ be greater than or equal to the value -- returned in the @minImageCount@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-minImageCount-01383# @minImageCount@ -- /must/ be @1@ if @presentMode@ is either -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR' -- or -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-imageFormat-01273# @imageFormat@ and -- @imageColorSpace@ /must/ match the @format@ and @colorSpace@ -- members, respectively, of one of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceFormatKHR' structures -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceFormatsKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-imageExtent-01274# @imageExtent@ -- /must/ be between @minImageExtent@ and @maxImageExtent@, inclusive, -- where @minImageExtent@ and @maxImageExtent@ are members of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-imageExtent-01689# @imageExtent@ -- members @width@ and @height@ /must/ both be non-zero -- -- - #VUID-VkSwapchainCreateInfoKHR-imageArrayLayers-01275# -- @imageArrayLayers@ /must/ be greater than @0@ and less than or equal -- to the @maxImageArrayLayers@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-01427# If @presentMode@ -- is 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_IMMEDIATE_KHR', -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_MAILBOX_KHR', -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_FIFO_KHR' or -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_FIFO_RELAXED_KHR', -- @imageUsage@ /must/ be a subset of the supported usage flags present -- in the @supportedUsageFlags@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageUsage-01384# If @presentMode@ is -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR' -- or -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR', -- @imageUsage@ /must/ be a subset of the supported usage flags present -- in the @sharedPresentSupportedUsageFlags@ member of the -- 'Vulkan.Extensions.VK_KHR_shared_presentable_image.SharedPresentSurfaceCapabilitiesKHR' -- structure returned by -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- for @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01277# If -- @imageSharingMode@ is -- 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT', -- @pQueueFamilyIndices@ /must/ be a valid pointer to an array of -- @queueFamilyIndexCount@ @uint32_t@ values -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01278# If -- @imageSharingMode@ is -- 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT', -- @queueFamilyIndexCount@ /must/ be greater than @1@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01428# If -- @imageSharingMode@ is -- 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT', each -- element of @pQueueFamilyIndices@ /must/ be unique and /must/ be less -- than @pQueueFamilyPropertyCount@ returned by either -- 'Vulkan.Core10.DeviceInitialization.getPhysicalDeviceQueueFamilyProperties' -- or -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceQueueFamilyProperties2' -- for the @physicalDevice@ that was used to create @device@ -- -- - #VUID-VkSwapchainCreateInfoKHR-preTransform-01279# @preTransform@ -- /must/ be one of the bits present in the @supportedTransforms@ -- member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-compositeAlpha-01280# -- @compositeAlpha@ /must/ be one of the bits present in the -- @supportedCompositeAlpha@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-01281# @presentMode@ -- /must/ be one of the -- 'Vulkan.Extensions.VK_KHR_surface.PresentModeKHR' values returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfacePresentModesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-physicalDeviceCount-01429# If the -- logical device was created with -- 'Vulkan.Core11.Promoted_From_VK_KHR_device_group_creation.DeviceGroupDeviceCreateInfo'::@physicalDeviceCount@ -- equal to 1, @flags@ /must/ not contain -- 'SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933# If @oldSwapchain@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @oldSwapchain@ -- /must/ be a non-retired swapchain associated with native window -- referred to by @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageFormat-01778# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#swapchain-wsi-image-create-info implied image creation parameters> -- of the swapchain /must/ be supported as reported by -- 'Vulkan.Core10.DeviceInitialization.getPhysicalDeviceImageFormatProperties' -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-03168# If @flags@ contains -- 'SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR' then the @pNext@ chain -- /must/ include a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure with a @viewFormatCount@ greater than zero and -- @pViewFormats@ /must/ have an element equal to @imageFormat@ -- -- - #VUID-VkSwapchainCreateInfoKHR-pNext-04099# If a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure was included in the @pNext@ chain and -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@viewFormatCount@ -- is not zero then all of the formats in -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@pViewFormats@ -- /must/ be compatible with the @format@ as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatibility compatibility table> -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-04100# If @flags@ does not -- contain 'SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR' and the @pNext@ -- chain include a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure then -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@viewFormatCount@ -- /must/ be @0@ or @1@ -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-03187# If @flags@ contains -- 'SWAPCHAIN_CREATE_PROTECTED_BIT_KHR', then -- 'Vulkan.Extensions.VK_KHR_surface_protected_capabilities.SurfaceProtectedCapabilitiesKHR'::@supportsProtected@ -- /must/ be 'Vulkan.Core10.FundamentalTypes.TRUE' in the -- 'Vulkan.Extensions.VK_KHR_surface_protected_capabilities.SurfaceProtectedCapabilitiesKHR' -- structure returned by -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- for @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-pNext-02679# If the @pNext@ chain -- includes a -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveInfoEXT' -- structure with its @fullScreenExclusive@ member set to -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT', -- and @surface@ was created using -- 'Vulkan.Extensions.VK_KHR_win32_surface.createWin32SurfaceKHR', a -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveWin32InfoEXT' -- structure /must/ be included in the @pNext@ chain -- -- == Valid Usage (Implicit) -- -- - #VUID-VkSwapchainCreateInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-pNext-pNext# Each @pNext@ member of -- any structure (including this one) in the @pNext@ chain /must/ be -- either @NULL@ or a pointer to a valid instance of -- 'DeviceGroupSwapchainCreateInfoKHR', -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo', -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveInfoEXT', -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveWin32InfoEXT', -- 'Vulkan.Extensions.VK_EXT_display_control.SwapchainCounterCreateInfoEXT', -- or -- 'Vulkan.Extensions.VK_AMD_display_native_hdr.SwapchainDisplayNativeHdrCreateInfoAMD' -- -- - #VUID-VkSwapchainCreateInfoKHR-sType-unique# The @sType@ value of -- each struct in the @pNext@ chain /must/ be unique -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-parameter# @flags@ /must/ be a -- valid combination of 'SwapchainCreateFlagBitsKHR' values -- -- - #VUID-VkSwapchainCreateInfoKHR-surface-parameter# @surface@ /must/ -- be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' handle -- -- - #VUID-VkSwapchainCreateInfoKHR-imageFormat-parameter# @imageFormat@ -- /must/ be a valid 'Vulkan.Core10.Enums.Format.Format' value -- -- - #VUID-VkSwapchainCreateInfoKHR-imageColorSpace-parameter# -- @imageColorSpace@ /must/ be a valid -- 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR' value -- -- - #VUID-VkSwapchainCreateInfoKHR-imageUsage-parameter# @imageUsage@ -- /must/ be a valid combination of -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlagBits' values -- -- - #VUID-VkSwapchainCreateInfoKHR-imageUsage-requiredbitmask# -- @imageUsage@ /must/ not be @0@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-parameter# -- @imageSharingMode@ /must/ be a valid -- 'Vulkan.Core10.Enums.SharingMode.SharingMode' value -- -- - #VUID-VkSwapchainCreateInfoKHR-preTransform-parameter# -- @preTransform@ /must/ be a valid -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceTransformFlagBitsKHR' value -- -- - #VUID-VkSwapchainCreateInfoKHR-compositeAlpha-parameter# -- @compositeAlpha@ /must/ be a valid -- 'Vulkan.Extensions.VK_KHR_surface.CompositeAlphaFlagBitsKHR' value -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-parameter# @presentMode@ -- /must/ be a valid 'Vulkan.Extensions.VK_KHR_surface.PresentModeKHR' -- value -- -- - #VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parameter# If -- @oldSwapchain@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @oldSwapchain@ /must/ be a valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parent# If -- @oldSwapchain@ is a valid handle, it /must/ have been created, -- allocated, or retrieved from @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-commonparent# Both of @oldSwapchain@, -- and @surface@ that are valid handles of non-ignored parameters -- /must/ have been created, allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR', -- 'Vulkan.Extensions.VK_KHR_surface.CompositeAlphaFlagBitsKHR', -- 'Vulkan.Core10.FundamentalTypes.Extent2D', -- 'Vulkan.Core10.Enums.Format.Format', -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlags', -- 'Vulkan.Extensions.VK_KHR_surface.PresentModeKHR', -- 'Vulkan.Core10.Enums.SharingMode.SharingMode', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SurfaceKHR', -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceTransformFlagBitsKHR', -- 'SwapchainCreateFlagsKHR', 'Vulkan.Extensions.Handles.SwapchainKHR', -- 'Vulkan.Extensions.VK_KHR_display_swapchain.createSharedSwapchainsKHR', -- 'createSwapchainKHR' data SwapchainCreateInfoKHR (es :: [Type]) = SwapchainCreateInfoKHR { -- | @pNext@ is @NULL@ or a pointer to a structure extending this structure. next :: Chain es , -- | @flags@ is a bitmask of 'SwapchainCreateFlagBitsKHR' indicating -- parameters of the swapchain creation. flags :: SwapchainCreateFlagsKHR , -- | @surface@ is the surface onto which the swapchain will present images. -- If the creation succeeds, the swapchain becomes associated with -- @surface@. surface :: SurfaceKHR , -- | @minImageCount@ is the minimum number of presentable images that the -- application needs. The implementation will either create the swapchain -- with at least that many images, or it will fail to create the swapchain. minImageCount :: Word32 , -- | @imageFormat@ is a 'Vulkan.Core10.Enums.Format.Format' value specifying -- the format the swapchain image(s) will be created with. imageFormat :: Format , -- | @imageColorSpace@ is a 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR' -- value specifying the way the swapchain interprets image data. imageColorSpace :: ColorSpaceKHR , -- | @imageExtent@ is the size (in pixels) of the swapchain image(s). The -- behavior is platform-dependent if the image extent does not match the -- surface’s @currentExtent@ as returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR'. -- -- Note -- -- On some platforms, it is normal that @maxImageExtent@ /may/ become @(0, -- 0)@, for example when the window is minimized. In such a case, it is not -- possible to create a swapchain due to the Valid Usage requirements. imageExtent :: Extent2D , -- | @imageArrayLayers@ is the number of views in a multiview\/stereo -- surface. For non-stereoscopic-3D applications, this value is 1. imageArrayLayers :: Word32 , -- | @imageUsage@ is a bitmask of -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlagBits' describing -- the intended usage of the (acquired) swapchain images. imageUsage :: ImageUsageFlags , -- | @imageSharingMode@ is the sharing mode used for the image(s) of the -- swapchain. imageSharingMode :: SharingMode , -- | @pQueueFamilyIndices@ is a pointer to an array of queue family indices -- having access to the images(s) of the swapchain when @imageSharingMode@ -- is 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT'. queueFamilyIndices :: Vector Word32 , -- | @preTransform@ is a -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceTransformFlagBitsKHR' value -- describing the transform, relative to the presentation engine’s natural -- orientation, applied to the image content prior to presentation. If it -- does not match the @currentTransform@ value returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR', -- the presentation engine will transform the image content as part of the -- presentation operation. preTransform :: SurfaceTransformFlagBitsKHR , -- | @compositeAlpha@ is a -- 'Vulkan.Extensions.VK_KHR_surface.CompositeAlphaFlagBitsKHR' value -- indicating the alpha compositing mode to use when this surface is -- composited together with other surfaces on certain window systems. compositeAlpha :: CompositeAlphaFlagBitsKHR , -- | @presentMode@ is the presentation mode the swapchain will use. A -- swapchain’s present mode determines how incoming present requests will -- be processed and queued internally. presentMode :: PresentModeKHR , -- | @clipped@ specifies whether the Vulkan implementation is allowed to -- discard rendering operations that affect regions of the surface that are -- not visible. -- -- - If set to 'Vulkan.Core10.FundamentalTypes.TRUE', the presentable -- images associated with the swapchain /may/ not own all of their -- pixels. Pixels in the presentable images that correspond to regions -- of the target surface obscured by another window on the desktop, or -- subject to some other clipping mechanism will have undefined content -- when read back. Fragment shaders /may/ not execute for these pixels, -- and thus any side effects they would have had will not occur. -- Setting 'Vulkan.Core10.FundamentalTypes.TRUE' does not guarantee any -- clipping will occur, but allows more efficient presentation methods -- to be used on some platforms. -- -- - If set to 'Vulkan.Core10.FundamentalTypes.FALSE', presentable images -- associated with the swapchain will own all of the pixels they -- contain. -- -- Note -- -- Applications /should/ set this value to -- 'Vulkan.Core10.FundamentalTypes.TRUE' if they do not expect to read -- back the content of presentable images before presenting them or -- after reacquiring them, and if their fragment shaders do not have -- any side effects that require them to run for all pixels in the -- presentable image. clipped :: Bool , -- | @oldSwapchain@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE', or the -- existing non-retired swapchain currently associated with @surface@. -- Providing a valid @oldSwapchain@ /may/ aid in the resource reuse, and -- also allows the application to still present any images that are already -- acquired from it. oldSwapchain :: SwapchainKHR } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (SwapchainCreateInfoKHR (es :: [Type])) #endif deriving instance Show (Chain es) => Show (SwapchainCreateInfoKHR es) instance Extensible SwapchainCreateInfoKHR where extensibleTypeName = "SwapchainCreateInfoKHR" setNext SwapchainCreateInfoKHR{..} next' = SwapchainCreateInfoKHR{next = next', ..} getNext SwapchainCreateInfoKHR{..} = next extends :: forall e b proxy. Typeable e => proxy e -> (Extends SwapchainCreateInfoKHR e => b) -> Maybe b extends _ f | Just Refl <- eqT @e @SurfaceFullScreenExclusiveWin32InfoEXT = Just f | Just Refl <- eqT @e @SurfaceFullScreenExclusiveInfoEXT = Just f | Just Refl <- eqT @e @ImageFormatListCreateInfo = Just f | Just Refl <- eqT @e @SwapchainDisplayNativeHdrCreateInfoAMD = Just f | Just Refl <- eqT @e @DeviceGroupSwapchainCreateInfoKHR = Just f | Just Refl <- eqT @e @SwapchainCounterCreateInfoEXT = Just f | otherwise = Nothing instance (Extendss SwapchainCreateInfoKHR es, PokeChain es) => ToCStruct (SwapchainCreateInfoKHR es) where withCStruct x f = allocaBytes 104 $ \p -> pokeCStruct p x (f p) pokeCStruct p SwapchainCreateInfoKHR{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR) pNext'' <- fmap castPtr . ContT $ withChain (next) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'' lift $ poke ((p `plusPtr` 16 :: Ptr SwapchainCreateFlagsKHR)) (flags) lift $ poke ((p `plusPtr` 24 :: Ptr SurfaceKHR)) (surface) lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) (minImageCount) lift $ poke ((p `plusPtr` 36 :: Ptr Format)) (imageFormat) lift $ poke ((p `plusPtr` 40 :: Ptr ColorSpaceKHR)) (imageColorSpace) lift $ poke ((p `plusPtr` 44 :: Ptr Extent2D)) (imageExtent) lift $ poke ((p `plusPtr` 52 :: Ptr Word32)) (imageArrayLayers) lift $ poke ((p `plusPtr` 56 :: Ptr ImageUsageFlags)) (imageUsage) lift $ poke ((p `plusPtr` 60 :: Ptr SharingMode)) (imageSharingMode) lift $ poke ((p `plusPtr` 64 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (queueFamilyIndices)) :: Word32)) pPQueueFamilyIndices' <- ContT $ allocaBytes @Word32 ((Data.Vector.length (queueFamilyIndices)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPQueueFamilyIndices' `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (queueFamilyIndices) lift $ poke ((p `plusPtr` 72 :: Ptr (Ptr Word32))) (pPQueueFamilyIndices') lift $ poke ((p `plusPtr` 80 :: Ptr SurfaceTransformFlagBitsKHR)) (preTransform) lift $ poke ((p `plusPtr` 84 :: Ptr CompositeAlphaFlagBitsKHR)) (compositeAlpha) lift $ poke ((p `plusPtr` 88 :: Ptr PresentModeKHR)) (presentMode) lift $ poke ((p `plusPtr` 92 :: Ptr Bool32)) (boolToBool32 (clipped)) lift $ poke ((p `plusPtr` 96 :: Ptr SwapchainKHR)) (oldSwapchain) lift $ f cStructSize = 104 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR) pNext' <- fmap castPtr . ContT $ withZeroChain @es lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext' lift $ poke ((p `plusPtr` 24 :: Ptr SurfaceKHR)) (zero) lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) (zero) lift $ poke ((p `plusPtr` 36 :: Ptr Format)) (zero) lift $ poke ((p `plusPtr` 40 :: Ptr ColorSpaceKHR)) (zero) lift $ poke ((p `plusPtr` 44 :: Ptr Extent2D)) (zero) lift $ poke ((p `plusPtr` 52 :: Ptr Word32)) (zero) lift $ poke ((p `plusPtr` 56 :: Ptr ImageUsageFlags)) (zero) lift $ poke ((p `plusPtr` 60 :: Ptr SharingMode)) (zero) lift $ poke ((p `plusPtr` 80 :: Ptr SurfaceTransformFlagBitsKHR)) (zero) lift $ poke ((p `plusPtr` 84 :: Ptr CompositeAlphaFlagBitsKHR)) (zero) lift $ poke ((p `plusPtr` 88 :: Ptr PresentModeKHR)) (zero) lift $ poke ((p `plusPtr` 92 :: Ptr Bool32)) (boolToBool32 (zero)) lift $ f instance (Extendss SwapchainCreateInfoKHR es, PeekChain es) => FromCStruct (SwapchainCreateInfoKHR es) where peekCStruct p = do pNext <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ()))) next <- peekChain (castPtr pNext) flags <- peek @SwapchainCreateFlagsKHR ((p `plusPtr` 16 :: Ptr SwapchainCreateFlagsKHR)) surface <- peek @SurfaceKHR ((p `plusPtr` 24 :: Ptr SurfaceKHR)) minImageCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) imageFormat <- peek @Format ((p `plusPtr` 36 :: Ptr Format)) imageColorSpace <- peek @ColorSpaceKHR ((p `plusPtr` 40 :: Ptr ColorSpaceKHR)) imageExtent <- peekCStruct @Extent2D ((p `plusPtr` 44 :: Ptr Extent2D)) imageArrayLayers <- peek @Word32 ((p `plusPtr` 52 :: Ptr Word32)) imageUsage <- peek @ImageUsageFlags ((p `plusPtr` 56 :: Ptr ImageUsageFlags)) imageSharingMode <- peek @SharingMode ((p `plusPtr` 60 :: Ptr SharingMode)) queueFamilyIndexCount <- peek @Word32 ((p `plusPtr` 64 :: Ptr Word32)) pQueueFamilyIndices <- peek @(Ptr Word32) ((p `plusPtr` 72 :: Ptr (Ptr Word32))) pQueueFamilyIndices' <- generateM (fromIntegral queueFamilyIndexCount) (\i -> peek @Word32 ((pQueueFamilyIndices `advancePtrBytes` (4 * (i)) :: Ptr Word32))) preTransform <- peek @SurfaceTransformFlagBitsKHR ((p `plusPtr` 80 :: Ptr SurfaceTransformFlagBitsKHR)) compositeAlpha <- peek @CompositeAlphaFlagBitsKHR ((p `plusPtr` 84 :: Ptr CompositeAlphaFlagBitsKHR)) presentMode <- peek @PresentModeKHR ((p `plusPtr` 88 :: Ptr PresentModeKHR)) clipped <- peek @Bool32 ((p `plusPtr` 92 :: Ptr Bool32)) oldSwapchain <- peek @SwapchainKHR ((p `plusPtr` 96 :: Ptr SwapchainKHR)) pure $ SwapchainCreateInfoKHR next flags surface minImageCount imageFormat imageColorSpace imageExtent imageArrayLayers imageUsage imageSharingMode pQueueFamilyIndices' preTransform compositeAlpha presentMode (bool32ToBool clipped) oldSwapchain instance es ~ '[] => Zero (SwapchainCreateInfoKHR es) where zero = SwapchainCreateInfoKHR () zero zero zero zero zero zero zero zero zero mempty zero zero zero zero zero -- | VkPresentInfoKHR - Structure describing parameters of a queue -- presentation -- -- = Description -- -- Before an application /can/ present an image, the image’s layout /must/ -- be transitioned to the -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR' layout, -- or for a shared presentable image the -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_SHARED_PRESENT_KHR' -- layout. -- -- Note -- -- When transitioning the image to -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_SHARED_PRESENT_KHR' or -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR', there is -- no need to delay subsequent processing, or perform any visibility -- operations (as 'queuePresentKHR' performs automatic visibility -- operations). To achieve this, the @dstAccessMask@ member of the -- 'Vulkan.Core10.OtherTypes.ImageMemoryBarrier' /should/ be set to @0@, -- and the @dstStageMask@ parameter /should/ be set to -- 'Vulkan.Core10.Enums.PipelineStageFlagBits.PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT'. -- -- == Valid Usage -- -- - #VUID-VkPresentInfoKHR-pImageIndices-01430# Each element of -- @pImageIndices@ /must/ be the index of a presentable image acquired -- from the swapchain specified by the corresponding element of the -- @pSwapchains@ array, and the presented image subresource /must/ be -- in the -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR' or -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_SHARED_PRESENT_KHR' -- layout at the time the operation is executed on a -- 'Vulkan.Core10.Handles.Device' -- -- - #VUID-VkPresentInfoKHR-pNext-06235# If a -- 'Vulkan.Extensions.VK_KHR_present_id.PresentIdKHR' structure is -- included in the @pNext@ chain, and the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-presentId presentId> -- feature is not enabled, each @presentIds@ entry in that structure -- /must/ be NULL -- -- == Valid Usage (Implicit) -- -- - #VUID-VkPresentInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PRESENT_INFO_KHR' -- -- - #VUID-VkPresentInfoKHR-pNext-pNext# Each @pNext@ member of any -- structure (including this one) in the @pNext@ chain /must/ be either -- @NULL@ or a pointer to a valid instance of -- 'DeviceGroupPresentInfoKHR', -- 'Vulkan.Extensions.VK_KHR_display_swapchain.DisplayPresentInfoKHR', -- 'Vulkan.Extensions.VK_GGP_frame_token.PresentFrameTokenGGP', -- 'Vulkan.Extensions.VK_KHR_present_id.PresentIdKHR', -- 'Vulkan.Extensions.VK_KHR_incremental_present.PresentRegionsKHR', or -- 'Vulkan.Extensions.VK_GOOGLE_display_timing.PresentTimesInfoGOOGLE' -- -- - #VUID-VkPresentInfoKHR-sType-unique# The @sType@ value of each -- struct in the @pNext@ chain /must/ be unique -- -- - #VUID-VkPresentInfoKHR-pWaitSemaphores-parameter# If -- @waitSemaphoreCount@ is not @0@, @pWaitSemaphores@ /must/ be a valid -- pointer to an array of @waitSemaphoreCount@ valid -- 'Vulkan.Core10.Handles.Semaphore' handles -- -- - #VUID-VkPresentInfoKHR-pSwapchains-parameter# @pSwapchains@ /must/ -- be a valid pointer to an array of @swapchainCount@ valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handles -- -- - #VUID-VkPresentInfoKHR-pImageIndices-parameter# @pImageIndices@ -- /must/ be a valid pointer to an array of @swapchainCount@ @uint32_t@ -- values -- -- - #VUID-VkPresentInfoKHR-pResults-parameter# If @pResults@ is not -- @NULL@, @pResults@ /must/ be a valid pointer to an array of -- @swapchainCount@ 'Vulkan.Core10.Enums.Result.Result' values -- -- - #VUID-VkPresentInfoKHR-swapchainCount-arraylength# @swapchainCount@ -- /must/ be greater than @0@ -- -- - #VUID-VkPresentInfoKHR-commonparent# Both of the elements of -- @pSwapchains@, and the elements of @pWaitSemaphores@ that are valid -- handles of non-ignored parameters /must/ have been created, -- allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.Enums.Result.Result', 'Vulkan.Core10.Handles.Semaphore', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR', 'queuePresentKHR' data PresentInfoKHR (es :: [Type]) = PresentInfoKHR { -- | @pNext@ is @NULL@ or a pointer to a structure extending this structure. next :: Chain es , -- | @pWaitSemaphores@ is @NULL@ or a pointer to an array of -- 'Vulkan.Core10.Handles.Semaphore' objects with @waitSemaphoreCount@ -- entries, and specifies the semaphores to wait for before issuing the -- present request. waitSemaphores :: Vector Semaphore , -- | @pSwapchains@ is a pointer to an array of -- 'Vulkan.Extensions.Handles.SwapchainKHR' objects with @swapchainCount@ -- entries. A given swapchain /must/ not appear in this list more than -- once. swapchains :: Vector SwapchainKHR , -- | @pImageIndices@ is a pointer to an array of indices into the array of -- each swapchain’s presentable images, with @swapchainCount@ entries. Each -- entry in this array identifies the image to present on the corresponding -- entry in the @pSwapchains@ array. imageIndices :: Vector Word32 , -- | @pResults@ is a pointer to an array of -- 'Vulkan.Core10.Enums.Result.Result' typed elements with @swapchainCount@ -- entries. Applications that do not need per-swapchain results /can/ use -- @NULL@ for @pResults@. If non-@NULL@, each entry in @pResults@ will be -- set to the 'Vulkan.Core10.Enums.Result.Result' for presenting the -- swapchain corresponding to the same index in @pSwapchains@. results :: Ptr Result } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (PresentInfoKHR (es :: [Type])) #endif deriving instance Show (Chain es) => Show (PresentInfoKHR es) instance Extensible PresentInfoKHR where extensibleTypeName = "PresentInfoKHR" setNext PresentInfoKHR{..} next' = PresentInfoKHR{next = next', ..} getNext PresentInfoKHR{..} = next extends :: forall e b proxy. Typeable e => proxy e -> (Extends PresentInfoKHR e => b) -> Maybe b extends _ f | Just Refl <- eqT @e @PresentFrameTokenGGP = Just f | Just Refl <- eqT @e @PresentTimesInfoGOOGLE = Just f | Just Refl <- eqT @e @PresentIdKHR = Just f | Just Refl <- eqT @e @DeviceGroupPresentInfoKHR = Just f | Just Refl <- eqT @e @PresentRegionsKHR = Just f | Just Refl <- eqT @e @DisplayPresentInfoKHR = Just f | otherwise = Nothing instance (Extendss PresentInfoKHR es, PokeChain es) => ToCStruct (PresentInfoKHR es) where withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p) pokeCStruct p PresentInfoKHR{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PRESENT_INFO_KHR) pNext'' <- fmap castPtr . ContT $ withChain (next) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'' lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (waitSemaphores)) :: Word32)) pPWaitSemaphores' <- ContT $ allocaBytes @Semaphore ((Data.Vector.length (waitSemaphores)) * 8) lift $ Data.Vector.imapM_ (\i e -> poke (pPWaitSemaphores' `plusPtr` (8 * (i)) :: Ptr Semaphore) (e)) (waitSemaphores) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr Semaphore))) (pPWaitSemaphores') let pSwapchainsLength = Data.Vector.length $ (swapchains) lift $ unless ((Data.Vector.length $ (imageIndices)) == pSwapchainsLength) $ throwIO $ IOError Nothing InvalidArgument "" "pImageIndices and pSwapchains must have the same length" Nothing Nothing lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) ((fromIntegral pSwapchainsLength :: Word32)) pPSwapchains' <- ContT $ allocaBytes @SwapchainKHR ((Data.Vector.length (swapchains)) * 8) lift $ Data.Vector.imapM_ (\i e -> poke (pPSwapchains' `plusPtr` (8 * (i)) :: Ptr SwapchainKHR) (e)) (swapchains) lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr SwapchainKHR))) (pPSwapchains') pPImageIndices' <- ContT $ allocaBytes @Word32 ((Data.Vector.length (imageIndices)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPImageIndices' `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (imageIndices) lift $ poke ((p `plusPtr` 48 :: Ptr (Ptr Word32))) (pPImageIndices') lift $ poke ((p `plusPtr` 56 :: Ptr (Ptr Result))) (results) lift $ f cStructSize = 64 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PRESENT_INFO_KHR) pNext' <- fmap castPtr . ContT $ withZeroChain @es lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext' lift $ f instance (Extendss PresentInfoKHR es, PeekChain es) => FromCStruct (PresentInfoKHR es) where peekCStruct p = do pNext <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ()))) next <- peekChain (castPtr pNext) waitSemaphoreCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pWaitSemaphores <- peek @(Ptr Semaphore) ((p `plusPtr` 24 :: Ptr (Ptr Semaphore))) pWaitSemaphores' <- generateM (fromIntegral waitSemaphoreCount) (\i -> peek @Semaphore ((pWaitSemaphores `advancePtrBytes` (8 * (i)) :: Ptr Semaphore))) swapchainCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pSwapchains <- peek @(Ptr SwapchainKHR) ((p `plusPtr` 40 :: Ptr (Ptr SwapchainKHR))) pSwapchains' <- generateM (fromIntegral swapchainCount) (\i -> peek @SwapchainKHR ((pSwapchains `advancePtrBytes` (8 * (i)) :: Ptr SwapchainKHR))) pImageIndices <- peek @(Ptr Word32) ((p `plusPtr` 48 :: Ptr (Ptr Word32))) pImageIndices' <- generateM (fromIntegral swapchainCount) (\i -> peek @Word32 ((pImageIndices `advancePtrBytes` (4 * (i)) :: Ptr Word32))) pResults <- peek @(Ptr Result) ((p `plusPtr` 56 :: Ptr (Ptr Result))) pure $ PresentInfoKHR next pWaitSemaphores' pSwapchains' pImageIndices' pResults instance es ~ '[] => Zero (PresentInfoKHR es) where zero = PresentInfoKHR () mempty mempty mempty zero -- | VkDeviceGroupPresentCapabilitiesKHR - Present capabilities from other -- physical devices -- -- = Description -- -- @modes@ always has 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR' set. -- -- The present mode flags are also used when presenting an image, in -- 'DeviceGroupPresentInfoKHR'::@mode@. -- -- If a device group only includes a single physical device, then @modes@ -- /must/ equal 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR'. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentModeFlagsKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'getDeviceGroupPresentCapabilitiesKHR' data DeviceGroupPresentCapabilitiesKHR = DeviceGroupPresentCapabilitiesKHR { -- | @presentMask@ is an array of -- 'Vulkan.Core10.APIConstants.MAX_DEVICE_GROUP_SIZE' @uint32_t@ masks, -- where the mask at element i is non-zero if physical device i has a -- presentation engine, and where bit j is set in element i if physical -- device i /can/ present swapchain images from physical device j. If -- element i is non-zero, then bit i /must/ be set. presentMask :: Vector Word32 , -- | @modes@ is a bitmask of 'DeviceGroupPresentModeFlagBitsKHR' indicating -- which device group presentation modes are supported. modes :: DeviceGroupPresentModeFlagsKHR } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DeviceGroupPresentCapabilitiesKHR) #endif deriving instance Show DeviceGroupPresentCapabilitiesKHR instance ToCStruct DeviceGroupPresentCapabilitiesKHR where withCStruct x f = allocaBytes 152 $ \p -> pokeCStruct p x (f p) pokeCStruct p DeviceGroupPresentCapabilitiesKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) unless ((Data.Vector.length $ (presentMask)) <= MAX_DEVICE_GROUP_SIZE) $ throwIO $ IOError Nothing InvalidArgument "" "presentMask is too long, a maximum of MAX_DEVICE_GROUP_SIZE elements are allowed" Nothing Nothing Data.Vector.imapM_ (\i e -> poke ((lowerArrayPtr ((p `plusPtr` 16 :: Ptr (FixedArray MAX_DEVICE_GROUP_SIZE Word32)))) `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (presentMask) poke ((p `plusPtr` 144 :: Ptr DeviceGroupPresentModeFlagsKHR)) (modes) f cStructSize = 152 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 144 :: Ptr DeviceGroupPresentModeFlagsKHR)) (zero) f instance FromCStruct DeviceGroupPresentCapabilitiesKHR where peekCStruct p = do presentMask <- generateM (MAX_DEVICE_GROUP_SIZE) (\i -> peek @Word32 (((lowerArrayPtr @Word32 ((p `plusPtr` 16 :: Ptr (FixedArray MAX_DEVICE_GROUP_SIZE Word32)))) `advancePtrBytes` (4 * (i)) :: Ptr Word32))) modes <- peek @DeviceGroupPresentModeFlagsKHR ((p `plusPtr` 144 :: Ptr DeviceGroupPresentModeFlagsKHR)) pure $ DeviceGroupPresentCapabilitiesKHR presentMask modes instance Storable DeviceGroupPresentCapabilitiesKHR where sizeOf ~_ = 152 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero DeviceGroupPresentCapabilitiesKHR where zero = DeviceGroupPresentCapabilitiesKHR mempty zero -- | VkImageSwapchainCreateInfoKHR - Specify that an image will be bound to -- swapchain memory -- -- == Valid Usage -- -- - #VUID-VkImageSwapchainCreateInfoKHR-swapchain-00995# If @swapchain@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', the fields of -- 'Vulkan.Core10.Image.ImageCreateInfo' /must/ match the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#swapchain-wsi-image-create-info implied image creation parameters> -- of the swapchain -- -- == Valid Usage (Implicit) -- -- - #VUID-VkImageSwapchainCreateInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR' -- -- - #VUID-VkImageSwapchainCreateInfoKHR-swapchain-parameter# If -- @swapchain@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @swapchain@ /must/ be a valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR' data ImageSwapchainCreateInfoKHR = ImageSwapchainCreateInfoKHR { -- | @swapchain@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a handle of a -- swapchain that the image will be bound to. swapchain :: SwapchainKHR } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImageSwapchainCreateInfoKHR) #endif deriving instance Show ImageSwapchainCreateInfoKHR instance ToCStruct ImageSwapchainCreateInfoKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImageSwapchainCreateInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (swapchain) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct ImageSwapchainCreateInfoKHR where peekCStruct p = do swapchain <- peek @SwapchainKHR ((p `plusPtr` 16 :: Ptr SwapchainKHR)) pure $ ImageSwapchainCreateInfoKHR swapchain instance Storable ImageSwapchainCreateInfoKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero ImageSwapchainCreateInfoKHR where zero = ImageSwapchainCreateInfoKHR zero -- | VkBindImageMemorySwapchainInfoKHR - Structure specifying swapchain image -- memory to bind to -- -- = Description -- -- If @swapchain@ is not @NULL@, the @swapchain@ and @imageIndex@ are used -- to determine the memory that the image is bound to, instead of @memory@ -- and @memoryOffset@. -- -- Memory /can/ be bound to a swapchain and use the @pDeviceIndices@ or -- @pSplitInstanceBindRegions@ members of -- 'Vulkan.Core11.Promoted_From_VK_KHR_device_groupAndVK_KHR_bind_memory2.BindImageMemoryDeviceGroupInfo'. -- -- == Valid Usage -- -- - #VUID-VkBindImageMemorySwapchainInfoKHR-imageIndex-01644# -- @imageIndex@ /must/ be less than the number of images in @swapchain@ -- -- == Valid Usage (Implicit) -- -- - #VUID-VkBindImageMemorySwapchainInfoKHR-sType-sType# @sType@ /must/ -- be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR' -- -- - #VUID-VkBindImageMemorySwapchainInfoKHR-swapchain-parameter# -- @swapchain@ /must/ be a valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR' data BindImageMemorySwapchainInfoKHR = BindImageMemorySwapchainInfoKHR { -- | @swapchain@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a swapchain -- handle. swapchain :: SwapchainKHR , -- | @imageIndex@ is an image index within @swapchain@. imageIndex :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (BindImageMemorySwapchainInfoKHR) #endif deriving instance Show BindImageMemorySwapchainInfoKHR instance ToCStruct BindImageMemorySwapchainInfoKHR where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p BindImageMemorySwapchainInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (swapchain) poke ((p `plusPtr` 24 :: Ptr Word32)) (imageIndex) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) f instance FromCStruct BindImageMemorySwapchainInfoKHR where peekCStruct p = do swapchain <- peek @SwapchainKHR ((p `plusPtr` 16 :: Ptr SwapchainKHR)) imageIndex <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) pure $ BindImageMemorySwapchainInfoKHR swapchain imageIndex instance Storable BindImageMemorySwapchainInfoKHR where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BindImageMemorySwapchainInfoKHR where zero = BindImageMemorySwapchainInfoKHR zero zero -- | VkAcquireNextImageInfoKHR - Structure specifying parameters of the -- acquire -- -- = Description -- -- If 'acquireNextImageKHR' is used, the device mask is considered to -- include all physical devices in the logical device. -- -- Note -- -- 'acquireNextImage2KHR' signals at most one semaphore, even if the -- application requests waiting for multiple physical devices to be ready -- via the @deviceMask@. However, only a single physical device /can/ wait -- on that semaphore, since the semaphore becomes unsignaled when the wait -- succeeds. For other physical devices to wait for the image to be ready, -- it is necessary for the application to submit semaphore signal -- operation(s) to that first physical device to signal additional -- semaphore(s) after the wait succeeds, which the other physical device(s) -- /can/ wait upon. -- -- == Valid Usage -- -- - #VUID-VkAcquireNextImageInfoKHR-swapchain-01675# @swapchain@ /must/ -- not be in the retired state -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-01288# If @semaphore@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-01781# If @semaphore@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ not have any -- uncompleted signal or wait operations pending -- -- - #VUID-VkAcquireNextImageInfoKHR-fence-01289# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled and -- /must/ not be associated with any other queue command that has not -- yet completed execution on that queue -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-01782# @semaphore@ and -- @fence@ /must/ not both be equal to -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' -- -- - #VUID-VkAcquireNextImageInfoKHR-deviceMask-01290# @deviceMask@ -- /must/ be a valid device mask -- -- - #VUID-VkAcquireNextImageInfoKHR-deviceMask-01291# @deviceMask@ -- /must/ not be zero -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-03266# @semaphore@ /must/ -- have a 'Vulkan.Core12.Enums.SemaphoreType.SemaphoreType' of -- 'Vulkan.Core12.Enums.SemaphoreType.SEMAPHORE_TYPE_BINARY' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkAcquireNextImageInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR' -- -- - #VUID-VkAcquireNextImageInfoKHR-pNext-pNext# @pNext@ /must/ be -- @NULL@ -- -- - #VUID-VkAcquireNextImageInfoKHR-swapchain-parameter# @swapchain@ -- /must/ be a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-parameter# If @semaphore@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @semaphore@ /must/ -- be a valid 'Vulkan.Core10.Handles.Semaphore' handle -- -- - #VUID-VkAcquireNextImageInfoKHR-fence-parameter# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @fence@ /must/ be a valid -- 'Vulkan.Core10.Handles.Fence' handle -- -- - #VUID-VkAcquireNextImageInfoKHR-commonparent# Each of @fence@, -- @semaphore@, and @swapchain@ that are valid handles of non-ignored -- parameters /must/ have been created, allocated, or retrieved from -- the same 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- - Host access to @semaphore@ /must/ be externally synchronized -- -- - Host access to @fence@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.Fence', 'Vulkan.Core10.Handles.Semaphore', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR', 'acquireNextImage2KHR' data AcquireNextImageInfoKHR = AcquireNextImageInfoKHR { -- | @swapchain@ is a non-retired swapchain from which an image is acquired. swapchain :: SwapchainKHR , -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. timeout :: Word64 , -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. semaphore :: Semaphore , -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. fence :: Fence , -- | @deviceMask@ is a mask of physical devices for which the swapchain image -- will be ready to use when the semaphore or fence is signaled. deviceMask :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (AcquireNextImageInfoKHR) #endif deriving instance Show AcquireNextImageInfoKHR instance ToCStruct AcquireNextImageInfoKHR where withCStruct x f = allocaBytes 56 $ \p -> pokeCStruct p x (f p) pokeCStruct p AcquireNextImageInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (swapchain) poke ((p `plusPtr` 24 :: Ptr Word64)) (timeout) poke ((p `plusPtr` 32 :: Ptr Semaphore)) (semaphore) poke ((p `plusPtr` 40 :: Ptr Fence)) (fence) poke ((p `plusPtr` 48 :: Ptr Word32)) (deviceMask) f cStructSize = 56 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (zero) poke ((p `plusPtr` 24 :: Ptr Word64)) (zero) poke ((p `plusPtr` 48 :: Ptr Word32)) (zero) f instance FromCStruct AcquireNextImageInfoKHR where peekCStruct p = do swapchain <- peek @SwapchainKHR ((p `plusPtr` 16 :: Ptr SwapchainKHR)) timeout <- peek @Word64 ((p `plusPtr` 24 :: Ptr Word64)) semaphore <- peek @Semaphore ((p `plusPtr` 32 :: Ptr Semaphore)) fence <- peek @Fence ((p `plusPtr` 40 :: Ptr Fence)) deviceMask <- peek @Word32 ((p `plusPtr` 48 :: Ptr Word32)) pure $ AcquireNextImageInfoKHR swapchain timeout semaphore fence deviceMask instance Storable AcquireNextImageInfoKHR where sizeOf ~_ = 56 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero AcquireNextImageInfoKHR where zero = AcquireNextImageInfoKHR zero zero zero zero zero -- | VkDeviceGroupPresentInfoKHR - Mode and mask controlling which physical -- devices\' images are presented -- -- = Description -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR', then each -- element of @pDeviceMasks@ selects which instance of the swapchain image -- is presented. Each element of @pDeviceMasks@ /must/ have exactly one bit -- set, and the corresponding physical device /must/ have a presentation -- engine as reported by 'DeviceGroupPresentCapabilitiesKHR'. -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR', then each -- element of @pDeviceMasks@ selects which instance of the swapchain image -- is presented. Each element of @pDeviceMasks@ /must/ have exactly one bit -- set, and some physical device in the logical device /must/ include that -- bit in its 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@. -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR', then each element -- of @pDeviceMasks@ selects which instances of the swapchain image are -- component-wise summed and the sum of those images is presented. If the -- sum in any component is outside the representable range, the value of -- that component is undefined. Each element of @pDeviceMasks@ /must/ have -- a value for which all set bits are set in one of the elements of -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@. -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR', -- then each element of @pDeviceMasks@ selects which instance(s) of the -- swapchain images are presented. For each bit set in each element of -- @pDeviceMasks@, the corresponding physical device /must/ have a -- presentation engine as reported by 'DeviceGroupPresentCapabilitiesKHR'. -- -- If 'DeviceGroupPresentInfoKHR' is not provided or @swapchainCount@ is -- zero then the masks are considered to be @1@. If -- 'DeviceGroupPresentInfoKHR' is not provided, @mode@ is considered to be -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR'. -- -- == Valid Usage -- -- - #VUID-VkDeviceGroupPresentInfoKHR-swapchainCount-01297# -- @swapchainCount@ /must/ equal @0@ or -- 'PresentInfoKHR'::@swapchainCount@ -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01298# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR', then each element of -- @pDeviceMasks@ /must/ have exactly one bit set, and the -- corresponding element of -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ /must/ be -- non-zero -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01299# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR', then each element of -- @pDeviceMasks@ /must/ have exactly one bit set, and some physical -- device in the logical device /must/ include that bit in its -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01300# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR', then each element of -- @pDeviceMasks@ /must/ have a value for which all set bits are set in -- one of the elements of -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01301# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR', then for -- each bit set in each element of @pDeviceMasks@, the corresponding -- element of 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ /must/ -- be non-zero -- -- - #VUID-VkDeviceGroupPresentInfoKHR-pDeviceMasks-01302# The value of -- each element of @pDeviceMasks@ /must/ be equal to the device mask -- passed in 'AcquireNextImageInfoKHR'::@deviceMask@ when the image -- index was last acquired -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01303# @mode@ /must/ have -- exactly one bit set, and that bit /must/ have been included in -- 'DeviceGroupSwapchainCreateInfoKHR'::@modes@ -- -- == Valid Usage (Implicit) -- -- - #VUID-VkDeviceGroupPresentInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR' -- -- - #VUID-VkDeviceGroupPresentInfoKHR-pDeviceMasks-parameter# If -- @swapchainCount@ is not @0@, @pDeviceMasks@ /must/ be a valid -- pointer to an array of @swapchainCount@ @uint32_t@ values -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-parameter# @mode@ /must/ be a -- valid 'DeviceGroupPresentModeFlagBitsKHR' value -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentModeFlagBitsKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data DeviceGroupPresentInfoKHR = DeviceGroupPresentInfoKHR { -- | @pDeviceMasks@ is a pointer to an array of device masks, one for each -- element of 'PresentInfoKHR'::pSwapchains. deviceMasks :: Vector Word32 , -- | @mode@ is a 'DeviceGroupPresentModeFlagBitsKHR' value specifying the -- device group present mode that will be used for this present. mode :: DeviceGroupPresentModeFlagBitsKHR } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DeviceGroupPresentInfoKHR) #endif deriving instance Show DeviceGroupPresentInfoKHR instance ToCStruct DeviceGroupPresentInfoKHR where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p DeviceGroupPresentInfoKHR{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (deviceMasks)) :: Word32)) pPDeviceMasks' <- ContT $ allocaBytes @Word32 ((Data.Vector.length (deviceMasks)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPDeviceMasks' `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (deviceMasks) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr Word32))) (pPDeviceMasks') lift $ poke ((p `plusPtr` 32 :: Ptr DeviceGroupPresentModeFlagBitsKHR)) (mode) lift $ f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 32 :: Ptr DeviceGroupPresentModeFlagBitsKHR)) (zero) f instance FromCStruct DeviceGroupPresentInfoKHR where peekCStruct p = do swapchainCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pDeviceMasks <- peek @(Ptr Word32) ((p `plusPtr` 24 :: Ptr (Ptr Word32))) pDeviceMasks' <- generateM (fromIntegral swapchainCount) (\i -> peek @Word32 ((pDeviceMasks `advancePtrBytes` (4 * (i)) :: Ptr Word32))) mode <- peek @DeviceGroupPresentModeFlagBitsKHR ((p `plusPtr` 32 :: Ptr DeviceGroupPresentModeFlagBitsKHR)) pure $ DeviceGroupPresentInfoKHR pDeviceMasks' mode instance Zero DeviceGroupPresentInfoKHR where zero = DeviceGroupPresentInfoKHR mempty zero -- | VkDeviceGroupSwapchainCreateInfoKHR - Structure specifying parameters of -- a newly created swapchain object -- -- = Description -- -- If this structure is not present, @modes@ is considered to be -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR'. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentModeFlagsKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data DeviceGroupSwapchainCreateInfoKHR = DeviceGroupSwapchainCreateInfoKHR { -- | @modes@ is a bitfield of modes that the swapchain /can/ be used with. -- -- #VUID-VkDeviceGroupSwapchainCreateInfoKHR-modes-parameter# @modes@ -- /must/ be a valid combination of 'DeviceGroupPresentModeFlagBitsKHR' -- values -- -- #VUID-VkDeviceGroupSwapchainCreateInfoKHR-modes-requiredbitmask# @modes@ -- /must/ not be @0@ modes :: DeviceGroupPresentModeFlagsKHR } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (DeviceGroupSwapchainCreateInfoKHR) #endif deriving instance Show DeviceGroupSwapchainCreateInfoKHR instance ToCStruct DeviceGroupSwapchainCreateInfoKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p DeviceGroupSwapchainCreateInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr DeviceGroupPresentModeFlagsKHR)) (modes) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr DeviceGroupPresentModeFlagsKHR)) (zero) f instance FromCStruct DeviceGroupSwapchainCreateInfoKHR where peekCStruct p = do modes <- peek @DeviceGroupPresentModeFlagsKHR ((p `plusPtr` 16 :: Ptr DeviceGroupPresentModeFlagsKHR)) pure $ DeviceGroupSwapchainCreateInfoKHR modes instance Storable DeviceGroupSwapchainCreateInfoKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero DeviceGroupSwapchainCreateInfoKHR where zero = DeviceGroupSwapchainCreateInfoKHR zero type DeviceGroupPresentModeFlagsKHR = DeviceGroupPresentModeFlagBitsKHR -- | VkDeviceGroupPresentModeFlagBitsKHR - Bitmask specifying supported -- device group present modes -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentInfoKHR', 'DeviceGroupPresentModeFlagsKHR' newtype DeviceGroupPresentModeFlagBitsKHR = DeviceGroupPresentModeFlagBitsKHR Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR' specifies that any physical -- device with a presentation engine /can/ present its own swapchain -- images. pattern DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000001 -- | 'DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR' specifies that any physical -- device with a presentation engine /can/ present swapchain images from -- any physical device in its @presentMask@. pattern DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000002 -- | 'DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR' specifies that any physical -- device with a presentation engine /can/ present the sum of swapchain -- images from any physical devices in its @presentMask@. pattern DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000004 -- | 'DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR' specifies that -- multiple physical devices with a presentation engine /can/ each present -- their own swapchain images. pattern DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000008 conNameDeviceGroupPresentModeFlagBitsKHR :: String conNameDeviceGroupPresentModeFlagBitsKHR = "DeviceGroupPresentModeFlagBitsKHR" enumPrefixDeviceGroupPresentModeFlagBitsKHR :: String enumPrefixDeviceGroupPresentModeFlagBitsKHR = "DEVICE_GROUP_PRESENT_MODE_" showTableDeviceGroupPresentModeFlagBitsKHR :: [(DeviceGroupPresentModeFlagBitsKHR, String)] showTableDeviceGroupPresentModeFlagBitsKHR = [ (DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR , "LOCAL_BIT_KHR") , (DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR , "REMOTE_BIT_KHR") , (DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR , "SUM_BIT_KHR") , (DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR, "LOCAL_MULTI_DEVICE_BIT_KHR") ] instance Show DeviceGroupPresentModeFlagBitsKHR where showsPrec = enumShowsPrec enumPrefixDeviceGroupPresentModeFlagBitsKHR showTableDeviceGroupPresentModeFlagBitsKHR conNameDeviceGroupPresentModeFlagBitsKHR (\(DeviceGroupPresentModeFlagBitsKHR x) -> x) (\x -> showString "0x" . showHex x) instance Read DeviceGroupPresentModeFlagBitsKHR where readPrec = enumReadPrec enumPrefixDeviceGroupPresentModeFlagBitsKHR showTableDeviceGroupPresentModeFlagBitsKHR conNameDeviceGroupPresentModeFlagBitsKHR DeviceGroupPresentModeFlagBitsKHR type SwapchainCreateFlagsKHR = SwapchainCreateFlagBitsKHR -- | VkSwapchainCreateFlagBitsKHR - Bitmask controlling swapchain creation -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'SwapchainCreateFlagsKHR' newtype SwapchainCreateFlagBitsKHR = SwapchainCreateFlagBitsKHR Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR' specifies that the images of -- the swapchain /can/ be used to create a -- 'Vulkan.Core10.Handles.ImageView' with a different format than what the -- swapchain was created with. The list of allowed image view formats is -- specified by adding a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure to the @pNext@ chain of 'SwapchainCreateInfoKHR'. In addition, -- this flag also specifies that the swapchain /can/ be created with usage -- flags that are not supported for the format the swapchain is created -- with but are supported for at least one of the allowed image view -- formats. pattern SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR = SwapchainCreateFlagBitsKHR 0x00000004 -- | 'SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR' specifies that -- images created from the swapchain (i.e. with the @swapchain@ member of -- 'ImageSwapchainCreateInfoKHR' set to this swapchain’s handle) /must/ use -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT'. pattern SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = SwapchainCreateFlagBitsKHR 0x00000001 -- | 'SWAPCHAIN_CREATE_PROTECTED_BIT_KHR' specifies that images created from -- the swapchain are protected images. pattern SWAPCHAIN_CREATE_PROTECTED_BIT_KHR = SwapchainCreateFlagBitsKHR 0x00000002 conNameSwapchainCreateFlagBitsKHR :: String conNameSwapchainCreateFlagBitsKHR = "SwapchainCreateFlagBitsKHR" enumPrefixSwapchainCreateFlagBitsKHR :: String enumPrefixSwapchainCreateFlagBitsKHR = "SWAPCHAIN_CREATE_" showTableSwapchainCreateFlagBitsKHR :: [(SwapchainCreateFlagBitsKHR, String)] showTableSwapchainCreateFlagBitsKHR = [ (SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR , "MUTABLE_FORMAT_BIT_KHR") , (SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR, "SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR") , (SWAPCHAIN_CREATE_PROTECTED_BIT_KHR , "PROTECTED_BIT_KHR") ] instance Show SwapchainCreateFlagBitsKHR where showsPrec = enumShowsPrec enumPrefixSwapchainCreateFlagBitsKHR showTableSwapchainCreateFlagBitsKHR conNameSwapchainCreateFlagBitsKHR (\(SwapchainCreateFlagBitsKHR x) -> x) (\x -> showString "0x" . showHex x) instance Read SwapchainCreateFlagBitsKHR where readPrec = enumReadPrec enumPrefixSwapchainCreateFlagBitsKHR showTableSwapchainCreateFlagBitsKHR conNameSwapchainCreateFlagBitsKHR SwapchainCreateFlagBitsKHR type KHR_SWAPCHAIN_SPEC_VERSION = 70 -- No documentation found for TopLevel "VK_KHR_SWAPCHAIN_SPEC_VERSION" pattern KHR_SWAPCHAIN_SPEC_VERSION :: forall a . Integral a => a pattern KHR_SWAPCHAIN_SPEC_VERSION = 70 type KHR_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_swapchain" -- No documentation found for TopLevel "VK_KHR_SWAPCHAIN_EXTENSION_NAME" pattern KHR_SWAPCHAIN_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_swapchain"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_KHR_swapchain.hs
bsd-3-clause
179,999
2
22
33,062
17,875
10,834
7,041
-1
-1
module Text.Highlighter.Lexers.Boo (lexer) where import Text.Regex.PCRE.Light import Text.Highlighter.Types lexer :: Lexer lexer = Lexer { lName = "Boo" , lAliases = ["boo"] , lExtensions = [".boo"] , lMimetypes = ["text/x-boo"] , lStart = root' , lFlags = [multiline] } comment' :: TokenMatcher comment' = [ tokNext "/[*]" (Arbitrary "Comment" :. Arbitrary "Multiline") Push , tokNext "[*]/" (Arbitrary "Comment" :. Arbitrary "Multiline") Pop , tok "[^/*]" (Arbitrary "Comment" :. Arbitrary "Multiline") , tok "[*/]" (Arbitrary "Comment" :. Arbitrary "Multiline") ] classname' :: TokenMatcher classname' = [ tokNext "[a-zA-Z_][a-zA-Z0-9_]*" (Arbitrary "Name" :. Arbitrary "Class") Pop ] namespace' :: TokenMatcher namespace' = [ tokNext "[a-zA-Z_][a-zA-Z0-9_.]*" (Arbitrary "Name" :. Arbitrary "Namespace") Pop ] root' :: TokenMatcher root' = [ tok "\\s+" (Arbitrary "Text") , tok "(#|//).*$" (Arbitrary "Comment" :. Arbitrary "Single") , tokNext "/[*]" (Arbitrary "Comment" :. Arbitrary "Multiline") (GoTo comment') , tok "[]{}:(),.;[]" (Arbitrary "Punctuation") , tok "\\\\\\n" (Arbitrary "Text") , tok "\\\\" (Arbitrary "Text") , tok "(in|is|and|or|not)\\b" (Arbitrary "Operator" :. Arbitrary "Word") , tok "/(\\\\\\\\|\\\\/|[^/\\s])/" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Regex") , tok "@/(\\\\\\\\|\\\\/|[^/])*/" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Regex") , tok "=\126|!=|==|<<|>>|[-+/*%=<>&^|]" (Arbitrary "Operator") , tok "(as|abstract|callable|constructor|destructor|do|import|enum|event|final|get|interface|internal|of|override|partial|private|protected|public|return|set|static|struct|transient|virtual|yield|super|and|break|cast|continue|elif|else|ensure|except|for|given|goto|if|in|is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|while|from|as)\\b" (Arbitrary "Keyword") , tok "def(?=\\s+\\(.*?\\))" (Arbitrary "Keyword") , tokNext "(def)(\\s+)" (ByGroups [(Arbitrary "Keyword"), (Arbitrary "Text")]) (GoTo funcname') , tokNext "(class)(\\s+)" (ByGroups [(Arbitrary "Keyword"), (Arbitrary "Text")]) (GoTo classname') , tokNext "(namespace)(\\s+)" (ByGroups [(Arbitrary "Keyword"), (Arbitrary "Text")]) (GoTo namespace') , tok "(?<!\\.)(true|false|null|self|__eval__|__switch__|array|assert|checked|enumerate|filter|getter|len|lock|map|matrix|max|min|normalArrayIndexing|print|property|range|rawArrayIndexing|required|typeof|unchecked|using|yieldAll|zip)\\b" (Arbitrary "Name" :. Arbitrary "Builtin") , tok "\"\"\"(\\\\|\\\"|.*?)\"\"\"" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Double") , tok "\"(\\\\|\\\"|[^\"]*?)\"" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Double") , tok "'(\\\\|\\'|[^']*?)'" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Single") , tok "[a-zA-Z_][a-zA-Z0-9_]*" (Arbitrary "Name") , tok "(\\d+\\.\\d*|\\d*\\.\\d+)([fF][+-]?[0-9]+)?" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Float") , tok "[0-9][0-9\\.]*(m|ms|d|h|s)" (Arbitrary "Literal" :. Arbitrary "Number") , tok "0\\d+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Oct") , tok "0x[a-fA-F0-9]+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Hex") , tok "\\d+L" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Integer" :. Arbitrary "Long") , tok "\\d+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Integer") ] funcname' :: TokenMatcher funcname' = [ tokNext "[a-zA-Z_][a-zA-Z0-9_]*" (Arbitrary "Name" :. Arbitrary "Function") Pop ]
chemist/highlighter
src/Text/Highlighter/Lexers/Boo.hs
bsd-3-clause
3,659
0
11
543
925
468
457
54
1
{-# LANGUAGE ForeignFunctionInterface #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Elem.LAPACK.Double -- Copyright : Copyright (c) , Patrick Perry <[email protected]> -- License : BSD3 -- Maintainer : Patrick Perry <[email protected]> -- Stability : experimental -- module Data.Elem.LAPACK.Double where import Foreign( Ptr ) import LAPACK.CTypes foreign import ccall unsafe "LAPACK.h lapack_dgeqrf" dgeqrf :: Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dgelqf" dgelqf :: Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dormqr" dormqr :: CBLASSide -> CBLASTrans -> Int -> Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dormlq" dormlq :: CBLASSide -> CBLASTrans -> Int -> Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dlarfg" dlarfg :: Int -> Ptr Double -> Ptr Double -> Int -> Ptr Double -> IO ()
patperry/lapack
lib/Data/Elem/LAPACK/Double.hs
bsd-3-clause
1,270
0
18
259
340
172
168
16
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- -- 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.Core.Constructs.Integral ( INTEGRAL (..) ) where import Data.Bits import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Condition import Feldspar.Range import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Bits import Feldspar.Core.Constructs.Eq import Feldspar.Core.Constructs.Ord import Feldspar.Core.Constructs.Logic import Feldspar.Core.Constructs.Complex data INTEGRAL a where Quot :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Rem :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Div :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Mod :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Exp :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) instance Semantic INTEGRAL where semantics Quot = Sem "quot" quot semantics Rem = Sem "rem" rem semantics Div = Sem "div" div semantics Mod = Sem "mod" mod semantics Exp = Sem "(^)" (^) semanticInstances ''INTEGRAL instance EvalBind INTEGRAL where evalBindSym = evalBindSymDefault instance AlphaEq dom dom dom env => AlphaEq INTEGRAL INTEGRAL dom env where alphaEqSym = alphaEqSymDefault instance Sharable INTEGRAL instance Cumulative INTEGRAL instance SizeProp (INTEGRAL :|| Type) where sizeProp (C' Quot) (WrapFull a :* WrapFull b :* Nil) = rangeQuot (infoSize a) (infoSize b) sizeProp (C' Rem) (WrapFull a :* WrapFull b :* Nil) = rangeRem (infoSize a) (infoSize b) sizeProp (C' Div) (WrapFull a :* WrapFull b :* Nil) = rangeDiv (infoSize a) (infoSize b) sizeProp (C' Mod) (WrapFull a :* WrapFull b :* Nil) = rangeMod (infoSize a) (infoSize b) sizeProp (C' Exp) (WrapFull a :* WrapFull b :* Nil) = rangeExp (infoSize a) (infoSize b) instance ( (INTEGRAL :||Type) :<: dom , (BITS :||Type) :<: dom , (EQ :||Type) :<: dom , (ORD :||Type) :<: dom , (COMPLEX :|| Type) :<: dom , (Condition :||Type) :<: dom , (Logic :||Type) :<: dom , Cumulative dom , OptimizeSuper dom , Optimize (Condition :|| Type) dom ) => Optimize (INTEGRAL :|| Type) dom where constructFeatOpt _ (C' Quot) (a :* b :* Nil) | Just 1 <- viewLiteral b = return a {- -- TODO: Rule disabled because of cyclic imports. constructFeatOpt opts (C' Quot) (a :* b :* Nil) | Just b' <- viewLiteral b , b' > 0 , isPowerOfTwo b' , let l = log2 b' , let lLit = literalDecor l = if isNatural $ infoSize $ getInfo a then constructFeat opts (c' ShiftR) (a :* lLit :* Nil) else do aIsNeg <- constructFeat opts (c' LTH) (a :* literalDecor 0 :* Nil) a' <- constructFeat opts (c' Add) (a :* literalDecor (2^l-1) :* Nil) negCase <- constructFeat opts (c' ShiftR) (a' :* lLit :* Nil) posCase <- constructFeat opts (c' ShiftR) (a :* lLit :* Nil) constructFeat opts (c' Condition) (aIsNeg :* negCase :* posCase :* Nil) -- TODO This rule should also fire when `b` is `2^l` but not a literal. -- TODO Make a case for `isNegative $ infoSize $ getInfo a`. Note that -- `isNegative /= (not . isNatural)` -- TODO Or maybe both `isNegative` and `isPositive` are handled by the -- size-based optimization of `Condition`? -} constructFeatOpt _ (C' Rem) (a :* b :* Nil) | rangeLess sza szb , isNatural sza = return a where sza = infoSize $ getInfo a szb = infoSize $ getInfo b constructFeatOpt _ (C' Div) (a :* b :* Nil) | Just 1 <- viewLiteral b = return a constructFeatOpt opts (C' Div) (a :* b :* Nil) | IntType U _ <- infoType $ getInfo a , Just b' <- viewLiteral b , b' > 0 , isPowerOfTwo b' = constructFeat opts (c' ShiftRU) (a :* literalDecor (log2 b') :* Nil) constructFeatOpt opts (C' Div) (a :* b :* Nil) | sameSign (infoSize (getInfo a)) (infoSize (getInfo b)) = constructFeat opts (c' Quot) (a :* b :* Nil) constructFeatOpt _ (C' Mod) (a :* b :* Nil) | rangeLess sza szb , isNatural sza = return a where sza = infoSize $ getInfo a szb = infoSize $ getInfo b constructFeatOpt opts (C' Mod) (a :* b :* Nil) | sameSign (infoSize (getInfo a)) (infoSize (getInfo b)) = constructFeat opts (c' Rem) (a :* b :* Nil) constructFeatOpt _ (C' Exp) (a :* b :* Nil) | Just 1 <- viewLiteral a = return $ literalDecor 1 | Just 0 <- viewLiteral a = return $ literalDecor 0 | Just 1 <- viewLiteral b = return a | Just 0 <- viewLiteral b = return $ literalDecor 1 constructFeatOpt opts (C' Exp) (a :* b :* Nil) | Just (-1) <- viewLiteral a = do bLSB <- constructFeat opts (c' BAnd) (b :* literalDecor 1 :* Nil) bIsEven <- constructFeat opts (c' Equal) (bLSB :* literalDecor 0 :* Nil) -- TODO Use testBit? (remove EQ :<: dom and import) constructFeat opts (c' Condition) (bIsEven :* literalDecor 1 :* literalDecor (-1) :* Nil) constructFeatOpt opts a args = constructFeatUnOpt opts a args constructFeatUnOpt opts x@(C' _) = constructFeatUnOptDefault opts x -- Auxiliary functions -- shouldn't be used for negative numbers isPowerOfTwo :: (Num a, Bits a) => a -> Bool isPowerOfTwo x = x .&. (x - 1) == 0 && (x /= 0) log2 :: (BoundedInt a, Integral b) => a -> b log2 v | v <= 1 = 0 log2 v = 1 + log2 (shiftR v 1) sameSign :: BoundedInt a => Range a -> Range a -> Bool sameSign ra rb = isNatural ra && isNatural rb || isNegative ra && isNegative rb
emwap/feldspar-language
src/Feldspar/Core/Constructs/Integral.hs
bsd-3-clause
7,822
0
15
2,016
2,001
1,007
994
109
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Rank2Types #-} module Hmlk.DataSet where import Debug.Trace import Data.IntMap (IntMap, fromList, elems, size, toList) import Data.Monoid import Data.MultiSet (findMax, insert, empty) import Data.List (maximumBy, elemIndex) import Data.Function (on) import Control.Lens hiding (rmap) import Control.Monad import Control.Monad.Trans.State import Control.Monad.Trans.Class data Attribute = Missing | Numeric Double | Nominal String | Boolean Bool deriving (Eq, Show, Ord) data Row = Row {_attributes :: [Attribute], _names :: [String]} deriving (Show) data DataSet = DataSet {_rows :: IntMap [Attribute], _names' :: [String]} makeLenses ''Row rows :: Lens' DataSet [Row] rows = lens getter (const buildRows) where getter ds = map (\x -> Row {_attributes = x, _names = _names' ds}) . elems . _rows $ ds buildRows rs = DataSet {_rows = fromList . zip [1..] . map _attributes $ rs, _names' = maybeNames rs} where maybeNames [] = [] maybeNames rs = _names . head $ rs instance Monoid Row where Row {_attributes = a1, _names = n1} `mappend` Row {_attributes = a2, _names = n2} = Row {_attributes = a1 ++ a2, _names = n1 ++ n2} mempty = Row {_attributes = [], _names = []} rmap :: (String -> Attribute -> a) -> Row -> [a] rmap f r = zipWith f (r ^. names) (r ^. attributes) namedNominals :: Row -> [(String, String)] namedNominals = map (\(x, Nominal n) -> (x, n)) . filter (isNominal . snd) . rmap (,) attr :: String -> Lens' Row Attribute attr s = lens getter setter where getter Row {_attributes = a, _names = n} = case s `elemIndex` n of Just i -> a !! i Nothing -> error "Attribute doesn't exist" setter (Row {_attributes = a, _names = n}) x = case s `elemIndex` n of Just i -> (Row {_names = n, _attributes = (a & (element i) .~ x)}) Nothing -> error "Attribute doesn't exist" dropCols :: DataSet -> (String -> Bool) -> DataSet dropCols ds f = ds & rows .~ newRows where newRows = map dropCols' (ds ^. rows) dropCols' row = row & names .~ n & attributes .~ a where a = filterW c $ row ^. attributes n = filterW c $ _names' ds c = map (\x -> not $ f x) $ _names' ds filterW :: [Bool] -> [a] -> [a] filterW ps xs = [x | (x, p) <- zip xs ps, p] numeric :: String -> Lens' Row Double numeric s = lens getter setter where getter r = case r ^. attr s of Numeric n -> n _ -> 0 setter r x = case r ^. attr s of Numeric n -> r & attr s .~ Numeric x _ -> r nominal :: String -> Lens' Row String nominal s = lens getter setter where getter r = case r ^. attr s of Nominal n -> n _ -> "" setter r x = case r ^. attr s of Nominal n -> r & attr s .~ Nominal x _ -> r addAttr :: String -> (Row -> Attribute) -> Row -> Row addAttr name f r = r & attributes <>~ [(f r)] & names <>~ [name] rmAttr :: String -> Row -> Row rmAttr name r = r & attributes %~ remove & names %~ remove where i = case name `elemIndex` (r ^. names) of Just i -> i + 1 Nothing -> error $ "Attribute " ++ name ++ " does not exist" remove l = [x | (j, x) <- zip [1..] l, j /= i] instance Show DataSet where show d@DataSet {_rows = r, _names' = n} | size r > 20 = header ++ "\n(too many rows too show: " ++ (show $ size r) ++ " - use \"dumpData\" to see them)" | otherwise = dumpData' d where paddingSize = 16 --fixme padding x = (replicate (paddingSize - length x + 1) ' ') ++ x ++ " |" header = unwords . map padding $ n dumpData' DataSet {_rows = r, _names' = n} = unlines $ header:(replicate (length header) '-'):datas where paddingSize = 16 --fixme padding x = (replicate (paddingSize - length x + 1) ' ') ++ x ++ " |" header = unwords . map padding $ n datas = [unwords . map (padding . showAttribute) $ x | (_, x) <- toList r] showAttribute (Numeric n) = show n showAttribute (Nominal n) = n showAttribute (Boolean n) = show n showAttribute Missing = "?" dumpData ds = putStrLn $ dumpData' ds numericsOf :: DataSet -> [[Double]] numericsOf ds = map (map strip . filter isNumeric) (ds ^.. rows . traverse . attributes) where strip (Numeric n) = n nominalsOf :: DataSet -> [[String]] nominalsOf ds = map (map strip . filter isNominal) (ds ^.. rows . traverse . attributes) where strip (Nominal n) = n isNumeric :: Attribute -> Bool isNumeric (Numeric n) = True isNumeric _ = False isNominal :: Attribute -> Bool isNominal (Nominal n) = True isNominal _ = False isMissing :: Attribute -> Bool isMissing Missing = True isMissing _ = False
rednum/hmlk
Hmlk/DataSet.hs
bsd-3-clause
4,739
0
17
1,250
2,000
1,057
943
-1
-1
{-# LANGUAGE CPP, ScopedTypeVariables, MagicHash, UnboxedTuples #-} ----------------------------------------------------------------------------- -- -- GHC Interactive support for inspecting arbitrary closures at runtime -- -- Pepe Iborra (supported by Google SoC) 2006 -- ----------------------------------------------------------------------------- module RtClosureInspect( cvObtainTerm, -- :: HscEnv -> Int -> Bool -> Maybe Type -> HValue -> IO Term cvReconstructType, improveRTTIType, Term(..), isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap, isFullyEvaluated, isFullyEvaluatedTerm, termType, mapTermType, termTyVars, foldTerm, TermFold(..), foldTermM, TermFoldM(..), idTermFold, pprTerm, cPprTerm, cPprTermBase, CustomTermPrinter, -- unsafeDeepSeq, Closure(..), getClosureData, ClosureType(..), isConstr, isIndirection ) where #include "HsVersions.h" import DebuggerUtils import ByteCodeItbls ( StgInfoTable, peekItbl ) import qualified ByteCodeItbls as BCI( StgInfoTable(..) ) import BasicTypes ( HValue ) import HscTypes import DataCon import Type import qualified Unify as U import Var import TcRnMonad import TcType import TcMType import TcHsSyn ( zonkTcTypeToType, mkEmptyZonkEnv ) import TcUnify import TcEnv import TyCon import Name import VarEnv import Util import VarSet import BasicTypes ( TupleSort(UnboxedTuple) ) import TysPrim import PrelNames import TysWiredIn import DynFlags import Outputable as Ppr import GHC.Arr ( Array(..) ) import GHC.Exts import GHC.IO ( IO(..) ) import StaticFlags( opt_PprStyle_Debug ) import Control.Monad import Data.Maybe import Data.Array.Base import Data.Ix import Data.List import qualified Data.Sequence as Seq #if __GLASGOW_HASKELL__ < 709 import Data.Monoid (mappend) #endif import Data.Sequence (viewl, ViewL(..)) import Foreign.Safe import System.IO.Unsafe --------------------------------------------- -- * A representation of semi evaluated Terms --------------------------------------------- data Term = Term { ty :: RttiType , dc :: Either String DataCon -- Carries a text representation if the datacon is -- not exported by the .hi file, which is the case -- for private constructors in -O0 compiled libraries , val :: HValue , subTerms :: [Term] } | Prim { ty :: RttiType , value :: [Word] } | Suspension { ctype :: ClosureType , ty :: RttiType , val :: HValue , bound_to :: Maybe Name -- Useful for printing } | NewtypeWrap{ -- At runtime there are no newtypes, and hence no -- newtype constructors. A NewtypeWrap is just a -- made-up tag saying "heads up, there used to be -- a newtype constructor here". ty :: RttiType , dc :: Either String DataCon , wrapped_term :: Term } | RefWrap { -- The contents of a reference ty :: RttiType , wrapped_term :: Term } isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap :: Term -> Bool isTerm Term{} = True isTerm _ = False isSuspension Suspension{} = True isSuspension _ = False isPrim Prim{} = True isPrim _ = False isNewtypeWrap NewtypeWrap{} = True isNewtypeWrap _ = False isFun Suspension{ctype=Fun} = True isFun _ = False isFunLike s@Suspension{ty=ty} = isFun s || isFunTy ty isFunLike _ = False termType :: Term -> RttiType termType t = ty t isFullyEvaluatedTerm :: Term -> Bool isFullyEvaluatedTerm Term {subTerms=tt} = all isFullyEvaluatedTerm tt isFullyEvaluatedTerm Prim {} = True isFullyEvaluatedTerm NewtypeWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm RefWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm _ = False instance Outputable (Term) where ppr t | Just doc <- cPprTerm cPprTermBase t = doc | otherwise = panic "Outputable Term instance" ------------------------------------------------------------------------- -- Runtime Closure Datatype and functions for retrieving closure related stuff ------------------------------------------------------------------------- data ClosureType = Constr | Fun | Thunk Int | ThunkSelector | Blackhole | AP | PAP | Indirection Int | MutVar Int | MVar Int | Other Int deriving (Show, Eq) data Closure = Closure { tipe :: ClosureType , infoPtr :: Ptr () , infoTable :: StgInfoTable , ptrs :: Array Int HValue , nonPtrs :: [Word] } instance Outputable ClosureType where ppr = text . show #include "../includes/rts/storage/ClosureTypes.h" aP_CODE, pAP_CODE :: Int aP_CODE = AP pAP_CODE = PAP #undef AP #undef PAP getClosureData :: DynFlags -> a -> IO Closure getClosureData dflags a = case unpackClosure# a of (# iptr, ptrs, nptrs #) -> do let iptr' | ghciTablesNextToCode = Ptr iptr | otherwise = -- the info pointer we get back from unpackClosure# -- is to the beginning of the standard info table, -- but the Storable instance for info tables takes -- into account the extra entry pointer when -- !ghciTablesNextToCode, so we must adjust here: Ptr iptr `plusPtr` negate (wORD_SIZE dflags) itbl <- peekItbl dflags iptr' let tipe = readCType (BCI.tipe itbl) elems = fromIntegral (BCI.ptrs itbl) ptrsList = Array 0 (elems - 1) elems ptrs nptrs_data = [W# (indexWordArray# nptrs i) | I# i <- [0.. fromIntegral (BCI.nptrs itbl)-1] ] ASSERT(elems >= 0) return () ptrsList `seq` return (Closure tipe (Ptr iptr) itbl ptrsList nptrs_data) readCType :: Integral a => a -> ClosureType readCType i | i >= CONSTR && i <= CONSTR_NOCAF_STATIC = Constr | i >= FUN && i <= FUN_STATIC = Fun | i >= THUNK && i < THUNK_SELECTOR = Thunk i' | i == THUNK_SELECTOR = ThunkSelector | i == BLACKHOLE = Blackhole | i >= IND && i <= IND_STATIC = Indirection i' | i' == aP_CODE = AP | i == AP_STACK = AP | i' == pAP_CODE = PAP | i == MUT_VAR_CLEAN || i == MUT_VAR_DIRTY= MutVar i' | i == MVAR_CLEAN || i == MVAR_DIRTY = MVar i' | otherwise = Other i' where i' = fromIntegral i isConstr, isIndirection, isThunk :: ClosureType -> Bool isConstr Constr = True isConstr _ = False isIndirection (Indirection _) = True isIndirection _ = False isThunk (Thunk _) = True isThunk ThunkSelector = True isThunk AP = True isThunk _ = False isFullyEvaluated :: DynFlags -> a -> IO Bool isFullyEvaluated dflags a = do closure <- getClosureData dflags a case tipe closure of Constr -> do are_subs_evaluated <- amapM (isFullyEvaluated dflags) (ptrs closure) return$ and are_subs_evaluated _ -> return False where amapM f = sequence . amap' f -- TODO: Fix it. Probably the otherwise case is failing, trace/debug it {- unsafeDeepSeq :: a -> b -> b unsafeDeepSeq = unsafeDeepSeq1 2 where unsafeDeepSeq1 0 a b = seq a $! b unsafeDeepSeq1 i a b -- 1st case avoids infinite loops for non reducible thunks | not (isConstr tipe) = seq a $! unsafeDeepSeq1 (i-1) a b -- | unsafePerformIO (isFullyEvaluated a) = b | otherwise = case unsafePerformIO (getClosureData a) of closure -> foldl' (flip unsafeDeepSeq) b (ptrs closure) where tipe = unsafePerformIO (getClosureType a) -} ----------------------------------- -- * Traversals for Terms ----------------------------------- type TermProcessor a b = RttiType -> Either String DataCon -> HValue -> [a] -> b data TermFold a = TermFold { fTerm :: TermProcessor a a , fPrim :: RttiType -> [Word] -> a , fSuspension :: ClosureType -> RttiType -> HValue -> Maybe Name -> a , fNewtypeWrap :: RttiType -> Either String DataCon -> a -> a , fRefWrap :: RttiType -> a -> a } data TermFoldM m a = TermFoldM {fTermM :: TermProcessor a (m a) , fPrimM :: RttiType -> [Word] -> m a , fSuspensionM :: ClosureType -> RttiType -> HValue -> Maybe Name -> m a , fNewtypeWrapM :: RttiType -> Either String DataCon -> a -> m a , fRefWrapM :: RttiType -> a -> m a } foldTerm :: TermFold a -> Term -> a foldTerm tf (Term ty dc v tt) = fTerm tf ty dc v (map (foldTerm tf) tt) foldTerm tf (Prim ty v ) = fPrim tf ty v foldTerm tf (Suspension ct ty v b) = fSuspension tf ct ty v b foldTerm tf (NewtypeWrap ty dc t) = fNewtypeWrap tf ty dc (foldTerm tf t) foldTerm tf (RefWrap ty t) = fRefWrap tf ty (foldTerm tf t) foldTermM :: Monad m => TermFoldM m a -> Term -> m a foldTermM tf (Term ty dc v tt) = mapM (foldTermM tf) tt >>= fTermM tf ty dc v foldTermM tf (Prim ty v ) = fPrimM tf ty v foldTermM tf (Suspension ct ty v b) = fSuspensionM tf ct ty v b foldTermM tf (NewtypeWrap ty dc t) = foldTermM tf t >>= fNewtypeWrapM tf ty dc foldTermM tf (RefWrap ty t) = foldTermM tf t >>= fRefWrapM tf ty idTermFold :: TermFold Term idTermFold = TermFold { fTerm = Term, fPrim = Prim, fSuspension = Suspension, fNewtypeWrap = NewtypeWrap, fRefWrap = RefWrap } mapTermType :: (RttiType -> Type) -> Term -> Term mapTermType f = foldTerm idTermFold { fTerm = \ty dc hval tt -> Term (f ty) dc hval tt, fSuspension = \ct ty hval n -> Suspension ct (f ty) hval n, fNewtypeWrap= \ty dc t -> NewtypeWrap (f ty) dc t, fRefWrap = \ty t -> RefWrap (f ty) t} mapTermTypeM :: Monad m => (RttiType -> m Type) -> Term -> m Term mapTermTypeM f = foldTermM TermFoldM { fTermM = \ty dc hval tt -> f ty >>= \ty' -> return $ Term ty' dc hval tt, fPrimM = (return.) . Prim, fSuspensionM = \ct ty hval n -> f ty >>= \ty' -> return $ Suspension ct ty' hval n, fNewtypeWrapM= \ty dc t -> f ty >>= \ty' -> return $ NewtypeWrap ty' dc t, fRefWrapM = \ty t -> f ty >>= \ty' -> return $ RefWrap ty' t} termTyVars :: Term -> TyVarSet termTyVars = foldTerm TermFold { fTerm = \ty _ _ tt -> tyVarsOfType ty `plusVarEnv` concatVarEnv tt, fSuspension = \_ ty _ _ -> tyVarsOfType ty, fPrim = \ _ _ -> emptyVarEnv, fNewtypeWrap= \ty _ t -> tyVarsOfType ty `plusVarEnv` t, fRefWrap = \ty t -> tyVarsOfType ty `plusVarEnv` t} where concatVarEnv = foldr plusVarEnv emptyVarEnv ---------------------------------- -- Pretty printing of terms ---------------------------------- type Precedence = Int type TermPrinter = Precedence -> Term -> SDoc type TermPrinterM m = Precedence -> Term -> m SDoc app_prec,cons_prec, max_prec ::Int max_prec = 10 app_prec = max_prec cons_prec = 5 -- TODO Extract this info from GHC itself pprTerm :: TermPrinter -> TermPrinter pprTerm y p t | Just doc <- pprTermM (\p -> Just . y p) p t = doc pprTerm _ _ _ = panic "pprTerm" pprTermM, ppr_termM, pprNewtypeWrap :: Monad m => TermPrinterM m -> TermPrinterM m pprTermM y p t = pprDeeper `liftM` ppr_termM y p t ppr_termM y p Term{dc=Left dc_tag, subTerms=tt} = do tt_docs <- mapM (y app_prec) tt return $ cparen (not (null tt) && p >= app_prec) (text dc_tag <+> pprDeeperList fsep tt_docs) ppr_termM y p Term{dc=Right dc, subTerms=tt} {- | dataConIsInfix dc, (t1:t2:tt') <- tt --TODO fixity = parens (ppr_term1 True t1 <+> ppr dc <+> ppr_term1 True ppr t2) <+> hsep (map (ppr_term1 True) tt) -} -- TODO Printing infix constructors properly | null sub_terms_to_show = return (ppr dc) | otherwise = do { tt_docs <- mapM (y app_prec) sub_terms_to_show ; return $ cparen (p >= app_prec) $ sep [ppr dc, nest 2 (pprDeeperList fsep tt_docs)] } where sub_terms_to_show -- Don't show the dictionary arguments to -- constructors unless -dppr-debug is on | opt_PprStyle_Debug = tt | otherwise = dropList (dataConTheta dc) tt ppr_termM y p t@NewtypeWrap{} = pprNewtypeWrap y p t ppr_termM y p RefWrap{wrapped_term=t} = do contents <- y app_prec t return$ cparen (p >= app_prec) (text "GHC.Prim.MutVar#" <+> contents) -- The constructor name is wired in here ^^^ for the sake of simplicity. -- I don't think mutvars are going to change in a near future. -- In any case this is solely a presentation matter: MutVar# is -- a datatype with no constructors, implemented by the RTS -- (hence there is no way to obtain a datacon and print it). ppr_termM _ _ t = ppr_termM1 t ppr_termM1 :: Monad m => Term -> m SDoc ppr_termM1 Prim{value=words, ty=ty} = return $ repPrim (tyConAppTyCon ty) words ppr_termM1 Suspension{ty=ty, bound_to=Nothing} = return (char '_' <+> ifPprDebug (text "::" <> ppr ty)) ppr_termM1 Suspension{ty=ty, bound_to=Just n} -- | Just _ <- splitFunTy_maybe ty = return$ ptext (sLit("<function>") | otherwise = return$ parens$ ppr n <> text "::" <> ppr ty ppr_termM1 Term{} = panic "ppr_termM1 - Term" ppr_termM1 RefWrap{} = panic "ppr_termM1 - RefWrap" ppr_termM1 NewtypeWrap{} = panic "ppr_termM1 - NewtypeWrap" pprNewtypeWrap y p NewtypeWrap{ty=ty, wrapped_term=t} | Just (tc,_) <- tcSplitTyConApp_maybe ty , ASSERT(isNewTyCon tc) True , Just new_dc <- tyConSingleDataCon_maybe tc = do real_term <- y max_prec t return $ cparen (p >= app_prec) (ppr new_dc <+> real_term) pprNewtypeWrap _ _ _ = panic "pprNewtypeWrap" ------------------------------------------------------- -- Custom Term Pretty Printers ------------------------------------------------------- -- We can want to customize the representation of a -- term depending on its type. -- However, note that custom printers have to work with -- type representations, instead of directly with types. -- We cannot use type classes here, unless we employ some -- typerep trickery (e.g. Weirich's RepLib tricks), -- which I didn't. Therefore, this code replicates a lot -- of what type classes provide for free. type CustomTermPrinter m = TermPrinterM m -> [Precedence -> Term -> (m (Maybe SDoc))] -- | Takes a list of custom printers with a explicit recursion knot and a term, -- and returns the output of the first successful printer, or the default printer cPprTerm :: Monad m => CustomTermPrinter m -> Term -> m SDoc cPprTerm printers_ = go 0 where printers = printers_ go go prec t = do let default_ = Just `liftM` pprTermM go prec t mb_customDocs = [pp prec t | pp <- printers] ++ [default_] Just doc <- firstJustM mb_customDocs return$ cparen (prec>app_prec+1) doc firstJustM (mb:mbs) = mb >>= maybe (firstJustM mbs) (return . Just) firstJustM [] = return Nothing -- Default set of custom printers. Note that the recursion knot is explicit cPprTermBase :: forall m. Monad m => CustomTermPrinter m cPprTermBase y = [ ifTerm (isTupleTy.ty) (\_p -> liftM (parens . hcat . punctuate comma) . mapM (y (-1)) . subTerms) , ifTerm (\t -> isTyCon listTyCon (ty t) && subTerms t `lengthIs` 2) ppr_list , ifTerm (isTyCon intTyCon . ty) ppr_int , ifTerm (isTyCon charTyCon . ty) ppr_char , ifTerm (isTyCon floatTyCon . ty) ppr_float , ifTerm (isTyCon doubleTyCon . ty) ppr_double , ifTerm (isIntegerTy . ty) ppr_integer ] where ifTerm :: (Term -> Bool) -> (Precedence -> Term -> m SDoc) -> Precedence -> Term -> m (Maybe SDoc) ifTerm pred f prec t@Term{} | pred t = Just `liftM` f prec t ifTerm _ _ _ _ = return Nothing isTupleTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (isBoxedTupleTyCon tc) isTyCon a_tc ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (a_tc == tc) isIntegerTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (tyConName tc == integerTyConName) ppr_int, ppr_char, ppr_float, ppr_double, ppr_integer :: Precedence -> Term -> m SDoc ppr_int _ v = return (Ppr.int (unsafeCoerce# (val v))) ppr_char _ v = return (Ppr.char '\'' <> Ppr.char (unsafeCoerce# (val v)) <> Ppr.char '\'') ppr_float _ v = return (Ppr.float (unsafeCoerce# (val v))) ppr_double _ v = return (Ppr.double (unsafeCoerce# (val v))) ppr_integer _ v = return (Ppr.integer (unsafeCoerce# (val v))) --Note pprinting of list terms is not lazy ppr_list :: Precedence -> Term -> m SDoc ppr_list p (Term{subTerms=[h,t]}) = do let elems = h : getListTerms t isConsLast = not(termType(last elems) `eqType` termType h) is_string = all (isCharTy . ty) elems print_elems <- mapM (y cons_prec) elems if is_string then return (Ppr.doubleQuotes (Ppr.text (unsafeCoerce# (map val elems)))) else if isConsLast then return $ cparen (p >= cons_prec) $ pprDeeperList fsep $ punctuate (space<>colon) print_elems else return $ brackets $ pprDeeperList fcat $ punctuate comma print_elems where getListTerms Term{subTerms=[h,t]} = h : getListTerms t getListTerms Term{subTerms=[]} = [] getListTerms t@Suspension{} = [t] getListTerms t = pprPanic "getListTerms" (ppr t) ppr_list _ _ = panic "doList" repPrim :: TyCon -> [Word] -> SDoc repPrim t = rep where rep x | t == charPrimTyCon = text $ show (build x :: Char) | t == intPrimTyCon = text $ show (build x :: Int) | t == wordPrimTyCon = text $ show (build x :: Word) | t == floatPrimTyCon = text $ show (build x :: Float) | t == doublePrimTyCon = text $ show (build x :: Double) | t == int32PrimTyCon = text $ show (build x :: Int32) | t == word32PrimTyCon = text $ show (build x :: Word32) | t == int64PrimTyCon = text $ show (build x :: Int64) | t == word64PrimTyCon = text $ show (build x :: Word64) | t == addrPrimTyCon = text $ show (nullPtr `plusPtr` build x) | t == stablePtrPrimTyCon = text "<stablePtr>" | t == stableNamePrimTyCon = text "<stableName>" | t == statePrimTyCon = text "<statethread>" | t == proxyPrimTyCon = text "<proxy>" | t == realWorldTyCon = text "<realworld>" | t == threadIdPrimTyCon = text "<ThreadId>" | t == weakPrimTyCon = text "<Weak>" | t == arrayPrimTyCon = text "<array>" | t == smallArrayPrimTyCon = text "<smallArray>" | t == byteArrayPrimTyCon = text "<bytearray>" | t == mutableArrayPrimTyCon = text "<mutableArray>" | t == smallMutableArrayPrimTyCon = text "<smallMutableArray>" | t == mutableByteArrayPrimTyCon = text "<mutableByteArray>" | t == mutVarPrimTyCon = text "<mutVar>" | t == mVarPrimTyCon = text "<mVar>" | t == tVarPrimTyCon = text "<tVar>" | otherwise = char '<' <> ppr t <> char '>' where build ww = unsafePerformIO $ withArray ww (peek . castPtr) -- This ^^^ relies on the representation of Haskell heap values being -- the same as in a C array. ----------------------------------- -- Type Reconstruction ----------------------------------- {- Type Reconstruction is type inference done on heap closures. The algorithm walks the heap generating a set of equations, which are solved with syntactic unification. A type reconstruction equation looks like: <datacon reptype> = <actual heap contents> The full equation set is generated by traversing all the subterms, starting from a given term. The only difficult part is that newtypes are only found in the lhs of equations. Right hand sides are missing them. We can either (a) drop them from the lhs, or (b) reconstruct them in the rhs when possible. The function congruenceNewtypes takes a shot at (b) -} -- A (non-mutable) tau type containing -- existentially quantified tyvars. -- (since GHC type language currently does not support -- existentials, we leave these variables unquantified) type RttiType = Type -- An incomplete type as stored in GHCi: -- no polymorphism: no quantifiers & all tyvars are skolem. type GhciType = Type -- The Type Reconstruction monad -------------------------------- type TR a = TcM a runTR :: HscEnv -> TR a -> IO a runTR hsc_env thing = do mb_val <- runTR_maybe hsc_env thing case mb_val of Nothing -> error "unable to :print the term" Just x -> return x runTR_maybe :: HscEnv -> TR a -> IO (Maybe a) runTR_maybe hsc_env thing_inside = do { (_errs, res) <- initTc hsc_env HsSrcFile False (icInteractiveModule (hsc_IC hsc_env)) thing_inside ; return res } traceTR :: SDoc -> TR () traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti -- Semantically different to recoverM in TcRnMonad -- recoverM retains the errors in the first action, -- whereas recoverTc here does not recoverTR :: TR a -> TR a -> TR a recoverTR recover thing = do (_,mb_res) <- tryTcErrs thing case mb_res of Nothing -> recover Just res -> return res trIO :: IO a -> TR a trIO = liftTcM . liftIO liftTcM :: TcM a -> TR a liftTcM = id newVar :: Kind -> TR TcType newVar = liftTcM . newFlexiTyVarTy instTyVars :: [TyVar] -> TR ([TcTyVar], [TcType], TvSubst) -- Instantiate fresh mutable type variables from some TyVars -- This function preserves the print-name, which helps error messages instTyVars = liftTcM . tcInstTyVars type RttiInstantiation = [(TcTyVar, TyVar)] -- Associates the typechecker-world meta type variables -- (which are mutable and may be refined), to their -- debugger-world RuntimeUnk counterparts. -- If the TcTyVar has not been refined by the runtime type -- elaboration, then we want to turn it back into the -- original RuntimeUnk -- | Returns the instantiated type scheme ty', and the -- mapping from new (instantiated) -to- old (skolem) type variables instScheme :: QuantifiedType -> TR (TcType, RttiInstantiation) instScheme (tvs, ty) = liftTcM $ do { (tvs', _, subst) <- tcInstTyVars tvs ; let rtti_inst = [(tv',tv) | (tv',tv) <- tvs' `zip` tvs] ; return (substTy subst ty, rtti_inst) } applyRevSubst :: RttiInstantiation -> TR () -- Apply the *reverse* substitution in-place to any un-filled-in -- meta tyvars. This recovers the original debugger-world variable -- unless it has been refined by new information from the heap applyRevSubst pairs = liftTcM (mapM_ do_pair pairs) where do_pair (tc_tv, rtti_tv) = do { tc_ty <- zonkTcTyVar tc_tv ; case tcGetTyVar_maybe tc_ty of Just tv | isMetaTyVar tv -> writeMetaTyVar tv (mkTyVarTy rtti_tv) _ -> return () } -- Adds a constraint of the form t1 == t2 -- t1 is expected to come from walking the heap -- t2 is expected to come from a datacon signature -- Before unification, congruenceNewtypes needs to -- do its magic. addConstraint :: TcType -> TcType -> TR () addConstraint actual expected = do traceTR (text "add constraint:" <+> fsep [ppr actual, equals, ppr expected]) recoverTR (traceTR $ fsep [text "Failed to unify", ppr actual, text "with", ppr expected]) $ do { (ty1, ty2) <- congruenceNewtypes actual expected ; _ <- captureConstraints $ unifyType ty1 ty2 ; return () } -- TOMDO: what about the coercion? -- we should consider family instances -- Type & Term reconstruction ------------------------------ cvObtainTerm :: HscEnv -> Int -> Bool -> RttiType -> HValue -> IO Term cvObtainTerm hsc_env max_depth force old_ty hval = runTR hsc_env $ do -- we quantify existential tyvars as universal, -- as this is needed to be able to manipulate -- them properly let quant_old_ty@(old_tvs, old_tau) = quantifyType old_ty sigma_old_ty = mkForAllTys old_tvs old_tau traceTR (text "Term reconstruction started with initial type " <> ppr old_ty) term <- if null old_tvs then do term <- go max_depth sigma_old_ty sigma_old_ty hval term' <- zonkTerm term return $ fixFunDictionaries $ expandNewtypes term' else do (old_ty', rev_subst) <- instScheme quant_old_ty my_ty <- newVar openTypeKind when (check1 quant_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') term <- go max_depth my_ty sigma_old_ty hval new_ty <- zonkTcType (termType term) if isMonomorphic new_ty || check2 (quantifyType new_ty) quant_old_ty then do traceTR (text "check2 passed") addConstraint new_ty old_ty' applyRevSubst rev_subst zterm' <- zonkTerm term return ((fixFunDictionaries . expandNewtypes) zterm') else do traceTR (text "check2 failed" <+> parens (ppr term <+> text "::" <+> ppr new_ty)) -- we have unsound types. Replace constructor types in -- subterms with tyvars zterm' <- mapTermTypeM (\ty -> case tcSplitTyConApp_maybe ty of Just (tc, _:_) | tc /= funTyCon -> newVar openTypeKind _ -> return ty) term zonkTerm zterm' traceTR (text "Term reconstruction completed." $$ text "Term obtained: " <> ppr term $$ text "Type obtained: " <> ppr (termType term)) return term where dflags = hsc_dflags hsc_env go :: Int -> Type -> Type -> HValue -> TcM Term -- I believe that my_ty should not have any enclosing -- foralls, nor any free RuntimeUnk skolems; -- that is partly what the quantifyType stuff achieved -- -- [SPJ May 11] I don't understand the difference between my_ty and old_ty go max_depth _ _ _ | seq max_depth False = undefined go 0 my_ty _old_ty a = do traceTR (text "Gave up reconstructing a term after" <> int max_depth <> text " steps") clos <- trIO $ getClosureData dflags a return (Suspension (tipe clos) my_ty a Nothing) go max_depth my_ty old_ty a = do let monomorphic = not(isTyVarTy my_ty) -- This ^^^ is a convention. The ancestor tests for -- monomorphism and passes a type instead of a tv clos <- trIO $ getClosureData dflags a case tipe clos of -- Thunks we may want to force t | isThunk t && force -> traceTR (text "Forcing a " <> text (show t)) >> seq a (go (pred max_depth) my_ty old_ty a) -- Blackholes are indirections iff the payload is not TSO or BLOCKING_QUEUE. So we -- treat them like indirections; if the payload is TSO or BLOCKING_QUEUE, we'll end up -- showing '_' which is what we want. Blackhole -> do traceTR (text "Following a BLACKHOLE") appArr (go max_depth my_ty old_ty) (ptrs clos) 0 -- We always follow indirections Indirection i -> do traceTR (text "Following an indirection" <> parens (int i) ) go max_depth my_ty old_ty $! (ptrs clos ! 0) -- We also follow references MutVar _ | Just (tycon,[world,contents_ty]) <- tcSplitTyConApp_maybe old_ty -> do -- Deal with the MutVar# primitive -- It does not have a constructor at all, -- so we simulate the following one -- MutVar# :: contents_ty -> MutVar# s contents_ty traceTR (text "Following a MutVar") contents_tv <- newVar liftedTypeKind contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w ASSERT(isUnliftedTypeKind $ typeKind my_ty) return () (mutvar_ty,_) <- instScheme $ quantifyType $ mkFunTy contents_ty (mkTyConApp tycon [world,contents_ty]) addConstraint (mkFunTy contents_tv my_ty) mutvar_ty x <- go (pred max_depth) contents_tv contents_ty contents return (RefWrap my_ty x) -- The interesting case Constr -> do traceTR (text "entering a constructor " <> if monomorphic then parens (text "already monomorphic: " <> ppr my_ty) else Ppr.empty) Right dcname <- dataConInfoPtrToName (infoPtr clos) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing -> do -- This can happen for private constructors compiled -O0 -- where the .hi descriptor does not export them -- In such case, we return a best approximation: -- ignore the unpointed args, and recover the pointeds -- This preserves laziness, and should be safe. traceTR (text "Not constructor" <+> ppr dcname) let dflags = hsc_dflags hsc_env tag = showPpr dflags dcname vars <- replicateM (length$ elems$ ptrs clos) (newVar liftedTypeKind) subTerms <- sequence [appArr (go (pred max_depth) tv tv) (ptrs clos) i | (i, tv) <- zip [0..] vars] return (Term my_ty (Left ('<' : tag ++ ">")) a subTerms) Just dc -> do traceTR (text "Is constructor" <+> (ppr dc $$ ppr my_ty)) subTtypes <- getDataConArgTys dc my_ty subTerms <- extractSubTerms (\ty -> go (pred max_depth) ty ty) clos subTtypes return (Term my_ty (Right dc) a subTerms) -- The otherwise case: can be a Thunk,AP,PAP,etc. tipe_clos -> return (Suspension tipe_clos my_ty a Nothing) -- insert NewtypeWraps around newtypes expandNewtypes = foldTerm idTermFold { fTerm = worker } where worker ty dc hval tt | Just (tc, args) <- tcSplitTyConApp_maybe ty , isNewTyCon tc , wrapped_type <- newTyConInstRhs tc args , Just dc' <- tyConSingleDataCon_maybe tc , t' <- worker wrapped_type dc hval tt = NewtypeWrap ty (Right dc') t' | otherwise = Term ty dc hval tt -- Avoid returning types where predicates have been expanded to dictionaries. fixFunDictionaries = foldTerm idTermFold {fSuspension = worker} where worker ct ty hval n | isFunTy ty = Suspension ct (dictsView ty) hval n | otherwise = Suspension ct ty hval n extractSubTerms :: (Type -> HValue -> TcM Term) -> Closure -> [Type] -> TcM [Term] extractSubTerms recurse clos = liftM thirdOf3 . go 0 (nonPtrs clos) where go ptr_i ws [] = return (ptr_i, ws, []) go ptr_i ws (ty:tys) | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = do (ptr_i, ws, terms0) <- go ptr_i ws elem_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) | otherwise = case repType ty of UnaryRep rep_ty -> do (ptr_i, ws, term0) <- go_rep ptr_i ws ty (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, term0 : terms1) UbxTupleRep rep_tys -> do (ptr_i, ws, terms0) <- go_unary_types ptr_i ws rep_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) go_unary_types ptr_i ws [] = return (ptr_i, ws, []) go_unary_types ptr_i ws (rep_ty:rep_tys) = do tv <- newVar liftedTypeKind (ptr_i, ws, term0) <- go_rep ptr_i ws tv (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go_unary_types ptr_i ws rep_tys return (ptr_i, ws, term0 : terms1) go_rep ptr_i ws ty rep = case rep of PtrRep -> do t <- appArr (recurse ty) (ptrs clos) ptr_i return (ptr_i + 1, ws, t) _ -> do dflags <- getDynFlags let (ws0, ws1) = splitAt (primRepSizeW dflags rep) ws return (ptr_i, ws1, Prim ty ws0) unboxedTupleTerm ty terms = Term ty (Right (tupleCon UnboxedTuple (length terms))) (error "unboxedTupleTerm: no HValue for unboxed tuple") terms -- Fast, breadth-first Type reconstruction ------------------------------------------ cvReconstructType :: HscEnv -> Int -> GhciType -> HValue -> IO (Maybe Type) cvReconstructType hsc_env max_depth old_ty hval = runTR_maybe hsc_env $ do traceTR (text "RTTI started with initial type " <> ppr old_ty) let sigma_old_ty@(old_tvs, _) = quantifyType old_ty new_ty <- if null old_tvs then return old_ty else do (old_ty', rev_subst) <- instScheme sigma_old_ty my_ty <- newVar openTypeKind when (check1 sigma_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') search (isMonomorphic `fmap` zonkTcType my_ty) (\(ty,a) -> go ty a) (Seq.singleton (my_ty, hval)) max_depth new_ty <- zonkTcType my_ty if isMonomorphic new_ty || check2 (quantifyType new_ty) sigma_old_ty then do traceTR (text "check2 passed" <+> ppr old_ty $$ ppr new_ty) addConstraint my_ty old_ty' applyRevSubst rev_subst zonkRttiType new_ty else traceTR (text "check2 failed" <+> parens (ppr new_ty)) >> return old_ty traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty) return new_ty where dflags = hsc_dflags hsc_env -- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m () search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <> int max_depth <> text " steps") search stop expand l d = case viewl l of EmptyL -> return () x :< xx -> unlessM stop $ do new <- expand x search stop expand (xx `mappend` Seq.fromList new) $! (pred d) -- returns unification tasks,since we are going to want a breadth-first search go :: Type -> HValue -> TR [(Type, HValue)] go my_ty a = do traceTR (text "go" <+> ppr my_ty) clos <- trIO $ getClosureData dflags a case tipe clos of Blackhole -> appArr (go my_ty) (ptrs clos) 0 -- carefully, don't eval the TSO Indirection _ -> go my_ty $! (ptrs clos ! 0) MutVar _ -> do contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w tv' <- newVar liftedTypeKind world <- newVar liftedTypeKind addConstraint my_ty (mkTyConApp mutVarPrimTyCon [world,tv']) return [(tv', contents)] Constr -> do Right dcname <- dataConInfoPtrToName (infoPtr clos) traceTR (text "Constr1" <+> ppr dcname) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing-> do -- TODO: Check this case forM [0..length (elems $ ptrs clos)] $ \i -> do tv <- newVar liftedTypeKind return$ appArr (\e->(tv,e)) (ptrs clos) i Just dc -> do arg_tys <- getDataConArgTys dc my_ty (_, itys) <- findPtrTyss 0 arg_tys traceTR (text "Constr2" <+> ppr dcname <+> ppr arg_tys) return $ [ appArr (\e-> (ty,e)) (ptrs clos) i | (i,ty) <- itys] _ -> return [] findPtrTys :: Int -- Current pointer index -> Type -- Type -> TR (Int, [(Int, Type)]) findPtrTys i ty | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = findPtrTyss i elem_tys | otherwise = case repType ty of UnaryRep rep_ty | typePrimRep rep_ty == PtrRep -> return (i + 1, [(i, ty)]) | otherwise -> return (i, []) UbxTupleRep rep_tys -> foldM (\(i, extras) rep_ty -> if typePrimRep rep_ty == PtrRep then newVar liftedTypeKind >>= \tv -> return (i + 1, extras ++ [(i, tv)]) else return (i, extras)) (i, []) rep_tys findPtrTyss :: Int -> [Type] -> TR (Int, [(Int, Type)]) findPtrTyss i tys = foldM step (i, []) tys where step (i, discovered) elem_ty = findPtrTys i elem_ty >>= \(i, extras) -> return (i, discovered ++ extras) -- Compute the difference between a base type and the type found by RTTI -- improveType <base_type> <rtti_type> -- The types can contain skolem type variables, which need to be treated as normal vars. -- In particular, we want them to unify with things. improveRTTIType :: HscEnv -> RttiType -> RttiType -> Maybe TvSubst improveRTTIType _ base_ty new_ty = U.tcUnifyTy base_ty new_ty getDataConArgTys :: DataCon -> Type -> TR [Type] -- Given the result type ty of a constructor application (D a b c :: ty) -- return the types of the arguments. This is RTTI-land, so 'ty' might -- not be fully known. Moreover, the arg types might involve existentials; -- if so, make up fresh RTTI type variables for them -- -- I believe that con_app_ty should not have any enclosing foralls getDataConArgTys dc con_app_ty = do { let UnaryRep rep_con_app_ty = repType con_app_ty ; traceTR (text "getDataConArgTys 1" <+> (ppr con_app_ty $$ ppr rep_con_app_ty $$ ppr (tcSplitTyConApp_maybe rep_con_app_ty))) ; (_, _, subst) <- instTyVars (univ_tvs ++ ex_tvs) ; addConstraint rep_con_app_ty (substTy subst (dataConOrigResTy dc)) -- See Note [Constructor arg types] ; let con_arg_tys = substTys subst (dataConRepArgTys dc) ; traceTR (text "getDataConArgTys 2" <+> (ppr rep_con_app_ty $$ ppr con_arg_tys $$ ppr subst)) ; return con_arg_tys } where univ_tvs = dataConUnivTyVars dc ex_tvs = dataConExTyVars dc {- Note [Constructor arg types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a GADT (cf Trac #7386) data family D a b data instance D [a] a where MkT :: a -> D [a] (Maybe a) ... In getDataConArgTys * con_app_ty is the known type (from outside) of the constructor application, say D [Int] Int * The data constructor MkT has a (representation) dataConTyCon = DList, say where data DList a where MkT :: a -> DList a (Maybe a) ... So the dataConTyCon of the data constructor, DList, differs from the "outside" type, D. So we can't straightforwardly decompose the "outside" type, and we end up in the "_" branch of the case. Then we match the dataConOrigResTy of the data constructor against the outside type, hoping to get a substitution that tells how to instantiate the *representation* type constructor. This looks a bit delicate to me, but it seems to work. -} -- Soundness checks -------------------- {- This is not formalized anywhere, so hold to your seats! RTTI in the presence of newtypes can be a tricky and unsound business. Example: ~~~~~~~~~ Suppose we are doing RTTI for a partially evaluated closure t, the real type of which is t :: MkT Int, for newtype MkT a = MkT [Maybe a] The table below shows the results of RTTI and the improvement calculated for different combinations of evaluatedness and :type t. Regard the two first columns as input and the next two as output. # | t | :type t | rtti(t) | improv. | result ------------------------------------------------------------ 1 | _ | t b | a | none | OK 2 | _ | MkT b | a | none | OK 3 | _ | t Int | a | none | OK If t is not evaluated at *all*, we are safe. 4 | (_ : _) | t b | [a] | t = [] | UNSOUND 5 | (_ : _) | MkT b | MkT a | none | OK (compensating for the missing newtype) 6 | (_ : _) | t Int | [Int] | t = [] | UNSOUND If a is a minimal whnf, we run into trouble. Note that row 5 above does newtype enrichment on the ty_rtty parameter. 7 | (Just _:_)| t b |[Maybe a] | t = [], | UNSOUND | | | b = Maybe a| 8 | (Just _:_)| MkT b | MkT a | none | OK 9 | (Just _:_)| t Int | FAIL | none | OK And if t is any more evaluated than whnf, we are still in trouble. Because constraints are solved in top-down order, when we reach the Maybe subterm what we got is already unsound. This explains why the row 9 fails to complete. 10 | (Just _:_)| t Int | [Maybe a] | FAIL | OK 11 | (Just 1:_)| t Int | [Maybe Int] | FAIL | OK We can undo the failure in row 9 by leaving out the constraint coming from the type signature of t (i.e., the 2nd column). Note that this type information is still used to calculate the improvement. But we fail when trying to calculate the improvement, as there is no unifier for t Int = [Maybe a] or t Int = [Maybe Int]. Another set of examples with t :: [MkT (Maybe Int)] \equiv [[Maybe (Maybe Int)]] # | t | :type t | rtti(t) | improvement | result --------------------------------------------------------------------- 1 |(Just _:_) | [t (Maybe a)] | [[Maybe b]] | t = [] | | | | | b = Maybe a | The checks: ~~~~~~~~~~~ Consider a function obtainType that takes a value and a type and produces the Term representation and a substitution (the improvement). Assume an auxiliar rtti' function which does the actual job if recovering the type, but which may produce a false type. In pseudocode: rtti' :: a -> IO Type -- Does not use the static type information obtainType :: a -> Type -> IO (Maybe (Term, Improvement)) obtainType v old_ty = do rtti_ty <- rtti' v if monomorphic rtti_ty || (check rtti_ty old_ty) then ... else return Nothing where check rtti_ty old_ty = check1 rtti_ty && check2 rtti_ty old_ty check1 :: Type -> Bool check2 :: Type -> Type -> Bool Now, if rtti' returns a monomorphic type, we are safe. If that is not the case, then we consider two conditions. 1. To prevent the class of unsoundness displayed by rows 4 and 7 in the example: no higher kind tyvars accepted. check1 (t a) = NO check1 (t Int) = NO check1 ([] a) = YES 2. To prevent the class of unsoundness shown by row 6, the rtti type should be structurally more defined than the old type we are comparing it to. check2 :: NewType -> OldType -> Bool check2 a _ = True check2 [a] a = True check2 [a] (t Int) = False check2 [a] (t a) = False -- By check1 we never reach this equation check2 [Int] a = True check2 [Int] (t Int) = True check2 [Maybe a] (t Int) = False check2 [Maybe Int] (t Int) = True check2 (Maybe [a]) (m [Int]) = False check2 (Maybe [Int]) (m [Int]) = True -} check1 :: QuantifiedType -> Bool check1 (tvs, _) = not $ any isHigherKind (map tyVarKind tvs) where isHigherKind = not . null . fst . splitKindFunTys check2 :: QuantifiedType -> QuantifiedType -> Bool check2 (_, rtti_ty) (_, old_ty) | Just (_, rttis) <- tcSplitTyConApp_maybe rtti_ty = case () of _ | Just (_,olds) <- tcSplitTyConApp_maybe old_ty -> and$ zipWith check2 (map quantifyType rttis) (map quantifyType olds) _ | Just _ <- splitAppTy_maybe old_ty -> isMonomorphicOnNonPhantomArgs rtti_ty _ -> True | otherwise = True -- Dealing with newtypes -------------------------- {- congruenceNewtypes does a parallel fold over two Type values, compensating for missing newtypes on both sides. This is necessary because newtypes are not present in runtime, but sometimes there is evidence available. Evidence can come from DataCon signatures or from compile-time type inference. What we are doing here is an approximation of unification modulo a set of equations derived from newtype definitions. These equations should be the same as the equality coercions generated for newtypes in System Fc. The idea is to perform a sort of rewriting, taking those equations as rules, before launching unification. The caller must ensure the following. The 1st type (lhs) comes from the heap structure of ptrs,nptrs. The 2nd type (rhs) comes from a DataCon type signature. Rewriting (i.e. adding/removing a newtype wrapper) can happen in both types, but in the rhs it is restricted to the result type. Note that it is very tricky to make this 'rewriting' work with the unification implemented by TcM, where substitutions are operationally inlined. The order in which constraints are unified is vital as we cannot modify anything that has been touched by a previous unification step. Therefore, congruenceNewtypes is sound only if the types recovered by the RTTI mechanism are unified Top-Down. -} congruenceNewtypes :: TcType -> TcType -> TR (TcType,TcType) congruenceNewtypes lhs rhs = go lhs rhs >>= \rhs' -> return (lhs,rhs') where go l r -- TyVar lhs inductive case | Just tv <- getTyVar_maybe l , isTcTyVar tv , isMetaTyVar tv = recoverTR (return r) $ do Indirect ty_v <- readMetaTyVar tv traceTR $ fsep [text "(congruence) Following indirect tyvar:", ppr tv, equals, ppr ty_v] go ty_v r -- FunTy inductive case | Just (l1,l2) <- splitFunTy_maybe l , Just (r1,r2) <- splitFunTy_maybe r = do r2' <- go l2 r2 r1' <- go l1 r1 return (mkFunTy r1' r2') -- TyconApp Inductive case; this is the interesting bit. | Just (tycon_l, _) <- tcSplitTyConApp_maybe lhs , Just (tycon_r, _) <- tcSplitTyConApp_maybe rhs , tycon_l /= tycon_r = upgrade tycon_l r | otherwise = return r where upgrade :: TyCon -> Type -> TR Type upgrade new_tycon ty | not (isNewTyCon new_tycon) = do traceTR (text "(Upgrade) Not matching newtype evidence: " <> ppr new_tycon <> text " for " <> ppr ty) return ty | otherwise = do traceTR (text "(Upgrade) upgraded " <> ppr ty <> text " in presence of newtype evidence " <> ppr new_tycon) (_, vars, _) <- instTyVars (tyConTyVars new_tycon) let ty' = mkTyConApp new_tycon vars UnaryRep rep_ty = repType ty' _ <- liftTcM (unifyType ty rep_ty) -- assumes that reptype doesn't ^^^^ touch tyconApp args return ty' zonkTerm :: Term -> TcM Term zonkTerm = foldTermM (TermFoldM { fTermM = \ty dc v tt -> zonkRttiType ty >>= \ty' -> return (Term ty' dc v tt) , fSuspensionM = \ct ty v b -> zonkRttiType ty >>= \ty -> return (Suspension ct ty v b) , fNewtypeWrapM = \ty dc t -> zonkRttiType ty >>= \ty' -> return$ NewtypeWrap ty' dc t , fRefWrapM = \ty t -> return RefWrap `ap` zonkRttiType ty `ap` return t , fPrimM = (return.) . Prim }) zonkRttiType :: TcType -> TcM Type -- Zonk the type, replacing any unbound Meta tyvars -- by skolems, safely out of Meta-tyvar-land zonkRttiType = zonkTcTypeToType (mkEmptyZonkEnv zonk_unbound_meta) where zonk_unbound_meta tv = ASSERT( isTcTyVar tv ) do { tv' <- skolemiseUnboundMetaTyVar tv RuntimeUnk -- This is where RuntimeUnks are born: -- otherwise-unconstrained unification variables are -- turned into RuntimeUnks as they leave the -- typechecker's monad ; return (mkTyVarTy tv') } -------------------------------------------------------------------------------- -- Restore Class predicates out of a representation type dictsView :: Type -> Type dictsView ty = ty -- Use only for RTTI types isMonomorphic :: RttiType -> Bool isMonomorphic ty = noExistentials && noUniversals where (tvs, _, ty') = tcSplitSigmaTy ty noExistentials = isEmptyVarSet (tyVarsOfType ty') noUniversals = null tvs -- Use only for RTTI types isMonomorphicOnNonPhantomArgs :: RttiType -> Bool isMonomorphicOnNonPhantomArgs ty | UnaryRep rep_ty <- repType ty , Just (tc, all_args) <- tcSplitTyConApp_maybe rep_ty , phantom_vars <- tyConPhantomTyVars tc , concrete_args <- [ arg | (tyv,arg) <- tyConTyVars tc `zip` all_args , tyv `notElem` phantom_vars] = all isMonomorphicOnNonPhantomArgs concrete_args | Just (ty1, ty2) <- splitFunTy_maybe ty = all isMonomorphicOnNonPhantomArgs [ty1,ty2] | otherwise = isMonomorphic ty tyConPhantomTyVars :: TyCon -> [TyVar] tyConPhantomTyVars tc | isAlgTyCon tc , Just dcs <- tyConDataCons_maybe tc , dc_vars <- concatMap dataConUnivTyVars dcs = tyConTyVars tc \\ dc_vars tyConPhantomTyVars _ = [] type QuantifiedType = ([TyVar], Type) -- Make the free type variables explicit -- The returned Type should have no top-level foralls (I believe) quantifyType :: Type -> QuantifiedType -- Generalize the type: find all free and forall'd tyvars -- and return them, together with the type inside, which -- should not be a forall type. -- -- Thus (quantifyType (forall a. a->[b])) -- returns ([a,b], a -> [b]) quantifyType ty = (varSetElems (tyVarsOfType rho), rho) where (_tvs, rho) = tcSplitForAllTys ty unlessM :: Monad m => m Bool -> m () -> m () unlessM condM acc = condM >>= \c -> unless c acc -- Strict application of f at index i appArr :: Ix i => (e -> a) -> Array i e -> Int -> a appArr f a@(Array _ _ _ ptrs#) i@(I# i#) = ASSERT2(i < length(elems a), ppr(length$ elems a, i)) case indexArray# ptrs# i# of (# e #) -> f e amap' :: (t -> b) -> Array Int t -> [b] amap' f (Array i0 i _ arr#) = map g [0 .. i - i0] where g (I# i#) = case indexArray# arr# i# of (# e #) -> f e
spacekitteh/smcghc
compiler/ghci/RtClosureInspect.hs
bsd-3-clause
52,399
12
27
16,035
12,179
6,184
5,995
-1
-1
module Math.Misc.Parity where import Prelude hiding (fromIntegral) import Math.Algebra.Monoid import Math.Algebra.AbelianMonoid import Data.List import Data.Hashable data Parity = Odd | Even deriving (Eq, Show) instance Hashable Parity where hash Even = 0 hash Odd = 1 opposite :: Parity -> Parity opposite Odd = Even opposite Even = Odd instance MultiplicativeMonoid Parity where Odd <*> Odd = Even Odd <*> Even = Odd Even <*> Odd = Odd Even <*> Even = Even one = Even instance AbelianMultiplicativeMonoid Parity instance Ord Parity where compare Odd Odd = EQ compare Even Even = EQ compare Even Odd = LT compare Odd Even = GT fromIntegral :: (Integral a) => a -> Parity fromIntegral m | even m = Even | otherwise = Odd fromBool :: Bool -> Parity fromBool True = Even fromBool False = Odd fromLength :: [a] -> Parity fromLength = foldl' (\p _ -> (opposite p)) Even
michiexile/hplex
pershom/src/Math/Misc/Parity.hs
bsd-3-clause
949
0
9
232
327
171
156
35
1
---------------------------------------------------------------------------- -- | -- Module : ModuleWithoutImportList -- Copyright : (c) Sergey Vinokurov 2016 -- License : BSD3-style (see LICENSE) -- Maintainer : [email protected] -- Created : Thursday, 20 October 2016 ---------------------------------------------------------------------------- module ModuleWithoutImportList where import ModuleThatExportsPattern
sergv/tags-server
test-data/0006export_pattern_with_type_ghc8.0/ModuleWithoutImportList.hs
bsd-3-clause
440
0
3
60
15
13
2
2
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} module ML.Vec where import ML.Nat import Control.Applicative ((<$>)) data Vec (n :: Nat) (a :: *) where Nil :: Vec Z a (:-) :: a -> Vec n a -> Vec (S n) a instance Functor (Vec n) where fmap f Nil = Nil fmap f (x :- xs) = f x :- fmap f xs instance Foldable (Vec n) where foldr f s Nil = s foldr f s (x :- xs) = foldr f (f x s) xs instance Show a => Show (Vec n a) where show Nil = "[]" show (a :- r) = show a ++ " :- " ++ show r infixr 5 :- fromList :: SNat n -> [a] -> Maybe (Vec n a) fromList SZ _ = Just Nil fromList (SS n) (x:xs) = (x :-) <$> fromList n xs fromList _ _ = Nothing toList :: Vec n a -> [a] toList Nil = [] toList (x :- xs) = x:(toList xs) vzip :: (a -> b -> c) -> Vec n a -> Vec n b -> Vec n c vzip _ Nil _ = Nil vzip f (x :- xs) (y :- ys) = f x y :- vzip f xs ys vlen :: Vec n a -> Int vlen = foldr (\_ x -> x + 1) 0 vdot :: Num a => Vec n a -> Vec n a -> a vdot v1 v2 = vsum $ vzip (*) v1 v2 vmul :: Num a => a -> Vec n a -> Vec n a vmul a = fmap (*a) vsub :: Num a => Vec n a -> Vec n a -> Vec n a vsub = vzip (-) vsum :: Num a => Vec n a -> a vsum = foldr (+) 0 vmax :: Ord a => Vec (S n) a -> a vmax (x :- xs) = foldr (max) x xs
ralphmorton/ml
src/ML/Vec.hs
bsd-3-clause
1,319
0
10
383
767
394
373
42
1
module Data.Torrent.Types ( BEncodedT(..) , mkBString , beList , beDictUTF8L , beDictUTF8 , beDict , beDictLookup , parseBencoded , ClientHandshake(..) , parseClientHandshake , randomPeerId , PeerMessage(..) , parseW8RunLength , beEncodeByteString , beString' , beInteger , beStringUTF8 , putBInt , getBInt ) where import Data.Binary import Data.Binary.Put import Data.Binary.Get import Data.Map (Map) import qualified Data.Map as Map import qualified Codec.Binary.UTF8.Generic as UTF8 import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.Attoparsec (Parser) import qualified Data.Attoparsec.ByteString.Char8 as P import qualified Data.Attoparsec.ByteString as PB import Crypto.Hash.SHA1 import qualified Data.Serialize as Ser import Crypto.Random.API data BEncodedT = BString !ByteString | BInteger !Integer | BList ![BEncodedT] | BDict ![(BEncodedT, BEncodedT)] deriving (Show, Eq) -- | After the client protocol handshake, there comes an alternating stream of length prefixes and 'PeerMessage's data PeerMessage = -- | Messages of length zero are keepalives, and ignored. Keepalives are generally sent once every two minutes, but note that timeouts can be done much more quickly when data is expected. KeepAlive | Choke | Unchoke | Interested | NotInterested | -- | The 'Have' message's payload is a single number, the index which that downloader just completed and checked the hash of. Have Int | -- | 'Bitfield' is only ever sent as the first message. Its payload is a bitfield with each index that downloader has sent set to one and the rest set to zero. Downloaders which don't have anything yet may skip the 'bitfield' message. The first byte of the bitfield corresponds to indices 0 - 7 from high bit to low bit, respectively. The next one 8-15, etc. Spare bits at the end are set to zero. Bitfield ByteString | -- | 'Request' messages contain an index, begin, and length. The last two are byte offsets. Length is generally a power of two unless it gets truncated by the end of the file. All current implementations use 2 15 , and close connections which request an amount greater than 2 17. Request Int Int Int | -- | 'Piece' messages contain an index, begin, and piece. Note that they are correlated with request messages implicitly. It's possible for an unexpected piece to arrive if choke and unchoke messages are sent in quick succession and/or transfer is going very slowly. Piece Int Int ByteString | -- | 'Cancel' messages have the same payload as request messages. They are generally only sent towards the end of a download, during what's called 'endgame mode'. When a download is almost complete, there's a tendency for the last few pieces to all be downloaded off a single hosed modem line, taking a very long time. To make sure the last few pieces come in quickly, once requests for all pieces a given downloader doesn't have yet are currently pending, it sends requests for everything to everyone it's downloading from. To keep this from becoming horribly inefficient, it sends cancels to everyone else every time a piece arrives. Cancel Int Int Int deriving (Show, Eq) instance Binary PeerMessage where put = putPeerMessage get = getPeerMessage putPeerMessage' :: PeerMessage -> Put putPeerMessage' KeepAlive = putLazyByteString BL.empty putPeerMessage' Choke = putWord8 0x00 putPeerMessage' Unchoke = putWord8 0x01 putPeerMessage' Interested = putWord8 0x02 putPeerMessage' NotInterested = putWord8 0x03 putPeerMessage' (Have i) = do putWord8 0x04 putBInt i putPeerMessage' (Bitfield bs) = do putWord8 0x05 putByteString bs putPeerMessage' (Request i b l) = do putWord8 0x06 putBInt i putBInt b putBInt l putPeerMessage' (Piece i b bs) = do putWord8 0x07 putBInt i putBInt b putByteString bs putPeerMessage' (Cancel i b l) = do putWord8 0x08 putBInt i putBInt b putBInt l putPeerMessage :: PeerMessage -> Put putPeerMessage pm = let bs = runPut $ do putPeerMessage' $ pm flush in do putBInt $ BL.length bs putLazyByteString bs flush getPeerMessage :: Get PeerMessage getPeerMessage = do l' <- getBInt if (l' == 0) then return KeepAlive else do t <- getWord8 let l = l' - 1 case t of 0x00 -> return Choke 0x01 -> return Unchoke 0x02 -> return Interested 0x03 -> return NotInterested 0x04 -> fmap Have getBInt 0x05 -> fmap Bitfield $ getByteString l 0x06 -> do i <- getBInt b <- getBInt l <- getBInt return $ Request i b l 0x07 -> do i <- getBInt b <- getBInt bs <- getByteString $ l - 8 return $ Piece i b bs 0x08 -> do i <- getBInt b <- getBInt l <- getBInt return $ Cancel i b l putBInt :: (Integral a) => a -> Put putBInt = putWord32be . fromInteger . toInteger getBInt :: (Integral a) => Get a getBInt = fmap (fromInteger . toInteger) getWord32be mkBString :: String -> BEncodedT mkBString = BString . UTF8.fromString parseW8RunLength :: Parser String parseW8RunLength = do l <- fmap (fromInteger . toInteger) PB.anyWord8 fmap UTF8.toString $ PB.take l data ClientHandshake = ClientHandshake { hsInfoHash :: SHA1, hsPeerId :: ByteString, hsReservedBytes :: ByteString } deriving (Eq, Show) handShakeText :: String handShakeText = "BitTorrent protocol" parseTorrentMagic :: PB.Parser () parseTorrentMagic = do hs <- parseW8RunLength if (hs /= handShakeText) then fail $ "handshake is not '" ++ handShakeText ++ "'" ++ " but '" ++ hs ++ "'" else return () parseClientHandshake :: PB.Parser ClientHandshake parseClientHandshake = do -- torrent magic PB.try $ parseTorrentMagic -- reserved bytes reservedBytes <- PB.take 8 -- info hash ih' <- fmap Ser.decode $ PB.take 20 h <- case (ih') of Left err -> fail $ "unable to decode SHA1 hash: " ++ err Right h -> return h -- peer id peerid <- PB.take 20 return $ ClientHandshake h peerid reservedBytes randomPeerId :: IO ByteString randomPeerId = fmap (fst. genRandomBytes 20) getSystemRandomGen beEncodeByteString :: BEncodedT -> ByteString beEncodeByteString (BString bs) = let l = BS.length bs pfix= UTF8.fromString $ show l ++ ":" in BS.concat [pfix,bs] beEncodeByteString (BInteger i) = UTF8.fromString $ "i" ++ show i ++ "e" beEncodeByteString (BList l) = let ls = BS.concat $ map beEncodeByteString l in BS.concat [UTF8.fromString "l", ls, UTF8.fromString "e"] beEncodeByteString (BDict d) = let r [] = BS.empty r ((k,v):rs) = BS.concat $ [beEncodeByteString k, beEncodeByteString v] ++ [(r rs)] in BS.concat [UTF8.fromString "d", r d, UTF8.fromString "e"] beString' :: BEncodedT -> ByteString beString' (BString bs) = bs beString' v = error $ "beString' called on a: " ++ show v beStringUTF8 = UTF8.toString . beString' beInteger :: BEncodedT -> Integer beInteger (BInteger i) = i beInteger v = error $ "beInteger called on a: " ++ show v beList :: BEncodedT -> [BEncodedT] beList (BList l) = l beList v = error $ "beList called on a: " ++ show v beDictLookup :: String -> BEncodedT -> BEncodedT beDictLookup k = maybe (error $ "unable to lookup dict key " ++ k) id . beDict k beDict :: String -> BEncodedT -> Maybe BEncodedT beDict k d = Map.lookup k $ beDictUTF8 d beDict' :: BEncodedT -> Map ByteString BEncodedT beDict' (BDict d) = Map.fromList [(beString' k, v) | (k,v) <- d] beDict' v = error $ "beDict' called on a: " ++ show v beDictUTF8L :: BEncodedT -> [(String, BEncodedT)] beDictUTF8L (BDict d) = [(beStringUTF8 k, v) | (k,v) <- d] beDictUTF8L v = error $ "beDictUTF8L called on a: " ++ show v beDictUTF8 :: BEncodedT -> Map String BEncodedT beDictUTF8 = Map.fromList . beDictUTF8L parseString :: Parser BEncodedT parseString = do l <- P.decimal _ <- P.char ':' fmap BString $ P.take l parseInteger :: Parser BEncodedT parseInteger = do _ <- P.char 'i' d <- fmap BInteger $ P.signed P.decimal _ <- P.char 'e' return d parseList :: Parser BEncodedT parseList = do _ <- P.char 'l' fmap BList $ P.manyTill parseBencoded $ P.try $ P.char 'e' parseDict :: Parser BEncodedT parseDict = do _ <- P.char 'd' let kvp = do k <- parseString v <- parseBencoded return (k,v) fmap BDict $ P.manyTill kvp $ P.try $ P.char 'e' parseBencoded :: Parser BEncodedT parseBencoded = P.choice [parseString, parseInteger, parseList, parseDict]
alios/lcars2
Data/Torrent/Types.hs
bsd-3-clause
8,746
0
17
1,984
2,284
1,156
1,128
226
10
module YampaSDL where import Data.IORef import FRP.Yampa as Yampa import Graphics.UI.SDL as SDL type TimeRef = IORef Int yampaSDLTimeInit :: IO TimeRef yampaSDLTimeInit = do timeRef <- newIORef (0 :: Int) _ <- yampaSDLTimeSense timeRef _ <- yampaSDLTimeSense timeRef _ <- yampaSDLTimeSense timeRef _ <- yampaSDLTimeSense timeRef return timeRef -- | Updates the time in an IO Ref and returns the time difference updateTime :: IORef Int -> Int -> IO Int updateTime timeRef newTime = do previousTime <- readIORef timeRef writeIORef timeRef newTime return (newTime - previousTime) yampaSDLTimeSense :: IORef Int -> IO Yampa.DTime yampaSDLTimeSense timeRef = do -- Get time passed since SDL init newTime <- fmap fromIntegral SDL.getTicks -- Obtain time difference dt <- updateTime timeRef newTime let dtSecs = fromIntegral dt / 100 return dtSecs
ivanperez-keera/Yampa
yampa/examples/yampa-game/YampaSDL.hs
bsd-3-clause
907
0
11
195
244
117
127
24
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE EmptyDataDecls #-} -- TODO: This is a hot-spot for generating user-unfriendly error messages. It -- could use some cleaning up in this regard. (Perhaps we should be -- lifting from TypecheckedSource instead of CoreExpr?) There's also a -- lot of logic here that wouldn't be necessary if Pred and Expr were -- merged. module Language.Haskell.Liquid.Spec.CoreToLogic ( LogicM, coreToDef, coreToFun, runToLogic, logicType, strengthenResult ) where import GHC hiding (Located) import Var import Type import qualified CoreSyn as C import Literal import IdInfo import TysWiredIn import Control.Applicative import Language.Fixpoint.Misc import Language.Fixpoint.Names (dropModuleNames, propConName, isPrefixOfSym) import Language.Fixpoint.Types hiding (Def, R, simplify) import qualified Language.Fixpoint.Types as F import Language.Haskell.Liquid.GhcMisc import Language.Haskell.Liquid.GhcPlay import Language.Haskell.Liquid.Literals (mkLit) import Language.Haskell.Liquid.Types hiding (GhcInfo(..), GhcSpec (..)) import Language.Haskell.Liquid.WiredIn import Language.Haskell.Liquid.RefType import qualified Data.HashMap.Strict as M import Data.Monoid logicType :: (Reftable r) => Type -> RRType r logicType τ = fromRTypeRep $ t{ty_res = res, ty_binds = binds, ty_args = args, ty_refts = refts} where t = toRTypeRep $ ofType τ res = mkResType $ ty_res t (binds, args, refts) = unzip3 $ dropWhile (isClassType.snd3) $ zip3 (ty_binds t) (ty_args t) (ty_refts t) mkResType t {-| isBool t = propType | otherwise-} = t isBool (RApp (RTyCon{rtc_tc = c}) _ _ _) = c == boolTyCon isBool _ = False {- strengthenResult type: the refinement depends on whether the result type is a Bool or not: CASE1: measure f@logic :: X -> Prop <=> f@haskell :: x:X -> {v:Bool | (Prop v) <=> (f@logic x)} CASE2: measure f@logic :: X -> Y <=> f@haskell :: x:X -> {v:Y | v = (f@logic x)} -} strengthenResult :: Var -> SpecType -> SpecType strengthenResult v t {- | isBool res = -- traceShow ("Type for " ++ showPpr v ++ "\t OF \t" ++ show (ty_binds rep)) $ fromRTypeRep $ rep{ty_res = res `strengthen` r} | otherwise-} = -- traceShow ("Type for " ++ showPpr v ++ "\t OF \t" ++ show (ty_binds rep)) $ fromRTypeRep $ rep{ty_res = res `strengthen` r'} where rep = toRTypeRep t res = ty_res rep r' = U (exprReft (EApp f (mkA <$> vxs))) mempty mempty r = U (propReft (PBexp $ EApp f (mkA <$> vxs))) mempty mempty vxs = dropWhile (isClassType.snd) $ zip (ty_binds rep) (ty_args rep) f = dummyLoc $ varSymbol v mkA = \(x, _) -> EVar x -- if isBool t then EApp (dummyLoc propConName) [(EVar x)] else EVar x newtype LogicM a = LM {runM :: LState -> Either a String} data LState = LState { symbolMap :: LogicMap } instance Monad LogicM where return = LM . const . Left (LM m) >>= f = LM $ \s -> case m s of (Left x) -> (runM (f x)) s (Right x) -> Right x instance Functor LogicM where fmap f (LM m) = LM $ \s -> case m s of (Left x) -> Left $ f x (Right x) -> Right x instance Applicative LogicM where pure = LM . const . Left (LM f) <*> (LM m) = LM $ \s -> case (f s, m s) of (Left f , Left x ) -> Left $ f x (Right f, Left _ ) -> Right f (Left _ , Right x) -> Right x (Right _, Right x) -> Right x throw :: String -> LogicM a throw str = LM $ const $ Right str getState :: LogicM LState getState = LM $ Left runToLogic lmap (LM m) = m $ LState {symbolMap = lmap} coreToDef :: LocSymbol -> Var -> C.CoreExpr -> LogicM [Def] coreToDef x _ e = go [] $ inline_preds $ simplify e where go args (C.Lam x e) = go (x:args) e go args (C.Tick _ e) = go args e go args (C.Case _ _ t alts) | eqType t boolTy = mapM (goalt_prop (reverse $ tail args) (head args)) alts | otherwise = mapM (goalt (reverse $ tail args) (head args)) alts go _ _ = throw "Measure Functions should have a case at top level" goalt args dx ((C.DataAlt d), xs, e) = ((Def x (toArgs id args) d (Just $ ofType $ varType dx) (toArgs Just xs)) . E) <$> coreToLogic e goalt _ _ alt = throw $ "Bad alternative" ++ showPpr alt goalt_prop args dx ((C.DataAlt d), xs, e) = ((Def x (toArgs id args) d (Just $ ofType $ varType dx) (toArgs Just xs)) . P) <$> coreToPred e goalt_prop _ _ alt = throw $ "Bad alternative" ++ showPpr alt toArgs f args = [(symbol x, f $ ofType $ varType x) | x <- args] inline_preds = inline (eqType boolTy . varType) coreToFun :: LocSymbol -> Var -> C.CoreExpr -> LogicM ([Var], Either Pred Expr) coreToFun _ v e = go [] $ inline_preds $ simplify e where go acc (C.Lam x e) | isTyVar x = go acc e go acc (C.Lam x e) | isErasable x = go acc e go acc (C.Lam x e) = go (x:acc) e go acc (C.Tick _ e) = go acc e go acc e | eqType rty boolTy = (reverse acc,) . Left <$> coreToPred e | otherwise = (reverse acc,) . Right <$> coreToLogic e inline_preds = inline (eqType boolTy . varType) rty = snd $ splitFunTys $ snd $ splitForAllTys $ varType v coreToPred :: C.CoreExpr -> LogicM Pred coreToPred (C.Let b p) = subst1 <$> coreToPred p <*> makesub b coreToPred (C.Tick _ p) = coreToPred p coreToPred (C.App (C.Var v) e) | ignoreVar v = coreToPred e coreToPred (C.Var x) | x == falseDataConId = return PFalse | x == trueDataConId = return PTrue | eqType boolTy (varType x) = return $ PBexp $ EVar $ symbol x -- $ EApp (dummyLoc propConName) [(EVar $ symbol x)] coreToPred p@(C.App _ _) = toPredApp p coreToPred e = PBexp <$> coreToLogic e -- coreToPred e -- = throw ("Cannot transform to Logical Predicate:\t" ++ showPpr e) coreToLogic :: C.CoreExpr -> LogicM Expr coreToLogic (C.Let b e) = subst1 <$> coreToLogic e <*> makesub b coreToLogic (C.Tick _ e) = coreToLogic e coreToLogic (C.App (C.Var v) e) | ignoreVar v = coreToLogic e coreToLogic (C.Lit l) = case mkLit l of Nothing -> throw $ "Bad Literal in measure definition" ++ showPpr l Just i -> return i coreToLogic (C.Var x) = (symbolMap <$> getState) >>= eVarWithMap x coreToLogic e@(C.App _ _) = toLogicApp e coreToLogic (C.Case e b _ alts) | eqType (varType b) boolTy = checkBoolAlts alts >>= coreToIte e coreToLogic e = throw ("Cannot transform to Logic:\t" ++ showPpr e) checkBoolAlts :: [C.CoreAlt] -> LogicM (C.CoreExpr, C.CoreExpr) checkBoolAlts [(C.DataAlt false, [], efalse), (C.DataAlt true, [], etrue)] | false == falseDataCon, true == trueDataCon = return (efalse, etrue) checkBoolAlts [(C.DataAlt true, [], etrue), (C.DataAlt false, [], efalse)] | false == falseDataCon, true == trueDataCon = return (efalse, etrue) checkBoolAlts alts = throw ("checkBoolAlts failed on " ++ showPpr alts) coreToIte e (efalse, etrue) = do p <- coreToPred e e1 <- coreToLogic efalse e2 <- coreToLogic etrue return $ EIte p e2 e1 toPredApp :: C.CoreExpr -> LogicM Pred toPredApp p = do let (f, es) = splitArgs p f' <- tosymbol f go f' es where go f [e1, e2] | Just rel <- M.lookup (val f) brels = PAtom rel <$> (coreToLogic e1) <*> (coreToLogic e2) go f [e] | val f == symbol ("not" :: String) = PNot <$> coreToPred e go f [e1, e2] | val f == symbol ("||" :: String) = POr <$> mapM coreToPred [e1, e2] | val f == symbol ("&&" :: String) = PAnd <$> mapM coreToPred [e1, e2] | val f == symbol ("==>" :: String) = PImp <$> coreToPred e1 <*> coreToPred e2 go f es | val f == symbol ("or" :: String) = POr <$> mapM coreToPred es | val f == symbol ("and" :: String) = PAnd <$> mapM coreToPred es | otherwise = PBexp <$> toLogicApp p toLogicApp :: C.CoreExpr -> LogicM Expr toLogicApp e = do let (f, es) = splitArgs e args <- mapM coreToLogic es lmap <- symbolMap <$> getState def <- (`EApp` args) <$> tosymbol0 f (\x -> makeApp def lmap x args) <$> tosymbol' f makeApp :: Expr -> LogicMap -> Located Symbol-> [Expr] -> Expr makeApp _ _ f [e] | val f == symbol ("GHC.Num.negate" :: String) = ENeg e | val f == symbol ("GHC.Num.fromInteger" :: String) = e makeApp _ _ f [e1, e2] | Just op <- M.lookup (val f) bops = EBin op e1 e2 makeApp def lmap f es = eAppWithMap lmap f es def eVarWithMap :: Id -> LogicMap -> LogicM Expr eVarWithMap x lmap = do f' <- tosymbol' (C.Var x :: C.CoreExpr) return $ eAppWithMap lmap f' [] (EVar $ symbol x) brels :: M.HashMap Symbol Brel brels = M.fromList [ (symbol ("==" :: String), Eq) , (symbol ("/=" :: String), Ne) , (symbol (">=" :: String), Ge) , (symbol (">" :: String) , Gt) , (symbol ("<=" :: String), Le) , (symbol ("<" :: String) , Lt) ] bops :: M.HashMap Symbol Bop bops = M.fromList [ (numSymbol "+", Plus) , (numSymbol "-", Minus) , (numSymbol "*", Times) , (numSymbol "/", Div) , (numSymbol "%", Mod) ] where numSymbol :: String -> Symbol numSymbol = symbol . (++) "GHC.Num." splitArgs e = (f, reverse es) where (f, es) = go e go (C.App (C.Var i) e) | ignoreVar i = go e go (C.App f (C.Var v)) | isErasable v = go f go (C.App f e) = (f', e:es) where (f', es) = go f go f = (f, []) tosymbol (C.Var c) | isDataConId c = return $ dummyLoc $ symbol c tosymbol (C.Var x) = return $ dummyLoc $ simpleSymbolVar x tosymbol e = throw ("Bad Measure Definition:\n" ++ showPpr e ++ "\t cannot be applied") -- TODO: Remove uniques from our symbols tosymbol0 (C.Var c) | isDataConId c = return $ dummyLoc $ symbol c tosymbol0 (C.Var x) = return $ dummyLoc $ varSymbol x tosymbol0 e = throw ("Bad Measure Definition:\n" ++ showPpr e ++ "\t cannot be applied") tosymbol' (C.Var x) = return $ dummyLoc $ simpleSymbolVar' x tosymbol' e = throw ("Bad Measure Definition:\n" ++ showPpr e ++ "\t cannot be applied") makesub (C.NonRec x e) = (symbol x,) <$> coreToLogic e makesub _ = throw "Cannot make Logical Substitution of Recursive Definitions" ignoreVar i = simpleSymbolVar i `elem` ["I#"] simpleSymbolVar = dropModuleNames . symbol . showPpr . getName simpleSymbolVar' = symbol . showPpr . getName isErasable v = isPrefixOfSym (symbol ("$" :: String)) (simpleSymbolVar v) isDead = isDeadOcc . occInfo . idInfo class Simplify a where simplify :: a -> a inline :: (Id -> Bool) -> a -> a instance Simplify C.CoreExpr where simplify e@(C.Var _) = e simplify e@(C.Lit _) = e simplify (C.App e (C.Type _)) = simplify e simplify (C.App e (C.Var dict)) | isErasable dict = simplify e simplify (C.App (C.Lam x e) _) | isDead x = simplify e simplify (C.App e1 e2) = C.App (simplify e1) (simplify e2) simplify (C.Lam x e) | isTyVar x = simplify e simplify (C.Lam x e) | isErasable x = simplify e simplify (C.Lam x e) = C.Lam x (simplify e) simplify (C.Let (C.NonRec x _) e) | isErasable x = simplify e simplify (C.Let (C.Rec xes) e) | all (isErasable . fst) xes = simplify e simplify (C.Let xes e) = C.Let (simplify xes) (simplify e) simplify (C.Case e x t alts) = C.Case (simplify e) x t (filter (not . isUndefined) (simplify <$> alts)) simplify (C.Cast e _) = simplify e simplify (C.Tick _ e) = simplify e simplify (C.Coercion c) = C.Coercion c simplify (C.Type t) = C.Type t inline p (C.Let (C.NonRec x ex) e) | p x = sub (M.singleton x (inline p ex)) (inline p e) inline p (C.Let xes e) = C.Let (inline p xes) (inline p e) inline p (C.App e1 e2) = C.App (inline p e1) (inline p e2) inline p (C.Lam x e) = C.Lam x (inline p e) inline p (C.Case e x t alts) = C.Case (inline p e) x t (inline p <$> alts) inline p (C.Cast e c) = C.Cast (inline p e) c inline p (C.Tick t e) = C.Tick t (inline p e) inline _ (C.Var x) = C.Var x inline _ (C.Lit l) = C.Lit l inline _ (C.Coercion c) = C.Coercion c inline _ (C.Type t) = C.Type t isUndefined (_, _, e) = isUndefinedExpr e where -- auto generated undefined case: (\_ -> (patError @type "error message")) void isUndefinedExpr (C.App (C.Var x) _) | (show x) `elem` perrors = True isUndefinedExpr (C.Let _ e) = isUndefinedExpr e -- otherwise isUndefinedExpr _ = False perrors = ["Control.Exception.Base.patError"] instance Simplify C.CoreBind where simplify (C.NonRec x e) = C.NonRec x (simplify e) simplify (C.Rec xes) = C.Rec (mapSnd simplify <$> xes ) inline p (C.NonRec x e) = C.NonRec x (inline p e) inline p (C.Rec xes) = C.Rec (mapSnd (inline p) <$> xes) instance Simplify C.CoreAlt where simplify (c, xs, e) = (c, xs, simplify e) inline p (c, xs, e) = (c, xs, inline p e)
spinda/liquidhaskell
src/Language/Haskell/Liquid/Spec/CoreToLogic.hs
bsd-3-clause
13,772
0
15
3,988
5,445
2,744
2,701
296
6
{- let s = "s" createSparkSessionDef $ defaultConf { confRequestedSessionName = Data.Text.pack s } execStateDef (checkDataStamps [HdfsPath (Data.Text.pack "/tmp/")]) -} module Spark.IO.StampSpec where import Test.Hspec -- import Spark.Core.Context -- import Spark.Core.Types -- import Spark.Core.Row -- import Spark.Core.Functions -- import Spark.Core.Column -- import Spark.IO.Inputs -- import Spark.Core.IntegrationUtilities import Spark.Core.SimpleAddSpec(run) spec :: Spec spec = do describe "Read a json file" $ do run "simple read" $ do let x = 1 :: Int x `shouldBe` x
krapsh/kraps-haskell
test-integration/Spark/IO/StampSpec.hs
apache-2.0
600
0
15
100
82
48
34
9
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} -- | Provides functions for manipulating parts. module Music.Score.Part ( -- ** Articulation type functions Part, SetPart, -- ** Accessing parts HasParts(..), HasPart(..), HasPart', HasParts', part', parts', -- * Listing parts allParts, -- * Extracting parts extracted, extractedWithInfo, extractPart, extractParts, extractPartsWithInfo, -- * Manipulating parts -- * Part representation PartT(..), -- Part, -- HasPart(..), -- HasPart', -- PartT(..), -- getParts, (</>), rcat, ) where import Control.Applicative import Control.Comonad import Control.Lens hiding (parts, transform) import Control.Monad.Plus -- import Data.Default import Data.Foldable import Data.Functor.Couple import qualified Data.List as List import qualified Data.List as List import Data.Ord (comparing) import Data.PairMonad import Data.Ratio import Data.Semigroup import Data.Traversable import Data.Typeable import Music.Dynamics.Literal import Music.Pitch.Literal import Music.Score.Ties import Music.Score.Internal.Util (through) import Music.Time import Music.Time.Internal.Transform -- | -- Parts type. -- type family Part (s :: *) :: * -- Part s = a -- | -- Part type. -- type family SetPart (b :: *) (s :: *) :: * -- Part b s = t -- | -- Class of types that provide a single part. -- class (HasParts s t) => HasPart s t where -- | Part type. part :: Lens s t (Part s) (Part t) -- | -- Class of types that provide a part traversal. -- class (Transformable (Part s), Transformable (Part t) -- , SetPart (Part t) s ~ t ) => HasParts s t where -- | Part type. parts :: Traversal s t (Part s) (Part t) type HasPart' a = HasPart a a type HasParts' a = HasParts a a -- | -- Part type. -- part' :: (HasPart s t, s ~ t) => Lens' s (Part s) part' = part -- | -- Part type. -- parts' :: (HasParts s t, s ~ t) => Traversal' s (Part s) parts' = parts type instance Part Bool = Bool type instance SetPart a Bool = a instance (b ~ Part b, Transformable b) => HasPart Bool b where part = ($) instance (b ~ Part b, Transformable b) => HasParts Bool b where parts = ($) type instance Part Ordering = Ordering type instance SetPart a Ordering = a instance (b ~ Part b, Transformable b) => HasPart Ordering b where part = ($) instance (b ~ Part b, Transformable b) => HasParts Ordering b where parts = ($) type instance Part () = () type instance SetPart a () = a instance (b ~ Part b, Transformable b) => HasPart () b where part = ($) instance (b ~ Part b, Transformable b) => HasParts () b where parts = ($) type instance Part Int = Int type instance SetPart a Int = a instance HasPart Int Int where part = ($) instance HasParts Int Int where parts = ($) type instance Part Integer = Integer type instance SetPart a Integer = a instance HasPart Integer Integer where part = ($) instance HasParts Integer Integer where parts = ($) type instance Part Float = Float type instance SetPart a Float = a instance HasPart Float Float where part = ($) instance HasParts Float Float where parts = ($) type instance Part (c,a) = Part a type instance SetPart b (c,a) = (c,SetPart b a) type instance Part [a] = Part a type instance SetPart b [a] = [SetPart b a] type instance Part (Maybe a) = Part a type instance SetPart b (Maybe a) = Maybe (SetPart b a) type instance Part (Either c a) = Part a type instance SetPart b (Either c a) = Either c (SetPart b a) type instance Part (Aligned a) = Part a type instance SetPart b (Aligned a) = Aligned (SetPart b a) instance HasParts a b => HasParts (Aligned a) (Aligned b) where parts = _Wrapped . parts instance HasPart a b => HasPart (c, a) (c, b) where part = _2 . part instance HasParts a b => HasParts (c, a) (c, b) where parts = traverse . parts instance HasParts a b => HasParts [a] [b] where parts = traverse . parts instance HasParts a b => HasParts (Maybe a) (Maybe b) where parts = traverse . parts instance HasParts a b => HasParts (Either c a) (Either c b) where parts = traverse . parts type instance Part (Event a) = Part a type instance SetPart g (Event a) = Event (SetPart g a) instance (HasPart a b) => HasPart (Event a) (Event b) where part = from event . whilstL part instance (HasParts a b) => HasParts (Event a) (Event b) where parts = from event . whilstL parts type instance Part (Note a) = Part a type instance SetPart g (Note a) = Note (SetPart g a) instance (HasPart a b) => HasPart (Note a) (Note b) where part = from note . whilstLD part instance (HasParts a b) => HasParts (Note a) (Note b) where parts = from note . whilstLD parts -- | -- List all the parts -- allParts :: (Ord (Part a), HasParts' a) => a -> [Part a] allParts = List.nub . List.sort . toListOf parts -- | -- List all the parts -- extractPart :: (Eq (Part a), HasPart' a) => Part a -> Score a -> Score a extractPart = extractPartG extractPartG :: (Eq (Part a), MonadPlus f, HasPart' a) => Part a -> f a -> f a extractPartG p x = head $ (\p s -> filterPart (== p) s) <$> [p] <*> return x -- | -- List all the parts -- extractParts :: (Ord (Part a), HasPart' a) => Score a -> [Score a] extractParts = extractPartsG extractPartsG :: ( MonadPlus f, HasParts' (f a), HasPart' a, Part (f a) ~ Part a, Ord (Part a) ) => f a -> [f a] extractPartsG x = (\p s -> filterPart (== p) s) <$> allParts x <*> return x filterPart :: (MonadPlus f, HasPart a a) => (Part a -> Bool) -> f a -> f a filterPart p = mfilter (\x -> p (x ^. part)) extractPartsWithInfo :: (Ord (Part a), HasPart' a) => Score a -> [(Part a, Score a)] extractPartsWithInfo x = zip (allParts x) (extractParts x) extracted :: (Ord (Part a), HasPart' a{-, HasPart a b-}) => Iso (Score a) (Score b) [Score a] [Score b] extracted = iso extractParts mconcat extractedWithInfo :: (Ord (Part a), Ord (Part b), HasPart' a, HasPart' b) => Iso (Score a) (Score b) [(Part a, Score a)] [(Part b, Score b)] extractedWithInfo = iso extractPartsWithInfo $ mconcat . fmap (uncurry $ set parts') newtype PartT n a = PartT { getPartT :: (n, a) } deriving (Eq, Ord, Show, Typeable, Functor, Applicative, Comonad, Monad, Transformable) instance Wrapped (PartT p a) where type Unwrapped (PartT p a) = (p, a) _Wrapped' = iso getPartT PartT instance Rewrapped (PartT p a) (PartT p' b) type instance Part (PartT p a) = p type instance SetPart p' (PartT p a) = PartT p' a instance (Transformable p, Transformable p') => HasPart (PartT p a) (PartT p' a) where part = _Wrapped . _1 instance (Transformable p, Transformable p') => HasParts (PartT p a) (PartT p' a) where parts = _Wrapped . _1 instance (IsPitch a, Enum n) => IsPitch (PartT n a) where fromPitch l = PartT (toEnum 0, fromPitch l) instance (IsDynamics a, Enum n) => IsDynamics (PartT n a) where fromDynamics l = PartT (toEnum 0, fromDynamics l) instance Reversible a => Reversible (PartT p a) where rev = fmap rev instance Tiable a => Tiable (PartT n a) where isTieEndBeginning (PartT (_,a)) = isTieEndBeginning a toTied (PartT (v,a)) = (PartT (v,b), PartT (v,c)) where (b,c) = toTied a type instance Part (Behavior a) = Behavior (Part a) type instance SetPart (Behavior g) (Behavior a) = Behavior (SetPart g a) instance (HasPart a a, HasPart a b) => HasParts (Behavior a) (Behavior b) where parts = through part part instance (HasPart a a, HasPart a b) => HasPart (Behavior a) (Behavior b) where part = through part part type instance Part (Score a) = Part a type instance SetPart g (Score a) = Score (SetPart g a) instance (HasParts a b) => HasParts (Score a) (Score b) where parts = _Wrapped . _2 -- into NScore . _Wrapped . traverse . from event -- this needed? . whilstL parts type instance Part (Voice a) = Part a type instance SetPart g (Voice a) = Voice (SetPart g a) instance (HasParts a b) => HasParts (Voice a) (Voice b) where parts = _Wrapped . traverse . _Wrapped -- this needed? . whilstLD parts infixr 6 </> -- | -- Concatenate parts. -- rcat :: (HasParts' a, Enum (Part a)) => [Score a] -> Score a rcat = List.foldr (</>) mempty -- | -- Similar to '<>', but increases parts in the second part to prevent collision. -- (</>) :: (HasParts' a, Enum (Part a)) => Score a -> Score a -> Score a a </> b = a <> moveParts offset b where -- max voice in a + 1 offset = succ $ maximum' 0 $ fmap fromEnum $ toListOf parts a -- | -- Move down one voice (all parts). -- moveParts :: (Integral b, HasParts' a, Enum (Part a)) => b -> Score a -> Score a moveParts x = parts %~ (successor x) -- | -- Move top-part to the specific voice (other parts follow). -- moveToPart :: (Enum b, HasParts' a, Enum (Part a)) => b -> Score a -> Score a moveToPart v = moveParts (fromEnum v) iterating :: (a -> a) -> (a -> a) -> Int -> a -> a iterating f g n | n < 0 = f . iterating f g (n + 1) | n == 0 = id | n > 0 = g . iterating f g (n - 1) successor :: (Integral b, Enum a) => b -> a -> a successor n = iterating pred succ (fromIntegral n) maximum' :: (Ord a, Foldable t) => a -> t a -> a maximum' z = option z getMax . foldMap (Option . Just . Max)
music-suite/music-score
src/Music/Score/Part.hs
bsd-3-clause
9,902
0
11
2,666
3,867
2,080
1,787
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE ViewPatterns #-} -- | Functionality for downloading packages securely for cabal's usage. module Stack.Fetch ( unpackPackages , unpackPackageIdents , fetchPackages , untar , resolvePackages , resolvePackagesAllowMissing , ResolvedPackage (..) , withCabalFiles , withCabalLoader ) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Check as Tar import qualified Codec.Archive.Tar.Entry as Tar import Codec.Compression.GZip (decompress) import Control.Applicative import Control.Concurrent.Async (Concurrently (..)) import Control.Concurrent.MVar.Lifted (modifyMVar, newMVar) import Control.Concurrent.STM import Control.Exception (assert) import Control.Exception.Safe (tryIO) import Control.Monad (join, liftM, unless, void, when) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (ask, runReaderT) import Control.Monad.Trans.Control import Control.Monad.Trans.Unlift (MonadBaseUnlift, askRunBase) import "cryptohash" Crypto.Hash (SHA256 (..)) import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Either (partitionEithers) import qualified Data.Foldable as F import Data.Function (fix) import qualified Data.Git as Git import qualified Data.Git.Ref as Git import qualified Data.Git.Storage as Git import qualified Data.Git.Storage.Object as Git import qualified Data.HashMap.Strict as HashMap import Data.List (intercalate) import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NE import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (maybeToList, catMaybes) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.String (fromString) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import Data.Text.Metrics import Data.Typeable (Typeable) import Data.Word (Word64) import Network.HTTP.Download import Path import Path.Extra (toFilePathNoTrailingSep) import Path.IO import Prelude -- Fix AMP warning import Stack.GhcPkg import Stack.PackageIndex import Stack.Types.BuildPlan import Stack.Types.Config import Stack.Types.PackageIdentifier import Stack.Types.PackageIndex import Stack.Types.PackageName import Stack.Types.Version import System.FilePath ((<.>)) import qualified System.FilePath as FP import System.IO import System.PosixCompat (setFileMode) type PackageCaches = Map PackageIdentifier (PackageIndex, PackageCache) data FetchException = Couldn'tReadIndexTarball FilePath Tar.FormatError | Couldn'tReadPackageTarball FilePath SomeException | UnpackDirectoryAlreadyExists (Set FilePath) | CouldNotParsePackageSelectors [String] | UnknownPackageNames (Set PackageName) | UnknownPackageIdentifiers (Set PackageIdentifier) String deriving Typeable instance Exception FetchException instance Show FetchException where show (Couldn'tReadIndexTarball fp err) = concat [ "There was an error reading the index tarball " , fp , ": " , show err ] show (Couldn'tReadPackageTarball fp err) = concat [ "There was an error reading the package tarball " , fp , ": " , show err ] show (UnpackDirectoryAlreadyExists dirs) = unlines $ "Unable to unpack due to already present directories:" : map (" " ++) (Set.toList dirs) show (CouldNotParsePackageSelectors strs) = "The following package selectors are not valid package names or identifiers: " ++ intercalate ", " strs show (UnknownPackageNames names) = "The following packages were not found in your indices: " ++ intercalate ", " (map packageNameString $ Set.toList names) show (UnknownPackageIdentifiers idents suggestions) = "The following package identifiers were not found in your indices: " ++ intercalate ", " (map packageIdentifierString $ Set.toList idents) ++ (if null suggestions then "" else "\n" ++ suggestions) -- | Fetch packages into the cache without unpacking fetchPackages :: (StackMiniM env m, HasConfig env) => EnvOverride -> Set PackageIdentifier -> m () fetchPackages menv idents' = do resolved <- resolvePackages menv Nothing idents Set.empty ToFetchResult toFetch alreadyUnpacked <- getToFetch Nothing resolved assert (Map.null alreadyUnpacked) (return ()) nowUnpacked <- fetchPackages' Nothing toFetch assert (Map.null nowUnpacked) (return ()) where -- Since we're just fetching tarballs and not unpacking cabal files, we can -- always provide a Nothing Git SHA idents = Map.fromList $ map (, Nothing) $ Set.toList idents' -- | Intended to work for the command line command. unpackPackages :: (StackMiniM env m, HasConfig env) => EnvOverride -> Maybe MiniBuildPlan -- ^ when looking up by name, take from this build plan -> FilePath -- ^ destination -> [String] -- ^ names or identifiers -> m () unpackPackages menv mMiniBuildPlan dest input = do dest' <- resolveDir' dest (names, idents) <- case partitionEithers $ map parse input of ([], x) -> return $ partitionEithers x (errs, _) -> throwM $ CouldNotParsePackageSelectors errs resolved <- resolvePackages menv mMiniBuildPlan (Map.fromList $ map (, Nothing) idents) (Set.fromList names) ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just dest') resolved unless (Map.null alreadyUnpacked) $ throwM $ UnpackDirectoryAlreadyExists $ Set.fromList $ map toFilePath $ Map.elems alreadyUnpacked unpacked <- fetchPackages' Nothing toFetch F.forM_ (Map.toList unpacked) $ \(ident, dest'') -> $logInfo $ T.pack $ concat [ "Unpacked " , packageIdentifierString ident , " to " , toFilePath dest'' ] where -- Possible future enhancement: parse names as name + version range parse s = case parsePackageNameFromString s of Right x -> Right $ Left x Left _ -> case parsePackageIdentifierFromString s of Left _ -> Left s Right x -> Right $ Right x -- | Ensure that all of the given package idents are unpacked into the build -- unpack directory, and return the paths to all of the subdirectories. unpackPackageIdents :: (StackMiniM env m, HasConfig env) => EnvOverride -> Path Abs Dir -- ^ unpack directory -> Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157 -> Map PackageIdentifier (Maybe GitSHA1) -> m (Map PackageIdentifier (Path Abs Dir)) unpackPackageIdents menv unpackDir mdistDir idents = do resolved <- resolvePackages menv Nothing idents Set.empty ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just unpackDir) resolved nowUnpacked <- fetchPackages' mdistDir toFetch return $ alreadyUnpacked <> nowUnpacked data ResolvedPackage = ResolvedPackage { rpIdent :: !PackageIdentifier , rpCache :: !PackageCache , rpIndex :: !PackageIndex , rpGitSHA1 :: !(Maybe GitSHA1) , rpMissingGitSHA :: !Bool } deriving Show -- | Resolve a set of package names and identifiers into @FetchPackage@ values. resolvePackages :: (StackMiniM env m, HasConfig env) => EnvOverride -> Maybe MiniBuildPlan -- ^ when looking up by name, take from this build plan -> Map PackageIdentifier (Maybe GitSHA1) -> Set PackageName -> m [ResolvedPackage] resolvePackages menv mMiniBuildPlan idents0 names0 = do eres <- go case eres of Left _ -> do updateAllIndices menv go >>= either throwM return Right x -> return x where go = r <$> resolvePackagesAllowMissing menv mMiniBuildPlan idents0 names0 r (missingNames, missingIdents, idents) | not $ Set.null missingNames = Left $ UnknownPackageNames missingNames | not $ Set.null missingIdents = Left $ UnknownPackageIdentifiers missingIdents "" | otherwise = Right idents resolvePackagesAllowMissing :: (StackMiniM env m, HasConfig env) => EnvOverride -> Maybe MiniBuildPlan -- ^ when looking up by name, take from this build plan -> Map PackageIdentifier (Maybe GitSHA1) -> Set PackageName -> m (Set PackageName, Set PackageIdentifier, [ResolvedPackage]) resolvePackagesAllowMissing menv mMiniBuildPlan idents0 names0 = do res@(_, _, resolved) <- inner if any rpMissingGitSHA resolved then do $logInfo "Missing some cabal revision files, updating indices" updateAllIndices menv res'@(_, _, resolved') <- inner -- Print an error message if any SHAs are still missing. F.forM_ (filter rpMissingGitSHA resolved') $ \rp -> F.forM_ (rpGitSHA1 rp) $ \(GitSHA1 sha) -> $logWarn $ mconcat [ "Did not find .cabal file for " , T.pack $ packageIdentifierString $ rpIdent rp , " with SHA of " , decodeUtf8 sha , " in tarball-based cache" ] return res' else return res where inner = do (caches, shaCaches) <- getPackageCaches let versions = Map.fromListWith max $ map toTuple $ Map.keys caches getNamed :: PackageName -> Maybe (PackageIdentifier, Maybe GitSHA1) getNamed = case mMiniBuildPlan of Nothing -> getNamedFromIndex Just mbp -> getNamedFromBuildPlan mbp getNamedFromBuildPlan mbp name = do mpi <- Map.lookup name $ mbpPackages mbp Just (PackageIdentifier name (mpiVersion mpi), mpiGitSHA1 mpi) getNamedFromIndex name = fmap (\ver -> (PackageIdentifier name ver, Nothing)) (Map.lookup name versions) (missingNames, idents1) = partitionEithers $ map (\name -> maybe (Left name) Right (getNamed name)) (Set.toList names0) let (missingIdents, resolved) = partitionEithers $ map (goIdent caches shaCaches) $ Map.toList $ idents0 <> Map.fromList idents1 return (Set.fromList missingNames, Set.fromList missingIdents, resolved) goIdent caches shaCaches (ident, mgitsha) = case Map.lookup ident caches of Nothing -> Left ident Just (index, cache) -> let (index', cache', mgitsha', missingGitSHA) = case mgitsha of Nothing -> (index, cache, mgitsha, False) Just gitsha -> case HashMap.lookup gitsha shaCaches of Just (index'', offsetSize) -> ( index'' , cache { pcOffsetSize = offsetSize } -- we already got the info -- about this SHA, don't do -- any lookups later , Nothing , False -- not missing, we found the Git SHA ) Nothing -> (index, cache, mgitsha, case simplifyIndexLocation (indexLocation index) of -- No surprise that there's -- nothing in the cache about -- the SHA, since this package -- comes from a Git -- repo. We'll look it up -- later when we've opened up -- the Git repo itself for -- reading. SILGit _ -> False -- Index using HTTP, so we're missing the Git SHA SILHttp _ _ -> True) in Right ResolvedPackage { rpIdent = ident , rpCache = cache' , rpIndex = index' , rpGitSHA1 = mgitsha' , rpMissingGitSHA = missingGitSHA } data ToFetch = ToFetch { tfTarball :: !(Path Abs File) , tfDestDir :: !(Maybe (Path Abs Dir)) , tfUrl :: !T.Text , tfSize :: !(Maybe Word64) , tfSHA256 :: !(Maybe ByteString) , tfCabal :: !ByteString -- ^ Contents of the .cabal file } data ToFetchResult = ToFetchResult { tfrToFetch :: !(Map PackageIdentifier ToFetch) , tfrAlreadyUnpacked :: !(Map PackageIdentifier (Path Abs Dir)) } -- | Add the cabal files to a list of idents with their caches. withCabalFiles :: (StackMiniM env m, HasConfig env) => IndexName -> [(ResolvedPackage, a)] -> (PackageIdentifier -> a -> ByteString -> IO b) -> m [b] withCabalFiles name pkgs f = do indexPath <- configPackageIndex name mgitRepo <- configPackageIndexRepo name bracket (liftIO $ openBinaryFile (toFilePath indexPath) ReadMode) (liftIO . hClose) $ \h -> let inner mgit = mapM (goPkg h mgit) pkgs in case mgitRepo of Nothing -> inner Nothing Just repo -> bracket (liftIO $ Git.openRepo $ fromString $ toFilePath repo FP.</> ".git") (liftIO . Git.closeRepo) (inner . Just) where goPkg h (Just git) (rp@(ResolvedPackage ident _pc _index (Just (GitSHA1 sha)) _missing), tf) = do let ref = Git.fromHex sha mobj <- liftIO $ tryIO $ Git.getObject git ref True case mobj of Right (Just (Git.ObjBlob (Git.Blob bs))) -> liftIO $ f ident tf (L.toStrict bs) -- fallback when the appropriate SHA isn't found e -> do $logWarn $ mconcat [ "Did not find .cabal file for " , T.pack $ packageIdentifierString ident , " with SHA of " , decodeUtf8 sha , " in the Git repository" ] $logDebug (T.pack (show e)) goPkg h Nothing (rp { rpGitSHA1 = Nothing }, tf) goPkg h _mgit (ResolvedPackage ident pc _index _mgitsha _missing, tf) = do -- Did not find warning for tarballs is handled above let OffsetSize offset size = pcOffsetSize pc liftIO $ do hSeek h AbsoluteSeek $ fromIntegral offset cabalBS <- S.hGet h $ fromIntegral size f ident tf cabalBS -- | Provide a function which will load up a cabal @ByteString@ from the -- package indices. withCabalLoader :: (StackMiniM env m, HasConfig env, MonadBaseUnlift IO m) => EnvOverride -> ((PackageIdentifier -> IO ByteString) -> m a) -> m a withCabalLoader menv inner = do env <- ask -- Want to try updating the index once during a single run for missing -- package identifiers. We also want to ensure we only update once at a -- time -- -- TODO: probably makes sense to move this concern into getPackageCaches updateRef <- liftIO $ newMVar True loadCaches <- getPackageCachesIO runInBase <- liftBaseWith $ \run -> return (void . run) unlift <- askRunBase -- TODO in the future, keep all of the necessary @Handle@s open let doLookup :: PackageIdentifier -> IO ByteString doLookup ident = do (caches, _gitSHACaches) <- loadCaches eres <- unlift $ lookupPackageIdentifierExact ident env caches case eres of Just bs -> return bs -- Update the cache and try again Nothing -> do let fuzzy = fuzzyLookupCandidates ident caches suggestions = case fuzzy of Nothing -> case typoCorrectionCandidates ident caches of Nothing -> "" Just cs -> "Perhaps you meant " <> orSeparated cs <> "?" Just cs -> "Possible candidates: " <> commaSeparated (NE.map packageIdentifierText cs) <> "." join $ modifyMVar updateRef $ \toUpdate -> if toUpdate then do runInBase $ do $logInfo $ T.concat [ "Didn't see " , T.pack $ packageIdentifierString ident , " in your package indices.\n" , "Updating and trying again." ] updateAllIndices menv _ <- getPackageCaches return () return (False, doLookup ident) else return (toUpdate, throwM $ UnknownPackageIdentifiers (Set.singleton ident) (T.unpack suggestions)) inner doLookup lookupPackageIdentifierExact :: (StackMiniM env m, HasConfig env) => PackageIdentifier -> env -> PackageCaches -> m (Maybe ByteString) lookupPackageIdentifierExact ident env caches = case Map.lookup ident caches of Nothing -> return Nothing Just (index, cache) -> do [bs] <- flip runReaderT env $ withCabalFiles (indexName index) [(ResolvedPackage { rpIdent = ident , rpCache = cache , rpIndex = index , rpGitSHA1 = Nothing , rpMissingGitSHA = False }, ())] $ \_ _ bs -> return bs return $ Just bs -- | Given package identifier and package caches, return list of packages -- with the same name and the same two first version number components found -- in the caches. fuzzyLookupCandidates :: PackageIdentifier -> PackageCaches -> Maybe (NonEmpty PackageIdentifier) fuzzyLookupCandidates (PackageIdentifier name ver) caches = let (_, zero, bigger) = Map.splitLookup zeroIdent caches zeroIdent = PackageIdentifier name $(mkVersion "0.0") sameName (PackageIdentifier n _) = n == name sameMajor (PackageIdentifier _ v) = toMajorVersion v == toMajorVersion ver in NE.nonEmpty . filter sameMajor $ maybe [] (pure . const zeroIdent) zero <> takeWhile sameName (Map.keys bigger) -- | Try to come up with typo corrections for given package identifier using -- package caches. This should be called before giving up, i.e. when -- 'fuzzyLookupCandidates' cannot return anything. typoCorrectionCandidates :: PackageIdentifier -> PackageCaches -> Maybe (NonEmpty T.Text) typoCorrectionCandidates ident = let getName = packageNameText . packageIdentifierName name = getName ident in NE.nonEmpty . Map.keys . Map.filterWithKey (const . (== 1) . damerauLevenshtein name) . Map.mapKeys getName -- | Figure out where to fetch from. getToFetch :: (StackMiniM env m, HasConfig env) => Maybe (Path Abs Dir) -- ^ directory to unpack into, @Nothing@ means no unpack -> [ResolvedPackage] -> m ToFetchResult getToFetch mdest resolvedAll = do (toFetch0, unpacked) <- liftM partitionEithers $ mapM checkUnpacked resolvedAll toFetch1 <- mapM goIndex $ Map.toList $ Map.fromListWith (++) toFetch0 return ToFetchResult { tfrToFetch = Map.unions toFetch1 , tfrAlreadyUnpacked = Map.fromList unpacked } where checkUnpacked resolved = do let ident = rpIdent resolved dirRel <- parseRelDir $ packageIdentifierString ident let mdestDir = (</> dirRel) <$> mdest mexists <- case mdestDir of Nothing -> return Nothing Just destDir -> do exists <- doesDirExist destDir return $ if exists then Just destDir else Nothing case mexists of Just destDir -> return $ Right (ident, destDir) Nothing -> do let index = rpIndex resolved d = pcDownload $ rpCache resolved targz = T.pack $ packageIdentifierString ident ++ ".tar.gz" tarball <- configPackageTarball (indexName index) ident return $ Left (indexName index, [(resolved, ToFetch { tfTarball = tarball , tfDestDir = mdestDir , tfUrl = case fmap pdUrl d of Just url | not (S.null url) -> decodeUtf8 url _ -> indexDownloadPrefix index <> targz , tfSize = fmap pdSize d , tfSHA256 = fmap pdSHA256 d , tfCabal = S.empty -- filled in by goIndex })]) goIndex (name, pkgs) = liftM Map.fromList $ withCabalFiles name pkgs $ \ident tf cabalBS -> return (ident, tf { tfCabal = cabalBS }) -- | Download the given name,version pairs into the directory expected by cabal. -- -- For each package it downloads, it will optionally unpack it to the given -- @Path@ (if present). Note that unpacking is not simply a matter of -- untarring, but also of grabbing the cabal file from the package index. The -- destinations should not include package identifiers. -- -- Returns the list of paths unpacked, including package identifiers. E.g.: -- -- @ -- fetchPackages [("foo-1.2.3", Just "/some/dest")] ==> ["/some/dest/foo-1.2.3"] -- @ -- -- Since 0.1.0.0 fetchPackages' :: (StackMiniM env m, HasConfig env) => Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157 -> Map PackageIdentifier ToFetch -> m (Map PackageIdentifier (Path Abs Dir)) fetchPackages' mdistDir toFetchAll = do connCount <- view $ configL.to configConnectionCount outputVar <- liftIO $ newTVarIO Map.empty runInBase <- liftBaseWith $ \run -> return (void . run) parMapM_ connCount (go outputVar runInBase) (Map.toList toFetchAll) liftIO $ readTVarIO outputVar where go :: (MonadIO m,MonadThrow m,MonadLogger m) => TVar (Map PackageIdentifier (Path Abs Dir)) -> (m () -> IO ()) -> (PackageIdentifier, ToFetch) -> m () go outputVar runInBase (ident, toFetch) = do req <- parseUrlThrow $ T.unpack $ tfUrl toFetch let destpath = tfTarball toFetch let toHashCheck bs = HashCheck SHA256 (CheckHexDigestByteString bs) let downloadReq = DownloadRequest { drRequest = req , drHashChecks = map toHashCheck $ maybeToList (tfSHA256 toFetch) , drLengthCheck = fromIntegral <$> tfSize toFetch , drRetryPolicy = drRetryPolicyDefault } let progressSink _ = liftIO $ runInBase $ $logInfo $ packageIdentifierText ident <> ": download" _ <- verifiedDownload downloadReq destpath progressSink identStrP <- parseRelDir $ packageIdentifierString ident F.forM_ (tfDestDir toFetch) $ \destDir -> do let innerDest = toFilePath destDir unexpectedEntries <- liftIO $ untar destpath identStrP (parent destDir) liftIO $ do case mdistDir of Nothing -> return () -- See: https://github.com/fpco/stack/issues/157 Just distDir -> do let inner = parent destDir </> identStrP oldDist = inner </> $(mkRelDir "dist") newDist = inner </> distDir exists <- doesDirExist oldDist when exists $ do -- Previously used takeDirectory, but that got confused -- by trailing slashes, see: -- https://github.com/commercialhaskell/stack/issues/216 -- -- Instead, use Path which is a bit more resilient ensureDir $ parent newDist renameDir oldDist newDist let cabalFP = innerDest FP.</> packageNameString (packageIdentifierName ident) <.> "cabal" S.writeFile cabalFP $ tfCabal toFetch atomically $ modifyTVar outputVar $ Map.insert ident destDir F.forM_ unexpectedEntries $ \(path, entryType) -> $logWarn $ "Unexpected entry type " <> entryType <> " for entry " <> T.pack path -- | Internal function used to unpack tarball. -- -- Takes a path to a .tar.gz file, the name of the directory it should contain, -- and a destination folder to extract the tarball into. Returns unexpected -- entries, as pairs of paths and descriptions. untar :: forall b1 b2. Path b1 File -> Path Rel Dir -> Path b2 Dir -> IO [(FilePath, T.Text)] untar tarPath expectedTarFolder destDirParent = do ensureDir destDirParent withBinaryFile (toFilePath tarPath) ReadMode $ \h -> do -- Avoid using L.readFile, which is more likely to leak -- resources lbs <- L.hGetContents h let rawEntries = fmap (either wrap wrap) $ Tar.checkTarbomb (toFilePathNoTrailingSep expectedTarFolder) $ Tar.read $ decompress lbs filterEntries :: Monoid w => (Tar.Entry -> (Bool, w)) -> Tar.Entries b -> (Tar.Entries b, w) -- Allow collecting warnings, Writer-monad style. filterEntries f = Tar.foldEntries (\e -> let (res, w) = f e in \(rest, wOld) -> ((if res then Tar.Next e else id) rest, wOld <> w)) (Tar.Done, mempty) (\err -> (Tar.Fail err, mempty)) extractableEntry e = case Tar.entryContent e of Tar.NormalFile _ _ -> (True, []) Tar.Directory -> (True, []) Tar.SymbolicLink _ -> (True, []) Tar.HardLink _ -> (True, []) Tar.OtherEntryType 'g' _ _ -> (False, []) Tar.OtherEntryType 'x' _ _ -> (False, []) Tar.CharacterDevice _ _ -> (False, [(path, "character device")]) Tar.BlockDevice _ _ -> (False, [(path, "block device")]) Tar.NamedPipe -> (False, [(path, "named pipe")]) Tar.OtherEntryType code _ _ -> (False, [(path, "other entry type with code " <> T.pack (show code))]) where path = Tar.fromTarPath $ Tar.entryTarPath e (entries, unexpectedEntries) = filterEntries extractableEntry rawEntries wrap :: Exception e => e -> FetchException wrap = Couldn'tReadPackageTarball (toFilePath tarPath) . toException getPerms :: Tar.Entry -> (FilePath, Tar.Permissions) getPerms e = (toFilePath destDirParent FP.</> Tar.fromTarPath (Tar.entryTarPath e), Tar.entryPermissions e) filePerms :: [(FilePath, Tar.Permissions)] filePerms = catMaybes $ Tar.foldEntries (\e -> (:) (Just $ getPerms e)) [] (const []) entries Tar.unpack (toFilePath destDirParent) entries -- Reset file permissions as they were in the tarball, but only -- for extracted entries (whence filterEntries extractableEntry above). -- See https://github.com/commercialhaskell/stack/issues/2361 mapM_ (\(fp, perm) -> setFileMode (FP.dropTrailingPathSeparator fp) perm) filePerms return unexpectedEntries parMapM_ :: (F.Foldable f,MonadIO m,MonadBaseControl IO m) => Int -> (a -> m ()) -> f a -> m () parMapM_ (max 1 -> 1) f xs = F.mapM_ f xs parMapM_ cnt f xs0 = do var <- liftIO (newTVarIO $ F.toList xs0) -- See comment on similar line in Stack.Build runInBase <- liftBaseWith $ \run -> return (void . run) let worker = fix $ \loop -> join $ atomically $ do xs <- readTVar var case xs of [] -> return $ return () x:xs' -> do writeTVar var xs' return $ do runInBase $ f x loop workers 1 = Concurrently worker workers i = Concurrently worker *> workers (i - 1) liftIO $ runConcurrently $ workers cnt orSeparated :: NonEmpty T.Text -> T.Text orSeparated xs | NE.length xs == 1 = NE.head xs | NE.length xs == 2 = NE.head xs <> " or " <> NE.last xs | otherwise = T.intercalate ", " (NE.init xs) <> ", or " <> NE.last xs commaSeparated :: NonEmpty T.Text -> T.Text commaSeparated = F.fold . NE.intersperse ", "
AndreasPK/stack
src/Stack/Fetch.hs
bsd-3-clause
31,472
0
30
11,418
7,012
3,608
3,404
594
11
{-# LANGUAGE OverloadedStrings #-} module Css.Graph (graphStyles) where import Clay import Prelude hiding ((**)) import Data.Monoid import Css.Constants {- graphStyles - Generates all CSS for the graph page. -} graphStyles :: Css graphStyles = do graphContainer sidebarCSS nodeCSS pathCSS resetCSS titleCSS regionCSS {- nodeCSS - Generates CSS for nodes in the graph. -} nodeCSS :: Css nodeCSS = "g" ? do "text" ? do userSelect none "-webkit-touch-callout" -: "none" "-webkit-user-select" -: "none" "-khtml-user-select" -: "none" "-moz-user-select" -: "none" "-ms-user-select" -: "none" ".node" & do cursor pointer "text" ? do fontSize (pt nodeFontSize) faded stroke "none" "text-anchor" -: "middle" -- For nodes in draw tab "data-active" @= "active" & do "rect" <? do wideStroke "text" <? do fullyVisible "data-active" @= "overridden" & do "rect" <? do wideStroke strokeRed "text" <? do fullyVisible "data-active" @= "inactive" & do "rect" <? do faded strokeDashed "data-active" @= "takeable" & do "rect" <? do semiVisible "text" <? do semiVisible "data-active" @= "missing" & do "rect" <> "ellipse" <? do wideStroke strokeRed "text" <? do fullyVisible "data-active" @= "unselected" & do "rect" <? do wideStroke faded "rect" <? do stroke "black" ".hybrid" & do cursor cursorDefault "text" <? do stroke "none" fill "white" fontSize (pt hybridFontSize) "text-anchor" -: "middle" "rect" <? do fill "#888888" stroke "black" ".active" & do "rect" <? do wideStroke "text" <? do fullyVisible ".overridden" & do "rect" <? do wideStroke strokeRed "text" <? do fullyVisible ".inactive" & do "rect" <? do faded strokeDashed ".takeable" & do "rect" <? do semiVisible "text" <? do semiVisible ".missing" & do "rect" <> "ellipse" <? do wideStroke strokeRed "text" <? do fullyVisible ".bool" & do cursor cursorDefault "data-active" @= "active" & do "ellipse" <? do fill "none" stroke "black" "data-active" @= "overridden" & do "ellipse" <? do fill "white" strokeRed "data-active" @= "inactive" & do "ellipse" <? do fill lightGrey faded strokeDashed stroke "black" "data-active" @= "takeable" & do "ellipse" <? do fill lightGrey stroke "black" "data-active" @= "missing" & do "ellipse" <? do fill "white" strokeRed -- For the React graph ".active" & do "ellipse" <? do fill "none" stroke "black" ".overridden" & do "ellipse" <? do fill "white" strokeRed ".inactive" & do "ellipse" <? do fill lightGrey faded strokeDashed stroke "black" ".takeable" & do "ellipse" <? do fill lightGrey stroke "black" ".missing" & do "ellipse" <? do fill "white" strokeRed "text" <? do fontFamily ["Trebuchet MS", "Arial"] [sansSerif] fontWeight bold stroke "none" fontSize (pt boolFontSize) "text-anchor" -: "middle" {- pathCSS - Generates CSS for paths between nodes - in the graph. -} pathCSS :: Css pathCSS = "path" ? do fill "none" "data-active" @= "drawn" & do faded wideStroke -- For the React graph ".takeable" & do strokeDashed stroke "black" ".inactive" & do faded strokeDashed stroke "black" ".active" & do opacity 1 "stroke-width" -: "2px" stroke "black" ".missing" & do strokeRed strokeDashed {- resetCSS - Generates CSS for the reset feature - in the graph. -} resetCSS :: Css resetCSS = "#resetButton" ? do fill "#990000" cursor pointer wideStroke "stroke" -: "#404040" "text" <? do fill "white" {- graphContainer - Generates CSS for the main division of - the page containing the graph. -} graphContainer :: Css graphContainer = do "#react-graph" ? do "width" -: "calc(100% - 40px)" height100 overflow hidden margin0 display inlineBlock position absolute textAlign $ alignSide sideCenter left (px 40) "#react-graphRootSVG" ? do width100 height100 stroke "black" "stroke-linecap" -: "square" "stroke-miterlimit" -: "10" "shape-rendering" -: "geometricPrecision" ".highlight-nodes" ? do backgroundColor grey ".graph-control-button" ? do textAlign $ alignSide sideCenter backgroundColor white border solid (px 1) purple10 "border-radius" -: "6px" "outline" -: "none" fontSize (px 14) fontWeight bold fontColor purple10 cursor pointer display inlineBlock width (px 25) height (px 25) position absolute ":hover" & do backgroundColor purple6 fontColor white ":active" & do backgroundColor purple10 fontColor white ":disabled" & do border solid (px 1) grey6 backgroundColor grey2 fontColor grey6 "#zoom-in-button" ? do top (px 85) right (px 30) "#zoom-out-button" ? do top (px 85) right (px 57) "#pan-up-button" ? do top (px 4) right (px 43) "#pan-down-button" ? do top (px 57) right (px 43) "#pan-right-button" ? do top (px 30) right (px 30) "#pan-left-button" ? do top (px 30) right (px 57) "#reset-button" ? do width (px 52) top (px 111) right (px 30) sidebarCSS :: Css sidebarCSS = do "#fce" ? do height (px 40) width (pct 100) border solid (px 1) black "#fcecount" ? do width (pct 53) height (px 40) float floatLeft backgroundColor purple7 display none textAlign $ alignSide sideCenter paddingLeft (px 15) paddingTop (px 5) fontSize (px 18) "#reset" ? do textAlign $ alignSide sideCenter float floatLeft width (pct 47) height (px 40) display none border solid (px 1) black cursor pointer ":hover" & do backgroundColor grey1 fontColor white "#container" ? do "height" -: "calc(100% - 100px)" width100 position relative "#sidebar" ? do display inlineBlock width (px 40) height100 float floatLeft backgroundColor purple8 position absolute paddingLeft (px 23) "#sidebar-button" ? do cursor pointer display inlineBlock width (px 40) height100 float floatLeft backgroundColor purple10 position absolute border solid (px 1) black ":hover" & do backgroundColor purple6 "#sidebar-icon" ? do width (px 30) height (px 50) paddingTop (px 20) paddingLeft (px 2) position absolute top (pct 40) left (px 4) "#focuses-nav, #graph-nav" ? do cursor pointer "#sidebar-nav" ? do width100 fontSize (px 13) backgroundColor purple6 border solid (px 1) grey2 "box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)" display block overflow hidden ul ? do width100 margin0 li ? do "list-style-type" -: "none" display inlineBlock width (pct 48) "-webkit-transition" -: "all 0.2s" "-moz-transition" -: "all 0.2s" "-ms-transition" -: "all 0.2s" "-o-transition" -: "all 0.2s" "transition" -: "all 0.2s" ":hover" & do "background-color" -: "#5C497E !important" a ? do "color" -: "white !important" a ? do color black display inlineBlock lineHeight (px 30) alignCenter width (pct 95) textDecoration none "#focuses, #graphs" ? do marginTop (px 25) marginLeft (px 25) height (pct 86) display none overflowY scroll ".focus" ? do display block cursor pointer fontSize (px 20) border solid (px 1) black alignCenter width (pct 90) backgroundColor white "border-radius" -: "6px" ":hover" & do backgroundColor grey2 "#close-focus" ? do display block cursor pointer backgroundColor purple6 fontSize (px 20) border solid (px 1) black textAlign $ alignSide sideCenter width (pct 90) ".spotlight" & do fill "white" stroke "none" ".details" & do border solid (px 1) black width (pct 90) height (px 0) marginBottom (px 7) overflow auto fontSize (px 14) fontColor white paddingLeft (px 5) paddingRight (px 5) ".active" & do backgroundColor purple8 ".disabled" & do backgroundColor grey2 pointerEvents none ".graph-button" & do display block cursor pointer fontSize (px 20) border solid (px 1) black "border-radius" -: "6px" textAlign $ alignSide sideCenter width (pct 90) backgroundColor white marginBottom (px 20) ":hover" & do backgroundColor grey2 ".flip" & do transform $ scaleX (-1) {- titleCSS - Generates CSS for the title. -} titleCSS :: Css titleCSS = "#svgTitle" ? do fontSize $ em 2.5 fontWeight bold fontFamily ["Bitter"] [serif] fontStyle italic fill titleColour {- regionCSS - Generates CSS for focus regions in the graph. -} regionCSS :: Css regionCSS = do ".region-label" ? do fontSize (pt regionFontSize) ".region" ? do "fill-opacity" -: "0.25"
bell-kelly/courseography
app/Css/Graph.hs
gpl-3.0
11,406
0
22
4,794
2,975
1,225
1,750
407
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.IAM.ListUserPolicies -- 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. -- | Lists the names of the inline policies embedded in the specified user. -- -- A user can also have managed policies attached to it. To list the managed -- policies that are attached to a user, use 'ListAttachedUserPolicies'. For more -- information about policies, refer to <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> in -- the /Using IAM/ guide. -- -- You can paginate the results using the 'MaxItems' and 'Marker' parameters. If -- there are no inline policies embedded with the specified user, the action -- returns an empty list. -- -- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUserPolicies.html> module Network.AWS.IAM.ListUserPolicies ( -- * Request ListUserPolicies -- ** Request constructor , listUserPolicies -- ** Request lenses , lupMarker , lupMaxItems , lupUserName -- * Response , ListUserPoliciesResponse -- ** Response constructor , listUserPoliciesResponse -- ** Response lenses , luprIsTruncated , luprMarker , luprPolicyNames ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.IAM.Types import qualified GHC.Exts data ListUserPolicies = ListUserPolicies { _lupMarker :: Maybe Text , _lupMaxItems :: Maybe Nat , _lupUserName :: Text } deriving (Eq, Ord, Read, Show) -- | 'ListUserPolicies' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lupMarker' @::@ 'Maybe' 'Text' -- -- * 'lupMaxItems' @::@ 'Maybe' 'Natural' -- -- * 'lupUserName' @::@ 'Text' -- listUserPolicies :: Text -- ^ 'lupUserName' -> ListUserPolicies listUserPolicies p1 = ListUserPolicies { _lupUserName = p1 , _lupMarker = Nothing , _lupMaxItems = Nothing } -- | Use this only when paginating results, and only in a subsequent request -- after you've received a response where the results are truncated. Set it to -- the value of the 'Marker' element in the response you just received. lupMarker :: Lens' ListUserPolicies (Maybe Text) lupMarker = lens _lupMarker (\s a -> s { _lupMarker = a }) -- | Use this only when paginating results to indicate the maximum number of -- policy names you want in the response. If there are additional policy names -- beyond the maximum you specify, the 'IsTruncated' response element is 'true'. -- This parameter is optional. If you do not include it, it defaults to 100. lupMaxItems :: Lens' ListUserPolicies (Maybe Natural) lupMaxItems = lens _lupMaxItems (\s a -> s { _lupMaxItems = a }) . mapping _Nat -- | The name of the user to list policies for. lupUserName :: Lens' ListUserPolicies Text lupUserName = lens _lupUserName (\s a -> s { _lupUserName = a }) data ListUserPoliciesResponse = ListUserPoliciesResponse { _luprIsTruncated :: Maybe Bool , _luprMarker :: Maybe Text , _luprPolicyNames :: List "member" Text } deriving (Eq, Ord, Read, Show) -- | 'ListUserPoliciesResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'luprIsTruncated' @::@ 'Maybe' 'Bool' -- -- * 'luprMarker' @::@ 'Maybe' 'Text' -- -- * 'luprPolicyNames' @::@ ['Text'] -- listUserPoliciesResponse :: ListUserPoliciesResponse listUserPoliciesResponse = ListUserPoliciesResponse { _luprPolicyNames = mempty , _luprIsTruncated = Nothing , _luprMarker = Nothing } -- | A flag that indicates whether there are more policy names to list. If your -- results were truncated, you can make a subsequent pagination request using -- the 'Marker' request parameter to retrieve more policy names in the list. luprIsTruncated :: Lens' ListUserPoliciesResponse (Maybe Bool) luprIsTruncated = lens _luprIsTruncated (\s a -> s { _luprIsTruncated = a }) -- | If 'IsTruncated' is 'true', this element is present and contains the value to -- use for the 'Marker' parameter in a subsequent pagination request. luprMarker :: Lens' ListUserPoliciesResponse (Maybe Text) luprMarker = lens _luprMarker (\s a -> s { _luprMarker = a }) -- | A list of policy names. luprPolicyNames :: Lens' ListUserPoliciesResponse [Text] luprPolicyNames = lens _luprPolicyNames (\s a -> s { _luprPolicyNames = a }) . _List instance ToPath ListUserPolicies where toPath = const "/" instance ToQuery ListUserPolicies where toQuery ListUserPolicies{..} = mconcat [ "Marker" =? _lupMarker , "MaxItems" =? _lupMaxItems , "UserName" =? _lupUserName ] instance ToHeaders ListUserPolicies instance AWSRequest ListUserPolicies where type Sv ListUserPolicies = IAM type Rs ListUserPolicies = ListUserPoliciesResponse request = post "ListUserPolicies" response = xmlResponse instance FromXML ListUserPoliciesResponse where parseXML = withElement "ListUserPoliciesResult" $ \x -> ListUserPoliciesResponse <$> x .@? "IsTruncated" <*> x .@? "Marker" <*> x .@? "PolicyNames" .!@ mempty instance AWSPager ListUserPolicies where page rq rs | stop (rs ^. luprIsTruncated) = Nothing | otherwise = Just $ rq & lupMarker .~ rs ^. luprMarker
romanb/amazonka
amazonka-iam/gen/Network/AWS/IAM/ListUserPolicies.hs
mpl-2.0
6,224
0
14
1,308
802
476
326
82
1
{-# LANGUAGE CPP, QuasiQuotes, TemplateHaskell, TypeFamilies #-} module Settings.StaticFiles where import Yesod.Static import qualified Yesod.Static as Static static :: FilePath -> IO Static #ifdef PRODUCTION static = Static.static #else static = Static.staticDevel #endif -- | This generates easy references to files in the static directory at compile time. -- The upside to this is that you have compile-time verification that referenced files -- exist. However, any files added to your static directory during run-time can't be -- accessed this way. You'll have to use their FilePath or URL to access them. $(staticFiles "static")
samstokes/yesodoro
Settings/StaticFiles.hs
bsd-2-clause
644
0
7
103
56
35
21
7
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} module T15437A where import Language.Haskell.TH.Syntax (Q, TExp) get :: forall a. Int get = 1 foo :: forall a. Q (TExp Int) foo = [|| get @a ||]
sdiehl/ghc
testsuite/tests/th/T15437A.hs
bsd-3-clause
252
2
9
43
72
45
27
-1
-1
{- Copyright 2016 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} import Distribution.Simple main = defaultMain
nomeata/codeworld
codeworld-server/Setup.hs
apache-2.0
657
0
4
121
12
7
5
2
1
{-# LANGUAGE QuasiQuotes #-} module Lib where import QQ val = [myq|hello|]
themoritz/cabal
cabal-testsuite/PackageTests/QuasiQuotes/vanilla/Lib.hs
bsd-3-clause
77
0
4
14
17
13
4
4
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TupleSections #-} -- | Code generation for server executables. module Futhark.CodeGen.Backends.GenericC.Server ( serverDefs, ) where import Data.Bifunctor (first, second) import qualified Data.Map as M import qualified Data.Text as T import Futhark.CodeGen.Backends.GenericC.Manifest import Futhark.CodeGen.Backends.GenericC.Options import Futhark.CodeGen.Backends.SimpleRep import Futhark.CodeGen.RTS.C (serverH, tuningH, valuesH) import Futhark.Util (zEncodeString) import Futhark.Util.Pretty (prettyText) import qualified Language.C.Quote.OpenCL as C import qualified Language.C.Syntax as C genericOptions :: [Option] genericOptions = [ Option { optionLongName = "debugging", optionShortName = Just 'D', optionArgument = NoArgument, optionDescription = "Perform possibly expensive internal correctness checks and verbose logging.", optionAction = [C.cstm|futhark_context_config_set_debugging(cfg, 1);|] }, Option { optionLongName = "log", optionShortName = Just 'L', optionArgument = NoArgument, optionDescription = "Print various low-overhead logging information while running.", optionAction = [C.cstm|futhark_context_config_set_logging(cfg, 1);|] }, Option { optionLongName = "help", optionShortName = Just 'h', optionArgument = NoArgument, optionDescription = "Print help information and exit.", optionAction = [C.cstm|{ printf("Usage: %s [OPTIONS]...\nOptions:\n\n%s\nFor more information, consult the Futhark User's Guide or the man pages.\n", fut_progname, option_descriptions); exit(0); }|] }, Option { optionLongName = "print-params", optionShortName = Nothing, optionArgument = NoArgument, optionDescription = "Print all tuning parameters that can be set with --param or --tuning.", optionAction = [C.cstm|{ int n = futhark_get_tuning_param_count(); for (int i = 0; i < n; i++) { printf("%s (%s)\n", futhark_get_tuning_param_name(i), futhark_get_tuning_param_class(i)); } exit(0); }|] }, Option { optionLongName = "param", optionShortName = Nothing, optionArgument = RequiredArgument "ASSIGNMENT", optionDescription = "Set a tuning parameter to the given value.", optionAction = [C.cstm|{ char *name = optarg; char *equals = strstr(optarg, "="); char *value_str = equals != NULL ? equals+1 : optarg; int value = atoi(value_str); if (equals != NULL) { *equals = 0; if (futhark_context_config_set_tuning_param(cfg, name, value) != 0) { futhark_panic(1, "Unknown size: %s\n", name); } } else { futhark_panic(1, "Invalid argument for size option: %s\n", optarg); }}|] }, Option { optionLongName = "tuning", optionShortName = Nothing, optionArgument = RequiredArgument "FILE", optionDescription = "Read size=value assignments from the given file.", optionAction = [C.cstm|{ char *ret = load_tuning_file(optarg, cfg, (int(*)(void*, const char*, size_t)) futhark_context_config_set_tuning_param); if (ret != NULL) { futhark_panic(1, "When loading tuning from '%s': %s\n", optarg, ret); }}|] } ] typeStructName :: T.Text -> String typeStructName tname = "type_" <> zEncodeString (T.unpack tname) typeBoilerplate :: (T.Text, Type) -> (C.Initializer, [C.Definition]) typeBoilerplate (tname, TypeArray _ et rank ops) = let type_name = typeStructName tname aux_name = type_name ++ "_aux" info_name = T.unpack et ++ "_info" shape_args = [[C.cexp|shape[$int:i]|] | i <- [0 .. rank -1]] array_new_wrap = arrayNew ops <> "_wrap" in ( [C.cinit|&$id:type_name|], [C.cunit| void* $id:array_new_wrap(struct futhark_context *ctx, const void* p, const typename int64_t* shape) { return $id:(arrayNew ops)(ctx, p, $args:shape_args); } struct array_aux $id:aux_name = { .name = $string:(T.unpack tname), .rank = $int:rank, .info = &$id:info_name, .new = (typename array_new_fn)$id:array_new_wrap, .free = (typename array_free_fn)$id:(arrayFree ops), .shape = (typename array_shape_fn)$id:(arrayShape ops), .values = (typename array_values_fn)$id:(arrayValues ops) }; struct type $id:type_name = { .name = $string:(T.unpack tname), .restore = (typename restore_fn)restore_array, .store = (typename store_fn)store_array, .free = (typename free_fn)free_array, .aux = &$id:aux_name };|] ) typeBoilerplate (tname, TypeOpaque _ ops) = let type_name = typeStructName tname aux_name = type_name ++ "_aux" in ( [C.cinit|&$id:type_name|], [C.cunit| struct opaque_aux $id:aux_name = { .store = (typename opaque_store_fn)$id:(opaqueStore ops), .restore = (typename opaque_restore_fn)$id:(opaqueRestore ops), .free = (typename opaque_free_fn)$id:(opaqueFree ops) }; struct type $id:type_name = { .name = $string:(T.unpack tname), .restore = (typename restore_fn)restore_opaque, .store = (typename store_fn)store_opaque, .free = (typename free_fn)free_opaque, .aux = &$id:aux_name };|] ) entryTypeBoilerplate :: Manifest -> ([C.Initializer], [C.Definition]) entryTypeBoilerplate = second concat . unzip . map typeBoilerplate . M.toList . manifestTypes oneEntryBoilerplate :: Manifest -> (T.Text, EntryPoint) -> ([C.Definition], C.Initializer) oneEntryBoilerplate manifest (name, EntryPoint cfun outputs inputs) = let call_f = "call_" ++ T.unpack name out_types = map outputType outputs in_types = map inputType inputs out_types_name = T.unpack name ++ "_out_types" in_types_name = T.unpack name ++ "_in_types" out_unique_name = T.unpack name ++ "_out_unique" in_unique_name = T.unpack name ++ "_in_unique" (out_items, out_args) | null out_types = ([C.citems|(void)outs;|], mempty) | otherwise = unzip $ zipWith loadOut [0 ..] out_types (in_items, in_args) | null in_types = ([C.citems|(void)ins;|], mempty) | otherwise = unzip $ zipWith loadIn [0 ..] in_types in ( [C.cunit| struct type* $id:out_types_name[] = { $inits:(map typeStructInit out_types), NULL }; bool $id:out_unique_name[] = { $inits:(map outputUniqueInit outputs) }; struct type* $id:in_types_name[] = { $inits:(map typeStructInit in_types), NULL }; bool $id:in_unique_name[] = { $inits:(map inputUniqueInit inputs) }; int $id:call_f(struct futhark_context *ctx, void **outs, void **ins) { $items:out_items $items:in_items return $id:cfun(ctx, $args:out_args, $args:in_args); } |], [C.cinit|{ .name = $string:(T.unpack name), .f = $id:call_f, .in_types = $id:in_types_name, .out_types = $id:out_types_name, .in_unique = $id:in_unique_name, .out_unique = $id:out_unique_name }|] ) where typeStructInit tname = [C.cinit|&$id:(typeStructName tname)|] inputUniqueInit = uniqueInit . inputUnique outputUniqueInit = uniqueInit . outputUnique uniqueInit True = [C.cinit|true|] uniqueInit False = [C.cinit|false|] cType tname = case M.lookup tname $ manifestTypes manifest of Just (TypeArray ctype _ _ _) -> [C.cty|typename $id:(T.unpack ctype)|] Just (TypeOpaque ctype _) -> [C.cty|typename $id:(T.unpack ctype)|] Nothing -> uncurry primAPIType $ scalarToPrim tname loadOut i tname = let v = "out" ++ show (i :: Int) in ( [C.citem|$ty:(cType tname) *$id:v = outs[$int:i];|], [C.cexp|$id:v|] ) loadIn i tname = let v = "in" ++ show (i :: Int) in ( [C.citem|$ty:(cType tname) $id:v = *($ty:(cType tname)*)ins[$int:i];|], [C.cexp|$id:v|] ) entryBoilerplate :: Manifest -> ([C.Definition], [C.Initializer]) entryBoilerplate manifest = first concat $ unzip $ map (oneEntryBoilerplate manifest) $ M.toList $ manifestEntryPoints manifest mkBoilerplate :: Manifest -> ([C.Definition], [C.Initializer], [C.Initializer]) mkBoilerplate manifest = let (type_inits, type_defs) = entryTypeBoilerplate manifest (entry_defs, entry_inits) = entryBoilerplate manifest scalar_type_inits = map scalarTypeInit scalar_types in (type_defs ++ entry_defs, scalar_type_inits ++ type_inits, entry_inits) where scalarTypeInit tname = [C.cinit|&$id:(typeStructName tname)|] scalar_types = [ "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f16", "f32", "f64", "bool" ] {-# NOINLINE serverDefs #-} -- | Generate Futhark server executable code. serverDefs :: [Option] -> Manifest -> T.Text serverDefs options manifest = let option_parser = generateOptionParser "parse_options" $ genericOptions ++ options (boilerplate_defs, type_inits, entry_point_inits) = mkBoilerplate manifest in prettyText [C.cunit| $esc:("#include <getopt.h>") $esc:("#include <ctype.h>") $esc:("#include <inttypes.h>") // If the entry point is NULL, the program will terminate after doing initialisation and such. It is not used for anything else in server mode. static const char *entry_point = "main"; $esc:(T.unpack valuesH) $esc:(T.unpack serverH) $esc:(T.unpack tuningH) $edecls:boilerplate_defs struct type* types[] = { $inits:type_inits, NULL }; struct entry_point entry_points[] = { $inits:entry_point_inits, { .name = NULL } }; struct futhark_prog prog = { .types = types, .entry_points = entry_points }; $func:option_parser int main(int argc, char** argv) { fut_progname = argv[0]; struct futhark_context_config *cfg = futhark_context_config_new(); assert(cfg != NULL); int parsed_options = parse_options(cfg, argc, argv); argc -= parsed_options; argv += parsed_options; if (argc != 0) { futhark_panic(1, "Excess non-option: %s\n", argv[0]); } struct futhark_context *ctx = futhark_context_new(cfg); assert (ctx != NULL); futhark_context_set_logging_file(ctx, stdout); char* error = futhark_context_get_error(ctx); if (error != NULL) { futhark_panic(1, "Error during context initialisation:\n%s", error); } if (entry_point != NULL) { run_server(&prog, cfg, ctx); } futhark_context_free(ctx); futhark_context_config_free(cfg); } |]
HIPERFIT/futhark
src/Futhark/CodeGen/Backends/GenericC/Server.hs
isc
11,971
0
13
3,578
1,554
918
636
153
4
{-# LANGUAGE RankNTypes #-} module Rx.Scheduler.SingleThread where import Control.Monad (join, forever) import Control.Concurrent (ThreadId, forkIO, forkOS, killThread, threadDelay, yield) import Control.Concurrent.STM (atomically) import qualified Control.Concurrent.STM.TChan as TChan import Tiempo (toMicroSeconds) import Rx.Disposable ( Disposable, IDisposable(..), ToDisposable(..) , newDisposable, emptyDisposable) import Rx.Scheduler.Types -------------------------------------------------------------------------------- -- ^ A special Scheduler that works on a single thread, this type -- implements both the IScheduler and the IDisposable classtypes. data SingleThreadScheduler s = SingleThreadScheduler { _scheduler :: Scheduler s , _disposable :: Disposable } type Forker = IO () -> IO ThreadId instance IScheduler SingleThreadScheduler where immediateSchedule = immediateSchedule . _scheduler timedSchedule = timedSchedule . _scheduler instance IDisposable (SingleThreadScheduler s) where disposeVerbose = disposeVerbose . _disposable instance ToDisposable (SingleThreadScheduler s) where toDisposable = _disposable -------------------------------------------------------------------------------- _singleThread :: Forker -> IO (SingleThreadScheduler Async) _singleThread fork = do reqChan <- TChan.newTChanIO tid <- fork $ forever $ do join $ atomically $ TChan.readTChan reqChan yield disposable <- newDisposable "Scheduler.singleThread" (killThread tid) let scheduler = Scheduler { _immediateSchedule = \action -> do atomically (TChan.writeTChan reqChan action) emptyDisposable , _timedSchedule = \interval innerAction -> do let action = threadDelay (toMicroSeconds interval) >> innerAction atomically (TChan.writeTChan reqChan action) emptyDisposable } return $ SingleThreadScheduler scheduler disposable -------------------------------------------------------------------------------- -- ^ Creates a @Scheduler@ that performs work on a single unbound -- thread singleThread :: IO (SingleThreadScheduler Async) singleThread = _singleThread forkIO -- ^ Creates a @Scheduler@ that performs work on a single bound -- thread. This is particularly useful when working with async -- actions and FFI calls. singleBoundThread :: IO (SingleThreadScheduler Async) singleBoundThread = _singleThread forkOS
roman/Haskell-Reactive-Extensions
rx-scheduler/src/Rx/Scheduler/SingleThread.hs
mit
2,507
0
21
452
470
257
213
44
1
-- Arithmetic List! -- http://www.codewars.com/kata/541da001259d9ca85d000688 module SeqList where seqlist :: Int -> Int -> Int -> [Int] seqlist f c l = take l [f, f+c ..]
gafiatulin/codewars
src/7 kyu/SeqList.hs
mit
173
0
8
29
54
31
23
3
1
module Web.Twitter.LtxBot.Types where import Control.Monad.Reader (ReaderT) import Network.HTTP.Conduit (Manager) import Web.Twitter.Conduit (TWInfo) import Web.Twitter.Types (UserId) data LtxbotEnv = LtxbotEnv { envUserId :: UserId , envTwInfo :: TWInfo , envManager :: Manager } type LTXE m = ReaderT LtxbotEnv m
passy/ltxbot
src/Web/Twitter/LtxBot/Types.hs
mit
372
0
8
96
91
58
33
9
0
{-# LANGUAGE FlexibleInstances #-} {-| Module : Hate.Math Description : Hate mathematical utilities License : MIT Maintainer : [email protected] Stability : provisional Portability : full This module mostly works with primitives from @Data.Vect@, adding some utilities useful in rendering and OpenGL interoperability. -} module Hate.Math ( module Data.Vect.Float , module Hate.Math.Util , module Hate.Math.Types ) where import Data.Vect.Float import Data.Vect.Float.Instances() import Hate.Math.Types import Hate.Math.Util
maque/Hate
src/Hate/Math.hs
mit
580
0
5
125
59
41
18
9
0
module ParserSpec where import Test.Hspec import Control.Arrow (left) import Text.ParserCombinators.Parsec (Parser) import Parser import VM spec :: Spec spec = describe "instructionsParser" $ do context "with normalInstructionsString" $ it "parses" $ parseTest instructionsParser normalInstructionsString `shouldBe` Right [Push 3, Add, Store 4] context "with commentBetweenLines" $ it "parses" $ parseTest instructionsParser commentBetweenLines `shouldBe` Right [Push 5, Add] context "with labelInstructions" $ it "parsers" $ parseTest instructionsParser labelInstructions `shouldBe` Right [Label "abc", Push 3, JumpIf "abc"] parseTest :: Parser a -> String -> Either String a parseTest p input = left show $ parse p "Spec" input normalInstructionsString :: String normalInstructionsString = "Push 3\nAdd\nStore 4\n" commentBetweenLines :: String commentBetweenLines = "# aaa\nPush 5\n# Add\nAdd\n#Push 5" labelInstructions :: String labelInstructions = "Label abc\nPush 3\nJumpIf abc"
taiki45/hs-vm
test/ParserSpec.hs
mit
1,209
0
11
345
263
135
128
28
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.Notification ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.Notification #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.Notification #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/Notification.hs
mit
349
0
5
33
33
26
7
4
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Risk where import Control.Monad.Random import Control.Monad import Data.List (sort) ------------------------------------------------------------ -- Die values newtype DieValue = DV { unDV :: Int } deriving (Eq, Ord, Show, Num) first :: (a -> b) -> (a, c) -> (b, c) first f (a, c) = (f a, c) instance Random DieValue where random = first DV . randomR (1,6) randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi)) die :: Rand StdGen DieValue die = getRandom dice :: Int -> Rand StdGen [DieValue] dice n = replicateM n die ------------------------------------------------------------ -- Risk type Army = Int data Battlefield = Battlefield { attackers :: Army, defenders :: Army } deriving (Show) battle :: Battlefield -> Rand StdGen Battlefield battle bf = rollFor bf >>= \rolls -> return $ runBattle bf rolls runBattle :: Battlefield -> [(DieValue, DieValue)] -> Battlefield runBattle (Battlefield att def) rolls = Battlefield att' def' where (att', def') = foldl (\(att', def') (a, d) -> if a > d then (att', def'-1) else (att'-1, def')) (att, def) rolls rollFor :: Battlefield -> Rand StdGen [(DieValue, DieValue)] rollFor bf = let (attArmy, defArmy) = units bf attackerRolls = dice attArmy defenderRolls = dice defArmy in attackerRolls >>= \ar -> defenderRolls >>= \dr -> return $ zip (sort ar) (sort dr) units :: Battlefield -> (Army, Army) units (Battlefield att def) = let att' = if att > 1 then min (att - 1) 3 else 1 def' = min def 2 in (att', def') invade :: Battlefield -> Rand StdGen Battlefield invade bf = battle bf >>= \bf' -> if defenders bf' == 0 || attackers bf' < 2 then return bf' else invade bf' successProb :: Battlefield -> Rand StdGen Double successProb bf = replicateM 1000 (invade bf) >>= success success :: [Battlefield] -> Rand StdGen Double success bfs = return $ fromIntegral attackerWins / fromIntegral (length bfs) where attackerWins = length . filter (== 0) . map defenders $ bfs
tomwadeson/cis194
week12/Risk.hs
mit
2,137
0
14
490
814
437
377
44
2
{-# LANGUAGE Strict #-} {-# LANGUAGE RecordWildCards #-} module WordEmbedding.HasText.Internal.Strict.Model ( binaryLogistic , computeHidden , getmWI ) where import Control.Monad.Reader import Control.Concurrent import qualified Data.Text as T import Data.Hashable (Hashable) import qualified Data.HashMap.Strict as HS import qualified Data.Vector as V import qualified Data.Vector.Unboxed.Mutable as VUM import qualified Data.Mutable as M import WordEmbedding.HasText.Internal.Strict.HasText (sigmoid) import qualified WordEmbedding.HasText.Internal.Strict.MVectorOps as HMV import WordEmbedding.HasText.Internal.Type ( Params(..) , LParams(..) , Model , MWeights(..) , WordVecRef ) -- | -- The function that update model based on formulas of the objective function and binary label. binaryLogistic :: Bool -- ^ label in Xin's tech report. (If this is True function compute about positive word. If False, negative-sampled word.) -> T.Text -- ^ a updating target word -> Model binaryLogistic label input = do (Params{..}, LParams{..}) <- ask liftIO $ do ws <- takeMVar _wordVecRef let mwo = _mwO (ws HS.! input) score <- sigmoid <$> HMV.sumDotMM mwo _hidden let alpha = _lr * (boolToNum label - score) HMV.foriM_ _grad $ \i e -> do emwo <- VUM.unsafeRead mwo i pure $! e + alpha * emwo HMV.mapi (const (alpha *)) _hidden HMV.addMM mwo _hidden putMVar _wordVecRef ws let minusLog = negate . log $! if label then score else 1.0 - score M.modifyRef' _loss (+ minusLog) where boolToNum = fromIntegral . fromEnum {-# INLINE binaryLogistic #-} computeHidden :: VUM.IOVector Double -> WordVecRef -> V.Vector T.Text -> IO () computeHidden hidden wsRef input = do ws <- readMVar wsRef mapM_ (HMV.addMM hidden) $ V.map (getmWI ws) input HMV.scale invLen hidden where inverse d = 1.0 / fromIntegral d invLen = inverse . V.length $! input {-# INLINE computeHidden #-} getmWI :: (Hashable k, Eq k) => HS.HashMap k MWeights -> k -> VUM.IOVector Double getmWI w k = _mwI $! w HS.! k {-# INLINE getmWI #-}
Nnwww/hastext
src/WordEmbedding/HasText/Internal/Strict/Model.hs
mit
2,464
0
16
774
611
331
280
53
2
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-} module HCraft.World.Camera ( module HCraft.World.Camera.Camera , updateCamera , getCameraVolume ) where import Control.Applicative import Control.Monad import Control.Monad.Error import Control.Monad.Reader import Data.Bits import Data.List import Graphics.UI.GLFW import Graphics.Rendering.OpenGL hiding (Plane) import HCraft.Engine import HCraft.Math import HCraft.World.Chunk import HCraft.World.Camera.Camera checkCollision :: Vec3 GLfloat -> Vec3 GLfloat -> Engine (Vec3 GLfloat) checkCollision pos@(Vec3 x y z) dir@(Vec3 dx dy dz) = do let xp = x + dx + 0.5 > fromIntegral (ceiling x) yp = y + dy + 0.5 > fromIntegral (ceiling y) zp = z + dz + 0.5 > fromIntegral (ceiling z) xn = x + dx - 0.5 < fromIntegral (floor x) yn = y + dy - 0.5 < fromIntegral (floor y) zn = z + dz - 0.5 < fromIntegral (floor z) Vec3 x' y' z' = floor <$> pos cond = [ ( xp, Vec3 (-1.0) 0.0 0.0, Vec3 (x' + 1) y' z' ) , ( xn, Vec3 1.0 0.0 0.0, Vec3 (x' - 1) y' z' ) , ( zp, Vec3 0.0 0.0 (-1.0), Vec3 x' y' (z' + 1) ) , ( zn, Vec3 0.0 0.0 1.0, Vec3 x' y' (z' - 1) ) , ( yp, Vec3 0.0 (-1.0) 0.0, Vec3 x' (y' + 1) z' ) , ( yn, Vec3 0.0 1.0 0.0, Vec3 x' (y' - 1) z' ) ] test dir ( cond, norm, block ) | not cond = return dir | otherwise = do block <- getBlock block case block of Nothing -> return dir Just _ -> return (dir ^-^ (norm ^*. (norm ^.^ dir))) (pos ^+^) <$> foldM test dir cond updateCamera :: GLfloat -> Engine () updateCamera dt = do EngineState{..} <- ask -- Retrieve input size@(Size w h) <- liftIO $ get windowSize Position mx my <- liftIO $ get mousePos -- Retrieve camera info camera@Camera{..} <- liftIO $ get esCamera let Vec3 rx ry rz = cRotation Vec3 px py pz = cPosition -- Compute new parameters let aspect = fromIntegral w / fromIntegral h dx = fromIntegral (my - (h `shiftR` 1)) * (dt * 0.2) dy = fromIntegral (mx - (w `shiftR` 1)) * (dt * 0.2) rx' = max (min (rx + dx) (pi / 2 - abs dx)) (-pi / 2 + abs dx) ry' = ry - dy rz' = rz dir = Vec3 (sin ry' * cos rx') (sin rx') (cos ry' * cos rx') -- Possible move directions let dirs = [ vinv dir , dir , Vec3{ v3x = sin (ry' - pi / 2) * cos rx' , v3y = 0.0 , v3z = cos (ry' - pi / 2) * cos rx' } , Vec3{ v3x = sin (ry' + pi / 2) * cos rx' , v3y = 0.0 , v3z = cos (ry' + pi / 2) * cos rx' } ] -- Sum up active directions dirs' <- forM (zip [ CharKey 'W', CharKey 'S', CharKey 'A', CharKey 'D' ] dirs) $ \( key, dir ) -> liftIO $ getKey key >>= \status -> return $ case status of Press -> dir Release -> Vec3 0 0 0 let moveDir = foldr1 (^+^) dirs' moveDir' = if vlen moveDir < 0.1 then Vec3 0 0 0 else (moveDir ^/. vlen moveDir) ^*. 0.3 pos <- checkCollision cPosition moveDir' -- Compute new orientation liftIO $ do mousePos $= Position (w `shiftR` 1) (h `shiftR` 1) esCamera $= camera { cPosition = pos , cRotation = Vec3 rx' ry' rz' , cDirection = dir , cProjMat = mat4Persp (pi / 4) aspect cNearPlane cFarPlane , cViewMat = mat4LookAt pos (pos ^+^ dir) (Vec3 0 1 0) , cSkyMat = mat4LookAt vzero dir (Vec3 0 1 0) , cAspect = aspect } getCameraVolume :: Camera -> Frustum getCameraVolume Camera{..} = Frustum . map pnorm $ [ Plane (Vec3 (m3 + m2) (m7 + m6) (m11 + m10)) (m15 + m14) , Plane (Vec3 (m3 - m2) (m7 - m6) (m11 - m10)) (m15 - m14) , Plane (Vec3 (m3 - m1) (m7 - m5) (m11 - m9)) (m15 - m13) , Plane (Vec3 (m3 + m1) (m7 + m5) (m11 + m9)) (m15 + m13) , Plane (Vec3 (m3 + m0) (m7 + m4) (m11 + m8)) (m15 + m12) , Plane (Vec3 (m3 - m0) (m7 - m4) (m11 - m8)) (m15 - m12) ] where Mat4 c0 c1 c2 c3 = cProjMat |*| cViewMat Vec4 m0 m4 m8 m12 = c0 Vec4 m1 m5 m9 m13 = c1 Vec4 m2 m6 m10 m14 = c2 Vec4 m3 m7 m11 m15 = c3
nandor/hcraft
HCraft/World/Camera.hs
mit
4,295
0
22
1,450
1,873
982
891
97
3
module Main where import Test.DocTest import System.Process main :: IO () main = do files <- lines <$> readProcess "find" ["src", "-type", "f", "-name", "*.hs"] [] doctest $ [] ++ files
namikingsoft/nlp100knock
test/DocTest.hs
mit
192
0
10
37
77
42
35
7
1
import System.Environment (getArgs) import System.Exit (exitFailure) import System.Cmd (system) import AbsMini import LexMini import ParMini import ErrM import AnnotatingTypeChecker import Compiler -- driver comp :: String -> String -> IO () comp name s = case pProgram (myLexer s) of Bad err -> do putStrLn "SYNTAX ERROR" putStrLn err exitFailure Ok tree -> case typecheck tree of Bad err -> do putStrLn "TYPE ERROR" putStrLn err exitFailure Ok tree' -> do writeFile (name ++ ".j") $ compile name tree' putStrLn $ "wrote " ++ name ++ ".j" main :: IO () main = do args <- getArgs case args of [file] -> do s <- readFile file comp "Foo" s --- name Foo instead of (takeWhile (/='.') file) system "java -jar jasmin.jar Foo.j" return () _ -> do putStrLn "Usage: lab3 <SourceFile>" exitFailure
izimbra/PLT2014
mini/haskell/compilemini.hs
gpl-2.0
1,207
0
16
551
287
135
152
31
3
-------------------------------------------------------------------------------- -- This file is part of diplomarbeit ("Diplomarbeit Johannes Weiß"). -- -- -- -- diplomarbeit is free software: you can redistribute it and/or modify -- -- it under the terms of the GNU General Public License as published by -- -- the Free Software Foundation, either version 3 of the License, or -- -- (at your option) any later version. -- -- -- -- diplomarbeit 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 diplomarbeit. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- Copyright 2012, Johannes Weiß -- -------------------------------------------------------------------------------- {-# LANGUAGE BangPatterns #-} module Math.FiniteFields.F2Pow256 ( F2Pow256, f2Pow256FromString , f2Pow256FromUtf8ByteString , f2Pow256ToUtf8ByteString , f2Pow256ToBytes , f2Pow256FromBytes ) where import Data.ByteString (ByteString) import Data.Helpers (integralBytes) import Data.FieldTypes import Control.Monad.CryptoRandom (CRandom(..)) import Crypto.Random (CryptoRandomGen(..)) import Test.QuickCheck.Arbitrary (Arbitrary(..)) import Test.QuickCheck.Gen (choose) import Text.Regex (Regex, mkRegex, matchRegex) import qualified Math.FiniteFields.Foreign.FFInterface as FFI newtype F2Pow256 = F2Pow256 { unF2Pow256 :: FFI.OpaqueElement } binaryOp :: (FFI.OpaqueElement -> FFI.OpaqueElement -> FFI.OpaqueElement) -> F2Pow256 -> F2Pow256 -> F2Pow256 binaryOp op (F2Pow256 !l) (F2Pow256 !r) = let result = l `op` r in result `seq` F2Pow256 result _READ_REGEX_ :: Regex _READ_REGEX_ = mkRegex "^(\\[([01]( [01]){0,255})?\\])" instance Field F2Pow256 where invert = F2Pow256 . FFI.ffInvertElement . unF2Pow256 one = fromIntegerF2Pow256 1 zero = fromIntegerF2Pow256 0 instance Show F2Pow256 where show = FFI.ffElementToString . unF2Pow256 instance Read F2Pow256 where readsPrec _ str = case matchRegex _READ_REGEX_ str of Nothing -> [] Just xs -> case xs of [] -> [] (value:_) -> let rest = drop (length value) str in [((F2Pow256 . FFI.ffElementFromString) value, rest)] instance Num F2Pow256 where (+) = binaryOp FFI.ffAddElements (*) = binaryOp FFI.ffMulElements (-) = binaryOp FFI.ffSubElements signum = error "F2Pow256.signum not implemented" abs = error "F2Pow256.abs not implemented" fromInteger = fromIntegerF2Pow256 instance Fractional F2Pow256 where (/) = binaryOp FFI.ffDivElements fromRational = error "F2Pow256: fromRational undefined" instance CRandom F2Pow256 where crandom g = case genBytes 32 g of Right (bs, g') -> Right (f2Pow256FromBytes bs, g') Left err -> Left err fromIntegerF2Pow256 :: Integer -> F2Pow256 fromIntegerF2Pow256 = F2Pow256 . FFI.ffElementFromBytes . integralBytes . abs f2Pow256FromString :: String -> F2Pow256 f2Pow256FromString = F2Pow256 . FFI.ffElementFromString f2Pow256FromUtf8ByteString :: ByteString -> F2Pow256 f2Pow256FromUtf8ByteString = F2Pow256 . FFI.ffElementFromUtf8ByteString f2Pow256ToUtf8ByteString :: F2Pow256 -> ByteString f2Pow256ToUtf8ByteString = FFI.ffElementToUtf8ByteString . unF2Pow256 f2Pow256ToBytes :: F2Pow256 -> ByteString f2Pow256ToBytes = FFI.ffElementToBytes . unF2Pow256 f2Pow256FromBytes :: ByteString -> F2Pow256 f2Pow256FromBytes = F2Pow256 . FFI.ffElementFromBytes instance Eq F2Pow256 where (==) (F2Pow256 !l) (F2Pow256 !r) = let rs = FFI.ffEquals l r in rs `seq` rs instance Arbitrary F2Pow256 where arbitrary = fmap fromInteger $ choose (0, (2::Integer)^(256::Integer)-1)
weissi/diplomarbeit
lib/Math/FiniteFields/F2Pow256.hs
gpl-3.0
4,612
0
19
1,373
830
462
368
70
1
{-# LANGUAGE NoImplicitPrelude #-} module Lamdu.Infer.Load ( Loader(..) , loadInfer ) where import Prelude.Compat import Control.Lens.Operators import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Traversable as Traversable import Lamdu.Expr.Lens (valGlobals, valNominals) import Lamdu.Expr.Nominal (Nominal) import Lamdu.Expr.Scheme (Scheme) import qualified Lamdu.Expr.Type as T import Lamdu.Expr.Val (Val) import qualified Lamdu.Expr.Val as V import Lamdu.Infer (Scope, Infer, infer, Payload, Loaded(..)) data Loader m = Loader { loadTypeOf :: V.GlobalId -> m Scheme , loadNominal :: T.NominalId -> m Nominal } loadVal :: Applicative m => Loader m -> Val a -> m Loaded loadVal loader val = Loaded <$> loadMap loadTypeOf (val ^.. valGlobals) <*> loadMap loadNominal (val ^.. valNominals) where loadMap f x = x & Set.fromList & Map.fromSet (f loader) & Traversable.sequenceA loadInfer :: Applicative m => Loader m -> Scope -> Val a -> m (Infer (Val (Payload, a))) loadInfer loader scope val = loadVal loader val <&> \loaded -> infer loaded scope val
da-x/Algorithm-W-Step-By-Step
Lamdu/Infer/Load.hs
gpl-3.0
1,217
0
14
289
380
216
164
29
1
-- decode a run-length output from p11 data RL a = Single a | Multiple Int a deriving (Show) p12 :: [RL a] -> [a] p12 xs = concat $ map conv xs where conv (Single x) = [x] conv (Multiple n x) = take n (repeat x)
yalpul/CENG242
H99/11-20/p12.hs
gpl-3.0
230
0
9
65
107
56
51
5
2
{-# LANGUAGE BangPatterns, OverloadedStrings #-} -- | The functions in this modules defines are used to generate user avatars, -- to resize uploaded images, to add and remove avatars in the database and to -- get paths and routes to avatar files. module Account.Avatar ( AvatarImage, ImageHash (..), aiImage, aiGenerated, aiHash , avatarSize, spriteFile, tileSize, loadSprite , genIdenticon, avatarImage , newAvatar, removeAvatar, getAvatarId, getAvatar, getAvatarFile , avatarPath, avatarRoute, hashImage ) where import Prelude import Control.Applicative import Control.Monad import qualified Data.Array as A import qualified Data.Binary.Get as G import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as C import Data.Digest.Pure.SHA (sha1, bytestringDigest, showDigest) import Data.Text (Text) import qualified Data.Text as T import Data.Word import System.Directory (createDirectoryIfMissing, removeFile) import System.FilePath ((</>), (<.>), takeDirectory) import Vision.Image ( D, GreyImage (..), GreyPixel (..), Image (..), InterpolMethod (..) , RGBAImage (..), RGBAPixel (..), Rect (..), Source, U, Z (..), (:.) (..) , convert, crop, extent, fromFunctionLine, horizontalFlip, load, getPixel , resize, save, toList, verticalFlip ) import Yesod import Account.Foundation import Util.HashDir (hashDir, hashDir') -- | Abstract data type used to enforce images to be resized before being -- inserted in the database. data AvatarImage = AvatarImage { aiImage :: !(RGBAImage U), aiGenerated :: !Bool, aiHash :: !ImageHash } newtype ImageHash = ImageHash Text -- Must be a multiple of 2 * tileSize as the avatar will be composed of four -- regions which are generated from a square number of tiles. avatarSize :: Int avatarSize = 4 * tileSize -- | Size of the tiles in 'spriteFile'. tileSize :: Int tileSize = 20 spriteFile :: FilePath spriteFile = "Account" </> "avatar_sprite" <.> "png" -- | Loads the image file which contains the different tiles and generates a -- vector of these tiles. Tiles must be arranged in horizontal order. loadSprite :: IO Sprite loadSprite = do Right io <- load spriteFile let img = convert io :: GreyImage D Z :. _ :. w = extent img n = w `quot` tileSize tiles = [ crop img (Rect x 0 tileSize tileSize) | let maxX = tileSize * (n - 1) , x <- [0,tileSize..maxX] ] return $! Sprite $! A.listArray (0, n-1) tiles -- | Generates a deterministic avatar using an user identifier. genIdenticon :: Sprite -> Text -> AvatarImage genIdenticon (Sprite sprite) str = let (color, tiles) = G.runGet getVals hash regionsArr = regions color tiles -- Combines the four regions into a single image. line (Z :. y) = let (!yQuot, !yRem) = y `quotRem` regionSide in (2 * yQuot, yRem) pixel (!yQuot2, !yRem) (Z :. _ :. x) = let (!xQuot, !xRem) = x `quotRem` regionSide !region = regionsArr A.! (yQuot2 + xQuot) in region `getPixel` (Z :. yRem :. xRem) img = fromFunctionLine (Z :. avatarSize :. avatarSize) line pixel in AvatarImage img True (hashImage img) where -- Generates an infinite hash by repeating the application of the SHA1 -- function. hash = C.concat $ tail $ iterate (bytestringDigest . sha1) (C.pack $ T.unpack str) -- Width/Height of one region if the avatar. -- There are 4 regions in the avatar. !regionSide = avatarSize `quot` 2 -- Each region is composed of a square number of tiles. !nTilesSide = regionSide `quot` tileSize !nTiles = nTilesSide * nTilesSide -- Takes a random color and a set of random tiles from a bytestring. getVals = do -- Uses the first 3 bytes to get a random color. (r, g, b) <- (,,) <$> G.getWord8 <*> G.getWord8 <*> G.getWord8 let color (GreyPixel v) = RGBAPixel r g b v -- Uses a byte to choose random tiles. let availTiles = 1 + snd (A.bounds sprite) tiles <- replicateM nTiles $ do w <- G.getWord8 return $! sprite A.! (int w `rem` availTiles) let arr = A.listArray (0, nTiles - 1) tiles return (color, arr) -- The avatar is divided in 4 symmetrical regions. Each region is randomly -- generated from a square number of randomly chosen tiles. -- This function returns the four regions from the set of randomly choosen -- tiles. regions :: (GreyPixel -> RGBAPixel) -> A.Array Int (GreyImage D) -> A.Array Int (RGBAImage U) regions color tiles = let regionSize = Z :. regionSide :. regionSide -- Computes the first region by copying the randomly choosen tiles. line (Z :. y) = let (!yQuot, !yRem) = y `quotRem` tileSize in (yQuot * nTilesSide, yRem) pixel (!yOffset, !yRem) (Z :. _ :. x) = let (!xQuot, !xRem) = x `quotRem` tileSize !tile = tiles A.! (yOffset + xQuot) in color $ tile `getPixel` (Z :. yRem :. xRem) region1 = fromFunctionLine regionSize line pixel region2 = horizontalFlip region1 region3 = verticalFlip region1 region4 = verticalFlip region2 in A.listArray (0, 3) [region1, region2, region3, region4] -- | Resizes and adapts an uploaded image to be used as an avatar. avatarImage :: Source r (Channel RGBAImage) => RGBAImage r -> AvatarImage avatarImage img = let img' = resize img Bilinear (Z :. avatarSize :. avatarSize) in AvatarImage img' False (hashImage img') {-# INLINE avatarImage #-} -- | Registers and saves a new avatar. Checks if the same avatar is not used by -- another user. newAvatar :: YesodAccount parent => AvatarImage -> YesodDB parent (AvatarNum, Avatar) newAvatar (AvatarImage img generated imgHash@(ImageHash hash)) = do mFile <- getBy $ UniqueAvatarFileHash hash case mFile of Just (Entity fileId _) -> do update fileId [AvatarFileCount +=. 1] Nothing -> do app <- lift $ getYesod let path = avatarPath app imgHash liftIO $ createDirectoryIfMissing True (takeDirectory path) liftIO $ save path img insert_ $ AvatarFile hash 1 let avatar = Avatar generated hash Key (PersistInt64 avatarId) <- insert avatar return (avatarId, avatar) -- | Removes a user\'s avatar from the database and from the filesystem if it -- is not shared by other users. removeAvatar :: YesodAccount parent => AvatarId -> Avatar -> YesodDB parent () removeAvatar avatarId avatar = do delete avatarId let hash = ImageHash $ avatarHash avatar Just (Entity fileId file) <- getAvatarFile avatar if avatarFileCount file <= 1 then do delete fileId app <- lift getYesod liftIO $ removeFile $ avatarPath app hash else update fileId [AvatarFileCount -=. 1] getAvatarId :: (MonadHandler m, YesodAccount (HandlerSite m)) => AccountUser (HandlerSite m) -> m AvatarId getAvatarId user = do app <- getYesod return $ Key $ PersistInt64 $ accountAvatarId app user getAvatar :: YesodAccount parent => AccountUser parent -> YesodDB parent (Maybe Avatar) getAvatar user = lift (getAvatarId user) >>= get getAvatarFile :: YesodAccount parent => Avatar -> YesodDB parent (Maybe (Entity AvatarFile)) getAvatarFile avatar = getBy $ UniqueAvatarFileHash $ avatarHash avatar avatarPath :: YesodAccount parent => parent -> ImageHash -> FilePath avatarPath app (ImageHash hash) = avatarsDir app </> hashDir hash <.> "png" avatarRoute :: YesodAccount parent => parent -> Avatar -> Route parent avatarRoute app avatar = let path = hashDir' $ avatarHash avatar file = init path ++ [last path `T.append` ".png"] in avatarsDirRoute app file -- | Returns the SHA1 of the pixels values of the image. hashImage :: (Image i, Channel i ~ Word8, Source r Word8) => i r -> ImageHash hashImage = ImageHash . T.pack . showDigest . sha1 . L.pack . toList int :: Integral a => a -> Int int = fromIntegral
RaphaelJ/getwebb.org
Account/Avatar.hs
gpl-3.0
8,324
0
17
2,156
2,240
1,190
1,050
-1
-1
module Hob.UiSpec (main, spec) where import Graphics.UI.Gtk import qualified Hob.Context as HC import qualified Hob.Context.UiContext as HC import Test.Hspec import HobTest.Context.Default main :: IO () main = hspec spec spec :: Spec spec = describe "mainWindow" $ it "is named" $ do ctx <- loadDefaultContext name <- widgetGetName $ HC.mainWindow . HC.uiContext $ ctx name `shouldBe` "mainWindow"
svalaskevicius/hob
test/Hob/UiSpec.hs
gpl-3.0
438
0
12
97
129
73
56
15
1
{-# LANGUAGE NoMonomorphismRestriction, QuasiQuotes #-} import Text.Printf.TH emitBox w h x y = [s|\\draw (%?,%?) -- (%?,%?) -- (%?,%?) -- (%?,%?)-- (%?,%?);|] x y (x+w) y (x+w) (y-h) x (y-h) x y memBox x y addr str = concat [box, text, addrLabel, line] where box = emitBox 9.1 h1 x y text = [s|\\draw (%?,%?) node[right]{\\Verb|%s|};|] (x+sep) (y-h2) str addrLabel = [s|\\draw (%?, %?) node[right]{\\verb|%s|};|] x (y-h2) addr line = [s|\\draw (%?,%?) -- (%?, %?);|] (x+sep) y (x+sep) (y-h1) sep = 2.5; h1 = 0.75; h2 = 0.25 stackFrame x y title contents = concat $ titleNode : frameNodes where titleNode = [s|\\draw (%?,%?) node[right]{\\Verb|%s|};|] x (y+0.25) title frameNodes = zipWith3 (\x y (a,z) -> memBox x y a z) (repeat x) [y,y-0.75..] contents offset y i = y - (0.75 * i) - 0.3 arrow x1 x2 x3 y1 y2 = [s|\\draw[->] (%?,%?) -- (%?,%?) -- (%?,%?) -- (%?,%?);|] x1 y1 x2 y1 x2 y2 x3 y2 where ebp = [s|EBP %c %4x|] stackDiagram = concat $ [ --stackFrame 7 10 "alphabet" ["hello", "world"], stackFrame 1 aesFrame "bank_aes_handshake arguments" [ (ebp '+' 0x08, "int client_fd"), (ebp '+' 0x0c, "PrivateKey &privateKey"), (ebp '+' 0x10, "PublicKey &publicKey"), (ebp '+' 0x14, "byte* aes_key"), (ebp '+' 0x18, "byte* iv"), (ebp '+' 0x1c, "std::string& init_nonce") ], stackFrame 11.5 threadFrame "thread_handle locals" [ (ebp '-' 0x1cc, "std::string nonce"), (ebp '-' 0x1c0, "action::Action response"), (ebp '-' 0x100, "action::Action action"), (ebp '-' 0x0e0, "std::string s"), (ebp '-' 0x048, "byte iv[16]"), (ebp '-' 0x038, "int dummy_alloc"), (ebp '-' 0x034, "byte aes_key[16]"), (ebp '-' 0x024, "PublicKey *publicKey"), (ebp '-' 0x020, "PrivateKey *privateKey"), (ebp '-' 0x01c, "int client_sock"), (ebp '-' 0x018, "client_info *client_args") ], stackFrame 1 mainFrame "main locals" [ (ebp '-' 0x29c, "int client_sock"), (ebp '-' 0x268, "char port_str[10]"), (ebp '-' 0x238, "client_info client_args"), (ebp '-' 0x238, " client_args.sockfd"), (ebp '-' 0x234, " client_args.privateKey"), (ebp '-' 0x230, " client_args.publicKey"), (ebp '-' 0x22c, "pthread_t client_thread"), (ebp '-' 0x224, "socklen_t addr_size"), (ebp '-' 0x220, "struct sockaddr_storage client"), (ebp '-' 0x190, "int listen_sock"), (ebp '-' 0x18c, "struct addrinfo *res"), (ebp '-' 0x188, "struct addrinfo hints"), (ebp '-' 0x164, "pthread_t console_thread"), (ebp '-' 0x160, "PublicKey publicKey"), (ebp '-' 0x128, "PrivateKey privateKey"), (ebp '-' 0x028, "std::string inputPort") ], arrow 1 0.5 1 (offset aesFrame 1) (offset mainFrame 4), arrow 1 0 1 (offset aesFrame 2) (offset mainFrame 5), arrow 11.5 11.0 10.1 (offset threadFrame 8) (offset mainFrame 4), arrow 11.5 10.5 10.1 (offset threadFrame 7) (offset mainFrame 5), arrow 10.1 11.0 11.5 (offset aesFrame 3) (offset 5 6), arrow 10.1 10.5 11.5 (offset aesFrame 4) (offset 5 4) ] where aesFrame = 6; threadFrame = 5; mainFrame = 0 main = writeFile "stackDiagram.tikz" stackDiagram
aweinstock314/sheedb_weinsa_crypto2015_project
writeups/GenerateStackDiagram.hs
agpl-3.0
3,295
0
10
816
1,122
625
497
60
1
{-# LANGUAGE TypeFamilies, ExistentialQuantification, GADTs #-} {-# OPTIONS_GHC -Wall #-} ---------------------------------------------------------------------- -- | -- Module : Shady.Attribute -- Copyright : (c) Conal Elliott 2009 -- License : AGPLv3 -- -- Maintainer : [email protected] -- Stability : experimental -- -- Setting attributes. An attribute is a stream of values named and -- described by a pattern. Attributes can be uniform vectors but also -- pairs of attributes, as well as (). Not really a single attribute, but -- rather a conglomeration of all properties of a vertex. -- -- I hope that glomming all properties into one value will be convenient, -- as well as eliminating the possibility of mismatching lengths of -- separated attributes. -- -- When set, these conglomerates get split into separate vector-valued -- attributes as required by GLSL. -- -- TODO: Replace the name "attribute" with something more descriptive. -- Maybe "vertex" or "vertex description". ---------------------------------------------------------------------- module Shady.Attribute ( setAttribute -- * Experimental , setAttribute', SinkUse ) where import Graphics.Rendering.OpenGL hiding (Shader,Program,Index,Sink,Int,Bool,Float) import Control.Applicative (liftA2) import Shady.MechanicsGL hiding (Attributes, mkAttribute) import TypeUnary.Vec (natToZ) import Shady.Language.Type (VectorT(..),Type(..)) import Shady.Language.Glom (Glom(..)) import Shady.Uniform (sType) import Shady.Language.Exp (Pat,V(..)) import Shady.Misc (Sink,Unop) setAttribute :: Pat a -> GlProgram -> Sink [a] setAttribute p prog = sink p where sink :: Pat a -> Sink [a] sink UnitG = const (return ()) sink (pa :* pb) = sink pa >+> sink pb sink (BaseG v) = vsink prog v infixr 1 >+> -- Combine sinks (>+>) :: Sink [a] -> Sink [b] -> Sink [(a,b)] (sa >+> sb) ps = sa as >> sb bs where (as,bs) = unzip ps -- Sink for vector lists vsink :: GlProgram -> V v -> Sink [v] vsink prog (V name (VecT ty)) = \ xs -> do vbo <- mkBuffer arr <- listArr xs _ <- createVBO ArrayBuffer vbo arr (lsize xs) useVar vbo (fromIntegral (attributeLoc prog name)) ty vsink _ v = error ("vsink: non-vector variable " ++ show v) -- TODO: separate sinking from using useVar :: BufferObject -> GlLoc' -> VectorT n a -> IO () useVar vbo loc (VectorT n a) = useVBO (natToZ n) (sType a) loc vbo {-------------------------------------------------------------------- Now create the VBO and returns the action to use it. --------------------------------------------------------------------} -- | Stash away some information and make an action to activate it later. type SinkUse z = z -> IO (Unop (IO ())) -- Or maybe -- -- type SinkUse z = z -> IO (forall a. Unop (IO a)) setAttribute' :: Pat a -> GlProgram -> SinkUse [a] setAttribute' p prog = sink p where sink :: Pat a -> SinkUse [a] sink UnitG = const (return id) sink (pa :* pb) = sink pa >++> sink pb sink (BaseG v) = vsink' prog v infixr 1 >++> (>++>) :: SinkUse [a] -> SinkUse [b] -> SinkUse [(a,b)] (sa >++> sb) ps = liftA2 (.) (sa as) (sb bs) where (as,bs) = unzip ps vsink' :: GlProgram -> V v -> SinkUse [v] vsink' prog (V name (VecT ty)) = \ xs -> do vbo <- mkBuffer arr <- listArr xs _ <- createVBO ArrayBuffer vbo arr (lsize xs) return (usingVar ty (fromIntegral (attributeLoc prog name)) vbo) vsink' _ v = error ("vsink: non-vector variable " ++ show v) usingVar :: VectorT n a -> GlLoc' -> BufferObject -> Unop (IO c) usingVar (VectorT n a) = usingVBO (natToZ n) (sType a)
conal/shady-render
src/Shady/Attribute.hs
agpl-3.0
3,619
0
14
705
1,053
562
491
52
3
{-| Module : Reflex.WX.Controls Description : This module contains wrappers for the functions in Graphics.UI.WX.Controls. License : wxWindows Library License Maintainer : [email protected] Stability : Experimental -} {-# LANGUAGE DeriveDataTypeable, FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses, RecursiveDo, RankNTypes #-} {-# LANGUAGE ScopedTypeVariables, TypeSynonymInstances #-} module Reflex.WX.Controls ( Window , window , tabTraversal , TopLevelWindow , Frame , frame , Panel , panel , ScrolledWindow , scrolledWindow , scrollRate , Button , button , smallButton , BitmapButton , bitmapButton , TextCtrl , entry , textEntry , textCtrl , processEnter , processTab , StaticText , staticText , Label , label , CheckBox , checkBox , Choice , choice ) where import Control.Monad.Fix import Control.Monad.IO.Class import Data.Typeable import qualified Graphics.UI.WX as W import qualified Graphics.UI.WXCore as W import Reflex import Reflex.WX.Class import Reflex.WX.Attributes import Reflex.WX.Layout wrapWC :: (W.Widget w, MonadWidget t m) => (forall a. W.Window a -> [W.Prop w] -> IO(w)) -> [Prop t w] -> m (Widget t w) wrapWC f p = do (AW w) <- askParent rec prop <- sequence $ fmap (unwrapProp x) p x <- liftIO $ f w prop return $ Widget x p wrapWF :: forall w t m b. (W.Form (W.Window w), MonadWidget t m) => (forall a. W.Window a -> [W.Prop (W.Window w)] -> IO (W.Window w)) -> [Prop t (W.Window w)] -> m Layout -> m (Widget t (W.Window w)) wrapWF f p l = do (AW w) <- askParent rec prop <- sequence $ fmap (unwrapProp x) p x <- liftIO $ f w prop pushParent (AW x) rl <- l popParent liftIO $ W.set x [W.layout W.:= rl] return $ Widget x p wrapWT :: MonadWidget t m => ([W.Prop (W.TopLevelWindow w)] -> IO (W.TopLevelWindow w)) -> [Prop t (W.TopLevelWindow w)] -> m Layout -> m (Widget t (W.TopLevelWindow w)) wrapWT f p l = do rec prop <- sequence $ fmap (unwrapProp x) p x <- liftIO $ f prop pushParent (AW x) rl <- l popParent liftIO $ W.set x [W.layout W.:= rl] return $ Widget x p -- Window type Window t a = Widget t (W.Window a) window :: (MonadWidget t m) => [Prop t (W.Window ())] -> m (Window t ()) window = wrapWC W.window tabTraversal :: Attr t (W.Window a) Bool tabTraversal = wrapAttr W.tabTraversal instance Able t (Widget t) (W.Window a) where enabled = wrapAttr W.enabled instance Bordered t (Widget t) (W.Window a) where border = wrapAttr W.border instance Colored t (Widget t) (W.Window a) where bgcolor = wrapAttr W.bgcolor color = wrapAttr W.color instance Dimensions t (Widget t) (W.Window a) where outerSize = wrapAttr W.outerSize position = wrapAttr W.position area = wrapAttr W.area bestSize = wrapAttr W.bestSize clientSize = wrapAttr W.clientSize virtualSize = wrapAttr W.virtualSize instance Literate t (Widget t) (W.Window a) where font = wrapAttr W.font fontSize = wrapAttr W.fontSize fontWeight = wrapAttr W.fontWeight fontFamily = wrapAttr W.fontFamily fontShape = wrapAttr W.fontShape fontFace = wrapAttr W.fontFace fontUnderline = wrapAttr W.fontUnderline textColor = wrapAttr W.textColor textBgcolor = wrapAttr W.textBgcolor instance Sized t (Widget t) (W.Window a) where size = wrapAttr W.size instance Styled t (Widget t) (W.Window a) where style = wrapAttr W.style instance Typeable a => Textual t (Widget t) (W.Window a) where text = Attr f W.text where f :: forall t m a. (Typeable a, MonadWidget t m) => Widget t (W.Window a) -> m (Dynamic t String) f a = case ((gcast a)::Maybe (Widget t (W.TextCtrl ()))) of Nothing -> (dget W.text) a Just w -> do let get :: IO () -> String -> IO () get a _ = a let set :: IO () -> (String -> IO ()) -> IO () set _ n = do str <- W.get (wxwidget w) W.text n str let ev = W.mapEvent get set W.update e <- wrapEvent1 ev w holdDyn "" e instance Tipped t (Widget t) (W.Window a) where tooltip = wrapAttr W.tooltip instance Visible t (Widget t) (W.Window a) where visible = wrapAttr W.visible instance Typeable a => Reactive t (Window t a) where mouse = wrapEvent1 W.mouse keyboard = wrapEvent1 W.keyboard closing = wrapEvent W.closing resize = wrapEvent W.resize focus = wrapEvent1 W.focus activate = wrapEvent1 W.activate -- TopLevelWindow type TopLevelWindow t a = Widget t (W.TopLevelWindow a) -- TODO Closeable? -- TODO Form? instance Framed t (Widget t) (W.TopLevelWindow a) where resizeable = wrapAttr W.resizeable minimizeable = wrapAttr W.minimizeable maximizeable = wrapAttr W.maximizeable closeable = wrapAttr W.closeable -- TODO HasDefault? instance Pictured t (Widget t) (W.TopLevelWindow a) where picture = wrapAttr W.picture -- Frame type Frame t a = Widget t (W.Frame a) frame :: (MonadWidget t m) => [Prop t (W.Frame ())] -> m Layout -> m (Frame t ()) frame = wrapWT W.frame -- Panel type Panel t a = Widget t (W.Panel a) panel :: (MonadWidget t m) => [Prop t (W.Panel ())] -> m Layout -> m (Panel t ()) panel = wrapWF W.panel --TODO Form? -- ScrolledWindow type ScrolledWindow t a = Widget t (W.ScrolledWindow a) scrolledWindow :: (MonadWidget t m) => [Prop t (W.ScrolledWindow ())] -> m Layout -> m (ScrolledWindow t ()) scrolledWindow = wrapWF W.scrolledWindow scrollRate :: Attr t (W.ScrolledWindow a) Size scrollRate = wrapAttr W.scrollRate -- Button type Button t a = Widget t (W.Button a) button :: (MonadWidget t m) => [Prop t (W.Button ())] -> m (Button t ()) button = wrapWC W.button smallButton :: (MonadWidget t m) => [Prop t (W.Button ())] -> m (Button t ()) smallButton = wrapWC W.smallButton instance Typeable a => Commanding t (Button t a) where command = wrapEvent W.command type BitmapButton t a = Widget t (W.BitmapButton a) bitmapButton :: (MonadWidget t m) => [Prop t (W.BitmapButton ())] -> m (BitmapButton t ()) bitmapButton = wrapWC W.bitmapButton instance Pictured t (Widget t) (W.BitmapButton a) where picture = wrapAttr W.picture -- TextCtrl type TextCtrl t a = Widget t (W.TextCtrl a) entry :: (MonadWidget t m) => [Prop t (W.TextCtrl ())] -> m (TextCtrl t ()) entry = textEntry textEntry :: (MonadWidget t m) => [Prop t (W.TextCtrl ())] -> m (TextCtrl t ()) textEntry = wrapWC W.textEntry textCtrl :: (MonadWidget t m) => [Prop t (W.TextCtrl ())] -> m (TextCtrl t ()) textCtrl = wrapWC W.textCtrl processEnter :: Attr t (W.TextCtrl a) Bool processEnter = wrapAttr W.processEnter processTab :: Attr t (W.TextCtrl a) Bool processTab = wrapAttr W.processTab instance Aligned t (Widget t) (W.TextCtrl a) where alignment = wrapAttr W.alignment instance Wrapped t (Widget t) (W.TextCtrl a) where wrap = wrapAttr W.wrap instance Typeable a => Commanding t (TextCtrl t a) where command = wrapEvent W.command instance Typeable a => Updating t (TextCtrl t a) where update c = do t <- get text c return $ fmap (const ()) (updated t) -- StaticText type StaticText t a = Widget t (W.StaticText a) staticText :: (MonadWidget t m) => [Prop t (W.StaticText ())] -> m (StaticText t ()) staticText = wrapWC W.staticText type Label t a = StaticText t a label :: (MonadWidget t m) => [Prop t (W.StaticText ())] -> m (Label t ()) label = staticText -- CheckBox type CheckBox t a = Widget t (W.CheckBox a) checkBox :: (MonadWidget t m) => [Prop t (W.CheckBox ())] -> m (CheckBox t ()) checkBox = wrapWC W.checkBox instance Typeable a => Commanding t (CheckBox t a) where command = wrapEvent W.command instance Checkable t (Widget t) (W.CheckBox a) where checkable = wrapAttr W.checkable checked = wrapAttr W.checked -- Choice type Choice t a = Widget t (W.Choice a) choice :: (MonadWidget t m) => [Prop t (W.Choice ())] -> m (Choice t ()) choice = wrapWC W.choice instance Sorted t (Widget t) (W.Choice a) where sorted = wrapAttr W.sorted instance Selecting t (Choice t ()) where select = wrapEvent W.select instance Selection t (Widget t) (W.Choice ()) where selection = wrapAttr W.selection -- TODO Items
Pamelloes/reflex-wx
src/main/Reflex/WX/Controls.hs
lgpl-2.1
9,440
0
21
2,999
3,451
1,761
1,690
224
1
import Data.List dupli x = concat [[x, x] | x <- x]
nstarke/icc13-introduction-to-haskell
ex14.hs
lgpl-3.0
52
0
8
12
34
18
16
2
1
module Graphics.UI.SDL.RWOps.PhysFS (fromPhysFile, tryFromPhysFile, withPhys) where import Control.Arrow import Control.Exception import Foreign (Ptr, maybePeek) import Graphics.UI.SDL.General (unwrapMaybe) import Graphics.UI.SDL.RWOps import Graphics.UI.SDL.Types (RWops, RWopsStruct) import System.IO.PhysFS import System.IO.PhysFS.Internal -- |Open a PhysicsFS file, perform an action, and close the file (regardless of what happens). withPhys :: FilePath -- ^The file to open -> PhysIOMode -- ^The mode to open with -> (RWops -> IO a) -- ^The action to perform on the resulting RWops -> IO a withPhys fp mode action = bracket (fromPhysFile fp mode) free action -- |Attempt to create a 'Graphics.UI.SDL.Types.RWops' structure from a PhysicsFS file. tryFromPhysFile :: FilePath -- ^The file to open -> PhysIOMode -- ^The mode to open with -> IO (Maybe RWops) tryFromPhysFile fp mode = rawOpen fp mode >>= (fst >>> createRWOps) >>= maybePeek mkFinalizedRW foreign import ccall "physfsrwops_create_rwops" createRWOps :: Ptr PhysFS_FileStruct -> IO (Ptr RWopsStruct) -- |Create a 'Graphics.UI.SDL.Types.RWops' structure from a PhysicsFS file. This will raise an exception if anything goes wrong. fromPhysFile :: FilePath -- ^The file to open -> PhysIOMode -- ^The mode to open with -> IO RWops fromPhysFile fp mode = unwrapMaybe "PHYSFS_SDL_RWFromFile" $ tryFromPhysFile fp mode -- The name given here (PHYSFS_...) is not actually a function, but it should get the point across
d3tucker/physfs
src/Graphics/UI/SDL/RWOps/PhysFS.hs
lgpl-3.0
1,567
0
10
299
277
157
120
23
1
data Fruit = Apple | Orange apple :: String apple = "apple" orange :: String orange = "orange" whichFrucit :: String -> Fruit --whichFrucit f = case f of -- apple -> Apple -- orange -> Orange -- --whichFrucit apple = Apple --whichFrucit orange = Orange whichFrucit "apple" = Apple whichFrucit "orange" = Orange
EricYT/real-world
src/chapter-3/BogusPattern.hs
apache-2.0
352
0
5
95
62
37
25
8
1
-- This is the main configuration file for Propellor, and is used to build -- the propellor program. import Propellor import Propellor.CmdLine import Propellor.Property.Scheduled import qualified Propellor.Property.File as File import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.Network as Network --import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Cron as Cron --import qualified Propellor.Property.Sudo as Sudo import qualified Propellor.Property.User as User --import qualified Propellor.Property.Hostname as Hostname --import qualified Propellor.Property.Tor as Tor import qualified Propellor.Property.Docker as Docker main :: IO () main = defaultMain hosts -- The hosts propellor knows about. -- Edit this to configure propellor! hosts :: [Host] hosts = [ host "mybox.example.com" & os (System (Debian Unstable) "amd64") & Apt.stdSourcesList & Apt.unattendedUpgrades & Apt.installed ["etckeeper"] & Apt.installed ["ssh"] & User.hasSomePassword (User "root") & Network.ipv6to4 & File.dirExists "/var/www" & Docker.docked webserverContainer & Docker.garbageCollected `period` Daily & Cron.runPropellor (Cron.Times "30 * * * *") -- add more hosts here... --, host "foo.example.com" = ... ] -- A generic webserver in a Docker container. webserverContainer :: Docker.Container webserverContainer = Docker.container "webserver" (Docker.latestImage "debian") & os (System (Debian (Stable "jessie")) "amd64") & Apt.stdSourcesList & Docker.publish "80:80" & Docker.volume "/var/www:/var/www" & Apt.serviceInstalledRunning "apache2"
sjfloat/propellor
config-simple.hs
bsd-2-clause
1,630
4
22
224
333
187
146
32
1
{-# LANGUAGE DeriveDataTypeable #-} module HEP.Parser.StdHep.ProgType where import System.Console.CmdArgs data HsStdHep = Test deriving (Show,Data,Typeable) test :: HsStdHep test = Test mode = modes [test]
wavewave/HsStdHep
lib/HEP/Parser/StdHep/ProgType.hs
bsd-2-clause
229
0
6
48
58
35
23
8
1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} module Propellor.Types.Core where import Propellor.Types.Info import Propellor.Types.OS import Propellor.Types.Result import Data.Monoid import "mtl" Control.Monad.RWS.Strict import Control.Monad.Catch import Control.Applicative import Prelude -- | Everything Propellor knows about a system: Its hostname, -- properties and their collected info. data Host = Host { hostName :: HostName , hostProperties :: [ChildProperty] , hostInfo :: Info } deriving (Show, Typeable) -- | Propellor's monad provides read-only access to info about the host -- it's running on, and a writer to accumulate EndActions. newtype Propellor p = Propellor { runWithHost :: RWST Host [EndAction] () IO p } deriving ( Monad , Functor , Applicative , MonadReader Host , MonadWriter [EndAction] , MonadIO , MonadCatch , MonadThrow , MonadMask ) class LiftPropellor m where liftPropellor :: m a -> Propellor a instance LiftPropellor Propellor where liftPropellor = id instance LiftPropellor IO where liftPropellor = liftIO -- | When two actions are appended together, the second action -- is only run if the first action does not fail. instance Monoid (Propellor Result) where mempty = return NoChange mappend x y = do rx <- x case rx of FailedChange -> return FailedChange _ -> do ry <- y return (rx <> ry) -- | An action that Propellor runs at the end, after trying to satisfy all -- properties. It's passed the combined Result of the entire Propellor run. data EndAction = EndAction Desc (Result -> Propellor Result) type Desc = String -- | Props is a combination of a list of properties, with their combined -- metatypes. data Props metatypes = Props [ChildProperty] -- | Since there are many different types of Properties, they cannot be put -- into a list. The simplified ChildProperty can be put into a list. data ChildProperty = ChildProperty Desc (Maybe (Propellor Result)) Info [ChildProperty] instance Show ChildProperty where show p = "property " ++ show (getDesc p) class IsProp p where setDesc :: p -> Desc -> p getDesc :: p -> Desc getChildren :: p -> [ChildProperty] addChildren :: p -> [ChildProperty] -> p -- | Gets the info of the property, combined with all info -- of all children properties. getInfoRecursive :: p -> Info -- | Info, not including info from children. getInfo :: p -> Info -- | Gets a ChildProperty representing the Property. -- You should not normally need to use this. toChildProperty :: p -> ChildProperty -- | Gets the action that can be run to satisfy a Property. -- You should never run this action directly. Use -- 'Propellor.EnsureProperty.ensureProperty` instead. getSatisfy :: p -> Maybe (Propellor Result) instance IsProp ChildProperty where setDesc (ChildProperty _ a i c) d = ChildProperty d a i c getDesc (ChildProperty d _ _ _) = d getChildren (ChildProperty _ _ _ c) = c addChildren (ChildProperty d a i c) c' = ChildProperty d a i (c ++ c') getInfoRecursive (ChildProperty _ _ i c) = i <> mconcat (map getInfoRecursive c) getInfo (ChildProperty _ _ i _) = i toChildProperty = id getSatisfy (ChildProperty _ a _ _) = a
ArchiveTeam/glowing-computing-machine
src/Propellor/Types/Core.hs
bsd-2-clause
3,285
14
15
616
738
403
335
69
0