code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module A5 where import D5 main = sumFun [1..4] + (sum ( map (f f_gen) [1..7]))
kmate/HaRe
old/testing/generaliseDef/A5_TokOut.hs
Haskell
bsd-3-clause
93
{-# OPTIONS_JHC -fno-prelude -fffi #-} module System.C.Stdio where import Jhc.Basics import Jhc.Type.C import Jhc.Type.Ptr type FILE = Ptr CFile foreign import ccall "stdio.h fopen" c_fopen :: Ptr CChar -> Ptr CChar -> IO FILE foreign import ccall "stdio.h popen" c_popen :: Ptr CChar -> Ptr CChar -> IO FILE foreign import ccall "stdio.h fclose" c_fclose :: FILE -> IO CInt foreign import ccall "stdio.h pclose" c_pclose :: FILE -> IO CInt foreign import ccall "stdio.h jhc_utf8_putchar" c_putwchar :: Int -> IO () foreign import ccall "wchar.h jhc_utf8_getc" c_fgetwc :: FILE -> IO Int foreign import ccall "wchar.h jhc_utf8_getchar" c_getwchar :: IO Int foreign import ccall "wchar.h jhc_utf8_putc" c_fputwc :: Int -> FILE -> IO Int foreign import ccall "stdio.h fwrite_unlocked" c_fwrite :: Ptr a -> CSize -> CSize -> FILE -> IO CSize foreign import ccall "stdio.h fread_unlocked" c_fread :: Ptr a -> CSize -> CSize -> FILE -> IO CSize foreign import ccall "stdio.h fflush" c_fflush :: FILE -> IO () foreign import ccall "stdio.h feof" c_feof :: FILE -> IO Int foreign import ccall "stdio.h ftell" c_ftell :: FILE -> IO IntMax foreign import ccall "stdio.h fseek" c_fseek :: FILE -> IntMax -> CInt -> IO Int foreign import ccall "stdio.h fileno" c_fileno :: FILE -> IO Int foreign import primitive "const.SEEK_SET" c_SEEK_SET :: CInt foreign import primitive "const.SEEK_CUR" c_SEEK_CUR :: CInt foreign import primitive "const.SEEK_END" c_SEEK_END :: CInt foreign import primitive "const._IOFBF" c__IOFBF :: CInt foreign import primitive "const._IOLBF" c__IOLBF :: CInt foreign import primitive "const._IONBF" c__IONBF :: CInt
m-alvarez/jhc
lib/jhc/System/C/Stdio.hs
Haskell
mit
1,772
{-# LANGUAGE CPP, DeriveDataTypeable, GeneralizedNewtypeDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Server.Packages.PackageIndex -- Copyright : (c) David Himmelstrup 2005, -- Bjorn Bringert 2007, -- Duncan Coutts 2008 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- An index of packages. -- module Distribution.Server.Packages.PackageIndex ( -- * Package index data type PackageIndex, -- * Creating an index fromList, -- * Updates merge, insert, insertWith, deletePackageName, deletePackageId, -- * Queries indexSize, numPackageVersions, packageNames, -- ** Precise lookups lookupPackageName, lookupPackageId, lookupPackageForId, lookupDependency, -- ** Case-insensitive searches searchByName, SearchResult(..), searchByNameSubstring, -- ** Bulk queries allPackages, allPackagesByName ) where import Distribution.Server.Framework.MemSize import Distribution.Server.Util.Merge import Prelude hiding (lookup) import Control.Exception (assert) import qualified Data.Map.Strict as Map import Data.Map.Strict (Map) import qualified Data.Foldable as Foldable import Data.List (groupBy, sortBy, find, isInfixOf) import Data.Monoid (Monoid(..)) import Data.Maybe (fromMaybe) import Data.SafeCopy import Data.Typeable import Distribution.Package ( PackageName(..), PackageIdentifier(..) , Package(..), packageName, packageVersion , Dependency(Dependency) ) import Distribution.Version ( withinRange ) import Distribution.Simple.Utils (lowercase, comparing) -- | The collection of information about packages from one or more 'PackageDB's. -- -- It can be searched effeciently by package name and version. -- newtype PackageIndex pkg = PackageIndex -- A mapping from package names to a non-empty list of versions of that -- package, in ascending order (most recent package last) -- TODO: Wouldn't it make more sense to store the most recent package first? -- -- This allows us to find all versions satisfying a dependency. -- Most queries are a map lookup followed by a linear scan of the bucket. -- (Map PackageName [pkg]) deriving (Show, Read, Typeable, MemSize) instance Eq pkg => Eq (PackageIndex pkg) where PackageIndex m1 == PackageIndex m2 = flip Foldable.all (mergeMaps m1 m2) $ \mr -> case mr of InBoth pkgs1 pkgs2 -> bagsEq pkgs1 pkgs2 OnlyInLeft _ -> False OnlyInRight _ -> False where bagsEq [] [] = True bagsEq [] _ = False bagsEq (x:xs) ys = case suitable_ys of [] -> False (_y:suitable_ys') -> bagsEq xs (unsuitable_ys ++ suitable_ys') where (unsuitable_ys, suitable_ys) = break (==x) ys instance Package pkg => Monoid (PackageIndex pkg) where mempty = PackageIndex (Map.empty) mappend = merge --save one mappend with empty in the common case: mconcat [] = mempty mconcat xs = foldr1 mappend xs invariant :: Package pkg => PackageIndex pkg -> Bool invariant (PackageIndex m) = all (uncurry goodBucket) (Map.toList m) where goodBucket _ [] = False goodBucket name (pkg0:pkgs0) = check (packageId pkg0) pkgs0 where check pkgid [] = packageName pkgid == name check pkgid (pkg':pkgs) = packageName pkgid == name && pkgid < pkgid' && check pkgid' pkgs where pkgid' = packageId pkg' -- -- * Internal helpers -- mkPackageIndex :: Package pkg => Map PackageName [pkg] -> PackageIndex pkg mkPackageIndex index = assert (invariant (PackageIndex index)) (PackageIndex index) internalError :: String -> a internalError name = error ("PackageIndex." ++ name ++ ": internal error") -- | Lookup a name in the index to get all packages that match that name -- case-sensitively. -- lookup :: Package pkg => PackageIndex pkg -> PackageName -> [pkg] lookup (PackageIndex m) name = fromMaybe [] $ Map.lookup name m -- -- * Construction -- -- | Build an index out of a bunch of packages. -- -- If there are duplicates, later ones mask earlier ones. -- fromList :: Package pkg => [pkg] -> PackageIndex pkg fromList pkgs = mkPackageIndex . Map.map fixBucket . Map.fromListWith (++) $ [ (packageName pkg, [pkg]) | pkg <- pkgs ] where fixBucket = -- out of groups of duplicates, later ones mask earlier ones -- but Map.fromListWith (++) constructs groups in reverse order map head -- Eq instance for PackageIdentifier is wrong, so use Ord: . groupBy (\a b -> EQ == comparing packageId a b) -- relies on sortBy being a stable sort so we -- can pick consistently among duplicates . sortBy (comparing packageId) -- -- * Updates -- -- | Merge two indexes. -- -- Packages from the second mask packages of the same exact name -- (case-sensitively) from the first. -- merge :: Package pkg => PackageIndex pkg -> PackageIndex pkg -> PackageIndex pkg merge i1@(PackageIndex m1) i2@(PackageIndex m2) = assert (invariant i1 && invariant i2) $ mkPackageIndex (Map.unionWith mergeBuckets m1 m2) -- | Elements in the second list mask those in the first. mergeBuckets :: Package pkg => [pkg] -> [pkg] -> [pkg] mergeBuckets [] ys = ys mergeBuckets xs [] = xs mergeBuckets xs@(x:xs') ys@(y:ys') = case packageId x `compare` packageId y of GT -> y : mergeBuckets xs ys' EQ -> y : mergeBuckets xs' ys' LT -> x : mergeBuckets xs' ys -- | Inserts a single package into the index. -- -- This is equivalent to (but slightly quicker than) using 'mappend' or -- 'merge' with a singleton index. -- insert :: Package pkg => pkg -> PackageIndex pkg -> PackageIndex pkg insert pkg (PackageIndex index) = mkPackageIndex $ -- or insertWith const Map.insertWith (\_ -> insertNoDup) (packageName pkg) [pkg] index where pkgid = packageId pkg insertNoDup [] = [pkg] insertNoDup pkgs@(pkg':pkgs') = case compare pkgid (packageId pkg') of LT -> pkg : pkgs EQ -> pkg : pkgs' -- this replaces the package GT -> pkg' : insertNoDup pkgs' -- | Inserts a single package into the index, combining an old and new value with a function. -- This isn't in cabal's version of PackageIndex. -- -- The merge function is called as (f newPkg oldPkg). Ensure that the result has the same -- package id as the two arguments; otherwise newPkg is used. -- insertWith :: Package pkg => (pkg -> pkg -> pkg) -> pkg -> PackageIndex pkg -> PackageIndex pkg insertWith mergeFunc pkg (PackageIndex index) = mkPackageIndex $ Map.insertWith (\_ -> insertMerge) (packageName pkg) [pkg] index where pkgid = packageId pkg insertMerge [] = [pkg] insertMerge pkgs@(pkg':pkgs') = case compare pkgid (packageId pkg') of LT -> pkg : pkgs EQ -> let merged = mergeFunc pkg pkg' in if packageId merged == pkgid then merged : pkgs' else pkg : pkgs' GT -> pkg' : insertMerge pkgs' -- | Internal delete helper. -- delete :: Package pkg => PackageName -> (pkg -> Bool) -> PackageIndex pkg -> PackageIndex pkg delete name p (PackageIndex index) = mkPackageIndex $ Map.update filterBucket name index where filterBucket = deleteEmptyBucket . filter (not . p) deleteEmptyBucket [] = Nothing deleteEmptyBucket remaining = Just remaining -- | Removes a single package from the index. -- deletePackageId :: Package pkg => PackageIdentifier -> PackageIndex pkg -> PackageIndex pkg deletePackageId pkgid = delete (packageName pkgid) (\pkg -> packageId pkg == pkgid) -- | Removes all packages with this (case-sensitive) name from the index. -- deletePackageName :: Package pkg => PackageName -> PackageIndex pkg -> PackageIndex pkg deletePackageName name = delete name (\pkg -> packageName pkg == name) -- -- * Bulk queries -- -- | Get all the packages from the index. -- allPackages :: Package pkg => PackageIndex pkg -> [pkg] allPackages (PackageIndex m) = concat (Map.elems m) -- | Get all the packages from the index. -- -- They are grouped by package name, case-sensitively. -- allPackagesByName :: Package pkg => PackageIndex pkg -> [[pkg]] allPackagesByName (PackageIndex m) = Map.elems m -- -- * Lookups -- -- | Does a lookup by package id (name & version). -- -- Since multiple package DBs mask each other case-sensitively by package name, -- then we get back at most one package. -- lookupPackageId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> Maybe pkg lookupPackageId index pkgid = case [ pkg | pkg <- lookup index (packageName pkgid) , packageId pkg == pkgid ] of [] -> Nothing [pkg] -> Just pkg _ -> internalError "lookupPackageIdentifier" -- | Does a case-sensitive search by package name. -- The returned list should be ordered (strictly ascending) by version number. -- lookupPackageName :: Package pkg => PackageIndex pkg -> PackageName -> [pkg] lookupPackageName index name = lookup index name -- | Search by name of a package identifier, and further select a version if possible. -- lookupPackageForId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> ([pkg], Maybe pkg) lookupPackageForId index pkgid = let pkgs = lookupPackageName index (packageName pkgid) in (,) pkgs $ find ((==pkgid) . packageId) pkgs -- | Does a case-sensitive search by package name and a range of versions. -- -- We get back any number of versions of the specified package name, all -- satisfying the version range constraint. -- lookupDependency :: Package pkg => PackageIndex pkg -> Dependency -> [pkg] lookupDependency index (Dependency name versionRange) = [ pkg | pkg <- lookup index name , packageName pkg == name , packageVersion pkg `withinRange` versionRange ] -- -- * Case insensitive name lookups -- -- | Does a case-insensitive search by package name. -- -- If there is only one package that compares case-insentiviely to this name -- then the search is unambiguous and we get back all versions of that package. -- If several match case-insentiviely but one matches exactly then it is also -- unambiguous. -- -- If however several match case-insentiviely and none match exactly then we -- have an ambiguous result, and we get back all the versions of all the -- packages. The list of ambiguous results is split by exact package name. So -- it is a non-empty list of non-empty lists. -- searchByName :: Package pkg => PackageIndex pkg -> String -> SearchResult [pkg] searchByName (PackageIndex m) name = case [ pkgs | pkgs@(PackageName name',_) <- Map.toList m , lowercase name' == lname ] of [] -> None [(_,pkgs)] -> Unambiguous pkgs pkgss -> case find ((PackageName name==) . fst) pkgss of Just (_,pkgs) -> Unambiguous pkgs Nothing -> Ambiguous (map snd pkgss) where lname = lowercase name data SearchResult a = None | Unambiguous a | Ambiguous [a] deriving (Show) -- | Does a case-insensitive substring search by package name. -- -- That is, all packages that contain the given string in their name. -- searchByNameSubstring :: Package pkg => PackageIndex pkg -> String -> [pkg] searchByNameSubstring (PackageIndex m) searchterm = [ pkg | (PackageName name, pkgs) <- Map.toList m , lsearchterm `isInfixOf` lowercase name , pkg <- pkgs ] where lsearchterm = lowercase searchterm -- | Gets the number of packages in the index (number of names). indexSize :: Package pkg => PackageIndex pkg -> Int indexSize (PackageIndex m) = Map.size m -- | The number of package versions -- (i.e., we should have @length . allPackages == numPackageVersions@) numPackageVersions ::PackageIndex pkg -> Int numPackageVersions (PackageIndex m) = sum . map (length . snd) $ Map.toList m -- | Get an ascending list of package names in the index. packageNames :: Package pkg => PackageIndex pkg -> [PackageName] packageNames (PackageIndex m) = Map.keys m ---------------------------------- State for PackageIndex instance (Package pkg, SafeCopy pkg) => SafeCopy (PackageIndex pkg) where putCopy index = contain $ do safePut $ allPackages index getCopy = contain $ do packages <- safeGet return $ fromList packages
ocharles/hackage-server
Distribution/Server/Packages/PackageIndex.hs
Haskell
bsd-3-clause
12,567
module Aws.Sqs.Commands ( module Aws.Sqs.Commands.Message, module Aws.Sqs.Commands.Permission, module Aws.Sqs.Commands.Queue, module Aws.Sqs.Commands.QueueAttributes ) where import Aws.Sqs.Commands.Message import Aws.Sqs.Commands.Permission import Aws.Sqs.Commands.Queue import Aws.Sqs.Commands.QueueAttributes
RayRacine/aws
Aws/Sqs/Commands.hs
Haskell
bsd-3-clause
320
<?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="az-AZ"> <title>Getting started Guide</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>İndeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Axtar</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>
ccgreen13/zap-extensions
src/org/zaproxy/zap/extension/gettingStarted/resources/help_az_AZ/helpset_az_AZ.hs
Haskell
apache-2.0
968
{-# OPTIONS_GHC -fglasgow-exts -O -ddump-simpl -fno-method-sharing #-} module Roman where import Control.Monad.ST newtype T s a = T { unT :: Int -> ST s a } instance Monad (T s) where return = T . const . return T p >>= f = T $ \i -> do { x <- p i ; unT (f x) i } myIndex :: T s Int {-# INLINE myIndex #-} myIndex = T return foo :: T s Int foo = do { x <- myIndex ; return (x + 1) } {- At one stage we got code looking like this: U.a3 = \ (@ s_a8E) (i_shA :: GHC.Base.Int) (eta_shB :: GHC.Prim.State# s_a8E) -> case ((((U.myIndex @ s_a8E) `cast` ...) i_shA) `cast` ...) eta_shB of wild_si5 { (# new_s_shF, r_shG #) -> ... U.foo :: forall s_a5S. U.T s_a5S GHC.Base.Int U.foo = U.a3 `cast` ... The point is that myIndex should be inlined, else code is bad -}
ezyang/ghc
testsuite/tests/eyeball/inline1.hs
Haskell
bsd-3-clause
916
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} -- | This holds the certificate authority (without the private key) module Types.CA where import Control.Lens import Data.Data (Data, Typeable) import Data.SafeCopy import Data.Text (Text) import Types.Common data CertificateAuthority = CA { _caSerialNumber :: SerialNumber -- ^ Current CA serial number. Updated with every signing , _caCertificate :: Text -- ^ The CA certificate without the private key. } deriving (Data, Typeable, Show) makeLenses ''CertificateAuthority $(deriveSafeCopy 0 'base ''CertificateAuthority)
tazjin/herbert
src/Types/CA.hs
Haskell
mit
733
module Spear.Math.Ray ( Ray(..) , raylr , rayfb ) where import Spear.Math.Utils import Spear.Math.Vector data Ray = Ray { origin :: {-# UNPACK #-} !Vector2 , dir :: {-# UNPACK #-} !Vector2 } -- | Classify the given point's position with respect to the given ray. Left/Right test. raylr :: Ray -> Vector2 -> Side raylr (Ray o d) p | orientation2d o (o+d) p < 0 = R | otherwise = L -- | Classify the given point's position with respect to the given ray. Front/Back test. rayfb :: Ray -> Vector2 -> Face rayfb (Ray o d) p | orientation2d o (perp d) p > 0 = F | otherwise = B
jeannekamikaze/Spear
Spear/Math/Ray.hs
Haskell
mit
650
module Numeric.LinearCombination ( LinearCombination(..) , Term(..) , multiplyUsing , operationUsing , basisChangeUsing , Numeric.LinearCombination.filter , find , elementsToList , scalarMult , zero , showUsing , simplify ) where import GHC.Exts (sortWith) import Data.AEq import Numeric (showGFloat) import qualified Data.List as L import Prelude hiding (filter) newtype LinearCombination coefficient element = LinComb [Term coefficient element] deriving (Eq) data Term coefficient element = coefficient :* element deriving (Eq, Show) instance (Num a) => Monad (Term a) where (c :* e) >>= f = (c * c') :* e' where (c' :* e') = f e return x = 1 :* x instance (Num a, AEq a, Eq b, Ord b) => Num (LinearCombination a b) where (LinComb terms) + (LinComb terms') = LinComb $ foldr addTerm short long where [short, long] = sortWith length [terms, terms'] negate = mapTerms (\(c :* e) -> (-c) :* e) (*) = error "Use the function `multiplyUsing` instead." abs = error "Absolute value not defined for LinearCombination." signum = error "Signum not defined for LinearCombination." fromInteger 0 = zero -- to allow sum fromInteger _ = error "Can't construct LinearCombination from integer." mapTerms :: (Num a, Eq b, Ord b) => (Term a b -> Term a b) -> LinearCombination a b -> LinearCombination a b mapTerms f (LinComb terms) = LinComb $ map f terms -- | Multiplies two 'LinearCombination's given a rule to multiply two elements. multiplyUsing :: (Num a, AEq a, Eq b, Ord b) => (b -> b -> Term a b) -> LinearCombination a b -> LinearCombination a b -> LinearCombination a b multiplyUsing op (LinComb xs) (LinComb ys) = simplify $ LinComb products where products = [(c1 * c2 * factor) :* e | (c1 :* e1) <- xs, (c2 :* e2) <- ys, let factor :* e = e1 `op` e2, factor /= 0] operationUsing :: (Num a, AEq a, Eq b, Ord b) => (b -> Term a b) -> LinearCombination a b -> LinearCombination a b operationUsing op = simplify . (mapTerms (>>= op)) basisChangeUsing :: (Num a, AEq a, Eq b, Ord b) => (b -> LinearCombination a b) -> LinearCombination a b -> LinearCombination a b basisChangeUsing op (LinComb terms) = sum $ map transform terms where transform (c :* e) = c `scalarMult` op e filter :: (Num a, AEq a, Eq b, Ord b) => (b -> Bool) -> LinearCombination a b -> LinearCombination a b filter p (LinComb terms) = LinComb $ L.filter (p . element) terms find :: (Num a, AEq a, Eq b, Ord b) => (b -> Bool) -> LinearCombination a b -> Maybe (Term a b) find p (LinComb terms) = L.find (p . element) terms elementsToList :: LinearCombination a b -> [b] elementsToList (LinComb terms) = map element terms element :: Term a b -> b element (c :* e) = e -- | Adds a Term to a list of Terms. addTerm :: (Num a, AEq a, Eq b, Ord b) => Term a b -> [Term a b] -> [Term a b] addTerm y [] = [y] addTerm y@(c1 :* e1) (x@(c2 :* e2):xs) | e1 == e2 = if c ~== 0 then xs else (c :* e1) : xs | e1 < e2 = y : x : xs | otherwise = x : addTerm y xs where c = c1 + c2 -- | Simplifies a LinearCombination so that each element only appears once by -- adding the coefficients of like elements. simplify :: (Num a, AEq a, Eq b, Ord b) => LinearCombination a b -> LinearCombination a b simplify (LinComb xs) = LinComb $ foldr addTerm [] xs -- | Multiplication by a scalar scalarMult :: (Num a, Eq b, Ord b) => a -> LinearCombination a b -> LinearCombination a b scalarMult x = mapTerms (\(c :* e) -> (x * c) :* e) zero :: LinearCombination a b zero = LinComb [] -- * Printing instance (Show a, Num a, AEq a, Ord a, Show b) => Show (LinearCombination a b) where show = showUsing show showUsing :: (Show a, Num a, AEq a, Ord a) => (b -> String) -> LinearCombination a b -> String showUsing _ (LinComb []) = "0" showUsing showElement (LinComb terms) = concat $ first : rest where first = showTerm True (head terms) rest = map (showTerm False) (tail terms) showTerm = showTermUsing showElement showTermUsing :: (Show a, Num a, AEq a, Ord a) => (b -> String) -> Bool -> Term a b -> String showTermUsing showElement first (c :* e) = sign ++ number ++ eString where sign | first = if c < 0 then "-" else "" | otherwise = if c < 0 then " - " else " + " number = if absc ~== 1 && eString /= "" then "" else absString absString = show absc--GFloat (Just 3) absc "" absc = abs c eString = showElement e instance (Num a, AEq a, Eq b) => AEq (LinearCombination a b) where (===) = (==) (LinComb terms) ~== (LinComb terms') = and $ zipWith (~==) terms terms' instance (Num a, AEq a, Eq b) => AEq (Term a b) where (===) = (==) (c :* e) ~== (c' :* e') = (c ~== c') && (e == e')
pnutus/geometric-algebra
src/Numeric/LinearCombination.hs
Haskell
mit
5,080
-- 1 take 1 $ map (+1) [undefined, 2, 3] -- ⊥ -- 2 take 1 $ map (+1) [1, undefined, 3] -- [2] -- 3 take 2 $ map (+1) [1, undefined, 3] -- ⊥ -- 4 -- itIsMystery takes string and return list of bools where True correspond to vowel and False to consonant for input string itIsMystery :: String -> [Bool] itIsMystery xs = map (\x -> elem x "aeiou") xs -- 5 map (^2) [1..10] -- [1,4,9,16,25,36,49,64,81,100] -- 6 import Data.Bool map (\x -> bool (x) (-x) (x == 3)) [1..10]
ashnikel/haskellbook
ch09/ch09.9_ex.hs
Haskell
mit
473
{-# LANGUAGE FlexibleContexts #-} module Helpers.Database where import Database.Groundhog import Database.Groundhog.Core import Database.Groundhog.Sqlite import Data.Proxy db :: Proxy Sqlite db = undefined intToKey :: (PrimitivePersistField (Key a b)) => Int -> Key a b intToKey p = integralToKey p integralToKey :: (PrimitivePersistField i, PrimitivePersistField (Key a b)) => i -> Key a b integralToKey = fromPrimitivePersistValue db . toPrimitivePersistValue db
archaeron/chatty-server
src/Helpers/Database.hs
Haskell
mit
471
{-# LANGUAGE QuasiQuotes #-} module AltParsing where import Control.Applicative import Text.Trifecta import Text.RawString.QQ type NumberOrString = Either Integer String parseNos :: Parser NumberOrString parseNos = skipMany (oneOf "\n") >> (Left <$> integer) <|> (Right <$> some letter) eitherOr :: String eitherOr = [r| 123 abc 456 def |]
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter24/AltParsing/src/AltParsing.hs
Haskell
mit
365
module Lab6 where import System.CPUTime import System.Random import Control.Monad import Lecture6 -- Exercise 1 -- Catches some edge cases and then use the exMsq to calculate squared modulo. exM :: Integer -> Integer -> Integer -> Integer exM b e m | e < 0 = 0 | e == 0 = 1 `mod` m | otherwise = exMsq b e m 1 -- Squaring -- Usage: exMsq b e m 1 exMsq :: Integer -> Integer -> Integer -> Integer -> Integer exMsq _ 0 _ r = r exMsq b e m r | odd e = exMsq b (e-1) m (mod (r*b) m) | otherwise = exMsq (mod (b*b) m) (div e 2) m r -- Memory-efficient method exMmem :: Integer -> Integer -> Integer -> Integer exMmem b 1 m = mod b m exMmem b e m = mod (b* exMmem b (e-1) m) m -- Exercise 2 -- Usage: testEx2 minRange maxRange testEx2 :: Integer -> Integer -> IO() testEx2 = randomFaster -- Generates a random test which compares both methods performance. randomFaster:: Integer -> Integer -> IO() randomFaster x y = do g <- newStdGen let (b, newGen) = randomR (x,y) g let (e, newGen') = randomR (x,y) newGen let (m, _) = randomR (x,y) newGen' faster b e m -- Given a base, exponent and modulus, it compares the performance of both methods. -- Time is in pico seconds. faster:: Integer -> Integer -> Integer -> IO () faster b e m = do print ("Comparison between the Ex1 method and lecture's method"::String) print ("Results are expressed in pico seconds."::String) x <- getDiffMsq b e m y <- getDiffDefault b e m r <- compareDiff x y if r then print ("--> Squaring method is faster"::String) else print ("--> Lecture's method is faster"::String) compareDiff:: Integer -> Integer -> IO Bool compareDiff x y = return (x < y) -- Calculates the execution time using the square method from the exercise 1. getDiffMsq:: Integer -> Integer -> Integer -> IO Integer getDiffMsq b e m = do start <- getCPUTime print ("Square method result: " ++ show (exMsq b e m 1)) end <- getCPUTime let diff = fromIntegral (end - start) print ("- Execution time: " ++ show diff) return diff -- Calculates the execution time using the default method from the lectures. getDiffDefault:: Integer -> Integer -> Integer -> IO Integer getDiffDefault b e m = do start <- getCPUTime print ("Lecture method result: " ++ show (expM b e m)) end <- getCPUTime let diff = fromIntegral (end - start) print ("- Execution time: " ++ show diff) return diff -- Exercise 3 -- The approach taken is fairly easy. Starting by the first known not prime number -- we generate a list filtering in not being prime using the function isPrime -- from the lectures. The function takes long time to compute if a number is -- prime, but in case it isn't it gives a result really fast. composites :: [Integer] composites = 4 : filter (not . isPrime) [5..] -- Exercise 4 -- Usage: testEx4 k -- Lowest found values for textEx k -- (k = 1) lowest found: 4 -- (k = 2) lowest found: 4 -- (k = 3) lowest found: 15 -- (k = 4) lowest found: 4 -- -- If you increase k the probability of fooling the test becomes smaller due to -- a larger number of random samples, However for low numbers the unique -- possible samples are quite small, for example for 4 there are only 3 samples. -- Namely : 1^3 mod 4, 2^3 mod 4 and 3^3 mod 4. One of which returns 1, which -- means that with k = 4 the chance of fooling the test is 1/3 ^ 4 == 1.23%. testEx4 :: Int -> IO() testEx4 k = do f <- foolFermat k print ("(k = " ++ show k ++ ") lowest found: " ++ show f) foolFermat :: Int -> IO Integer foolFermat k = lowestFermatFooler k composites lowestFermatFooler :: Int -> [Integer] -> IO Integer lowestFermatFooler _ [] = return 0 lowestFermatFooler k (x:xs) = do result <- prime_tests_F k x if result then return x else lowestFermatFooler k xs -- Exercise 5 -- Usage: testEx5 k -- We are going to test Fermant's primalty test using Carmichael's numbers. -- The first thing we do is to define a function to generate Carmichael's numbers. -- In this case, it is given in the description of the exercise. carmichael :: [Integer] carmichael = [ (6*k+1)*(12*k+1)*(18*k+1) | k <- [2..], isPrime (6*k+1), isPrime (12*k+1), isPrime (18*k+1) ] -- Test the first k Carmichael numbers using the Fermat's primalty test. We take -- the function prime_test_F from the lectures as our implementation of Fermat's -- primalty test. testFermatC :: Int -> IO [Bool] testFermatC k = mapM prime_test_F (take k carmichael) -- We also define a test using the Sieve of Erastothenes to check if the output -- of the Fermat's test is true. testIsPrime :: Int -> [Bool] testIsPrime k = map isPrime (take k carmichael) -- Finally, we output the solution. Carmichael numbers are quite big so the -- primalty check takes long time to compute. testEx5 :: Int -> IO() testEx5 k = do let num = take k carmichael print ("Test for the first " ++ show k ++ " Carmichael's numbers.") print ("Displays the result as a triple following the structure:"::String) print ("- (Carmichael number, (Fermat's test, Sieve of Erastothenes))"::String) ferm <- testFermatC k let eras = testIsPrime k let comb = zip num (zip ferm eras) print comb -- The output of the test deservers to be discussed. The Carmichael's numbers is -- derivated from Fermat's primalty test. Fermat's primalty test states that if -- p is prime, then a random number a not divisible by p fulfills -- a^(p-1) = 1 mod p. Carmichael numbers are composite numbers (as we can see in -- the function used to generate them) that pass Fermat's test but they are not -- prime. Indeed, those numbers p are not prime but coprimes with the chosen -- base a. This turns Fermat's test into a necessary condition but not sufficient: -- If a number is prime, it fulfills Fermat's theorem but if a number fulfills -- Fermat's theorem, it may not be prime as Carmichael numbers demostrate. -- The current formula used to calculate this numbers was proved by J. Chernick -- in 1939 and it produces Carmichael numbers as far as his 3 components are -- prime numbers. As the number is a Carmichael number, it should pass Fermat's -- test but fail on Erastothenes sieve. -- Exercise 6 -- Miller-Rabin testMR :: Int -> [Integer] -> IO () testMR k (p:ps) = do r <- primeMR k p when r $ print(show p ++ ", Miller-Rabin: " ++ show r) testMR k ps -- Test: testMR 1 carmichael, will take forever -- Test: testMR 1 (take 1000 carmichael) 118901521 Miller-Rabin:True, and -- probably many more but my processor fails. -- Conclusion: testER uses an iterator int k, and list of Carmichael numbers to -- test. Our test isn't consistent enough to write a solid conclusion, but they -- are hard to find and this fact make presume that using carmichael numbers the -- MR test is more difficult to fool. -- Mersenne mersnPrimes :: Integer -> IO () mersnPrimes p = do print(show p) let p1 = (2^p - 1) in do r <- primeMR 5 p1 when r $ mersnPrimes p1 --Test : mersnPrimes 5 --Test : mersnPrimes m3 "2147483647" (= m8: 2^31-1) --Conclusion: mersnPrimes takes a p (prime number) and check in primeMR -- searching for similarity. According with -- https://en.wikipedia.org/wiki/Mersenne_prime not all the numbers has pass the -- check are genuine Mersenne primes. -- Exercise 7
Gurrt/software-testing
week-6/Lab6.hs
Haskell
mit
7,815
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2018.M04.D04.Exercise where {-- So you have the data from the last two day's exercises, let's start storing those data into a PostgreSQL database. Today's exercise is to store just the authors. But there's a catch: you have to consider you're doing this as a daily upload. So: are there authors already stored? If so we don't store them, if not, we DO store them and get back the unique ID associated with those authors (for eventual storage in an article_author join table. First, fetch all the authors already stored (with, of course their unique ids) --} import Control.Monad.State import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.FromRow import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.ToField import Database.PostgreSQL.Simple.ToRow -- we will use previous techniques for memoizing tables: -- below imports available via 1HaskellADay git repository import Data.LookupTable import Data.MemoizingTable import Store.SQL.Connection import Store.SQL.Util.Indexed import Store.SQL.Util.LookupTable import Y2018.M04.D02.Exercise (readJSON, arts) import Y2018.M04.D03.Exercise (Author, authors) -- 1. fetch the authors into a LookupTable then convert that into a memoizing -- table state authorTableName :: String authorTableName = "author" lookupAuthors :: Connection -> IO LookupTable lookupAuthors conn = undefined type MemoizedAuthors m = MemoizingS m Integer Author () lk2MS :: Monad m => LookupTable -> MemoizedAuthors m lk2MS table = undefined -- 2. from yesterday's exercise, triage the authors into the memoizing table addNewAuthors :: [Author] -> MemoizedAuthors m addNewAuthors authors = undefined -- 3. store the new memoizing table values into the author table authorStmt :: Query authorStmt = [sql|INSERT INTO author (author) VALUES (?) returning id|] insertAuthors :: Connection -> MemoizedAuthors IO insertAuthors conn = undefined -- and there we go for today! Have at it!
geophf/1HaskellADay
exercises/HAD/Y2018/M04/D04/Exercise.hs
Haskell
mit
2,012
{-# LANGUAGE OverloadedStrings #-} -- -- | Test SQL queries using SQLite interpreter -- module Codex.Tester.Sql ( sqliteTester ) where import Codex.Tester import Control.Applicative ((<|>)) import Data.Maybe (fromMaybe) import qualified Data.Text as T import Data.List (sort) import Control.Exception (throwIO, catch) import System.FilePath (takeFileName) sqliteTester :: Tester Result sqliteTester = queryTester <|> updateTester -- -- | Tester for queries -- queryTester :: Tester Result queryTester = tester "sqlite-query" $ do Code lang query <- testCode guard (lang == "sql") --- limits <- configLimits "language.sqlite.limits" sqlite <- configured "language.sqlite.command" >>= parseArgs answer <- fromMaybe "" <$> metadata "answer" assert (pure $ answer /= "") "missing SQL query answer in metadata" dir <- takeDirectory <$> testFilePath inputs <- globPatterns dir =<< metadataWithDefault "databases" [] assert (pure $ not $ null inputs) "missing SQL databases metadata" ordering <- metadataWithDefault "ignore-order" False let normalize = if ordering then T.unlines . sort . T.lines else T.strip liftIO (runQueries limits sqlite answer query normalize inputs `catch` return) runQueries _ [] _ _ _ _ = throwIO $ userError "no SQLite command in config file" runQueries limits (sqlcmd:sqlargs) answer query normalize inputs = loop 1 inputs where total = length inputs runQuery db sql = do (exitCode, stdout, stderr) <- safeExec limits sqlcmd Nothing (sqlargs++["-init", db]) sql case exitCode of ExitSuccess -> -- NB: SQLite can exit with zero code in many errors, -- so we need to check stderr if match "Error" stderr then throwIO $ runtimeError stderr else return stdout ExitFailure _ -> throwIO $ runtimeError stderr --- loop _ [] = return $ accepted $ "Passed " <> T.pack (show total) <> " tests" loop n (db : rest) = do obtained <- runQuery db query expected <- runQuery db answer if normalize obtained == normalize expected then loop (n+1) rest else return $ wrongAnswer $ T.unlines [ "Test " <> T.pack (show n) <> " / " <> T.pack (show total) <> " using database " <> T.pack (takeFileName db) , "" , "EXPECTED:" , expected , "" , "OBTAINED:" , obtained ] -- -- | Tester for updates -- updateTester = tester "sqlite-update" $ do Code lang update <- testCode guard (lang == "sql") --- limits <- configLimits "language.sqlite.limits" sqlite <- configured "language.sqlite.command" >>= parseArgs sqldiff<- configured "language.sqlite.diff" >>= parseArgs answer <- metadataWithDefault "answer" "" assert (pure $ answer /= "") "missing SQL query answer in metadata" dir <- takeDirectory <$> testFilePath inputs <- globPatterns dir =<< metadataWithDefault "databases" [] assert (pure $ not $ null inputs) "missing SQL databases in metadata" liftIO (runUpdates limits sqlite sqldiff answer update inputs `catch` return) runUpdates _ [] _ _ _ _ = throwIO $ userError "no SQLite command in config file" runUpdates _ _ [] _ _ _ = throwIO $ userError "no SQLite diff command in config file" runUpdates limits (sqlite:args) (sqldiff:args') answer update inputs = loop 1 inputs where total = length inputs runDiff db1 db2 = do (exitCode, stdout, stderr) <- safeExec limits sqldiff Nothing (args' ++ [db1, db2]) "" case exitCode of ExitSuccess -> if match "Error" stderr then throwIO $ runtimeError stderr else return stdout ExitFailure _ -> throwIO $ runtimeError stderr runUpdate db sql file = do (exitCode, _, stderr) <- safeExec limits sqlite Nothing (args++["-init", db, file]) sql case exitCode of ExitSuccess -> -- NB: SQLite can exit with zero code in many errors, -- so we need to check stderr when (match "Error" stderr) $ throwIO $ runtimeError ("runUpdate: " <> stderr) ExitFailure _ -> throwIO $ runtimeError ("runUpdate: "<> stderr) --- loop _ [] = return $ accepted $ "Passed " <> T.pack (show total) <> " tests" loop n (db : rest) = do stdout <- withTemp "expected.db" "" $ \expectf -> withTemp "observed.db" "" $ \observef -> do chmod (readable . writeable) expectf chmod (readable . writeable) observef runUpdate db answer expectf runUpdate db update observef runDiff observef expectf if T.null stdout then loop (n+1) rest else throwIO $ wrongAnswer stdout
pbv/codex
src/Codex/Tester/Sql.hs
Haskell
mit
5,242
module Triplet (isPythagorean, mkTriplet, pythagoreanTriplets) where isPythagorean :: (Int, Int, Int) -> Bool isPythagorean (a, b, c) = a * a + b * b + c * c == 2 * m * m where m = maximum [a, b, c] mkTriplet :: Int -> Int -> Int -> (Int, Int, Int) mkTriplet a b c = (a, b, c) pythagoreanTriplets :: Int -> Int -> [(Int, Int, Int)] pythagoreanTriplets minFactor maxFactor = filter isPythagorean [(a, b, c) | a <- [minFactor..maxFactor], b <- [a..maxFactor], c <- [b..maxFactor]]
c19/Exercism-Haskell
pythagorean-triplet/src/Triplet.hs
Haskell
mit
484
import Test.Hspec import Control.Exception (evaluate) import qualified Data.Map.Strict as Map import Go import Go.UI.Color main :: IO () main = hspec $ do describe "Go.addMove" $ do it "adds a black stone to an empty board" $ do let point = Point (3, 4) Right game = addMove newGame point in (boardAt game point) `shouldBe` (Just Black) it "cannot add a stone to a place already taken" $ do let point = Point (3, 4) Right game = addMove newGame point in (addMove game point) `shouldBe` (Left "Invalid move") it "cannot add a stone to coordinates outside the board" $ do let point = Point (20, 4) in (addMove newGame point) `shouldBe` (Left "Invalid coordinates") it "removes a single dead stone" $ do let moves = ["d4", "d3", "pass", "d5", "pass", "c4", "pass", "e4"] game = addMoves moves newGame in boardAt game (Point (4, 4)) `shouldBe` Just Ko it "does not allow to set to a Ko point" $ do let moves = ["d4", "d3", "pass", "d5", "pass", "c4", "pass", "e4"] game = addMoves moves newGame in addMove game (Point (4, 4)) `shouldBe` Left "Invalid move" it "clears Ko after one move" $ do let moves = ["d4", "d3", "pass", "d5", "pass", "c4", "pass", "e4", "q16"] game = addMoves moves newGame in boardAt game (Point (4, 4)) `shouldBe` Nothing it "ends the game after second consecutive pass" $ do let moves = ["pass", "pass"] game = addMoves moves newGame in addMove game (Point (4, 4)) `shouldBe` Left "Game over" describe "Go.pass" $ do it "lets the player pass" $ do let Right (Game { moves = moves }) = pass newGame in moves `shouldBe` [Nothing] it "clears Ko after one pass" $ do let moves = ["d4", "d3", "pass", "d5", "pass", "c4", "pass", "e4", "pass"] game = addMoves moves newGame in boardAt game (Point (4, 4)) `shouldBe` Nothing it "ends the game after second consecutive pass" $ do let moves = ["pass", "pass"] game = addMoves moves newGame in pass game `shouldBe` Left "Game over" addMoves :: [String] -> Game -> Game addMoves [] game = game addMoves ("pass":moves) game = addMoves moves game' where Right game' = pass game addMoves ((x:y):moves) game = addMoves moves game' where y' = read y::Int Just x' = Map.lookup x coordLetters point = Point (x', y') Right game' = addMove game point
tsujigiri/gosh
spec/Spec.hs
Haskell
mit
2,748
module RandomForest where import Data.List import Numeric.LinearAlgebra import Predictor import Utils import CART type RandomForest = EnsembleLearner CART_Tree newtype EnsembleLearner learner = EL [learner] instance (Predictor l) => Predictor (EnsembleLearner l) where predict v (EL ls) = (sum' (map (predict v) ls))/(fromIntegral $ length ls) instance (Learner l) => Learner (EnsembleLearner l) where learn x y (EL ls) = fmap EL $ mapM (learn x y) ls new_ensemble f n = fmap EL $ mapM (const f) [1..n]
jvictor0/OnlineRandomForest
src/RandomForest.hs
Haskell
mit
518
-- Copyright 2015 Mitchell Kember. Subject to the MIT License. -- Project Euler: Problem 11 -- Summation of primes module Problem11 where import Data.Maybe (catMaybes) type Coord = (Int, Int) grid :: [[Int]] grid = [ [08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08] , [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00] , [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65] , [52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91] , [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80] , [24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50] , [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70] , [67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21] , [24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72] , [21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95] , [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92] , [16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57] , [86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58] , [19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40] , [04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66] , [88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69] , [04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36] , [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16] , [20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54] , [01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48] ] cell :: Coord -> Maybe Int cell (x, y) | inBounds = Just $ row !! x | otherwise = Nothing where row = grid !! y inBounds = x >= 0 && y >= 0 && y < length grid && x < length row move :: Coord -> Coord -> Coord move (x, y) (dx, dy) = (x + dx, y + dy) productsForCell :: Int -> Coord -> [Int] productsForCell n coord = catMaybes prods where slide delta = take n . iterate (move delta) $ coord multCells = fmap product . sequence . map cell directions = [(1, 0), (0, 1), (1, 1), (-1, 1)] prods = map (multCells . slide) directions solve :: Int solve = maximum . concatMap (productsForCell size) $ coords where size = 4 lastIdx = length grid - 1 coords = [(x, y) | x <- [0..lastIdx], y <- [0..lastIdx]]
mk12/euler
haskell/Problem11.hs
Haskell
mit
2,717
module Note.Character where import Control.Arrow import Control.Applicative hiding ( (<|>) ) import Control.Name import Data.List import Data.String.Utils import Data.Utils import Note import Text.ParserCombinators.Parsec import Text.ParserCombinators.TagWiki import Text.Pin ( fromName ) import qualified Control.Modifier as Mods import qualified Data.Set as Set newtype Character = Character { base :: Basic } deriving (Eq, Ord, Show) instance Note Character where basic = base -- | Adds prefixes and suffixes to tags. -- | Character names will be split on spaces, that they may be referenced -- | by either first or last or full names. -- | -- | If the character has multi-part names (i.e. "Van Halen"), escape the -- | whitespace (i.e. "Van\ Halen"). -- | -- | Only the first name is so split; all following names will not be touched. names c = alter (names $ basic c) where (ps, ss) = (prefixes &&& suffixes) c expand = addSuffixes ss . applyPrefixes ps . splitIntoNames alter (Name pri n:ns) = nub $ [Name pri x | x <- expand n] ++ ns alter [] = [] -- | The primary name is the prefixed and suffixed full name primaryName c = doHead "" expand $ map namePart $ names $ basic c where expand n = prefixString (prefixes c) ++ n ++ suffixString (suffixes c) -- | Updates a character to add 'nicknames' to the qualifiers. -- | Thus, if you have the following character: -- | -- | Fredward Sharpe, Freddie -- | -- | He may be referenced as (for example): -- | -- | |Fredward (Freddie) Sharpe| qualifiers c = qualifiers (basic c) `Set.union` extras where extras = Set.fromList $ map fromName $ drop 1 ns ns = names $ basic c -- | Of a character's tags, the first is the "full name" and the rest -- | are pseudonyms. Therefore, the first of a character's tags -- | will have the prefixes and suffixes applied, the rest will not. tags c = Set.fromList $ expand $ map namePart $ names $ basic c where expanded n = prefixString (prefixes c) ++ n ++ suffixString (suffixes c) expand (n:ns) = expanded n : ns expand [] = [] parseCharacter :: Int -> GenParser Char st Character parseCharacter i = Character <$> parseBasic i Mods.anyMod -- | Add all suffixes to each name. -- | Will be separated by spaces (unless the suffix starts with a comma) -- | For example, given the following character: -- | -- | Shane Cantlyn -- | $Jr. $, M.D. -- | -- | Yields the following names (in addition to the un-suffixed names) -- | -- | Shane Jr., M.D. -- | Cantlyn Jr., M.D. -- | Shane Cantlyn Jr., M.D. addSuffixes :: [String] -> [String] -> [String] addSuffixes [] xs = xs addSuffixes ss xs = xs ++ [x ++ suffixString ss | x <- xs] -- | Applies each prefix in turn to each string in turn -- | If a character has multiple names, the prefixes will not be applied -- | to the first (assumed informal) name. -- | -- | Only one prefix is applied at a time. So the following character: -- | -- | Shane Cantlyn -- | ^Dr. ^Fr. -- | -- | Yields the following names (in addition to the un-prefixed ones) -- | -- | Dr. Cantlyn, Fr. Cantlyn, Dr. Shane Cantlyn, Fr. Shane Cantlyn applyPrefixes :: [String] -> [String] -> [String] applyPrefixes _ [] = [] applyPrefixes ps [x] = x : [unwords [p, x] | p <- ps] applyPrefixes ps (x:ys) = x : ys ++ [unwords [p, y] | p <- ps, y <- ys] -- | Splits a name into the names that can be tagged, which include: -- | -- | First name, Last name, First & Last Name, All names splitIntoNames :: String -> [String] splitIntoNames s = let str = strip s in case parseNames str of [] -> [str] [x] -> [x] [x, y] -> [x, y, unwords [x, y]] xs -> [x, z, unwords [x, z], unwords xs] where x = head xs z = last xs -- | Combines a list of suffixes into one suffix, separating by space -- | except when the suffix starts with a comma suffixString :: [String] -> String suffixString = concatMap (prep . strip) where prep [] = [] prep trail@(',':_) = trail prep suffix = ' ':suffix -- | Like 'suffixString', for prefixes prefixString :: [String] -> String prefixString = concatMap (prep . strip) where prep prefix = if null prefix then "" else prefix ++ " " -- | Parse a name into names, respecting escaped whitespace -- | Return the original name on failure parseNames :: String -> [String] parseNames str = case parse namesParser str str of Left _ -> [str] Right ns -> ns namesParser :: GenParser Char st [String] namesParser = many1 (whitespace *> nameParser <* whitespace) nameParser :: GenParser Char st String nameParser = except " \t\""
Soares/tagwiki
src/Note/Character.hs
Haskell
mit
4,677
-- Take a number of items from the beginning of a list. module Take where import Prelude hiding (take) take :: Integer -> [t] -> [t] take _ [] = [] take numberOfItems list | numberOfItems < 0 = error "Negative number." | otherwise = take' numberOfItems list where take' 0 _ = [] take' numberOfItems (listItem : remainingListItems) = listItem : (take' (numberOfItems - 1) remainingListItems) {- GHCi> take 1 [] take 0 [1] take 1 [1] take (-1) [1] take 1 [1, 2] take 2 [1, 2] take 2 [1, 2, 3] -} -- [] -- [] -- [1] -- *** Exception: Negative number. -- [1] -- [1, 2] -- [1, 2]
pascal-knodel/haskell-craft
Examples/· Recursion/· Primitive Recursion/Lists/Take.hs
Haskell
mit
630
module ScoreToLilypond.UtilsTest where import Data.ByteString.Builder import Data.Either.Combinators (fromRight') import Data.Ratio import qualified Data.Set as Set import Music.RealSimpleMusic.Music.Data import Music.RealSimpleMusic.Music.Utils import Music.RealSimpleMusic.ScoreToLilypond.Utils import Test.HUnit testAccentNames :: Assertion testAccentNames = fromEnum (maxBound::Accent) @=? length accentValues testRenderPitchOctaves :: Assertion testRenderPitchOctaves = map (toLazyByteString . stringEncoding) ["c'", "c''", "c'''", "c", "c,", "c,,"] @=? map (toLazyByteString . renderPitch) [Pitch C (Octave octave) | octave <- [0, 1, 2, -1, -2, -3]] testRenderPitchAccidentals :: Assertion testRenderPitchAccidentals = map (toLazyByteString . stringEncoding) ["c", "ces", "ceses", "cis", "cisis"] @=? map (toLazyByteString . renderPitch) [Pitch pc (Octave (-1)) | pc <- [C, Cf, Cff, Cs, Css]] testRenderRhythmBase :: Assertion testRenderRhythmBase = (map . map) (toLazyByteString . stringEncoding) [["1"], ["2"], ["4"], ["8"], ["16"], ["32"], ["64"]] @=? map (map toLazyByteString . renderRhythm . fromRight' . mkRhythm) [1%1, 1%2, 1%4, 1%8, 1%16, 1%32, 1%64] testRenderRhythmDots :: Assertion testRenderRhythmDots = (map . map) (toLazyByteString . stringEncoding) [["1."], ["2."], ["4."], ["8."], ["16."], ["32."], ["64."]] @=? map (map toLazyByteString . renderRhythm . fromRight' . mkRhythm) [3%2, 3%4, 3%8, 3%16, 3%32, 3%64, 3%128] testRenderRhythmTies :: Assertion testRenderRhythmTies = (map . map) (toLazyByteString . stringEncoding) [["1", "4"], ["1", "2."], ["1", "1", "4"], ["2", "8"], ["2."]] @=? map (map toLazyByteString . renderRhythm . fromRight' . mkRhythm) [5%4, 7%4, 9%4, 5%8, 6%8] renderNote' :: Note -> Builder renderNote' note = renderedNote where (_, _, renderedNote) = renderNote (False, False) note testRenderNote :: Assertion testRenderNote = (toLazyByteString . stringEncoding) "c'64" @=? (toLazyByteString . renderNote') (Note (Pitch C (Octave 0)) ((fromRight' . mkRhythm) (1%64)) Set.empty) testRenderAccentedNote :: Assertion testRenderAccentedNote = (toLazyByteString . stringEncoding) "d'32\\verysoft" @=? (toLazyByteString . renderNote') (Note (Pitch D (Octave 0)) ((fromRight'. mkRhythm) (1%32)) (Set.singleton (AccentControl VerySoft))) testRenderRest :: Assertion testRenderRest = (toLazyByteString . stringEncoding) "r64" @=? (toLazyByteString . renderNote') (Rest (fromRight' (mkRhythm (1%64))) Set.empty) testRenderPercussionNote :: Assertion testRenderPercussionNote = (toLazyByteString . stringEncoding) "c64" @=? (toLazyByteString . renderNote') (PercussionNote (fromRight' (mkRhythm (1%64))) Set.empty) testRenderAccentedPercussionNote :: Assertion testRenderAccentedPercussionNote = (toLazyByteString . stringEncoding) "c32\\hard" @=? (toLazyByteString . renderNote') (PercussionNote (fromRight' (mkRhythm (1%32))) (Set.singleton (AccentControl Hard))) testRenderTiedNote :: Assertion testRenderTiedNote = (toLazyByteString . stringEncoding) "c'1~ c'4" @=? (toLazyByteString . renderNote') (Note (Pitch C (Octave 0)) (fromRight' (mkRhythm (5%4))) Set.empty) testRenderNotes :: Assertion testRenderNotes = (toLazyByteString . stringEncoding) "c8 d16 e32 f64 g128 a64 b32" @=? (toLazyByteString . renderNotes) (zipWith (\pc dur -> Note (Pitch pc (Octave (-1))) (fromRight' (mkRhythm dur)) Set.empty) (ascendingScale (fromRight' (majorScale C))) [1%8, 1%16, 1%32, 1%64, 1%128, 1%64, 1%32]) -- Fractional Dynamic Voice. Mix of -- a) tied whole notes of varying durations with fractional dynamics that include crescendo and decrescendo -- b) quarter note with discrete dyanmic -- c) tied whole notes of varying durations with fractional dynamics that consist of a series of discrete dynamics -- d) instrument should be a sustained instrument -- TBD: when units add up to 3 things go badly wrong, e.g. "s3" in Lilypond, where the duration has to be power of 2. d1, d2, d3, d4 :: Dynamic d1 = FractionalDynamic [(Crescendo,1),(Fortissimo,0),(Decrescendo,1),(Piano,0)] -- must not be first dynamic, needs dynamic to start crescendo d2 = FractionalDynamic [(Fortissimo,1),(Piano,1),(MezzoForte,1),(MezzoPiano,1)] d3 = DiscreteDynamic MezzoPiano d4 = DiscreteDynamic MezzoForte p1, p2, p3, p4 :: Pitch p1 = Pitch C (Octave 0) p2 = Pitch A (Octave 0) p3 = Pitch D (Octave (-1)) p4 = Pitch G (Octave (-2)) rhythm :: Rhythm rhythm = fromRight' (mkRhythm (4%1)) np1d1, np1d3, np1d2, np2d1, np2d2, np2d3, np2d4, np3d3, np3d2, np3d4, np4d1, np4d2, np4d4 :: Note np1d1 = Note p1 rhythm (Set.singleton (DynamicControl d1)) np1d3 = Note p1 rhythm (Set.singleton (DynamicControl d3)) np1d2 = Note p1 rhythm (Set.singleton (DynamicControl d2)) np2d1 = Note p2 rhythm (Set.singleton (DynamicControl d1)) np2d2 = Note p2 rhythm (Set.singleton (DynamicControl d2)) np2d3 = Note p2 rhythm (Set.singleton (DynamicControl d3)) np2d4 = Note p2 rhythm (Set.singleton (DynamicControl d4)) np3d3 = Note p3 rhythm (Set.singleton (DynamicControl d3)) np3d4 = Note p3 rhythm (Set.singleton (DynamicControl d4)) np3d2 = Note p3 rhythm (Set.singleton (DynamicControl d2)) np4d4 = Note p4 rhythm (Set.singleton (DynamicControl d4)) np4d1 = Note p4 rhythm (Set.singleton (DynamicControl d1)) np4d2 = Note p4 rhythm (Set.singleton (DynamicControl d2)) -- Fractional Dynamics: validate by inspection of rendered results. -- For Midi, open in editor and check alignment of dynamic events. -- For Lilypond view score and verify alignment of dynamic events. genFractDyn :: Score genFractDyn = Score "GenFractDynTest" "Test" controls voices where controls = ScoreControls (KeySignature 0) (TimeSignature 4 4) [(Tempo (TempoVal Quarter 120), fromRight' (mkRhythm (0%4)))] voices = [ Voice (Instrument "Trombone") [np1d3,np1d1,np1d2] , Voice (Instrument "Trombone") [np2d3,np2d2,np3d4] , Voice (Instrument "Trombone") [np3d3,np3d2,np4d2] , Voice (Instrument "Trombone") [np4d4,np4d1,np2d4]]
tomtitchener/RealSimpleMusic
tests/ScoreToLilypond/UtilsTest.hs
Haskell
cc0-1.0
6,069
{-# OPTIONS_GHC -Wall #-} import Control.Monad (void) import Test.HUnit import CreditCard digitsTest1, digitsTest2, digitsTest3, digitsTest4 :: Test digitsTest1 = TestCase $ assertEqual "in digits decomposition" [1,2,3,4] (toDigits 1234) digitsTest2 = TestCase $ assertEqual "in reverse digits decomposition" [4,3,2,1] (toDigitsRev 1234) digitsTest3 = TestCase $ assertEqual "in zero decomposition" [] (toDigits 0) digitsTest4 = TestCase $ assertEqual "in negative number decomposition" [] (toDigits (-2014)) doublingTest1, doublingTest2 :: Test doublingTest1 = TestCase $ assertEqual "in every-other doubling of even-length list" [16,7,12,5] (doubleEveryOther [8,7,6,5]) doublingTest2 = TestCase $ assertEqual "in every-other doubling of odd-length list" [1,4,3] (doubleEveryOther [1,2,3]) sumTest :: Test sumTest = TestCase $ assertEqual "in sum of digits" 22 (sumDigits [16,7,12,5]) validationTest1, validationTest2 :: Test validationTest1 = TestCase $ assertBool "in validation of valid input" (validate 4012888888881881) validationTest2 = TestCase $ assertBool "in validation of invalid input" (not (validate 4012888888881882)) tests :: Test tests = TestList [ TestLabel "number to digits decomposition" $ TestList [ digitsTest1 , digitsTest2 , digitsTest3 , digitsTest4 ] , TestLabel "doubling routine" $ TestList [ doublingTest1 , doublingTest2 ] , TestLabel "sum of digits" $ sumTest , TestLabel "number validation" $ TestList [ validationTest1 , validationTest2 ] ] main :: IO () main = void $ runTestTT tests
mgrabovsky/upenn-cis194
hw01/testCreditCard.hs
Haskell
cc0-1.0
1,819
{-# LANGUAGE FlexibleInstances #-} -- | The RLP module provides a framework within which serializers can be built, described in the Ethereum Yellowpaper (<http://gavwood.com/paper.pdf>). -- -- The 'RLPObject' is an intermediate data container, whose serialization rules are well defined. By creating code that converts from a -- given type to an 'RLPObject', full serialization will be specified. The 'RLPSerializable' class provides functions to do this conversion. module Blockchain.Data.RLP ( RLPObject(..) , formatRLPObject , RLPSerializable(..) , rlpSplit , rlpSerialize , rlpDeserialize ) where import Data.Bits import qualified Data.ByteString as B import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Char8 as BC import Data.ByteString.Internal import Data.Word import Numeric import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import Blockchain.Data.Util -- | An internal representation of generic data, with no type information. -- -- End users will not need to directly create objects of this type (an 'RLPObject' can be created using 'rlpEncode'), -- however the designer of a new type will need to create conversion code by making their type an instance -- of the RLPSerializable class. data RLPObject = RLPScalar Word8 | RLPString B.ByteString | RLPArray [RLPObject] deriving (Show, Eq, Ord) -- | Converts objects to and from 'RLPObject's. class RLPSerializable a where rlpDecode :: RLPObject -> a rlpEncode :: a -> RLPObject instance Pretty RLPObject where pretty (RLPArray objects) = encloseSep (text "[") (text "]") (text ", ") $ pretty <$> objects pretty (RLPScalar n) = text $ "0x" ++ showHex n "" pretty (RLPString s) = text $ "0x" ++ BC.unpack (B16.encode s) formatRLPObject :: RLPObject -> String formatRLPObject = show . pretty splitAtWithError :: Int -> B.ByteString -> (B.ByteString, B.ByteString) splitAtWithError i s | i > B.length s = error "splitAtWithError called with n > length arr" splitAtWithError i s = B.splitAt i s getLength :: Int -> B.ByteString -> (Integer, B.ByteString) getLength sizeOfLength bytes = ( bytes2Integer $ B.unpack $ B.take sizeOfLength bytes , B.drop sizeOfLength bytes) rlpSplit :: B.ByteString -> (RLPObject, B.ByteString) rlpSplit input = case B.head input of x | x >= 192 && x <= 192 + 55 -> let (arrayData, nextRest) = splitAtWithError (fromIntegral x - 192) $ B.tail input in (RLPArray $ getRLPObjects arrayData, nextRest) x | x >= 0xF8 && x <= 0xFF -> let (arrLength, restAfterLen) = getLength (fromIntegral x - 0xF7) $ B.tail input (arrayData, nextRest) = splitAtWithError (fromIntegral arrLength) restAfterLen in (RLPArray $ getRLPObjects arrayData, nextRest) x | x >= 128 && x <= 128 + 55 -> let (strList, nextRest) = splitAtWithError (fromIntegral $ x - 128) $ B.tail input in (RLPString strList, nextRest) x | x >= 0xB8 && x <= 0xBF -> let (strLength, restAfterLen) = getLength (fromIntegral x - 0xB7) $ B.tail input (strList, nextRest) = splitAtWithError (fromIntegral strLength) restAfterLen in (RLPString strList, nextRest) x | x < 128 -> (RLPScalar x, B.tail input) x -> error ("Missing case in rlpSplit: " ++ show x) getRLPObjects :: ByteString -> [RLPObject] getRLPObjects x | B.null x = [] getRLPObjects theData = obj : getRLPObjects rest where (obj, rest) = rlpSplit theData int2Bytes :: Int -> [Word8] int2Bytes val | val < 0x100 = map (fromIntegral . (val `shiftR`)) [0] int2Bytes val | val < 0x10000 = map (fromIntegral . (val `shiftR`)) [8, 0] int2Bytes val | val < 0x1000000 = map (fromIntegral . (val `shiftR`)) [16, 8, 0] int2Bytes val | val < 0x100000000 = map (fromIntegral . (val `shiftR`)) [24,16 .. 0] int2Bytes val | val < 0x10000000000 = map (fromIntegral . (val `shiftR`)) [32,24 .. 0] int2Bytes _ = error "int2Bytes not defined for val >= 0x10000000000." rlp2Bytes :: RLPObject -> [Word8] rlp2Bytes (RLPScalar val) = [fromIntegral val] rlp2Bytes (RLPString s) | B.length s <= 55 = 0x80 + fromIntegral (B.length s) : B.unpack s rlp2Bytes (RLPString s) = [0xB7 + fromIntegral (length lengthAsBytes)] ++ lengthAsBytes ++ B.unpack s where lengthAsBytes = int2Bytes $ B.length s rlp2Bytes (RLPArray innerObjects) = if length innerBytes <= 55 then 0xC0 + fromIntegral (length innerBytes) : innerBytes else let lenBytes = int2Bytes $ length innerBytes in [0xF7 + fromIntegral (length lenBytes)] ++ lenBytes ++ innerBytes where innerBytes = concat $ rlp2Bytes <$> innerObjects --TODO- Probably should just use Data.Binary's 'Binary' class for this -- | Converts bytes to 'RLPObject's. -- -- Full deserialization of an object can be obtained using @rlpDecode . rlpDeserialize@. rlpDeserialize :: B.ByteString -> RLPObject rlpDeserialize s = case rlpSplit s of (o, x) | B.null x -> o _ -> error ("parse error converting ByteString to an RLP Object: " ++ show (B.unpack s)) -- | Converts 'RLPObject's to bytes. -- -- Full serialization of an object can be obtained using @rlpSerialize . rlpEncode@. rlpSerialize :: RLPObject -> B.ByteString rlpSerialize o = B.pack $ rlp2Bytes o instance RLPSerializable Integer where rlpEncode 0 = RLPString B.empty rlpEncode x | x < 128 = RLPScalar $ fromIntegral x rlpEncode x = RLPString $ B.pack $ integer2Bytes x rlpDecode (RLPScalar x) = fromIntegral x rlpDecode (RLPString s) = byteString2Integer s rlpDecode (RLPArray _) = error "rlpDecode called for Integer for array" instance RLPSerializable String where rlpEncode s = rlpEncode $ BC.pack s rlpDecode (RLPString s) = BC.unpack s rlpDecode (RLPScalar n) = [w2c $ fromIntegral n] rlpDecode (RLPArray x) = error $ "Malformed RLP in call to rlpDecode for String: RLPObject is an array: " ++ show (pretty x) instance RLPSerializable B.ByteString where rlpEncode x | B.length x == 1 && B.head x < 128 = RLPScalar $ B.head x rlpEncode s = RLPString s rlpDecode (RLPScalar x) = B.singleton x rlpDecode (RLPString s) = s rlpDecode x = error ("rlpDecode for ByteString not defined for: " ++ show x)
zchn/ethereum-analyzer
ethereum-analyzer-deps/src/Blockchain/Data/RLP.hs
Haskell
apache-2.0
6,324
{-# LANGUAGE ScopedTypeVariables #-} {- HSStructMain.hs Copyright 2014 Sebastien Soudan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Main where import qualified AVLTree import qualified BSTree import qualified BatchedQueue import qualified BatchedDequeue import qualified Dequeue import qualified Queue import Data.Digest.Murmur32 import Microbench import Graph import RDG buildBatchedQueue :: Int -> BatchedQueue.BatchedQueue Integer buildBatchedQueue n = let rs = [ (toInteger . asWord32 . hash32) m | m <- [1..n] ] in BatchedQueue.buildBatchedQueue rs buildBatchedDequeue :: Int -> BatchedDequeue.BatchedDequeue Integer buildBatchedDequeue n = let rs = [ (toInteger . asWord32 . hash32) m | m <- [1..n] ] in BatchedDequeue.buildBatchedDequeue rs buildAVLTree :: Int -> AVLTree.AVLTree Integer buildAVLTree n = let rs = [ (toInteger . asWord32 . hash32) m | m <- [1..n] ] in AVLTree.buildTree rs searchAVLTree :: AVLTree.AVLTree Integer -> Int -> Integer searchAVLTree tree n = let rs = [ (toInteger . asWord32 . hash32) m | m <- [500000..n] ] (a,b) = span (`AVLTree.elemTree` tree) rs in sum a + sum b buildBSTree :: Int -> BSTree.BSTree Integer buildBSTree n = let rs = [ (toInteger . asWord32 . hash32) m | m <- [1..n] ] in BSTree.buildTree rs searchBSTree :: BSTree.BSTree Integer -> Int -> Integer searchBSTree tree n = let rs = [ (toInteger . asWord32 . hash32) m | m <- [500000..n] ] (a,b) = span (`BSTree.elemTree` tree) rs in sum a + sum b connectedCompF = let g = buildGraph ["A", "B", "C"] [("A", "B", "AB"), ("B", "C", "BC")] cc = connectedComp g v = Prelude.map vertexData $ vertices cc in v main :: IO () main = do putStrLn "Testing performance of 'buildTree'" microbench "buildAVLTree " buildAVLTree microbench "buildBSTree " buildAVLTree putStrLn "Testing performance of 'elemTree' in pre-built trees" let rs = [ (toInteger . asWord32 . hash32) m | (m :: Integer) <- [1..1000000] ] avltree = AVLTree.buildTree rs bstree = BSTree.buildTree rs putStrLn $ "AVLTree size: " ++ show (AVLTree.size avltree) putStrLn $ "BSTree size: " ++ show (BSTree.size bstree) microbench "searchAVLTree " $ searchAVLTree avltree microbench "searchBSTree " $ searchBSTree bstree ---- putStrLn "Testing performance of 'buildQueue'" microbench "buildBatchedQueue " buildBatchedQueue putStrLn "Testing performance of 'head' in pre-built queue" let rs = [ (toInteger . asWord32 . hash32) m | (m :: Integer) <- [1..1000000] ] batchedQueue = BatchedQueue.buildBatchedQueue rs putStrLn $ "BatchedQueue size: " ++ show (Queue.size batchedQueue) --microbench "BatchedQueue.head " $ Queue.head batchedQueue ---- putStrLn "Testing performance of 'buildDequeue'" microbench "buildBatchedDequeue " buildBatchedDequeue putStrLn "Testing performance of 'head' in pre-built dequeue" let rs = [ (toInteger . asWord32 . hash32) m | (m :: Integer) <- [1..1000000] ] batchedDequeue = BatchedDequeue.buildBatchedDequeue rs putStrLn $ "BatchedDequeue size: " ++ show (Dequeue.size batchedDequeue) --microbench "BatchedDequeue.head " $ Dequeue.head batchedDequeue putStrLn $ "connected comp: " ++ show (connectedCompF)
ssoudan/hsStruct
src/HSStructMain.hs
Haskell
apache-2.0
4,013
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTextCursor.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:35 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QTextCursor ( MoveMode, eMoveAnchor, eKeepAnchor , MoveOperation, eNoMove, eStart, eStartOfLine, eStartOfBlock, eStartOfWord, ePreviousBlock, ePreviousCharacter, ePreviousWord, eWordLeft, eEndOfLine, eEndOfWord, eEndOfBlock, eNextBlock, eNextCharacter, eNextWord, eWordRight , SelectionType, eWordUnderCursor, eLineUnderCursor, eBlockUnderCursor, eDocument ) where import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CMoveMode a = CMoveMode a type MoveMode = QEnum(CMoveMode Int) ieMoveMode :: Int -> MoveMode ieMoveMode x = QEnum (CMoveMode x) instance QEnumC (CMoveMode Int) where qEnum_toInt (QEnum (CMoveMode x)) = x qEnum_fromInt x = QEnum (CMoveMode x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> MoveMode -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eMoveAnchor :: MoveMode eMoveAnchor = ieMoveMode $ 0 eKeepAnchor :: MoveMode eKeepAnchor = ieMoveMode $ 1 data CMoveOperation a = CMoveOperation a type MoveOperation = QEnum(CMoveOperation Int) ieMoveOperation :: Int -> MoveOperation ieMoveOperation x = QEnum (CMoveOperation x) instance QEnumC (CMoveOperation Int) where qEnum_toInt (QEnum (CMoveOperation x)) = x qEnum_fromInt x = QEnum (CMoveOperation x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> MoveOperation -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eNoMove :: MoveOperation eNoMove = ieMoveOperation $ 0 eStart :: MoveOperation eStart = ieMoveOperation $ 1 instance QeUp MoveOperation where eUp = ieMoveOperation $ 2 eStartOfLine :: MoveOperation eStartOfLine = ieMoveOperation $ 3 eStartOfBlock :: MoveOperation eStartOfBlock = ieMoveOperation $ 4 eStartOfWord :: MoveOperation eStartOfWord = ieMoveOperation $ 5 ePreviousBlock :: MoveOperation ePreviousBlock = ieMoveOperation $ 6 ePreviousCharacter :: MoveOperation ePreviousCharacter = ieMoveOperation $ 7 ePreviousWord :: MoveOperation ePreviousWord = ieMoveOperation $ 8 instance QeLeft MoveOperation where eLeft = ieMoveOperation $ 9 eWordLeft :: MoveOperation eWordLeft = ieMoveOperation $ 10 instance QeEnd MoveOperation where eEnd = ieMoveOperation $ 11 instance QeDown MoveOperation where eDown = ieMoveOperation $ 12 eEndOfLine :: MoveOperation eEndOfLine = ieMoveOperation $ 13 eEndOfWord :: MoveOperation eEndOfWord = ieMoveOperation $ 14 eEndOfBlock :: MoveOperation eEndOfBlock = ieMoveOperation $ 15 eNextBlock :: MoveOperation eNextBlock = ieMoveOperation $ 16 eNextCharacter :: MoveOperation eNextCharacter = ieMoveOperation $ 17 eNextWord :: MoveOperation eNextWord = ieMoveOperation $ 18 instance QeRight MoveOperation where eRight = ieMoveOperation $ 19 eWordRight :: MoveOperation eWordRight = ieMoveOperation $ 20 data CSelectionType a = CSelectionType a type SelectionType = QEnum(CSelectionType Int) ieSelectionType :: Int -> SelectionType ieSelectionType x = QEnum (CSelectionType x) instance QEnumC (CSelectionType Int) where qEnum_toInt (QEnum (CSelectionType x)) = x qEnum_fromInt x = QEnum (CSelectionType x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> SelectionType -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eWordUnderCursor :: SelectionType eWordUnderCursor = ieSelectionType $ 0 eLineUnderCursor :: SelectionType eLineUnderCursor = ieSelectionType $ 1 eBlockUnderCursor :: SelectionType eBlockUnderCursor = ieSelectionType $ 2 eDocument :: SelectionType eDocument = ieSelectionType $ 3
uduki/hsQt
Qtc/Enums/Gui/QTextCursor.hs
Haskell
bsd-2-clause
7,402
-- -- Copyright 2014, NICTA -- -- This software may be distributed and modified according to the terms of -- the BSD 2-Clause license. Note that NO WARRANTY is provided. -- See "LICENSE_BSD2.txt" for details. -- -- @TAG(NICTA_BSD) -- -- Printer for C source format to be consumed by the CapDL initialiser. -- Note: corresponds to the -c/--code argument. module CapDL.PrintC where import CapDL.Model import Control.Exception (assert) import Data.List import Data.List.Ordered import Data.List.Utils import Data.Maybe (fromJust, fromMaybe) import Data.Word import Data.Map as Map import Data.Set as Set import Data.String.Utils (rstrip) import Data.Bits import Numeric (showHex) import Text.PrettyPrint (∈) = Set.member indent :: String -> String indent s = rstrip $ unlines $ Prelude.map (\a -> " " ++ a) $ lines s (+++) :: String -> String -> String s1 +++ s2 = s1 ++ "\n" ++ s2 hex :: Word -> String hex x = "0x" ++ showHex x "" maxObjects :: Int -> String maxObjects count = "#define MAX_OBJECTS " ++ show count memberArch :: Arch -> String memberArch IA32 = ".arch = CDL_Arch_IA32," memberArch ARM11 = ".arch = CDL_Arch_ARM," memberNum :: Int -> String memberNum n = ".num = " ++ show n ++ "," showObjID :: Map ObjID Int -> ObjID -> String showObjID xs id = (case Map.lookup id xs of Just w -> show w _ -> "INVALID_SLOT") ++ " /* " ++ fst id ++ " */" showRights :: CapRights -> String showRights rights = prefix ++ r ++ w ++ g where prefix = if Set.null rights then "0" else "CDL_" r = if Read ∈ rights then "R" else "" w = if Write ∈ rights then "W" else "" g = if Grant ∈ rights then "G" else "" showPorts :: Set Word -> String showPorts ports = show ((.|.) (shift start 16) end) where start = Set.findMin ports end = Set.findMax ports showPCI :: Word -> (Word, Word, Word) -> String showPCI domainID (pciBus, pciDev, pciFun) = hex $ shift domainID 16 .|. shift pciBus 8 .|. shift pciDev 3 .|. pciFun -- Lookup-by-value on a dictionary. I feel like I need a shower. lookupByValue :: Ord k => (a -> Bool) -> Map k a -> k lookupByValue f m = head $ keys $ Map.filter f m showCap :: Map ObjID Int -> Cap -> IRQMap -> String -> ObjMap Word -> String showCap _ NullCap _ _ _ = "{.type = CDL_NullCap}" showCap objs (UntypedCap id) _ _ _ = "{.type = CDL_UntypedCap, .obj_id = " ++ showObjID objs id ++ "}" showCap objs (EndpointCap id badge rights) _ is_orig _ = "{.type = CDL_EPCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ ", .rights = " ++ showRights rights ++ ", .data = { .tag = seL4_CapData_Badge, .badge = " ++ show badge ++ "}}" showCap objs (AsyncEndpointCap id badge rights) _ is_orig _ = "{.type = CDL_AEPCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ ", .rights = " ++ showRights rights ++ ", .data = { .tag = seL4_CapData_Badge, .badge = " ++ show badge ++ "}}" showCap objs (ReplyCap id) _ _ _ = "{.type = CDL_ReplyCap, .obj_id = " ++ showObjID objs id ++ "}" -- XXX: Does it even make sense to give out a reply cap? How does init fake this? showCap objs (MasterReplyCap id) _ _ _ = "{.type = CDL_MasterReplyCap, .obj_id = " ++ showObjID objs id ++ "}" -- XXX: As above. showCap objs (CNodeCap id guard guard_size) _ is_orig _ = "{.type = CDL_CNodeCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ ", .rights = CDL_RWG, .data = CDL_CapData_MakeGuard(" ++ show guard_size ++ ", " ++ show guard ++ ")}" showCap objs (TCBCap id) _ is_orig _ = "{.type = CDL_TCBCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ ", .rights = CDL_RWG}" showCap _ IRQControlCap _ _ _ = "{.type = CDL_IRQControlCap}" showCap objs (IRQHandlerCap id) irqNode is_orig _ = "{.type = CDL_IRQHandlerCap, .obj_id = INVALID_OBJ_ID" ++ ", .is_orig = " ++ is_orig ++ ", .irq = " ++ show (lookupByValue (\x -> x == id) irqNode) ++ "}" -- Caps have obj_ids, or IRQs, but not both. showCap objs (FrameCap id rights _ cached) _ is_orig _ = "{.type = CDL_FrameCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ ", .rights = " ++ showRights rights ++ ", .vm_attribs = " ++ (if cached then "seL4_Default_VMAttributes" else "CDL_VM_CacheDisabled") ++ "}" -- FIXME: I feel like I should be doing something with the ASID data here... showCap objs (PTCap id _) _ is_orig _ = "{.type = CDL_PTCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ "}" showCap objs (PDCap id _) _ is_orig _ = "{.type = CDL_PDCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ "}" showCap _ ASIDControlCap _ _ _ = "{.type = CDL_ASIDControlCap}" showCap objs (ASIDPoolCap id _) _ is_orig _ = "{.type = CDL_ASIDPoolCap, .obj_id = " ++ showObjID objs id ++ "}" showCap objs (IOPortsCap id ports) _ is_orig _ = "{.type = CDL_IOPortsCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ ", .data = { .tag = CDL_CapData_Raw, .data = " ++ showPorts ports ++ "}}" showCap objs (IOSpaceCap id) _ is_orig ms = "{.type = CDL_IOSpaceCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ ", .data = { .tag = CDL_CapData_Raw, .data = " ++ showPCI dom pci ++ "}}" where pci = pciDevice $ fromJust $ Map.lookup id ms dom = domainID $ fromJust $ Map.lookup id ms showCap objs (VCPUCap id) _ _ _ = "{.type = CDL_VCPUCap, .obj_id = " ++ showObjID objs id ++ "}" showCap _ SchedControlCap _ _ _ = "{.type = CDL_SchedControlCap}" showCap objs (SCCap id) _ is_orig _ = "{.type = CDL_SCCap, .obj_id = " ++ showObjID objs id ++ ", .is_orig = " ++ is_orig ++ "}" showCap _ x _ _ _ = assert False $ "UNSUPPORTED CAP TYPE: " ++ show x -- These are not supported by the initialiser itself. showSlots :: Map ObjID Int -> ObjID -> [(Word, Cap)] -> IRQMap -> CDT -> ObjMap Word -> String showSlots _ _ [] _ _ _ = "" showSlots objs obj_id (x:xs) irqNode cdt ms = "{" ++ show index ++ ", " ++ slot ++ "}," +++ showSlots objs obj_id xs irqNode cdt ms where index = fst x slot = showCap objs (snd x) irqNode is_orig ms is_orig = if (Map.notMember (obj_id, index) cdt) then "true" else "false" memberSlots :: Map ObjID Int -> ObjID -> CapMap Word -> IRQMap -> CDT -> ObjMap Word -> String memberSlots objs obj_id slots irqNode cdt ms = ".slots.num = " ++ show slot_count ++ "," +++ ".slots.slot = (CDL_CapSlot[]) {" +++ indent (showSlots objs obj_id (Map.toList slots) irqNode cdt ms) +++ "}," where slot_count = Map.size slots printInit :: [Word] -> String printInit argv = "{" ++ Data.List.Utils.join ", " (Data.List.map show argv) ++ "}" showObjectFields :: Map ObjID Int -> ObjID -> KernelObject Word -> IRQMap -> CDT -> ObjMap Word -> String showObjectFields _ _ Endpoint _ _ _ = ".type = CDL_Endpoint," showObjectFields _ _ AsyncEndpoint _ _ _ = ".type = CDL_AsyncEndpoint," showObjectFields objs obj_id (TCB slots info domain argv) _ _ _ = ".type = CDL_TCB," +++ ".tcb_extra = {" +++ indent (".ipcbuffer_addr = " ++ show ipcbuffer_addr ++ "," +++ ".driverinfo = " ++ show driverinfo ++ "," +++ ".priority = " ++ show priority ++ "," +++ ".max_priority = " ++ show max_priority ++ "," +++ ".criticality = " ++ show criticality ++ "," +++ ".max_criticality = " ++ show max_criticality ++ "," +++ ".pc = " ++ show pc ++ "," +++ ".sp = " ++ show stack ++ "," +++ ".elf_name = " ++ show elf_name ++ "," +++ ".init = (const seL4_Word[])" ++ printInit argv ++ "," +++ ".init_sz = " ++ show (length argv) ++ "," +++ ".domain = " ++ show domain ++ ",") +++ "}," +++ memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required where ipcbuffer_addr = case info of {Just i -> ipcBufferAddr i; _ -> 0} driverinfo = 0 -- TODO: Not currently in CapDL priority = case info of {Just i -> case prio i of {Just p -> p; _ -> 125}; _ -> 125} max_priority = case info of {Just i -> case max_prio i of {Just p -> p; _ -> 125}; _ -> 125} criticality = case info of {Just i -> case crit i of {Just p -> p; _ -> 125}; _ -> 125} max_criticality = case info of {Just i -> case max_crit i of {Just p -> p; _ -> 125}; _ -> 125} pc = case info of {Just i -> case ip i of {Just v -> v; _ -> 0}; _ -> 0} stack = case info of {Just i -> case sp i of {Just v -> v; _ -> 0}; _ -> 0} elf_name = case info of {Just i -> case elf i of {Just e -> e; _ -> ""}; _ -> ""} showObjectFields objs obj_id (CNode slots sizeBits) irqNode cdt ms = ".type = " ++ t ++ "," +++ ".size_bits = " ++ show sizeBits ++ "," +++ memberSlots objs obj_id slots irqNode cdt ms where -- IRQs are represented in CapDL as 0-sized CNodes. This is fine for -- the model, but the initialiser needs to know what objects represent -- interrupts to avoid trying to create them at runtime. It's a bit of -- a hack to assume that any 0-sized CNode is an interrupt, but this is -- an illegal size for a valid CNode so everything should work out. t = if sizeBits == 0 then "CDL_Interrupt" else "CDL_CNode" showObjectFields _ _ (Untyped size_bits) _ _ _ = ".type = CDL_Untyped," +++ ".size_bits = " ++ show sizeBits ++ "," where sizeBits = case size_bits of {Just s -> s; _ -> -1} showObjectFields objs obj_id (PT slots) _ _ _ = ".type = CDL_PT," +++ memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required showObjectFields objs obj_id (PD slots) _ _ _ = ".type = CDL_PD," +++ memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required showObjectFields _ _ (Frame size paddr) _ _ _ = ".type = CDL_Frame," +++ ".size_bits = " ++ show (logBase 2 $ fromIntegral size) ++ "," +++ ".paddr = (void*)" ++ hex (fromMaybe 0 paddr) ++ "," showObjectFields _ _ (IOPorts size) _ _ _ = ".type = CDL_IOPorts," +++ ".size_bits = " ++ show size ++ "," -- FIXME: This doesn't seem right. showObjectFields objs obj_id (ASIDPool slots) _ _ _ = ".type = CDL_ASIDPool," +++ memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required showObjectFields objs _ (IODevice slots domainID (bus, dev, fun)) _ _ _ = ".type = CDL_IODevice," showObjectFields _ _ VCPU _ _ _ = ".type = CDL_VCPU," showObjectFields objs obj_id (SC info) _ _ _ = ".type = CDL_SchedContext," +++ ".sc_extra = {" +++ indent (".period = " ++ show period_ ++ "," +++ ".deadline = " ++ show deadline_ ++ "," +++ ".exec_req = " ++ show exec_req_ ++ "," +++ ".flags = {{" ++ show flags_ ++ "}},") +++ "}," where period_ = case info of {Just i -> case period i of {Just p -> p; _ -> 0}; _ -> 0} deadline_ = case info of {Just i -> case deadline i of {Just p -> p; _ -> 0}; _ -> 0} exec_req_ = case info of {Just i -> case exec_req i of {Just p -> p; _ -> 0}; _ -> 0} flags_ = case info of {Just i -> case flags i of {Just p -> p; _ -> 0}; _ -> 0} showObjectFields _ _ x _ _ _ = assert False $ "UNSUPPORTED OBJECT TYPE: " ++ show x showObject :: Map ObjID Int -> (ObjID, KernelObject Word) -> IRQMap -> CDT -> ObjMap Word -> String showObject objs obj irqNode cdt ms = "{" +++ indent (".name = \"" ++ name ++ "\"," +++ showObjectFields objs id (snd obj) irqNode cdt ms) +++ "}" where id = fst obj name = fst id ++ (case snd id of Just index -> "[" ++ show index ++ "]" _ -> "") showObjects :: Map ObjID Int -> Int -> [(ObjID, KernelObject Word)] -> IRQMap -> CDT -> ObjMap Word -> String showObjects _ _ [] _ _ _ = "" showObjects objs counter (x:xs) irqNode cdt ms = "[" ++ show counter ++ "] = " ++ showObject objs x irqNode cdt ms ++ "," +++ showObjects objs (counter + 1) xs irqNode cdt ms sizeOf :: Arch -> KernelObject Word -> Word sizeOf _ (Frame vmSz _) = vmSz sizeOf _ (Untyped (Just bSz)) = 2 ^ bSz sizeOf _ (CNode _ bSz) = 16 * 2 ^ bSz sizeOf _ Endpoint = 16 sizeOf _ AsyncEndpoint = 16 sizeOf _ ASIDPool {} = 4 * 2^10 sizeOf _ IOPT {} = 4 * 2^10 sizeOf _ IODevice {} = 1 sizeOf _ SC {} = 16 -- FIXME size of SC ?? sizeOf IA32 TCB {} = 2^10 sizeOf IA32 PD {} = 4 * 2^10 sizeOf IA32 PT {} = 4 * 2^10 sizeOf ARM11 TCB {} = 512 sizeOf ARM11 PD {} = 16 * 2^10 sizeOf ARM11 PT {} = 2^10 sizeOf _ _ = 0 memberObjects :: Map ObjID Int -> Arch -> [(ObjID, KernelObject Word)] -> IRQMap -> CDT -> ObjMap Word -> String memberObjects obj_ids arch objs irqNode cdt objs' = ".objects = (CDL_Object[]) {" +++ (indent $ showObjects obj_ids 0 objs irqNode cdt objs') +++ "}," -- Emit an array where each entry represents a given interrupt. Each is -1 if -- that interrupt has no handler or else the object ID of the interrupt -- (0-sized CNode). memberIRQs :: Map ObjID Int -> IRQMap -> Arch -> String memberIRQs objs irqNode arch = ".irqs = {" +++ (indent $ join ", " $ Data.List.map (\k -> show $ case Map.lookup k irqNode of Just i -> fromJust $ Map.lookup i objs _ -> -1) [0..(CONFIG_CAPDL_LOADER_MAX_IRQS - 1)]) +++ "}," printC :: Model Word -> Idents CapName -> CopyMap -> Doc printC (Model arch objs irqNode cdt untypedCovers) ids copies = text $ "/* Generated file. Your changes will be overwritten. */" +++ "" +++ "#include <capdl.h>" +++ "" +++ "#ifndef INVALID_SLOT" +++ indent "#define INVALID_SLOT (-1)" +++ "#endif" +++ "" +++ maxObjects objs_sz +++ -- FIXME: I suspect this is not the right list to measure. "" +++ "CDL_Model capdl_spec = {" +++ indent (memberArch arch +++ memberNum objs_sz +++ memberIRQs obj_ids irqNode arch +++ memberObjects obj_ids arch objs' irqNode cdt objs) +++ "};" where objs_sz = length $ Map.toList objs objs' = reverse $ sortOn (sizeOf arch . snd) $ Map.toList objs obj_ids = Map.fromList $ flip zip [0..] $ Prelude.map fst objs'
smaccm/capDL-tool
CapDL/PrintC.hs
Haskell
bsd-2-clause
14,280
{-# LANGUAGE CPP, OverloadedStrings #-} -- Requires the network-bytestring library. -- -- Start server and run -- httperf --server=localhost --port=5002 --uri=/ --num-conns=10000 -- or -- ab -n 10000 -c 100 http://localhost:5002/ import Args (ljust, parseArgs, positive, theLast) import Control.Concurrent (forkIO, runInUnboundThread) import Data.ByteString.Char8 () import Data.Function (on) import Data.Monoid (Monoid(..), Last(..)) import Network.Socket hiding (accept, recv) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as C () #ifdef USE_GHC_IO_MANAGER import Network.Socket (accept) import Network.Socket.ByteString (recv, sendAll) #else import EventSocket (accept, recv, sendAll) import System.Event.Thread (ensureIOManagerIsRunning) #endif import System.Console.GetOpt (ArgDescr(ReqArg), OptDescr(..)) import System.Environment (getArgs) import System.Posix.Resource (ResourceLimit(..), ResourceLimits(..), Resource(..), setResourceLimit) main = do (cfg, _) <- parseArgs defaultConfig defaultOptions =<< getArgs let listenBacklog = theLast cfgListenBacklog cfg port = theLast cfgPort cfg lim = ResourceLimit . fromIntegral . theLast cfgMaxFds $ cfg myHints = defaultHints { addrFlags = [AI_PASSIVE] , addrSocketType = Stream } #ifndef USE_GHC_IO_MANAGER ensureIOManagerIsRunning #endif setResourceLimit ResourceOpenFiles ResourceLimits { softLimit = lim, hardLimit = lim } (ai:_) <- getAddrInfo (Just myHints) Nothing (Just port) sock <- socket (addrFamily ai) (addrSocketType ai) (addrProtocol ai) setSocketOption sock ReuseAddr 1 bindSocket sock (addrAddress ai) listen sock listenBacklog runInUnboundThread $ acceptConnections sock acceptConnections :: Socket -> IO () acceptConnections sock = loop where loop = do (c,_) <- accept sock forkIO $ client c loop client :: Socket -> IO () client sock = do recvRequest "" sendAll sock msg sClose sock where msg = "HTTP/1.0 200 OK\r\nConnection: Close\r\nContent-Length: 5\r\n\r\nPong!" recvRequest r = do s <- recv sock 4096 let t = S.append r s if S.null s || "\r\n\r\n" `S.isInfixOf` t then return () else recvRequest t ------------------------------------------------------------------------ -- Configuration data Config = Config { cfgListenBacklog :: Last Int , cfgMaxFds :: Last Int , cfgPort :: Last String } defaultConfig :: Config defaultConfig = Config { cfgListenBacklog = ljust 1024 , cfgMaxFds = ljust 256 , cfgPort = ljust "5002" } instance Monoid Config where mempty = Config { cfgListenBacklog = mempty , cfgMaxFds = mempty , cfgPort = mempty } mappend a b = Config { cfgListenBacklog = app cfgListenBacklog a b , cfgMaxFds = app cfgMaxFds a b , cfgPort = app cfgPort a b } where app :: (Monoid b) => (a -> b) -> a -> a -> b app = on mappend defaultOptions :: [OptDescr (IO Config)] defaultOptions = [ Option ['p'] ["port"] (ReqArg (\s -> return mempty { cfgPort = ljust s }) "N") "server port" , Option ['m'] ["max-fds"] (ReqArg (positive "maximum number of file descriptors" $ \n -> mempty { cfgMaxFds = n }) "N") "maximum number of file descriptors" , Option [] ["listen-backlog"] (ReqArg (positive "maximum number of pending connections" $ \n -> mempty { cfgListenBacklog = n }) "N") "maximum number of pending connections" ]
tibbe/event
benchmarks/PongServer.hs
Haskell
bsd-2-clause
3,719
module Application.Scaffold.Generate.Darcs where import System.Process import System.Exit darcsInit :: IO ExitCode darcsInit = system "darcs init" darcsFile :: FilePath -> IO ExitCode darcsFile fp = do putStrLn $ "add " ++ fp system ("darcs add " ++ fp) darcsRecord :: String -> IO ExitCode darcsRecord patchname = system ("darcs record --all -m \"" ++ patchname ++ "\"")
wavewave/scaffold
lib/Application/Scaffold/Generate/Darcs.hs
Haskell
bsd-2-clause
387
module Animation where import Graphics.UI.SDL import Graphics.UI.SDL.Image import Control.Monad type Animation = [Surface] loadAnimation :: FilePath -> Int -> IO Animation loadAnimation folder size = do frames <- forM [0..size-1] $ \i -> do load $ folder ++ show i ++ ".png" return $ cycle frames
alexisVallet/hachitai-haskell-shmup
Animation.hs
Haskell
bsd-2-clause
307
{-# LANGUAGE PatternGuards #-} module Idris.PartialEval(partial_eval, getSpecApps, specType, mkPE_TyDecl, mkPE_TermDecl, PEArgType(..), pe_app, pe_def, pe_clauses, pe_simple) where import Idris.AbsSyntax import Idris.Delaborate import Idris.Core.TT import Idris.Core.Evaluate import Control.Monad.State import Control.Applicative import Data.Maybe import Debug.Trace -- | Data type representing binding-time annotations for partial evaluation of arguments data PEArgType = ImplicitS -- ^ Implicit static argument | ImplicitD -- ^ Implicit dynamic argument | ExplicitS -- ^ Explicit static argument | ExplicitD -- ^ Explicit dynamic argument | UnifiedD -- ^ Erasable dynamic argument (found under unification) deriving (Eq, Show) -- | A partially evaluated function. pe_app captures the lhs of the -- new definition, pe_def captures the rhs, and pe_clauses is the -- specialised implementation. -- pe_simple is set if the result is always reducible, because in such a -- case we'll also need to reduce the static argument data PEDecl = PEDecl { pe_app :: PTerm, -- new application pe_def :: PTerm, -- old application pe_clauses :: [(PTerm, PTerm)], -- clauses of new application pe_simple :: Bool -- if just one reducible clause } -- | Partially evaluates given terms under the given context. -- It is an error if partial evaluation fails to make any progress. -- Making progress is defined as: all of the names given with explicit -- reduction limits (in practice, the function being specialised) -- must have reduced at least once. -- If we don't do this, we might end up making an infinite function after -- applying the transformation. partial_eval :: Context -> [(Name, Maybe Int)] -> [Either Term (Term, Term)] -> Maybe [Either Term (Term, Term)] partial_eval ctxt ns_in tms = mapM peClause tms where ns = squash ns_in squash ((n, Just x) : ns) | Just (Just y) <- lookup n ns = squash ((n, Just (x + y)) : drop n ns) | otherwise = (n, Just x) : squash ns squash (n : ns) = n : squash ns squash [] = [] drop n ((m, _) : ns) | n == m = ns drop n (x : ns) = x : drop n ns drop n [] = [] -- If the term is not a clause, it is simply kept as is peClause (Left t) = Just $ Left t -- If the term is a clause, specialise the right hand side peClause (Right (lhs, rhs)) = let (rhs', reductions) = specialise ctxt [] (map toLimit ns) rhs in do when (length tms == 1) $ checkProgress ns reductions return (Right (lhs, rhs')) -- TMP HACK until I do PE by WHNF rather than using main evaluator toLimit (n, Nothing) | isTCDict n ctxt = (n, 2) toLimit (n, Nothing) = (n, 65536) -- somewhat arbitrary reduction limit toLimit (n, Just l) = (n, l) checkProgress ns [] = return () checkProgress ns ((n, r) : rs) | Just (Just start) <- lookup n ns = if start <= 1 || r < start then checkProgress ns rs else Nothing | otherwise = checkProgress ns rs -- | Specialises the type of a partially evaluated TT function returning -- a pair of the specialised type and the types of expected arguments. specType :: [(PEArgType, Term)] -> Type -> (Type, [(PEArgType, Term)]) specType args ty = let (t, args') = runState (unifyEq args ty) [] in (st (map fst args') t, map fst args') where -- Specialise static argument in type by let-binding provided value instead -- of expecting it as a function argument st ((ExplicitS, v) : xs) (Bind n (Pi _ t _) sc) = Bind n (Let t v) (st xs sc) st ((ImplicitS, v) : xs) (Bind n (Pi _ t _) sc) = Bind n (Let t v) (st xs sc) -- Erase argument from function type st ((UnifiedD, _) : xs) (Bind n (Pi _ t _) sc) = st xs sc -- Keep types as is st (_ : xs) (Bind n (Pi i t k) sc) = Bind n (Pi i t k) (st xs sc) st _ t = t -- Erase implicit dynamic argument if existing argument shares it value, -- by substituting the value of previous argument unifyEq (imp@(ImplicitD, v) : xs) (Bind n (Pi i t k) sc) = do amap <- get case lookup imp amap of Just n' -> do put (amap ++ [((UnifiedD, Erased), n)]) sc' <- unifyEq xs (subst n (P Bound n' Erased) sc) return (Bind n (Pi i t k) sc') -- erase later _ -> do put (amap ++ [(imp, n)]) sc' <- unifyEq xs sc return (Bind n (Pi i t k) sc') unifyEq (x : xs) (Bind n (Pi i t k) sc) = do args <- get put (args ++ [(x, n)]) sc' <- unifyEq xs sc return (Bind n (Pi i t k) sc') unifyEq xs t = do args <- get put (args ++ (zip xs (repeat (sUN "_")))) return t -- | Creates an Idris type declaration given current state and a -- specialised TT function application type. -- Can be used in combination with the output of 'specType'. -- -- This should: specialise any static argument position, then generalise -- over any function applications in the result. mkPE_TyDecl :: IState -> [(PEArgType, Term)] -> Type -> PTerm mkPE_TyDecl ist args ty = mkty args ty where mkty ((ExplicitD, v) : xs) (Bind n (Pi _ t k) sc) = PPi expl n NoFC (delab ist (generaliseIn t)) (mkty xs sc) mkty ((ImplicitD, v) : xs) (Bind n (Pi _ t k) sc) | concreteClass ist t = mkty xs sc | classConstraint ist t = PPi constraint n NoFC (delab ist (generaliseIn t)) (mkty xs sc) | otherwise = PPi impl n NoFC (delab ist (generaliseIn t)) (mkty xs sc) mkty (_ : xs) t = mkty xs t mkty [] t = delab ist t generaliseIn tm = evalState (gen tm) 0 gen tm | (P _ fn _, args) <- unApply tm, isFnName fn (tt_ctxt ist) = do nm <- get put (nm + 1) return (P Bound (sMN nm "spec") Erased) gen (App s f a) = App s <$> gen f <*> gen a gen tm = return tm -- | Checks if a given argument is a type class constraint argument classConstraint :: Idris.AbsSyntax.IState -> TT Name -> Bool classConstraint ist v | (P _ c _, args) <- unApply v = case lookupCtxt c (idris_classes ist) of [_] -> True _ -> False | otherwise = False -- | Checks if the given arguments of a type class constraint are all either constants -- or references (i.e. that it doesn't contain any complex terms). concreteClass :: IState -> TT Name -> Bool concreteClass ist v | not (classConstraint ist v) = False | (P _ c _, args) <- unApply v = all concrete args | otherwise = False where concrete (Constant _) = True concrete tm | (P _ n _, args) <- unApply tm = case lookupTy n (tt_ctxt ist) of [_] -> all concrete args _ -> False | otherwise = False mkNewPats :: IState -> [(Term, Term)] -> -- definition to specialise [(PEArgType, Term)] -> -- arguments to specialise with Name -> -- New name Name -> -- Specialised function name PTerm -> -- Default lhs PTerm -> -- Default rhs PEDecl -- If all of the dynamic positions on the lhs are variables (rather than -- patterns or constants) then we can just make a simple definition -- directly applying the specialised function, since we know the -- definition isn't going to block on any of the dynamic arguments -- in this case mkNewPats ist d ns newname sname lhs rhs | all dynVar (map fst d) = PEDecl lhs rhs [(lhs, rhs)] True where dynVar ap = case unApply ap of (_, args) -> dynArgs ns args dynArgs _ [] = True -- can definitely reduce from here -- if Static, doesn't matter what the argument is dynArgs ((ImplicitS, _) : ns) (a : as) = dynArgs ns as dynArgs ((ExplicitS, _) : ns) (a : as) = dynArgs ns as -- if Dynamic, it had better be a variable or we'll need to -- do some more work dynArgs (_ : ns) (V _ : as) = dynArgs ns as dynArgs (_ : ns) (P _ _ _ : as) = dynArgs ns as dynArgs _ _ = False -- and now we'll get stuck mkNewPats ist d ns newname sname lhs rhs = PEDecl lhs rhs (map mkClause d) False where mkClause :: (Term, Term) -> (PTerm, PTerm) mkClause (oldlhs, oldrhs) = let (_, as) = unApply oldlhs lhsargs = mkLHSargs [] ns as lhs = PApp emptyFC (PRef emptyFC newname) lhsargs rhs = PApp emptyFC (PRef emptyFC sname) (mkRHSargs ns lhsargs) in (lhs, rhs) mkLHSargs _ [] _ = [] -- dynamics don't appear if they're implicit mkLHSargs sub ((ExplicitD, t) : ns) (a : as) = pexp (delab ist (substNames sub a)) : mkLHSargs sub ns as mkLHSargs sub ((ImplicitD, _) : ns) (a : as) = mkLHSargs sub ns as mkLHSargs sub ((UnifiedD, _) : ns) (a : as) = mkLHSargs sub ns as -- statics get dropped in any case mkLHSargs sub ((ImplicitS, t) : ns) (a : as) = mkLHSargs (extend a t sub) ns as mkLHSargs sub ((ExplicitS, t) : ns) (a : as) = mkLHSargs (extend a t sub) ns as mkLHSargs sub _ [] = [] -- no more LHS extend (P _ n _) t sub = (n, t) : sub extend _ _ sub = sub mkRHSargs ((ExplicitS, t) : ns) as = pexp (delab ist t) : mkRHSargs ns as mkRHSargs ((ExplicitD, t) : ns) (a : as) = a : mkRHSargs ns as mkRHSargs (_ : ns) as = mkRHSargs ns as mkRHSargs _ _ = [] mkSubst :: (Term, Term) -> Maybe (Name, Term) mkSubst (P _ n _, t) = Just (n, t) mkSubst _ = Nothing -- | Creates a new declaration for a specialised function application. -- Simple version at the moment: just create a version which is a direct -- application of the function to be specialised. -- More complex version to do: specialise the definition clause by clause mkPE_TermDecl :: IState -> Name -> Name -> [(PEArgType, Term)] -> PEDecl mkPE_TermDecl ist newname sname ns = let lhs = PApp emptyFC (PRef emptyFC newname) (map pexp (mkp ns)) rhs = eraseImps $ delab ist (mkApp (P Ref sname Erased) (map snd ns)) patdef = lookupCtxtExact sname (idris_patdefs ist) newpats = case patdef of Nothing -> PEDecl lhs rhs [(lhs, rhs)] True Just d -> mkNewPats ist (getPats d) ns newname sname lhs rhs in newpats where getPats (ps, _) = map (\(_, lhs, rhs) -> (lhs, rhs)) ps mkp [] = [] mkp ((ExplicitD, tm) : tms) = delab ist tm : mkp tms mkp (_ : tms) = mkp tms eraseImps tm = mapPT deImp tm deImp (PApp fc t as) = PApp fc t (map deImpArg as) deImp t = t deImpArg a@(PImp _ _ _ _ _) = a { getTm = Placeholder } deImpArg a = a -- | Get specialised applications for a given function getSpecApps :: IState -> [Name] -> Term -> [(Name, [(PEArgType, Term)])] getSpecApps ist env tm = ga env (explicitNames tm) where -- staticArg env True _ tm@(P _ n _) _ | n `elem` env = Just (True, tm) -- staticArg env True _ tm@(App f a) _ | (P _ n _, args) <- unApply tm, -- n `elem` env = Just (True, tm) staticArg env x imp tm n | x && imparg imp = (ImplicitS, tm) | x = (ExplicitS, tm) | imparg imp = (ImplicitD, tm) | otherwise = (ExplicitD, (P Ref (sUN (show n ++ "arg")) Erased)) imparg (PExp _ _ _ _) = False imparg _ = True buildApp env [] [] _ _ = [] buildApp env (s:ss) (i:is) (a:as) (n:ns) = let s' = staticArg env s i a n ss' = buildApp env ss is as ns in (s' : ss') -- if we have a *defined* function that has static arguments, -- it will become a specialised application ga env tm@(App _ f a) | (P _ n _, args) <- unApply tm, n `notElem` map fst (idris_metavars ist) = ga env f ++ ga env a ++ case (lookupCtxtExact n (idris_statics ist), lookupCtxtExact n (idris_implicits ist)) of (Just statics, Just imps) -> if (length statics == length args && or statics) then case buildApp env statics imps args [0..] of args -> [(n, args)] -- _ -> [] else [] _ -> [] ga env (Bind n (Let t v) sc) = ga env v ++ ga (n : env) sc ga env (Bind n t sc) = ga (n : env) sc ga env t = []
BartAdv/Idris-dev
src/Idris/PartialEval.hs
Haskell
bsd-3-clause
13,072
import Control.Concurrent import Control.Monad foreign import ccall input :: Int foreign import ccall output :: Int -> IO () main :: IO () main = do m <- newEmptyMVar forkIO $ putMVar m input r <- takeMVar m output r
bosu/josh
t/progs/MVar.hs
Haskell
bsd-3-clause
235
{-# LANGUAGE CPP, GADTs #-} ----------------------------------------------------------------------------- -- | -- Module : Math.Combinatorics.Species.AST.Instances -- Copyright : (c) Brent Yorgey 2010 -- License : BSD-style (see LICENSE) -- Maintainer : byorgey@cis.upenn.edu -- Stability : experimental -- -- Type class instances for 'TSpeciesAST', 'ESpeciesAST', and -- 'SpeciesAST', in a separate module to avoid a dependency cycle -- between "Math.Combinatorics.Species.AST" and -- "Math.Combinatorics.Species.Class". -- -- This module also contains functions for reifying species -- expressions to ASTs and reflecting ASTs back into other species -- instances, which are in this module since they depend on the AST -- type class instances. -- ----------------------------------------------------------------------------- module Math.Combinatorics.Species.AST.Instances ( reify, reifyE, reflect, reflectT, reflectE ) where #if MIN_VERSION_numeric_prelude(0,2,0) import NumericPrelude hiding (cycle) #else import NumericPrelude import PreludeBase hiding (cycle) #endif import Math.Combinatorics.Species.Class import Math.Combinatorics.Species.AST import Math.Combinatorics.Species.Util.Interval hiding (omega) import qualified Math.Combinatorics.Species.Util.Interval as I import qualified Algebra.Additive as Additive import qualified Algebra.Ring as Ring import qualified Algebra.Differential as Differential import Data.Typeable ------------------------------------------------------------ -- SpeciesAST instances ---------------------------------- ------------------------------------------------------------ -- grr -- can't autoderive this because of Rec constructor! =P -- | Species expressions can be compared for /structural/ equality. -- (Note that if @s1@ and @s2@ are /isomorphic/ species we do not -- necessarily have @s1 == s2@.) -- -- Note, however, that species containing an 'OfSize' constructor -- will always compare as @False@ with any other species, since we -- cannot decide function equality. instance Eq SpeciesAST where Zero == Zero = True One == One = True (N m) == (N n) = m == n X == X = True E == E = True C == C = True L == L = True Subset == Subset = True (KSubset k) == (KSubset j) = k == j Elt == Elt = True (f1 :+ g1) == (f2 :+ g2) = f1 == f2 && g1 == g2 (f1 :* g1) == (f2 :* g2) = f1 == f2 && g1 == g2 (f1 :. g1) == (f2 :. g2) = f1 == f2 && g1 == g2 (f1 :>< g1) == (f2 :>< g2) = f1 == f2 && g1 == g2 (f1 :@ g1) == (f2 :@ g2) = f1 == f2 && g1 == g2 Der f1 == Der f2 = f1 == f2 -- note, OfSize will always compare False since we can't compare the functions for equality OfSizeExactly f1 k1 == OfSizeExactly f2 k2 = f1 == f2 && k1 == k2 NonEmpty f1 == NonEmpty f2 = f1 == f2 Rec f1 == Rec f2 = typeOf f1 == typeOf f2 Omega == Omega = True _ == _ = False -- argh, can't derive this either. ugh. -- | An (arbitrary) 'Ord' instance, so that we can put species -- expressions in canonical order when simplifying. instance Ord SpeciesAST where compare x y | x == y = EQ compare Zero _ = LT compare _ Zero = GT compare One _ = LT compare _ One = GT compare (N m) (N n) = compare m n compare (N _) _ = LT compare _ (N _) = GT compare X _ = LT compare _ X = GT compare E _ = LT compare _ E = GT compare C _ = LT compare _ C = GT compare L _ = LT compare _ L = GT compare Subset _ = LT compare _ Subset = GT compare (KSubset j) (KSubset k) = compare j k compare (KSubset _) _ = LT compare _ (KSubset _) = GT compare Elt _ = LT compare _ Elt = GT compare (f1 :+ g1) (f2 :+ g2) | f1 == f2 = compare g1 g2 | otherwise = compare f1 f2 compare (_ :+ _) _ = LT compare _ (_ :+ _) = GT compare (f1 :* g1) (f2 :* g2) | f1 == f2 = compare g1 g2 | otherwise = compare f1 f2 compare (_ :* _) _ = LT compare _ (_ :* _) = GT compare (f1 :. g1) (f2 :. g2) | f1 == f2 = compare g1 g2 | otherwise = compare f1 f2 compare (_ :. _) _ = LT compare _ (_ :. _) = GT compare (f1 :>< g1) (f2 :>< g2) | f1 == f2 = compare g1 g2 | otherwise = compare f1 f2 compare (_ :>< _) _ = LT compare _ (_ :>< _) = GT compare (f1 :@ g1) (f2 :@ g2) | f1 == f2 = compare g1 g2 | otherwise = compare f1 f2 compare (_ :@ _) _ = LT compare _ (_ :@ _) = GT compare (Der f1) (Der f2) = compare f1 f2 compare (Der _) _ = LT compare _ (Der _) = GT compare (OfSize f1 p1) (OfSize f2 p2) = compare f1 f2 compare (OfSize _ _) _ = LT compare _ (OfSize _ _) = GT compare (OfSizeExactly f1 k1) (OfSizeExactly f2 k2) | f1 == f2 = compare k1 k2 | otherwise = compare f1 f2 compare (OfSizeExactly _ _) _ = LT compare _ (OfSizeExactly _ _) = GT compare (NonEmpty f1) (NonEmpty f2) = compare f1 f2 compare (NonEmpty _) _ = LT compare _ (NonEmpty _) = GT compare (Rec f1) (Rec f2) = compare (show $ typeOf f1) (show $ typeOf f2) compare Omega _ = LT compare _ Omega = GT -- | Display species expressions in a nice human-readable form. Note -- that we commit the unforgivable sin of omitting a corresponding -- Read instance. This will hopefully be remedied in a future -- version. instance Show SpeciesAST where showsPrec _ Zero = shows (0 :: Int) showsPrec _ One = shows (1 :: Int) showsPrec _ (N n) = shows n showsPrec _ X = showChar 'X' showsPrec _ E = showChar 'E' showsPrec _ C = showChar 'C' showsPrec _ L = showChar 'L' showsPrec _ Subset = showChar 'p' showsPrec _ (KSubset n) = showChar 'p' . shows n showsPrec _ (Elt) = showChar 'e' showsPrec p (f :+ g) = showParen (p>6) $ showsPrec 6 f . showString " + " . showsPrec 6 g showsPrec p (f :* g) = showParen (p>=7) $ showsPrec 7 f . showString " * " . showsPrec 7 g showsPrec p (f :. g) = showParen (p>=7) $ showsPrec 7 f . showString " . " . showsPrec 7 g showsPrec p (f :>< g) = showParen (p>=7) $ showsPrec 7 f . showString " >< " . showsPrec 7 g showsPrec p (f :@ g) = showParen (p>=7) $ showsPrec 7 f . showString " @ " . showsPrec 7 g showsPrec p (Der f) = showsPrec 11 f . showChar '\'' showsPrec _ (OfSize f p) = showChar '<' . showsPrec 0 f . showChar '>' showsPrec _ (OfSizeExactly f n) = showsPrec 11 f . shows n showsPrec _ (NonEmpty f) = showsPrec 11 f . showChar '+' showsPrec _ (Rec f) = shows f -- | Species expressions are additive. instance Additive.C SpeciesAST where zero = Zero (+) = (:+) negate = error "negation is not implemented yet! wait until virtual species..." -- | Species expressions form a ring. Well, sort of. Of course the -- ring laws actually only hold up to isomorphism of species, not up -- to structural equality. instance Ring.C SpeciesAST where (*) = (:*) one = One fromInteger 0 = zero fromInteger 1 = one fromInteger n = N n _ ^ 0 = one w ^ 1 = w f ^ n = f * (f ^ (n-1)) -- | Species expressions are differentiable. instance Differential.C SpeciesAST where differentiate = Der -- | Species expressions are an instance of the 'Species' class, so we -- can use the Species class DSL to build species expression ASTs. instance Species SpeciesAST where singleton = X set = E cycle = C linOrd = L subset = Subset ksubset k = KSubset k element = Elt o = (:.) (><) = (:><) (@@) = (:@) ofSize = OfSize ofSizeExactly = OfSizeExactly nonEmpty = NonEmpty rec = Rec omega = Omega instance Show (TSpeciesAST s) where show = show . erase' instance Show ESpeciesAST where show = show . erase instance Additive.C ESpeciesAST where zero = wrap TZero Wrap f + Wrap g = wrap $ f :+:: g negate = error "negation is not implemented yet! wait until virtual species..." instance Ring.C ESpeciesAST where Wrap f * Wrap g = wrap $ f :*:: g one = wrap TOne fromInteger 0 = zero fromInteger 1 = one fromInteger n = wrap $ TN n _ ^ 0 = one w@(Wrap{}) ^ 1 = w (Wrap f) ^ n = case (Wrap f) ^ (n-1) of (Wrap f') -> wrap $ f :*:: f' instance Differential.C ESpeciesAST where differentiate (Wrap f) = wrap (TDer f) instance Species ESpeciesAST where singleton = wrap TX set = wrap TE cycle = wrap TC linOrd = wrap TL subset = wrap TSubset ksubset k = wrap $ TKSubset k element = wrap TElt o (Wrap f) (Wrap g) = wrap $ f :.:: g Wrap f >< Wrap g = wrap $ f :><:: g Wrap f @@ Wrap g = wrap $ f :@:: g ofSize (Wrap f) p = wrap $ TOfSize f p ofSizeExactly (Wrap f) n = wrap $ TOfSizeExactly f n nonEmpty (Wrap f) = wrap $ TNonEmpty f rec f = wrap $ TRec f omega = wrap TOmega ------------------------------------------------------------ -- Reify/reflect ----------------------------------------- ------------------------------------------------------------ -- | Reify a species expression into an AST. (Actually, this is just -- the identity function with a usefully restricted type.) For -- example: -- -- > > reify octopus -- > C . TL+ -- > > reify (ksubset 3) -- > E3 * TE reify :: SpeciesAST -> SpeciesAST reify = id -- | The same as reify, but produce a typed, size-annotated AST. reifyE :: ESpeciesAST -> ESpeciesAST reifyE = id -- | Reflect an AST back into any instance of the 'Species' class. reflect :: Species s => SpeciesAST -> s reflect Zero = zero reflect One = one reflect (N n) = fromInteger n reflect X = singleton reflect E = set reflect C = cycle reflect L = linOrd reflect Subset = subset reflect (KSubset k) = ksubset k reflect Elt = element reflect (f :+ g) = reflect f + reflect g reflect (f :* g) = reflect f * reflect g reflect (f :. g) = reflect f `o` reflect g reflect (f :>< g) = reflect f >< reflect g reflect (f :@ g) = reflect f @@ reflect g reflect (Der f) = oneHole (reflect f) reflect (OfSize f p) = ofSize (reflect f) p reflect (OfSizeExactly f n) = ofSizeExactly (reflect f) n reflect (NonEmpty f) = nonEmpty (reflect f) reflect (Rec f) = rec f reflect Omega = omega -- | Reflect a typed AST back into any instance of the 'Species' -- class. reflectT :: Species s => TSpeciesAST f -> s reflectT = reflect . erase' -- | Reflect an existentially wrapped typed AST back into any -- instance of the 'Species' class. reflectE :: Species s => ESpeciesAST -> s reflectE = reflect . erase
timsears/species
Math/Combinatorics/Species/AST/Instances.hs
Haskell
bsd-3-clause
13,095
{-# language CPP #-} -- | = Name -- -- VK_KHR_ray_tracing_pipeline - device extension -- -- == VK_KHR_ray_tracing_pipeline -- -- [__Name String__] -- @VK_KHR_ray_tracing_pipeline@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 348 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.1 -- -- - Requires @VK_KHR_spirv_1_4@ -- -- - Requires @VK_KHR_acceleration_structure@ -- -- [__Contact__] -- -- - Daniel Koch -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_ray_tracing_pipeline] @dgkoch%0A<<Here describe the issue or question you have about the VK_KHR_ray_tracing_pipeline extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2020-11-12 -- -- [__Interactions and External Dependencies__] -- -- - This extension requires -- <https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/KHR/SPV_KHR_ray_tracing.html SPV_KHR_ray_tracing> -- -- - This extension provides API support for -- <https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GLSL_EXT_ray_tracing.txt GLSL_EXT_ray_tracing> -- -- - This extension interacts with -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.2 Vulkan 1.2> -- and @VK_KHR_vulkan_memory_model@, adding the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#shader-call-related shader-call-related> -- relation of invocations, -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#shader-call-order shader-call-order> -- partial order of dynamic instances of instructions, and the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#shaders-scope-shadercall ShaderCallKHR> -- scope. -- -- - This extension interacts with @VK_KHR_pipeline_library@, -- enabling pipeline libraries to be used with ray tracing -- pipelines and enabling usage of -- 'RayTracingPipelineInterfaceCreateInfoKHR'. -- -- [__Contributors__] -- -- - Matthäus Chajdas, AMD -- -- - Greg Grebe, AMD -- -- - Nicolai Hähnle, AMD -- -- - Tobias Hector, AMD -- -- - Dave Oldcorn, AMD -- -- - Skyler Saleh, AMD -- -- - Mathieu Robart, Arm -- -- - Marius Bjorge, Arm -- -- - Tom Olson, Arm -- -- - Sebastian Tafuri, EA -- -- - Henrik Rydgard, Embark -- -- - Juan Cañada, Epic Games -- -- - Patrick Kelly, Epic Games -- -- - Yuriy O’Donnell, Epic Games -- -- - Michael Doggett, Facebook\/Oculus -- -- - Andrew Garrard, Imagination -- -- - Don Scorgie, Imagination -- -- - Dae Kim, Imagination -- -- - Joshua Barczak, Intel -- -- - Slawek Grajewski, Intel -- -- - Jeff Bolz, NVIDIA -- -- - Pascal Gautron, NVIDIA -- -- - Daniel Koch, NVIDIA -- -- - Christoph Kubisch, NVIDIA -- -- - Ashwin Lele, NVIDIA -- -- - Robert Stepinski, NVIDIA -- -- - Martin Stich, NVIDIA -- -- - Nuno Subtil, NVIDIA -- -- - Eric Werness, NVIDIA -- -- - Jon Leech, Khronos -- -- - Jeroen van Schijndel, OTOY -- -- - Juul Joosten, OTOY -- -- - Alex Bourd, Qualcomm -- -- - Roman Larionov, Qualcomm -- -- - David McAllister, Qualcomm -- -- - Spencer Fricke, Samsung -- -- - Lewis Gordon, Samsung -- -- - Ralph Potter, Samsung -- -- - Jasper Bekkers, Traverse Research -- -- - Jesse Barker, Unity -- -- - Baldur Karlsson, Valve -- -- == Description -- -- Rasterization has been the dominant method to produce interactive -- graphics, but increasing performance of graphics hardware has made ray -- tracing a viable option for interactive rendering. Being able to -- integrate ray tracing with traditional rasterization makes it easier for -- applications to incrementally add ray traced effects to existing -- applications or to do hybrid approaches with rasterization for primary -- visibility and ray tracing for secondary queries. -- -- To enable ray tracing, this extension adds a few different categories of -- new functionality: -- -- - A new ray tracing pipeline type with new shader domains: ray -- generation, intersection, any-hit, closest hit, miss, and callable -- -- - A shader binding indirection table to link shader groups with -- acceleration structure items -- -- - Ray tracing commands which initiate the ray pipeline traversal and -- invocation of the various new shader domains depending on which -- traversal conditions are met -- -- This extension adds support for the following SPIR-V extension in -- Vulkan: -- -- - @SPV_KHR_ray_tracing@ -- -- == New Commands -- -- - 'cmdSetRayTracingPipelineStackSizeKHR' -- -- - 'cmdTraceRaysIndirectKHR' -- -- - 'cmdTraceRaysKHR' -- -- - 'createRayTracingPipelinesKHR' -- -- - 'getRayTracingCaptureReplayShaderGroupHandlesKHR' -- -- - 'getRayTracingShaderGroupHandlesKHR' -- -- - 'getRayTracingShaderGroupStackSizeKHR' -- -- == New Structures -- -- - 'RayTracingPipelineCreateInfoKHR' -- -- - 'RayTracingPipelineInterfaceCreateInfoKHR' -- -- - 'RayTracingShaderGroupCreateInfoKHR' -- -- - 'StridedDeviceAddressRegionKHR' -- -- - 'TraceRaysIndirectCommandKHR' -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2', -- 'Vulkan.Core10.Device.DeviceCreateInfo': -- -- - 'PhysicalDeviceRayTracingPipelineFeaturesKHR' -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2': -- -- - 'PhysicalDeviceRayTracingPipelinePropertiesKHR' -- -- == New Enums -- -- - 'RayTracingShaderGroupTypeKHR' -- -- - 'ShaderGroupShaderKHR' -- -- == New Enum Constants -- -- - 'KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME' -- -- - 'KHR_RAY_TRACING_PIPELINE_SPEC_VERSION' -- -- - 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' -- -- - Extending -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BufferUsageFlagBits': -- -- - 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- -- - Extending 'Vulkan.Core10.Enums.DynamicState.DynamicState': -- -- - 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR' -- -- - Extending 'Vulkan.Core10.Enums.PipelineBindPoint.PipelineBindPoint': -- -- - 'Vulkan.Core10.Enums.PipelineBindPoint.PIPELINE_BIND_POINT_RAY_TRACING_KHR' -- -- - Extending -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits': -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_ANY_HIT_SHADERS_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_MISS_SHADERS_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_AABBS_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR' -- -- - Extending -- 'Vulkan.Core10.Enums.PipelineStageFlagBits.PipelineStageFlagBits': -- -- - 'Vulkan.Core10.Enums.PipelineStageFlagBits.PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR' -- -- - Extending -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.ShaderStageFlagBits': -- -- - 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_ANY_HIT_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_CALLABLE_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_CLOSEST_HIT_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_INTERSECTION_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_MISS_BIT_KHR' -- -- - 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_RAYGEN_BIT_KHR' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RAY_TRACING_PIPELINE_INTERFACE_CREATE_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR' -- -- == New or Modified Built-In Variables -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-launchid LaunchIdKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-launchsize LaunchSizeKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-worldrayorigin WorldRayOriginKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-worldraydirection WorldRayDirectionKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-objectrayorigin ObjectRayOriginKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-objectraydirection ObjectRayDirectionKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-raytmin RayTminKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-raytmax RayTmaxKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-instancecustomindex InstanceCustomIndexKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-instanceid InstanceId> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-objecttoworld ObjectToWorldKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-worldtoobject WorldToObjectKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-hitkind HitKindKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-incomingrayflags IncomingRayFlagsKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-raygeometryindex RayGeometryIndexKHR> -- -- - (modified)@PrimitiveId@ -- -- == New SPIR-V Capabilities -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#spirvenv-capabilities-table-RayTracingKHR RayTracingKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#spirvenv-capabilities-table-RayTraversalPrimitiveCullingKHR RayTraversalPrimitiveCullingKHR> -- -- == Issues -- -- (1) How does this extension differ from VK_NV_ray_tracing? -- -- __DISCUSSION__: -- -- The following is a summary of the main functional differences between -- VK_KHR_ray_tracing_pipeline and VK_NV_ray_tracing: -- -- - added support for indirect ray tracing ('cmdTraceRaysIndirectKHR') -- -- - uses SPV_KHR_ray_tracing instead of SPV_NV_ray_tracing -- -- - refer to KHR SPIR-V enums instead of NV SPIR-V enums (which are -- functionally equivalent and aliased to the same values). -- -- - added @RayGeometryIndexKHR@ built-in -- -- - removed vkCompileDeferredNV compilation functionality and replaced -- with -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#deferred-host-operations deferred host operations> -- interactions for ray tracing -- -- - added 'PhysicalDeviceRayTracingPipelineFeaturesKHR' structure -- -- - extended 'PhysicalDeviceRayTracingPipelinePropertiesKHR' structure -- -- - renamed @maxRecursionDepth@ to @maxRayRecursionDepth@ and it has -- a minimum of 1 instead of 31 -- -- - require @shaderGroupHandleSize@ to be 32 bytes -- -- - added @maxRayDispatchInvocationCount@, -- @shaderGroupHandleAlignment@ and @maxRayHitAttributeSize@ -- -- - reworked geometry structures so they could be better shared between -- device, host, and indirect builds -- -- - changed SBT parameters to a structure and added size -- ('StridedDeviceAddressRegionKHR') -- -- - add parameter for requesting memory requirements for host and\/or -- device build -- -- - added -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#pipeline-library pipeline library> -- support for ray tracing -- -- - added -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#ray-traversal-watertight watertightness guarantees> -- -- - added no-null-shader pipeline flags -- (@VK_PIPELINE_CREATE_RAY_TRACING_NO_NULL_*_SHADERS_BIT_KHR@) -- -- - added -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#ray-tracing-shader-call memory model interactions> -- with ray tracing and define how subgroups work and can be repacked -- -- (2) Can you give a more detailed comparision of differences and -- similarities between VK_NV_ray_tracing and VK_KHR_ray_tracing_pipeline? -- -- __DISCUSSION__: -- -- The following is a more detailed comparision of which commands, -- structures, and enums are aliased, changed, or removed. -- -- - Aliased functionality — enums, structures, and commands that are -- considered equivalent: -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.RayTracingShaderGroupTypeNV' -- ↔ 'RayTracingShaderGroupTypeKHR' -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.getRayTracingShaderGroupHandlesNV' -- ↔ 'getRayTracingShaderGroupHandlesKHR' -- -- - Changed enums, structures, and commands: -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.RayTracingShaderGroupCreateInfoNV' -- → 'RayTracingShaderGroupCreateInfoKHR' (added -- @pShaderGroupCaptureReplayHandle@) -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.RayTracingPipelineCreateInfoNV' -- → 'RayTracingPipelineCreateInfoKHR' (changed type of @pGroups@, -- added @libraries@, @pLibraryInterface@, and @pDynamicState@) -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.PhysicalDeviceRayTracingPropertiesNV' -- → VkPhysicalDeviceRayTracingPropertiesKHR (renamed -- @maxTriangleCount@ to @maxPrimitiveCount@, added -- @shaderGroupHandleCaptureReplaySize@) -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.cmdTraceRaysNV' → -- 'cmdTraceRaysKHR' (params to struct) -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.createRayTracingPipelinesNV' -- → 'createRayTracingPipelinesKHR' (different struct, changed -- functionality) -- -- - Added enums, structures and commands: -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_ANY_HIT_SHADERS_BIT_KHR' -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR', -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_MISS_SHADERS_BIT_KHR', -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR', -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR', -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_AABBS_BIT_KHR' -- to -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits' -- -- - 'PhysicalDeviceRayTracingPipelineFeaturesKHR' structure -- -- - 'Vulkan.Extensions.VK_KHR_acceleration_structure.DeviceOrHostAddressKHR' -- and -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.DeviceOrHostAddressConstKHR' -- unions -- -- - 'Vulkan.Extensions.VK_KHR_pipeline_library.PipelineLibraryCreateInfoKHR' -- struct -- -- - 'RayTracingPipelineInterfaceCreateInfoKHR' struct -- -- - 'StridedDeviceAddressRegionKHR' struct -- -- - 'cmdTraceRaysIndirectKHR' command and -- 'TraceRaysIndirectCommandKHR' struct -- -- - 'getRayTracingCaptureReplayShaderGroupHandlesKHR' (shader group -- capture\/replay) -- -- - 'cmdSetRayTracingPipelineStackSizeKHR' and -- 'getRayTracingShaderGroupStackSizeKHR' commands for stack size -- control -- -- - Functionality removed: -- -- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_DEFER_COMPILE_BIT_NV' -- -- - 'Vulkan.Extensions.VK_NV_ray_tracing.compileDeferredNV' command -- (replaced with @VK_KHR_deferred_host_operations@) -- -- (3) What are the changes between the public provisional -- (VK_KHR_ray_tracing v8) release and the internal provisional -- (VK_KHR_ray_tracing v9) release? -- -- - Require Vulkan 1.1 and SPIR-V 1.4 -- -- - Added interactions with Vulkan 1.2 and @VK_KHR_vulkan_memory_model@ -- -- - added creation time capture and replay flags -- -- - added -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR' -- to -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits' -- -- - replace @VkStridedBufferRegionKHR@ with -- 'StridedDeviceAddressRegionKHR' and change 'cmdTraceRaysKHR', -- 'cmdTraceRaysIndirectKHR', to take these for the shader binding -- table and use device addresses instead of buffers. -- -- - require the shader binding table buffers to have the -- @VK_BUFFER_USAGE_RAY_TRACING_BIT_KHR@ set -- -- - make @VK_KHR_pipeline_library@ an interaction instead of required -- extension -- -- - rename the @libraries@ member of 'RayTracingPipelineCreateInfoKHR' -- to @pLibraryInfo@ and make it a pointer -- -- - make @VK_KHR_deferred_host_operations@ an interaction instead of a -- required extension (later went back on this) -- -- - added explicit stack size management for ray tracing pipelines -- -- - removed the @maxCallableSize@ member of -- 'RayTracingPipelineInterfaceCreateInfoKHR' -- -- - added the @pDynamicState@ member to -- 'RayTracingPipelineCreateInfoKHR' -- -- - added -- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR' -- dynamic state for ray tracing pipelines -- -- - added 'getRayTracingShaderGroupStackSizeKHR' and -- 'cmdSetRayTracingPipelineStackSizeKHR' commands -- -- - added 'ShaderGroupShaderKHR' enum -- -- - Added @maxRayDispatchInvocationCount@ limit to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR' -- -- - Added @shaderGroupHandleAlignment@ property to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR' -- -- - Added @maxRayHitAttributeSize@ property to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR' -- -- - Clarify deferred host ops for pipeline creation -- -- - 'Vulkan.Extensions.Handles.DeferredOperationKHR' is now a -- top-level parameter for 'createRayTracingPipelinesKHR' -- -- - removed @VkDeferredOperationInfoKHR@ structure -- -- - change deferred host creation\/return parameter behavior such -- that the implementation can modify such parameters until the -- deferred host operation completes -- -- - @VK_KHR_deferred_host_operations@ is required again -- -- (4) What are the changes between the internal provisional -- (VK_KHR_ray_tracing v9) release and the final -- (VK_KHR_acceleration_structure v11 \/ VK_KHR_ray_tracing_pipeline v1) -- release? -- -- - refactor VK_KHR_ray_tracing into 3 extensions, enabling -- implementation flexibility and decoupling ray query support from ray -- pipelines: -- -- - @VK_KHR_acceleration_structure@ (for acceleration structure -- operations) -- -- - @VK_KHR_ray_tracing_pipeline@ (for ray tracing pipeline and -- shader stages) -- -- - @VK_KHR_ray_query@ (for ray queries in existing shader stages) -- -- - Require @Volatile@ for the following builtins in the ray generation, -- closest hit, miss, intersection, and callable shader stages: -- -- - @SubgroupSize@, @SubgroupLocalInvocationId@, @SubgroupEqMask@, -- @SubgroupGeMask@, @SubgroupGtMask@, @SubgroupLeMask@, -- @SubgroupLtMask@ -- -- - @SMIDNV@, @WarpIDNV@ -- -- - clarify buffer usage flags for ray tracing -- -- - 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- is added as an alias of -- 'Vulkan.Extensions.VK_NV_ray_tracing.BUFFER_USAGE_RAY_TRACING_BIT_NV' -- and is required on shader binding table buffers -- -- - 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_STORAGE_BUFFER_BIT' -- is used in @VK_KHR_acceleration_structure@ for @scratchData@ -- -- - rename @maxRecursionDepth@ to @maxRayPipelineRecursionDepth@ -- (pipeline creation) and @maxRayRecursionDepth@ (limit) to reduce -- confusion -- -- - Add queryable @maxRayHitAttributeSize@ limit and rename members of -- 'RayTracingPipelineInterfaceCreateInfoKHR' to -- @maxPipelineRayPayloadSize@ and @maxPipelineRayHitAttributeSize@ for -- clarity -- -- - Update SPIRV capabilities to use @RayTracingKHR@ -- -- - extension is no longer provisional -- -- - define synchronization requirements for indirect trace rays and -- indirect buffer -- -- (5) This extension adds gl_InstanceID for the intersection, any-hit, and -- closest hit shaders, but in KHR_vulkan_glsl, gl_InstanceID is replaced -- with gl_InstanceIndex. Which should be used for Vulkan in this -- extension? -- -- __RESOLVED__: This extension uses gl_InstanceID and maps it to -- @InstanceId@ in SPIR-V. It is acknowledged that this is different than -- other shader stages in Vulkan. There are two main reasons for the -- difference here: -- -- - symmetry with gl_PrimitiveID which is also available in these -- shaders -- -- - there is no “baseInstance” relevant for these shaders, and so ID -- makes it more obvious that this is zero-based. -- -- == Sample Code -- -- Example ray generation GLSL shader -- -- > #version 450 core -- > #extension GL_EXT_ray_tracing : require -- > layout(set = 0, binding = 0, rgba8) uniform image2D image; -- > layout(set = 0, binding = 1) uniform accelerationStructureEXT as; -- > layout(location = 0) rayPayloadEXT float payload; -- > -- > void main() -- > { -- > vec4 col = vec4(0, 0, 0, 1); -- > -- > vec3 origin = vec3(float(gl_LaunchIDEXT.x)/float(gl_LaunchSizeEXT.x), float(gl_LaunchIDEXT.y)/float(gl_LaunchSizeEXT.y), 1.0); -- > vec3 dir = vec3(0.0, 0.0, -1.0); -- > -- > traceRayEXT(as, 0, 0xff, 0, 1, 0, origin, 0.0, dir, 1000.0, 0); -- > -- > col.y = payload; -- > -- > imageStore(image, ivec2(gl_LaunchIDEXT.xy), col); -- > } -- -- == Version History -- -- - Revision 1, 2020-11-12 (Mathieu Robart, Daniel Koch, Eric Werness, -- Tobias Hector) -- -- - Decomposition of the specification, from VK_KHR_ray_tracing to -- VK_KHR_ray_tracing_pipeline (#1918,!3912) -- -- - require certain subgroup and sm_shader_builtin shader builtins -- to be decorated as volatile in the ray generation, closest hit, -- miss, intersection, and callable stages (#1924,!3903,!3954) -- -- - clarify buffer usage flags for ray tracing (#2181,!3939) -- -- - rename maxRecursionDepth to maxRayPipelineRecursionDepth and -- maxRayRecursionDepth (#2203,!3937) -- -- - add queriable maxRayHitAttributeSize and rename members of -- VkRayTracingPipelineInterfaceCreateInfoKHR (#2102,!3966) -- -- - update to use @RayTracingKHR@ SPIR-V capability -- -- - add VUs for matching hit group type against geometry type -- (#2245,!3994) -- -- - require @RayTMaxKHR@ be volatile in intersection shaders -- (#2268,!4030) -- -- - add numerical limits for ray parameters (#2235,!3960) -- -- - fix SBT indexing rules for device addresses (#2308,!4079) -- -- - relax formula for ray intersection candidate determination -- (#2322,!4080) -- -- - add more details on @ShaderRecordBufferKHR@ variables -- (#2230,!4083) -- -- - clarify valid bits for @InstanceCustomIndexKHR@ -- (GLSL\/GLSL#19,!4128) -- -- - allow at most one @IncomingRayPayloadKHR@, -- @IncomingCallableDataKHR@, and @HitAttributeKHR@ (!4129) -- -- - add minimum for maxShaderGroupStride (#2353,!4131) -- -- - require VK_KHR_pipeline_library extension to be supported -- (#2348,!4135) -- -- - clarify meaning of \'geometry index\' (#2272,!4137) -- -- - restrict traces to TLAS (#2239,!4141) -- -- - add note about maxPipelineRayPayloadSize (#2383,!4172) -- -- - do not require raygen shader in pipeline libraries (!4185) -- -- - define sync for indirect trace rays and indirect buffer -- (#2407,!4208) -- -- == See Also -- -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR', -- 'PhysicalDeviceRayTracingPipelineFeaturesKHR', -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR', -- 'RayTracingPipelineCreateInfoKHR', -- 'RayTracingPipelineInterfaceCreateInfoKHR', -- 'RayTracingShaderGroupCreateInfoKHR', 'RayTracingShaderGroupTypeKHR', -- 'ShaderGroupShaderKHR', 'StridedDeviceAddressRegionKHR', -- 'TraceRaysIndirectCommandKHR', 'cmdSetRayTracingPipelineStackSizeKHR', -- 'cmdTraceRaysIndirectKHR', 'cmdTraceRaysKHR', -- 'createRayTracingPipelinesKHR', -- 'getRayTracingCaptureReplayShaderGroupHandlesKHR', -- 'getRayTracingShaderGroupHandlesKHR', -- 'getRayTracingShaderGroupStackSizeKHR' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline 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_ray_tracing_pipeline ( cmdTraceRaysKHR , getRayTracingShaderGroupHandlesKHR , getRayTracingCaptureReplayShaderGroupHandlesKHR , createRayTracingPipelinesKHR , withRayTracingPipelinesKHR , cmdTraceRaysIndirectKHR , getRayTracingShaderGroupStackSizeKHR , cmdSetRayTracingPipelineStackSizeKHR , RayTracingShaderGroupCreateInfoKHR(..) , RayTracingPipelineCreateInfoKHR(..) , PhysicalDeviceRayTracingPipelineFeaturesKHR(..) , PhysicalDeviceRayTracingPipelinePropertiesKHR(..) , StridedDeviceAddressRegionKHR(..) , TraceRaysIndirectCommandKHR(..) , RayTracingPipelineInterfaceCreateInfoKHR(..) , RayTracingShaderGroupTypeKHR( RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR , RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR , RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR , .. ) , ShaderGroupShaderKHR( SHADER_GROUP_SHADER_GENERAL_KHR , SHADER_GROUP_SHADER_CLOSEST_HIT_KHR , SHADER_GROUP_SHADER_ANY_HIT_KHR , SHADER_GROUP_SHADER_INTERSECTION_KHR , .. ) , KHR_RAY_TRACING_PIPELINE_SPEC_VERSION , pattern KHR_RAY_TRACING_PIPELINE_SPEC_VERSION , KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME , pattern KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME , DeferredOperationKHR(..) , PipelineLibraryCreateInfoKHR(..) , SHADER_UNUSED_KHR , pattern SHADER_UNUSED_KHR ) where 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.Foldable (traverse_) import Data.Typeable (eqT) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import Foreign.Marshal.Utils (maybePeek) 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 (showsPrec) 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 Foreign.C.Types (CSize(..)) 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.String (IsString) import Data.Type.Equality ((:~:)(Refl)) import Data.Typeable (Typeable) import Foreign.C.Types (CSize) import Foreign.C.Types (CSize(CSize)) 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 Data.Int (Int32) 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.Core10.Pipeline (destroyPipeline) import Vulkan.CStruct.Extends (forgetExtensions) import Vulkan.CStruct.Extends (peekSomeCStruct) import Vulkan.CStruct.Extends (pokeSomeCStruct) import Vulkan.NamedType ((:::)) import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.CStruct.Extends (Chain) import Vulkan.Core10.Handles (CommandBuffer) import Vulkan.Core10.Handles (CommandBuffer(..)) import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer)) import Vulkan.Core10.Handles (CommandBuffer_T) import Vulkan.Extensions.Handles (DeferredOperationKHR) import Vulkan.Extensions.Handles (DeferredOperationKHR(..)) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Core10.FundamentalTypes (DeviceAddress) import Vulkan.Dynamic (DeviceCmds(pVkCmdSetRayTracingPipelineStackSizeKHR)) import Vulkan.Dynamic (DeviceCmds(pVkCmdTraceRaysIndirectKHR)) import Vulkan.Dynamic (DeviceCmds(pVkCmdTraceRaysKHR)) import Vulkan.Dynamic (DeviceCmds(pVkCreateRayTracingPipelinesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetRayTracingCaptureReplayShaderGroupHandlesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetRayTracingShaderGroupHandlesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetRayTracingShaderGroupStackSizeKHR)) import Vulkan.Core10.FundamentalTypes (DeviceSize) import Vulkan.Core10.Handles (Device_T) import Vulkan.CStruct.Extends (Extends) import Vulkan.CStruct.Extends (Extendss) import Vulkan.CStruct.Extends (Extensible(..)) import Vulkan.CStruct.Extends (PeekChain) import Vulkan.CStruct.Extends (PeekChain(..)) import Vulkan.Core10.Handles (Pipeline) import Vulkan.Core10.Handles (Pipeline(..)) import Vulkan.Core10.Handles (PipelineCache) import Vulkan.Core10.Handles (PipelineCache(..)) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags) import {-# SOURCE #-} Vulkan.Core13.Promoted_From_VK_EXT_pipeline_creation_feedback (PipelineCreationFeedbackCreateInfo) import Vulkan.Core10.Pipeline (PipelineDynamicStateCreateInfo) import Vulkan.Core10.Handles (PipelineLayout) import Vulkan.Extensions.VK_KHR_pipeline_library (PipelineLibraryCreateInfoKHR) import Vulkan.Core10.Pipeline (PipelineShaderStageCreateInfo) import Vulkan.CStruct.Extends (PokeChain) import Vulkan.CStruct.Extends (PokeChain(..)) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.CStruct.Extends (SomeStruct) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RAY_TRACING_PIPELINE_INTERFACE_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Extensions.Handles (DeferredOperationKHR(..)) import Vulkan.Extensions.VK_KHR_pipeline_library (PipelineLibraryCreateInfoKHR(..)) import Vulkan.Core10.APIConstants (SHADER_UNUSED_KHR) import Vulkan.Core10.APIConstants (pattern SHADER_UNUSED_KHR) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCmdTraceRaysKHR :: FunPtr (Ptr CommandBuffer_T -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Word32 -> Word32 -> Word32 -> IO ()) -> Ptr CommandBuffer_T -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Word32 -> Word32 -> Word32 -> IO () -- | vkCmdTraceRaysKHR - Initialize a ray tracing dispatch -- -- = Description -- -- When the command is executed, a ray generation group of @width@ × -- @height@ × @depth@ rays is assembled. -- -- == Valid Usage -- -- - #VUID-vkCmdTraceRaysKHR-magFilter-04553# If a -- 'Vulkan.Core10.Handles.Sampler' created with @magFilter@ or -- @minFilter@ equal to 'Vulkan.Core10.Enums.Filter.FILTER_LINEAR' and -- @compareEnable@ equal to 'Vulkan.Core10.FundamentalTypes.FALSE' is -- used to sample a 'Vulkan.Core10.Handles.ImageView' as a result of -- this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT' -- -- - #VUID-vkCmdTraceRaysKHR-mipmapMode-04770# If a -- 'Vulkan.Core10.Handles.Sampler' created with @mipmapMode@ equal to -- 'Vulkan.Core10.Enums.SamplerMipmapMode.SAMPLER_MIPMAP_MODE_LINEAR' -- and @compareEnable@ equal to 'Vulkan.Core10.FundamentalTypes.FALSE' -- is used to sample a 'Vulkan.Core10.Handles.ImageView' as a result of -- this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT' -- -- - #VUID-vkCmdTraceRaysKHR-None-06479# If a -- 'Vulkan.Core10.Handles.ImageView' is sampled with -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#textures-depth-compare-operation depth comparison>, -- the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_SAMPLED_IMAGE_DEPTH_COMPARISON_BIT' -- -- - #VUID-vkCmdTraceRaysKHR-None-02691# If a -- 'Vulkan.Core10.Handles.ImageView' is accessed using atomic -- operations as a result of this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT' -- -- - #VUID-vkCmdTraceRaysKHR-None-02692# If a -- 'Vulkan.Core10.Handles.ImageView' is sampled with -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FILTER_CUBIC_EXT' as a result -- of this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT' -- -- - #VUID-vkCmdTraceRaysKHR-filterCubic-02694# Any -- 'Vulkan.Core10.Handles.ImageView' being sampled with -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FILTER_CUBIC_EXT' as a result -- of this command /must/ have a -- 'Vulkan.Core10.Enums.ImageViewType.ImageViewType' and format that -- supports cubic filtering, as specified by -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FilterCubicImageViewImageFormatPropertiesEXT'::@filterCubic@ -- returned by -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceImageFormatProperties2' -- -- - #VUID-vkCmdTraceRaysKHR-filterCubicMinmax-02695# Any -- 'Vulkan.Core10.Handles.ImageView' being sampled with -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FILTER_CUBIC_EXT' with a -- reduction mode of either -- 'Vulkan.Core12.Enums.SamplerReductionMode.SAMPLER_REDUCTION_MODE_MIN' -- or -- 'Vulkan.Core12.Enums.SamplerReductionMode.SAMPLER_REDUCTION_MODE_MAX' -- as a result of this command /must/ have a -- 'Vulkan.Core10.Enums.ImageViewType.ImageViewType' and format that -- supports cubic filtering together with minmax filtering, as -- specified by -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FilterCubicImageViewImageFormatPropertiesEXT'::@filterCubicMinmax@ -- returned by -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceImageFormatProperties2' -- -- - #VUID-vkCmdTraceRaysKHR-flags-02696# Any -- 'Vulkan.Core10.Handles.Image' created with a -- 'Vulkan.Core10.Image.ImageCreateInfo'::@flags@ containing -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_CORNER_SAMPLED_BIT_NV' -- sampled as a result of this command /must/ only be sampled using a -- 'Vulkan.Core10.Enums.SamplerAddressMode.SamplerAddressMode' of -- 'Vulkan.Core10.Enums.SamplerAddressMode.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE' -- -- - #VUID-vkCmdTraceRaysKHR-OpTypeImage-06423# Any -- 'Vulkan.Core10.Handles.ImageView' or -- 'Vulkan.Core10.Handles.BufferView' being written as a storage image -- or storage texel buffer where the image format field of the -- @OpTypeImage@ is @Unknown@ /must/ have image format features that -- support -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT' -- -- - #VUID-vkCmdTraceRaysKHR-OpTypeImage-06424# Any -- 'Vulkan.Core10.Handles.ImageView' or -- 'Vulkan.Core10.Handles.BufferView' being read as a storage image or -- storage texel buffer where the image format field of the -- @OpTypeImage@ is @Unknown@ /must/ have image format features that -- support -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT' -- -- - #VUID-vkCmdTraceRaysKHR-None-02697# For each set /n/ that is -- statically used by the 'Vulkan.Core10.Handles.Pipeline' bound to the -- pipeline bind point used by this command, a descriptor set /must/ -- have been bound to /n/ at the same pipeline bind point, with a -- 'Vulkan.Core10.Handles.PipelineLayout' that is compatible for set -- /n/, with the 'Vulkan.Core10.Handles.PipelineLayout' used to create -- the current 'Vulkan.Core10.Handles.Pipeline', as described in -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#descriptorsets-compatibility ???> -- -- - #VUID-vkCmdTraceRaysKHR-maintenance4-06425# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-maintenance4 maintenance4> -- feature is not enabled, then for each push constant that is -- statically used by the 'Vulkan.Core10.Handles.Pipeline' bound to the -- pipeline bind point used by this command, a push constant value -- /must/ have been set for the same pipeline bind point, with a -- 'Vulkan.Core10.Handles.PipelineLayout' that is compatible for push -- constants, with the 'Vulkan.Core10.Handles.PipelineLayout' used to -- create the current 'Vulkan.Core10.Handles.Pipeline', as described in -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#descriptorsets-compatibility ???> -- -- - #VUID-vkCmdTraceRaysKHR-None-02699# Descriptors in each bound -- descriptor set, specified via -- 'Vulkan.Core10.CommandBufferBuilding.cmdBindDescriptorSets', /must/ -- be valid if they are statically used by the -- 'Vulkan.Core10.Handles.Pipeline' bound to the pipeline bind point -- used by this command -- -- - #VUID-vkCmdTraceRaysKHR-None-02700# A valid pipeline /must/ be bound -- to the pipeline bind point used by this command -- -- - #VUID-vkCmdTraceRaysKHR-commandBuffer-02701# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command requires any dynamic state, that state -- /must/ have been set or inherited (if the -- @VK_NV_inherited_viewport_scissor@ extension is enabled) for -- @commandBuffer@, and done so after any previously bound pipeline -- with the corresponding state not specified as dynamic -- -- - #VUID-vkCmdTraceRaysKHR-None-02859# There /must/ not have been any -- calls to dynamic state setting commands for any state not specified -- as dynamic in the 'Vulkan.Core10.Handles.Pipeline' object bound to -- the pipeline bind point used by this command, since that pipeline -- was bound -- -- - #VUID-vkCmdTraceRaysKHR-None-02702# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command accesses a -- 'Vulkan.Core10.Handles.Sampler' object that uses unnormalized -- coordinates, that sampler /must/ not be used to sample from any -- 'Vulkan.Core10.Handles.Image' with a -- 'Vulkan.Core10.Handles.ImageView' of the type -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_3D', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_1D_ARRAY', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE_ARRAY', in -- any shader stage -- -- - #VUID-vkCmdTraceRaysKHR-None-02703# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command accesses a -- 'Vulkan.Core10.Handles.Sampler' object that uses unnormalized -- coordinates, that sampler /must/ not be used with any of the SPIR-V -- @OpImageSample*@ or @OpImageSparseSample*@ instructions with -- @ImplicitLod@, @Dref@ or @Proj@ in their name, in any shader stage -- -- - #VUID-vkCmdTraceRaysKHR-None-02704# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command accesses a -- 'Vulkan.Core10.Handles.Sampler' object that uses unnormalized -- coordinates, that sampler /must/ not be used with any of the SPIR-V -- @OpImageSample*@ or @OpImageSparseSample*@ instructions that -- includes a LOD bias or any offset values, in any shader stage -- -- - #VUID-vkCmdTraceRaysKHR-None-02705# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-robustBufferAccess robust buffer access> -- feature is not enabled, and if the 'Vulkan.Core10.Handles.Pipeline' -- object bound to the pipeline bind point used by this command -- accesses a uniform buffer, it /must/ not access values outside of -- the range of the buffer as specified in the descriptor set bound to -- the same pipeline bind point -- -- - #VUID-vkCmdTraceRaysKHR-None-02706# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-robustBufferAccess robust buffer access> -- feature is not enabled, and if the 'Vulkan.Core10.Handles.Pipeline' -- object bound to the pipeline bind point used by this command -- accesses a storage buffer, it /must/ not access values outside of -- the range of the buffer as specified in the descriptor set bound to -- the same pipeline bind point -- -- - #VUID-vkCmdTraceRaysKHR-commandBuffer-02707# If @commandBuffer@ is -- an unprotected command buffer and -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#limits-protectedNoFault protectedNoFault> -- is not supported, any resource accessed by the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command /must/ not be a protected resource -- -- - #VUID-vkCmdTraceRaysKHR-None-04115# If a -- 'Vulkan.Core10.Handles.ImageView' is accessed using @OpImageWrite@ -- as a result of this command, then the @Type@ of the @Texel@ operand -- of that instruction /must/ have at least as many components as the -- image view’s format -- -- - #VUID-vkCmdTraceRaysKHR-OpImageWrite-04469# If a -- 'Vulkan.Core10.Handles.BufferView' is accessed using @OpImageWrite@ -- as a result of this command, then the @Type@ of the @Texel@ operand -- of that instruction /must/ have at least as many components as the -- buffer view’s format -- -- - #VUID-vkCmdTraceRaysKHR-SampledType-04470# If a -- 'Vulkan.Core10.Handles.ImageView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a 64-bit component -- width is accessed as a result of this command, the @SampledType@ of -- the @OpTypeImage@ operand of that instruction /must/ have a @Width@ -- of 64 -- -- - #VUID-vkCmdTraceRaysKHR-SampledType-04471# If a -- 'Vulkan.Core10.Handles.ImageView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a component width less -- than 64-bit is accessed as a result of this command, the -- @SampledType@ of the @OpTypeImage@ operand of that instruction -- /must/ have a @Width@ of 32 -- -- - #VUID-vkCmdTraceRaysKHR-SampledType-04472# If a -- 'Vulkan.Core10.Handles.BufferView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a 64-bit component -- width is accessed as a result of this command, the @SampledType@ of -- the @OpTypeImage@ operand of that instruction /must/ have a @Width@ -- of 64 -- -- - #VUID-vkCmdTraceRaysKHR-SampledType-04473# If a -- 'Vulkan.Core10.Handles.BufferView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a component width less -- than 64-bit is accessed as a result of this command, the -- @SampledType@ of the @OpTypeImage@ operand of that instruction -- /must/ have a @Width@ of 32 -- -- - #VUID-vkCmdTraceRaysKHR-sparseImageInt64Atomics-04474# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-sparseImageInt64Atomics sparseImageInt64Atomics> -- feature is not enabled, 'Vulkan.Core10.Handles.Image' objects -- created with the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_RESIDENCY_BIT' -- flag /must/ not be accessed by atomic instructions through an -- @OpTypeImage@ with a @SampledType@ with a @Width@ of 64 by this -- command -- -- - #VUID-vkCmdTraceRaysKHR-sparseImageInt64Atomics-04475# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-sparseImageInt64Atomics sparseImageInt64Atomics> -- feature is not enabled, 'Vulkan.Core10.Handles.Buffer' objects -- created with the -- 'Vulkan.Core10.Enums.BufferCreateFlagBits.BUFFER_CREATE_SPARSE_RESIDENCY_BIT' -- flag /must/ not be accessed by atomic instructions through an -- @OpTypeImage@ with a @SampledType@ with a @Width@ of 64 by this -- command -- -- - #VUID-vkCmdTraceRaysKHR-None-03429# Any shader group handle -- referenced by this call /must/ have been queried from the currently -- bound ray tracing pipeline -- -- - #VUID-vkCmdTraceRaysKHR-maxPipelineRayRecursionDepth-03679# This -- command /must/ not cause a shader call instruction to be executed -- from a shader invocation with a -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#ray-tracing-recursion-depth recursion depth> -- greater than the value of @maxPipelineRayRecursionDepth@ used to -- create the bound ray tracing pipeline -- -- - #VUID-vkCmdTraceRaysKHR-pRayGenShaderBindingTable-03680# If the -- buffer from which @pRayGenShaderBindingTable->deviceAddress@ was -- queried is non-sparse then it /must/ be bound completely and -- contiguously to a single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysKHR-pRayGenShaderBindingTable-03681# The buffer -- from which the @pRayGenShaderBindingTable->deviceAddress@ is queried -- /must/ have been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysKHR-pRayGenShaderBindingTable-03682# -- @pRayGenShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysKHR-size-04023# The @size@ member of -- @pRayGenShaderBindingTable@ /must/ be equal to its @stride@ member -- -- - #VUID-vkCmdTraceRaysKHR-pMissShaderBindingTable-03683# If the buffer -- from which @pMissShaderBindingTable->deviceAddress@ was queried is -- non-sparse then it /must/ be bound completely and contiguously to a -- single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysKHR-pMissShaderBindingTable-03684# The buffer -- from which the @pMissShaderBindingTable->deviceAddress@ is queried -- /must/ have been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysKHR-pMissShaderBindingTable-03685# -- @pMissShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysKHR-stride-03686# The @stride@ member of -- @pMissShaderBindingTable@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleAlignment@ -- -- - #VUID-vkCmdTraceRaysKHR-stride-04029# The @stride@ member of -- @pMissShaderBindingTable@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxShaderGroupStride@ -- -- - #VUID-vkCmdTraceRaysKHR-pHitShaderBindingTable-03687# If the buffer -- from which @pHitShaderBindingTable->deviceAddress@ was queried is -- non-sparse then it /must/ be bound completely and contiguously to a -- single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysKHR-pHitShaderBindingTable-03688# The buffer -- from which the @pHitShaderBindingTable->deviceAddress@ is queried -- /must/ have been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysKHR-pHitShaderBindingTable-03689# -- @pHitShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysKHR-stride-03690# The @stride@ member of -- @pHitShaderBindingTable@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleAlignment@ -- -- - #VUID-vkCmdTraceRaysKHR-stride-04035# The @stride@ member of -- @pHitShaderBindingTable@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxShaderGroupStride@ -- -- - #VUID-vkCmdTraceRaysKHR-pCallableShaderBindingTable-03691# If the -- buffer from which @pCallableShaderBindingTable->deviceAddress@ was -- queried is non-sparse then it /must/ be bound completely and -- contiguously to a single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysKHR-pCallableShaderBindingTable-03692# The -- buffer from which the @pCallableShaderBindingTable->deviceAddress@ -- is queried /must/ have been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysKHR-pCallableShaderBindingTable-03693# -- @pCallableShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysKHR-stride-03694# The @stride@ member of -- @pCallableShaderBindingTable@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleAlignment@ -- -- - #VUID-vkCmdTraceRaysKHR-stride-04041# The @stride@ member of -- @pCallableShaderBindingTable@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxShaderGroupStride@ -- -- - #VUID-vkCmdTraceRaysKHR-flags-03696# If the currently bound ray -- tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR', -- the @deviceAddress@ member of @pHitShaderBindingTable@ /must/ not be -- zero -- -- - #VUID-vkCmdTraceRaysKHR-flags-03697# If the currently bound ray -- tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR', -- the @deviceAddress@ member of @pHitShaderBindingTable@ /must/ not be -- zero -- -- - #VUID-vkCmdTraceRaysKHR-flags-03511# If the currently bound ray -- tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_MISS_SHADERS_BIT_KHR', -- the shader group handle identified by @pMissShaderBindingTable@ -- /must/ not be set to zero -- -- - #VUID-vkCmdTraceRaysKHR-flags-03512# If the currently bound ray -- tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_ANY_HIT_SHADERS_BIT_KHR', -- entries in @pHitShaderBindingTable@ accessed as a result of this -- command in order to execute an any-hit shader /must/ not be set to -- zero -- -- - #VUID-vkCmdTraceRaysKHR-flags-03513# If the currently bound ray -- tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR', -- entries in @pHitShaderBindingTable@ accessed as a result of this -- command in order to execute a closest hit shader /must/ not be set -- to zero -- -- - #VUID-vkCmdTraceRaysKHR-flags-03514# If the currently bound ray -- tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR', -- entries in @pHitShaderBindingTable@ accessed as a result of this -- command in order to execute an intersection shader /must/ not be set -- to zero -- -- - #VUID-vkCmdTraceRaysKHR-pHitShaderBindingTable-04735# Any non-zero -- hit shader group entries in @pHitShaderBindingTable@ accessed by -- this call from a geometry with a @geometryType@ of -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.GEOMETRY_TYPE_TRIANGLES_KHR' -- /must/ have been created with -- 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' -- -- - #VUID-vkCmdTraceRaysKHR-pHitShaderBindingTable-04736# Any non-zero -- hit shader group entries in @pHitShaderBindingTable@ accessed by -- this call from a geometry with a @geometryType@ of -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.GEOMETRY_TYPE_AABBS_KHR' -- /must/ have been created with -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR' -- -- - #VUID-vkCmdTraceRaysKHR-commandBuffer-04625# @commandBuffer@ /must/ -- not be a protected command buffer -- -- - #VUID-vkCmdTraceRaysKHR-width-03626# @width@ /must/ be less than or -- equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupCount@[0] -- × -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupSize@[0] -- -- - #VUID-vkCmdTraceRaysKHR-height-03627# @height@ /must/ be less than -- or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupCount@[1] -- × -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupSize@[1] -- -- - #VUID-vkCmdTraceRaysKHR-depth-03628# @depth@ /must/ be less than or -- equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupCount@[2] -- × -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupSize@[2] -- -- - #VUID-vkCmdTraceRaysKHR-width-03629# @width@ × @height@ × @depth@ -- /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxRayDispatchInvocationCount@ -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCmdTraceRaysKHR-commandBuffer-parameter# @commandBuffer@ -- /must/ be a valid 'Vulkan.Core10.Handles.CommandBuffer' handle -- -- - #VUID-vkCmdTraceRaysKHR-pRaygenShaderBindingTable-parameter# -- @pRaygenShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysKHR-pMissShaderBindingTable-parameter# -- @pMissShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysKHR-pHitShaderBindingTable-parameter# -- @pHitShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysKHR-pCallableShaderBindingTable-parameter# -- @pCallableShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysKHR-commandBuffer-recording# @commandBuffer@ -- /must/ be in the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> -- -- - #VUID-vkCmdTraceRaysKHR-commandBuffer-cmdpool# The -- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was -- allocated from /must/ support compute operations -- -- - #VUID-vkCmdTraceRaysKHR-renderpass# This command /must/ only be -- called outside of a render pass instance -- -- == Host Synchronization -- -- - Host access to @commandBuffer@ /must/ be externally synchronized -- -- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that -- @commandBuffer@ was allocated from /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> | -- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+ -- | Primary | Outside | Compute | -- | Secondary | | | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.Handles.CommandBuffer', 'StridedDeviceAddressRegionKHR' cmdTraceRaysKHR :: forall io . (MonadIO io) => -- | @commandBuffer@ is the command buffer into which the command will be -- recorded. CommandBuffer -> -- | @pRaygenShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that -- holds the shader binding table data for the ray generation shader stage. ("raygenShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @pMissShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that -- holds the shader binding table data for the miss shader stage. ("missShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @pHitShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that holds -- the shader binding table data for the hit shader stage. ("hitShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @pCallableShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that -- holds the shader binding table data for the callable shader stage. ("callableShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @width@ is the width of the ray trace query dimensions. ("width" ::: Word32) -> -- | @height@ is height of the ray trace query dimensions. ("height" ::: Word32) -> -- | @depth@ is depth of the ray trace query dimensions. ("depth" ::: Word32) -> io () cmdTraceRaysKHR commandBuffer raygenShaderBindingTable missShaderBindingTable hitShaderBindingTable callableShaderBindingTable width height depth = liftIO . evalContT $ do let vkCmdTraceRaysKHRPtr = pVkCmdTraceRaysKHR (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds) lift $ unless (vkCmdTraceRaysKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdTraceRaysKHR is null" Nothing Nothing let vkCmdTraceRaysKHR' = mkVkCmdTraceRaysKHR vkCmdTraceRaysKHRPtr pRaygenShaderBindingTable <- ContT $ withCStruct (raygenShaderBindingTable) pMissShaderBindingTable <- ContT $ withCStruct (missShaderBindingTable) pHitShaderBindingTable <- ContT $ withCStruct (hitShaderBindingTable) pCallableShaderBindingTable <- ContT $ withCStruct (callableShaderBindingTable) lift $ traceAroundEvent "vkCmdTraceRaysKHR" (vkCmdTraceRaysKHR' (commandBufferHandle (commandBuffer)) pRaygenShaderBindingTable pMissShaderBindingTable pHitShaderBindingTable pCallableShaderBindingTable (width) (height) (depth)) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetRayTracingShaderGroupHandlesKHR :: FunPtr (Ptr Device_T -> Pipeline -> Word32 -> Word32 -> CSize -> Ptr () -> IO Result) -> Ptr Device_T -> Pipeline -> Word32 -> Word32 -> CSize -> Ptr () -> IO Result -- | vkGetRayTracingShaderGroupHandlesKHR - Query ray tracing pipeline shader -- group handles -- -- == Valid Usage -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-pipeline-04619# -- @pipeline@ /must/ be a ray tracing pipeline -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-firstGroup-04050# -- @firstGroup@ /must/ be less than the number of shader groups in -- @pipeline@ -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-firstGroup-02419# The sum -- of @firstGroup@ and @groupCount@ /must/ be less than or equal to the -- number of shader groups in @pipeline@ -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-dataSize-02420# -- @dataSize@ /must/ be at least -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleSize@ -- × @groupCount@ -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-pipeline-03482# -- @pipeline@ /must/ have not been created with -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_LIBRARY_BIT_KHR' -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-pipeline-parameter# -- @pipeline@ /must/ be a valid 'Vulkan.Core10.Handles.Pipeline' handle -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-pData-parameter# @pData@ -- /must/ be a valid pointer to an array of @dataSize@ bytes -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-dataSize-arraylength# -- @dataSize@ /must/ be greater than @0@ -- -- - #VUID-vkGetRayTracingShaderGroupHandlesKHR-pipeline-parent# -- @pipeline@ /must/ have been created, allocated, or retrieved from -- @device@ -- -- == 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_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_ray_tracing VK_NV_ray_tracing>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Pipeline' getRayTracingShaderGroupHandlesKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device containing the ray tracing pipeline. Device -> -- | @pipeline@ is the ray tracing pipeline object containing the shaders. Pipeline -> -- | @firstGroup@ is the index of the first group to retrieve a handle for -- from the 'RayTracingPipelineCreateInfoKHR'::@pGroups@ or -- 'Vulkan.Extensions.VK_NV_ray_tracing.RayTracingPipelineCreateInfoNV'::@pGroups@ -- array. ("firstGroup" ::: Word32) -> -- | @groupCount@ is the number of shader handles to retrieve. ("groupCount" ::: Word32) -> -- | @dataSize@ is the size in bytes of the buffer pointed to by @pData@. ("dataSize" ::: Word64) -> -- | @pData@ is a pointer to a user-allocated buffer where the results will -- be written. ("data" ::: Ptr ()) -> io () getRayTracingShaderGroupHandlesKHR device pipeline firstGroup groupCount dataSize data' = liftIO $ do let vkGetRayTracingShaderGroupHandlesKHRPtr = pVkGetRayTracingShaderGroupHandlesKHR (case device of Device{deviceCmds} -> deviceCmds) unless (vkGetRayTracingShaderGroupHandlesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetRayTracingShaderGroupHandlesKHR is null" Nothing Nothing let vkGetRayTracingShaderGroupHandlesKHR' = mkVkGetRayTracingShaderGroupHandlesKHR vkGetRayTracingShaderGroupHandlesKHRPtr r <- traceAroundEvent "vkGetRayTracingShaderGroupHandlesKHR" (vkGetRayTracingShaderGroupHandlesKHR' (deviceHandle (device)) (pipeline) (firstGroup) (groupCount) (CSize (dataSize)) (data')) when (r < SUCCESS) (throwIO (VulkanException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetRayTracingCaptureReplayShaderGroupHandlesKHR :: FunPtr (Ptr Device_T -> Pipeline -> Word32 -> Word32 -> CSize -> Ptr () -> IO Result) -> Ptr Device_T -> Pipeline -> Word32 -> Word32 -> CSize -> Ptr () -> IO Result -- | vkGetRayTracingCaptureReplayShaderGroupHandlesKHR - Query ray tracing -- capture replay pipeline shader group handles -- -- == Valid Usage -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-pipeline-04620# -- @pipeline@ /must/ be a ray tracing pipeline -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-firstGroup-04051# -- @firstGroup@ /must/ be less than the number of shader groups in -- @pipeline@ -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-firstGroup-03483# -- The sum of @firstGroup@ and @groupCount@ /must/ be less than or -- equal to the number of shader groups in @pipeline@ -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-dataSize-03484# -- @dataSize@ /must/ be at least -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleCaptureReplaySize@ -- × @groupCount@ -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-rayTracingPipelineShaderGroupHandleCaptureReplay-03606# -- 'PhysicalDeviceRayTracingPipelineFeaturesKHR'::@rayTracingPipelineShaderGroupHandleCaptureReplay@ -- /must/ be enabled to call this function -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-pipeline-03607# -- @pipeline@ /must/ have been created with a @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR' -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-pipeline-parameter# -- @pipeline@ /must/ be a valid 'Vulkan.Core10.Handles.Pipeline' handle -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-pData-parameter# -- @pData@ /must/ be a valid pointer to an array of @dataSize@ bytes -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-dataSize-arraylength# -- @dataSize@ /must/ be greater than @0@ -- -- - #VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-pipeline-parent# -- @pipeline@ /must/ have been created, allocated, or retrieved from -- @device@ -- -- == 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_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Pipeline' getRayTracingCaptureReplayShaderGroupHandlesKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device containing the ray tracing pipeline. Device -> -- | @pipeline@ is the ray tracing pipeline object containing the shaders. Pipeline -> -- | @firstGroup@ is the index of the first group to retrieve a handle for -- from the 'RayTracingPipelineCreateInfoKHR'::@pGroups@ array. ("firstGroup" ::: Word32) -> -- | @groupCount@ is the number of shader handles to retrieve. ("groupCount" ::: Word32) -> -- | @dataSize@ is the size in bytes of the buffer pointed to by @pData@. ("dataSize" ::: Word64) -> -- | @pData@ is a pointer to a user-allocated buffer where the results will -- be written. ("data" ::: Ptr ()) -> io () getRayTracingCaptureReplayShaderGroupHandlesKHR device pipeline firstGroup groupCount dataSize data' = liftIO $ do let vkGetRayTracingCaptureReplayShaderGroupHandlesKHRPtr = pVkGetRayTracingCaptureReplayShaderGroupHandlesKHR (case device of Device{deviceCmds} -> deviceCmds) unless (vkGetRayTracingCaptureReplayShaderGroupHandlesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetRayTracingCaptureReplayShaderGroupHandlesKHR is null" Nothing Nothing let vkGetRayTracingCaptureReplayShaderGroupHandlesKHR' = mkVkGetRayTracingCaptureReplayShaderGroupHandlesKHR vkGetRayTracingCaptureReplayShaderGroupHandlesKHRPtr r <- traceAroundEvent "vkGetRayTracingCaptureReplayShaderGroupHandlesKHR" (vkGetRayTracingCaptureReplayShaderGroupHandlesKHR' (deviceHandle (device)) (pipeline) (firstGroup) (groupCount) (CSize (dataSize)) (data')) when (r < SUCCESS) (throwIO (VulkanException r)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCreateRayTracingPipelinesKHR :: FunPtr (Ptr Device_T -> DeferredOperationKHR -> PipelineCache -> Word32 -> Ptr (SomeStruct RayTracingPipelineCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr Pipeline -> IO Result) -> Ptr Device_T -> DeferredOperationKHR -> PipelineCache -> Word32 -> Ptr (SomeStruct RayTracingPipelineCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr Pipeline -> IO Result -- | vkCreateRayTracingPipelinesKHR - Creates a new ray tracing pipeline -- object -- -- = Description -- -- The 'Vulkan.Core10.Enums.Result.ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS' -- error is returned if the implementation is unable to re-use the shader -- group handles provided in -- 'RayTracingShaderGroupCreateInfoKHR'::@pShaderGroupCaptureReplayHandle@ -- when -- 'PhysicalDeviceRayTracingPipelineFeaturesKHR'::@rayTracingPipelineShaderGroupHandleCaptureReplay@ -- is enabled. -- -- == Valid Usage -- -- - #VUID-vkCreateRayTracingPipelinesKHR-flags-03415# If the @flags@ -- member of any element of @pCreateInfos@ contains the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_DERIVATIVE_BIT' -- flag, and the @basePipelineIndex@ member of that same element is not -- @-1@, @basePipelineIndex@ /must/ be less than the index into -- @pCreateInfos@ that corresponds to that element -- -- - #VUID-vkCreateRayTracingPipelinesKHR-flags-03416# If the @flags@ -- member of any element of @pCreateInfos@ contains the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_DERIVATIVE_BIT' -- flag, the base pipeline /must/ have been created with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT' -- flag set -- -- - #VUID-vkCreateRayTracingPipelinesKHR-flags-03816# @flags@ /must/ not -- contain the -- 'Vulkan.Core11.Promoted_From_VK_KHR_device_group.PIPELINE_CREATE_DISPATCH_BASE' -- flag -- -- - #VUID-vkCreateRayTracingPipelinesKHR-pipelineCache-02903# If -- @pipelineCache@ was created with -- 'Vulkan.Core10.Enums.PipelineCacheCreateFlagBits.PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT', -- host access to @pipelineCache@ /must/ be -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-threadingbehavior externally synchronized> -- -- - #VUID-vkCreateRayTracingPipelinesKHR-deferredOperation-03677# If -- @deferredOperation@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- it /must/ be a valid -- 'Vulkan.Extensions.Handles.DeferredOperationKHR' object -- -- - #VUID-vkCreateRayTracingPipelinesKHR-deferredOperation-03678# Any -- previous deferred operation that was associated with -- @deferredOperation@ /must/ be complete -- -- - #VUID-vkCreateRayTracingPipelinesKHR-rayTracingPipeline-03586# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-rayTracingPipeline rayTracingPipeline> -- feature /must/ be enabled -- -- - #VUID-vkCreateRayTracingPipelinesKHR-deferredOperation-03587# If -- @deferredOperation@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- the @flags@ member of elements of @pCreateInfos@ /must/ not include -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT' -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCreateRayTracingPipelinesKHR-device-parameter# @device@ -- /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkCreateRayTracingPipelinesKHR-deferredOperation-parameter# If -- @deferredOperation@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @deferredOperation@ /must/ be a valid -- 'Vulkan.Extensions.Handles.DeferredOperationKHR' handle -- -- - #VUID-vkCreateRayTracingPipelinesKHR-pipelineCache-parameter# If -- @pipelineCache@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @pipelineCache@ /must/ be a valid -- 'Vulkan.Core10.Handles.PipelineCache' handle -- -- - #VUID-vkCreateRayTracingPipelinesKHR-pCreateInfos-parameter# -- @pCreateInfos@ /must/ be a valid pointer to an array of -- @createInfoCount@ valid 'RayTracingPipelineCreateInfoKHR' structures -- -- - #VUID-vkCreateRayTracingPipelinesKHR-pAllocator-parameter# If -- @pAllocator@ is not @NULL@, @pAllocator@ /must/ be a valid pointer -- to a valid 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' -- structure -- -- - #VUID-vkCreateRayTracingPipelinesKHR-pPipelines-parameter# -- @pPipelines@ /must/ be a valid pointer to an array of -- @createInfoCount@ 'Vulkan.Core10.Handles.Pipeline' handles -- -- - #VUID-vkCreateRayTracingPipelinesKHR-createInfoCount-arraylength# -- @createInfoCount@ /must/ be greater than @0@ -- -- - #VUID-vkCreateRayTracingPipelinesKHR-deferredOperation-parent# If -- @deferredOperation@ is a valid handle, it /must/ have been created, -- allocated, or retrieved from @device@ -- -- - #VUID-vkCreateRayTracingPipelinesKHR-pipelineCache-parent# If -- @pipelineCache@ is a valid handle, it /must/ have been created, -- allocated, or retrieved from @device@ -- -- == 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.OPERATION_DEFERRED_KHR' -- -- - 'Vulkan.Core10.Enums.Result.OPERATION_NOT_DEFERRED_KHR' -- -- - 'Vulkan.Extensions.VK_EXT_pipeline_creation_cache_control.PIPELINE_COMPILE_REQUIRED_EXT' -- -- [<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_INVALID_OPAQUE_CAPTURE_ADDRESS' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Extensions.Handles.DeferredOperationKHR', -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Pipeline', -- 'Vulkan.Core10.Handles.PipelineCache', 'RayTracingPipelineCreateInfoKHR' createRayTracingPipelinesKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device that creates the ray tracing pipelines. Device -> -- | @deferredOperation@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or the -- handle of a valid 'Vulkan.Extensions.Handles.DeferredOperationKHR' -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#deferred-host-operations-requesting request deferral> -- object for this command. DeferredOperationKHR -> -- | @pipelineCache@ is either 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- indicating that pipeline caching is disabled, or the handle of a valid -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#pipelines-cache pipeline cache> -- object, in which case use of that cache is enabled for the duration of -- the command. PipelineCache -> -- | @pCreateInfos@ is a pointer to an array of -- 'RayTracingPipelineCreateInfoKHR' structures. ("createInfos" ::: Vector (SomeStruct RayTracingPipelineCreateInfoKHR)) -> -- | @pAllocator@ controls host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter. ("allocator" ::: Maybe AllocationCallbacks) -> io (Result, ("pipelines" ::: Vector Pipeline)) createRayTracingPipelinesKHR device deferredOperation pipelineCache createInfos allocator = liftIO . evalContT $ do let vkCreateRayTracingPipelinesKHRPtr = pVkCreateRayTracingPipelinesKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkCreateRayTracingPipelinesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateRayTracingPipelinesKHR is null" Nothing Nothing let vkCreateRayTracingPipelinesKHR' = mkVkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHRPtr pPCreateInfos <- ContT $ allocaBytes @(RayTracingPipelineCreateInfoKHR _) ((Data.Vector.length (createInfos)) * 104) Data.Vector.imapM_ (\i e -> ContT $ pokeSomeCStruct (forgetExtensions (pPCreateInfos `plusPtr` (104 * (i)) :: Ptr (RayTracingPipelineCreateInfoKHR _))) (e) . ($ ())) (createInfos) pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) pPPipelines <- ContT $ bracket (callocBytes @Pipeline ((fromIntegral ((fromIntegral (Data.Vector.length $ (createInfos)) :: Word32))) * 8)) free r <- lift $ traceAroundEvent "vkCreateRayTracingPipelinesKHR" (vkCreateRayTracingPipelinesKHR' (deviceHandle (device)) (deferredOperation) (pipelineCache) ((fromIntegral (Data.Vector.length $ (createInfos)) :: Word32)) (forgetExtensions (pPCreateInfos)) pAllocator (pPPipelines)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pPipelines <- lift $ generateM (fromIntegral ((fromIntegral (Data.Vector.length $ (createInfos)) :: Word32))) (\i -> peek @Pipeline ((pPPipelines `advancePtrBytes` (8 * (i)) :: Ptr Pipeline))) pure $ (r, pPipelines) -- | A convenience wrapper to make a compatible pair of calls to -- 'createRayTracingPipelinesKHR' and 'destroyPipeline' -- -- To ensure that 'destroyPipeline' 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. -- withRayTracingPipelinesKHR :: forall io r . MonadIO io => Device -> DeferredOperationKHR -> PipelineCache -> Vector (SomeStruct RayTracingPipelineCreateInfoKHR) -> Maybe AllocationCallbacks -> (io (Result, Vector Pipeline) -> ((Result, Vector Pipeline) -> io ()) -> r) -> r withRayTracingPipelinesKHR device deferredOperation pipelineCache pCreateInfos pAllocator b = b (createRayTracingPipelinesKHR device deferredOperation pipelineCache pCreateInfos pAllocator) (\(_, o1) -> traverse_ (\o1Elem -> destroyPipeline device o1Elem pAllocator) o1) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCmdTraceRaysIndirectKHR :: FunPtr (Ptr CommandBuffer_T -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> DeviceAddress -> IO ()) -> Ptr CommandBuffer_T -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> Ptr StridedDeviceAddressRegionKHR -> DeviceAddress -> IO () -- | vkCmdTraceRaysIndirectKHR - Initialize an indirect ray tracing dispatch -- -- = Description -- -- 'cmdTraceRaysIndirectKHR' behaves similarly to 'cmdTraceRaysKHR' except -- that the ray trace query dimensions are read by the device from -- @indirectDeviceAddress@ during execution. -- -- == Valid Usage -- -- - #VUID-vkCmdTraceRaysIndirectKHR-magFilter-04553# If a -- 'Vulkan.Core10.Handles.Sampler' created with @magFilter@ or -- @minFilter@ equal to 'Vulkan.Core10.Enums.Filter.FILTER_LINEAR' and -- @compareEnable@ equal to 'Vulkan.Core10.FundamentalTypes.FALSE' is -- used to sample a 'Vulkan.Core10.Handles.ImageView' as a result of -- this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-mipmapMode-04770# If a -- 'Vulkan.Core10.Handles.Sampler' created with @mipmapMode@ equal to -- 'Vulkan.Core10.Enums.SamplerMipmapMode.SAMPLER_MIPMAP_MODE_LINEAR' -- and @compareEnable@ equal to 'Vulkan.Core10.FundamentalTypes.FALSE' -- is used to sample a 'Vulkan.Core10.Handles.ImageView' as a result of -- this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-06479# If a -- 'Vulkan.Core10.Handles.ImageView' is sampled with -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#textures-depth-compare-operation depth comparison>, -- the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_SAMPLED_IMAGE_DEPTH_COMPARISON_BIT' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02691# If a -- 'Vulkan.Core10.Handles.ImageView' is accessed using atomic -- operations as a result of this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02692# If a -- 'Vulkan.Core10.Handles.ImageView' is sampled with -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FILTER_CUBIC_EXT' as a result -- of this command, then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-filterCubic-02694# Any -- 'Vulkan.Core10.Handles.ImageView' being sampled with -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FILTER_CUBIC_EXT' as a result -- of this command /must/ have a -- 'Vulkan.Core10.Enums.ImageViewType.ImageViewType' and format that -- supports cubic filtering, as specified by -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FilterCubicImageViewImageFormatPropertiesEXT'::@filterCubic@ -- returned by -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceImageFormatProperties2' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-filterCubicMinmax-02695# Any -- 'Vulkan.Core10.Handles.ImageView' being sampled with -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FILTER_CUBIC_EXT' with a -- reduction mode of either -- 'Vulkan.Core12.Enums.SamplerReductionMode.SAMPLER_REDUCTION_MODE_MIN' -- or -- 'Vulkan.Core12.Enums.SamplerReductionMode.SAMPLER_REDUCTION_MODE_MAX' -- as a result of this command /must/ have a -- 'Vulkan.Core10.Enums.ImageViewType.ImageViewType' and format that -- supports cubic filtering together with minmax filtering, as -- specified by -- 'Vulkan.Extensions.VK_EXT_filter_cubic.FilterCubicImageViewImageFormatPropertiesEXT'::@filterCubicMinmax@ -- returned by -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceImageFormatProperties2' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-flags-02696# Any -- 'Vulkan.Core10.Handles.Image' created with a -- 'Vulkan.Core10.Image.ImageCreateInfo'::@flags@ containing -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_CORNER_SAMPLED_BIT_NV' -- sampled as a result of this command /must/ only be sampled using a -- 'Vulkan.Core10.Enums.SamplerAddressMode.SamplerAddressMode' of -- 'Vulkan.Core10.Enums.SamplerAddressMode.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-OpTypeImage-06423# Any -- 'Vulkan.Core10.Handles.ImageView' or -- 'Vulkan.Core10.Handles.BufferView' being written as a storage image -- or storage texel buffer where the image format field of the -- @OpTypeImage@ is @Unknown@ /must/ have image format features that -- support -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-OpTypeImage-06424# Any -- 'Vulkan.Core10.Handles.ImageView' or -- 'Vulkan.Core10.Handles.BufferView' being read as a storage image or -- storage texel buffer where the image format field of the -- @OpTypeImage@ is @Unknown@ /must/ have image format features that -- support -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02697# For each set /n/ that is -- statically used by the 'Vulkan.Core10.Handles.Pipeline' bound to the -- pipeline bind point used by this command, a descriptor set /must/ -- have been bound to /n/ at the same pipeline bind point, with a -- 'Vulkan.Core10.Handles.PipelineLayout' that is compatible for set -- /n/, with the 'Vulkan.Core10.Handles.PipelineLayout' used to create -- the current 'Vulkan.Core10.Handles.Pipeline', as described in -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#descriptorsets-compatibility ???> -- -- - #VUID-vkCmdTraceRaysIndirectKHR-maintenance4-06425# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-maintenance4 maintenance4> -- feature is not enabled, then for each push constant that is -- statically used by the 'Vulkan.Core10.Handles.Pipeline' bound to the -- pipeline bind point used by this command, a push constant value -- /must/ have been set for the same pipeline bind point, with a -- 'Vulkan.Core10.Handles.PipelineLayout' that is compatible for push -- constants, with the 'Vulkan.Core10.Handles.PipelineLayout' used to -- create the current 'Vulkan.Core10.Handles.Pipeline', as described in -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#descriptorsets-compatibility ???> -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02699# Descriptors in each -- bound descriptor set, specified via -- 'Vulkan.Core10.CommandBufferBuilding.cmdBindDescriptorSets', /must/ -- be valid if they are statically used by the -- 'Vulkan.Core10.Handles.Pipeline' bound to the pipeline bind point -- used by this command -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02700# A valid pipeline /must/ -- be bound to the pipeline bind point used by this command -- -- - #VUID-vkCmdTraceRaysIndirectKHR-commandBuffer-02701# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command requires any dynamic state, that state -- /must/ have been set or inherited (if the -- @VK_NV_inherited_viewport_scissor@ extension is enabled) for -- @commandBuffer@, and done so after any previously bound pipeline -- with the corresponding state not specified as dynamic -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02859# There /must/ not have -- been any calls to dynamic state setting commands for any state not -- specified as dynamic in the 'Vulkan.Core10.Handles.Pipeline' object -- bound to the pipeline bind point used by this command, since that -- pipeline was bound -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02702# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command accesses a -- 'Vulkan.Core10.Handles.Sampler' object that uses unnormalized -- coordinates, that sampler /must/ not be used to sample from any -- 'Vulkan.Core10.Handles.Image' with a -- 'Vulkan.Core10.Handles.ImageView' of the type -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_3D', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_1D_ARRAY', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE_ARRAY', in -- any shader stage -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02703# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command accesses a -- 'Vulkan.Core10.Handles.Sampler' object that uses unnormalized -- coordinates, that sampler /must/ not be used with any of the SPIR-V -- @OpImageSample*@ or @OpImageSparseSample*@ instructions with -- @ImplicitLod@, @Dref@ or @Proj@ in their name, in any shader stage -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02704# If the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command accesses a -- 'Vulkan.Core10.Handles.Sampler' object that uses unnormalized -- coordinates, that sampler /must/ not be used with any of the SPIR-V -- @OpImageSample*@ or @OpImageSparseSample*@ instructions that -- includes a LOD bias or any offset values, in any shader stage -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02705# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-robustBufferAccess robust buffer access> -- feature is not enabled, and if the 'Vulkan.Core10.Handles.Pipeline' -- object bound to the pipeline bind point used by this command -- accesses a uniform buffer, it /must/ not access values outside of -- the range of the buffer as specified in the descriptor set bound to -- the same pipeline bind point -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-02706# If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-robustBufferAccess robust buffer access> -- feature is not enabled, and if the 'Vulkan.Core10.Handles.Pipeline' -- object bound to the pipeline bind point used by this command -- accesses a storage buffer, it /must/ not access values outside of -- the range of the buffer as specified in the descriptor set bound to -- the same pipeline bind point -- -- - #VUID-vkCmdTraceRaysIndirectKHR-commandBuffer-02707# If -- @commandBuffer@ is an unprotected command buffer and -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#limits-protectedNoFault protectedNoFault> -- is not supported, any resource accessed by the -- 'Vulkan.Core10.Handles.Pipeline' object bound to the pipeline bind -- point used by this command /must/ not be a protected resource -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-04115# If a -- 'Vulkan.Core10.Handles.ImageView' is accessed using @OpImageWrite@ -- as a result of this command, then the @Type@ of the @Texel@ operand -- of that instruction /must/ have at least as many components as the -- image view’s format -- -- - #VUID-vkCmdTraceRaysIndirectKHR-OpImageWrite-04469# If a -- 'Vulkan.Core10.Handles.BufferView' is accessed using @OpImageWrite@ -- as a result of this command, then the @Type@ of the @Texel@ operand -- of that instruction /must/ have at least as many components as the -- buffer view’s format -- -- - #VUID-vkCmdTraceRaysIndirectKHR-SampledType-04470# If a -- 'Vulkan.Core10.Handles.ImageView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a 64-bit component -- width is accessed as a result of this command, the @SampledType@ of -- the @OpTypeImage@ operand of that instruction /must/ have a @Width@ -- of 64 -- -- - #VUID-vkCmdTraceRaysIndirectKHR-SampledType-04471# If a -- 'Vulkan.Core10.Handles.ImageView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a component width less -- than 64-bit is accessed as a result of this command, the -- @SampledType@ of the @OpTypeImage@ operand of that instruction -- /must/ have a @Width@ of 32 -- -- - #VUID-vkCmdTraceRaysIndirectKHR-SampledType-04472# If a -- 'Vulkan.Core10.Handles.BufferView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a 64-bit component -- width is accessed as a result of this command, the @SampledType@ of -- the @OpTypeImage@ operand of that instruction /must/ have a @Width@ -- of 64 -- -- - #VUID-vkCmdTraceRaysIndirectKHR-SampledType-04473# If a -- 'Vulkan.Core10.Handles.BufferView' with a -- 'Vulkan.Core10.Enums.Format.Format' that has a component width less -- than 64-bit is accessed as a result of this command, the -- @SampledType@ of the @OpTypeImage@ operand of that instruction -- /must/ have a @Width@ of 32 -- -- - #VUID-vkCmdTraceRaysIndirectKHR-sparseImageInt64Atomics-04474# If -- the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-sparseImageInt64Atomics sparseImageInt64Atomics> -- feature is not enabled, 'Vulkan.Core10.Handles.Image' objects -- created with the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_RESIDENCY_BIT' -- flag /must/ not be accessed by atomic instructions through an -- @OpTypeImage@ with a @SampledType@ with a @Width@ of 64 by this -- command -- -- - #VUID-vkCmdTraceRaysIndirectKHR-sparseImageInt64Atomics-04475# If -- the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-sparseImageInt64Atomics sparseImageInt64Atomics> -- feature is not enabled, 'Vulkan.Core10.Handles.Buffer' objects -- created with the -- 'Vulkan.Core10.Enums.BufferCreateFlagBits.BUFFER_CREATE_SPARSE_RESIDENCY_BIT' -- flag /must/ not be accessed by atomic instructions through an -- @OpTypeImage@ with a @SampledType@ with a @Width@ of 64 by this -- command -- -- - #VUID-vkCmdTraceRaysIndirectKHR-None-03429# Any shader group handle -- referenced by this call /must/ have been queried from the currently -- bound ray tracing pipeline -- -- - #VUID-vkCmdTraceRaysIndirectKHR-maxPipelineRayRecursionDepth-03679# -- This command /must/ not cause a shader call instruction to be -- executed from a shader invocation with a -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#ray-tracing-recursion-depth recursion depth> -- greater than the value of @maxPipelineRayRecursionDepth@ used to -- create the bound ray tracing pipeline -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pRayGenShaderBindingTable-03680# If -- the buffer from which @pRayGenShaderBindingTable->deviceAddress@ was -- queried is non-sparse then it /must/ be bound completely and -- contiguously to a single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pRayGenShaderBindingTable-03681# The -- buffer from which the @pRayGenShaderBindingTable->deviceAddress@ is -- queried /must/ have been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pRayGenShaderBindingTable-03682# -- @pRayGenShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-size-04023# The @size@ member of -- @pRayGenShaderBindingTable@ /must/ be equal to its @stride@ member -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pMissShaderBindingTable-03683# If -- the buffer from which @pMissShaderBindingTable->deviceAddress@ was -- queried is non-sparse then it /must/ be bound completely and -- contiguously to a single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pMissShaderBindingTable-03684# The -- buffer from which the @pMissShaderBindingTable->deviceAddress@ is -- queried /must/ have been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pMissShaderBindingTable-03685# -- @pMissShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-stride-03686# The @stride@ member of -- @pMissShaderBindingTable@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleAlignment@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-stride-04029# The @stride@ member of -- @pMissShaderBindingTable@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxShaderGroupStride@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pHitShaderBindingTable-03687# If the -- buffer from which @pHitShaderBindingTable->deviceAddress@ was -- queried is non-sparse then it /must/ be bound completely and -- contiguously to a single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pHitShaderBindingTable-03688# The -- buffer from which the @pHitShaderBindingTable->deviceAddress@ is -- queried /must/ have been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pHitShaderBindingTable-03689# -- @pHitShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-stride-03690# The @stride@ member of -- @pHitShaderBindingTable@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleAlignment@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-stride-04035# The @stride@ member of -- @pHitShaderBindingTable@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxShaderGroupStride@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pCallableShaderBindingTable-03691# -- If the buffer from which -- @pCallableShaderBindingTable->deviceAddress@ was queried is -- non-sparse then it /must/ be bound completely and contiguously to a -- single 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pCallableShaderBindingTable-03692# -- The buffer from which the -- @pCallableShaderBindingTable->deviceAddress@ is queried /must/ have -- been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR' -- usage flag -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pCallableShaderBindingTable-03693# -- @pCallableShaderBindingTable->deviceAddress@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupBaseAlignment@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-stride-03694# The @stride@ member of -- @pCallableShaderBindingTable@ /must/ be a multiple of -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@shaderGroupHandleAlignment@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-stride-04041# The @stride@ member of -- @pCallableShaderBindingTable@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxShaderGroupStride@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-flags-03696# If the currently bound -- ray tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR', -- the @deviceAddress@ member of @pHitShaderBindingTable@ /must/ not be -- zero -- -- - #VUID-vkCmdTraceRaysIndirectKHR-flags-03697# If the currently bound -- ray tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR', -- the @deviceAddress@ member of @pHitShaderBindingTable@ /must/ not be -- zero -- -- - #VUID-vkCmdTraceRaysIndirectKHR-flags-03511# If the currently bound -- ray tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_MISS_SHADERS_BIT_KHR', -- the shader group handle identified by @pMissShaderBindingTable@ -- /must/ not be set to zero -- -- - #VUID-vkCmdTraceRaysIndirectKHR-flags-03512# If the currently bound -- ray tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_ANY_HIT_SHADERS_BIT_KHR', -- entries in @pHitShaderBindingTable@ accessed as a result of this -- command in order to execute an any-hit shader /must/ not be set to -- zero -- -- - #VUID-vkCmdTraceRaysIndirectKHR-flags-03513# If the currently bound -- ray tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR', -- entries in @pHitShaderBindingTable@ accessed as a result of this -- command in order to execute a closest hit shader /must/ not be set -- to zero -- -- - #VUID-vkCmdTraceRaysIndirectKHR-flags-03514# If the currently bound -- ray tracing pipeline was created with @flags@ that included -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR', -- entries in @pHitShaderBindingTable@ accessed as a result of this -- command in order to execute an intersection shader /must/ not be set -- to zero -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pHitShaderBindingTable-04735# Any -- non-zero hit shader group entries in @pHitShaderBindingTable@ -- accessed by this call from a geometry with a @geometryType@ of -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.GEOMETRY_TYPE_TRIANGLES_KHR' -- /must/ have been created with -- 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pHitShaderBindingTable-04736# Any -- non-zero hit shader group entries in @pHitShaderBindingTable@ -- accessed by this call from a geometry with a @geometryType@ of -- 'Vulkan.Extensions.VK_KHR_acceleration_structure.GEOMETRY_TYPE_AABBS_KHR' -- /must/ have been created with -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR' -- -- - #VUID-vkCmdTraceRaysIndirectKHR-indirectDeviceAddress-03632# If the -- buffer from which @indirectDeviceAddress@ was queried is non-sparse -- then it /must/ be bound completely and contiguously to a single -- 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-vkCmdTraceRaysIndirectKHR-indirectDeviceAddress-03633# The -- buffer from which @indirectDeviceAddress@ was queried /must/ have -- been created with the -- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_INDIRECT_BUFFER_BIT' -- bit set -- -- - #VUID-vkCmdTraceRaysIndirectKHR-indirectDeviceAddress-03634# -- @indirectDeviceAddress@ /must/ be a multiple of @4@ -- -- - #VUID-vkCmdTraceRaysIndirectKHR-commandBuffer-03635# @commandBuffer@ -- /must/ not be a protected command buffer -- -- - #VUID-vkCmdTraceRaysIndirectKHR-indirectDeviceAddress-03636# All -- device addresses between @indirectDeviceAddress@ and -- @indirectDeviceAddress@ + @sizeof@('TraceRaysIndirectCommandKHR') - -- 1 /must/ be in the buffer device address range of the same buffer -- -- - #VUID-vkCmdTraceRaysIndirectKHR-rayTracingPipelineTraceRaysIndirect-03637# -- The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-rayTracingPipelineTraceRaysIndirect ::rayTracingPipelineTraceRaysIndirect> -- feature /must/ be enabled -- -- - #VUID-vkCmdTraceRaysIndirectKHR-rayTracingMotionBlurPipelineTraceRaysIndirect-04951# -- If the bound ray tracing pipeline was created with -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_ALLOW_MOTION_BIT_NV' -- 'Vulkan.Extensions.VK_NV_ray_tracing_motion_blur.PhysicalDeviceRayTracingMotionBlurFeaturesNV'::@rayTracingMotionBlurPipelineTraceRaysIndirect@ -- feature /must/ be enabled -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCmdTraceRaysIndirectKHR-commandBuffer-parameter# -- @commandBuffer@ /must/ be a valid -- 'Vulkan.Core10.Handles.CommandBuffer' handle -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pRaygenShaderBindingTable-parameter# -- @pRaygenShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pMissShaderBindingTable-parameter# -- @pMissShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pHitShaderBindingTable-parameter# -- @pHitShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysIndirectKHR-pCallableShaderBindingTable-parameter# -- @pCallableShaderBindingTable@ /must/ be a valid pointer to a valid -- 'StridedDeviceAddressRegionKHR' structure -- -- - #VUID-vkCmdTraceRaysIndirectKHR-commandBuffer-recording# -- @commandBuffer@ /must/ be in the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> -- -- - #VUID-vkCmdTraceRaysIndirectKHR-commandBuffer-cmdpool# The -- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was -- allocated from /must/ support compute operations -- -- - #VUID-vkCmdTraceRaysIndirectKHR-renderpass# This command /must/ only -- be called outside of a render pass instance -- -- == Host Synchronization -- -- - Host access to @commandBuffer@ /must/ be externally synchronized -- -- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that -- @commandBuffer@ was allocated from /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> | -- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+ -- | Primary | Outside | Compute | -- | Secondary | | | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.Handles.CommandBuffer', -- 'Vulkan.Core10.FundamentalTypes.DeviceAddress', -- 'StridedDeviceAddressRegionKHR' cmdTraceRaysIndirectKHR :: forall io . (MonadIO io) => -- | @commandBuffer@ is the command buffer into which the command will be -- recorded. CommandBuffer -> -- | @pRaygenShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that -- holds the shader binding table data for the ray generation shader stage. ("raygenShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @pMissShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that -- holds the shader binding table data for the miss shader stage. ("missShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @pHitShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that holds -- the shader binding table data for the hit shader stage. ("hitShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @pCallableShaderBindingTable@ is a 'StridedDeviceAddressRegionKHR' that -- holds the shader binding table data for the callable shader stage. ("callableShaderBindingTable" ::: StridedDeviceAddressRegionKHR) -> -- | @indirectDeviceAddress@ is a buffer device address which is a pointer to -- a 'TraceRaysIndirectCommandKHR' structure containing the trace ray -- parameters. ("indirectDeviceAddress" ::: DeviceAddress) -> io () cmdTraceRaysIndirectKHR commandBuffer raygenShaderBindingTable missShaderBindingTable hitShaderBindingTable callableShaderBindingTable indirectDeviceAddress = liftIO . evalContT $ do let vkCmdTraceRaysIndirectKHRPtr = pVkCmdTraceRaysIndirectKHR (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds) lift $ unless (vkCmdTraceRaysIndirectKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdTraceRaysIndirectKHR is null" Nothing Nothing let vkCmdTraceRaysIndirectKHR' = mkVkCmdTraceRaysIndirectKHR vkCmdTraceRaysIndirectKHRPtr pRaygenShaderBindingTable <- ContT $ withCStruct (raygenShaderBindingTable) pMissShaderBindingTable <- ContT $ withCStruct (missShaderBindingTable) pHitShaderBindingTable <- ContT $ withCStruct (hitShaderBindingTable) pCallableShaderBindingTable <- ContT $ withCStruct (callableShaderBindingTable) lift $ traceAroundEvent "vkCmdTraceRaysIndirectKHR" (vkCmdTraceRaysIndirectKHR' (commandBufferHandle (commandBuffer)) pRaygenShaderBindingTable pMissShaderBindingTable pHitShaderBindingTable pCallableShaderBindingTable (indirectDeviceAddress)) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetRayTracingShaderGroupStackSizeKHR :: FunPtr (Ptr Device_T -> Pipeline -> Word32 -> ShaderGroupShaderKHR -> IO DeviceSize) -> Ptr Device_T -> Pipeline -> Word32 -> ShaderGroupShaderKHR -> IO DeviceSize -- | vkGetRayTracingShaderGroupStackSizeKHR - Query ray tracing pipeline -- shader group shader stack size -- -- = Description -- -- The return value is the ray tracing pipeline stack size in bytes for the -- specified shader as called from the specified shader group. -- -- == Valid Usage -- -- - #VUID-vkGetRayTracingShaderGroupStackSizeKHR-pipeline-04622# -- @pipeline@ /must/ be a ray tracing pipeline -- -- - #VUID-vkGetRayTracingShaderGroupStackSizeKHR-group-03608# The value -- of @group@ must be less than the number of shader groups in -- @pipeline@ -- -- - #VUID-vkGetRayTracingShaderGroupStackSizeKHR-groupShader-03609# The -- shader identified by @groupShader@ in @group@ /must/ not be -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetRayTracingShaderGroupStackSizeKHR-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetRayTracingShaderGroupStackSizeKHR-pipeline-parameter# -- @pipeline@ /must/ be a valid 'Vulkan.Core10.Handles.Pipeline' handle -- -- - #VUID-vkGetRayTracingShaderGroupStackSizeKHR-groupShader-parameter# -- @groupShader@ /must/ be a valid 'ShaderGroupShaderKHR' value -- -- - #VUID-vkGetRayTracingShaderGroupStackSizeKHR-pipeline-parent# -- @pipeline@ /must/ have been created, allocated, or retrieved from -- @device@ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Pipeline', -- 'ShaderGroupShaderKHR' getRayTracingShaderGroupStackSizeKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device containing the ray tracing pipeline. Device -> -- | @pipeline@ is the ray tracing pipeline object containing the shaders -- groups. Pipeline -> -- | @group@ is the index of the shader group to query. ("group" ::: Word32) -> -- | @groupShader@ is the type of shader from the group to query. ShaderGroupShaderKHR -> io (DeviceSize) getRayTracingShaderGroupStackSizeKHR device pipeline group groupShader = liftIO $ do let vkGetRayTracingShaderGroupStackSizeKHRPtr = pVkGetRayTracingShaderGroupStackSizeKHR (case device of Device{deviceCmds} -> deviceCmds) unless (vkGetRayTracingShaderGroupStackSizeKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetRayTracingShaderGroupStackSizeKHR is null" Nothing Nothing let vkGetRayTracingShaderGroupStackSizeKHR' = mkVkGetRayTracingShaderGroupStackSizeKHR vkGetRayTracingShaderGroupStackSizeKHRPtr r <- traceAroundEvent "vkGetRayTracingShaderGroupStackSizeKHR" (vkGetRayTracingShaderGroupStackSizeKHR' (deviceHandle (device)) (pipeline) (group) (groupShader)) pure $ (r) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCmdSetRayTracingPipelineStackSizeKHR :: FunPtr (Ptr CommandBuffer_T -> Word32 -> IO ()) -> Ptr CommandBuffer_T -> Word32 -> IO () -- | vkCmdSetRayTracingPipelineStackSizeKHR - Set the stack size dynamically -- for a ray tracing pipeline -- -- = Description -- -- This command sets the stack size for subsequent ray tracing commands -- when the ray tracing pipeline is created with -- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR' -- set in -- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo'::@pDynamicStates@. -- Otherwise, the stack size is computed as described in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#ray-tracing-pipeline-stack Ray Tracing Pipeline Stack>. -- -- == Valid Usage -- -- - #VUID-vkCmdSetRayTracingPipelineStackSizeKHR-pipelineStackSize-03610# -- @pipelineStackSize@ /must/ be large enough for any dynamic execution -- through the shaders in the ray tracing pipeline used by a subsequent -- trace call -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCmdSetRayTracingPipelineStackSizeKHR-commandBuffer-parameter# -- @commandBuffer@ /must/ be a valid -- 'Vulkan.Core10.Handles.CommandBuffer' handle -- -- - #VUID-vkCmdSetRayTracingPipelineStackSizeKHR-commandBuffer-recording# -- @commandBuffer@ /must/ be in the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> -- -- - #VUID-vkCmdSetRayTracingPipelineStackSizeKHR-commandBuffer-cmdpool# -- The 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was -- allocated from /must/ support compute operations -- -- - #VUID-vkCmdSetRayTracingPipelineStackSizeKHR-renderpass# This -- command /must/ only be called outside of a render pass instance -- -- == Host Synchronization -- -- - Host access to @commandBuffer@ /must/ be externally synchronized -- -- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that -- @commandBuffer@ was allocated from /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> | -- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+ -- | Primary | Outside | Compute | -- | Secondary | | | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.Handles.CommandBuffer' cmdSetRayTracingPipelineStackSizeKHR :: forall io . (MonadIO io) => -- | @commandBuffer@ is the command buffer into which the command will be -- recorded. CommandBuffer -> -- | @pipelineStackSize@ is the stack size to use for subsequent ray tracing -- trace commands. ("pipelineStackSize" ::: Word32) -> io () cmdSetRayTracingPipelineStackSizeKHR commandBuffer pipelineStackSize = liftIO $ do let vkCmdSetRayTracingPipelineStackSizeKHRPtr = pVkCmdSetRayTracingPipelineStackSizeKHR (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds) unless (vkCmdSetRayTracingPipelineStackSizeKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetRayTracingPipelineStackSizeKHR is null" Nothing Nothing let vkCmdSetRayTracingPipelineStackSizeKHR' = mkVkCmdSetRayTracingPipelineStackSizeKHR vkCmdSetRayTracingPipelineStackSizeKHRPtr traceAroundEvent "vkCmdSetRayTracingPipelineStackSizeKHR" (vkCmdSetRayTracingPipelineStackSizeKHR' (commandBufferHandle (commandBuffer)) (pipelineStackSize)) pure $ () -- | VkRayTracingShaderGroupCreateInfoKHR - Structure specifying shaders in a -- shader group -- -- == Valid Usage -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474# If @type@ is -- 'RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR' then @generalShader@ -- /must/ be a valid index into -- 'RayTracingPipelineCreateInfoKHR'::@pStages@ referring to a shader -- of -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_RAYGEN_BIT_KHR', -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_MISS_BIT_KHR', -- or -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_CALLABLE_BIT_KHR' -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475# If @type@ is -- 'RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR' then @closestHitShader@, -- @anyHitShader@, and @intersectionShader@ /must/ be -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476# If @type@ is -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR' then -- @intersectionShader@ /must/ be a valid index into -- 'RayTracingPipelineCreateInfoKHR'::@pStages@ referring to a shader -- of -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_INTERSECTION_BIT_KHR' -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477# If @type@ is -- 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' then -- @intersectionShader@ /must/ be -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478# -- @closestHitShader@ /must/ be either -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' or a valid index into -- 'RayTracingPipelineCreateInfoKHR'::@pStages@ referring to a shader -- of -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_CLOSEST_HIT_BIT_KHR' -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479# -- @anyHitShader@ /must/ be either -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' or a valid index into -- 'RayTracingPipelineCreateInfoKHR'::@pStages@ referring to a shader -- of -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_ANY_HIT_BIT_KHR' -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-rayTracingPipelineShaderGroupHandleCaptureReplayMixed-03603# -- If -- 'PhysicalDeviceRayTracingPipelineFeaturesKHR'::@rayTracingPipelineShaderGroupHandleCaptureReplayMixed@ -- is 'Vulkan.Core10.FundamentalTypes.FALSE' then -- @pShaderGroupCaptureReplayHandle@ /must/ not be provided if it has -- not been provided on a previous call to ray tracing pipeline -- creation -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-rayTracingPipelineShaderGroupHandleCaptureReplayMixed-03604# -- If -- 'PhysicalDeviceRayTracingPipelineFeaturesKHR'::@rayTracingPipelineShaderGroupHandleCaptureReplayMixed@ -- is 'Vulkan.Core10.FundamentalTypes.FALSE' then the caller /must/ -- guarantee that no ray tracing pipeline creation commands with -- @pShaderGroupCaptureReplayHandle@ provided execute simultaneously -- with ray tracing pipeline creation commands without -- @pShaderGroupCaptureReplayHandle@ provided -- -- == Valid Usage (Implicit) -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-sType-sType# @sType@ -- /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR' -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-pNext-pNext# @pNext@ -- /must/ be @NULL@ -- -- - #VUID-VkRayTracingShaderGroupCreateInfoKHR-type-parameter# @type@ -- /must/ be a valid 'RayTracingShaderGroupTypeKHR' value -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'RayTracingPipelineCreateInfoKHR', 'RayTracingShaderGroupTypeKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data RayTracingShaderGroupCreateInfoKHR = RayTracingShaderGroupCreateInfoKHR { -- | @type@ is the type of hit group specified in this structure. type' :: RayTracingShaderGroupTypeKHR , -- | @generalShader@ is the index of the ray generation, miss, or callable -- shader from 'RayTracingPipelineCreateInfoKHR'::@pStages@ in the group if -- the shader group has @type@ of -- 'RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR', and -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' otherwise. generalShader :: Word32 , -- | @closestHitShader@ is the optional index of the closest hit shader from -- 'RayTracingPipelineCreateInfoKHR'::@pStages@ in the group if the shader -- group has @type@ of -- 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' or -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR', and -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' otherwise. closestHitShader :: Word32 , -- | @anyHitShader@ is the optional index of the any-hit shader from -- 'RayTracingPipelineCreateInfoKHR'::@pStages@ in the group if the shader -- group has @type@ of -- 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' or -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR', and -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' otherwise. anyHitShader :: Word32 , -- | @intersectionShader@ is the index of the intersection shader from -- 'RayTracingPipelineCreateInfoKHR'::@pStages@ in the group if the shader -- group has @type@ of -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR', and -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' otherwise. intersectionShader :: Word32 , -- | @pShaderGroupCaptureReplayHandle@ is @NULL@ or a pointer to replay -- information for this shader group. Ignored if -- 'PhysicalDeviceRayTracingPipelineFeaturesKHR'::@rayTracingPipelineShaderGroupHandleCaptureReplay@ -- is 'Vulkan.Core10.FundamentalTypes.FALSE'. shaderGroupCaptureReplayHandle :: Ptr () } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (RayTracingShaderGroupCreateInfoKHR) #endif deriving instance Show RayTracingShaderGroupCreateInfoKHR instance ToCStruct RayTracingShaderGroupCreateInfoKHR where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p RayTracingShaderGroupCreateInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr RayTracingShaderGroupTypeKHR)) (type') poke ((p `plusPtr` 20 :: Ptr Word32)) (generalShader) poke ((p `plusPtr` 24 :: Ptr Word32)) (closestHitShader) poke ((p `plusPtr` 28 :: Ptr Word32)) (anyHitShader) poke ((p `plusPtr` 32 :: Ptr Word32)) (intersectionShader) poke ((p `plusPtr` 40 :: Ptr (Ptr ()))) (shaderGroupCaptureReplayHandle) f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr RayTracingShaderGroupTypeKHR)) (zero) poke ((p `plusPtr` 20 :: Ptr Word32)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) poke ((p `plusPtr` 28 :: Ptr Word32)) (zero) poke ((p `plusPtr` 32 :: Ptr Word32)) (zero) f instance FromCStruct RayTracingShaderGroupCreateInfoKHR where peekCStruct p = do type' <- peek @RayTracingShaderGroupTypeKHR ((p `plusPtr` 16 :: Ptr RayTracingShaderGroupTypeKHR)) generalShader <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) closestHitShader <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) anyHitShader <- peek @Word32 ((p `plusPtr` 28 :: Ptr Word32)) intersectionShader <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pShaderGroupCaptureReplayHandle <- peek @(Ptr ()) ((p `plusPtr` 40 :: Ptr (Ptr ()))) pure $ RayTracingShaderGroupCreateInfoKHR type' generalShader closestHitShader anyHitShader intersectionShader pShaderGroupCaptureReplayHandle instance Storable RayTracingShaderGroupCreateInfoKHR where sizeOf ~_ = 48 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero RayTracingShaderGroupCreateInfoKHR where zero = RayTracingShaderGroupCreateInfoKHR zero zero zero zero zero zero -- | VkRayTracingPipelineCreateInfoKHR - Structure specifying parameters of a -- newly created ray tracing pipeline -- -- = Description -- -- The parameters @basePipelineHandle@ and @basePipelineIndex@ are -- described in more detail in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#pipelines-pipeline-derivatives Pipeline Derivatives>. -- -- When -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_LIBRARY_BIT_KHR' -- is specified, this pipeline defines a /pipeline library/ which /cannot/ -- be bound as a ray tracing pipeline directly. Instead, pipeline libraries -- define common shaders and shader groups which /can/ be included in -- future pipeline creation. -- -- If pipeline libraries are included in @pLibraryInfo@, shaders defined in -- those libraries are treated as if they were defined as additional -- entries in @pStages@, appended in the order they appear in the -- @pLibraries@ array and in the @pStages@ array when those libraries were -- defined. -- -- When referencing shader groups in order to obtain a shader group handle, -- groups defined in those libraries are treated as if they were defined as -- additional entries in @pGroups@, appended in the order they appear in -- the @pLibraries@ array and in the @pGroups@ array when those libraries -- were defined. The shaders these groups reference are set when the -- pipeline library is created, referencing those specified in the pipeline -- library, not in the pipeline that includes it. -- -- The default stack size for a pipeline if -- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR' -- is not provided is computed as described in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#ray-tracing-pipeline-stack Ray Tracing Pipeline Stack>. -- -- == Valid Usage -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03421# If @flags@ -- contains the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_DERIVATIVE_BIT' -- flag, and @basePipelineIndex@ is @-1@, @basePipelineHandle@ /must/ -- be a valid handle to a ray tracing 'Vulkan.Core10.Handles.Pipeline' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03422# If @flags@ -- contains the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_DERIVATIVE_BIT' -- flag, and @basePipelineHandle@ is -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @basePipelineIndex@ /must/ -- be a valid index into the calling command’s @pCreateInfos@ parameter -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03423# If @flags@ -- contains the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_DERIVATIVE_BIT' -- flag, and @basePipelineIndex@ is not @-1@, @basePipelineHandle@ -- /must/ be 'Vulkan.Core10.APIConstants.NULL_HANDLE' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03424# If @flags@ -- contains the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_DERIVATIVE_BIT' -- flag, and @basePipelineHandle@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @basePipelineIndex@ /must/ -- be @-1@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pStages-03426# The shader -- code for the entry points identified by @pStages@, and the rest of -- the state identified by this structure /must/ adhere to the pipeline -- linking rules described in the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#interfaces Shader Interfaces> -- chapter -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427# @layout@ -- /must/ be -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#descriptorsets-pipelinelayout-consistency consistent> -- with all shaders specified in @pStages@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-layout-03428# The number of -- resources in @layout@ accessible to each shader stage that is used -- by the pipeline /must/ be less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxPerStageResources@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-02904# @flags@ /must/ -- not include -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_INDIRECT_BINDABLE_BIT_NV' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pipelineCreationCacheControl-02905# -- If the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-pipelineCreationCacheControl pipelineCreationCacheControl> -- feature is not enabled, @flags@ /must/ not include -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT' -- or -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425# If @flags@ does -- not include -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_LIBRARY_BIT_KHR', -- the @stage@ member of at least one element of @pStages@, including -- those implicitly added by @pLibraryInfo@, /must/ be -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_RAYGEN_BIT_KHR' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-maxPipelineRayRecursionDepth-03589# -- @maxPipelineRayRecursionDepth@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxRayRecursionDepth@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03465# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_LIBRARY_BIT_KHR', -- @pLibraryInterface@ /must/ not be @NULL@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03590# If -- @pLibraryInfo@ is not @NULL@ and its @libraryCount@ member is -- greater than @0@, its @pLibraryInterface@ member /must/ not be -- @NULL@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03591# Each -- element of @pLibraryInfo->pLibraries@ /must/ have been created with -- the value of @maxPipelineRayRecursionDepth@ equal to that in this -- pipeline -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03592# If -- @pLibraryInfo@ is not @NULL@, each element of its @pLibraries@ -- member /must/ have been created with a @layout@ that is compatible -- with the @layout@ in this pipeline -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03593# If -- @pLibraryInfo@ is not @NULL@, each element of its @pLibraries@ -- member /must/ have been created with values of the -- @maxPipelineRayPayloadSize@ and @maxPipelineRayHitAttributeSize@ -- members of @pLibraryInterface@ equal to those in this pipeline -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03594# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR', -- each element of @pLibraryInfo->pLibraries@ /must/ have been created -- with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR' -- bit set -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-04718# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_AABBS_BIT_KHR', -- each element of @pLibraryInfo->pLibraries@ /must/ have been created -- with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_AABBS_BIT_KHR' -- bit set -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-04719# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR', -- each element of @pLibraryInfo->pLibraries@ /must/ have been created -- with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR' -- bit set -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-04720# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_ANY_HIT_SHADERS_BIT_KHR', -- each element of @pLibraryInfo->pLibraries@ /must/ have been created -- with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_ANY_HIT_SHADERS_BIT_KHR' -- bit set -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-04721# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR', -- each element of @pLibraryInfo->pLibraries@ /must/ have been created -- with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR' -- bit set -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-04722# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR', -- each element of @pLibraryInfo->pLibraries@ /must/ have been created -- with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_INTERSECTION_SHADERS_BIT_KHR' -- bit set -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-04723# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_MISS_SHADERS_BIT_KHR', -- each element of @pLibraryInfo->pLibraries@ /must/ have been created -- with the -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_MISS_SHADERS_BIT_KHR' -- bit set -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03595# If the -- @VK_KHR_pipeline_library@ extension is not enabled, @pLibraryInfo@ -- and @pLibraryInterface@ /must/ be @NULL@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03470# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_ANY_HIT_SHADERS_BIT_KHR', -- for any element of @pGroups@ with a @type@ of -- 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' or -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR', the -- @anyHitShader@ of that element /must/ not be -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03471# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_NO_NULL_CLOSEST_HIT_SHADERS_BIT_KHR', -- for any element of @pGroups@ with a @type@ of -- 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' or -- 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR', the -- @closestHitShader@ of that element /must/ not be -- 'Vulkan.Core10.APIConstants.SHADER_UNUSED_KHR' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-rayTraversalPrimitiveCulling-03596# -- If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-rayTraversalPrimitiveCulling rayTraversalPrimitiveCulling> -- feature is not enabled, @flags@ /must/ not include -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_AABBS_BIT_KHR' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-rayTraversalPrimitiveCulling-03597# -- If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-rayTraversalPrimitiveCulling rayTraversalPrimitiveCulling> -- feature is not enabled, @flags@ /must/ not include -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-03598# If @flags@ -- includes -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR', -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-rayTracingPipelineShaderGroupHandleCaptureReplay rayTracingPipelineShaderGroupHandleCaptureReplay> -- /must/ be enabled -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-rayTracingPipelineShaderGroupHandleCaptureReplay-03599# -- If -- 'PhysicalDeviceRayTracingPipelineFeaturesKHR'::@rayTracingPipelineShaderGroupHandleCaptureReplay@ -- is 'Vulkan.Core10.FundamentalTypes.TRUE' and the -- @pShaderGroupCaptureReplayHandle@ member of any element of @pGroups@ -- is not @NULL@, @flags@ /must/ include -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03600# If -- @pLibraryInfo@ is not @NULL@ and its @libraryCount@ is @0@, -- @stageCount@ /must/ not be @0@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-03601# If -- @pLibraryInfo@ is not @NULL@ and its @libraryCount@ is @0@, -- @groupCount@ /must/ not be @0@ -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pDynamicStates-03602# Any -- element of the @pDynamicStates@ member of @pDynamicState@ /must/ be -- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-sType-sType# @sType@ /must/ -- be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pNext-pNext# @pNext@ /must/ -- be @NULL@ or a pointer to a valid instance of -- 'Vulkan.Core13.Promoted_From_VK_EXT_pipeline_creation_feedback.PipelineCreationFeedbackCreateInfo' -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-sType-unique# The @sType@ -- value of each struct in the @pNext@ chain /must/ be unique -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-flags-parameter# @flags@ -- /must/ be a valid combination of -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits' -- values -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pStages-parameter# If -- @stageCount@ is not @0@, @pStages@ /must/ be a valid pointer to an -- array of @stageCount@ valid -- 'Vulkan.Core10.Pipeline.PipelineShaderStageCreateInfo' structures -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pGroups-parameter# If -- @groupCount@ is not @0@, @pGroups@ /must/ be a valid pointer to an -- array of @groupCount@ valid 'RayTracingShaderGroupCreateInfoKHR' -- structures -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInfo-parameter# If -- @pLibraryInfo@ is not @NULL@, @pLibraryInfo@ /must/ be a valid -- pointer to a valid -- 'Vulkan.Extensions.VK_KHR_pipeline_library.PipelineLibraryCreateInfoKHR' -- structure -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pLibraryInterface-parameter# -- If @pLibraryInterface@ is not @NULL@, @pLibraryInterface@ /must/ be -- a valid pointer to a valid -- 'RayTracingPipelineInterfaceCreateInfoKHR' structure -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-pDynamicState-parameter# If -- @pDynamicState@ is not @NULL@, @pDynamicState@ /must/ be a valid -- pointer to a valid -- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo' structure -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-layout-parameter# @layout@ -- /must/ be a valid 'Vulkan.Core10.Handles.PipelineLayout' handle -- -- - #VUID-VkRayTracingPipelineCreateInfoKHR-commonparent# Both of -- @basePipelineHandle@, and @layout@ that are valid handles of -- non-ignored parameters /must/ have been created, allocated, or -- retrieved from the same 'Vulkan.Core10.Handles.Device' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.Handles.Pipeline', -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlags', -- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo', -- 'Vulkan.Core10.Handles.PipelineLayout', -- 'Vulkan.Extensions.VK_KHR_pipeline_library.PipelineLibraryCreateInfoKHR', -- 'Vulkan.Core10.Pipeline.PipelineShaderStageCreateInfo', -- 'RayTracingPipelineInterfaceCreateInfoKHR', -- 'RayTracingShaderGroupCreateInfoKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'createRayTracingPipelinesKHR' data RayTracingPipelineCreateInfoKHR (es :: [Type]) = RayTracingPipelineCreateInfoKHR { -- | @pNext@ is @NULL@ or a pointer to a structure extending this structure. next :: Chain es , -- | @flags@ is a bitmask of -- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits' -- specifying how the pipeline will be generated. flags :: PipelineCreateFlags , -- | @pStages@ is a pointer to an array of @stageCount@ -- 'Vulkan.Core10.Pipeline.PipelineShaderStageCreateInfo' structures -- describing the set of the shader stages to be included in the ray -- tracing pipeline. stages :: Vector (SomeStruct PipelineShaderStageCreateInfo) , -- | @pGroups@ is a pointer to an array of @groupCount@ -- 'RayTracingShaderGroupCreateInfoKHR' structures describing the set of -- the shader stages to be included in each shader group in the ray tracing -- pipeline. groups :: Vector RayTracingShaderGroupCreateInfoKHR , -- | @maxPipelineRayRecursionDepth@ is the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#ray-tracing-recursion-depth maximum recursion depth> -- of shaders executed by this pipeline. maxPipelineRayRecursionDepth :: Word32 , -- | @pLibraryInfo@ is a pointer to a -- 'Vulkan.Extensions.VK_KHR_pipeline_library.PipelineLibraryCreateInfoKHR' -- structure defining pipeline libraries to include. libraryInfo :: Maybe PipelineLibraryCreateInfoKHR , -- | @pLibraryInterface@ is a pointer to a -- 'RayTracingPipelineInterfaceCreateInfoKHR' structure defining additional -- information when using pipeline libraries. libraryInterface :: Maybe RayTracingPipelineInterfaceCreateInfoKHR , -- | @pDynamicState@ is a pointer to a -- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo' structure, and -- is used to indicate which properties of the pipeline state object are -- dynamic and /can/ be changed independently of the pipeline state. This -- /can/ be @NULL@, which means no state in the pipeline is considered -- dynamic. dynamicState :: Maybe PipelineDynamicStateCreateInfo , -- | @layout@ is the description of binding locations used by both the -- pipeline and descriptor sets used with the pipeline. layout :: PipelineLayout , -- | @basePipelineHandle@ is a pipeline to derive from. basePipelineHandle :: Pipeline , -- | @basePipelineIndex@ is an index into the @pCreateInfos@ parameter to use -- as a pipeline to derive from. basePipelineIndex :: Int32 } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (RayTracingPipelineCreateInfoKHR (es :: [Type])) #endif deriving instance Show (Chain es) => Show (RayTracingPipelineCreateInfoKHR es) instance Extensible RayTracingPipelineCreateInfoKHR where extensibleTypeName = "RayTracingPipelineCreateInfoKHR" setNext RayTracingPipelineCreateInfoKHR{..} next' = RayTracingPipelineCreateInfoKHR{next = next', ..} getNext RayTracingPipelineCreateInfoKHR{..} = next extends :: forall e b proxy. Typeable e => proxy e -> (Extends RayTracingPipelineCreateInfoKHR e => b) -> Maybe b extends _ f | Just Refl <- eqT @e @PipelineCreationFeedbackCreateInfo = Just f | otherwise = Nothing instance (Extendss RayTracingPipelineCreateInfoKHR es, PokeChain es) => ToCStruct (RayTracingPipelineCreateInfoKHR es) where withCStruct x f = allocaBytes 104 $ \p -> pokeCStruct p x (f p) pokeCStruct p RayTracingPipelineCreateInfoKHR{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) pNext'' <- fmap castPtr . ContT $ withChain (next) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'' lift $ poke ((p `plusPtr` 16 :: Ptr PipelineCreateFlags)) (flags) lift $ poke ((p `plusPtr` 20 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (stages)) :: Word32)) pPStages' <- ContT $ allocaBytes @(PipelineShaderStageCreateInfo _) ((Data.Vector.length (stages)) * 48) Data.Vector.imapM_ (\i e -> ContT $ pokeSomeCStruct (forgetExtensions (pPStages' `plusPtr` (48 * (i)) :: Ptr (PipelineShaderStageCreateInfo _))) (e) . ($ ())) (stages) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr (PipelineShaderStageCreateInfo _)))) (pPStages') lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (groups)) :: Word32)) pPGroups' <- ContT $ allocaBytes @RayTracingShaderGroupCreateInfoKHR ((Data.Vector.length (groups)) * 48) lift $ Data.Vector.imapM_ (\i e -> poke (pPGroups' `plusPtr` (48 * (i)) :: Ptr RayTracingShaderGroupCreateInfoKHR) (e)) (groups) lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr RayTracingShaderGroupCreateInfoKHR))) (pPGroups') lift $ poke ((p `plusPtr` 48 :: Ptr Word32)) (maxPipelineRayRecursionDepth) pLibraryInfo'' <- case (libraryInfo) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ poke ((p `plusPtr` 56 :: Ptr (Ptr PipelineLibraryCreateInfoKHR))) pLibraryInfo'' pLibraryInterface'' <- case (libraryInterface) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ poke ((p `plusPtr` 64 :: Ptr (Ptr RayTracingPipelineInterfaceCreateInfoKHR))) pLibraryInterface'' pDynamicState'' <- case (dynamicState) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ poke ((p `plusPtr` 72 :: Ptr (Ptr PipelineDynamicStateCreateInfo))) pDynamicState'' lift $ poke ((p `plusPtr` 80 :: Ptr PipelineLayout)) (layout) lift $ poke ((p `plusPtr` 88 :: Ptr Pipeline)) (basePipelineHandle) lift $ poke ((p `plusPtr` 96 :: Ptr Int32)) (basePipelineIndex) lift $ f cStructSize = 104 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) pNext' <- fmap castPtr . ContT $ withZeroChain @es lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext' lift $ poke ((p `plusPtr` 48 :: Ptr Word32)) (zero) lift $ poke ((p `plusPtr` 80 :: Ptr PipelineLayout)) (zero) lift $ poke ((p `plusPtr` 96 :: Ptr Int32)) (zero) lift $ f instance (Extendss RayTracingPipelineCreateInfoKHR es, PeekChain es) => FromCStruct (RayTracingPipelineCreateInfoKHR es) where peekCStruct p = do pNext <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ()))) next <- peekChain (castPtr pNext) flags <- peek @PipelineCreateFlags ((p `plusPtr` 16 :: Ptr PipelineCreateFlags)) stageCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) pStages <- peek @(Ptr (PipelineShaderStageCreateInfo _)) ((p `plusPtr` 24 :: Ptr (Ptr (PipelineShaderStageCreateInfo _)))) pStages' <- generateM (fromIntegral stageCount) (\i -> peekSomeCStruct (forgetExtensions ((pStages `advancePtrBytes` (48 * (i)) :: Ptr (PipelineShaderStageCreateInfo _))))) groupCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pGroups <- peek @(Ptr RayTracingShaderGroupCreateInfoKHR) ((p `plusPtr` 40 :: Ptr (Ptr RayTracingShaderGroupCreateInfoKHR))) pGroups' <- generateM (fromIntegral groupCount) (\i -> peekCStruct @RayTracingShaderGroupCreateInfoKHR ((pGroups `advancePtrBytes` (48 * (i)) :: Ptr RayTracingShaderGroupCreateInfoKHR))) maxPipelineRayRecursionDepth <- peek @Word32 ((p `plusPtr` 48 :: Ptr Word32)) pLibraryInfo <- peek @(Ptr PipelineLibraryCreateInfoKHR) ((p `plusPtr` 56 :: Ptr (Ptr PipelineLibraryCreateInfoKHR))) pLibraryInfo' <- maybePeek (\j -> peekCStruct @PipelineLibraryCreateInfoKHR (j)) pLibraryInfo pLibraryInterface <- peek @(Ptr RayTracingPipelineInterfaceCreateInfoKHR) ((p `plusPtr` 64 :: Ptr (Ptr RayTracingPipelineInterfaceCreateInfoKHR))) pLibraryInterface' <- maybePeek (\j -> peekCStruct @RayTracingPipelineInterfaceCreateInfoKHR (j)) pLibraryInterface pDynamicState <- peek @(Ptr PipelineDynamicStateCreateInfo) ((p `plusPtr` 72 :: Ptr (Ptr PipelineDynamicStateCreateInfo))) pDynamicState' <- maybePeek (\j -> peekCStruct @PipelineDynamicStateCreateInfo (j)) pDynamicState layout <- peek @PipelineLayout ((p `plusPtr` 80 :: Ptr PipelineLayout)) basePipelineHandle <- peek @Pipeline ((p `plusPtr` 88 :: Ptr Pipeline)) basePipelineIndex <- peek @Int32 ((p `plusPtr` 96 :: Ptr Int32)) pure $ RayTracingPipelineCreateInfoKHR next flags pStages' pGroups' maxPipelineRayRecursionDepth pLibraryInfo' pLibraryInterface' pDynamicState' layout basePipelineHandle basePipelineIndex instance es ~ '[] => Zero (RayTracingPipelineCreateInfoKHR es) where zero = RayTracingPipelineCreateInfoKHR () zero mempty mempty zero Nothing Nothing Nothing zero zero zero -- | VkPhysicalDeviceRayTracingPipelineFeaturesKHR - Structure describing the -- ray tracing features that can be supported by an implementation -- -- = Members -- -- This structure describes the following features: -- -- = Description -- -- - @sType@ is the type of this structure. -- -- - @pNext@ is @NULL@ or a pointer to a structure extending this -- structure. -- -- - #features-rayTracingPipeline# @rayTracingPipeline@ indicates whether -- the implementation supports the ray tracing pipeline functionality. -- See -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#ray-tracing Ray Tracing>. -- -- - #features-rayTracingPipelineShaderGroupHandleCaptureReplay# -- @rayTracingPipelineShaderGroupHandleCaptureReplay@ indicates whether -- the implementation supports saving and reusing shader group handles, -- e.g. for trace capture and replay. -- -- - #features-rayTracingPipelineShaderGroupHandleCaptureReplayMixed# -- @rayTracingPipelineShaderGroupHandleCaptureReplayMixed@ indicates -- whether the implementation supports reuse of shader group handles -- being arbitrarily mixed with creation of non-reused shader group -- handles. If this is 'Vulkan.Core10.FundamentalTypes.FALSE', all -- reused shader group handles /must/ be specified before any -- non-reused handles /may/ be created. -- -- - #features-rayTracingPipelineTraceRaysIndirect# -- @rayTracingPipelineTraceRaysIndirect@ indicates whether the -- implementation supports indirect ray tracing commands, e.g. -- 'cmdTraceRaysIndirectKHR'. -- -- - #features-rayTraversalPrimitiveCulling# -- @rayTraversalPrimitiveCulling@ indicates whether the implementation -- supports -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#ray-traversal-culling-primitive primitive culling during ray traversal>. -- -- If the 'PhysicalDeviceRayTracingPipelineFeaturesKHR' structure is -- included in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. 'PhysicalDeviceRayTracingPipelineFeaturesKHR' /can/ also be -- used in the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to -- selectively enable these features. -- -- == Valid Usage -- -- - #VUID-VkPhysicalDeviceRayTracingPipelineFeaturesKHR-rayTracingPipelineShaderGroupHandleCaptureReplayMixed-03575# -- If @rayTracingPipelineShaderGroupHandleCaptureReplayMixed@ is -- 'Vulkan.Core10.FundamentalTypes.TRUE', -- @rayTracingPipelineShaderGroupHandleCaptureReplay@ /must/ also be -- 'Vulkan.Core10.FundamentalTypes.TRUE' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkPhysicalDeviceRayTracingPipelineFeaturesKHR-sType-sType# -- @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceRayTracingPipelineFeaturesKHR = PhysicalDeviceRayTracingPipelineFeaturesKHR { -- No documentation found for Nested "VkPhysicalDeviceRayTracingPipelineFeaturesKHR" "rayTracingPipeline" rayTracingPipeline :: Bool , -- No documentation found for Nested "VkPhysicalDeviceRayTracingPipelineFeaturesKHR" "rayTracingPipelineShaderGroupHandleCaptureReplay" rayTracingPipelineShaderGroupHandleCaptureReplay :: Bool , -- No documentation found for Nested "VkPhysicalDeviceRayTracingPipelineFeaturesKHR" "rayTracingPipelineShaderGroupHandleCaptureReplayMixed" rayTracingPipelineShaderGroupHandleCaptureReplayMixed :: Bool , -- No documentation found for Nested "VkPhysicalDeviceRayTracingPipelineFeaturesKHR" "rayTracingPipelineTraceRaysIndirect" rayTracingPipelineTraceRaysIndirect :: Bool , -- No documentation found for Nested "VkPhysicalDeviceRayTracingPipelineFeaturesKHR" "rayTraversalPrimitiveCulling" rayTraversalPrimitiveCulling :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceRayTracingPipelineFeaturesKHR) #endif deriving instance Show PhysicalDeviceRayTracingPipelineFeaturesKHR instance ToCStruct PhysicalDeviceRayTracingPipelineFeaturesKHR where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceRayTracingPipelineFeaturesKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (rayTracingPipeline)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (rayTracingPipelineShaderGroupHandleCaptureReplay)) poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (rayTracingPipelineShaderGroupHandleCaptureReplayMixed)) poke ((p `plusPtr` 28 :: Ptr Bool32)) (boolToBool32 (rayTracingPipelineTraceRaysIndirect)) poke ((p `plusPtr` 32 :: Ptr Bool32)) (boolToBool32 (rayTraversalPrimitiveCulling)) f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 28 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 32 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceRayTracingPipelineFeaturesKHR where peekCStruct p = do rayTracingPipeline <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) rayTracingPipelineShaderGroupHandleCaptureReplay <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32)) rayTracingPipelineShaderGroupHandleCaptureReplayMixed <- peek @Bool32 ((p `plusPtr` 24 :: Ptr Bool32)) rayTracingPipelineTraceRaysIndirect <- peek @Bool32 ((p `plusPtr` 28 :: Ptr Bool32)) rayTraversalPrimitiveCulling <- peek @Bool32 ((p `plusPtr` 32 :: Ptr Bool32)) pure $ PhysicalDeviceRayTracingPipelineFeaturesKHR (bool32ToBool rayTracingPipeline) (bool32ToBool rayTracingPipelineShaderGroupHandleCaptureReplay) (bool32ToBool rayTracingPipelineShaderGroupHandleCaptureReplayMixed) (bool32ToBool rayTracingPipelineTraceRaysIndirect) (bool32ToBool rayTraversalPrimitiveCulling) instance Storable PhysicalDeviceRayTracingPipelineFeaturesKHR where sizeOf ~_ = 40 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceRayTracingPipelineFeaturesKHR where zero = PhysicalDeviceRayTracingPipelineFeaturesKHR zero zero zero zero zero -- | VkPhysicalDeviceRayTracingPipelinePropertiesKHR - Properties of the -- physical device for ray tracing -- -- = Description -- -- If the 'PhysicalDeviceRayTracingPipelinePropertiesKHR' structure is -- included in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2', -- it is filled in with each corresponding implementation-dependent -- property. -- -- Limits specified by this structure /must/ match those specified with the -- same name in -- 'Vulkan.Extensions.VK_NV_ray_tracing.PhysicalDeviceRayTracingPropertiesNV'. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceRayTracingPipelinePropertiesKHR = PhysicalDeviceRayTracingPipelinePropertiesKHR { -- | @shaderGroupHandleSize@ is the size in bytes of the shader header. shaderGroupHandleSize :: Word32 , -- | #limits-maxRayRecursionDepth# @maxRayRecursionDepth@ is the maximum -- number of levels of ray recursion allowed in a trace command. maxRayRecursionDepth :: Word32 , -- | @maxShaderGroupStride@ is the maximum stride in bytes allowed between -- shader groups in the shader binding table. maxShaderGroupStride :: Word32 , -- | @shaderGroupBaseAlignment@ is the /required/ alignment in bytes for the -- base of the shader binding table. shaderGroupBaseAlignment :: Word32 , -- | @shaderGroupHandleCaptureReplaySize@ is the number of bytes for the -- information required to do capture and replay for shader group handles. shaderGroupHandleCaptureReplaySize :: Word32 , -- | @maxRayDispatchInvocationCount@ is the maximum number of ray generation -- shader invocations which /may/ be produced by a single -- 'cmdTraceRaysIndirectKHR' or 'cmdTraceRaysKHR' command. maxRayDispatchInvocationCount :: Word32 , -- | @shaderGroupHandleAlignment@ is the /required/ alignment in bytes for -- each shader binding table entry. The value /must/ be a power of two. shaderGroupHandleAlignment :: Word32 , -- | @maxRayHitAttributeSize@ is the maximum size in bytes for a ray -- attribute structure maxRayHitAttributeSize :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceRayTracingPipelinePropertiesKHR) #endif deriving instance Show PhysicalDeviceRayTracingPipelinePropertiesKHR instance ToCStruct PhysicalDeviceRayTracingPipelinePropertiesKHR where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceRayTracingPipelinePropertiesKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (shaderGroupHandleSize) poke ((p `plusPtr` 20 :: Ptr Word32)) (maxRayRecursionDepth) poke ((p `plusPtr` 24 :: Ptr Word32)) (maxShaderGroupStride) poke ((p `plusPtr` 28 :: Ptr Word32)) (shaderGroupBaseAlignment) poke ((p `plusPtr` 32 :: Ptr Word32)) (shaderGroupHandleCaptureReplaySize) poke ((p `plusPtr` 36 :: Ptr Word32)) (maxRayDispatchInvocationCount) poke ((p `plusPtr` 40 :: Ptr Word32)) (shaderGroupHandleAlignment) poke ((p `plusPtr` 44 :: Ptr Word32)) (maxRayHitAttributeSize) f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (zero) poke ((p `plusPtr` 20 :: Ptr Word32)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) poke ((p `plusPtr` 28 :: Ptr Word32)) (zero) poke ((p `plusPtr` 32 :: Ptr Word32)) (zero) poke ((p `plusPtr` 36 :: Ptr Word32)) (zero) poke ((p `plusPtr` 40 :: Ptr Word32)) (zero) poke ((p `plusPtr` 44 :: Ptr Word32)) (zero) f instance FromCStruct PhysicalDeviceRayTracingPipelinePropertiesKHR where peekCStruct p = do shaderGroupHandleSize <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) maxRayRecursionDepth <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) maxShaderGroupStride <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) shaderGroupBaseAlignment <- peek @Word32 ((p `plusPtr` 28 :: Ptr Word32)) shaderGroupHandleCaptureReplaySize <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) maxRayDispatchInvocationCount <- peek @Word32 ((p `plusPtr` 36 :: Ptr Word32)) shaderGroupHandleAlignment <- peek @Word32 ((p `plusPtr` 40 :: Ptr Word32)) maxRayHitAttributeSize <- peek @Word32 ((p `plusPtr` 44 :: Ptr Word32)) pure $ PhysicalDeviceRayTracingPipelinePropertiesKHR shaderGroupHandleSize maxRayRecursionDepth maxShaderGroupStride shaderGroupBaseAlignment shaderGroupHandleCaptureReplaySize maxRayDispatchInvocationCount shaderGroupHandleAlignment maxRayHitAttributeSize instance Storable PhysicalDeviceRayTracingPipelinePropertiesKHR where sizeOf ~_ = 48 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceRayTracingPipelinePropertiesKHR where zero = PhysicalDeviceRayTracingPipelinePropertiesKHR zero zero zero zero zero zero zero zero -- | VkStridedDeviceAddressRegionKHR - Structure specifying a region of -- device addresses with a stride -- -- == Valid Usage -- -- - #VUID-VkStridedDeviceAddressRegionKHR-size-04631# If @size@ is not -- zero, all addresses between @deviceAddress@ and @deviceAddress@ + -- @size@ - 1 /must/ be in the buffer device address range of the same -- buffer -- -- - #VUID-VkStridedDeviceAddressRegionKHR-size-04632# If @size@ is not -- zero, @stride@ /must/ be less than or equal to the size of the -- buffer from which @deviceAddress@ was queried -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'Vulkan.Core10.FundamentalTypes.DeviceAddress', -- 'Vulkan.Core10.FundamentalTypes.DeviceSize', 'cmdTraceRaysIndirectKHR', -- 'cmdTraceRaysKHR' data StridedDeviceAddressRegionKHR = StridedDeviceAddressRegionKHR { -- | @deviceAddress@ is the device address (as returned by the -- 'Vulkan.Core12.Promoted_From_VK_KHR_buffer_device_address.getBufferDeviceAddress' -- command) at which the region starts, or zero if the region is unused. deviceAddress :: DeviceAddress , -- | @stride@ is the byte stride between consecutive elements. stride :: DeviceSize , -- | @size@ is the size in bytes of the region starting at @deviceAddress@. size :: DeviceSize } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (StridedDeviceAddressRegionKHR) #endif deriving instance Show StridedDeviceAddressRegionKHR instance ToCStruct StridedDeviceAddressRegionKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p StridedDeviceAddressRegionKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr DeviceAddress)) (deviceAddress) poke ((p `plusPtr` 8 :: Ptr DeviceSize)) (stride) poke ((p `plusPtr` 16 :: Ptr DeviceSize)) (size) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 8 :: Ptr DeviceSize)) (zero) poke ((p `plusPtr` 16 :: Ptr DeviceSize)) (zero) f instance FromCStruct StridedDeviceAddressRegionKHR where peekCStruct p = do deviceAddress <- peek @DeviceAddress ((p `plusPtr` 0 :: Ptr DeviceAddress)) stride <- peek @DeviceSize ((p `plusPtr` 8 :: Ptr DeviceSize)) size <- peek @DeviceSize ((p `plusPtr` 16 :: Ptr DeviceSize)) pure $ StridedDeviceAddressRegionKHR deviceAddress stride size instance Storable StridedDeviceAddressRegionKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero StridedDeviceAddressRegionKHR where zero = StridedDeviceAddressRegionKHR zero zero zero -- | VkTraceRaysIndirectCommandKHR - Structure specifying the parameters of -- an indirect ray tracing command -- -- = Description -- -- The members of 'TraceRaysIndirectCommandKHR' have the same meaning as -- the similarly named parameters of 'cmdTraceRaysKHR'. -- -- == Valid Usage -- -- - #VUID-VkTraceRaysIndirectCommandKHR-width-03638# @width@ /must/ be -- less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupCount@[0] -- × -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupSize@[0] -- -- - #VUID-VkTraceRaysIndirectCommandKHR-height-03639# @height@ /must/ be -- less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupCount@[1] -- × -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupSize@[1] -- -- - #VUID-VkTraceRaysIndirectCommandKHR-depth-03640# @depth@ /must/ be -- less than or equal to -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupCount@[2] -- × -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxComputeWorkGroupSize@[2] -- -- - #VUID-VkTraceRaysIndirectCommandKHR-width-03641# @width@ × @height@ -- × @depth@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxRayDispatchInvocationCount@ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline> data TraceRaysIndirectCommandKHR = TraceRaysIndirectCommandKHR { -- | @width@ is the width of the ray trace query dimensions. width :: Word32 , -- | @height@ is height of the ray trace query dimensions. height :: Word32 , -- | @depth@ is depth of the ray trace query dimensions. depth :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (TraceRaysIndirectCommandKHR) #endif deriving instance Show TraceRaysIndirectCommandKHR instance ToCStruct TraceRaysIndirectCommandKHR where withCStruct x f = allocaBytes 12 $ \p -> pokeCStruct p x (f p) pokeCStruct p TraceRaysIndirectCommandKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr Word32)) (width) poke ((p `plusPtr` 4 :: Ptr Word32)) (height) poke ((p `plusPtr` 8 :: Ptr Word32)) (depth) f cStructSize = 12 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr Word32)) (zero) poke ((p `plusPtr` 4 :: Ptr Word32)) (zero) poke ((p `plusPtr` 8 :: Ptr Word32)) (zero) f instance FromCStruct TraceRaysIndirectCommandKHR where peekCStruct p = do width <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32)) height <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32)) depth <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32)) pure $ TraceRaysIndirectCommandKHR width height depth instance Storable TraceRaysIndirectCommandKHR where sizeOf ~_ = 12 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero TraceRaysIndirectCommandKHR where zero = TraceRaysIndirectCommandKHR zero zero zero -- | VkRayTracingPipelineInterfaceCreateInfoKHR - Structure specifying -- additional interface information when using libraries -- -- = Description -- -- @maxPipelineRayPayloadSize@ is calculated as the maximum number of bytes -- used by any block declared in the @RayPayloadKHR@ or -- @IncomingRayPayloadKHR@ storage classes. -- @maxPipelineRayHitAttributeSize@ is calculated as the maximum number of -- bytes used by any block declared in the @HitAttributeKHR@ storage class. -- As variables in these storage classes do not have explicit offsets, the -- size should be calculated as if each variable has a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-alignment-requirements scalar alignment> -- equal to the largest scalar alignment of any of the block’s members. -- -- Note -- -- There is no explicit upper limit for @maxPipelineRayPayloadSize@, but in -- practice it should be kept as small as possible. Similar to invocation -- local memory, it must be allocated for each shader invocation and for -- devices which support many simultaneous invocations, this storage can -- rapidly be exhausted, resulting in failure. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'RayTracingPipelineCreateInfoKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data RayTracingPipelineInterfaceCreateInfoKHR = RayTracingPipelineInterfaceCreateInfoKHR { -- | @maxPipelineRayPayloadSize@ is the maximum payload size in bytes used by -- any shader in the pipeline. maxPipelineRayPayloadSize :: Word32 , -- | @maxPipelineRayHitAttributeSize@ is the maximum attribute structure size -- in bytes used by any shader in the pipeline. -- -- #VUID-VkRayTracingPipelineInterfaceCreateInfoKHR-maxPipelineRayHitAttributeSize-03605# -- @maxPipelineRayHitAttributeSize@ /must/ be less than or equal to -- 'PhysicalDeviceRayTracingPipelinePropertiesKHR'::@maxRayHitAttributeSize@ maxPipelineRayHitAttributeSize :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (RayTracingPipelineInterfaceCreateInfoKHR) #endif deriving instance Show RayTracingPipelineInterfaceCreateInfoKHR instance ToCStruct RayTracingPipelineInterfaceCreateInfoKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p RayTracingPipelineInterfaceCreateInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RAY_TRACING_PIPELINE_INTERFACE_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (maxPipelineRayPayloadSize) poke ((p `plusPtr` 20 :: Ptr Word32)) (maxPipelineRayHitAttributeSize) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RAY_TRACING_PIPELINE_INTERFACE_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Word32)) (zero) poke ((p `plusPtr` 20 :: Ptr Word32)) (zero) f instance FromCStruct RayTracingPipelineInterfaceCreateInfoKHR where peekCStruct p = do maxPipelineRayPayloadSize <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) maxPipelineRayHitAttributeSize <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32)) pure $ RayTracingPipelineInterfaceCreateInfoKHR maxPipelineRayPayloadSize maxPipelineRayHitAttributeSize instance Storable RayTracingPipelineInterfaceCreateInfoKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero RayTracingPipelineInterfaceCreateInfoKHR where zero = RayTracingPipelineInterfaceCreateInfoKHR zero zero -- | VkRayTracingShaderGroupTypeKHR - Shader group types -- -- = Description -- -- Note -- -- For current group types, the hit group type could be inferred from the -- presence or absence of the intersection shader, but we provide the type -- explicitly for future hit groups that do not have that property. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_ray_tracing VK_NV_ray_tracing>, -- 'RayTracingShaderGroupCreateInfoKHR', -- 'Vulkan.Extensions.VK_NV_ray_tracing.RayTracingShaderGroupCreateInfoNV' newtype RayTracingShaderGroupTypeKHR = RayTracingShaderGroupTypeKHR Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR' indicates a shader group -- with a single -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_RAYGEN_BIT_KHR', -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_MISS_BIT_KHR', or -- 'Vulkan.Core10.Enums.ShaderStageFlagBits.SHADER_STAGE_CALLABLE_BIT_KHR' -- shader in it. pattern RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR = RayTracingShaderGroupTypeKHR 0 -- | 'RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR' specifies a -- shader group that only hits triangles and /must/ not contain an -- intersection shader, only closest hit and any-hit shaders. pattern RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR = RayTracingShaderGroupTypeKHR 1 -- | 'RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR' specifies a -- shader group that only intersects with custom geometry and /must/ -- contain an intersection shader and /may/ contain closest hit and any-hit -- shaders. pattern RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR = RayTracingShaderGroupTypeKHR 2 {-# complete RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR, RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR, RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR :: RayTracingShaderGroupTypeKHR #-} conNameRayTracingShaderGroupTypeKHR :: String conNameRayTracingShaderGroupTypeKHR = "RayTracingShaderGroupTypeKHR" enumPrefixRayTracingShaderGroupTypeKHR :: String enumPrefixRayTracingShaderGroupTypeKHR = "RAY_TRACING_SHADER_GROUP_TYPE_" showTableRayTracingShaderGroupTypeKHR :: [(RayTracingShaderGroupTypeKHR, String)] showTableRayTracingShaderGroupTypeKHR = [ (RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR , "GENERAL_KHR") , (RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR , "TRIANGLES_HIT_GROUP_KHR") , (RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR, "PROCEDURAL_HIT_GROUP_KHR") ] instance Show RayTracingShaderGroupTypeKHR where showsPrec = enumShowsPrec enumPrefixRayTracingShaderGroupTypeKHR showTableRayTracingShaderGroupTypeKHR conNameRayTracingShaderGroupTypeKHR (\(RayTracingShaderGroupTypeKHR x) -> x) (showsPrec 11) instance Read RayTracingShaderGroupTypeKHR where readPrec = enumReadPrec enumPrefixRayTracingShaderGroupTypeKHR showTableRayTracingShaderGroupTypeKHR conNameRayTracingShaderGroupTypeKHR RayTracingShaderGroupTypeKHR -- | VkShaderGroupShaderKHR - Shader group shaders -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_ray_tracing_pipeline VK_KHR_ray_tracing_pipeline>, -- 'getRayTracingShaderGroupStackSizeKHR' newtype ShaderGroupShaderKHR = ShaderGroupShaderKHR Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'SHADER_GROUP_SHADER_GENERAL_KHR' uses the shader specified in the group -- with 'RayTracingShaderGroupCreateInfoKHR'::@generalShader@ pattern SHADER_GROUP_SHADER_GENERAL_KHR = ShaderGroupShaderKHR 0 -- | 'SHADER_GROUP_SHADER_CLOSEST_HIT_KHR' uses the shader specified in the -- group with 'RayTracingShaderGroupCreateInfoKHR'::@closestHitShader@ pattern SHADER_GROUP_SHADER_CLOSEST_HIT_KHR = ShaderGroupShaderKHR 1 -- | 'SHADER_GROUP_SHADER_ANY_HIT_KHR' uses the shader specified in the group -- with 'RayTracingShaderGroupCreateInfoKHR'::@anyHitShader@ pattern SHADER_GROUP_SHADER_ANY_HIT_KHR = ShaderGroupShaderKHR 2 -- | 'SHADER_GROUP_SHADER_INTERSECTION_KHR' uses the shader specified in the -- group with 'RayTracingShaderGroupCreateInfoKHR'::@intersectionShader@ pattern SHADER_GROUP_SHADER_INTERSECTION_KHR = ShaderGroupShaderKHR 3 {-# complete SHADER_GROUP_SHADER_GENERAL_KHR, SHADER_GROUP_SHADER_CLOSEST_HIT_KHR, SHADER_GROUP_SHADER_ANY_HIT_KHR, SHADER_GROUP_SHADER_INTERSECTION_KHR :: ShaderGroupShaderKHR #-} conNameShaderGroupShaderKHR :: String conNameShaderGroupShaderKHR = "ShaderGroupShaderKHR" enumPrefixShaderGroupShaderKHR :: String enumPrefixShaderGroupShaderKHR = "SHADER_GROUP_SHADER_" showTableShaderGroupShaderKHR :: [(ShaderGroupShaderKHR, String)] showTableShaderGroupShaderKHR = [ (SHADER_GROUP_SHADER_GENERAL_KHR , "GENERAL_KHR") , (SHADER_GROUP_SHADER_CLOSEST_HIT_KHR , "CLOSEST_HIT_KHR") , (SHADER_GROUP_SHADER_ANY_HIT_KHR , "ANY_HIT_KHR") , (SHADER_GROUP_SHADER_INTERSECTION_KHR, "INTERSECTION_KHR") ] instance Show ShaderGroupShaderKHR where showsPrec = enumShowsPrec enumPrefixShaderGroupShaderKHR showTableShaderGroupShaderKHR conNameShaderGroupShaderKHR (\(ShaderGroupShaderKHR x) -> x) (showsPrec 11) instance Read ShaderGroupShaderKHR where readPrec = enumReadPrec enumPrefixShaderGroupShaderKHR showTableShaderGroupShaderKHR conNameShaderGroupShaderKHR ShaderGroupShaderKHR type KHR_RAY_TRACING_PIPELINE_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_KHR_RAY_TRACING_PIPELINE_SPEC_VERSION" pattern KHR_RAY_TRACING_PIPELINE_SPEC_VERSION :: forall a . Integral a => a pattern KHR_RAY_TRACING_PIPELINE_SPEC_VERSION = 1 type KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME = "VK_KHR_ray_tracing_pipeline" -- No documentation found for TopLevel "VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME" pattern KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME = "VK_KHR_ray_tracing_pipeline"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_KHR_ray_tracing_pipeline.hs
Haskell
bsd-3-clause
195,430
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} -- https://github.com/Gabriel439/post-rfc/blob/master/sotu.md#scripting--command-line-applications module Lib ( someFunc ) where import qualified Data.ByteString.Char8 as BS import qualified Data.Text as Text import Data.Yaml (FromJSON) import qualified Data.Yaml as Yaml import GHC.Generics (Generic) import Turtle (shell, (<>)) import qualified Turtle as T data Build = Build { language :: String , install :: [T.Text] , blurb :: Maybe String} deriving (Show, Generic, FromJSON) getYaml :: FilePath -> IO BS.ByteString getYaml = BS.readFile runCmd :: T.Text -> IO () runCmd cmd = do print ("Running: " <> cmd) res <- shell cmd T.empty case res of T.ExitSuccess -> return () T.ExitFailure n -> T.die ("Shell cmd: " <> cmd <> " failed with code: " <> T.repr n) runCmds cmds = T.sh $ do res <- T.select cmds T.liftIO (runCmd res) someFunc :: IO () someFunc = do d <- Yaml.decodeEither <$> getYaml "build.yml" case d of Left err -> T.die $ Text.pack err Right ps -> runCmds (install ps)
minimal/build-lib
src/Lib.hs
Haskell
bsd-3-clause
1,322
{-# LANGUAGE CPP #-} {-# LANGUAGE EmptyDataDecls, MultiParamTypeClasses, FunctionalDependencies, Rank2Types, DeriveDataTypeable, FlexibleInstances, UndecidableInstances, FlexibleContexts,ScopedTypeVariables, TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Data.TypeLevel.Bool -- Copyright : (c) 2008 Benedikt Huber (port to Associative types (ghc 6.9+)) -- (c) 2008 Alfonso Acosta, Oleg Kiselyov, Wolfgang Jeltsch -- and KTH's SAM group -- License : BSD-style (see the file LICENSE) -- -- Maintainer : alfonso.acosta@gmail.com -- Stability : experimental (MPTC, non-standarad instances) -- Portability : non-portable -- -- Type-level Booleans. -- ---------------------------------------------------------------------------- module Data.TypeLevel.Bool ( -- * Type-level boolean values -- Bool, toBool, False, false, True, true, -- reifyBool, -- * Type-level boolean operations Not, And, Or -- Not, not, -- And, (&&), -- Or, (||), -- Xor, xor, -- Impl, imp, ) where import Data.Generics (Typeable) import Prelude hiding (Bool, not, (&&), (||), Eq) import qualified Prelude as P ------------------------------------ -- Definition of type-level Booleans ------------------------------------ -- | True type-level value data True deriving Typeable instance Show True where show _ = "True" -- | True value-level reflecting function true :: True true = undefined -- | False type-level value data False deriving Typeable instance Show False where show _ = "False" -- | False value-level reflecting function false :: False false = undefined type family And b_0 b_1 type instance And True True = True type instance And True False = False type instance And False True = False type instance And False False = False type family Or b_0 b_1 type instance Or True True = True type instance Or True False = True type instance Or False True = True type instance Or False False = False type family Not b type instance Not True = False type instance Not False = True #if 0 type family Id b type family Const a b type instance Id a = a type instance Const b a = b -- | Booleans, internal version class BoolI b where toBool :: b -> P.Bool type Not b type And b :: * -> * type Or b :: * -> * type Xor b :: * -> * type Impl b :: * -> * type BoolEq b :: * -> * -- To prevent the user from adding new instances to BoolI we do NOT export -- BoolI itself. Rather, we export the following proxy (Bool). -- The proxy entails BoolI and so can be used to add BoolI -- constraints in the signatures. However, all the constraints below -- are expressed in terms of BoolI rather than the proxy. Thus, even if the -- user adds new instances to the proxy, it would not matter. -- Besides, because the following proxy instances are most general, -- one may not add further instances without the overlapping instances -- extension. -- | Type-level Booleans class BoolI b => Bool b instance BoolI b => Bool b instance BoolI True where toBool _ = True type Not True = False type And True = Id type Or True = Const True type Xor True = Not type Impl True = Id type BoolEq True = Id instance BoolI False where toBool _ = False type Not False = True type And False = Const False type Or False = Id type Xor False = Id type Impl False = Const True type BoolEq False = Not -- | Reification function. In CPS style (best possible solution) reifyBool :: P.Bool -> (forall b . Bool b => b -> r) -> r reifyBool True f = f true reifyBool False f = f false ------------- -- Operations ------------- -- | value-level reflection function for the 'Not' type-level relation not :: b1 -> Not b1 not = undefined -- | 'And' type-level relation. @And b1 b2 b3@ establishes that -- @b1 && b2 = b3@ -- | value-level reflection function for the 'And' type-level relation (&&) :: b1 -> b2 -> And b1 b2 (&&) = undefined infixr 3 && -- | Or type-level relation. @Or b1 b2 b3@ establishes that -- @b1 || b2 = b3@ -- | value-level reflection function for the 'Or' type-level relation (||) :: b1 -> b2 -> Or b1 b2 (||) = undefined infixr 2 || -- | Exclusive or type-level relation. @Xor b1 b2 b3@ establishes that -- @xor b1 b2 = b3@ -- | value-level reflection function for the 'Xor' type-level relation xor :: b1 -> b2 -> Xor b1 b2 xor = undefined -- | Implication type-level relation. @Imp b1 b2 b3@ establishes that -- @b1 =>b2 = b3@ -- | value-level reflection function for the Imp type-level relation imp :: b1 -> b2 -> Impl b1 b2 imp = undefined -- Although equality can be defined as the composition of Xor and Not -- we define it specifically -- | Boolean equality type-level relation -- FIXME: eq should be named (==) but it clashes with the (==) defined -- in Data.TypeLevel.Num . The chosen (and ugly) workaround was -- to rename it to eq. -- | value-level reflection function for the 'Eq' type-level relation boolEq :: b1 -> b2 -> BoolEq b1 b2 boolEq = undefined #endif
coreyoconnor/type-level-tf
src/Data/TypeLevel/Bool.hs
Haskell
bsd-3-clause
5,146
-- | All the solutions of the 4-queens puzzle. module Example.Monad.Queens4All ( run ) where import Control.Applicative import Control.Monad ( join ) import Data.Maybe import qualified Data.Traversable as T import Z3.Monad run :: IO () run = do sols <- evalZ3With Nothing opts script putStrLn "Solutions: " mapM_ print sols where opts = opt "MODEL" True +? opt "MODEL_COMPLETION" True type Solution = [Integer] getSolutions :: AST -> AST -> AST -> AST -> Z3 [Solution] getSolutions q1 q2 q3 q4 = go [] where go acc = do mb_sol <- getSolution case mb_sol of Nothing -> return acc Just sol -> do restrictSolution sol go (sol:acc) restrictSolution :: Solution -> Z3 () restrictSolution [c1,c2,c3,c4] = assert =<< mkNot =<< mkOr =<< T.sequence [ mkEq q1 =<< mkIntNum c1 , mkEq q2 =<< mkIntNum c2 , mkEq q3 =<< mkIntNum c3 , mkEq q4 =<< mkIntNum c4 ] restrictSolution _____________ = error "invalid argument" getSolution :: Z3 (Maybe Solution) getSolution = fmap snd $ withModel $ \m -> catMaybes <$> mapM (evalInt m) [q1,q2,q3,q4] script :: Z3 [Solution] script = do q1 <- mkFreshIntVar "q1" q2 <- mkFreshIntVar "q2" q3 <- mkFreshIntVar "q3" q4 <- mkFreshIntVar "q4" _1 <- mkIntNum (1::Integer) _4 <- mkIntNum (4::Integer) -- the ith-queen is in the ith-row. -- qi is the column of the ith-queen assert =<< mkAnd =<< T.sequence [ mkLe _1 q1, mkLe q1 _4 -- 1 <= q1 <= 4 , mkLe _1 q2, mkLe q2 _4 , mkLe _1 q3, mkLe q3 _4 , mkLe _1 q4, mkLe q4 _4 ] -- different columns assert =<< mkDistinct [q1,q2,q3,q4] -- avoid diagonal attacks assert =<< mkNot =<< mkOr =<< T.sequence [ diagonal 1 q1 q2 -- diagonal line of attack between q1 and q2 , diagonal 2 q1 q3 , diagonal 3 q1 q4 , diagonal 1 q2 q3 , diagonal 2 q2 q4 , diagonal 1 q3 q4 ] getSolutions q1 q2 q3 q4 where mkAbs :: AST -> Z3 AST mkAbs x = do _0 <- mkIntNum (0::Integer) join $ mkIte <$> mkLe _0 x <*> pure x <*> mkUnaryMinus x diagonal :: Integer -> AST -> AST -> Z3 AST diagonal d c c' = join $ mkEq <$> (mkAbs =<< mkSub [c',c]) <*> (mkIntNum d)
sukwon0709/z3-haskell
examples/Example/Monad/Queens4All.hs
Haskell
bsd-3-clause
2,355
{-# LANGUAGE PackageImports #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE UnicodeSyntax #-} module Test.Complexity.Pretty (prettyStats, printStats) where import "base-unicode-symbols" Data.Function.Unicode ( (∘) ) import qualified "vector" Data.Vector as V import "this" Test.Complexity.Types ( MeasurementStats(..), Sample ) import "pretty" Text.PrettyPrint import "base" Text.Printf ( printf ) prettyStats ∷ MeasurementStats → Doc prettyStats (MeasurementStats {..}) = text "desc:" <+> text msDesc $+$ text "" $+$ vcat (map ppSample msSamples) where ppSample ∷ Sample → Doc ppSample (x, y) = (text ∘ printf "%3i") x <+> char '|' <+> ppStats y ppStats (Stats {..}) = int (V.length statsSamples) <+> hsep (map (text ∘ printf "%13.9f") [statsMin, statsMean2, statsMax, statsStdDev] ) printStats ∷ [MeasurementStats] → IO () printStats = mapM_ (\s → do putStrLn ∘ render ∘ prettyStats $ s putStrLn "" )
roelvandijk/complexity
Test/Complexity/Pretty.hs
Haskell
bsd-3-clause
1,204
{-# LANGUAGE ViewPatterns, GADTs, FlexibleContexts, DataKinds #-} module Sprite.GUI where import Graphics.UI.Gtk.OpenGL import Graphics.UI.Gtk hiding (Point, Object) import Graphics.Rendering.OpenGL import Control.Concurrent.STM import Control.Monad.Trans import Data.List.PointedList import Sprite.Widget (graphing) import Sprite.Logic import Sprite.GL import Sprite.D2 run :: (Point -> a -> STM a) -> (ScrollDirection -> Point -> a -> STM a) -> (a -> IO ()) -> RenderSocket IO Input -> RenderSocket IO Output -> TVar (PointedList (Graph a)) -> IO () run setx scrollx renderx renderSI renderSO ref = do initGUI bootGL window <- windowNew onDestroy window mainQuit set window [ containerBorderWidth := 8, windowTitle := "tracks widget" ] hb <- hBoxNew False 1 connects <- graphing setx scrollx renderx renderSI renderSO ref set window [containerChild := connects] widgetShowAll window dat <- widgetGetDrawWindow $ window cursorNew Tcross >>= drawWindowSetCursor dat . Just mainGUI
paolino/sprites
Sprite/GUI.hs
Haskell
bsd-3-clause
1,071
module Rules.Libffi (libffiRules, libffiDependencies) where import Base import Expression import GHC import Oracles import Rules.Actions import Settings.Builders.Common import Settings.Packages.Rts import Settings.TargetDirectory import Settings.User rtsBuildPath :: FilePath rtsBuildPath = targetPath Stage1 rts -/- "build" libffiDependencies :: [FilePath] libffiDependencies = (rtsBuildPath -/-) <$> [ "ffi.h", "ffitarget.h" ] libffiBuild :: FilePath libffiBuild = "libffi/build" libffiLibrary :: FilePath libffiLibrary = libffiBuild -/- "inst/lib/libffi.a" libffiMakefile :: FilePath libffiMakefile = libffiBuild -/- "Makefile.in" fixLibffiMakefile :: String -> String fixLibffiMakefile = unlines . map ( replace "-MD" "-MMD" . replace "@toolexeclibdir@" "$(libdir)" . replace "@INSTALL@" "$(subst ../install-sh,C:/msys/home/chEEtah/ghc/install-sh,@INSTALL@)" ) . lines target :: PartialTarget target = PartialTarget Stage0 libffi -- TODO: remove code duplication (see Settings/Builders/GhcCabal.hs) configureEnvironment :: Action [CmdOption] configureEnvironment = do cFlags <- interpretPartial target . fromDiffExpr $ mconcat [ cArgs , argStagedSettingList ConfCcArgs ] ldFlags <- interpretPartial target $ fromDiffExpr ldArgs sequence [ builderEnv "CC" $ Gcc Stage1 , builderEnv "CXX" $ Gcc Stage1 , builderEnv "LD" Ld , builderEnv "AR" Ar , builderEnv "NM" Nm , builderEnv "RANLIB" Ranlib , return . AddEnv "CFLAGS" $ unwords cFlags ++ " -w" , return . AddEnv "LDFLAGS" $ unwords ldFlags ++ " -w" ] where builderEnv var builder = do needBuilder False builder path <- builderPath builder return $ AddEnv var path configureArguments :: Action [String] configureArguments = do top <- topDirectory targetPlatform <- setting TargetPlatform return [ "--prefix=" ++ top ++ "/libffi/build/inst" , "--libdir=" ++ top ++ "/libffi/build/inst/lib" , "--enable-static=yes" , "--enable-shared=no" -- TODO: add support for yes , "--host=" ++ targetPlatform ] libffiRules :: Rules () libffiRules = do libffiDependencies &%> \_ -> do when trackBuildSystem $ need [sourcePath -/- "Rules/Libffi.hs"] liftIO $ removeFiles libffiBuild ["//*"] tarballs <- getDirectoryFiles "" ["libffi-tarballs/libffi*.tar.gz"] when (length tarballs /= 1) $ putError $ "libffiRules: exactly one libffi tarball expected" ++ "(found: " ++ show tarballs ++ ")." need tarballs build $ fullTarget target Tar tarballs ["libffi-tarballs"] let libname = dropExtension . dropExtension . takeFileName $ head tarballs moveDirectory ("libffi-tarballs" -/- libname) libffiBuild fixFile libffiMakefile fixLibffiMakefile forM_ ["config.guess", "config.sub"] $ \file -> copyFile file (libffiBuild -/- file) envs <- configureEnvironment args <- configureArguments runConfigure libffiBuild envs args runMake libffiBuild ["MAKEFLAGS="] runMake libffiBuild ["MAKEFLAGS=", "install"] forM_ ["ffi.h", "ffitarget.h"] $ \file -> do let src = libffiBuild -/- "inst/lib" -/- libname -/- "include" -/- file copyFile src (rtsBuildPath -/- file) libffiName <- rtsLibffiLibraryName copyFile libffiLibrary (rtsBuildPath -/- "lib" ++ libffiName <.> "a") putSuccess $ "| Successfully built custom library 'libffi'" -- chmod +x libffi/ln -- # wc on OS X has spaces in its output, which libffi's Makefile -- # doesn't expect, so we tweak it to sed them out -- mv libffi/build/Makefile libffi/build/Makefile.orig -- sed "s#wc -w#wc -w | sed 's/ //g'#" < libffi/build/Makefile.orig > libffi/build/Makefile
quchen/shaking-up-ghc
src/Rules/Libffi.hs
Haskell
bsd-3-clause
3,933
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.KO.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale KO Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "0" , "영" , "빵" , "공" ] , examples (NumeralValue 1) [ "1" , "일" , "하나" , "한" ] , examples (NumeralValue 10) [ "10" , "십" , "열" ] , examples (NumeralValue 11) [ "11" , "십일" , "열하나" , "십하나" , "열한" ] , examples (NumeralValue 20) [ "20" , "이십" , "스물" ] , examples (NumeralValue 35) [ "35" , "삼십오" , "서른다섯" ] , examples (NumeralValue 47) [ "47" , "사십칠" , "마흔일곱" ] , examples (NumeralValue 52) [ "52" , "오십이" , "쉰둘" , "쉰두" ] , examples (NumeralValue 69) [ "69" , "육십구" , "예순아홉" ] , examples (NumeralValue 71) [ "71" , "칠십일" , "일흔하나" , "일흔한" ] , examples (NumeralValue 84) [ "84" , "팔십사" , "여든넷" ] , examples (NumeralValue 93) [ "93" , "구십삼" , "아흔셋" ] , examples (NumeralValue 100) [ "100" , "백" ] , examples (NumeralValue 123) [ "123" , "백이십삼" ] , examples (NumeralValue 579) [ "579" , "오백칠십구" ] , examples (NumeralValue 1000) [ "1000" , "천" ] , examples (NumeralValue 1723) [ "1723" , "천칠백이십삼" ] , examples (NumeralValue 5619) [ "5619" , "오천육백십구" ] , examples (NumeralValue 10000) [ "10000" , "만" , "일만" ] , examples (NumeralValue 12345) [ "12345" , "만이천삼백사십오" , "일만이천삼백사십오" ] , examples (NumeralValue 58194) [ "58194" , "오만팔천백구십사" ] , examples (NumeralValue 581900) [ "581900" , "오십팔만천구백" ] , examples (NumeralValue 5819014) [ "5819014" , "오백팔십일만구천십사" ] , examples (NumeralValue 58190148) [ "58190148" , "오천팔백십구만백사십팔" ] , examples (NumeralValue 100000000) [ "100000000" , "일억" ] , examples (NumeralValue 274500000000) [ "274500000000" , "이천칠백사십오억" ] , examples (NumeralValue 100000002) [ "100000002" , "일억이" ] , examples (NumeralValue 27350000) [ "27350000" , "이천칠백삼십오만" ] , examples (NumeralValue 3235698120) [ "3235698120" , "삼십이억삼천오백육십구만팔천백이십" ] , examples (NumeralValue 40234985729) [ "40234985729" , "사백이억삼천사백구십팔만오천칠백이십구" ] , examples (NumeralValue 701239801123) [ "701239801123" , "칠천십이억삼천구백팔십만천백이십삼" ] , examples (NumeralValue 3.4) [ "3.4" , "삼점사" ] , examples (NumeralValue 4123.3) [ "4123.3" , "사천백이십삼점삼" ] , examples (NumeralValue 1.23) [ "일점이삼" ] , examples (NumeralValue (-3)) [ "-3" , "마이너스3" , "마이너스삼" , "마이너스 3" , "마이나스3" , "마이나스 3" ] , examples (NumeralValue 0.75) [ "3/4" , "사분의삼" ] ]
facebookincubator/duckling
Duckling/Numeral/KO/Corpus.hs
Haskell
bsd-3-clause
5,023
-- | Yesod.Test.Json provides convenience functions for working -- with Test.Hspec and Network.Wai.Test on JSON data. module Yesod.Test.Json ( testApp, APIFunction, assertBool, assertString, assertOK, assertJSON, Session(..), H.Assertion, module Test.Hspec, module Data.Aeson, SResponse(..) ) where import qualified Test.HUnit as H import qualified Data.ByteString.Lazy.Char8 as L8 import qualified Data.ByteString.Lazy as L import Data.ByteString (ByteString) import Data.Text (Text) import Data.Aeson import Network.HTTP.Types import Test.Hspec import Network.Wai import Network.Wai.Test import Control.Monad.IO.Class import Yesod.Default.Config import Data.Conduit.List -- | A request to your server. type APIFunction = ByteString -- ^ method -> [Text] -- ^ path -> Maybe Value -- JSON data -> Session SResponse -- Assert a boolean value assertBool :: String -> Bool -> Session () assertBool s b = liftIO $ H.assertBool s b -- Fail a test with an error string assertString :: String -> Session () assertString = liftIO . H.assertString -- Assert a 200 response code assertOK :: SResponse -> Session () assertOK SResponse{simpleStatus = s, simpleBody = b} = assertBool (concat [ "Expected status code 200, but received " , show sc , ". Response body: " , show (L8.unpack b) ]) $ sc == 200 where sc = statusCode s -- Assert a JSON body meeting some requirement assertJSON :: (ToJSON a, FromJSON a) => (a -> (String, Bool)) -> SResponse -> Session () assertJSON f SResponse{simpleBody = lbs} = do case decode lbs of Nothing -> assertString $ "Invalid JSON: " ++ show (L8.unpack lbs) Just a -> case fromJSON a of Error s -> assertString (concat [s, "\nInput JSON: ", show a]) Success x -> uncurry assertBool (f x) -- | Make a request to your server apiRequest :: AppConfig env extra -> APIFunction apiRequest conf m p x = srequest $ SRequest r (maybe L.empty encode x) where r = defaultRequest { serverPort = appPort conf, requestBody = sourceList . L.toChunks $ encode x, requestMethod = m, pathInfo = p } -- | Run a test suite for your 'Application' testApp :: Application -> AppConfig env extra -> (((APIFunction -> Session ()) -> H.Assertion) -> Spec) -> IO () testApp app conf specfun = do let apiTest f = runSession (f (apiRequest conf)) app hspec $ (specfun apiTest)
bogiebro/yesod-test-json
Yesod/Test/Json.hs
Haskell
bsd-3-clause
2,449
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} module Plots.Axis.Labels where import Control.Lens hiding (( # )) import Data.Default import Data.Data import Numeric import Diagrams.Prelude hiding (view) import Diagrams.TwoD.Text import Data.Monoid.Recommend ------------------------------------------------------------------------ -- Axis labels ------------------------------------------------------------------------ -- Labels for the axis. Pretty basic right now. data AxisLabelPosition = MiddleAxisLabel | LowerAxisLabel | UpperAxisLabel data AxisLabelPlacement = InsideAxisLabel | OutsideAxisLabel -- | Function to render the axis label from a string. This is very basic -- now and will be replace by a more sophisticated system. type AxisLabelFunction b v n = TextAlignment n -> String -> QDiagram b v n Any data AxisLabel b v n = AxisLabel { _axisLabelFunction :: AxisLabelFunction b v n , _axisLabelText :: String , _axisLabelStyle :: Style v n , _axisLabelGap :: n , _axisLabelPos :: AxisLabelPosition , _axisLabelPlacement :: AxisLabelPlacement } makeLenses ''AxisLabel instance (TypeableFloat n, Renderable (Text n) b) => Default (AxisLabel b V2 n) where def = AxisLabel { _axisLabelFunction = mkText' , _axisLabelText = "" , _axisLabelStyle = mempty & recommendFontSize (output 8) , _axisLabelGap = 20 , _axisLabelPos = MiddleAxisLabel , _axisLabelPlacement = OutsideAxisLabel } type AxisLabels b v n = v (AxisLabel b v n) ------------------------------------------------------------------------ -- Tick labels ------------------------------------------------------------------------ -- Labels that are placed next to the ticks (usually) of an axis. -- | Tick labels functions are used to draw the tick labels. They has access to -- the major ticks and the current bounds. Returns the position of the -- tick and label to use at that position. type TickLabelFunction b v n = [n] -> (n,n) -> TextAlignment n -> [(n, QDiagram b v n Any)] data TickLabels b v n = TickLabels { _tickLabelFunction :: TickLabelFunction b v n , _tickLabelStyle :: Style v n , _tickGap :: n } deriving Typeable makeLenses ''TickLabels type AxisTickLabels b v n = v (TickLabels b v n) instance (TypeableFloat n, Renderable (Text n) b) => Default (TickLabels b V2 n) where def = TickLabels { _tickLabelFunction = atMajorTicks label , _tickLabelStyle = mempty & recommendFontSize (output 8) , _tickGap = 8 } -- | Make a 'TickLabelFunction' by specifying how to draw a single label -- from a position on the axis. atMajorTicks :: (TextAlignment n -> n -> QDiagram b v n Any) -> TickLabelFunction b v n atMajorTicks f ticks _ a = map ((,) <*> f a) ticks -- | Standard way to render a label by using 'Text'. label :: (TypeableFloat n, Renderable (Text n) b) => TextAlignment n -> n -> QDiagram b V2 n Any label a n = mkText' a $ showFFloat (Just 2) n "" leftLabel :: (TypeableFloat n, Renderable (Text n) b) => n -> QDiagram b V2 n Any leftLabel n = alignedText 1 0.5 (showFFloat (Just 2) n "") -- | Use the list of strings as the labels for the axis, starting at 0 -- and going to 1, 2, 3 ... stringLabels :: Num n => (TextAlignment n -> String -> QDiagram b v n Any) -> [String] -> TickLabelFunction b v n stringLabels f ls _ _ a = imap (\i l -> (fromIntegral i, f a l)) ls -- -- horrible name -- labelFunctionFromTicks :: (Double -> Diagram b R2) -> TickFunction -> LabelFunction b -- labelFunctionFromTickFunction f aF bounds = map ((,) <*> f) (aF bounds)
AjayRamanathan/plots
src/Plots/Axis/Labels.hs
Haskell
bsd-3-clause
3,989
module Rules.Generators.GhcVersionH (generateGhcVersionH) where import Base import Expression import Oracles import Settings.User generateGhcVersionH :: Expr String generateGhcVersionH = do when trackBuildSystem . lift $ need [sourcePath -/- "Rules/Generators/GhcVersionH.hs"] version <- getSetting ProjectVersionInt patchLevel1 <- getSetting ProjectPatchLevel1 patchLevel2 <- getSetting ProjectPatchLevel2 return . unlines $ [ "#ifndef __GHCVERSION_H__" , "#define __GHCVERSION_H__" , "" , "#ifndef __GLASGOW_HASKELL__" , "# define __GLASGOW_HASKELL__ " ++ version , "#endif" , ""] ++ [ "#define __GLASGOW_HASKELL_PATCHLEVEL1__ " ++ patchLevel1 | patchLevel1 /= "" ] ++ [ "#define __GLASGOW_HASKELL_PATCHLEVEL2__ " ++ patchLevel2 | patchLevel2 /= "" ] ++ [ "" , "#define MIN_VERSION_GLASGOW_HASKELL(ma,mi,pl1,pl2) (\\" , " ((ma)*100+(mi)) < __GLASGOW_HASKELL__ || \\" , " ((ma)*100+(mi)) == __GLASGOW_HASKELL__ \\" , " && (pl1) < __GLASGOW_HASKELL_PATCHLEVEL1__ || \\" , " ((ma)*100+(mi)) == __GLASGOW_HASKELL__ \\" , " && (pl1) == __GLASGOW_HASKELL_PATCHLEVEL1__ \\" , " && (pl2) <= __GLASGOW_HASKELL_PATCHLEVEL2__ )" , "" , "#endif /* __GHCVERSION_H__ */" ]
quchen/shaking-up-ghc
src/Rules/Generators/GhcVersionH.hs
Haskell
bsd-3-clause
1,412
{-# LANGUAGE DeriveDataTypeable, RecordWildCards , OverloadedStrings, StandaloneDeriving , ScopedTypeVariables, CPP #-} module Database where import Data.Typeable import Data.TCache.IndexQuery import Data.TCache.DefaultPersistence import Data.TCache.AWS import Data.Monoid import qualified Data.Text as T import Data.String import Data.ByteString.Lazy.Char8 hiding (index) -- #define ALONE -- to execute it alone, uncomment this #ifdef ALONE import MFlow.Wai.Blaze.Html.All main= do syncWrite $ Asyncronous 120 defaultCheck 1000 index idnumber runNavigation "" $ transientNav grid #else import MFlow.Wai.Blaze.Html.All hiding(select, page) import Menu #endif -- to run it alone, remove Menu.hs and uncomment this: --askm= ask -- --main= do -- syncWrite $ Asyncronous 120 defaultCheck 1000 -- index idnumber -- runNavigation "" $ step database data MyData= MyData{idnumber :: Int, textdata :: T.Text} deriving (Typeable, Read, Show) -- that is enough for file persistence instance Indexable MyData where key= show . idnumber -- the key of the register domain= "mflowdemo" instance Serializable MyData where serialize= pack . show deserialize= read . unpack setPersist = const . Just $ amazonS3Persist domain -- False data Options= NewText | Exit deriving (Show, Typeable) database= do liftIO $ index idnumber database' database'= do all <- allTexts r <- page $ listtexts all case r of NewText -> do text <- page $ p "Insert the text" ++> htmlEdit ["bold","italic"] "" -- rich text editor with bold and italic buttons (getMultilineText "" <! [("rows","3"),("cols","80")]) <++ br <** submitButton "enter" addtext all text -- store the name in the cache (later will be written to disk automatically) database' Exit -> return () where menu= wlink NewText << p "enter a new text" <|> wlink Exit << p "exit to the home page" listtexts all = do h3 "list of all texts" ++> mconcat[p $ preEscapedToHtml t >> hr | t <- all] ++> menu <++ b "or press the back button or enter the URL any other page in the web site" addtext all text= liftIO . atomically . newDBRef $ MyData (Prelude.length all) text allTexts= liftIO . atomically . select textdata $ idnumber .>=. (0 :: Int)
agocorona/MFlow
Demos/Database.hs
Haskell
bsd-3-clause
2,521
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Network.Sock.Handler.Common where ------------------------------------------------------------------------------ import Control.Concurrent.MVar.Lifted import Control.Concurrent.STM import Control.Concurrent.STM.TMChan import Control.Concurrent.STM.TMChan.Extra import Control.Monad import Control.Monad.Trans (MonadIO, liftIO, lift) import Control.Monad.Trans.Resource.Extra as R ------------------------------------------------------------------------------ import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as BS import qualified Data.Conduit as C import Data.Proxy import Data.Int (Int64) ------------------------------------------------------------------------------ import qualified Network.HTTP.Types as H (Status) import qualified Network.HTTP.Types.Request as H import qualified Network.HTTP.Types.Response as H import qualified Network.HTTP.Types.Extra as H ------------------------------------------------------------------------------ import qualified Blaze.ByteString.Builder as B ------------------------------------------------------------------------------ import Network.Sock.Frame import Network.Sock.Request import Network.Sock.Session import Network.Sock.Types.Protocol import Network.Sock.Types.Handler ------------------------------------------------------------------------------ -- | Ideally we would C.register putMvar and put different value there depending on context, -- but currently registert does not support registering function of the form (a -> IO ()), but it should be -- quite an easy fix. -- | The default Source for polling transports. pollingSource :: Handler tag => Proxy tag -- ^ Handler tag. -> Request -- ^ Request we are responsing to. -> Session -- ^ Associated session. -> C.Source (C.ResourceT IO) (C.Flush B.Builder) pollingSource tag req ses = do status <- tryTakeMVar $! sessionStatus ses case status of Just (SessionFresh) -> addCleanup ses $ \key -> initialize >> yieldAndFlush (format' FrameOpen) >> releaseOpened key Just (SessionOpened) -> addCleanup ses $ \key -> liftSTM (getTMChanContents $ sessionOutgoingBuffer ses) >>= loop key id Just (SessionClosed code reason) -> addCleanup ses $ \key -> yieldAndFlush (format' $ FrameClose code reason) >> releaseClosed key Nothing -> yieldAndFlush $ format' $ FrameClose 2010 "Another connection still open" where loop key front [] = yieldAndFlush (format' $ FrameMessages $ front []) >> releaseOpened key loop key front (x:xs) = case x of Message s -> loop key (front . (s:)) xs Raw s -> yieldAndFlush s >> releaseOpened key Control Close -> do -- yieldAndFlush (format' $ FrameMessages $ front []) -- ^ We mimic the way sockjs-node behaves. yieldAndFlush (format' $ FrameClose 3000 "Go away!") finalize >> releaseClosed key format' = format tag req initialize = lift $! initializeSession ses $! requestApplication req finalize = lift $! finalizeSession ses {-# INLINE pollingSource #-} -- | The default Source for streaming transports. streamingSource :: Handler tag => Proxy tag -- ^ Handler tag. -> Request -- ^ Request we are responsing to. -> Int64 -- ^ Maximum amount of bytes to be transfered (we can exceed the maximum if the last message is long, but the loop will stop). -> C.Source (C.ResourceT IO) (C.Flush B.Builder) -- ^ Prelude sent before any other data. -> Session -- ^ Associated session. -> C.Source (C.ResourceT IO) (C.Flush B.Builder) streamingSource tag req limit prelude ses = do status <- tryTakeMVar $! sessionStatus ses case status of Just (SessionFresh) -> addCleanup ses $ \key -> initialize >> prelude >> yieldOpenFrame >> loop key 0 Just (SessionOpened) -> addCleanup ses $ \key -> prelude >> yieldOpenFrame >> loop key 0 Just (SessionClosed code reason) -> addCleanup ses $ \key -> prelude >> yieldAndFlush (format' $ FrameClose code reason) >> releaseClosed key Nothing -> prelude >> yieldAndFlush (format' $ FrameClose 2010 "Another connection still open") where loop key n = liftSTM (readTMChan $ sessionOutgoingBuffer ses) >>= maybe (return ()) (\x -> do case x of Message s -> do let load = format' (FrameMessages [s]) let newn = n + BL.length load yieldAndFlush load if newn < limit then loop key newn else releaseOpened key Raw s -> do let load = s let newn = n + BL.length load yieldAndFlush load if newn < limit then loop key newn else releaseOpened key Control Close -> do yieldAndFlush (format' $ FrameClose 3000 "Go away!") finalize >> releaseClosed key ) format' = format tag req initialize = lift $! initializeSession ses $! requestApplication req finalize = lift $! finalizeSession ses yieldOpenFrame = yieldAndFlush $ format' FrameOpen {-# INLINE streamingSource #-} ------------------------------------------------------------------------------ -- | Common utility functions addCleanup :: Session -> (ReleaseKeyF SessionStatus -> C.Source (C.ResourceT IO) (C.Flush B.Builder)) -> C.Source (C.ResourceT IO) (C.Flush B.Builder) addCleanup ses fsrc = do key <- registerPutStatus ses C.addCleanup (flip unless $! R.releaseF key $! SessionClosed 1002 "Connection interrupted") (fsrc key) registerPutStatus :: Session -> C.Pipe l i o u (C.ResourceT IO) (ReleaseKeyF SessionStatus) registerPutStatus ses = lift $! R.registerF (void . tryPutMVar (sessionStatus ses)) (SessionClosed 1002 "Connection interrupted") {-# INLINE registerPutStatus #-} releaseClosed :: ReleaseKeyF SessionStatus -> C.Pipe l i o u (C.ResourceT IO) () releaseClosed key = lift $! R.releaseF key $! SessionClosed 3000 "Go away!" {-# INLINE releaseClosed #-} releaseOpened :: ReleaseKeyF SessionStatus -> C.Pipe l i o u (C.ResourceT IO) () releaseOpened key = lift $! R.releaseF key $! SessionOpened {-# INLINE releaseOpened #-} liftSTM :: MonadIO m => STM a -> m a liftSTM = liftIO . atomically {-# INLINE liftSTM #-} ------------------------------------------------------------------------------ -- | Used as a response to http://example.com/<application_prefix>/<server_id>/<session_id>/<transport> -- -- Documentation: http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-7 -- TODO: Put somewhere else. responseOptions :: (H.IsResponse res, H.IsRequest req) => [BS.ByteString] -> req -> res responseOptions methods req = H.response204 headers "" where headers = [("Access-Control-Allow-Methods", BS.intercalate ", " methods)] ++ H.headerCached ++ H.headerCORS "*" req {-# INLINE responseOptions #-} respondSource :: (H.IsResponse res, Handler tag) => Proxy tag -> Request -> H.Status -> C.Source (C.ResourceT IO) (C.Flush B.Builder) -> res respondSource tag req status source = H.responseSource status (headers tag req) source {-# INLINE respondSource #-} respondFrame :: (H.IsResponse res, Handler tag) => Proxy tag -> Request -> H.Status -> Frame -> res respondFrame tag req st fr = respondLBS tag req st (format tag req fr) {-# INLINE respondFrame #-} respondLBS :: (H.IsResponse res, Handler tag) => Proxy tag -> Request -> H.Status -> BL.ByteString -> res respondLBS tag req status body = H.responseLBS status (headers tag req) body {-# INLINE respondLBS #-} -- | Yields a Chunk (a ByteString) and then Flushes. yieldAndFlush :: Monad m => BL.ByteString -> C.Pipe l i (C.Flush B.Builder) u m () yieldAndFlush load = C.yield (C.Chunk $ B.fromLazyByteString load) >> C.yield C.Flush {-# INLINE yieldAndFlush #-}
Palmik/wai-sockjs
src/Network/Sock/Handler/Common.hs
Haskell
bsd-3-clause
9,309
{-# LANGUAGE OverloadedStrings #-} module Definition where import qualified Data.Text as T import Language data Definition = Definition { word :: T.Text , sourceLang :: Language , definitionLang :: Language , partOfSpeechList :: [(T.Text, [T.Text])] } showPartOfSpeech :: (T.Text, [T.Text]) -> T.Text showPartOfSpeech (pos, ds) = T.concat [ pos , "\n" , T.intercalate "\n" ds , "\n" ] prettyPrintDefinition :: Definition -> T.Text prettyPrintDefinition def = let ps = partOfSpeechList def in T.concat [ "----------------------------\n" , word def , "\n\n" , T.concat $ map showPartOfSpeech ps , "----------------------------" ]
aupiff/def
src/Definition.hs
Haskell
bsd-3-clause
963
{-# LANGUAGE FlexibleContexts #-} module PeerTrader where import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.STM (atomically, dupTChan, readTChan, writeTChan) import Control.Exception (SomeException) import Control.Exception.Enclosed (catchAny) import Control.Monad.Reader import Data.Maybe (isNothing) import Data.Traversable as T import Database.Groundhog.Postgresql (runDbConn) import Logging import NoteScript import P2PPicks.Keys import P2PPicks.Types import Prosper import Prosper.Monad import PeerTrader.Account import PeerTrader.Investment.Database import PeerTrader.Ops import PeerTrader.P2PPicks.Account import PeerTrader.StrategyType import PeerTrader.Types (UserLogin) -- | Given 'Prosper' actions per 'Listing', read from the 'Listing' 'TChan' -- and automatically invest based upon those Listings. -- -- Write all 'InvestResponse' to the database processListings :: UserLogin -> StrategyType -> (Listing -> Prosper (Maybe (Async InvestResponse))) -> OpsReader (Maybe (ThreadId, ThreadId)) processListings n stratType s = getAccountVar n prosperChans >>= setUpChans where processingQueue AutoFilterStrategy = do ps <- asks _prosperState return $ prosperProcessingQueue ps processingQueue (P2PPicksStrategy ProfitMax) = asks _p2pProfitMaxResults processingQueue (P2PPicksStrategy LossMin) = asks _p2pLossMinResults setUpChans (Just (ProsperChans (Just pq) i r)) = initializeThreads pq i r setUpChans (Just (ProsperChans Nothing i r)) = do -- Duplicate the read listings TChan pq <- processingQueue stratType pq' <- (liftIO . atomically . dupTChan) pq putAccountVar n prosperChans $ ProsperChans (Just pq') i r initializeThreads pq' i r setUpChans Nothing = warningM (show n) "Could not retrieve Prosper Chans!" >> return Nothing initializeThreads pq is readInvests = do responseThread <- do app <- ask liftIO . forkIO . forever $ do investResp <- atomically $ readTChan readInvests runDbConn (insertResponse n stratType investResp) app strategyTypeResponse app stratType investResp scriptThread <- evalProsper . forkP . forever $ do ls <- liftIO . atomically $ readTChan pq forkP $ do mResp <- s ls maybe (return ()) (liftIO . atomically . writeTChan is <=< waitProsper) mResp return $ Just (scriptThread, responseThread) strategyTypeResponse app (P2PPicksStrategy p2pType) ir@(InvestResponse { investStatus = Success }) = flip runReaderT app $ do keys <- asks _p2ppicksKeys Just p2pacct <- runDbConn (getP2PPicksAccount n) app let lid = investListingId ir amt = requestedAmount ir sid = subscriberId p2pacct -- TODO Handle failed report to P2P Picks reportResult <- flip runReaderT keys $ reportInvestment sid p2pType lid amt debugM "P2PPicks" $ "Sending report to P2PPicks " ++ show reportResult strategyTypeResponse _ _ _ = return () -- | Interpret a NoteScript into Prosper commands startProsperScript :: UserLogin -> StrategyType -> ProsperScript (Maybe (Async InvestResponse)) -> OpsReader (Maybe (ThreadId, ThreadId)) startProsperScript n stratType pscript = do tid <- join <$> getAccountVar n prosperScriptThread ui <- getAccountVar n prosperUser -- Kill current NoteScript _ <- T.mapM (liftIO . (\(t1, t2) -> killThread t1 >> killThread t2)) tid case ui of Just i -> do let lg = show n debugM lg $ "Setting prosper script for user: " ++ show n newTid <- processListings n stratType (\l -> prosperScript i l pscript) when (isNothing newTid) $ warningM lg "Unable to set new thread..." putAccountVar n prosperScriptThread newTid return newTid _ -> warningM (show n) "Could not find prosper user." >> return Nothing -- | Kill the strategy thread. Stop automatically investing. killProsper :: UserLogin -> OpsReader () killProsper n = do tid <- join <$> getAccountVar n prosperScriptThread stateTid <- join <$> getAccountVar n prosperInvestThread _ <- T.mapM (liftIO . (\(t1, t2) -> killThread t1 >> killThread t2)) tid _ <- T.mapM (liftIO . killThread) stateTid putAccountVar n prosperScriptThread Nothing putAccountVar n (prosperChans.readListings) Nothing putAccountVar n prosperInvestThread Nothing putAccountVar n prosperInvestState Nothing initializeProsper' :: IO ProsperState initializeProsper' = do ps <- initializeProsper "prosper.cfg" _ <- runProsper ps updateAllListings -- Synchronize _ <- forkIO $ updateListingsLoop ps return ps where -- TODO Do something with the retry package here. Need to retry at a non-constant rate. updateListingsLoop :: ProsperState -> IO () updateListingsLoop ps = forever $ runProsper ps updateAllListings `catchAny` statusExceptionHandler statusExceptionHandler :: SomeException -> IO () statusExceptionHandler e = debugM "MarketData" $ "Caught some exception... " ++ show e ++ " Continuing..." -- | Initialize logs and initialize ProsperState -- -- ProsperState reads configuration from prosper.cfg. This involves initializing -- Listings poll thread initializePeerTrader :: MonadIO m => m ProsperState initializePeerTrader = liftIO $ do initializeLogs debugM "Prosper" "Initializing Prosper..." initializeProsper'
WraithM/peertrader-backend
src/PeerTrader.hs
Haskell
bsd-3-clause
5,958
module NAA.Loop (runNoughtsAndArrs) where import NAA.AI import NAA.Logic import NAA.State import NAA.Data hiding (player) import NAA.Interface import NAA.Interface.CLI import Control.Monad.Trans import Control.Monad.State.Lazy -- So not only do we need to keep running the GameState over IO but we probably -- want some scene state information. type NoughtsAndArrs a = StateT GameState IO a -- We start a game, loop as necessary, and end a game. -- The end of the game is handled by the loop! runNoughtsAndArrs :: UserInterface -> NoughtsAndArrs () runNoughtsAndArrs ui = do gs <- get liftIO $ onGameStart ui gs runGameLoop ui -- >> onGameEnd ui -- | Loop maintains the liftime of a single game. It carries out a game with -- they help of an Interface. -- -- 1) onRetrieveMove. This is a blocking call. It only returns when the player has -- chosen a move to make. It can be an invalid one, and no input validation -- is expected. -- It is the Interface's responsibility to show the game state in a way that -- a human being can make an informed decision about what -- move to take. It is also the Interface's responsibility to deal with the -- necessary IO to retrieve the move's coordinates. -- -- 2) onInvalidMove. This is a non-blocking call. This notifies the interface -- that the move given by onRetrieveMove was found to be not valid for the -- current GameState. This permits the error to be fed back to the player in -- some form. onRetrieveMove is invoked again. -- -- 3) onPlayerMove. This is a non-blocking call. This is invoked when a player -- has made a valid move, and is an opportunity for the Interface to update -- itself. -- -- 4) onGameEnd. This is a non-blocking call. This is invoked when the game has -- reached an end state: either draw, or win. -- runGameLoop :: UserInterface -> NoughtsAndArrs () runGameLoop ui = do -- Get the current game state and prompt the user to make a move ----------------------------------------------------------------- gs@GameState{human=plyr,computer=comp} <- get gs' <- withGameState gs $ \gs -> do let bs@(BoardState {turn=currentTurn}) = boardState gs let retrieveMove = if plyr == currentTurn then retrieveMoveFromPlayer plyr else unbeatableAI move <- retrieveMove gs -- obtain a move from the AI or player -- Compute the upated game state --------------------------------- let bs' = bs `apply` move let gs' = gs {boardState=bs'} onPlayerMove ui move gs' return gs' put gs' -- Here, we decide how to continue after the move has been made. -- If it yielded an end-game result then we will notify the interface -- Otherwise we continue looping, running the Noughts and Arrs game. ----------------------------------------------------------------- let BoardState {board=brd} = boardState gs' case judge brd of Just result -> liftIO $ onGameEnd ui gs' result -- when the game ends with result Nothing -> runGameLoop ui -- neither won or lost. Continue. where withGameState gs mf = liftIO (mf gs) retrieveMoveFromPlayer :: Player -> GameState -> IO Move retrieveMoveFromPlayer plyr gs = msum . repeat $ do m <- onRetrieveMove ui plyr gs validate m gs return m validate :: Move -> GameState -> IO (Idx2D) validate m (GameState {boardState=bs}) | m `isValidIn` bs = return $ snd m | otherwise = onInvalidMove ui m >> mzero
fatuhoku/haskell-noughts-and-crosses
src/NAA/Loop.hs
Haskell
bsd-3-clause
3,522
module Math.Misc.Permutation where import Math.Misc.Parity import Misc.Misc import Math.Algebra.Monoid -- | A permutation is represented as a pair of lists. The condition -- that the two lists contain precisely the same elements is /not -- checked/. type Permutation a = ([a], [a]) -- | Calculate the parity of a given permutation. The parity is 'Even' -- if the permutation can be decomposed into an even number of -- transpositions, and 'Odd' otherwise. parity :: (Eq a) => Permutation a -> Parity parity = go Even where go p (u, v) | u == v = p | otherwise = go (p <*> fromLength v1) (tail u, v1 ++ tail' v2) where pivot = head u (v1, v2) = break (== pivot) v
michiexile/hplex
pershom/src/Math/Misc/Permutation.hs
Haskell
bsd-3-clause
748
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-} module Himpress.Plumbing where import qualified Himpress.Format as F import Paths_himpress import System.INotify import System.FilePath (takeExtension) import Control.Concurrent (threadDelay) import Control.Arrow ((&&&),(***)) import Control.Monad (mapM_) import Prelude hiding (writeFile,readFile,putStrLn,getContents) import Data.Text.IO (readFile,getContents) import Data.Text.Lazy.IO (writeFile,putStrLn) import Data.Text (pack,Text) import System.Console.CmdArgs data Opts = Opts { size::(Int,Int) -- "window" size for calculating presentation coordinates , input::String -- Input file - defaults to stdin , output::String -- Output file - defaults to stdout , title::String -- Presentation title , include::String -- CSS and JS files to directly include in the presentation. -- CSS is placed in the head, JS as the last elements of the body. , link::String -- CSS and JS files to link to , watch::Bool -- If set, himpress watches the input file and includes using inotify, and recompiles on changes. , nodefault::Bool -- If set, doesn't include the default CSS and JS files. , bare::Bool -- If set, himpress will only generate the markup for slides, without a full document. } deriving (Show,Data,Typeable) opts = Opts { size = (1000,1000) &= help "Default size (in pixels) for each step" , input = "" &= typFile , output = "" &= typFile , title = "" &= help "Presentation title" , include = "" &= typ listType &= help "CSS and JS files to include in the presentation - path from current directory." , link = "" &= typ listType &= help "CSS and JS files to link to from the presentation" , bare = False &= help "Only generate markup for slides, and not the full document" , nodefault = False &= help "Don't include the default CSS and JS" , watch = False &= help "Recompile presentation on changes" } &= summary "himpress v1.0, (c) Matthew Sorensen 2012" listType="<space-separated list of paths>" --- Overall interface this file spits out: format::Opts->IO (IO F.Format) format o = fmap (dynamicOptions $ staticOptions o) $ includes o dependencies::Opts->[FilePath] dependencies o = if null $ input o then words $ include o else input o : words (include o) watchFiles::[FilePath]->IO () ->IO () watchFiles files act = withINotify $ \inot -> mapM_ (watch inot) files >> loop where watch inot f = addWatch inot [CloseWrite] f $ const act loop = threadDelay 1000000 >> loop -- The assumption is made that you're an idiot (read: "I'm lazy") if this tool is -- set up to watch a file that it potentially modifies. outputStream o | output o == "" = putStrLn | otherwise = writeFile $ output o inputStream::Opts->IO Text inputStream o = case (input o,watch o) of ("",True) -> error "An input file must be provided if --watch is used." ("",False)-> getContents (f,_) -> readFile f splitCssJs = (hasExt ".css" &&& hasExt ".js") . words where hasExt e = filter $ (e==) . takeExtension staticOptions o = let (css,js) = splitCssJs $ link o plinks = map $ F.Link . pack in F.Format { F.meta = [] , F.title = pack $ title o , F.bare = bare o , F.scripts = plinks js , F.style = plinks css } dynamicOptions::F.Format->([FilePath],[FilePath])->IO F.Format dynamicOptions base (css,js) = do css <- mapM readFile css js <- mapM readFile js return base { F.scripts = F.scripts base ++ map F.Inline js , F.style = F.style base ++ map F.Inline css} includes::Opts->IO ([FilePath],[FilePath]) includes o | nodefault o = return $ splitCssJs $ include o | otherwise = do imp <- getDataFileName "js/impress.min.js" start <- getDataFileName "js/start.js" sty <- getDataFileName "css/style.min.css" return $ ((sty:) *** ([imp,start]++)) $ splitCssJs $ include o
matthewSorensen/himpress
Himpress/Plumbing.hs
Haskell
bsd-3-clause
4,258
module Pos.Chain.Ssc.Error ( module Pos.Chain.Ssc.Error.Seed , module Pos.Chain.Ssc.Error.Verify ) where import Pos.Chain.Ssc.Error.Seed import Pos.Chain.Ssc.Error.Verify
input-output-hk/pos-haskell-prototype
chain/src/Pos/Chain/Ssc/Error.hs
Haskell
mit
213
{-| Implementation of the generic daemon functionality. -} {- Copyright (C) 2011, 2012 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.Daemon ( DaemonOptions(..) , OptType , CheckFn , PrepFn , MainFn , defaultOptions , oShowHelp , oShowVer , oNoDaemonize , oNoUserChecks , oDebug , oPort , oBindAddress , oSyslogUsage , oForceNode , oNoVoting , oYesDoIt , parseArgs , parseAddress , cleanupSocket , describeError , genericMain , getFQDN ) where import Control.Concurrent import Control.Exception import Control.Monad import Data.Maybe (fromMaybe, listToMaybe) import Text.Printf import Data.Word import GHC.IO.Handle (hDuplicateTo) import Network.BSD (getHostName) import qualified Network.Socket as Socket import System.Console.GetOpt import System.Directory import System.Exit import System.Environment import System.IO import System.IO.Error (isDoesNotExistError, modifyIOError, annotateIOError) import System.Posix.Directory import System.Posix.Files import System.Posix.IO import System.Posix.Process import System.Posix.Types import System.Posix.Signals import Ganeti.Common as Common import Ganeti.Logging import Ganeti.Runtime import Ganeti.BasicTypes import Ganeti.Utils import qualified Ganeti.Constants as C import qualified Ganeti.Ssconf as Ssconf -- * Constants -- | \/dev\/null path. devNull :: FilePath devNull = "/dev/null" -- | Error message prefix, used in two separate paths (when forking -- and when not). daemonStartupErr :: String -> String daemonStartupErr = ("Error when starting the daemon process: " ++) -- * Data types -- | Command line options structure. data DaemonOptions = DaemonOptions { optShowHelp :: Bool -- ^ Just show the help , optShowVer :: Bool -- ^ Just show the program version , optShowComp :: Bool -- ^ Just show the completion info , optDaemonize :: Bool -- ^ Whether to daemonize or not , optPort :: Maybe Word16 -- ^ Override for the network port , optDebug :: Bool -- ^ Enable debug messages , optNoUserChecks :: Bool -- ^ Ignore user checks , optBindAddress :: Maybe String -- ^ Override for the bind address , optSyslogUsage :: Maybe SyslogUsage -- ^ Override for Syslog usage , optForceNode :: Bool -- ^ Ignore node checks , optNoVoting :: Bool -- ^ skip voting for master , optYesDoIt :: Bool -- ^ force dangerous options } -- | Default values for the command line options. defaultOptions :: DaemonOptions defaultOptions = DaemonOptions { optShowHelp = False , optShowVer = False , optShowComp = False , optDaemonize = True , optPort = Nothing , optDebug = False , optNoUserChecks = False , optBindAddress = Nothing , optSyslogUsage = Nothing , optForceNode = False , optNoVoting = False , optYesDoIt = False } instance StandardOptions DaemonOptions where helpRequested = optShowHelp verRequested = optShowVer compRequested = optShowComp requestHelp o = o { optShowHelp = True } requestVer o = o { optShowVer = True } requestComp o = o { optShowComp = True } -- | Abrreviation for the option type. type OptType = GenericOptType DaemonOptions -- | Check function type. type CheckFn a = DaemonOptions -> IO (Either ExitCode a) -- | Prepare function type. type PrepFn a b = DaemonOptions -> a -> IO b -- | Main execution function type. type MainFn a b = DaemonOptions -> a -> b -> IO () -- * Command line options oNoDaemonize :: OptType oNoDaemonize = (Option "f" ["foreground"] (NoArg (\ opts -> Ok opts { optDaemonize = False })) "Don't detach from the current terminal", OptComplNone) oDebug :: OptType oDebug = (Option "d" ["debug"] (NoArg (\ opts -> Ok opts { optDebug = True })) "Enable debug messages", OptComplNone) oNoUserChecks :: OptType oNoUserChecks = (Option "" ["no-user-checks"] (NoArg (\ opts -> Ok opts { optNoUserChecks = True })) "Ignore user checks", OptComplNone) oPort :: Int -> OptType oPort def = (Option "p" ["port"] (reqWithConversion (tryRead "reading port") (\port opts -> Ok opts { optPort = Just port }) "PORT") ("Network port (default: " ++ show def ++ ")"), OptComplInteger) oBindAddress :: OptType oBindAddress = (Option "b" ["bind"] (ReqArg (\addr opts -> Ok opts { optBindAddress = Just addr }) "ADDR") "Bind address (default depends on cluster configuration)", OptComplInetAddr) oSyslogUsage :: OptType oSyslogUsage = (Option "" ["syslog"] (reqWithConversion syslogUsageFromRaw (\su opts -> Ok opts { optSyslogUsage = Just su }) "SYSLOG") ("Enable logging to syslog (except debug \ \messages); one of 'no', 'yes' or 'only' [" ++ C.syslogUsage ++ "]"), OptComplChoices ["yes", "no", "only"]) oForceNode :: OptType oForceNode = (Option "" ["force-node"] (NoArg (\ opts -> Ok opts { optForceNode = True })) "Force the daemon to run on a different node than the master", OptComplNone) oNoVoting :: OptType oNoVoting = (Option "" ["no-voting"] (NoArg (\ opts -> Ok opts { optNoVoting = True })) "Skip node agreement check (dangerous)", OptComplNone) oYesDoIt :: OptType oYesDoIt = (Option "" ["yes-do-it"] (NoArg (\ opts -> Ok opts { optYesDoIt = True })) "Force a dangerous operation", OptComplNone) -- | Generic options. genericOpts :: [OptType] genericOpts = [ oShowHelp , oShowVer , oShowComp ] -- | Annotates and transforms IOErrors into a Result type. This can be -- used in the error handler argument to 'catch', for example. ioErrorToResult :: String -> IOError -> IO (Result a) ioErrorToResult description exc = return . Bad $ description ++ ": " ++ show exc -- | Small wrapper over getArgs and 'parseOpts'. parseArgs :: String -> [OptType] -> IO (DaemonOptions, [String]) parseArgs cmd options = do cmd_args <- getArgs parseOpts defaultOptions cmd_args cmd (options ++ genericOpts) [] -- * Daemon-related functions -- | PID file mode. pidFileMode :: FileMode pidFileMode = unionFileModes ownerReadMode ownerWriteMode -- | PID file open flags. pidFileFlags :: OpenFileFlags pidFileFlags = defaultFileFlags { noctty = True, trunc = False } -- | Writes a PID file and locks it. writePidFile :: FilePath -> IO Fd writePidFile path = do fd <- openFd path ReadWrite (Just pidFileMode) pidFileFlags setLock fd (WriteLock, AbsoluteSeek, 0, 0) my_pid <- getProcessID _ <- fdWrite fd (show my_pid ++ "\n") return fd -- | Helper function to ensure a socket doesn't exist. Should only be -- called once we have locked the pid file successfully. cleanupSocket :: FilePath -> IO () cleanupSocket socketPath = catchJust (guard . isDoesNotExistError) (removeLink socketPath) (const $ return ()) -- | Sets up a daemon's environment. setupDaemonEnv :: FilePath -> FileMode -> IO () setupDaemonEnv cwd umask = do changeWorkingDirectory cwd _ <- setFileCreationMask umask _ <- createSession return () -- | Cleanup function, performing all the operations that need to be done prior -- to shutting down a daemon. finalCleanup :: FilePath -> IO () finalCleanup = removeFile -- | Signal handler for the termination signal. handleSigTerm :: ThreadId -> IO () handleSigTerm mainTID = -- Throw termination exception to the main thread, so that the daemon is -- actually stopped in the proper way, executing all the functions waiting on -- "finally" statement. Control.Exception.throwTo mainTID ExitSuccess -- | Signal handler for reopening log files. handleSigHup :: FilePath -> IO () handleSigHup path = do setupDaemonFDs (Just path) logInfo "Reopening log files after receiving SIGHUP" -- | Sets up a daemon's standard file descriptors. setupDaemonFDs :: Maybe FilePath -> IO () setupDaemonFDs logfile = do null_in_handle <- openFile devNull ReadMode null_out_handle <- openFile (fromMaybe devNull logfile) AppendMode hDuplicateTo null_in_handle stdin hDuplicateTo null_out_handle stdout hDuplicateTo null_out_handle stderr hClose null_in_handle hClose null_out_handle -- | Computes the default bind address for a given family. defaultBindAddr :: Int -- ^ The port we want -> Socket.Family -- ^ The cluster IP family -> Result (Socket.Family, Socket.SockAddr) defaultBindAddr port Socket.AF_INET = Ok (Socket.AF_INET, Socket.SockAddrInet (fromIntegral port) Socket.iNADDR_ANY) defaultBindAddr port Socket.AF_INET6 = Ok (Socket.AF_INET6, Socket.SockAddrInet6 (fromIntegral port) 0 Socket.iN6ADDR_ANY 0) defaultBindAddr _ fam = Bad $ "Unsupported address family: " ++ show fam -- | Based on the options, compute the socket address to use for the -- daemon. parseAddress :: DaemonOptions -- ^ Command line options -> Int -- ^ Default port for this daemon -> IO (Result (Socket.Family, Socket.SockAddr)) parseAddress opts defport = do let port = maybe defport fromIntegral $ optPort opts def_family <- Ssconf.getPrimaryIPFamily Nothing case optBindAddress opts of Nothing -> return (def_family >>= defaultBindAddr port) Just saddr -> Control.Exception.catch (resolveAddr port saddr) (ioErrorToResult $ "Invalid address " ++ saddr) -- | Environment variable to override the assumed host name of the -- current node. vClusterHostNameEnvVar :: String vClusterHostNameEnvVar = "GANETI_HOSTNAME" -- | Get the real full qualified host name. getFQDN' :: IO String getFQDN' = do hostname <- getHostName addrInfos <- Socket.getAddrInfo Nothing (Just hostname) Nothing let address = listToMaybe addrInfos >>= (Just . Socket.addrAddress) case address of Just a -> do fqdn <- liftM fst $ Socket.getNameInfo [] True False a return (fromMaybe hostname fqdn) Nothing -> return hostname -- | Return the full qualified host name, honoring the vcluster setup. getFQDN :: IO String getFQDN = do let ioErrorToNothing :: IOError -> IO (Maybe String) ioErrorToNothing _ = return Nothing vcluster_node <- Control.Exception.catch (liftM Just (getEnv vClusterHostNameEnvVar)) ioErrorToNothing case vcluster_node of Just node_name -> return node_name Nothing -> getFQDN' -- | Returns if the current node is the master node. isMaster :: IO Bool isMaster = do curNode <- getFQDN masterNode <- Ssconf.getMasterNode Nothing case masterNode of Ok n -> return (curNode == n) Bad _ -> return False -- | Ensures that the daemon runs on the right node (and exits -- gracefully if it doesnt) ensureNode :: GanetiDaemon -> DaemonOptions -> IO () ensureNode daemon opts = do is_master <- isMaster when (daemonOnlyOnMaster daemon && not is_master && not (optForceNode opts)) $ do putStrLn "Not master, exiting." exitWith (ExitFailure C.exitNotmaster) -- | Run an I\/O action that might throw an I\/O error, under a -- handler that will simply annotate and re-throw the exception. describeError :: String -> Maybe Handle -> Maybe FilePath -> IO a -> IO a describeError descr hndl fpath = modifyIOError (\e -> annotateIOError e descr hndl fpath) -- | Run an I\/O action as a daemon. -- -- WARNING: this only works in single-threaded mode (either using the -- single-threaded runtime, or using the multi-threaded one but with -- only one OS thread, i.e. -N1). daemonize :: FilePath -> (Maybe Fd -> IO ()) -> IO () daemonize logfile action = do (rpipe, wpipe) <- createPipe -- first fork _ <- forkProcess $ do -- in the child closeFd rpipe let wpipe' = Just wpipe setupDaemonEnv "/" (unionFileModes groupModes otherModes) setupDaemonFDs (Just logfile) `Control.Exception.catch` handlePrepErr False wpipe' -- second fork, launches the actual child code; standard -- double-fork technique _ <- forkProcess (action wpipe') exitImmediately ExitSuccess closeFd wpipe hndl <- fdToHandle rpipe errors <- hGetContents hndl ecode <- if null errors then return ExitSuccess else do hPutStrLn stderr $ daemonStartupErr errors return $ ExitFailure C.exitFailure exitImmediately ecode -- | Generic daemon startup. genericMain :: GanetiDaemon -- ^ The daemon we're running -> [OptType] -- ^ The available options -> CheckFn a -- ^ Check function -> PrepFn a b -- ^ Prepare function -> MainFn a b -- ^ Execution function -> IO () genericMain daemon options check_fn prep_fn exec_fn = do let progname = daemonName daemon (opts, args) <- parseArgs progname options -- Modify handleClient in Ganeti.UDSServer to remove this logging from luxid. when (optDebug opts && daemon == GanetiLuxid) . hPutStrLn stderr $ printf C.debugModeConfidentialityWarning (daemonName daemon) ensureNode daemon opts exitUnless (null args) "This program doesn't take any arguments" unless (optNoUserChecks opts) $ do runtimeEnts <- runResultT getEnts ents <- exitIfBad "Can't find required user/groups" runtimeEnts verifyDaemonUser daemon ents syslog <- case optSyslogUsage opts of Nothing -> exitIfBad "Invalid cluster syslog setting" $ syslogUsageFromRaw C.syslogUsage Just v -> return v log_file <- daemonLogFile daemon -- run the check function and optionally exit if it returns an exit code check_result <- check_fn opts check_result' <- case check_result of Left code -> exitWith code Right v -> return v let processFn = if optDaemonize opts then daemonize log_file else \action -> action Nothing _ <- installHandler lostConnection (Catch (handleSigHup log_file)) Nothing processFn $ innerMain daemon opts syslog check_result' prep_fn exec_fn -- | Full prepare function. -- -- This is executed after daemonization, and sets up both the log -- files (a generic functionality) and the custom prepare function of -- the daemon. fullPrep :: GanetiDaemon -- ^ The daemon we're running -> DaemonOptions -- ^ The options structure, filled from the cmdline -> SyslogUsage -- ^ Syslog mode -> a -- ^ Check results -> PrepFn a b -- ^ Prepare function -> IO (FilePath, b) fullPrep daemon opts syslog check_result prep_fn = do logfile <- if optDaemonize opts then return Nothing else liftM Just $ daemonLogFile daemon pidfile <- daemonPidFile daemon let dname = daemonName daemon setupLogging logfile dname (optDebug opts) True False syslog _ <- describeError "writing PID file; already locked?" Nothing (Just pidfile) $ writePidFile pidfile logNotice $ dname ++ " daemon startup" prep_res <- prep_fn opts check_result tid <- myThreadId _ <- installHandler sigTERM (Catch $ handleSigTerm tid) Nothing return (pidfile, prep_res) -- | Inner daemon function. -- -- This is executed after daemonization. innerMain :: GanetiDaemon -- ^ The daemon we're running -> DaemonOptions -- ^ The options structure, filled from the cmdline -> SyslogUsage -- ^ Syslog mode -> a -- ^ Check results -> PrepFn a b -- ^ Prepare function -> MainFn a b -- ^ Execution function -> Maybe Fd -- ^ Error reporting function -> IO () innerMain daemon opts syslog check_result prep_fn exec_fn fd = do (pidFile, prep_result) <- fullPrep daemon opts syslog check_result prep_fn `Control.Exception.catch` handlePrepErr True fd -- no error reported, we should now close the fd maybeCloseFd fd finally (exec_fn opts check_result prep_result) (finalCleanup pidFile) -- | Daemon prepare error handling function. handlePrepErr :: Bool -> Maybe Fd -> IOError -> IO a handlePrepErr logging_setup fd err = do let msg = show err case fd of -- explicitly writing to the fd directly, since when forking it's -- better (safer) than trying to convert this into a full handle Just fd' -> fdWrite fd' msg >> return () Nothing -> hPutStrLn stderr (daemonStartupErr msg) when logging_setup $ logError msg exitWith $ ExitFailure 1 -- | Close a file descriptor. maybeCloseFd :: Maybe Fd -> IO () maybeCloseFd Nothing = return () maybeCloseFd (Just fd) = closeFd fd
apyrgio/ganeti
src/Ganeti/Daemon.hs
Haskell
bsd-2-clause
17,864
module Language.Haskell.GhcMod.Lint where import Exception (ghandle) import Control.Exception (SomeException(..)) import Language.Haskell.GhcMod.Logger (checkErrorPrefix) import Language.Haskell.GhcMod.Convert import Language.Haskell.GhcMod.Monad import Language.Haskell.GhcMod.Types import Language.Haskell.HLint (hlint) -- | Checking syntax of a target file using hlint. -- Warnings and errors are returned. lint :: IOish m => FilePath -- ^ A target file. -> GhcModT m String lint file = do opt <- options ghandle handler . pack =<< liftIO (hlint $ file : "--quiet" : hlintOpts opt) where pack = convert' . map (init . show) -- init drops the last \n. handler (SomeException e) = return $ checkErrorPrefix ++ show e ++ "\n"
cabrera/ghc-mod
Language/Haskell/GhcMod/Lint.hs
Haskell
bsd-3-clause
754
----------------------------------------------------------------------------- -- | -- License : BSD-3-Clause -- Maintainer : Oleg Grenrus <oleg.grenrus@iki.fi> -- -- The repo collaborators API as described on -- <http://developer.github.com/v3/repos/collaborators/>. module GitHub.Endpoints.Repos.Collaborators ( collaboratorsOnR, collaboratorPermissionOnR, isCollaboratorOnR, addCollaboratorR, module GitHub.Data, ) where import GitHub.Data import GitHub.Internal.Prelude import Prelude () -- | List collaborators. -- See <https://developer.github.com/v3/repos/collaborators/#list-collaborators> collaboratorsOnR :: Name Owner -> Name Repo -> FetchCount -> Request k (Vector SimpleUser) collaboratorsOnR user repo = pagedQuery ["repos", toPathPart user, toPathPart repo, "collaborators"] [] -- | Review a user's permission level. -- <https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level> collaboratorPermissionOnR :: Name Owner -- ^ Repository owner -> Name Repo -- ^ Repository name -> Name User -- ^ Collaborator to check permissions of. -> GenRequest 'MtJSON rw CollaboratorWithPermission collaboratorPermissionOnR owner repo coll = query ["repos", toPathPart owner, toPathPart repo, "collaborators", toPathPart coll, "permission"] [] -- | Check if a user is a collaborator. -- See <https://developer.github.com/v3/repos/collaborators/#check-if-a-user-is-a-collaborator> isCollaboratorOnR :: Name Owner -- ^ Repository owner -> Name Repo -- ^ Repository name -> Name User -- ^ Collaborator? -> GenRequest 'MtStatus rw Bool isCollaboratorOnR user repo coll = Query ["repos", toPathPart user, toPathPart repo, "collaborators", toPathPart coll] [] -- | Invite a user as a collaborator. -- See <https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator> addCollaboratorR :: Name Owner -- ^ Repository owner -> Name Repo -- ^ Repository name -> Name User -- ^ Collaborator to add -> GenRequest 'MtJSON 'RW (Maybe RepoInvitation) addCollaboratorR owner repo coll = Command Put ["repos", toPathPart owner, toPathPart repo, "collaborators", toPathPart coll] mempty
jwiegley/github
src/GitHub/Endpoints/Repos/Collaborators.hs
Haskell
bsd-3-clause
2,278
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE MultiWayIf #-} module Hans.Dns.Packet ( DNSPacket(..) , DNSHeader(..) , OpCode(..) , RespCode(..) , Query(..) , QClass(..) , QType(..) , RR(..) , Type(..) , Class(..) , RData(..) , Name , getDNSPacket , putDNSPacket ) where import Hans.IP4.Packet (IP4,getIP4,putIP4) import Control.Monad import Data.Bits import qualified Data.ByteString as S import qualified Data.Map.Strict as Map import qualified Data.Serialize.Get as C import qualified Data.Foldable as F import Data.Int import Data.Serialize ( Putter, runPut, putWord8, putWord16be, putWord32be , putByteString ) import Data.Word import MonadLib ( lift, StateT, runStateT, get, set ) import Numeric ( showHex ) -- DNS Packets ----------------------------------------------------------------- data DNSPacket = DNSPacket { dnsHeader :: DNSHeader , dnsQuestions :: [Query] , dnsAnswers :: [RR] , dnsAuthorityRecords :: [RR] , dnsAdditionalRecords :: [RR] } deriving (Show) data DNSHeader = DNSHeader { dnsId :: !Word16 , dnsQuery :: Bool , dnsOpCode :: OpCode , dnsAA :: Bool , dnsTC :: Bool , dnsRD :: Bool , dnsRA :: Bool , dnsRC :: RespCode } deriving (Show) data OpCode = OpQuery | OpIQuery | OpStatus | OpReserved !Word16 deriving (Show) data RespCode = RespNoError | RespFormatError | RespServerFailure | RespNameError | RespNotImplemented | RespRefused | RespReserved !Word16 deriving (Eq,Show) type Name = [S.ByteString] data Query = Query { qName :: Name , qType :: QType , qClass :: QClass } deriving (Show) data RR = RR { rrName :: Name , rrClass :: Class , rrTTL :: !Int32 , rrRData :: RData } deriving (Show) data QType = QType Type | AFXR | MAILB | MAILA | QTAny deriving (Show) data Type = A | NS | MD | MF | CNAME | SOA | MB | MG | MR | NULL | PTR | HINFO | MINFO | MX | AAAA deriving (Show) data QClass = QClass Class | QAnyClass deriving (Show) data Class = IN | CS | CH | HS deriving (Show,Eq) data RData = RDA IP4 | RDNS Name | RDMD Name | RDMF Name | RDCNAME Name | RDSOA Name Name !Word32 !Int32 !Int32 !Int32 !Word32 | RDMB Name | RDMG Name | RDMR Name | RDPTR Name | RDHINFO S.ByteString S.ByteString | RDMINFO Name Name | RDMX !Word16 Name | RDNULL S.ByteString | RDUnknown Type S.ByteString deriving (Show) -- Cereal With Label Compression ----------------------------------------------- data RW = RW { rwOffset :: !Int , rwLabels :: Map.Map Int Name } deriving (Show) type Get = StateT RW C.Get {-# INLINE unGet #-} unGet :: Get a -> C.Get a unGet m = do (a,_) <- runStateT RW { rwOffset = 0, rwLabels = Map.empty } m return a getOffset :: Get Int getOffset = rwOffset `fmap` get addOffset :: Int -> Get () addOffset off = do rw <- get set $! rw { rwOffset = rwOffset rw + off } lookupPtr :: Int -> Get Name lookupPtr off = do rw <- get when (off >= rwOffset rw) (fail "Invalid offset in pointer") case Map.lookup off (rwLabels rw) of Just ls -> return ls Nothing -> fail $ "Unknown label for offset: " ++ showHex off "\n" ++ show (rwLabels rw) data Label = Label Int S.ByteString | Ptr Int Name deriving (Show) labelsToName :: [Label] -> Name labelsToName = F.foldMap toName where toName (Label _ l) = [l] toName (Ptr _ n) = n addLabels :: [Label] -> Get () addLabels labels = do rw <- get set $! rw { rwLabels = Map.fromList newLabels `Map.union` rwLabels rw } where newLabels = go labels (labelsToName labels) go (Label off _ : rest) name@(_ : ns) = (off,name) : go rest ns go (Ptr off _ : _) name = [(off,name)] go _ _ = [] {-# INLINE liftGet #-} liftGet :: Int -> C.Get a -> Get a liftGet n m = do addOffset n lift m {-# INLINE getWord8 #-} getWord8 :: Get Word8 getWord8 = liftGet 1 C.getWord8 {-# INLINE getWord16be #-} getWord16be :: Get Word16 getWord16be = liftGet 2 C.getWord16be {-# INLINE getWord32be #-} getWord32be :: Get Word32 getWord32be = liftGet 4 C.getWord32be {-# INLINE getInt32be #-} getInt32be :: Get Int32 getInt32be = fromIntegral `fmap` liftGet 4 C.getWord32be {-# INLINE getBytes #-} getBytes :: Int -> Get S.ByteString getBytes n = liftGet n (C.getBytes n) isolate :: Int -> Get a -> Get a isolate n body = do off <- get (a,off') <- lift (C.isolate n (runStateT off body)) set off' return a label :: String -> Get a -> Get a label str m = do off <- get (a,off') <- lift (C.label str (runStateT off m)) set off' return a {-# INLINE putInt32be #-} putInt32be :: Putter Int32 putInt32be i = putWord32be (fromIntegral i) -- Parsing --------------------------------------------------------------------- getDNSPacket :: C.Get DNSPacket getDNSPacket = unGet $ label "DNSPacket" $ do dnsHeader <- getDNSHeader qdCount <- getWord16be anCount <- getWord16be nsCount <- getWord16be arCount <- getWord16be let blockOf c l m = label l (replicateM (fromIntegral c) m) dnsQuestions <- blockOf qdCount "Questions" getQuery dnsAnswers <- blockOf anCount "Answers" getRR dnsAuthorityRecords <- blockOf nsCount "Authority Records" getRR dnsAdditionalRecords <- blockOf arCount "Additional Records" getRR return DNSPacket { .. } -- 1 1 1 1 1 1 -- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | ID | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- |QR| Opcode |AA|TC|RD|RA| Z | RCODE | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | QDCOUNT | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | ANCOUNT | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | NSCOUNT | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | ARCOUNT | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ getDNSHeader :: Get DNSHeader getDNSHeader = label "DNS Header" $ do dnsId <- getWord16be flags <- getWord16be let dnsQuery = not (flags `testBit` 15) dnsOpCode = parseOpCode (flags `shiftR` 11) dnsAA = flags `testBit` 10 dnsTC = flags `testBit` 9 dnsRD = flags `testBit` 8 dnsRA = flags `testBit` 7 dnsZ = (flags `shiftR` 4) .&. 0x7 dnsRC = parseRespCode (flags .&. 0xf) unless (dnsZ == 0) (fail ("Z not zero")) return DNSHeader { .. } parseOpCode :: Word16 -> OpCode parseOpCode 0 = OpQuery parseOpCode 1 = OpIQuery parseOpCode 2 = OpStatus parseOpCode c = OpReserved (c .&. 0xf) parseRespCode :: Word16 -> RespCode parseRespCode 0 = RespNoError parseRespCode 1 = RespFormatError parseRespCode 2 = RespServerFailure parseRespCode 3 = RespNameError parseRespCode 4 = RespNotImplemented parseRespCode 5 = RespRefused parseRespCode c = RespReserved (c .&. 0xf) getQuery :: Get Query getQuery = label "Question" $ do qName <- getName qType <- label "QTYPE" getQType qClass <- label "QCLASS" getQClass return Query { .. } -- 1 1 1 1 1 1 -- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | | -- / / -- / NAME / -- | | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | TYPE | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | CLASS | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | TTL | -- | | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -- | RDLENGTH | -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| -- / RDATA / -- / / -- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ getRR :: Get RR getRR = label "RR" $ do rrName <- getName ty <- getType rrClass <- getClass rrTTL <- getInt32be rrRData <- getRData ty return RR { .. } getType :: Get Type getType = do qt <- getQType case qt of QType ty -> return ty _ -> fail ("Invalid TYPE: " ++ show qt) getQType :: Get QType getQType = do tag <- getWord16be case tag of 1 -> return (QType A) 2 -> return (QType NS) 3 -> return (QType MD) 4 -> return (QType MF) 5 -> return (QType CNAME) 6 -> return (QType SOA) 7 -> return (QType MB) 8 -> return (QType MG) 9 -> return (QType MR) 10 -> return (QType NULL) 12 -> return (QType PTR) 13 -> return (QType HINFO) 14 -> return (QType MINFO) 15 -> return (QType MX) 28 -> return (QType AAAA) 252 -> return AFXR 253 -> return MAILB 254 -> return MAILA 255 -> return QTAny _ -> fail ("Invalid TYPE: " ++ show tag) getQClass :: Get QClass getQClass = do tag <- getWord16be case tag of 1 -> return (QClass IN) 2 -> return (QClass CS) 3 -> return (QClass CH) 4 -> return (QClass HS) 255 -> return QAnyClass _ -> fail ("Invalid CLASS: " ++ show tag) getName :: Get Name getName = do labels <- go addLabels labels return (labelsToName labels) where go = do off <- getOffset len <- getWord8 if | len .&. 0xc0 == 0xc0 -> do l <- getWord8 let ptr = fromIntegral ((0x3f .&. len) `shiftL` 8) + fromIntegral l ns <- lookupPtr ptr return [Ptr off ns] | len == 0 -> return [] | otherwise -> do l <- getBytes (fromIntegral len) ls <- go return (Label off l:ls) getClass :: Get Class getClass = label "CLASS" $ do qc <- getQClass case qc of QClass c -> return c QAnyClass -> fail "Invalid CLASS" getRData :: Type -> Get RData getRData ty = label (show ty) $ do len <- getWord16be isolate (fromIntegral len) $ case ty of A -> RDA `fmap` liftGet 4 getIP4 NS -> RDNS `fmap` getName MD -> RDMD `fmap` getName MF -> RDMF `fmap` getName CNAME -> RDCNAME `fmap` getName SOA -> do mname <- getName rname <- getName serial <- getWord32be refresh <- getInt32be retry <- getInt32be expire <- getInt32be minTTL <- getWord32be return (RDSOA mname rname serial refresh retry expire minTTL) MB -> RDMB `fmap` getName MG -> RDMG `fmap` getName MR -> RDMR `fmap` getName NULL -> RDNULL `fmap` (getBytes =<< lift C.remaining) PTR -> RDPTR `fmap` getName HINFO -> do cpuLen <- getWord8 cpu <- getBytes (fromIntegral cpuLen) osLen <- getWord8 os <- getBytes (fromIntegral osLen) return (RDHINFO cpu os) MINFO -> do rmailBx <- getName emailBx <- getName return (RDMINFO rmailBx emailBx) MX -> do pref <- getWord16be ex <- getName return (RDMX pref ex) _ -> RDUnknown ty `fmap` (getBytes =<< lift C.remaining) -- Rendering ------------------------------------------------------------------- putDNSPacket :: Putter DNSPacket putDNSPacket DNSPacket{ .. } = do putDNSHeader dnsHeader putWord16be (fromIntegral (length dnsQuestions)) putWord16be (fromIntegral (length dnsAnswers)) putWord16be (fromIntegral (length dnsAuthorityRecords)) putWord16be (fromIntegral (length dnsAdditionalRecords)) F.traverse_ putQuery dnsQuestions F.traverse_ putRR dnsAnswers F.traverse_ putRR dnsAuthorityRecords F.traverse_ putRR dnsAdditionalRecords putDNSHeader :: Putter DNSHeader putDNSHeader DNSHeader { .. } = do putWord16be dnsId let flag i b w | b = setBit w i | otherwise = clearBit w i flags = flag 15 (not dnsQuery) $ flag 10 dnsAA $ flag 9 dnsTC $ flag 8 dnsRD $ flag 7 dnsRA $ flag 4 False -- dnsZ $ (renderOpCode dnsOpCode `shiftL` 11) .|. renderRespCode dnsRC putWord16be flags renderOpCode :: OpCode -> Word16 renderOpCode OpQuery = 0 renderOpCode OpIQuery = 1 renderOpCode OpStatus = 2 renderOpCode (OpReserved c) = c .&. 0xf renderRespCode :: RespCode -> Word16 renderRespCode RespNoError = 0 renderRespCode RespFormatError = 1 renderRespCode RespServerFailure = 2 renderRespCode RespNameError = 3 renderRespCode RespNotImplemented = 4 renderRespCode RespRefused = 5 renderRespCode (RespReserved c) = c .&. 0xf putName :: Putter Name putName = go where go (l:ls) | S.null l = putWord8 0 | S.length l > 63 = error "Label too big" | otherwise = do putWord8 (fromIntegral len) putByteString l go ls where len = S.length l go [] = putWord8 0 putQuery :: Putter Query putQuery Query { .. } = do putName qName putQType qType putQClass qClass putType :: Putter Type putType A = putWord16be 1 putType NS = putWord16be 2 putType MD = putWord16be 3 putType MF = putWord16be 4 putType CNAME = putWord16be 5 putType SOA = putWord16be 6 putType MB = putWord16be 7 putType MG = putWord16be 8 putType MR = putWord16be 9 putType NULL = putWord16be 10 putType PTR = putWord16be 12 putType HINFO = putWord16be 13 putType MINFO = putWord16be 14 putType MX = putWord16be 15 putType AAAA = putWord16be 28 putQType :: Putter QType putQType (QType ty) = putType ty putQType AFXR = putWord16be 252 putQType MAILB = putWord16be 253 putQType MAILA = putWord16be 254 putQType QTAny = putWord16be 255 putQClass :: Putter QClass putQClass (QClass c) = putClass c putQClass QAnyClass = putWord16be 255 putRR :: Putter RR putRR RR { .. } = do putName rrName let (ty,rdata) = putRData rrRData putType ty putClass rrClass putWord32be (fromIntegral rrTTL) putWord16be (fromIntegral (S.length rdata)) putByteString rdata putClass :: Putter Class putClass IN = putWord16be 1 putClass CS = putWord16be 2 putClass CH = putWord16be 3 putClass HS = putWord16be 4 putRData :: RData -> (Type,S.ByteString) putRData rd = case rd of RDA addr -> rdata A (putIP4 addr) RDNS name -> rdata NS (putName name) RDMD name -> rdata MD (putName name) RDMF name -> rdata MF (putName name) RDCNAME name -> rdata CNAME (putName name) RDSOA m r s f t ex ttl -> rdata SOA $ do putName m putName r putWord32be s putInt32be f putInt32be t putInt32be ex putWord32be ttl RDMB name -> rdata MB (putName name) RDMG name -> rdata MG (putName name) RDMR name -> rdata MR (putName name) RDNULL bytes -> rdata NULL $ do putWord8 (fromIntegral (S.length bytes)) putByteString bytes RDPTR name -> rdata PTR (putName name) RDHINFO cpu os -> rdata HINFO $ do putWord8 (fromIntegral (S.length cpu)) putByteString cpu putWord8 (fromIntegral (S.length os)) putByteString os RDMINFO rm em -> rdata MINFO $ do putName rm putName em RDMX pref ex -> rdata MX $ do putWord16be pref putName ex RDUnknown ty bytes -> (ty,bytes) where rdata tag m = (tag,runPut m)
GaloisInc/HaNS
src/Hans/Dns/Packet.hs
Haskell
bsd-3-clause
18,069
import System.Process.Extra main = system_ "bake-test"
capital-match/bake
travis.hs
Haskell
bsd-3-clause
57
module EnvSpec (main, spec) where import TestUtil import Network.MPD import System.Posix.Env hiding (getEnvDefault) main :: IO () main = hspec spec spec :: Spec spec = do describe "getEnvDefault" $ do it "returns the value of an environment variable" $ do setEnv "FOO" "foo" True r <- getEnvDefault "FOO" "bar" r `shouldBe` "foo" it "returns a given default value if that environment variable is not set" $ do unsetEnv "FOO" r <- getEnvDefault "FOO" "bar" r `shouldBe` "bar" describe "getConnectionSettings" $ do it "takes an optional argument, that overrides MPD_HOST" $ do setEnv "MPD_HOST" "user@example.com" True Right (host, _, pw) <- getConnectionSettings (Just "foo@bar") Nothing pw `shouldBe` "foo" host `shouldBe` "bar" it "takes an optional argument, that overrides MPD_PORT" $ do setEnv "MPD_PORT" "8080" True Right (_, port, _) <- getConnectionSettings Nothing (Just "23") port `shouldBe` 23 it "returns an error message, if MPD_PORT is not an int" $ do setEnv "MPD_PORT" "foo" True r <- getConnectionSettings Nothing Nothing r `shouldBe` Left "\"foo\" is not a valid port!" unsetEnv "MPD_PORT" describe "host" $ do it "is taken from MPD_HOST" $ do setEnv "MPD_HOST" "example.com" True Right (host, _, _) <- getConnectionSettings Nothing Nothing host `shouldBe` "example.com" it "is 'localhost' if MPD_HOST is not set" $ do unsetEnv "MPD_HOST" Right (host, _, _) <- getConnectionSettings Nothing Nothing host `shouldBe` "localhost" describe "port" $ do it "is taken from MPD_PORT" $ do setEnv "MPD_PORT" "8080" True Right (_, port, _) <- getConnectionSettings Nothing Nothing port `shouldBe` 8080 it "is 6600 if MPD_PORT is not set" $ do unsetEnv "MPD_PORT" Right (_, port, _) <- getConnectionSettings Nothing Nothing port `shouldBe` 6600 describe "password" $ do it "is taken from MPD_HOST if MPD_HOST is of the form password@host" $ do setEnv "MPD_HOST" "password@host" True Right (host, _, pw) <- getConnectionSettings Nothing Nothing host `shouldBe` "host" pw `shouldBe` "password" it "is '' if MPD_HOST is not of the form password@host" $ do setEnv "MPD_HOST" "example.com" True Right (_, _, pw) <- getConnectionSettings Nothing Nothing pw `shouldBe` "" it "is '' if MPD_HOST is not set" $ do unsetEnv "MPD_HOST" Right (_, _, pw) <- getConnectionSettings Nothing Nothing pw `shouldBe` ""
beni55/libmpd-haskell
tests/EnvSpec.hs
Haskell
mit
2,706
<?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="hr-HR"> <title>Core Language Files | 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>
kingthorin/zap-extensions
addOns/coreLang/src/main/javahelp/org/zaproxy/zap/extension/coreLang/resources/help_hr_HR/helpset_hr_HR.hs
Haskell
apache-2.0
980
{-# LANGUAGE TupleSections #-} import CoreSyn import CoreUtils import Id import Type import MkCore import CallArity (callArityRHS) import MkId import SysTools import DynFlags import ErrUtils import Outputable import TysWiredIn import Literal import GHC import Control.Monad import Control.Monad.IO.Class import System.Environment( getArgs ) import VarSet import PprCore import Unique import CoreLint import FastString -- Build IDs. use mkTemplateLocal, more predictable than proper uniques go, go2, x, d, n, y, z, scrut :: Id [go, go2, x,d, n, y, z, scrut, f] = mkTestIds (words "go go2 x d n y z scrut f") [ mkFunTys [intTy, intTy] intTy , mkFunTys [intTy, intTy] intTy , intTy , mkFunTys [intTy] intTy , mkFunTys [intTy] intTy , intTy , intTy , boolTy , mkFunTys [intTy, intTy] intTy -- protoypical external function ] exprs :: [(String, CoreExpr)] exprs = [ ("go2",) $ mkRFun go [x] (mkLet d (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y) ) $ mkLams [z] $ Var d `mkVarApps` [x]) $ go `mkLApps` [0, 0] , ("nested_go2",) $ mkRFun go [x] (mkLet n (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y)) $ mkACase (Var n) $ mkFun go2 [y] (mkLet d (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y) ) $ mkLams [z] $ Var d `mkVarApps` [x] )$ Var go2 `mkApps` [mkLit 1] ) $ go `mkLApps` [0, 0] , ("d0 (go 2 would be bad)",) $ mkRFun go [x] (mkLet d (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y) ) $ mkLams [z] $ Var f `mkApps` [ Var d `mkVarApps` [x], Var d `mkVarApps` [x] ]) $ go `mkLApps` [0, 0] , ("go2 (in case crut)",) $ mkRFun go [x] (mkLet d (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y) ) $ mkLams [z] $ Var d `mkVarApps` [x]) $ Case (go `mkLApps` [0, 0]) z intTy [(DEFAULT, [], Var f `mkVarApps` [z,z])] , ("go2 (in function call)",) $ mkRFun go [x] (mkLet d (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y) ) $ mkLams [z] $ Var d `mkVarApps` [x]) $ f `mkLApps` [0] `mkApps` [go `mkLApps` [0, 0]] , ("go2 (using surrounding interesting let)",) $ mkLet n (f `mkLApps` [0]) $ mkRFun go [x] (mkLet d (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y) ) $ mkLams [z] $ Var d `mkVarApps` [x]) $ Var f `mkApps` [n `mkLApps` [0], go `mkLApps` [0, 0]] , ("go2 (using surrounding boring let)",) $ mkLet z (mkLit 0) $ mkRFun go [x] (mkLet d (mkACase (Var go `mkVarApps` [x]) (mkLams [y] $ Var y) ) $ mkLams [z] $ Var d `mkVarApps` [x]) $ Var f `mkApps` [Var z, go `mkLApps` [0, 0]] , ("two calls, one from let and from body (d 1 would be bad)",) $ mkLet d (mkACase (mkLams [y] $ mkLit 0) (mkLams [y] $ mkLit 0)) $ mkFun go [x,y] (mkVarApps (Var d) [x]) $ mkApps (Var d) [mkLApps go [1,2]] , ("a thunk in a recursion (d 1 would be bad)",) $ mkRLet n (mkACase (mkLams [y] $ mkLit 0) (Var n)) $ mkRLet d (mkACase (mkLams [y] $ mkLit 0) (Var d)) $ Var n `mkApps` [d `mkLApps` [0]] , ("two thunks, one called multiple times (both arity 1 would be bad!)",) $ mkLet n (mkACase (mkLams [y] $ mkLit 0) (f `mkLApps` [0])) $ mkLet d (mkACase (mkLams [y] $ mkLit 0) (f `mkLApps` [0])) $ Var n `mkApps` [Var d `mkApps` [Var d `mkApps` [mkLit 0]]] , ("two functions, not thunks",) $ mkLet go (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var f `mkVarApps` [x]))) $ mkLet go2 (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var f `mkVarApps` [x]))) $ Var go `mkApps` [go2 `mkLApps` [0,1], mkLit 0] , ("a thunk, called multiple times via a forking recursion (d 1 would be bad!)",) $ mkLet d (mkACase (mkLams [y] $ mkLit 0) (f `mkLApps` [0])) $ mkRLet go2 (mkLams [x] (mkACase (Var go2 `mkApps` [Var go2 `mkApps` [mkLit 0, mkLit 0]]) (Var d))) $ go2 `mkLApps` [0,1] , ("a function, one called multiple times via a forking recursion",) $ mkLet go (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var f `mkVarApps` [x]))) $ mkRLet go2 (mkLams [x] (mkACase (Var go2 `mkApps` [Var go2 `mkApps` [mkLit 0, mkLit 0]]) (go `mkLApps` [0]))) $ go2 `mkLApps` [0,1] , ("two functions (recursive)",) $ mkRLet go (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go `mkVarApps` [x]))) $ mkRLet go2 (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go2 `mkVarApps` [x]))) $ Var go `mkApps` [go2 `mkLApps` [0,1], mkLit 0] , ("mutual recursion (thunks), called mutiple times (both arity 1 would be bad!)",) $ Let (Rec [ (n, mkACase (mkLams [y] $ mkLit 0) (Var d)) , (d, mkACase (mkLams [y] $ mkLit 0) (Var n))]) $ Var n `mkApps` [Var d `mkApps` [Var d `mkApps` [mkLit 0]]] , ("mutual recursion (functions), but no thunks",) $ Let (Rec [ (go, mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go2 `mkVarApps` [x]))) , (go2, mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go `mkVarApps` [x])))]) $ Var go `mkApps` [go2 `mkLApps` [0,1], mkLit 0] , ("mutual recursion (functions), one boring (d 1 would be bad)",) $ mkLet d (f `mkLApps` [0]) $ Let (Rec [ (go, mkLams [x, y] (Var d `mkApps` [go2 `mkLApps` [1,2]])) , (go2, mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go `mkVarApps` [x])))]) $ Var d `mkApps` [go2 `mkLApps` [0,1]] , ("a thunk (non-function-type), called twice, still calls once",) $ mkLet d (f `mkLApps` [0]) $ mkLet x (d `mkLApps` [1]) $ Var f `mkVarApps` [x, x] , ("a thunk (function type), called multiple times, still calls once",) $ mkLet d (f `mkLApps` [0]) $ mkLet n (Var f `mkApps` [d `mkLApps` [1]]) $ mkLams [x] $ Var n `mkVarApps` [x] , ("a thunk (non-function-type), in mutual recursion, still calls once (d 1 would be good)",) $ mkLet d (f `mkLApps` [0]) $ Let (Rec [ (x, Var d `mkApps` [go `mkLApps` [1,2]]) , (go, mkLams [x] $ mkACase (mkLams [z] $ Var x) (Var go `mkVarApps` [x]) ) ]) $ Var go `mkApps` [mkLit 0, go `mkLApps` [0,1]] , ("a thunk (function type), in mutual recursion, still calls once (d 1 would be good)",) $ mkLet d (f `mkLApps` [0]) $ Let (Rec [ (n, Var go `mkApps` [d `mkLApps` [1]]) , (go, mkLams [x] $ mkACase (Var n) (Var go `mkApps` [Var n `mkVarApps` [x]]) ) ]) $ Var go `mkApps` [mkLit 0, go `mkLApps` [0,1]] , ("a thunk (non-function-type) co-calls with the body (d 1 would be bad)",) $ mkLet d (f `mkLApps` [0]) $ mkLet x (d `mkLApps` [1]) $ Var d `mkVarApps` [x] ] main = do [libdir] <- getArgs runGhc (Just libdir) $ do getSessionDynFlags >>= setSessionDynFlags . flip gopt_set Opt_SuppressUniques dflags <- getSessionDynFlags liftIO $ forM_ exprs $ \(n,e) -> do case lintExpr [f,scrut] e of Just msg -> putMsg dflags (msg $$ text "in" <+> text n) Nothing -> return () putMsg dflags (text n <> char ':') -- liftIO $ putMsg dflags (ppr e) let e' = callArityRHS e let bndrs = varSetElems (allBoundIds e') -- liftIO $ putMsg dflags (ppr e') forM_ bndrs $ \v -> putMsg dflags $ nest 4 $ ppr v <+> ppr (idCallArity v) -- Utilities mkLApps :: Id -> [Integer] -> CoreExpr mkLApps v = mkApps (Var v) . map mkLit mkACase = mkIfThenElse (Var scrut) mkTestId :: Int -> String -> Type -> Id mkTestId i s ty = mkSysLocal (mkFastString s) (mkBuiltinUnique i) ty mkTestIds :: [String] -> [Type] -> [Id] mkTestIds ns tys = zipWith3 mkTestId [0..] ns tys mkLet :: Id -> CoreExpr -> CoreExpr -> CoreExpr mkLet v rhs body = Let (NonRec v rhs) body mkRLet :: Id -> CoreExpr -> CoreExpr -> CoreExpr mkRLet v rhs body = Let (Rec [(v, rhs)]) body mkFun :: Id -> [Id] -> CoreExpr -> CoreExpr -> CoreExpr mkFun v xs rhs body = mkLet v (mkLams xs rhs) body mkRFun :: Id -> [Id] -> CoreExpr -> CoreExpr -> CoreExpr mkRFun v xs rhs body = mkRLet v (mkLams xs rhs) body mkLit :: Integer -> CoreExpr mkLit i = Lit (mkLitInteger i intTy) -- Collects all let-bound IDs allBoundIds :: CoreExpr -> VarSet allBoundIds (Let (NonRec v rhs) body) = allBoundIds rhs `unionVarSet` allBoundIds body `extendVarSet` v allBoundIds (Let (Rec binds) body) = allBoundIds body `unionVarSet` unionVarSets [ allBoundIds rhs `extendVarSet` v | (v, rhs) <- binds ] allBoundIds (App e1 e2) = allBoundIds e1 `unionVarSet` allBoundIds e2 allBoundIds (Case scrut _ _ alts) = allBoundIds scrut `unionVarSet` unionVarSets [ allBoundIds e | (_, _ , e) <- alts ] allBoundIds (Lam _ e) = allBoundIds e allBoundIds (Tick _ e) = allBoundIds e allBoundIds (Cast e _) = allBoundIds e allBoundIds _ = emptyVarSet
green-haskell/ghc
testsuite/tests/callarity/unittest/CallArity1.hs
Haskell
bsd-3-clause
9,333
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.Concurrent -- Copyright : (c) The University of Glasgow 2003 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : non-portable (requires concurrency) -- -- FFI datatypes and operations that use or require concurrency (GHC only). -- ----------------------------------------------------------------------------- module Foreign.Concurrent ( -- * Concurrency-based 'ForeignPtr' operations -- | These functions generalize their namesakes in the portable -- "Foreign.ForeignPtr" module by allowing arbitrary 'IO' actions -- as finalizers. These finalizers necessarily run in a separate -- thread, cf. /Destructors, Finalizers and Synchronization/, -- by Hans Boehm, /POPL/, 2003. newForeignPtr, addForeignPtrFinalizer, ) where import GHC.IO ( IO ) import GHC.Ptr ( Ptr ) import GHC.ForeignPtr ( ForeignPtr ) import qualified GHC.ForeignPtr newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a) -- -- ^Turns a plain memory reference into a foreign object by -- associating a finalizer - given by the monadic operation - with the -- reference. The storage manager will start the finalizer, in a -- separate thread, some time after the last reference to the -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and -- in fact there is no guarantee that the finalizer will eventually -- run at all. -- -- Note that references from a finalizer do not necessarily prevent -- another object from being finalized. If A's finalizer refers to B -- (perhaps using 'touchForeignPtr', then the only guarantee is that -- B's finalizer will never be started before A's. If both A and B -- are unreachable, then both finalizers will start together. See -- 'touchForeignPtr' for more on finalizer ordering. -- newForeignPtr = GHC.ForeignPtr.newConcForeignPtr addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO () -- ^This function adds a finalizer to the given @ForeignPtr@. The -- finalizer will run /before/ all other finalizers for the same -- object which have already been registered. -- -- This is a variant of @Foreign.ForeignPtr.addForeignPtrFinalizer@, -- where the finalizer is an arbitrary @IO@ action. When it is -- invoked, the finalizer will run in a new thread. -- -- NB. Be very careful with these finalizers. One common trap is that -- if a finalizer references another finalized value, it does not -- prevent that value from being finalized. In particular, 'Handle's -- are finalized objects, so a finalizer should not refer to a 'Handle' -- (including @stdout@, @stdin@ or @stderr@). -- addForeignPtrFinalizer = GHC.ForeignPtr.addForeignPtrConcFinalizer
ezyang/ghc
libraries/base/Foreign/Concurrent.hs
Haskell
bsd-3-clause
2,940
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Hpc -- Copyright : Thomas Tuegel 2011 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This module provides functions for locating various HPC-related paths and -- a function for adding the necessary options to a PackageDescription to -- build test suites with HPC enabled. module Distribution.Simple.Hpc ( Way(..), guessWay , htmlDir , mixDir , tixDir , tixFilePath , markupPackage , markupTest ) where import Control.Monad ( when ) import Distribution.ModuleName ( main ) import Distribution.PackageDescription ( TestSuite(..) , testModules ) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) ) import Distribution.Simple.Program ( hpcProgram , requireProgramVersion ) import Distribution.Simple.Program.Hpc ( markup, union ) import Distribution.Simple.Utils ( notice ) import Distribution.Version ( anyVersion ) import Distribution.Verbosity ( Verbosity() ) import System.Directory ( createDirectoryIfMissing, doesFileExist ) import System.FilePath -- ------------------------------------------------------------------------- -- Haskell Program Coverage data Way = Vanilla | Prof | Dyn deriving (Bounded, Enum, Eq, Read, Show) hpcDir :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Directory containing component's HPC .mix files hpcDir distPref way = distPref </> "hpc" </> wayDir where wayDir = case way of Vanilla -> "vanilla" Prof -> "prof" Dyn -> "dyn" mixDir :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name -> FilePath -- ^ Directory containing test suite's .mix files mixDir distPref way name = hpcDir distPref way </> "mix" </> name tixDir :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name -> FilePath -- ^ Directory containing test suite's .tix files tixDir distPref way name = hpcDir distPref way </> "tix" </> name -- | Path to the .tix file containing a test suite's sum statistics. tixFilePath :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name -> FilePath -- ^ Path to test suite's .tix file tixFilePath distPref way name = tixDir distPref way name </> name <.> "tix" htmlDir :: FilePath -- ^ \"dist/\" prefix -> Way -> FilePath -- ^ Component name -> FilePath -- ^ Path to test suite's HTML markup directory htmlDir distPref way name = hpcDir distPref way </> "html" </> name -- | Attempt to guess the way the test suites in this package were compiled -- and linked with the library so the correct module interfaces are found. guessWay :: LocalBuildInfo -> Way guessWay lbi | withProfExe lbi = Prof | withDynExe lbi = Dyn | otherwise = Vanilla -- | Generate the HTML markup for a test suite. markupTest :: Verbosity -> LocalBuildInfo -> FilePath -- ^ \"dist/\" prefix -> String -- ^ Library name -> TestSuite -> IO () markupTest verbosity lbi distPref libName suite = do tixFileExists <- doesFileExist $ tixFilePath distPref way $ testName suite when tixFileExists $ do -- behaviour of 'markup' depends on version, so we need *a* version -- but no particular one (hpc, hpcVer, _) <- requireProgramVersion verbosity hpcProgram anyVersion (withPrograms lbi) let htmlDir_ = htmlDir distPref way $ testName suite markup hpc hpcVer verbosity (tixFilePath distPref way $ testName suite) mixDirs htmlDir_ (testModules suite ++ [ main ]) notice verbosity $ "Test coverage report written to " ++ htmlDir_ </> "hpc_index" <.> "html" where way = guessWay lbi mixDirs = map (mixDir distPref way) [ testName suite, libName ] -- | Generate the HTML markup for all of a package's test suites. markupPackage :: Verbosity -> LocalBuildInfo -> FilePath -- ^ \"dist/\" prefix -> String -- ^ Library name -> [TestSuite] -> IO () markupPackage verbosity lbi distPref libName suites = do let tixFiles = map (tixFilePath distPref way . testName) suites tixFilesExist <- mapM doesFileExist tixFiles when (and tixFilesExist) $ do -- behaviour of 'markup' depends on version, so we need *a* version -- but no particular one (hpc, hpcVer, _) <- requireProgramVersion verbosity hpcProgram anyVersion (withPrograms lbi) let outFile = tixFilePath distPref way libName htmlDir' = htmlDir distPref way libName excluded = concatMap testModules suites ++ [ main ] createDirectoryIfMissing True $ takeDirectory outFile union hpc verbosity tixFiles outFile excluded markup hpc hpcVer verbosity outFile mixDirs htmlDir' excluded notice verbosity $ "Package coverage report written to " ++ htmlDir' </> "hpc_index.html" where way = guessWay lbi mixDirs = map (mixDir distPref way) $ libName : map testName suites
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/Distribution/Simple/Hpc.hs
Haskell
bsd-3-clause
5,350
module Thread ( ThreadTree (..) , ContM (..) , atom , stop , buildThread ) where ---------------------------------- data ThreadTree req rsp m = Atom (m (ThreadTree req rsp m)) | Stop ---------------------------------- newtype ContM req rsp m a = ContM ((a-> ThreadTree req rsp m)-> ThreadTree req rsp m) instance Functor (ContM req rsp m) where fmap = undefined instance Applicative (ContM req rsp m) where pure = undefined (<*>) = undefined instance Monad m => Monad (ContM req rsp m) where m >>= f = contmBind m f return = contmReturn contmBind :: (ContM req rsp m a) -> (a -> (ContM req rsp m b)) -> (ContM req rsp m b) contmBind (ContM x) f = ContM(\y-> x (\z-> let ContM f' = f z in f' y)) contmReturn :: a -> (ContM req rsp m a) contmReturn x = ContM(\c -> c x) {-- how to build primitive ContM blocks... --} atom :: Monad m => (m a) -> (ContM req rsp m a) atom mx = ContM( \c -> Atom( do x <- mx; return (c x) )) stop :: (ContM req rsp m a) stop = ContM( \c -> Stop ) buildThread :: (ContM req rsp m a) -> ThreadTree req rsp m buildThread (ContM f) = f (\c->Stop) ----------------------------------
ezyang/ghc
testsuite/tests/concurrent/prog002/Thread.hs
Haskell
bsd-3-clause
1,155
import qualified Graphics.UI.GLFW as GLFW import Graphics.GL import Data.Bits import Control.Monad import Linear import SetupGLFW import ShaderLoader import Cube ------------------------------------------------------------- -- A test to make sure our rendering works without the Oculus ------------------------------------------------------------- main :: IO a main = do let (resX, resY) = (1920, 1080) win <- setupGLFW "Cube" resX resY -- Scene rendering setup shader <- createShaderProgram "test/cube.v.glsl" "test/cube.f.glsl" cube <- makeCube shader glClearColor 0 0.1 0.1 1 glEnable GL_DEPTH_TEST forever $ mainLoop win shader cube mainLoop :: GLFW.Window -> GLProgram -> Cube -> IO () mainLoop win shader cube = do -- glGetErrors -- Get mouse/keyboard/OS events from GLFW GLFW.pollEvents -- Clear the framebuffer glClear ( GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT ) -- Normally we'd render something here beyond just clearing the screen to a color glUseProgram (fromIntegral (unGLProgram shader)) let projection = perspective 45 (1920/1080) 0.01 1000 model = mkTransformation 1 (V3 0 0 (-4)) view = lookAt (V3 0 2 0) (V3 0 0 (-4)) (V3 0 1 0) mvp = projection !*! view !*! model (x,y,w,h) = (0,0,1920,1080) glViewport x y w h renderCube cube mvp GLFW.swapBuffers win
lukexi/oculus-mini
test/TestCube.hs
Haskell
mit
1,441
import Control.Monad.Trans.State.Lazy tick :: State Int String tick = return "foo" tick2 :: State Int String tick2 = do s <- tick return $ s ++ "bar" tick3 = do s <- tick s2 <- tick2 s3 <- tick2 put 1600 return $ s3 type Stack = [Int] pop :: State Stack Int pop = do (x:xs) <- get put xs return x push :: Int -> State Stack () push a = do xs <- get put (a:xs) return () stackManip = do push 3 push 3 push 3 i <- pop push $ i*29 pop
nlim/haskell-playground
src/Statements.hs
Haskell
mit
620
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} -- module module Persistence (loadSession, saveSession) where -- imports import Control.Applicative import Control.Monad.Error import Control.Monad.State import Data.Aeson as A import Data.Aeson.Types as A import qualified Data.ByteString.Base64.Lazy as B import qualified Data.ByteString.Lazy as B import System.Directory import System.FilePath import System.IO (hFlush, stdout) import RCL -- exported functions loadSession :: (Functor m, MonadIO m) => FilePath -> String -> RTMT m () loadSession path app = do file <- liftIO $ getFile path app readFrom file `catchError` const createNew where readFrom file = do guard =<< liftIO (doesFileExist file) guard =<< liftIO (readable <$> getPermissions file) rsess <- liftIO (B.readFile file) >>= decodeSession guard =<< testToken (token rsess) put rsess saveSession :: (Functor m, MonadIO m) => FilePath -> String -> RTMT m () saveSession path app = do file <- liftIO $ getFile path app sess <- encodeSession <$> session liftIO $ B.writeFile file sess -- internal functions createNew :: (Functor m, MonadIO m) => RTMT m () createNew = do authUrl <- getAuthURL liftIO $ do putStrLn "Couldn't find authentification token" putStrLn $ "Please authorize RCL: " ++ authUrl putStr "(Press enter when done.)" hFlush stdout void getLine void updateToken line <- call (method "rtm.timelines.create") >>= extractM (.: "timeline") modify $ setTimeline line getFile :: FilePath -> String -> IO FilePath getFile path app = do dirName <- getAppUserDataDirectory app createDirectoryIfMissing True dirName return $ dirName </> path decodeSession :: MonadError Failure m => B.ByteString -> m Session decodeSession = either (throwError . strMsg) return . (B.decode >=> A.eitherDecode >=> parseJ) encodeSession :: Session -> B.ByteString encodeSession = B.encode . A.encode . toJ parseJ :: Value -> Either String Session parseJ = parseEither $ withObject "session object" $ \o -> do tk <- o .: "token" tl <- o .: "timeline" return $ Session tl tk "" toJ :: Session -> Value toJ s = object [ "timeline" .= timeline s, "token" .= token s ]
nicuveo/RCL
src/Persistence.hs
Haskell
mit
2,461
data Way = U | R | D | L deriving(Eq, Show) data Op = Op { opPiece :: Int , opCost :: Int , opWay :: [Way] } deriving(Eq, Show) type Field = [Int] swapCost = 1 choiceCost = 10 fieldWidth = 4 fieldHeight = 4 maxChoice = 3 magicNum = 0 goal = [0..24] :: [Int] fie = 1:2:0:[3..24] :: [Int] solver :: Field -> Field -> Int -> Int -> Way -> Maybe [Op] solver goalField field count piece way | goalField == field = Just [(Op (-1) 0 [])] -- 終端 | count > 5 = Nothing | piece' == Nothing = Nothing | (jw' - jw) < magicNum = Nothing | best == Nothing = Nothing | (length opx) + 1 > maxChoice = Nothing | opPiece(op) == pieceVal = Just ( (Op piece (opCost(op) + swapCost) (way:opWay(op))) : opx ) | otherwise = Just ( (Op piece (choiceCost + swapCost) [way]) : (op : opx)) where (Just (op:opx)) = best best = bestOp $ (choice goalField field' (count + 1)) : (map (solver goalField field' (count + 1) pieceVal) (genWay way)) field' = swapByIndex piece pieceVal field piece' = afterIndex piece way (Just pieceVal) = piece' jw = jwDist goalField field jw' = jwDist goalField field' choice :: Field -> Field -> Int -> Maybe [Op] choice goalField field count = bestOp $ mapNeo (map (solver goalField field count) (wrongList goalField field 0)) genWay :: Way -> [Way] genWay U = [U,R,L] genWay R = [U,R,D] genWay D = [R,D,L] genWay L = [U,D,L] {- tapleList :: a -> [b] -> [(a,b)] -> [(a,b)] tapleList _ [] list = list tapleList y x:xs list = (y,x) : tapleList y xs list -} mapNeo :: [(Way -> Maybe [Op])] -> [Maybe [Op]] mapNeo [] = [] mapNeo (f:fs) = (f U) : (f R) : (f D) : (f L) : (mapNeo fs) bestOp :: [Maybe [Op]] -> Maybe [Op] bestOp [] = Nothing bestOp [x] = x bestOp (x:xs) | x == Nothing = bestOp xs | (opCostTotal op) == 0 = x | otherwise = rase minOp x (bestOp xs) where (Just op) = x minOp :: [Op] -> [Op] -> [Op] minOp xs ys | xsCost < ysCost = xs | otherwise = ys where xsCost = sum $ map opCost xs ysCost = sum $ map opCost ys opCostTotal :: [Op] -> Int opCostTotal ops = sum $ map opCost ops rase :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a rase f (Just a) (Just b) = Just (f a b) rase _ (Just a) Nothing = Just a rase _ Nothing (Just b) = Just b rase _ Nothing Nothing = Nothing swap :: Int -> Way -> Field -> Maybe Field swap piece way field = case (afterIndex piece way) of (Just piece') -> Just $ swapByIndex piece piece' field (Nothing) -> Nothing afterIndex :: Int -> Way -> Maybe Int afterIndex index way | way == U = if afterU >= 0 then Just afterU else Nothing | way == R = if (mod index fieldWidth) + 1 < fieldWidth then Just $ index + 1 else Nothing | way == D = if afterD < fieldLength then Just afterD else Nothing | way == L = if (mod index fieldWidth) - 1 >= 0 then Just $ index - 1 else Nothing where fieldLength = fieldWidth * fieldHeight afterU = index - fieldWidth afterD = index + fieldWidth swapByIndex :: Int -> Int -> Field -> Field swapByIndex i j xs = reverse $ fst $ foldl f ([],0) xs where f (acc, idx) x | idx == i = (xs!!j:acc, idx+1) | idx == j = (xs!!i:acc, idx+1) | otherwise = (x:acc, idx+1) wrongList :: (Eq a) => [a] -> [a] -> Int -> [Int] wrongList [] _ _ = [] wrongList _ [] _ = [] wrongList (x:xs) (y:ys) count | x == y = wrongList xs ys (count + 1) | otherwise = count : (wrongList xs ys (count + 1)) tJW :: (Eq a) => [a] -> [a] -> Float tJW [] _ = 0 tJW _ [] = 0 tJW (x:xs) (y:ys) | x == y = tJW xs ys | otherwise = (tJW xs ys) + 1 jwDist :: (Eq a) => [a] -> [a] -> Float jwDist x y = (2 + (m - t) / m ) / 3 where m = fromIntegral( length(x) ) :: Float t = (tJW x y) / 2
inct-www-club/Procon2014
src/solver.hs
Haskell
mit
3,874
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} -- for the client: export those types needed for playnow module Game.Play.Api.Types where import Control.Lens.TH (makeLenses) import Data.Aeson (FromJSON, ToJSON) import GHC.Generics (Generic) import Servant.Docs (ToSample (..), singleSample) import Game.Api.Types (AuthInfo, sampleAuthInfo) import Game.Types (CardKind (..)) data PlayCardRq = PlayCardRq { _pcrqCardKind :: CardKind , _pcrqAuth :: AuthInfo } deriving (Generic, FromJSON, ToJSON) instance ToSample PlayCardRq where toSamples _ = let _pcrqCardKind = Plain _pcrqAuth = sampleAuthInfo in singleSample PlayCardRq{..} data PlaceBetRq = PlaceBetRq { _pbrqValue :: Int , _pbrqAuth :: AuthInfo } deriving (Generic, FromJSON, ToJSON) instance ToSample PlaceBetRq where toSamples _ = let _pbrqValue = 3 _pbrqAuth = sampleAuthInfo in singleSample PlaceBetRq{..} makeLenses ''PlayCardRq makeLenses ''PlaceBetRq
rubenmoor/skull
skull-server/src/Game/Play/Api/Types.hs
Haskell
mit
1,138
module ProjectEuler.Problem56 ( problem ) where import Data.List import ProjectEuler.Types problem :: Problem problem = pureProblem 56 Solved result digitSum :: Integer -> Int digitSum = sum . unfoldr f where f 0 = Nothing f n = let (q,r) = n `quotRem` 10 in Just (fromIntegral r, q) result :: Int result = maximum [ digitSum (a^b) | a <- [1..100], b <- [1..100 :: Int]]
Javran/Project-Euler
src/ProjectEuler/Problem56.hs
Haskell
mit
389
-- | <http://strava.github.io/api/v3/activities/> module Strive.Actions.Activities ( createActivity , getActivity , updateActivity , deleteActivity , getCurrentActivities , getRelatedActivities , getFeed , getActivityZones , getActivityLaps ) where import Data.Aeson (encode) import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy (toStrict) import Network.HTTP.Client (responseBody, responseStatus) import Network.HTTP.Types (Query, methodDelete, noContent204, toQuery) import Strive.Aliases (ActivityId, ElapsedTime, Name, Result, StartTime) import Strive.Client (Client) import Strive.Enums (ActivityType) import Strive.Internal.HTTP (buildRequest, get, performRequest, post, put) import Strive.Options ( CreateActivityOptions , GetActivityOptions , GetCurrentActivitiesOptions , GetFeedOptions , GetRelatedActivitiesOptions , UpdateActivityOptions ) import Strive.Types (ActivityDetailed, ActivityLapSummary, ActivitySummary, ActivityZoneDetailed) -- | <http://strava.github.io/api/v3/activities/#create> createActivity :: Client -> Name -> ActivityType -> StartTime -> ElapsedTime -> CreateActivityOptions -> IO (Result ActivityDetailed) createActivity client name type_ startDateLocal elapsedTime options = post client resource query where resource = "api/v3/activities" query = toQuery [ ("name", name) , ("type", show type_) , ("start_date_local", unpack (toStrict (encode startDateLocal))) , ("elapsed_time", show elapsedTime) ] <> toQuery options -- | <http://strava.github.io/api/v3/activities/#get-details> getActivity :: Client -> ActivityId -> GetActivityOptions -> IO (Result ActivitySummary) getActivity client activityId options = get client resource query where resource = "api/v3/activities/" <> show activityId query = toQuery options -- | <http://strava.github.io/api/v3/activities/#put-updates> updateActivity :: Client -> ActivityId -> UpdateActivityOptions -> IO (Result ActivityDetailed) updateActivity client activityId options = put client resource query where resource = "api/v3/activities/" <> show activityId query = toQuery options -- | <http://strava.github.io/api/v3/activities/#delete> deleteActivity :: Client -> ActivityId -> IO (Result ()) deleteActivity client activityId = do request <- buildRequest methodDelete client resource query response <- performRequest client request return (if responseStatus response == noContent204 then Right () else Left (response, unpack (toStrict (responseBody response))) ) where resource = "api/v3/activities/" <> show activityId query = [] :: Query -- | <http://strava.github.io/api/v3/activities/#get-activities> getCurrentActivities :: Client -> GetCurrentActivitiesOptions -> IO (Result [ActivitySummary]) getCurrentActivities client options = get client resource query where resource = "api/v3/athlete/activities" query = toQuery options -- | <http://strava.github.io/api/v3/activities/#get-related> getRelatedActivities :: Client -> ActivityId -> GetRelatedActivitiesOptions -> IO (Result [ActivitySummary]) getRelatedActivities client activityId options = get client resource query where resource = "api/v3/activities/" <> show activityId <> "/related" query = toQuery options -- | <http://strava.github.io/api/v3/activities/#get-feed> getFeed :: Client -> GetFeedOptions -> IO (Result [ActivitySummary]) getFeed client options = get client resource query where resource = "api/v3/activities/following" query = toQuery options -- | <http://strava.github.io/api/v3/activities/#zones> getActivityZones :: Client -> ActivityId -> IO (Result [ActivityZoneDetailed]) getActivityZones client activityId = get client resource query where resource = "api/v3/activities/" <> show activityId <> "/zones" query = [] :: Query -- | <http://strava.github.io/api/v3/activities/#laps> getActivityLaps :: Client -> ActivityId -> IO (Result [ActivityLapSummary]) getActivityLaps client activityId = get client resource query where resource = "api/v3/activities/" <> show activityId <> "/laps" query = [] :: Query
tfausak/strive
source/library/Strive/Actions/Activities.hs
Haskell
mit
4,194
module Data.Bson.Binary.Tests ( tests ) where import Data.Binary (encode, decode) import Test.Tasty (TestTree, testGroup) import Test.Tasty.QuickCheck (testProperty) import Data.Bson (Document) import Data.Bson.Binary () import Data.Bson.Tests.Instances () testEncodeDecodeDocument :: Document -> Bool testEncodeDecodeDocument doc = (==) doc $ decode $ encode doc tests :: TestTree tests = testGroup "Data.Bson.Binary.Tests" [ testProperty "testEncodeDecodeDocument" testEncodeDecodeDocument ]
lambda-llama/bresson
tests/Data/Bson/Binary/Tests.hs
Haskell
mit
515
{-# LANGUAGE DeriveGeneric #-} module Test.SimpleTable where import DB.Model.SimpleTable import qualified DB.Model.SimpleTable as S import DB.Model.MultiTable (MultiTable) import qualified DB.Model.MultiTable as M import Test.Hspec data Test m = Test { key :: m Int, f :: m String, c :: m String, n :: m String } deriving (Generic) instance SimpleTable Test where relation = Test { key = S.IsKey "Test" "id", f = S.IsCol "f", c = S.IsConst "c", n = S.IsNull } test :: IO () test = hspec $ do it "Convert Table.relation to MultiTable.relation" $ do let expect = Test { key = M.IsKey [("Test", "id")], f = M.IsCol "Test" "f", c = M.IsConst "c", n = M.IsNull } M.relation `shouldBe` expect
YLiLarry/db-model
test/Test/SimpleTable.hs
Haskell
mit
837
module LispLovesMe where import Text.ParserCombinators.Parsec hiding (spaces) import Data.List (intercalate) data AST = I32 Int | Sym String | Nul | Err | Lst [AST] | Boo Bool | Nod AST [AST] deriving (Eq, Show) spaces :: Parser String spaces = many $ oneOf " ,\r\n\t" spaces1 :: Parser String spaces1 = many1 $ oneOf " ,\r\n\t" parseLisp :: Parser AST parseLisp = try parseNod <|> parseExpr parseNod :: Parser AST parseNod = do spaces char '(' e <- spaces *> parseExpr <* spaces es <- parseExpr `sepEndBy` spaces spaces char ')' spaces return $ Nod e es parseExpr :: Parser AST parseExpr = spaces *> (try parseBoolean <|> try parseNull <|> parseSymbol <|> parseNumber <|> parseNod) <* spaces where parseSymbol = do s <- noneOf $ " ,\n\t\r()" ++ [ '0' .. '9' ] ss <- many $ noneOf " ,\n\t\r()" return $ Sym (s:ss) parseNumber = I32 . read <$> many1 digit parseBoolean = (string "true" *> return (Boo True)) <|> (string "false" *> return (Boo False)) parseNull = (string "()" <|> string "null") *> return Nul -- if Err eval :: AST -> AST eval (Nod (Sym f) es) = case f `lookup` preludeFunctions of Nothing -> Err Just func -> func es eval (Nod _ _) = Err eval (Lst as) = Lst (map eval as) eval x = x is_i32 :: AST -> Bool is_i32 (I32 _) = True is_i32 _ = False is_bool :: AST -> Bool is_bool (Boo _) = True is_bool _ = False is_list :: AST -> Bool is_list (Lst _) = True is_list _ = False seq_op :: (Int -> Int -> Int) -> [AST] -> AST seq_op f es = let vs = map eval es in if all is_i32 vs then foldl1 (\(I32 x) (I32 y) -> I32 (f x y)) vs else Err bin_op :: (Int -> Int -> Bool) -> [AST] -> AST bin_op f es | length es /= 2 = Err | otherwise = let vs = map eval es in if all is_i32 vs then let (I32 x) = head vs (I32 y) = last vs in Boo (f x y) else Err cond :: [AST] -> AST cond es | length es < 2 = Err | otherwise = let (a:b:c) = map eval es in if is_bool a then let (Boo cc) = a in if cc then b else if null c then Nul else head c else Err no :: [AST] -> AST no es | length es /= 1 = Err | otherwise = let v = eval (head es) in if is_bool v then let (Boo x) = v in Boo (not x) else Err range :: [AST] -> AST range es | length es /= 2 = Err | otherwise = let vs@[v1, v2] = map eval es in if all is_i32 vs then let (I32 x) = v1 (I32 y) = v2 in Lst $ I32 <$> [x .. y] else Err size :: [AST] -> AST size es | length es /= 1 = Err | otherwise = let v = eval (head es) in if is_list v then let (Lst ls) = v in I32 (length ls) else Err rev :: [AST] -> AST rev es | length es /= 1 = Err | otherwise = let v = eval (head es) in if is_list v then let (Lst ls) = v in Lst (reverse ls) else Err preludeFunctions :: [(String, [AST] -> AST)] preludeFunctions = [ ("+", seq_op (+)) , ("*", seq_op (*)) , ("-", seq_op (-)) , ("/", seq_op div) , ("^", seq_op (^)) , (">", bin_op (>)) , ("<", bin_op (<)) , ("!", no) , ("list", Lst) , ("size", size) , ("reverse", rev) , ("..", range) , ("==", bin_op (==)) , (">=", bin_op (>=)) , ("<=", bin_op (<=)) , ("!=", bin_op (/=)) , ("if", cond) ] lisp2s :: AST -> String lisp2s (I32 i) = show i lisp2s (Sym s) = s lisp2s Nul = "null" lisp2s (Boo True) = "true" lisp2s (Boo False) = "false" lisp2s (Nod e es) = "(" ++ intercalate " " (map lisp2s (e:es)) ++ ")" lispPretty :: String -> Maybe String lispPretty s = case parse (parseLisp <* eof) "" s of Left _ -> Nothing Right ast -> Just $ lisp2s ast lispEval :: String -> Maybe AST lispEval s = case parse (parseLisp <* eof) "" s of Left _ -> Nothing Right ast -> Just (eval ast)
delta4d/codewars
kata/i-love-lisp/LispLovesMe.hs
Haskell
mit
4,742
{-# LANGUAGE OverloadedStrings #-} module System.PassengerCheck.HealthSpec (spec) where import Test.Hspec import System.PassengerCheck.Types import System.PassengerCheck.Health import System.Nagios.Plugin (CheckStatus(..)) spec :: Spec spec = do describe "queuedRequests" $ it "returns the number of queued requests" $ queuedRequests (PassengerStatus 15 2 3 [4, 5]) `shouldBe` 12 describe "status" $ do it "returns Critical when the queue is >= 90% full" $ status (PassengerStatus 10 2 7 [1, 1]) `shouldBe` (Critical, "Queue is at or above 90% full") it "returns Warning when the queue is >= 50% full" $ status (PassengerStatus 10 2 3 [1, 1]) `shouldBe` (Warning, "Queue is at or above 50% full") it "returns OK when the queue is < 50% full" $ status (PassengerStatus 10 2 1 [0, 0]) `shouldBe` (OK, "Queue is less than 50% full")
stackbuilders/passenger-check
spec/System/PassengerCheck/HealthSpec.hs
Haskell
mit
906
{- | Module : Main Copyright : Justin Ethier Licence : MIT (see LICENSE in the distribution) Maintainer : github.com/justinethier Stability : experimental Portability : portable This file implements a REPL /shell/ to host the interpreter, and also allows execution of stand-alone files containing Scheme code. -} module Main where import qualified Language.Scheme.Core as LSC -- Scheme Interpreter import Language.Scheme.Types -- Scheme data types import qualified Language.Scheme.Util as LSU (countAllLetters, countLetters, strip) import qualified Language.Scheme.Variables as LSV -- Scheme variable operations import Control.Monad.Except import qualified Data.Char as DC import qualified Data.List as DL import Data.Maybe (fromMaybe) import System.Console.GetOpt import qualified System.Console.Haskeline as HL import qualified System.Console.Haskeline.Completion as HLC import System.Environment import System.Exit (exitSuccess) import System.IO main :: IO () main = do args <- getArgs let (actions, nonOpts, _) = getOpt Permute options args opts <- foldl (>>=) (return defaultOptions) actions let Options {optInter = interactive, optSchemeRev = schemeRev} = opts if null nonOpts then do LSC.showBanner env <- liftIO $ getRuntimeEnv schemeRev runRepl env else do runOne (getRuntimeEnv schemeRev) nonOpts interactive -- -- Command line options section -- data Options = Options { optInter :: Bool, optSchemeRev :: String -- RxRS version } -- |Default values for the command line options defaultOptions :: Options defaultOptions = Options { optInter = False, optSchemeRev = "5" } options :: [OptDescr (Options -> IO Options)] options = [ Option ['i'] ["interactive"] (NoArg getInter) "load file and run REPL", Option ['r'] ["revision"] (ReqArg writeRxRSVersion "Scheme") "scheme RxRS version", Option ['h', '?'] ["help"] (NoArg showHelp) "show usage information" ] where getInter opt = return opt { optInter = True } writeRxRSVersion arg opt = return opt { optSchemeRev = arg } showHelp :: Options -> IO Options showHelp _ = do putStrLn "Usage: huski [options] [file]" putStrLn "" putStrLn " huski is the husk scheme interpreter." putStrLn "" putStrLn " File is a scheme source file to execute. If no file is specified" putStrLn " the husk REPL will be started." putStrLn "" putStrLn " Options may be any of the following:" putStrLn "" putStrLn " -h, --help Display this information" putStrLn " -i Start interactive REPL after file is executed. This" putStrLn " option has no effect if a file is not specified. " -- putStrLn " --revision rev Specify the scheme revision to use:" -- putStrLn "" -- putStrLn " 5 - r5rs (default)" -- putStrLn " 7 - r7rs small" putStrLn "" exitSuccess -- -- REPL Section -- flushStr :: String -> IO () flushStr str = putStr str >> hFlush stdout getRuntimeEnv :: String -> IO Env getRuntimeEnv "7" = LSC.r7rsEnv getRuntimeEnv _ = LSC.r5rsEnv -- |Execute a single scheme file from the command line runOne :: IO Env -> [String] -> Bool -> IO () runOne initEnv args interactive = do env <- initEnv >>= flip LSV.extendEnv [((LSV.varNamespace, "args"), List $ map String $ drop 1 args)] result <- (LSC.runIOThrows $ liftM show $ LSC.evalLisp env (List [Atom "load", String (head args)])) _ <- case result of Just errMsg -> putStrLn errMsg _ -> do -- Call into (main) if it exists... alreadyDefined <- liftIO $ LSV.isBound env "main" let argv = List $ map String args when alreadyDefined (do mainResult <- (LSC.runIOThrows $ liftM show $ LSC.evalLisp env (List [Atom "main", List [Atom "quote", argv]])) case mainResult of Just errMsg -> putStrLn errMsg _ -> return ()) when interactive (do runRepl env) -- |Start the REPL (interactive interpreter) runRepl :: Env -> IO () runRepl env' = do let settings = HL.Settings (completeScheme env') Nothing True HL.runInputT settings (loop env') where -- Main REPL loop loop :: Env -> HL.InputT IO () loop env = do minput <- HL.getInputLine "huski> " case minput of Nothing -> return () Just i -> do case LSU.strip i of "quit" -> return () "" -> loop env -- ignore inputs of just whitespace input -> do inputLines <- getMultiLine [input] let input' = unlines inputLines result <- liftIO (LSC.evalString env input') if not (null result) then do HL.outputStrLn result loop env else loop env -- Read another input line, if necessary getMultiLine previous = do if test previous then do mb_input <- HL.getInputLine "" case mb_input of Nothing -> return previous Just input -> getMultiLine $ previous ++ [input] else return previous -- Check if we need another input line -- This just does a bare minimum, and could be more robust test ls = do let cOpen = LSU.countAllLetters '(' ls cClose = LSU.countAllLetters ')' ls cOpen > cClose -- |Auto-complete using scheme symbols completeScheme :: Env -> (String, String) -> IO (String, [HLC.Completion]) -- Right after a ')' it seems more useful to autocomplete next closed parenthesis completeScheme _ (lnL@(')':_), _) = do let cOpen = LSU.countLetters '(' lnL cClose = LSU.countLetters ')' lnL if cOpen > cClose then return (lnL, [HL.Completion ")" ")" False]) else return (lnL, []) completeScheme env (lnL, lnR) = do complete $ reverse $ readAtom lnL where complete ('"' : _) = do -- Special case, inside a string it seems more -- useful to autocomplete filenames liftIO $ HLC.completeFilename (lnL, lnR) complete pre = do -- Get list of possible completions from ENV xps <- LSV.recExportsFromEnv env let allDefs = xps ++ specialForms let allDefs' = filter (\ (Atom a) -> DL.isPrefixOf pre a) allDefs let comps = map (\ (Atom a) -> HL.Completion a a False) allDefs' -- Get unused portion of the left-hand string let unusedLnL = fromMaybe lnL (DL.stripPrefix (reverse pre) lnL) return (unusedLnL, comps) -- Not loaded into an env, so we need to list them here specialForms = map Atom [ "define" , "define-syntax" , "expand" , "hash-table-delete!" , "hash-table-set!" , "if" , "lambda" , "let-syntax" , "letrec-syntax" , "quote" , "set!" , "set-car!" , "set-cdr!" , "string-set!" , "vector-set!"] -- Read until the end of the current symbol (atom), if there is one. -- There is also a special case for files if a double-quote is found. readAtom (c:cs) | c == '"' = ['"'] -- Save to indicate file completion to caller | c == '(' = [] | c == '[' = [] | DC.isSpace c = [] | otherwise = (c : readAtom cs) readAtom [] = []
justinethier/husk-scheme
hs-src/Interpreter/shell.hs
Haskell
mit
7,473
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Api.MimeTypes ( Markdown ) where import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Media ((//), (/:)) import Servant as S data Markdown instance S.Accept Markdown where contentType _ = "text" // "markdown" /: ("charset", "utf-8") instance S.MimeRender Markdown Text where mimeRender _ text = LBS.fromStrict (encodeUtf8 text)
gust/feature-creature
legacy/lib/Api/MimeTypes.hs
Haskell
mit
497
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLInputElement (js_stepUp, stepUp, js_stepDown, stepDown, js_checkValidity, checkValidity, js_setCustomValidity, setCustomValidity, js_select, select, js_setRangeText, setRangeText, js_setRangeText4, setRangeText4, js_setSelectionRange, setSelectionRange, js_setAccept, setAccept, js_getAccept, getAccept, js_setAlt, setAlt, js_getAlt, getAlt, js_setAutocomplete, setAutocomplete, js_getAutocomplete, getAutocomplete, js_setAutofocus, setAutofocus, js_getAutofocus, getAutofocus, js_setDefaultChecked, setDefaultChecked, js_getDefaultChecked, getDefaultChecked, js_setChecked, setChecked, js_getChecked, getChecked, js_setDirName, setDirName, js_getDirName, getDirName, js_setDisabled, setDisabled, js_getDisabled, getDisabled, js_getForm, getForm, js_setFiles, setFiles, js_getFiles, getFiles, js_setFormAction, setFormAction, js_getFormAction, getFormAction, js_setFormEnctype, setFormEnctype, js_getFormEnctype, getFormEnctype, js_setFormMethod, setFormMethod, js_getFormMethod, getFormMethod, js_setFormNoValidate, setFormNoValidate, js_getFormNoValidate, getFormNoValidate, js_setFormTarget, setFormTarget, js_getFormTarget, getFormTarget, js_setHeight, setHeight, js_getHeight, getHeight, js_setIndeterminate, setIndeterminate, js_getIndeterminate, getIndeterminate, js_getList, getList, js_setMax, setMax, js_getMax, getMax, js_setMaxLength, setMaxLength, js_getMaxLength, getMaxLength, js_setMin, setMin, js_getMin, getMin, js_setMultiple, setMultiple, js_getMultiple, getMultiple, js_setName, setName, js_getName, getName, js_setPattern, setPattern, js_getPattern, getPattern, js_setPlaceholder, setPlaceholder, js_getPlaceholder, getPlaceholder, js_setReadOnly, setReadOnly, js_getReadOnly, getReadOnly, js_setRequired, setRequired, js_getRequired, getRequired, js_setSize, setSize, js_getSize, getSize, js_setSrc, setSrc, js_getSrc, getSrc, js_setStep, setStep, js_getStep, getStep, js_setType, setType, js_getType, getType, js_setDefaultValue, setDefaultValue, js_getDefaultValue, getDefaultValue, js_setValue, setValue, js_getValue, getValue, js_setValueAsDate, setValueAsDate, js_getValueAsDate, getValueAsDate, js_setValueAsNumber, setValueAsNumber, js_getValueAsNumber, getValueAsNumber, js_setWidth, setWidth, js_getWidth, getWidth, js_getWillValidate, getWillValidate, js_getValidity, getValidity, js_getValidationMessage, getValidationMessage, js_getLabels, getLabels, js_setSelectionStart, setSelectionStart, js_getSelectionStart, getSelectionStart, js_setSelectionEnd, setSelectionEnd, js_getSelectionEnd, getSelectionEnd, js_setSelectionDirection, setSelectionDirection, js_getSelectionDirection, getSelectionDirection, js_setAlign, setAlign, js_getAlign, getAlign, js_setUseMap, setUseMap, js_getUseMap, getUseMap, js_setIncremental, setIncremental, js_getIncremental, getIncremental, js_setAutocorrect, setAutocorrect, js_getAutocorrect, getAutocorrect, js_setAutocapitalize, setAutocapitalize, js_getAutocapitalize, getAutocapitalize, js_setCapture, setCapture, js_getCapture, getCapture, HTMLInputElement, castToHTMLInputElement, gTypeHTMLInputElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"stepUp\"]($2)" js_stepUp :: JSRef HTMLInputElement -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.stepUp Mozilla HTMLInputElement.stepUp documentation> stepUp :: (MonadIO m) => HTMLInputElement -> Int -> m () stepUp self n = liftIO (js_stepUp (unHTMLInputElement self) n) foreign import javascript unsafe "$1[\"stepDown\"]($2)" js_stepDown :: JSRef HTMLInputElement -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.stepDown Mozilla HTMLInputElement.stepDown documentation> stepDown :: (MonadIO m) => HTMLInputElement -> Int -> m () stepDown self n = liftIO (js_stepDown (unHTMLInputElement self) n) foreign import javascript unsafe "($1[\"checkValidity\"]() ? 1 : 0)" js_checkValidity :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checkValidity Mozilla HTMLInputElement.checkValidity documentation> checkValidity :: (MonadIO m) => HTMLInputElement -> m Bool checkValidity self = liftIO (js_checkValidity (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"setCustomValidity\"]($2)" js_setCustomValidity :: JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setCustomValidity Mozilla HTMLInputElement.setCustomValidity documentation> setCustomValidity :: (MonadIO m, ToJSString error) => HTMLInputElement -> Maybe error -> m () setCustomValidity self error = liftIO (js_setCustomValidity (unHTMLInputElement self) (toMaybeJSString error)) foreign import javascript unsafe "$1[\"select\"]()" js_select :: JSRef HTMLInputElement -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.select Mozilla HTMLInputElement.select documentation> select :: (MonadIO m) => HTMLInputElement -> m () select self = liftIO (js_select (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"setRangeText\"]($2)" js_setRangeText :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setRangeText Mozilla HTMLInputElement.setRangeText documentation> setRangeText :: (MonadIO m, ToJSString replacement) => HTMLInputElement -> replacement -> m () setRangeText self replacement = liftIO (js_setRangeText (unHTMLInputElement self) (toJSString replacement)) foreign import javascript unsafe "$1[\"setRangeText\"]($2, $3, $4,\n$5)" js_setRangeText4 :: JSRef HTMLInputElement -> JSString -> Word -> Word -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setRangeText Mozilla HTMLInputElement.setRangeText documentation> setRangeText4 :: (MonadIO m, ToJSString replacement, ToJSString selectionMode) => HTMLInputElement -> replacement -> Word -> Word -> selectionMode -> m () setRangeText4 self replacement start end selectionMode = liftIO (js_setRangeText4 (unHTMLInputElement self) (toJSString replacement) start end (toJSString selectionMode)) foreign import javascript unsafe "$1[\"setSelectionRange\"]($2, $3,\n$4)" js_setSelectionRange :: JSRef HTMLInputElement -> Int -> Int -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setSelectionRange Mozilla HTMLInputElement.setSelectionRange documentation> setSelectionRange :: (MonadIO m, ToJSString direction) => HTMLInputElement -> Int -> Int -> direction -> m () setSelectionRange self start end direction = liftIO (js_setSelectionRange (unHTMLInputElement self) start end (toJSString direction)) foreign import javascript unsafe "$1[\"accept\"] = $2;" js_setAccept :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.accept Mozilla HTMLInputElement.accept documentation> setAccept :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setAccept self val = liftIO (js_setAccept (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"accept\"]" js_getAccept :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.accept Mozilla HTMLInputElement.accept documentation> getAccept :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getAccept self = liftIO (fromJSString <$> (js_getAccept (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"alt\"] = $2;" js_setAlt :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.alt Mozilla HTMLInputElement.alt documentation> setAlt :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setAlt self val = liftIO (js_setAlt (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"alt\"]" js_getAlt :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.alt Mozilla HTMLInputElement.alt documentation> getAlt :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getAlt self = liftIO (fromJSString <$> (js_getAlt (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"autocomplete\"] = $2;" js_setAutocomplete :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocomplete Mozilla HTMLInputElement.autocomplete documentation> setAutocomplete :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setAutocomplete self val = liftIO (js_setAutocomplete (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"autocomplete\"]" js_getAutocomplete :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocomplete Mozilla HTMLInputElement.autocomplete documentation> getAutocomplete :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getAutocomplete self = liftIO (fromJSString <$> (js_getAutocomplete (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"autofocus\"] = $2;" js_setAutofocus :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autofocus Mozilla HTMLInputElement.autofocus documentation> setAutofocus :: (MonadIO m) => HTMLInputElement -> Bool -> m () setAutofocus self val = liftIO (js_setAutofocus (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"autofocus\"] ? 1 : 0)" js_getAutofocus :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autofocus Mozilla HTMLInputElement.autofocus documentation> getAutofocus :: (MonadIO m) => HTMLInputElement -> m Bool getAutofocus self = liftIO (js_getAutofocus (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"defaultChecked\"] = $2;" js_setDefaultChecked :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultChecked Mozilla HTMLInputElement.defaultChecked documentation> setDefaultChecked :: (MonadIO m) => HTMLInputElement -> Bool -> m () setDefaultChecked self val = liftIO (js_setDefaultChecked (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"defaultChecked\"] ? 1 : 0)" js_getDefaultChecked :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultChecked Mozilla HTMLInputElement.defaultChecked documentation> getDefaultChecked :: (MonadIO m) => HTMLInputElement -> m Bool getDefaultChecked self = liftIO (js_getDefaultChecked (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"checked\"] = $2;" js_setChecked :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checked Mozilla HTMLInputElement.checked documentation> setChecked :: (MonadIO m) => HTMLInputElement -> Bool -> m () setChecked self val = liftIO (js_setChecked (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"checked\"] ? 1 : 0)" js_getChecked :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checked Mozilla HTMLInputElement.checked documentation> getChecked :: (MonadIO m) => HTMLInputElement -> m Bool getChecked self = liftIO (js_getChecked (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"dirName\"] = $2;" js_setDirName :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.dirName Mozilla HTMLInputElement.dirName documentation> setDirName :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setDirName self val = liftIO (js_setDirName (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"dirName\"]" js_getDirName :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.dirName Mozilla HTMLInputElement.dirName documentation> getDirName :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getDirName self = liftIO (fromJSString <$> (js_getDirName (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"disabled\"] = $2;" js_setDisabled :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.disabled Mozilla HTMLInputElement.disabled documentation> setDisabled :: (MonadIO m) => HTMLInputElement -> Bool -> m () setDisabled self val = liftIO (js_setDisabled (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"disabled\"] ? 1 : 0)" js_getDisabled :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.disabled Mozilla HTMLInputElement.disabled documentation> getDisabled :: (MonadIO m) => HTMLInputElement -> m Bool getDisabled self = liftIO (js_getDisabled (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"form\"]" js_getForm :: JSRef HTMLInputElement -> IO (JSRef HTMLFormElement) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.form Mozilla HTMLInputElement.form documentation> getForm :: (MonadIO m) => HTMLInputElement -> m (Maybe HTMLFormElement) getForm self = liftIO ((js_getForm (unHTMLInputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"files\"] = $2;" js_setFiles :: JSRef HTMLInputElement -> JSRef FileList -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation> setFiles :: (MonadIO m) => HTMLInputElement -> Maybe FileList -> m () setFiles self val = liftIO (js_setFiles (unHTMLInputElement self) (maybe jsNull pToJSRef val)) foreign import javascript unsafe "$1[\"files\"]" js_getFiles :: JSRef HTMLInputElement -> IO (JSRef FileList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation> getFiles :: (MonadIO m) => HTMLInputElement -> m (Maybe FileList) getFiles self = liftIO ((js_getFiles (unHTMLInputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"formAction\"] = $2;" js_setFormAction :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formAction Mozilla HTMLInputElement.formAction documentation> setFormAction :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setFormAction self val = liftIO (js_setFormAction (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"formAction\"]" js_getFormAction :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formAction Mozilla HTMLInputElement.formAction documentation> getFormAction :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getFormAction self = liftIO (fromJSString <$> (js_getFormAction (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"formEnctype\"] = $2;" js_setFormEnctype :: JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formEnctype Mozilla HTMLInputElement.formEnctype documentation> setFormEnctype :: (MonadIO m, ToJSString val) => HTMLInputElement -> Maybe val -> m () setFormEnctype self val = liftIO (js_setFormEnctype (unHTMLInputElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"formEnctype\"]" js_getFormEnctype :: JSRef HTMLInputElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formEnctype Mozilla HTMLInputElement.formEnctype documentation> getFormEnctype :: (MonadIO m, FromJSString result) => HTMLInputElement -> m (Maybe result) getFormEnctype self = liftIO (fromMaybeJSString <$> (js_getFormEnctype (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"formMethod\"] = $2;" js_setFormMethod :: JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formMethod Mozilla HTMLInputElement.formMethod documentation> setFormMethod :: (MonadIO m, ToJSString val) => HTMLInputElement -> Maybe val -> m () setFormMethod self val = liftIO (js_setFormMethod (unHTMLInputElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"formMethod\"]" js_getFormMethod :: JSRef HTMLInputElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formMethod Mozilla HTMLInputElement.formMethod documentation> getFormMethod :: (MonadIO m, FromJSString result) => HTMLInputElement -> m (Maybe result) getFormMethod self = liftIO (fromMaybeJSString <$> (js_getFormMethod (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"formNoValidate\"] = $2;" js_setFormNoValidate :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formNoValidate Mozilla HTMLInputElement.formNoValidate documentation> setFormNoValidate :: (MonadIO m) => HTMLInputElement -> Bool -> m () setFormNoValidate self val = liftIO (js_setFormNoValidate (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"formNoValidate\"] ? 1 : 0)" js_getFormNoValidate :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formNoValidate Mozilla HTMLInputElement.formNoValidate documentation> getFormNoValidate :: (MonadIO m) => HTMLInputElement -> m Bool getFormNoValidate self = liftIO (js_getFormNoValidate (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"formTarget\"] = $2;" js_setFormTarget :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formTarget Mozilla HTMLInputElement.formTarget documentation> setFormTarget :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setFormTarget self val = liftIO (js_setFormTarget (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"formTarget\"]" js_getFormTarget :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formTarget Mozilla HTMLInputElement.formTarget documentation> getFormTarget :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getFormTarget self = liftIO (fromJSString <$> (js_getFormTarget (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"height\"] = $2;" js_setHeight :: JSRef HTMLInputElement -> Word -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.height Mozilla HTMLInputElement.height documentation> setHeight :: (MonadIO m) => HTMLInputElement -> Word -> m () setHeight self val = liftIO (js_setHeight (unHTMLInputElement self) val) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: JSRef HTMLInputElement -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.height Mozilla HTMLInputElement.height documentation> getHeight :: (MonadIO m) => HTMLInputElement -> m Word getHeight self = liftIO (js_getHeight (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"indeterminate\"] = $2;" js_setIndeterminate :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.indeterminate Mozilla HTMLInputElement.indeterminate documentation> setIndeterminate :: (MonadIO m) => HTMLInputElement -> Bool -> m () setIndeterminate self val = liftIO (js_setIndeterminate (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"indeterminate\"] ? 1 : 0)" js_getIndeterminate :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.indeterminate Mozilla HTMLInputElement.indeterminate documentation> getIndeterminate :: (MonadIO m) => HTMLInputElement -> m Bool getIndeterminate self = liftIO (js_getIndeterminate (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"list\"]" js_getList :: JSRef HTMLInputElement -> IO (JSRef HTMLElement) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.list Mozilla HTMLInputElement.list documentation> getList :: (MonadIO m) => HTMLInputElement -> m (Maybe HTMLElement) getList self = liftIO ((js_getList (unHTMLInputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"max\"] = $2;" js_setMax :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.max Mozilla HTMLInputElement.max documentation> setMax :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setMax self val = liftIO (js_setMax (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"max\"]" js_getMax :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.max Mozilla HTMLInputElement.max documentation> getMax :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getMax self = liftIO (fromJSString <$> (js_getMax (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"maxLength\"] = $2;" js_setMaxLength :: JSRef HTMLInputElement -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.maxLength Mozilla HTMLInputElement.maxLength documentation> setMaxLength :: (MonadIO m) => HTMLInputElement -> Int -> m () setMaxLength self val = liftIO (js_setMaxLength (unHTMLInputElement self) val) foreign import javascript unsafe "$1[\"maxLength\"]" js_getMaxLength :: JSRef HTMLInputElement -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.maxLength Mozilla HTMLInputElement.maxLength documentation> getMaxLength :: (MonadIO m) => HTMLInputElement -> m Int getMaxLength self = liftIO (js_getMaxLength (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"min\"] = $2;" js_setMin :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.min Mozilla HTMLInputElement.min documentation> setMin :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setMin self val = liftIO (js_setMin (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"min\"]" js_getMin :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.min Mozilla HTMLInputElement.min documentation> getMin :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getMin self = liftIO (fromJSString <$> (js_getMin (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"multiple\"] = $2;" js_setMultiple :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.multiple Mozilla HTMLInputElement.multiple documentation> setMultiple :: (MonadIO m) => HTMLInputElement -> Bool -> m () setMultiple self val = liftIO (js_setMultiple (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"multiple\"] ? 1 : 0)" js_getMultiple :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.multiple Mozilla HTMLInputElement.multiple documentation> getMultiple :: (MonadIO m) => HTMLInputElement -> m Bool getMultiple self = liftIO (js_getMultiple (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.name Mozilla HTMLInputElement.name documentation> setName :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setName self val = liftIO (js_setName (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"name\"]" js_getName :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.name Mozilla HTMLInputElement.name documentation> getName :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getName self = liftIO (fromJSString <$> (js_getName (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"pattern\"] = $2;" js_setPattern :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.pattern Mozilla HTMLInputElement.pattern documentation> setPattern :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setPattern self val = liftIO (js_setPattern (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"pattern\"]" js_getPattern :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.pattern Mozilla HTMLInputElement.pattern documentation> getPattern :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getPattern self = liftIO (fromJSString <$> (js_getPattern (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"placeholder\"] = $2;" js_setPlaceholder :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.placeholder Mozilla HTMLInputElement.placeholder documentation> setPlaceholder :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setPlaceholder self val = liftIO (js_setPlaceholder (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"placeholder\"]" js_getPlaceholder :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.placeholder Mozilla HTMLInputElement.placeholder documentation> getPlaceholder :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getPlaceholder self = liftIO (fromJSString <$> (js_getPlaceholder (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"readOnly\"] = $2;" js_setReadOnly :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.readOnly Mozilla HTMLInputElement.readOnly documentation> setReadOnly :: (MonadIO m) => HTMLInputElement -> Bool -> m () setReadOnly self val = liftIO (js_setReadOnly (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"readOnly\"] ? 1 : 0)" js_getReadOnly :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.readOnly Mozilla HTMLInputElement.readOnly documentation> getReadOnly :: (MonadIO m) => HTMLInputElement -> m Bool getReadOnly self = liftIO (js_getReadOnly (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"required\"] = $2;" js_setRequired :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.required Mozilla HTMLInputElement.required documentation> setRequired :: (MonadIO m) => HTMLInputElement -> Bool -> m () setRequired self val = liftIO (js_setRequired (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"required\"] ? 1 : 0)" js_getRequired :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.required Mozilla HTMLInputElement.required documentation> getRequired :: (MonadIO m) => HTMLInputElement -> m Bool getRequired self = liftIO (js_getRequired (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"size\"] = $2;" js_setSize :: JSRef HTMLInputElement -> Word -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.size Mozilla HTMLInputElement.size documentation> setSize :: (MonadIO m) => HTMLInputElement -> Word -> m () setSize self val = liftIO (js_setSize (unHTMLInputElement self) val) foreign import javascript unsafe "$1[\"size\"]" js_getSize :: JSRef HTMLInputElement -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.size Mozilla HTMLInputElement.size documentation> getSize :: (MonadIO m) => HTMLInputElement -> m Word getSize self = liftIO (js_getSize (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"src\"] = $2;" js_setSrc :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.src Mozilla HTMLInputElement.src documentation> setSrc :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setSrc self val = liftIO (js_setSrc (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"src\"]" js_getSrc :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.src Mozilla HTMLInputElement.src documentation> getSrc :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getSrc self = liftIO (fromJSString <$> (js_getSrc (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"step\"] = $2;" js_setStep :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.step Mozilla HTMLInputElement.step documentation> setStep :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setStep self val = liftIO (js_setStep (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"step\"]" js_getStep :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.step Mozilla HTMLInputElement.step documentation> getStep :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getStep self = liftIO (fromJSString <$> (js_getStep (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.type Mozilla HTMLInputElement.type documentation> setType :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setType self val = liftIO (js_setType (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"type\"]" js_getType :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.type Mozilla HTMLInputElement.type documentation> getType :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getType self = liftIO (fromJSString <$> (js_getType (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"defaultValue\"] = $2;" js_setDefaultValue :: JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultValue Mozilla HTMLInputElement.defaultValue documentation> setDefaultValue :: (MonadIO m, ToJSString val) => HTMLInputElement -> Maybe val -> m () setDefaultValue self val = liftIO (js_setDefaultValue (unHTMLInputElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"defaultValue\"]" js_getDefaultValue :: JSRef HTMLInputElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultValue Mozilla HTMLInputElement.defaultValue documentation> getDefaultValue :: (MonadIO m, FromJSString result) => HTMLInputElement -> m (Maybe result) getDefaultValue self = liftIO (fromMaybeJSString <$> (js_getDefaultValue (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue :: JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.value Mozilla HTMLInputElement.value documentation> setValue :: (MonadIO m, ToJSString val) => HTMLInputElement -> Maybe val -> m () setValue self val = liftIO (js_setValue (unHTMLInputElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"value\"]" js_getValue :: JSRef HTMLInputElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.value Mozilla HTMLInputElement.value documentation> getValue :: (MonadIO m, FromJSString result) => HTMLInputElement -> m (Maybe result) getValue self = liftIO (fromMaybeJSString <$> (js_getValue (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"valueAsDate\"] = $2;" js_setValueAsDate :: JSRef HTMLInputElement -> JSRef Date -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation> setValueAsDate :: (MonadIO m, IsDate val) => HTMLInputElement -> Maybe val -> m () setValueAsDate self val = liftIO (js_setValueAsDate (unHTMLInputElement self) (maybe jsNull (unDate . toDate) val)) foreign import javascript unsafe "$1[\"valueAsDate\"]" js_getValueAsDate :: JSRef HTMLInputElement -> IO (JSRef Date) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation> getValueAsDate :: (MonadIO m) => HTMLInputElement -> m (Maybe Date) getValueAsDate self = liftIO ((js_getValueAsDate (unHTMLInputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"valueAsNumber\"] = $2;" js_setValueAsNumber :: JSRef HTMLInputElement -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsNumber Mozilla HTMLInputElement.valueAsNumber documentation> setValueAsNumber :: (MonadIO m) => HTMLInputElement -> Double -> m () setValueAsNumber self val = liftIO (js_setValueAsNumber (unHTMLInputElement self) val) foreign import javascript unsafe "$1[\"valueAsNumber\"]" js_getValueAsNumber :: JSRef HTMLInputElement -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsNumber Mozilla HTMLInputElement.valueAsNumber documentation> getValueAsNumber :: (MonadIO m) => HTMLInputElement -> m Double getValueAsNumber self = liftIO (js_getValueAsNumber (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"width\"] = $2;" js_setWidth :: JSRef HTMLInputElement -> Word -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.width Mozilla HTMLInputElement.width documentation> setWidth :: (MonadIO m) => HTMLInputElement -> Word -> m () setWidth self val = liftIO (js_setWidth (unHTMLInputElement self) val) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: JSRef HTMLInputElement -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.width Mozilla HTMLInputElement.width documentation> getWidth :: (MonadIO m) => HTMLInputElement -> m Word getWidth self = liftIO (js_getWidth (unHTMLInputElement self)) foreign import javascript unsafe "($1[\"willValidate\"] ? 1 : 0)" js_getWillValidate :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.willValidate Mozilla HTMLInputElement.willValidate documentation> getWillValidate :: (MonadIO m) => HTMLInputElement -> m Bool getWillValidate self = liftIO (js_getWillValidate (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"validity\"]" js_getValidity :: JSRef HTMLInputElement -> IO (JSRef ValidityState) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.validity Mozilla HTMLInputElement.validity documentation> getValidity :: (MonadIO m) => HTMLInputElement -> m (Maybe ValidityState) getValidity self = liftIO ((js_getValidity (unHTMLInputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"validationMessage\"]" js_getValidationMessage :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.validationMessage Mozilla HTMLInputElement.validationMessage documentation> getValidationMessage :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getValidationMessage self = liftIO (fromJSString <$> (js_getValidationMessage (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"labels\"]" js_getLabels :: JSRef HTMLInputElement -> IO (JSRef NodeList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.labels Mozilla HTMLInputElement.labels documentation> getLabels :: (MonadIO m) => HTMLInputElement -> m (Maybe NodeList) getLabels self = liftIO ((js_getLabels (unHTMLInputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"selectionStart\"] = $2;" js_setSelectionStart :: JSRef HTMLInputElement -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionStart Mozilla HTMLInputElement.selectionStart documentation> setSelectionStart :: (MonadIO m) => HTMLInputElement -> Int -> m () setSelectionStart self val = liftIO (js_setSelectionStart (unHTMLInputElement self) val) foreign import javascript unsafe "$1[\"selectionStart\"]" js_getSelectionStart :: JSRef HTMLInputElement -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionStart Mozilla HTMLInputElement.selectionStart documentation> getSelectionStart :: (MonadIO m) => HTMLInputElement -> m Int getSelectionStart self = liftIO (js_getSelectionStart (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"selectionEnd\"] = $2;" js_setSelectionEnd :: JSRef HTMLInputElement -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionEnd Mozilla HTMLInputElement.selectionEnd documentation> setSelectionEnd :: (MonadIO m) => HTMLInputElement -> Int -> m () setSelectionEnd self val = liftIO (js_setSelectionEnd (unHTMLInputElement self) val) foreign import javascript unsafe "$1[\"selectionEnd\"]" js_getSelectionEnd :: JSRef HTMLInputElement -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionEnd Mozilla HTMLInputElement.selectionEnd documentation> getSelectionEnd :: (MonadIO m) => HTMLInputElement -> m Int getSelectionEnd self = liftIO (js_getSelectionEnd (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"selectionDirection\"] = $2;" js_setSelectionDirection :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionDirection Mozilla HTMLInputElement.selectionDirection documentation> setSelectionDirection :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setSelectionDirection self val = liftIO (js_setSelectionDirection (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"selectionDirection\"]" js_getSelectionDirection :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionDirection Mozilla HTMLInputElement.selectionDirection documentation> getSelectionDirection :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getSelectionDirection self = liftIO (fromJSString <$> (js_getSelectionDirection (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.align Mozilla HTMLInputElement.align documentation> setAlign :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setAlign self val = liftIO (js_setAlign (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"align\"]" js_getAlign :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.align Mozilla HTMLInputElement.align documentation> getAlign :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getAlign self = liftIO (fromJSString <$> (js_getAlign (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"useMap\"] = $2;" js_setUseMap :: JSRef HTMLInputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.useMap Mozilla HTMLInputElement.useMap documentation> setUseMap :: (MonadIO m, ToJSString val) => HTMLInputElement -> val -> m () setUseMap self val = liftIO (js_setUseMap (unHTMLInputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"useMap\"]" js_getUseMap :: JSRef HTMLInputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.useMap Mozilla HTMLInputElement.useMap documentation> getUseMap :: (MonadIO m, FromJSString result) => HTMLInputElement -> m result getUseMap self = liftIO (fromJSString <$> (js_getUseMap (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"incremental\"] = $2;" js_setIncremental :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.incremental Mozilla HTMLInputElement.incremental documentation> setIncremental :: (MonadIO m) => HTMLInputElement -> Bool -> m () setIncremental self val = liftIO (js_setIncremental (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"incremental\"] ? 1 : 0)" js_getIncremental :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.incremental Mozilla HTMLInputElement.incremental documentation> getIncremental :: (MonadIO m) => HTMLInputElement -> m Bool getIncremental self = liftIO (js_getIncremental (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"autocorrect\"] = $2;" js_setAutocorrect :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocorrect Mozilla HTMLInputElement.autocorrect documentation> setAutocorrect :: (MonadIO m) => HTMLInputElement -> Bool -> m () setAutocorrect self val = liftIO (js_setAutocorrect (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"autocorrect\"] ? 1 : 0)" js_getAutocorrect :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocorrect Mozilla HTMLInputElement.autocorrect documentation> getAutocorrect :: (MonadIO m) => HTMLInputElement -> m Bool getAutocorrect self = liftIO (js_getAutocorrect (unHTMLInputElement self)) foreign import javascript unsafe "$1[\"autocapitalize\"] = $2;" js_setAutocapitalize :: JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocapitalize Mozilla HTMLInputElement.autocapitalize documentation> setAutocapitalize :: (MonadIO m, ToJSString val) => HTMLInputElement -> Maybe val -> m () setAutocapitalize self val = liftIO (js_setAutocapitalize (unHTMLInputElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"autocapitalize\"]" js_getAutocapitalize :: JSRef HTMLInputElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocapitalize Mozilla HTMLInputElement.autocapitalize documentation> getAutocapitalize :: (MonadIO m, FromJSString result) => HTMLInputElement -> m (Maybe result) getAutocapitalize self = liftIO (fromMaybeJSString <$> (js_getAutocapitalize (unHTMLInputElement self))) foreign import javascript unsafe "$1[\"capture\"] = $2;" js_setCapture :: JSRef HTMLInputElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.capture Mozilla HTMLInputElement.capture documentation> setCapture :: (MonadIO m) => HTMLInputElement -> Bool -> m () setCapture self val = liftIO (js_setCapture (unHTMLInputElement self) val) foreign import javascript unsafe "($1[\"capture\"] ? 1 : 0)" js_getCapture :: JSRef HTMLInputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.capture Mozilla HTMLInputElement.capture documentation> getCapture :: (MonadIO m) => HTMLInputElement -> m Bool getCapture self = liftIO (js_getCapture (unHTMLInputElement self))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/HTMLInputElement.hs
Haskell
mit
47,804
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html module Stratosphere.Resources.ElasticBeanstalkApplicationVersion where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.ElasticBeanstalkApplicationVersionSourceBundle -- | Full data type definition for ElasticBeanstalkApplicationVersion. See -- 'elasticBeanstalkApplicationVersion' for a more convenient constructor. data ElasticBeanstalkApplicationVersion = ElasticBeanstalkApplicationVersion { _elasticBeanstalkApplicationVersionApplicationName :: Val Text , _elasticBeanstalkApplicationVersionDescription :: Maybe (Val Text) , _elasticBeanstalkApplicationVersionSourceBundle :: ElasticBeanstalkApplicationVersionSourceBundle } deriving (Show, Eq) instance ToResourceProperties ElasticBeanstalkApplicationVersion where toResourceProperties ElasticBeanstalkApplicationVersion{..} = ResourceProperties { resourcePropertiesType = "AWS::ElasticBeanstalk::ApplicationVersion" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ (Just . ("ApplicationName",) . toJSON) _elasticBeanstalkApplicationVersionApplicationName , fmap (("Description",) . toJSON) _elasticBeanstalkApplicationVersionDescription , (Just . ("SourceBundle",) . toJSON) _elasticBeanstalkApplicationVersionSourceBundle ] } -- | Constructor for 'ElasticBeanstalkApplicationVersion' containing required -- fields as arguments. elasticBeanstalkApplicationVersion :: Val Text -- ^ 'ebavApplicationName' -> ElasticBeanstalkApplicationVersionSourceBundle -- ^ 'ebavSourceBundle' -> ElasticBeanstalkApplicationVersion elasticBeanstalkApplicationVersion applicationNamearg sourceBundlearg = ElasticBeanstalkApplicationVersion { _elasticBeanstalkApplicationVersionApplicationName = applicationNamearg , _elasticBeanstalkApplicationVersionDescription = Nothing , _elasticBeanstalkApplicationVersionSourceBundle = sourceBundlearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-applicationname ebavApplicationName :: Lens' ElasticBeanstalkApplicationVersion (Val Text) ebavApplicationName = lens _elasticBeanstalkApplicationVersionApplicationName (\s a -> s { _elasticBeanstalkApplicationVersionApplicationName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-description ebavDescription :: Lens' ElasticBeanstalkApplicationVersion (Maybe (Val Text)) ebavDescription = lens _elasticBeanstalkApplicationVersionDescription (\s a -> s { _elasticBeanstalkApplicationVersionDescription = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-sourcebundle ebavSourceBundle :: Lens' ElasticBeanstalkApplicationVersion ElasticBeanstalkApplicationVersionSourceBundle ebavSourceBundle = lens _elasticBeanstalkApplicationVersionSourceBundle (\s a -> s { _elasticBeanstalkApplicationVersionSourceBundle = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/ElasticBeanstalkApplicationVersion.hs
Haskell
mit
3,311
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} #if __GLASGOW_HASKELL__ >= 802 -- Retain support for older compilers, assuming dependency versions which do too {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE StandaloneDeriving #-} #endif module TestSite ( User(..), migrateAll, App(..), Route(..), Handler, runDB ) where import Control.Monad (when) import Data.Text import Database.Persist.Sqlite import Network.HTTP.Client.Conduit (Manager) import Yesod import Yesod.Auth import Yesod.Auth.HashDB (HashDBUser(..), authHashDB, submitRouteHashDB) import Yesod.Auth.Message (AuthMessage (InvalidLogin)) -- Trivial example site needing authentication -- share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User name Text password Text Maybe UniqueUser name deriving Show |] instance HashDBUser User where userPasswordHash = userPassword setPasswordHash h u = u { userPassword = Just h } data App = App { appHttpManager :: Manager , appDBConnection :: SqlBackend } #if !MIN_VERSION_yesod_core(1,6,0) #define liftHandler lift #define doRunDB runDB getAppHttpManager :: App -> Manager getAppHttpManager = appHttpManager #else #define doRunDB liftHandler $ runDB getAppHttpManager :: (MonadHandler m, HandlerSite m ~ App) => m Manager getAppHttpManager = appHttpManager <$> getYesod #endif mkYesod "App" [parseRoutes| / HomeR GET /prot ProtectedR GET /auth AuthR Auth getAuth |] instance Yesod App where approot = ApprootStatic "http://localhost:3000" authRoute _ = Just $ AuthR LoginR isAuthorized ProtectedR _ = do mu <- maybeAuthId return $ case mu of Nothing -> AuthenticationRequired Just _ -> Authorized -- Other pages (HomeR and AuthR _) do not require login isAuthorized _ _ = return Authorized -- CSRF middleware requires yesod-core-1.4.14, yesod-test >= 1.5 is -- required so that tests can get at the token. yesodMiddleware = defaultCsrfMiddleware . defaultYesodMiddleware instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlConn action $ appDBConnection master instance YesodAuth App where type AuthId App = UserId loginDest _ = HomeR logoutDest _ = HomeR authenticate creds = doRunDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (Entity uid _) -> return $ Authenticated uid Nothing -> return $ UserError InvalidLogin authPlugins _ = [ authHashDB (Just . UniqueUser) ] authHttpManager = getAppHttpManager loginHandler = do submission <- submitRouteHashDB render <- liftHandler getUrlRender typedContent@(TypedContent ct _) <- selectRep $ do provideRepType typeHtml $ return emptyContent -- Dummy: the real Html version is at the end provideJson $ object [("loginUrl", toJSON $ render submission)] when (ct == typeJson) $ sendResponse typedContent -- Short-circuit JSON response defaultLoginHandler -- Html response instance YesodAuthPersist App instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage getHomeR :: Handler Html getHomeR = do mauth <- maybeAuth let mname = userName . entityVal <$> mauth defaultLayout [whamlet| <p>Your current auth ID: #{show mname} $maybe _ <- mname <p> <a href=@{AuthR LogoutR}>Logout $nothing <p> <a href=@{AuthR LoginR}>Go to the login page <p><a href=@{ProtectedR}>Go to protected page |] -- This page requires a valid login getProtectedR :: Handler Html getProtectedR = defaultLayout [whamlet| <p>OK, you are logged in so you are allowed to see this! <p><a href=@{HomeR}>Go to home page |]
paul-rouse/yesod-auth-hashdb
test/TestSite.hs
Haskell
mit
4,580
module Problem02 (partA, partB) where import Data.Monoid import Text.Megaparsec import Text.Megaparsec.String inputLocation :: FilePath inputLocation = "input/input02.txt" data Offset = Negative | Neutral | Positive deriving (Eq,Show,Enum,Ord) instance Monoid Offset where mempty = Neutral mappend Negative Positive = Neutral mappend Negative _ = Negative mappend Positive Negative = Neutral mappend Positive _ = Positive mappend Neutral a = a data Position = Position Offset Offset deriving (Eq,Show) instance Monoid Position where mempty = Position mempty mempty Position ax ay `mappend` Position bx by = Position (ax <> bx) (ay <> by) positionToNumber :: Position -> Int positionToNumber (Position Negative Negative) = 1 positionToNumber (Position Neutral Negative) = 2 positionToNumber (Position Positive Negative) = 3 positionToNumber (Position Negative Neutral ) = 4 positionToNumber (Position Neutral Neutral ) = 5 positionToNumber (Position Positive Neutral ) = 6 positionToNumber (Position Negative Positive) = 7 positionToNumber (Position Neutral Positive) = 8 positionToNumber (Position Positive Positive) = 9 parseInstruction :: Parser [[Position]] parseInstruction = helper `sepBy` eol where helper = many $ (Position Neutral Negative <$ char 'U') <|> (Position Neutral Positive <$ char 'D') <|> (Position Positive Neutral <$ char 'R') <|> (Position Negative Neutral <$ char 'L') partA :: IO () partA = readFile inputLocation >>= print . fmap (foldMap show . runA) . runParser parseInstruction "" runA :: [[Position]] -> [Int] runA = map positionToNumber . helper mempty . filter (not . null) where helper _ [] = [] helper s (x : xs) = newS : helper newS xs where newS = foldl mappend s x data PositionB = PositionB Int Int deriving (Eq,Show) isValidGrid :: PositionB -> Bool isValidGrid (PositionB x y) = abs x <= 2 && abs y <= helper (abs x) where helper 0 = 2 helper 1 = 1 helper 2 = 0 movePosition :: PositionB -> (Int,Int) -> PositionB movePosition p@(PositionB sx sy) (dx,dy) = if isValidGrid newPos then newPos else p where newPos = PositionB (sx + dx) (sy + dy) parseBInstructions :: Parser [[(Int,Int)]] parseBInstructions = helper `sepBy` eol where helper = many $ ((0,-1) <$ char 'U') <|> ((0,1 ) <$ char 'D') <|> ((1,0) <$ char 'R') <|> ((-1,0) <$ char 'L') gridBToNum :: PositionB -> Char gridBToNum (PositionB 0 (-2)) = '1' gridBToNum (PositionB (-1) (-1)) = '2' gridBToNum (PositionB 0 (-1)) = '3' gridBToNum (PositionB 1 (-1)) = '4' gridBToNum (PositionB (-2) 0) = '5' gridBToNum (PositionB (-1) 0) = '6' gridBToNum (PositionB 0 0) = '7' gridBToNum (PositionB 1 0) = '8' gridBToNum (PositionB 2 0) = '9' gridBToNum (PositionB (-1) 1) = 'A' gridBToNum (PositionB 0 1) = 'B' gridBToNum (PositionB 1 1) = 'C' gridBToNum (PositionB 0 2) = 'D' gridBToNum (PositionB x y) = error $ "Grid to num: " ++ show x ++ " " ++ show y runB :: [[(Int,Int)]] -> [Char] runB = map gridBToNum . helper (PositionB (-2) 0) . filter (not . null) where helper _ [] = [] helper s (x : xs) = newS : helper newS xs where newS = foldl movePosition s x partB :: IO () partB = readFile inputLocation >>= print . fmap runB . runParser parseBInstructions ""
edwardwas/adventOfCodeTwo
src/Problem02.hs
Haskell
mit
3,402
-- (**) Rotate a list N places to the left. -- -- Hint: Use the predefined functions length and (++). -- -- Examples: -- -- * (rotate '(a b c d e f g h) 3) -- (D E F G H A B C) -- -- * (rotate '(a b c d e f g h) -2) -- (G H A B C D E F) -- Examples in Haskell: -- -- *Main> rotate ['a','b','c','d','e','f','g','h'] 3 -- "defghabc" -- -- *Main> rotate ['a','b','c','d','e','f','g','h'] (-2) -- "ghabcdef" rotate :: [a] -> Int -> [a] rotate xs n | n >= 0 = snd slice ++ fst slice | otherwise = rotate xs (length xs + n) where slice = splitAt n xs
tiann/haskell-learning
haskell99/p19/main.hs
Haskell
apache-2.0
561
module Problem063 where main = print $ length [n | b <- [1 .. 9], p <- ps, let n = b ^ p, length (show n) == p] where ps = takeWhile (\p -> length (show (9 ^ p)) >= p) [1 ..]
vasily-kartashov/playground
euler/problem-063.hs
Haskell
apache-2.0
181
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} import Data.List class Foo a where foo :: a -> String -- Now will error due to the compiler don't know which one to call between -- String and [char] instance (Foo a) => Foo [a] where foo = concat . intersperse ", " . map foo instance Foo Char where foo c = [c] instance Foo String where foo = id
EricYT/Haskell
src/chapter-6-4.hs
Haskell
apache-2.0
375
-------------------------------------------------------------------------------- -- | -- Module : Network.SimpleIRC.Core.Lens -- Copyright : (C) 2014 Ricky Elrod -- License : BSD-style (see the file LICENSE) -- Maintainer : Ricky Elrod <ricky@elrod.me> -- Stability : provisional -- Portability : portable -- -- This module provides lenses for types in -- <https://hackage.haskell.org/package/simpleirc/docs/Network-SimpleIRC-Core.html Network.SimpleIRC.Core>. ------------------------------------------------------------------------------- module Network.SimpleIRC.Core.Lens ( -- * 'IrcConfig' addr, port, secure, nick, pass, username, realname, channels, events, ctcpVersion, ctcpTime, ctcpPingTimeoutInterval ) where import Network.SimpleIRC.Core addr :: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig addr fn (IrcConfig a b c d e f g h i j k l) = fmap (\a' -> IrcConfig a' b c d e f g h i j k l) (fn a) port :: Functor f => (Int -> f Int) -> IrcConfig -> f IrcConfig port fn (IrcConfig a b c d e f g h i j k l) = fmap (\b' -> IrcConfig a b' c d e f g h i j k l) (fn b) secure :: Functor f => (Bool -> f Bool) -> IrcConfig -> f IrcConfig secure fn (IrcConfig a b c d e f g h i j k l) = fmap (\c' -> IrcConfig a b c' d e f g h i j k l) (fn c) nick :: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig nick fn (IrcConfig a b c d e f g h i j k l) = fmap (\d' -> IrcConfig a b c d' e f g h i j k l) (fn d) pass :: Functor f => (Maybe String -> f (Maybe String)) -> IrcConfig -> f IrcConfig pass fn (IrcConfig a b c d e f g h i j k l) = fmap (\e' -> IrcConfig a b c d e' f g h i j k l) (fn e) username :: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig username fn (IrcConfig a b c d e f g h i j k l) = fmap (\f' -> IrcConfig a b c d e f' g h i j k l) (fn f) realname :: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig realname fn (IrcConfig a b c d e f g h i j k l) = fmap (\g' -> IrcConfig a b c d e f g' h i j k l) (fn g) channels :: Functor f => ([String] -> f [String]) -> IrcConfig -> f IrcConfig channels fn (IrcConfig a b c d e f g h i j k l) = fmap (\h' -> IrcConfig a b c d e f g h' i j k l) (fn h) events :: Functor f => ([IrcEvent] -> f [IrcEvent]) -> IrcConfig -> f IrcConfig events fn (IrcConfig a b c d e f g h i j k l) = fmap (\i' -> IrcConfig a b c d e f g h i' j k l) (fn i) ctcpVersion :: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig ctcpVersion fn (IrcConfig a b c d e f g h i j k l) = fmap (\j' -> IrcConfig a b c d e f g h i j' k l) (fn j) ctcpTime :: Functor f => (IO String -> f (IO String)) -> IrcConfig -> f IrcConfig ctcpTime fn (IrcConfig a b c d e f g h i j k l) = fmap (\k' -> IrcConfig a b c d e f g h i j k' l) (fn k) ctcpPingTimeoutInterval :: Functor f => (Int -> f Int) -> IrcConfig -> f IrcConfig ctcpPingTimeoutInterval fn (IrcConfig a b c d e f g h i j k l) = fmap (\l' -> IrcConfig a b c d e f g h i j k l') (fn l)
relrod/simpleirc-lens
src/Network/SimpleIRC/Core/Lens.hs
Haskell
bsd-2-clause
3,054
import Prelude data Encoded a = Single a | Multiple Int a deriving Show encodeDirect :: Eq a => [a] -> [Encoded a] encodeDirect [] = [] encodeDirect xs = foldr (append) [] xs where append y [] = [Single y] append y ((Single z):zs) | (y == z) = (Multiple 2 z):zs | otherwise = (Single y):(Single z):zs append y ((Multiple n z):zs) | (y == z) = (Multiple (n + 1) z):zs | otherwise = (Single y):(Multiple n z):zs
2dor/99-problems-Haskell
11-20-lists-continued/problem-13.hs
Haskell
bsd-2-clause
492
{-# LANGUAGE OverloadedStrings, ViewPatterns #-} import qualified Prelude as P import BasicPrelude import Filesystem.Path.CurrentOS (decodeString) import System.Environment (getArgs) import qualified Data.Text.Encoding as T import qualified Data.Ini.Reader as Ini import Data.Conduit.Network (runTCPServer, serverSettings, HostPreference(HostAny), serverNeedLocalAddr) import Network.HTTP.Conduit import qualified Network.Aliyun as Ali import Network.FTP.Server import Network.FTP.Backend.Cloud main = do [P.read -> port, path] <- getArgs conf <- loadCloudConf path let serverConf = (serverSettings port HostAny){serverNeedLocalAddr=True} runCloudBackend conf $ runTCPServer serverConf ftpServer
yihuang/cloud-ftp
Main.hs
Haskell
bsd-3-clause
715
{-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ConstraintKinds #-} module Types where import Util import Network import Vector import Static import Static.Image import Network.Label import Data.Singletons.Prelude import Data.Singletons.TypeLits import Data.Singletons.Prelude.List import Data.Serialize import Conduit class Pretty a where pretty :: a -> String -- | A GameState is a data type that fully describes a games' state. class ( KnownSymbol (Title g) , KnownNat (ScreenWidth g) , KnownNat (ScreenHeight g) , Show g, Pretty g ) => GameState g where label :: g -> LabelVec g delabel :: LabelVec g -> g rootDir :: Path g parse :: Path g -> LabelVec g type Title g :: Symbol type ScreenWidth g :: Nat -- ^ The width of a screen of this game in pixels. -- This value and the height are mostly used to -- scale the positions and dimensions of widgets type ScreenHeight g :: Nat type Widgets g :: [*] class ( KnownNat (Height w), KnownNat (Width w), KnownNat (Length (Positions w)) , KnownNat (ScreenWidth (Parent w)), KnownNat (ScreenHeight (Parent w)) , KnownNat (Sum (DataShape w)), KnownNat ((Sum (DataShape w)) :* (Length (Positions w))) , SingI (Positions w), Measure (InputShape w) , SingI (DataShape w) , KnownNat (SampleWidth w) , KnownNat (SampleHeight w) , KnownNat (Length (Positions w) :* SampleWidth w) , (NOutput (Network (InputShape w) (NetConfig w))) ~ (ZZ ::. Length (Positions w) ::. Sum (DataShape w)) ) => Widget w where toLabel :: w -> WLabel w fromLabel :: LabelParser w params :: Params w -- Widget description type Positions w :: [(Nat, Nat)] type DataShape w :: [Nat] type Width w :: Nat type Height w :: Nat type Parent w :: * -- Widget classifier configuration type SampleWidth w :: Nat type SampleHeight w :: Nat type NetConfig w :: [*] newtype Params w = Params LearningParameters type InputShape w = ZZ ::. Length (Positions w) ::. 3 ::. SampleHeight w ::. SampleWidth w type OutputShape w = LabelComposite (Length (Positions w)) (DataShape w) type BatchInputShape w n = ZZ ::. n :* Length (Positions w) ::. 3 ::. SampleHeight w ::. SampleWidth w type BatchOutputShape w n = ZZ ::. n :* Length (Positions w) ::. Sum (DataShape w) newtype WLabel w = WLabel (OutputShape w) deriving instance Serialize (OutputShape w) => Serialize (WLabel w) deriving instance Creatable (OutputShape w) => Creatable (WLabel w) deriving instance Show (OutputShape w) => Show (WLabel w) deriving instance Eq (OutputShape w) => Eq (WLabel w) newtype WNetwork w = WNetwork (Network (InputShape w) (NetConfig w)) deriving instance Serialize (Network (InputShape w) (NetConfig w)) => Serialize (WNetwork w) deriving instance Creatable (Network (InputShape w) (NetConfig w)) => Creatable (WNetwork w) deriving instance Show (Network (InputShape w) (NetConfig w)) => Show (WNetwork w) newtype WInput w = WInput (SArray U (InputShape w)) deriving instance Serialize (SArray U (InputShape w)) => Serialize (WInput w) deriving instance Creatable (SArray U (InputShape w)) => Creatable (WInput w) deriving instance Show (SArray U (InputShape w)) => Show (WInput w) newtype WBatch n w = WBatch ( SArray U (BatchInputShape w n) , SArray U (BatchOutputShape w n)) deriving instance ( Serialize (SArray U (BatchInputShape w n)) , Serialize (SArray U (BatchOutputShape w n)) ) => Serialize (WBatch n w) deriving instance ( Show (SArray U (BatchInputShape w n)) , Show (SArray U (BatchOutputShape w n)) ) => Show (WBatch n w) newtype LabelVec g = LabelVec (Vec WLabel (Widgets g)) deriving instance Show (Vec WLabel (Widgets g)) => Show (LabelVec g) deriving instance Eq (Vec WLabel (Widgets g)) => Eq (LabelVec g) type InputVec g = Vec WInput (Widgets g) type NetworkVec g = Vec WNetwork (Widgets g) type BatchVec n g = Vec (WBatch n) (Widgets g) type BatchC n g = RTConduit (Screenshot g, LabelVec g) (Vec (WBatch n) (Widgets g)) newtype Visor game = Visor (NetworkVec game) deriving instance Serialize (NetworkVec game) => Serialize (Visor game) deriving instance Creatable (NetworkVec game) => Creatable (Visor game) newtype Screenshot g = Screenshot BMP newtype Path g = Path {unpath :: FilePath} instance Show (Path g) where show (Path p) = p type RTSource a = Source (ResourceT IO) a type RTConduit a b = Conduit a (ResourceT IO) b type RTSink a = Sink a (ResourceT IO) ()
jonascarpay/visor
src/Types.hs
Haskell
bsd-3-clause
5,061
-- | -- Module : Language.Logo -- Copyright : (c) 2013-2016, the HLogo team -- License : BSD3 -- Maintainer : Nikolaos Bezirgiannis <bezirgia@cwi.nl> -- Stability : experimental -- -- Main wrapper module; the only module that should be imported by the model module Language.Logo ( module Language.Logo.Keyword, module Language.Logo.Prim, module Language.Logo.Exception, module Language.Logo.Base, module Prelude, forever, when, liftM, liftM2 ) where import Prelude hiding (show, print, length) import Language.Logo.Keyword import Language.Logo.Prim import Language.Logo.Exception import Language.Logo.Base import Control.Monad (forever, when, liftM, liftM2)
bezirg/hlogo
src/Language/Logo.hs
Haskell
bsd-3-clause
721
module Util.Integral where instance Integral Float where quotRem a b = (fab, (ab - fab)*b) where ab = a/b fab = floor ab toInteger = floor instance Integral Double where quotRem a b = (fab, (ab - fab)*b) where ab = a/b fab = floor ab toInteger = floor
phylake/haskell-util
Integral.hs
Haskell
bsd-3-clause
295
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, TemplateHaskell, DeriveGeneric #-} module OpenGL.Evaluator.GLPrimitives where import Data.Word import qualified Data.ByteString as BS import Data.Data import Data.Typeable import Foreign import Foreign.C.Types import Foreign.Storable import Data.Binary import Data.Binary.Get import Data.Binary.Put import Data.Binary.IEEE754 import Data.DeriveTH import Test.QuickCheck import GHC.Generics newtype GLbitfield = GLbitfield Word32 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLboolean = GLboolean Bool deriving(Show, Eq, Storable, Data, Typeable, Arbitrary, Generic) instance Binary GLboolean where put (GLboolean x) = if x then putWord8 1 else putWord8 0 get = undefined newtype GLbyte = GLbyte Word8 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLchar = GLchar Char deriving(Show, Eq, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLclampf = GLclampf Float deriving(Show, Eq, Num, Storable, Ord, Fractional, Real, Data, Typeable, Arbitrary, Generic) instance Binary GLclampf where put (GLclampf x) = putFloat32le x get = undefined newtype GLenum = GLenum Word32 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLfloat = GLfloat Float deriving(Show, Eq, Num, Storable, Ord, Fractional, Real, Data, Typeable, Arbitrary, Generic) instance Binary GLfloat where put (GLfloat x) = putFloat32le x get = undefined newtype GLint = GLint Int32 deriving(Show, Eq, Num, Storable, Data, Typeable, Arbitrary, Generic) instance Binary GLint where put (GLint x) = putWord32le $ fromIntegral x get = undefined newtype GLshort = GLshort Int16 deriving(Show, Eq, Num, Storable, Data, Typeable, Arbitrary, Generic) instance Binary GLshort where put (GLshort x) = putWord16le $ fromIntegral x get = undefined newtype GLsizei = GLsizei Word32 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLubyte = GLubyte Word8 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLuint = GLuint Word32 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLushort = GLushort Word16 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLfixed = GLfixed Word32 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) newtype GLclampx = GLclampx Word32 deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic) type GLIntPtr = GLuint type GLsizeiptr = GLuint data MatrixUniformType = MATRIX_UNIFORM_2X2 | MATRIX_UNIFORM_3X3 | MATRIX_UNIFORM_4X4 deriving(Show, Eq, Data, Typeable, Generic) $(derive makeBinary ''MatrixUniformType) $(derive makeArbitrary ''MatrixUniformType) type GLError = GLenum type GLPointer = GLuint type Id = GLuint type GLId = GLuint
jfischoff/opengl-eval
src/OpenGL/Evaluator/GLPrimitives.hs
Haskell
bsd-3-clause
3,172
{-# LANGUAGE NoImplicitPrelude, UnicodeSyntax #-} -- |Help.Imports provides a central location for universally shared exports, primarily -- the non-standard Prelude. module Help.Imports ( -- *Overrides FilePath -- *Re-Exports , module ClassyPrelude , module Data.Eq.Unicode ) where import ClassyPrelude hiding (FilePath) import Data.Eq.Unicode -- |Overrides the default @ClassyPrelude@ @FilePath@ for fun and profit. type FilePath = String
argiopetech/help
Help/Imports.hs
Haskell
bsd-3-clause
547
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Reactive.Banana.DOM.Widget ( ReactiveDom, CleanupHandler, IsWidget(..), IsEventWidget(..), WidgetInstance, mkWidget, removeWidget, fromWidgetInstance, widgetRoot, mkSubWidget, registerCleanupIO, handleBehavior, rsFlipFlop, newBehavior ) where import Control.Lens import Control.Monad import Control.Monad.Writer import Data.Typeable import GHCJS.DOM.Element (Element, setAttribute) import GHCJS.DOM.Node (getParentNode, removeChild) import GHCJS.DOM.Types (IsNode) import Reactive.Banana import Reactive.Banana.Frameworks --- | The 'Monad' in which 'WidgetInstance' creation is enacted. Use 'registerCleanupIO' --- to register cleanup handles. Use 'mkSubWidget' to create sub 'WidgetInstance's type ReactiveDom a = WriterT [CleanupHandler] MomentIO a -- | a type class for all reactive widgets class IsWidget w where data WidgetInput w :: * -- | Create and register widget 'w'. Returns the widget and its root 'Element'. -- Use 'mkSubWidget' to creat sub widgets. mkWidgetInstance :: (IsNode parent) => parent -> WidgetInput w -> ReactiveDom (w, Element) -- | A widget witch emits an 'Event' class (IsWidget w) => IsEventWidget w where type WidgetEventType w :: * widgetEvent :: w -> Event (WidgetEventType w) type CleanupHandler = MomentIO () -- | Represents an instance of an 'IsWidget' newtype WidgetInstance w = WidgetInstance (w, CleanupHandler, Element) makePrisms ''WidgetInstance -- | Register an 'IO' action as cleanup function in 'ReactiveDom' registerCleanupIO :: IO () -> ReactiveDom () registerCleanupIO = tell . pure . liftIO -- | Get the widget from a 'WidgetInstance' fromWidgetInstance :: (IsWidget w) => WidgetInstance w -> w fromWidgetInstance = view $ _WidgetInstance . _1 -- | Should deregister all event handlers, kill threads etc. widgetCleanup :: (IsWidget w) => WidgetInstance w -> CleanupHandler widgetCleanup = view $ _WidgetInstance . _2 -- | Get the root 'Element' of a 'WidgetInstance' widgetRoot :: (IsWidget w) => WidgetInstance w -> Element widgetRoot = view $ _WidgetInstance . _3 -- | Creates a new 'WidgetInstance' in the DOM mkWidget :: (Typeable w, IsWidget w, IsNode parent) => parent -> WidgetInput w -> MomentIO (WidgetInstance w) mkWidget parent i = do (r, cs) <- runWriterT $ mkWidgetInstance parent i let widgetClass = mkWidgetClassName . show . typeOf . view _1 $ r liftIOLater . setAttribute (r ^. _2) ("data-widget" :: String) $ widgetClass return $ _WidgetInstance # (r ^. _1, sequence_ cs, r ^. _2) where mkWidgetClassName = takeWhile (not . (==) ' ') -- | Calls cleanup of 'WidgetInstance' tree. Removes element from DOM. removeWidget :: (IsWidget w) => WidgetInstance w -> MomentIO () removeWidget w = do widgetCleanup w let r = widgetRoot w pM <- getParentNode r case pM of Nothing -> return () Just p -> void $ removeChild p (pure r) -- | Creates a sub widget in the 'ReactiveDom' 'Monad'. mkSubWidget :: (Typeable w, IsWidget w, IsNode parent) => parent -> WidgetInput w -> ReactiveDom (WidgetInstance w) mkSubWidget parent i = do w <- lift . mkWidget parent $ i tell . pure . widgetCleanup $ w return w newBehavior :: a -> MomentIO (Behavior a, a -> IO ()) newBehavior s0 = do (e, fe) <- newEvent (,) <$> stepper s0 e <*> pure fe -- | register an handler for changes on a 'Behavior' handleBehavior :: Behavior a -> Handler a -> ReactiveDom () handleBehavior a = lift . handleBehavior' a handleBehavior' :: Behavior a -> Handler a -> MomentIO () handleBehavior' a h = do valueBLater a >>= liftIOLater . h changes a >>= reactimate' . fmap (fmap h) rsFlipFlop :: Behavior Bool -> Behavior Bool -> MomentIO (Behavior Bool) rsFlipFlop s r = do (b, fire) <- newBehavior False handleBehavior' s $ \a -> when a $ fire True handleBehavior' r $ \a -> when a $ fire False return b
open-etcs/openetcs-dmi
src/Reactive/Banana/DOM/Widget.hs
Haskell
bsd-3-clause
4,195
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} module Data.Type.Uniform where import Data.Kind import Data.Type.Length import Type.Class.Known import Type.Class.Witness import Data.Type.Nat import Type.Family.List.Util import Type.Family.Constraint import Type.Family.List -- | A @'Uniform' a as@ is a witness that every item in @as@ is -- (identically) @a@. data Uniform :: a -> [a] -> Type where UØ :: Uniform a '[] US :: !(Uniform a as) -> Uniform a (a ': as) deriving instance Show (Uniform a as) uniformLength :: Uniform n ns -> Length ns uniformLength = \case UØ -> LZ US u -> LS (uniformLength u) instance Known (Uniform n) '[] where known = UØ instance Known (Uniform n) ns => Known (Uniform n) (n ': ns) where known = US known -- instance (m ~ Len ns) => Witness ØC (Known Nat m) (Uniform n ns) where -- (\\) r = \case -- UØ -> r -- US u -> r \\ u instance Witness ØC (Known Length ms) (Uniform m ms) where (\\) r = \case UØ -> r US u -> r \\ u appendUniform :: Uniform o ns -> Uniform o ms -> Uniform o (ns ++ ms) appendUniform = \case UØ -> id US u -> US . appendUniform u replicateUniform :: forall x n. () => Nat n -> Uniform x (Replicate n x) replicateUniform = \case Z_ -> UØ S_ n -> US (replicateUniform @x n)
mstksg/tensor-ops
src/Data/Type/Uniform.hs
Haskell
bsd-3-clause
1,854
module Bump where import Control.Monad.Error (throwError, liftIO) import qualified Data.List as List import qualified Catalog import qualified CommandLine.Helpers as Cmd import qualified Diff.Compare as Compare import qualified Docs import qualified Elm.Docs as Docs import qualified Elm.Package.Description as Desc import qualified Elm.Package.Name as N import qualified Elm.Package.Paths as Path import qualified Elm.Package.Version as V import qualified Manager bump :: Manager.Manager () bump = do description <- Desc.read Path.description let name = Desc.name description let statedVersion = Desc.version description newDocs <- Docs.generate description maybeVersions <- Catalog.versions name case maybeVersions of Nothing -> validateInitialVersion description Just publishedVersions -> let baseVersions = map (\(old, _, _) -> old) (validBumps publishedVersions) in if statedVersion `elem` baseVersions then suggestVersion newDocs name statedVersion description else throwError (unbumpable baseVersions) return () unbumpable :: [V.Version] -> String unbumpable baseVersions = let versions = map head (List.group (List.sort baseVersions)) in unlines [ "To bump you must start with an already published version number in" , Path.description ++ ", giving us a starting point to bump from." , "" , "The version numbers that can be bumped include the following subset of" , "published versions:" , " " ++ List.intercalate ", " (map V.toString versions) , "" , "Switch back to one of these versions before running 'elm-package bump'" , "again." ] data Validity = Valid | Invalid | Changed V.Version validateInitialVersion :: Desc.Description -> Manager.Manager Validity validateInitialVersion description = do Cmd.out explanation if Desc.version description == V.initialVersion then Cmd.out goodMsg >> return Valid else changeVersion badMsg description V.initialVersion where explanation = unlines [ "This package has never been published before. Here's how things work:" , "" , " * Versions all have exactly three parts: MAJOR.MINOR.PATCH" , "" , " * All packages start with initial version " ++ V.toString V.initialVersion , "" , " * Versions are incremented based on how the API changes:" , "" , " PATCH - the API is the same, no risk of breaking code" , " MINOR - values have been added, existing values are unchanged" , " MAJOR - existing values have been changed or removed" , "" , " * I will bump versions for you, automatically enforcing these rules" , "" ] goodMsg = "The version number in " ++ Path.description ++ " is correct so you are all set!" badMsg = concat [ "It looks like the version in " ++ Path.description ++ " has been changed though!\n" , "Would you like me to change it back to " ++ V.toString V.initialVersion ++ "? (y/n) " ] changeVersion :: String -> Desc.Description -> V.Version -> Manager.Manager Validity changeVersion explanation description newVersion = do liftIO $ putStr explanation yes <- liftIO Cmd.yesOrNo case yes of False -> do Cmd.out "Okay, no changes were made." return Invalid True -> do liftIO $ Desc.write (description { Desc.version = newVersion }) Cmd.out $ "Version changed to " ++ V.toString newVersion ++ "." return (Changed newVersion) suggestVersion :: [Docs.Documentation] -> N.Name -> V.Version -> Desc.Description -> Manager.Manager Validity suggestVersion newDocs name version description = do changes <- Compare.computeChanges newDocs name version let newVersion = Compare.bumpBy changes version changeVersion (infoMsg changes newVersion) description newVersion where infoMsg changes newVersion = let old = V.toString version new = V.toString newVersion magnitude = show (Compare.packageChangeMagnitude changes) in concat [ "Based on your new API, this should be a ", magnitude, " change (", old, " => ", new, ")\n" , "Bail out of this command and run 'elm-package diff' for a full explanation.\n" , "\n" , "Should I perform the update (", old, " => ", new, ") in ", Path.description, "? (y/n) " ] validateVersion :: [Docs.Documentation] -> N.Name -> V.Version -> [V.Version] -> Manager.Manager Validity validateVersion newDocs name statedVersion publishedVersions = case List.find (\(_ ,new, _) -> statedVersion == new) bumps of Nothing -> let isPublished = statedVersion `elem` publishedVersions in throwError (if isPublished then alreadyPublished else invalidBump) Just (old, new, magnitude) -> do changes <- Compare.computeChanges newDocs name old let realNew = Compare.bumpBy changes old case new == realNew of False -> throwError (badBump old new realNew magnitude changes) True -> do Cmd.out (looksGood old new magnitude) return Valid where bumps = validBumps publishedVersions looksGood old new magnitude = "Version number " ++ V.toString new ++ " verified (" ++ show magnitude ++ " change, " ++ V.toString old ++ " => " ++ V.toString new ++ ")" alreadyPublished = "Version " ++ V.toString statedVersion ++ " has already been published, but you are trying to publish\n" ++ "it again! Run the following command to see what the new version should be.\n" ++ "\n elm-package bump\n" invalidBump = unlines [ "The version listed in " ++ Path.description ++ " is neither a previously" , "published version, nor a valid version bump." , "" , "Set the version number in " ++ Path.description ++ " to the released version" , "that you are improving upon. If you are working on the latest API, that means" , "you are modifying version " ++ V.toString (last publishedVersions) ++ "." , "" , "From there, we can compute which version comes next based on the API changes" , "when you run the following command." , "" , " elm-package bump" ] badBump old new realNew magnitude changes = unlines [ "It looks like you are trying to bump from version " ++ V.toString old ++ " to " ++ V.toString new ++ "." , "This implies you are making a " ++ show magnitude ++ " change, but when we compare" , "the " ++ V.toString old ++ " API to the API you have now it seems that it should" , "really be a " ++ show (Compare.packageChangeMagnitude changes) ++ " change (" ++ V.toString realNew ++ ")." , "" , "Run the following command to see the API diff we are working from:" , "" , " elm-package diff " ++ V.toString old , "" , "The easiest way to bump versions is to let us do it automatically. If you set" , "the version number in " ++ Path.description ++ " to the released version" , "that you are improving upon, we will compute which version should come next" , "when you run:" , "" , " elm-package bump" ] -- VALID BUMPS validBumps :: [V.Version] -> [(V.Version, V.Version, Compare.Magnitude)] validBumps publishedVersions = [ (majorPoint, V.bumpMajor majorPoint, Compare.MAJOR) ] ++ map (\v -> (v, V.bumpMinor v, Compare.MINOR)) minorPoints ++ map (\v -> (v, V.bumpPatch v, Compare.PATCH)) patchPoints where patchPoints = V.filterLatest V.majorAndMinor publishedVersions minorPoints = V.filterLatest V.major publishedVersions majorPoint = head publishedVersions
rtfeldman/elm-package
src/Bump.hs
Haskell
bsd-3-clause
8,561
-- HSlippyMap Exemple import HSlippyMap {-- let max = tileFromLatLong 48.9031 2.5214 10 let min = tileFromLatLong 48.8146 2.1732 10 mapM (\(x,y) -> mapM (\y'-> print $ "http://tile.openstreetmap.org/" ++ show z ++ "/" \ ++ show x ++ "/" ++ show y' ++ ".png") y) [(x,[(minimum [tymin, tymax])..(maximum [tymin\ ,tymax])]) | x <- [(minimum [txmin, txmax])..(maximum [txmin, txmax])]] --} main = do --mapM (print . show . tileFromLatLong lat long) [0..18] mapM (\(x,y) -> mapM (\y'-> print $ "http://tile.openstreetmap.org/" ++ show z ++ "/" ++ show x ++ "/" ++ show y' ++ ".png") y) [(x,[(minimum [tymin, tymax])..(maximum [tymin,tymax])]) | x <- [(minimum [txmin, txmax])..(maximum [txmin, txmax])]] where min = tileFromLatLong 49.13 3.05 8 max = tileFromLatLong (-48.57) 1.66 8 txmin = tx min txmax = tx max tymax = ty min tymin = ty max z = tz min
j4/HSlippyMap
hsl.hs
Haskell
bsd-3-clause
914
{- - Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Hacq. - Hacq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE UndecidableInstances #-} -- | A class for monads which describe quantum circuits, with various gates and circuit combinators. module Control.Monad.Quantum.Base.Class ( Bit(..), negateBit, bit, MonadQuantumBase(..), newWires, ancillae, applyZ, applyS, applyT, applyZC, cnotWire, cnotWires, with_, parallel, parallel_, parallels, parallels_, mapParM, mapParM_, forParM, forParM_, swapWire, swapWires, bitToWire, cnotBit) where import Control.Applicative (Applicative, (<*>)) import qualified Control.Applicative as Applicative import Control.Monad (void, when) import Control.Monad.Reader (ReaderT(ReaderT), runReaderT) import Control.Monad.Trans (lift) import Data.Foldable (Foldable) import qualified Data.Foldable as Foldable import Data.Functor ((<$>)) import Data.Hashable (Hashable(hashWithSalt)) import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.Traversable (Traversable) import qualified Data.Traversable as Traversable import Data.Typeable (Typeable) import Control.Monad.Memo.Null import Util (replicateA_, genericReplicateA_) -- |A Bit is a Boolean constant, a wire, or the negation of a wire. -- A circuit can accept a Bit as part of its input when the operation -- implemented by the circuit is block-diagonal with respect to that qubit of the input. data Bit w = BitConst !Bool | BitWire !Bool w deriving (Eq, Show, Functor, Foldable, Traversable, Typeable) instance Hashable w => Hashable (Bit w) where s `hashWithSalt` (BitConst False) = s `hashWithSalt` (0 :: Int) s `hashWithSalt` (BitConst True) = s `hashWithSalt` (1 :: Int) s `hashWithSalt` (BitWire False w) = s `hashWithSalt` (2 :: Int) `hashWithSalt` w s `hashWithSalt` (BitWire True w) = s `hashWithSalt` (3 :: Int) `hashWithSalt` w -- |The negation of a `Bit`. negateBit :: Bit w -> Bit w negateBit (BitConst b) = BitConst $ not b negateBit (BitWire neg w) = BitWire (not neg) w -- |Convert a wire to a `Bit`. bit :: w -> Bit w bit = BitWire False -- | A monad which represents basic quantum circuits and their compositions. -- @w@ is the type for wires. class (Applicative m, Monad m) => MonadQuantumBase w m | m -> w where -- | Return a new qubit. newWire :: m w -- | Return a new qubit which is initialized to |0\>. ancilla :: m w -- | Apply NOT (Pauli-X) to the given wire. applyX :: w -> m () -- | Apply the Pauli-Y gate. applyY :: w -> m () -- | Apply the Pauli-Z gate to a wire or its negation. -- This is the low-level interface for an implementor of `MonadQuantumBase`; -- for a user, it is easier to use `applyZ`. rawApplyZ :: w -> Bool -> m () -- | Apply the Hadamard gate. applyH :: w -> m () -- | Apply the S gate, or its inverse if the third argument is True. -- This is the low-level interface for an implementor of `MonadQuantumBase`; -- for a user, it is easier to use `applyS`. rawApplyS :: w -> Bool -> Bool -> m () -- | Apply the T gate, or its inverse if the third argument is True. -- This is the low-level interface for an implementor of `MonadQuantumBase`; -- for a user, it is easier to use `applyT`. rawApplyT :: w -> Bool -> Bool -> m () -- | Negate the global phase. -- This is no-op if the current control context is empty. negateGlobalPhase :: m () -- | Shift the global phase by pi/2 (if the argument is False) or -pi/2 (if the argument is True). -- This is no-op if the current control context is empty. rotateGlobalPhase90 :: Bool -> m () -- | Shift the global phase by pi/4 (if the argument is False) or -pi/4 (if the argument is True). -- This is no-op if the current control context is empty. rotateGlobalPhase45 :: Bool -> m () -- | Apply controlled Pauli-Z. -- -- The two wires must be different. rawApplyZC :: w -> Bool -> w -> Bool -> m () -- | @cnotWire w w1@ applies CNOT (controlled Pauli-X) with target @w@ controlled by @w1@. -- -- @w@ and @w1@ must not refer to the same wire. rawCnotWire :: w -> w -> Bool -> m () -- | Given two sequences of wires, apply CNOT to each pair of wires at the corresponding position. -- -- Precondition: -- -- * The given wires are all distinct. rawCnotWires :: [(w, w, Bool)] -> m () -- | @with prepare body@ is the sequential composition of @prepare@, @body@, and the inverse of @prepare@, -- where @body@ takes the result of @prepare@ as its argument. -- -- Precondition: -- -- * The composition restores all the ancillae introduced by @prepare@ to the initial state |0\>. with :: m a -> (a -> m b) -> m b -- | Apply given two circuits, possibly in parallel. -- Implementations may choose to apply the given circuits sequentially. -- -- Precondition: -- -- * The two circuits do not refer to the same wire. bindParallel :: m a -> (a -> m b) -> m b -- | Apply the inverse of a given unitary circuit. -- -- Precondition: -- -- * The given circuit is unitary; that is, the circuit deallocates all new wires which it allocates. invert :: m a -> m a -- |Apply the given circuit with the empty control context. withoutCtrls :: m a -> m a -- | @replicateQ n m@ evaluates to the sequential composition of @n@ copies of circuit @m@. {-# INLINABLE replicateQ #-} replicateQ :: Int -> m a -> m (Seq a) replicateQ = Seq.replicateA -- | @replicateParallelQ n m@ evaluates to the possibly parallel composition of @n@ copies of circuit @m@. -- This is useful when preparing many copies of a state in new wires without referring to any old wires. -- -- Precondition: -- -- * No two of the @n@ copies refer to the same wire. -- This means that the given circuit cannot refer to any old wires unless @n@ <= 1. {-# INLINABLE replicateParallelQ #-} replicateParallelQ :: Int -> m a -> m (Seq a) replicateParallelQ n = getParallel . Seq.replicateA n . Parallel -- | @replicateQ_ n m@ evaluates to the sequential composition of @n@ copies of circuit @m@, and discards the result. {-# INLINABLE replicateQ_ #-} replicateQ_ :: Int -> m () -> m () replicateQ_ = replicateA_ -- | @replicateParallelQ n m@ evaluates to the possibly parallel composition of @n@ copies of circuit @m@, and discards the result. -- -- Precondition: -- -- * No two of the @n@ copies refer to the same wire. -- This means that the given circuit cannot refer to any old wires unless @n@ <= 1. {-# INLINABLE replicateParallelQ_ #-} replicateParallelQ_ :: Int -> m () -> m () replicateParallelQ_ n = getParallel . replicateA_ n . Parallel -- | Generic version of `replicateQ_`. -- -- Note: There is no @genericReplicateQ@ because `Seq` cannot handle size larger than `Int`. {-# INLINABLE genericReplicateQ_ #-} genericReplicateQ_ :: Integral i => i -> m () -> m () genericReplicateQ_ = genericReplicateA_ -- | Generic version of `replicateParallelQ_`. -- -- Note: There is no @genericFastReplicateParallelM@ because `Seq` cannot handle size larger than `Int`. {-# INLINABLE genericReplicateParallelQ_ #-} genericReplicateParallelQ_ :: Integral i => i -> m () -> m () genericReplicateParallelQ_ n = getParallel . genericReplicateA_ n . Parallel -- | Return new qubits. newWires :: MonadQuantumBase w m => Int -> m (Seq w) newWires n | n >= 0 = replicateParallelQ n newWire | otherwise = error "newWires: the number of qubits must be nonnegative" {-# INLINABLE newWires #-} -- | Return new qubits which are initialized to |0\>. ancillae :: MonadQuantumBase w m => Int -> m (Seq w) ancillae n | n >= 0 = replicateParallelQ n ancilla | otherwise = error "ancillae: the number of ancillae must be nonnegative" {-# INLINABLE ancillae #-} -- | Apply the Pauli-Z gate. applyZ :: MonadQuantumBase w m => Bit w -> m () applyZ (BitConst False) = return () applyZ (BitConst True) = negateGlobalPhase applyZ (BitWire neg w) = rawApplyZ w neg -- | Apply the S gate, or its inverse if the second argument is True. applyS :: MonadQuantumBase w m => Bit w -> Bool -> m () applyS (BitConst False) _ = return () applyS (BitConst True) inv = rotateGlobalPhase90 inv applyS (BitWire neg w) inv = rawApplyS w neg inv -- | Apply the T gate, or its inverse if the second argument is True. applyT :: MonadQuantumBase w m => Bit w -> Bool -> m () applyT (BitConst False) _ = return () applyT (BitConst True) inv = rotateGlobalPhase45 inv applyT (BitWire neg w) inv = rawApplyT w neg inv -- | Apply controlled Pauli-Z. -- -- The two wires must be different. applyZC :: MonadQuantumBase w m => Bit w -> Bit w -> m () applyZC (BitConst False) _ = return () applyZC (BitConst True) b = applyZ b applyZC _ (BitConst False) = return () applyZC a (BitConst True) = applyZ a applyZC (BitWire nega a) (BitWire negb b) = rawApplyZC a nega b negb -- | @cnotWire w w1@ applies CNOT (controlled Pauli-X) with target @w@ controlled by @w1@. -- -- @w@ and @w1@ must not refer to the same wire. cnotWire :: MonadQuantumBase w m => w -> Bit w -> m () cnotWire _ (BitConst False) = return () cnotWire w (BitConst True) = applyX w cnotWire w (BitWire neg w1) = rawCnotWire w w1 neg -- | Given two sequences of wires, apply CNOT to each pair of wires at the corresponding position. -- -- Precondition: -- -- * The given wires are all distinct. cnotWires :: MonadQuantumBase w m => Seq w -> Seq (Bit w) -> m () cnotWires targ ctrl = if Seq.length targ /= Seq.length ctrl then error "cnotWires: lengths do not match" else if null cnots then if null nots then return () else mapParM_ applyX nots else if null nots then rawCnotWires cnots else parallel_ (rawCnotWires cnots) (mapParM_ applyX nots) where pairs = zip (Foldable.toList targ) (Foldable.toList ctrl) cnots = [(t, c, neg) | (t, BitWire neg c) <- pairs] nots = [t | (t, BitConst True) <- pairs] -- | @with_ prepare body@ is the sequential composition of @prepare@, @body@, and the inverse of @prepare@. -- The result of @prepare@ is discarded. -- -- Precondition: -- -- * The composition restores all the ancillae introduced by @prepare@ to the initial state |0\>. with_ :: MonadQuantumBase w m => m () -> m a -> m a with_ prepare body = with prepare (const body) {-# INLINABLE with_ #-} -- | Apply given two circuits, possibly in parallel. -- Implementations may choose to apply the given circuits sequentially. -- -- Precondition: -- -- * The two circuits do not refer to the same wire. parallel :: MonadQuantumBase w m => m a -> m b -> m (a, b) parallel ma mb = bindParallel ma (\a -> (\b -> (a, b)) <$> mb) -- | The same as `parallel`, but discards the result. parallel_ :: MonadQuantumBase w m => m a -> m b -> m () parallel_ a b = void (parallel a b) {-# INLINABLE parallel_ #-} -- Although any instance of MonadQuantumBase is an applicative functor, -- @pure@ may not be an identity of @\mf mx -> uncurry id <$> parallel mf mx@ -- because @parallel@ may compress the control context. -- This is why we define two cases here. data Parallel w m a = ParallelPure a | Parallel (m a) deriving Functor getParallel :: Applicative m => Parallel w m a -> m a getParallel (ParallelPure x) = Applicative.pure x getParallel (Parallel mx) = mx instance MonadQuantumBase w m => Applicative (Parallel w m) where pure = ParallelPure ParallelPure f <*> mx = f <$> mx Parallel mf <*> ParallelPure x = Parallel (($ x) <$> mf) Parallel mf <*> Parallel mx = Parallel (uncurry id <$> parallel mf mx) -- | Apply the circuits in the given container possibly in parallel, and return the results in the container of the same form. -- -- Precondition: -- -- No two of the given circuits refer to the same wire. parallels :: (MonadQuantumBase w m, Traversable t) => t (m a) -> m (t a) parallels ms = getParallel $ Traversable.traverse Parallel ms {-# INLINABLE parallels #-} -- | Apply the circuits in the given container possibly in parallel, and discard the results. -- -- Precondition: -- -- No two of the given circuits refer to the same wire. parallels_ :: (MonadQuantumBase w m, Foldable t) => t (m a) -> m () parallels_ ms = getParallel $ Foldable.traverse_ Parallel ms {-# INLINABLE parallels_ #-} -- | Apply the circuit to the elements in the given container possibly in parallel, -- and return the results in the container of the same form. -- -- Precondition: -- -- No two of the given circuits refer to the same wire. mapParM :: (MonadQuantumBase w m, Traversable t) => (a -> m b) -> t a -> m (t b) mapParM f xs = getParallel $ Traversable.traverse (Parallel . f) xs {-# INLINABLE mapParM #-} -- | Apply the circuit to the elements in the given container possibly in parallel, and discard the results. -- -- Precondition: -- -- No two of the given circuits refer to the same wire. mapParM_ :: (MonadQuantumBase w m, Foldable t) => (a -> m b) -> t a -> m () mapParM_ f xs = getParallel $ Foldable.traverse_ (Parallel . f) xs {-# INLINABLE mapParM_ #-} -- | `mapParM` with its arguments flipped. forParM :: (MonadQuantumBase w m, Traversable t) => t a -> (a -> m b) -> m (t b) forParM = flip mapParM {-# INLINABLE forParM #-} -- | `mapParM_` with its arguments flipped. forParM_ :: (MonadQuantumBase w m, Foldable t) => t a -> (a -> m b) -> m () forParM_ = flip mapParM_ {-# INLINABLE forParM_ #-} -- | Apply the swap gate to two wires. -- -- The two wires must be distinct. swapWire :: MonadQuantumBase w m => w -> w -> m () swapWire w1 w2 = with_ (cnotWire w1 (bit w2)) $ cnotWire w2 (bit w1) {-# INLINABLE swapWire #-} -- | Given two sequences of wires, apply the swap gate to each pair of wires at the corresponding position. -- -- All the given wires must be distinct. swapWires :: MonadQuantumBase w m => Seq w -> Seq w -> m () swapWires ws1 ws2 = if Seq.length ws1 /= Seq.length ws2 then error "swapWires: lengths do not match" else with_ (cnotWires ws1 (bit <$> ws2)) $ cnotWires ws2 (bit <$> ws1) {-# INLINABLE swapWires #-} -- |Convert a `Bit` to a wire, possibly consuming the given Bit. -- -- If the input `Bit` is a wire, the returned wire is the same as the input wire. -- Therefore, the input bit should be considered as “consumed” -- while the wire returned by this function is being used. bitToWire :: MonadQuantumBase w m => Bit w -> m w bitToWire (BitConst b) = withoutCtrls $ do w <- ancilla when b $ applyX w return w bitToWire (BitWire neg w) = withoutCtrls $ do when neg $ applyX w return w {-# INLINABLE bitToWire #-} -- |@cnotBit t c@ returns a `Bit` representing @t XOR c@, possibly consuming @t@. -- -- If @t@ is a wire, then this wire is returned. -- Therefore, @t@ should be considered as “consumed” -- while the bit returned by this function is being used. cnotBit :: MonadQuantumBase w m => Bit w -> Bit w -> m (Bit w) cnotBit (BitConst t) (BitConst c) = return $ BitConst (t /= c) cnotBit t c = withoutCtrls $ do t' <- bitToWire t cnotWire t' c return $ bit t' {-# INLINABLE cnotBit #-} -- Instance for ReaderT -- Requires UndecidableInstances. instance MonadQuantumBase w m => MonadQuantumBase w (ReaderT r m) where newWire = lift newWire {-# INLINABLE newWire #-} ancilla = lift ancilla {-# INLINABLE ancilla #-} applyX w = lift $ applyX w {-# INLINABLE applyX #-} applyY w = lift $ applyY w {-# INLINABLE applyY #-} rawApplyZ w neg = lift $ rawApplyZ w neg {-# INLINABLE rawApplyZ #-} applyH w = lift $ applyH w {-# INLINABLE applyH #-} rawApplyS w neg inv = lift $ rawApplyS w neg inv {-# INLINABLE rawApplyS #-} rawApplyT w neg inv = lift $ rawApplyT w neg inv {-# INLINABLE rawApplyT #-} negateGlobalPhase = lift negateGlobalPhase {-# INLINABLE negateGlobalPhase #-} rotateGlobalPhase90 = lift . rotateGlobalPhase90 {-# INLINABLE rotateGlobalPhase90 #-} rotateGlobalPhase45 = lift . rotateGlobalPhase45 {-# INLINABLE rotateGlobalPhase45 #-} rawApplyZC a nega b negb = lift $ rawApplyZC a nega b negb {-# INLINABLE rawApplyZC #-} rawCnotWire w w1 neg = lift $ rawCnotWire w w1 neg {-# INLINABLE rawCnotWire #-} rawCnotWires ws = lift $ rawCnotWires ws {-# INLINABLE rawCnotWires #-} with prepare body = ReaderT $ \r -> with (runReaderT prepare r) $ \a -> runReaderT (body a) r {-# INLINABLE with #-} bindParallel m1 m2 = ReaderT $ \r -> bindParallel (runReaderT m1 r) (\a -> runReaderT (m2 a) r) {-# INLINABLE bindParallel #-} invert m = ReaderT $ \r -> invert (runReaderT m r) {-# INLINABLE invert #-} withoutCtrls m = ReaderT $ \r -> withoutCtrls (runReaderT m r) replicateQ n m = ReaderT $ \r -> replicateQ n (runReaderT m r) {-# INLINABLE replicateQ #-} replicateParallelQ n m = ReaderT $ \r -> replicateParallelQ n (runReaderT m r) {-# INLINABLE replicateParallelQ #-} replicateQ_ n m = ReaderT $ \r -> replicateQ_ n (runReaderT m r) {-# INLINABLE replicateQ_ #-} replicateParallelQ_ n m = ReaderT $ \r -> replicateParallelQ_ n (runReaderT m r) {-# INLINABLE replicateParallelQ_ #-} genericReplicateQ_ n m = ReaderT $ \r -> genericReplicateQ_ n (runReaderT m r) {-# INLINABLE genericReplicateQ_ #-} genericReplicateParallelQ_ n m = ReaderT $ \r -> genericReplicateParallelQ_ n (runReaderT m r) {-# INLINABLE genericReplicateParallelQ_ #-} -- Instance for MemoNullT -- Requires UndecidableInstances. instance MonadQuantumBase w m => MonadQuantumBase w (MemoNullT k m) where newWire = lift newWire {-# INLINABLE newWire #-} ancilla = lift ancilla {-# INLINABLE ancilla #-} applyX w = lift $ applyX w {-# INLINABLE applyX #-} applyY w = lift $ applyY w {-# INLINABLE applyY #-} rawApplyZ w neg = lift $ rawApplyZ w neg {-# INLINABLE rawApplyZ #-} applyH w = lift $ applyH w {-# INLINABLE applyH #-} rawApplyS w neg inv = lift $ rawApplyS w neg inv {-# INLINABLE rawApplyS #-} rawApplyT w neg inv = lift $ rawApplyT w neg inv {-# INLINABLE rawApplyT #-} negateGlobalPhase = lift negateGlobalPhase {-# INLINABLE negateGlobalPhase #-} rotateGlobalPhase90 = lift . rotateGlobalPhase90 {-# INLINABLE rotateGlobalPhase90 #-} rotateGlobalPhase45 = lift . rotateGlobalPhase45 {-# INLINABLE rotateGlobalPhase45 #-} rawApplyZC a nega b negb = lift $ rawApplyZC a nega b negb {-# INLINABLE rawApplyZC #-} rawCnotWire w w1 neg = lift $ rawCnotWire w w1 neg {-# INLINABLE rawCnotWire #-} rawCnotWires ws = lift $ rawCnotWires ws {-# INLINABLE rawCnotWires #-} with prepare body = MemoNullT $ with (runMemoNullT prepare) $ \a -> runMemoNullT (body a) {-# INLINABLE with #-} bindParallel m1 m2 = MemoNullT $ bindParallel (runMemoNullT m1) (\a -> runMemoNullT (m2 a)) {-# INLINABLE bindParallel #-} invert m = MemoNullT $ invert (runMemoNullT m) {-# INLINABLE invert #-} withoutCtrls m = MemoNullT $ withoutCtrls (runMemoNullT m) replicateQ n m = MemoNullT $ replicateQ n (runMemoNullT m) {-# INLINABLE replicateQ #-} replicateParallelQ n m = MemoNullT $ replicateParallelQ n (runMemoNullT m) {-# INLINABLE replicateParallelQ #-} replicateQ_ n m = MemoNullT $ replicateQ_ n (runMemoNullT m) {-# INLINABLE replicateQ_ #-} replicateParallelQ_ n m = MemoNullT $ replicateParallelQ_ n (runMemoNullT m) {-# INLINABLE replicateParallelQ_ #-} genericReplicateQ_ n m = MemoNullT $ genericReplicateQ_ n (runMemoNullT m) {-# INLINABLE genericReplicateQ_ #-} genericReplicateParallelQ_ n m = MemoNullT $ genericReplicateParallelQ_ n (runMemoNullT m) {-# INLINABLE genericReplicateParallelQ_ #-}
ti1024/hacq
src/Control/Monad/Quantum/Base/Class.hs
Haskell
bsd-3-clause
20,174
{-# LANGUAGE FlexibleContexts #-} -------------------------------------------------------------------------------- -- | -- Module : Network.OpenID.Discovery -- Copyright : (c) Trevor Elliott, 2008 -- License : BSD3 -- -- Maintainer : Trevor Elliott <trevor@geekgateway.com> -- Stability : -- Portability : -- module Network.OpenID.Discovery ( -- * Discovery discover ) where -- Friends import Network.OpenID.Types import Text.XRDS -- Libraries import Data.Char import Data.List import Data.Maybe import MonadLib import Network.HTTP import Network.URI type M = ExceptionT Error -- | Attempt to resolve an OpenID endpoint, and user identifier. discover :: Monad m => Resolver m -> Identifier -> m (Either Error (Provider,Identifier)) discover resolve ident = do res <- runExceptionT (discoverYADIS resolve ident Nothing) case res of Right {} -> return res _ -> runExceptionT (discoverHTML resolve ident) -- YADIS-Based Discovery ------------------------------------------------------- -- | Attempt a YADIS based discovery, given a valid identifier. The result is -- an OpenID endpoint, and the actual identifier for the user. discoverYADIS :: Monad m => Resolver m -> Identifier -> Maybe String -> M m (Provider,Identifier) discoverYADIS resolve ident mb_loc = do let err = raise . Error uri = fromMaybe (getIdentifier ident) mb_loc case parseURI uri of Nothing -> err "Unable to parse identifier as a URI" Just uri -> do estr <- lift $ resolve Request { rqMethod = GET , rqURI = uri , rqHeaders = [] , rqBody = "" } case estr of Left e -> err $ "HTTP request error: " ++ show e Right rsp -> case rspCode rsp of (2,0,0) -> case findHeader (HdrCustom "X-XRDS-Location") rsp of Just loc -> discoverYADIS resolve ident (Just loc) _ -> do let e = err "Unable to parse YADIS document" doc <- maybe e return $ parseXRDS $ rspBody rsp parseYADIS ident doc _ -> err $ "HTTP request error: unexpected response code "++show (rspCode rsp) -- | Parse out an OpenID endpoint, and actual identifier from a YADIS xml -- document. parseYADIS :: ExceptionM m Error => Identifier -> XRDS -> m (Provider,Identifier) parseYADIS ident = handleError . listToMaybe . mapMaybe isOpenId . concat where handleError = maybe e return where e = raise (Error "YADIS document doesn't include an OpenID provider") isOpenId svc = do let tys = serviceTypes svc localId = maybe ident Identifier $ listToMaybe $ serviceLocalIDs svc f (x,y) | x `elem` tys = Just y | otherwise = mzero lid <- listToMaybe $ mapMaybe f [ ("http://specs.openid.net/auth/2.0/server", ident) -- claimed identifiers , ("http://specs.openid.net/auth/2.0/signon", localId) , ("http://openid.net/signon/1.0" , localId) , ("http://openid.net/signon/1.1" , localId) ] uri <- parseProvider =<< listToMaybe (serviceURIs svc) return (uri,lid) -- HTML-Based Discovery -------------------------------------------------------- -- | Attempt to discover an OpenID endpoint, from an HTML document. The result -- will be an endpoint on success, and the actual identifier of the user. discoverHTML :: Monad m => Resolver m -> Identifier -> M m (Provider,Identifier) discoverHTML resolve ident = do let err = raise . Error case parseURI (getIdentifier ident) of Nothing -> err "Unable to parse identifier as a URI" Just uri -> do estr <- lift $ resolve Request { rqMethod = GET , rqURI = uri , rqHeaders = [] , rqBody = "" } case estr of Left e -> err $ "HTTP request error: " ++ show e Right rsp -> case rspCode rsp of (2,0,0) -> maybe (err "Unable to find identifier in HTML") return $ parseHTML ident $ rspBody rsp _ -> err $ "HTTP request error: unexpected response code "++show (rspCode rsp) -- | Parse out an OpenID endpoint and an actual identifier from an HTML -- document. parseHTML :: Identifier -> String -> Maybe (Provider,Identifier) parseHTML ident = resolve . filter isOpenId . linkTags . htmlTags where isOpenId (rel,_) = "openid" `isPrefixOf` rel resolve ls = do prov <- parseProvider =<< lookup "openid2.provider" ls let lid = maybe ident Identifier $ lookup "openid2.local_id" ls return (prov,lid) -- | Filter out link tags from a list of html tags. linkTags :: [String] -> [(String,String)] linkTags = mapMaybe f . filter p where p = ("link " `isPrefixOf`) f xs = do let ys = unfoldr splitAttr (drop 5 xs) x <- lookup "rel" ys y <- lookup "href" ys return (x,y) -- | Split a string into strings of html tags. htmlTags :: String -> [String] htmlTags [] = [] htmlTags xs = case break (== '<') xs of (as,_:bs) -> fmt as : htmlTags bs (as,[]) -> [as] where fmt as = case break (== '>') as of (bs,_) -> bs -- | Split out values from a key="value" like string, in a way that -- is suitable for use with unfoldr. splitAttr :: String -> Maybe ((String,String),String) splitAttr xs = case break (== '=') xs of (_,[]) -> Nothing (key,_:'"':ys) -> f key (== '"') ys (key,_:ys) -> f key isSpace ys where f key p cs = case break p cs of (_,[]) -> Nothing (value,_:rest) -> Just ((key,value), dropWhile isSpace rest)
substack/hsopenid
src/Network/OpenID/Discovery.hs
Haskell
bsd-3-clause
5,704
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.DList.Instances () where -- don't define instance for dlist>=0.8 && base>=4.9 #if !(MIN_VERSION_base(4,9,0)) || !(MIN_VERSION_dlist(0,8,0)) import Data.DList import Data.Semigroup instance Semigroup (DList a) where (<>) = append #endif
gregwebs/dlist-instances
Data/DList/Instances.hs
Haskell
bsd-3-clause
311
{-# LANGUAGE NoImplicitPrelude, UnicodeSyntax, OverloadedStrings, TemplateHaskell #-} module Help.Settings ( -- *The Settings type Settings -- *Lens getters for Settings , ymlFile , logFile , logCollection , logParser , adminHost , adminPort , database , servers , mongoHost -- *The TCPConnection type , TCPConnection -- *Lens getters for TCPConnections , port , collection , parser -- *Utilities , loadSettings ) where import Help.Imports import Help.Logging.Parse import Control.Lens.Getter (to, Getter) import qualified Data.Yaml.Config as YAML (lookup, load) import Data.Aeson.Types hiding (Parser, parse) import Data.Attoparsec.Text import Database.MongoDB (Document) import Options data Settings = Settings { _ymlFile ∷ FilePath , _logFile ∷ FilePath , _logCollection ∷ Text , _logParser ∷ Maybe (Parser Document) , _database ∷ Text , _adminHost ∷ FilePath , _adminPort ∷ Int , _servers ∷ [TCPConnection] , _mongoHost ∷ String } data TCPConnection = TCPConnection { _port ∷ Int , _collection ∷ Text , _parser ∷ Parser Document } data TempSettings = TempSettings { tempYmlFile ∷ Maybe FilePath , tempLogFile ∷ Maybe FilePath , tempLogCollection ∷ Maybe Text , tempLogParser ∷ Maybe (Parser Document) , tempDatabase ∷ Maybe Text , tempAdminHost ∷ Maybe String , tempAdminPort ∷ Maybe Int , tempServers ∷ Maybe [TCPConnection] , tempMongoHost ∷ Maybe String } instance FromJSON TCPConnection where parseJSON (Object v) = do testRecord <- v .: "sampleRecord" parserLine <- v .: "recordFormat" let p = makeRecordParser parserLine if not $ goodParser p testRecord then error $ "Specified parser does not parse line " ++ unpack parserLine else do TCPConnection <$> v .: "port" <*> v .: "collection" <*> (pure $! p) parseJSON _ = mempty goodParser ∷ Parser Document → Text → Bool goodParser p t = let parseResult = parse p t in case parseResult of Done "" _ -> True _ -> False ymlFile ∷ Getter Settings FilePath ymlFile = to _ymlFile logFile ∷ Getter Settings FilePath logFile = to _logFile logCollection ∷ Getter Settings Text logCollection = to _logCollection logParser ∷ Getter Settings (Maybe (Parser Document)) logParser = to _logParser database ∷ Getter Settings Text database = to _database adminHost ∷ Getter Settings FilePath adminHost = to _adminHost adminPort ∷ Getter Settings Int adminPort = to _adminPort servers ∷ Getter Settings [TCPConnection] servers = to _servers port ∷ Getter TCPConnection Int port = to _port collection ∷ Getter TCPConnection Text collection = to _collection parser ∷ Getter TCPConnection (Parser Document) parser = to _parser mongoHost ∷ Getter Settings String mongoHost = to _mongoHost defineOptions "MainOptions" $ do stringOption "cliYml" "yamlFile" "help.yaml" "The default YAML configuration file" stringOption "cliLogFile" "logFile" "" "A log file from which to import" textOption "cliLogCollection" "collection" "default" "The MongoDB collection to import to" textOption "cliRecordFormat" "recordFormat" "" "The format of the records in the log file" -- |Loads all settings and creates one authoritative set loadSettings ∷ IO Settings loadSettings = do cliSettings ← loadCLISettings ymlSettings ← loadYMLSettings $ loadableYmlFile $ cliSettings `overrides` defaultSettings return $ verifySettings $ cliSettings `overrides` ymlSettings `overrides` defaultSettings -- |Changes a TempSettings to a Settings, assuming it contains all required options verifySettings ∷ TempSettings → Settings verifySettings (TempSettings (Just s1) (Just s2) (Just s3) s4 (Just s5) (Just s6) (Just s7) (Just s8) (Just s9)) = Settings s1 s2 s3 s4 s5 s6 s7 s8 s9 verifySettings _ = error "Not all settings set" -- TODO: Handle this better -- |Loads command-line settings from the output of @getArgs@ loadCLISettings ∷ IO TempSettings loadCLISettings = runCommand $ \opts _ -> do let p = if null $ cliYml opts then Nothing else Just $! makeRecordParser $ cliRecordFormat opts return $ emptySettings { tempYmlFile = (Just $ cliYml opts) , tempLogFile = (Just $ cliLogFile opts) , tempLogCollection = (Just $ cliLogCollection opts) , tempLogParser = p } -- |Loads settings from a YAML file loadYMLSettings ∷ FilePath → IO TempSettings loadYMLSettings yamlFile = do yaml <- YAML.load yamlFile let aHost = YAML.lookup yaml "adminHost" aPort = YAML.lookup yaml "adminPort" serve = YAML.lookup yaml "servers" mHost = YAML.lookup yaml "mongoHost" datab = YAML.lookup yaml "database" return $ TempSettings Nothing Nothing datab Nothing Nothing aHost aPort serve mHost -- |Default settings defaultSettings ∷ TempSettings defaultSettings = TempSettings (Just "help.yaml") Nothing Nothing Nothing (Just "help-db") (Just "localhost") (Just 8080) Nothing (Just "127.0.0.1") -- |Empty settings emptySettings ∷ TempSettings emptySettings = TempSettings Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing -- |Takes two TempSettings and returns a new TempSettings, favoring settings in the first over the second overrides ∷ TempSettings → TempSettings → TempSettings overrides ns os = let yF = if isJust $ tempYmlFile ns then tempYmlFile ns else tempYmlFile os lF = if isJust $ tempLogFile ns then tempLogFile ns else tempLogFile os lC = if isJust $ tempLogCollection ns then tempLogCollection ns else tempLogCollection os lP = if isJust $ tempLogParser ns then tempLogParser ns else tempLogParser os db = if isJust $ tempDatabase ns then tempDatabase ns else tempDatabase os aH = if isJust $ tempAdminHost ns then tempAdminHost ns else tempAdminHost os aP = if isJust $ tempAdminPort ns then tempAdminPort ns else tempAdminPort os ss = if isJust $ tempServers ns then tempServers ns else tempServers os mH = if isJust $ tempMongoHost ns then tempMongoHost ns else tempMongoHost os in TempSettings yF lF lC lP db aH aP ss mH -- |Pull the YAML file from TempSettings. In the event that the current stack doesn't have a file, fallback to default. -- -- IN THE EVENT THAT NO DEFAULT FILE EXISTS, THIS WILL LOOP INFINITELY! loadableYmlFile ∷ TempSettings → FilePath loadableYmlFile s = case tempYmlFile s of (Just f) → f Nothing → loadableYmlFile defaultSettings
argiopetech/help
Help/Settings.hs
Haskell
bsd-3-clause
8,648
{-# LANGUAGE OverloadedStrings #-} module Network.API.TLDR.Types.Time ( Time(..), LastActive(..), CreatedAt(..) ) where import Data.Aeson import Data.Aeson.Types (typeMismatch) import Data.Text (unpack) import Data.Time (parseTime, Day(..)) import Data.Time.RFC3339 (readRFC3339) import Data.Time.LocalTime (ZonedTime(..)) import System.Locale (defaultTimeLocale) newtype Time = Time {time :: ZonedTime} deriving (Show) instance FromJSON Time where parseJSON (String t) = case readRFC3339 (unpack t) of Just d -> return $ Time d _ -> fail "could not parse time" parseJSON v = typeMismatch "Time" v type LastActive = Time type CreatedAt = Time
joshrotenberg/tldrio-hs
Network/API/TLDR/Types/Time.hs
Haskell
bsd-3-clause
806