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 HERMIT.Set.Life where import Data.Set as Set import Data.List as List (nub,(\\)) import Life.Types -- Standard implementation type Board = LifeBoard Config [Pos] -- The new data structure to be used in the implementation type Board' = LifeBoard Config (Set Pos) -- Transformations required by hermit for worker/wrapper conversions -- repb and absb change the underlying board field {-# NOINLINE repb #-} repb :: [Pos] -> Set Pos repb = fromList {-# NOINLINE absb #-} absb :: Set Pos -> [Pos] absb = toList -- repB and absB change the entire Board structure {-# NOINLINE repB #-} repB :: Board -> Board' repB b = LifeBoard (config b) $ repb (board b) {-# NOINLINE absB #-} absB :: Board' -> Board absB b = LifeBoard (config b) $ absb (board b) -- rep for "alive" repBx :: (Board -> Scene) -> Board' -> Scene repBx f b = f (absB b) -- abs for "alive" absBx :: (Board' -> Scene) -> Board -> Scene absBx f b = f (repB b) --"isAlive", "isEmpty" repBpb :: (Board -> Pos -> Bool) -> Board' -> Pos -> Bool repBpb f b p = f (absB b) p absBpb :: (Board' -> Pos -> Bool) -> Board -> Pos -> Bool absBpb f b p = f (repB b) p --"liveneighbs" repBpi :: (Board -> Pos -> Int) -> Board' -> Pos -> Int repBpi f b p = f (absB b) p absBpi :: (Board' -> Pos -> Int) -> Board -> Pos -> Int absBpi f b p = f (repB b) p -- rep for "empty" repcB :: (Config -> Board) -> Config -> Board' repcB f c = repB (f c) -- abs for "empty" abscB :: (Config -> Board') -> Config -> Board abscB f c = absB (f c) -- rep for "inv" reppBB :: (Pos -> Board -> Board) -> Pos -> Board' -> Board' reppBB f x b = repB (f x (absB b)) -- abs for "inv" abspBB :: (Pos -> Board' -> Board') -> Pos -> Board -> Board abspBB f x b = absB (f x (repB b)) -- rep for "births", "survivors", "next" repBB :: (Board -> Board) -> Board' -> Board' repBB f b = repB (f (absB b)) -- abs for "births", "survivors", "next" absBB :: (Board' -> Board') -> Board -> Board absBB f b = absB (f (repB b)) -- GHC Rules for HERMIT -- Simplification rules {-# RULES "repb/absb-fusion" [~] forall b. repb (absb b) = b "LifeBoard-reduce" [~] forall b. LifeBoard (config b) (board b) = b #-} --Code replacement rules {-# RULES "empty-l/empty-s" [~] repb [] = Set.empty "not-elem/notMember" [~] forall p b. not (elem p (absb b)) = notMember p b "elem/member" [~] forall p b. elem p (absb b) = member p b "cons/insert" [~] forall p b. p : (absb b) = absb (insert p b) "filter/delete" [~] forall p b. Prelude.filter ((/=) p) (absb b) = absb (delete p b) "filter-l/filter-s" [~] forall f b. Prelude.filter f (absb b) = absb (Set.filter f b) "nub-concatMap/unions" [~] forall f b. nub (concatMap f (absb b)) = absb (unions (toList (Set.map (fromList . f) b))) "concat/union" [~] forall b1 b2. absb b1 ++ absb b2 = absb (union b1 b2) #-}
ku-fpg/better-life
HERMIT/Set/Life.hs
Haskell
bsd-2-clause
2,793
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Computations in logarithmic scale. module NLP.Nerf2.LogReal ( LogReal , fromLogReal , logToLogReal , logFromLogReal ) where import Prelude hiding (sum, product) import Data.Vector.Generic.Base import Data.Vector.Generic.Mutable import Data.Binary (Binary) import qualified Data.Vector.Unboxed as U newtype LogReal = LogReal Double deriving ( Show, Read, Eq, Ord, Binary , Vector U.Vector, MVector U.MVector, U.Unbox ) foreign import ccall unsafe "math.h log1p" log1p :: Double -> Double zero :: Double zero = -(1/0) isZero :: Double -> Bool isZero = (zero==) instance Num LogReal where LogReal x * LogReal y = LogReal $ x + y LogReal x + LogReal y | isZero x = LogReal $ y | x > y = LogReal $ x + log1p(exp(y - x)) | otherwise = LogReal $ y + log1p(exp(x - y)) LogReal _ - LogReal _ = error "LogReal: (-) not supported" negate _ = error "LogReal: negate not supported" abs = id signum (LogReal x) | x > zero = 1 | otherwise = 0 fromInteger x | x == 0 = LogReal zero | x > 0 = LogReal . log . fromInteger $ x | otherwise = error "LogReal: fromInteger on negative argument" instance Fractional LogReal where LogReal x / LogReal y = LogReal $ x - y fromRational x | x == 0 = LogReal zero | x > 0 = LogReal . log . fromRational $ x | otherwise = error "LogReal: fromRational on negative argument" -- This is simply a polymorphic version of the 'LogReal' data -- constructor. We present it mainly because we hide the constructor -- in order to make the type a bit more opaque. If the polymorphism -- turns out to be a performance liability because the rewrite rules -- can't remove it, then we need to rethink all four -- constructors\/destructors. -- -- | Constructor which assumes the argument is already in the -- log-domain. logToLogReal :: Double -> LogReal logToLogReal = LogReal -- | Return our log-domain value back into normal-domain. fromLogReal :: LogReal -> Double fromLogReal (LogReal x) = exp x -- | Return the log-domain value itself without conversion. logFromLogReal :: LogReal -> Double logFromLogReal (LogReal x) = x
kawu/nerf-proto
src/NLP/Nerf2/LogReal.hs
Haskell
bsd-2-clause
2,300
----------------------------------------------------------------------------- -- | -- Module : ByteFields -- Copyright : (c) Conrad Parker 2006 -- License : BSD-style -- -- Maintainer : conradp@cse.unsw.edu.au -- Stability : experimental -- Portability : portable -- -- Utilities for handling byte-aligned fields -- ----------------------------------------------------------------------------- module Codec.Container.Ogg.ByteFields ( be64At, be32At, be16At, le64At, le32At, le16At, u8At, le64Fill, le32Fill, le16Fill, u8Fill ) where import Data.Int (Int64) import Data.Word import qualified Data.ByteString.Lazy as L beNAt :: Integral a => Int64 -> Int64 -> L.ByteString -> a beNAt len off s = fromTwosComp $ reverse $ L.unpack (L.take len (L.drop off s)) be64At :: Integral a => Int64 -> L.ByteString -> a be64At = beNAt 8 be32At :: Integral a => Int64 -> L.ByteString -> a be32At = beNAt 4 be16At :: Integral a => Int64 -> L.ByteString -> a be16At = beNAt 2 leNAt :: Integral a => Int64 -> Int64 -> L.ByteString -> a leNAt len off s = fromTwosComp $ L.unpack (L.take len (L.drop off s)) le64At :: Integral a => Int64 -> L.ByteString -> a le64At = leNAt 8 le32At :: Integral a => Int64 -> L.ByteString -> a le32At = leNAt 4 le16At :: Integral a => Int64 -> L.ByteString -> a le16At = leNAt 2 u8At :: Integral a => Int64 -> L.ByteString -> a u8At = leNAt 1 -- Generate a ByteString containing the given number leNFill :: Integral a => Int -> a -> L.ByteString leNFill n x | l < n = L.pack $ (i ++ (take (n-l) $ repeat 0x00)) | l > n = error "leNFill too short" | otherwise = L.pack $ i where l = length i i = toTwosComp x le64Fill :: Integral a => a -> L.ByteString le64Fill = leNFill 8 le32Fill :: Integral a => a -> L.ByteString le32Fill = leNFill 4 le16Fill :: Integral a => a -> L.ByteString le16Fill = leNFill 2 u8Fill :: Integral a => a -> L.ByteString u8Fill = leNFill 1 -- | Convert to twos complement, unsigned, little endian toTwosComp :: Integral a => a -> [Word8] toTwosComp x = g $ f x where f y = (fromIntegral y) `divMod` 256 :: (Integer, Integer) g (0,b) = [fromIntegral b] g (a,b) = [fromIntegral b] ++ (g $ f a) -- | Convert from twos complement, unsigned, little endian fromTwosComp :: Integral a => [Word8] -> a fromTwosComp x = foldr (\a b -> fromIntegral a + b*256) 0 x
kfish/hogg
Codec/Container/Ogg/ByteFields.hs
Haskell
bsd-3-clause
2,417
{-# LANGUAGE CPP #-} {- Copyright (c) 2008 David Roundy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Franchise.Buildable ( Buildable(..), BuildRule(..), Dependency(..), build, buildWithArgs, buildTarget, bin, etc, man, install, installDoc, installData, installHtml, defaultRule, buildName, build', rm, clean, distclean, addToRule, addDependencies, addTarget, rule, simpleTarget, getBuildable, (|<-), getTarget, Target(..), phony, extraData ) where import Data.List ( sort, isSuffixOf, (\\) ) import System.Environment ( getArgs ) import System.Directory ( doesFileExist, removeFile, getModificationTime ) import Control.Concurrent ( readChan, writeChan, newChan ) import Control.Monad ( when, mplus ) import Distribution.Franchise.Util import Distribution.Franchise.ConfigureState import Distribution.Franchise.StringSet import Distribution.Franchise.Trie import Distribution.Franchise.GhcState ( getBinDir, getEtcDir, getManDir, getDataDir, getDocDir, getHtmlDir ) import Distribution.Franchise.Flags ( FranchiseFlag, handleArgs ) data Dependency = [String] :< [String] infix 2 :< data BuildRule = BuildRule { make :: Dependency -> C (), postinst :: Dependency -> Maybe (C ()), clean0 :: Dependency -> [String] } data Buildable = Dependency :<- BuildRule instance Eq Buildable where (xs:<_:<-_) == (ys:<_:<-_) = fromListS xs == fromListS ys (|<-) :: Dependency -> BuildRule -> Buildable (|<-) = (:<-) infix 1 :<- infix 1 |<- defaultRule :: BuildRule defaultRule = BuildRule (const $ return ()) (const $ Just $ return ()) cleanIt extraData :: String -> String extraData x = "config.d/"++x cleanIt :: Dependency -> [String] cleanIt (_:<[]) = [] cleanIt (xs:<_) = filter (not . isPhony) xs isPhony :: String -> Bool isPhony ('*':r) = case reverse r of ('*':_) -> True _ -> False isPhony _ = False phony :: String -> String phony x | isPhony x = x phony x = '*':x++"*" unphony :: String -> String unphony x = if isPhony x then init $ tail x else x rm :: String -> C () rm f | "/" `isSuffixOf` f = return () rm f = do noRm <- getNoRemove f' <- processFilePath f if not $ null noRm then putV $ "#rm "++f else do io $ removeFile f' putV $ "rm "++f `catchC` \_ -> return () depName :: Dependency -> [String] depName (n :< _) = n buildName :: Buildable -> [String] buildName (d:<-_) = depName d -- | 'build' is at the heart of any Setup.hs build script, and drives -- the entire build process. Its first argument is a list of flags -- you want the Setup.hs script to accept, and the second argument is -- the actual function that configures the build. build :: [C FranchiseFlag] -> C () -> IO () build opts mkbuild = do args <- getArgs buildWithArgs args opts mkbuild #ifndef FRANCHISE_VERSION #define FRANCHISE_VERSION "franchise (unknown)" #endif addPaths :: String -> [FilePath] -> C () addPaths v ps = do ps' <- mapM processFilePath ps addExtraUnique v ps' clean :: [FilePath] -> C () clean = addPaths "to-clean" distclean :: [FilePath] -> C () distclean = addPaths "to-distclean" (</>) :: FilePath -> FilePath -> FilePath "" </> x = x x </> ('/':y) = x </> y x </> y = reverse (dropWhile (=='/') $ reverse x) ++ '/':y -- | add the specified install to the install target. This function -- respects the DESTDIR environment variable, and should therefore be -- used for installing. install :: FilePath -- ^ file or directory to be installed -> FilePath -- ^ install location as an absolute path -> C () install x y = do x' <- processFilePath x addDependencies (phony "build") [x] destdir <- maybe "" id `fmap` getExtraData "destdir" addExtraUnique "to-install" [(x',destdir</>y)] installHelper :: C FilePath -> (FilePath -> FilePath) -> FilePath -> C () installHelper getdir cleanp x = do dir <- getdir install x (dir++"/"++cleanp x) -- | request that the given file be installed in the sysconfdir. This -- location may be modified at configure time via the environment -- variable PREFIX or SYSCONFDIR. etc :: FilePath -> C () etc = installHelper getEtcDir id -- | request that the given file be installed in the bindir. This -- location may be modified at configure time via the environment -- variable PREFIX or BINDIR. bin :: FilePath -> C () bin = installHelper getBinDir basename -- | request that the given file be installed in the mandir in the -- specified section. This location may be modified at configure time -- via the environment variable PREFIX, DATADIR or MANDIR. man :: Int -> FilePath -> C () man section = installHelper (getManDir section) basename -- | install the specified HTML file in an appropriate place for -- documentation. This location may be modified at configure time via -- the environment variables PREFIX, DATADIR, DOCDIR or HTMLDIR. installHtml :: FilePath -> C () installHtml = installHelper getHtmlDir id -- | install the specified file in the documentation location. This -- location may be modified at configure time via the environment -- variable PREFIX, DATADIR or DOCDIR. installDoc :: FilePath -> C () installDoc = installHelper getDocDir id -- | install in the data path. This location may be modified at -- configure time via the environment variable PREFIX or DATADIR. installData :: FilePath -> C () installData = installHelper getDataDir id buildWithArgs :: [String] -> [C FranchiseFlag] -> C () -> IO () buildWithArgs args opts mkbuild = runC $ do putV $ "compiled with franchise version "++FRANCHISE_VERSION rule [phony "clean"] [] $ do toclean <- getExtra "to-clean" mapM_ rm_rf toclean rule [phony "distclean"] [] $ do toclean <- getExtra "to-clean" dist <- getExtra "to-distclean" mapM_ rm_rf (toclean++dist) rule [phony "copy"] [phony "build"] $ do is <- getExtra "to-install" let inst (x, y) = do mkdir (dirname y) cp x y mapM_ inst is rule [phony "uncopy"] [] $ do is <- getExtra "to-install" mapM_ (rm_rf . snd) (is :: [(String,String)]) rule [phony "register"] [] $ return () whenC amInWindows $ do rule ["register.bat", phony "register-script"] [] $ saveAsScript "register.bat" $ build' CannotModifyState (phony "register") rule ["unregister.bat", phony "unregister-script"] [] $ saveAsScript "unregister.bat" $ build' CannotModifyState (phony "unregister") unlessC amInWindows $ do rule ["register.sh", phony "register-script"] [] $ saveAsScript "register.sh" $ build' CannotModifyState (phony "register") rule ["unregister.sh", phony "unregister-script"] [] $ saveAsScript "unregister.sh" $ build' CannotModifyState (phony "unregister") rule [phony "unregister"] [] $ return () rule [phony "install"] [phony "build"] $ do build' CannotModifyState (phony "copy") build' CannotModifyState (phony "register") rule [phony "uninstall"] [] $ do build' CannotModifyState (phony "unregister") build' CannotModifyState (phony "uncopy") if "configure" `elem` args then return () else (do readConfigureState "config.d" putV "reusing old configuration") `catchC` \e -> do putD e putV "Couldn't read old config.d" rm_rf "config.d" putExtra "commandLine" args distclean ["config.d", "franchise.log"] targets <- handleArgs opts runHooks mkbuild writeConfigureState "config.d" putD "Done writinf to config.d" when ("configure" `elem` args) $ putS "configure successful!" mapM_ buildtarget targets where buildtarget t = do mt <- sloppyTarget t case mt of [] -> fail $ "No such target: "++t ["*register*"] -> do putS "{register}" x <- getExtraData "gen-script" let realtarg = maybe "*register*" (const "*register-script*") x build' CannotModifyState realtarg ["*unregister*"] -> do putS "{unregister}" x <- getExtraData "gen-script" let realtarg = maybe "*unregister*" (const "*unregister-script*") x build' CannotModifyState realtarg ["*clean*"] -> do putS "{clean}" build' CannotModifyState "*clean*" clearAllBuilt ["*distclean*"] -> do putS "{distclean}" build' CannotModifyState "*distclean*" clearAllBuilt [tt] -> do putS $ "["++unphony tt++"]" build' CannotModifyState tt ts -> fail $ unlines ["No such target: "++t, "Perhaps you meant one of "++ unwords (map unphony ts)++"?"] needsWork :: String -> C Bool needsWork t = do isb <- isBuilt t if isb then do putD $ t++" is already built!" return False else do mtt <- getTarget t case mtt of Nothing -> do putD $ "marking "++t++" as built since it has no rule" setBuilt t return False Just (Target _ ds _) | nullS ds -> return True -- no dependencies means it always needs work! Just (Target ts ds _) -> do mmt <- (Just `fmap` io (mapM getModificationTime $ filter (not . isPhony) $ t:toListS ts)) `catchC` \_ -> return Nothing case mmt of Nothing -> do putD $ "need work because "++t++ " doesn't exist (or a friend)" return True Just [] -> do putD $ "need work because "++ t ++ " is a phony target." return True Just mt -> do anylater <- anyM (latertime mt) $ toListS ds if anylater then return () else do putD $ unwords $ "Marking":t: "as built since it's older than": toListS ds setBuilt t return anylater where latertime mt y = do ye <- io $ doesFileExist y if not ye then do putD $ "Need work cuz "++y++" don't exist" return True else do mty <- io $ getModificationTime y if mty > maximum mt then putD $ "I need work since "++y++ " is newer than " ++ t else return () return (mty > maximum mt) anyM _ [] = return False anyM f (z:zs) = do b <- f z if b then return True else anyM f zs buildTarget :: String -> C () buildTarget = build' CannotModifyState build' :: CanModifyState -> String -> C () build' cms b = unlessC (isBuilt b) $ -- short circuit if we're already built! do --put $S unwords ("I'm thinking of recompiling...": buildName b) origw <- toListS `fmap` findWork b case origw of [] -> putD "I see nothing here to recompile" _ -> putD $ "I want to recompile all of "++ unwords origw case length origw of 0 -> putD $ "Nothing to recompile for "++b++"." l -> putD $ unwords $ ["Need to recompile ",show l,"for"]++b:["."] chan <- io $ newChan tis <- targetImportances let buildthem _ [] = return () buildthem inprogress w = do putD $ unwords ("I am now wanting to compile":w) loadavgstr <- cat "/proc/loadavg" `catchC` \_ -> return "" let loadavg = case reads loadavgstr of ((n,_):_) -> max 0.0 (n :: Double) _ -> 0.0 fixNumJobs nj = if nj > 1 && loadavg >= 0.5+fromIntegral nj then do putV $ "Throttling jobs with load "++ show loadavg return 1 else return nj njobs <- getNumJobs >>= fixNumJobs (canb'',depb') <- partitionM (canBuildNow (w `addsS` inprogress)) w canb' <- if njobs > 1 then filterDupTargets $ map snd $ sort $ map (\t -> (maybe 0 negate$lookupT t tis,t)) canb'' else filterDupTargets canb'' putD $ unwords $ "I can now build: ": canb' let jobs = max 0 (njobs - lengthS inprogress) canb = take jobs canb' depb = drop jobs canb' ++ (canb'' \\ canb') ++ depb' buildone ttt = forkC cms $ do Just (Target ts xs0 makettt) <- getTarget ttt stillneedswork <- if any (`elemS` ts) $ toListS inprogress then do putD "Already in progress..." return False else needsWork ttt if stillneedswork then do putD $ unlines ["I am making "++ ttt, " This depends on "++ unwords (toListS xs0)] makettt `catchC` \e -> do putV $ errorBuilding e ttt io $ writeChan chan $ Left e io $ writeChan chan $ Right (ttt, ts) else do putD $ "I get to skip one! " ++ ttt io $ writeChan chan $ Right (ttt, ts) case filter (".o" `isSuffixOf`) canb of [] -> return () [_] -> return () tb -> putD $ "I can now build "++ unwords tb mapM_ buildone canb md <- io $ readChan chan case md of Left e -> do putV $ errorBuilding e b fail $ errorBuilding e b Right (d,ts) -> do putD $ "Done building "++ show d mapM_ setBuilt $ d : toListS ts buildthem (delS d (addsS canb $ inprogress)) (depb \\ toListS ts) errorBuilding e "config.d/commandLine" = "configure failed:\n"++e errorBuilding e f | ".depend" `isSuffixOf` f = e errorBuilding e bn = "Error building "++unphony bn++'\n':e filterDupTargets [] = return [] filterDupTargets (t:ts) = do Just (Target xs _ _) <- getTarget t ts' <- filterDupTargets $ filter (not . (`elemS` xs)) ts return (t:ts') buildthem emptyS origw targetImportances :: C (Trie Int) targetImportances = do ts <- getTargets let invertedDeps = foldl invertDep emptyT $ toListT ts invertDep ids (t,Target _ dd _) =inv (toListS dd) ids where inv [] x = x inv (d:ds) x = inv ds $ alterT d addit x addit (Just ss) = Just $ addS t ss addit Nothing = Just $ addS t emptyS gti x [] = x gti ti (t:rest) = case lookupT t ti of Just _ -> gti ti rest _ -> case toListS `fmap` lookupT t invertedDeps of Nothing -> gti (insertT t 0 ti) rest Just ds -> case mapM (`lookupT` ti) ds of Just dsv -> gti (insertT t (1+maximum (0:dsv)) ti) rest Nothing -> gti ti (ds++t:rest) return $ gti emptyT $ toListS $ keysT ts partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a],[a]) partitionM _ [] = return ([],[]) partitionM f (x:xs) = do amok <- f x (ok,notok) <- partitionM f xs return $ if amok then (x:ok,notok) else (ok,x:notok) canBuildNow :: StringSet -> String -> C Bool canBuildNow needwork t = do mt <- getTarget t case (delS t . dependencies) `fmap` mt of Just d -> return $ not $ any (`elemS` needwork) $ toListS d _ -> return True getBuildable :: String -> C (Maybe Buildable) getBuildable t = do allts <- getTargets case lookupT t allts of Just (Target ts ds how) -> return $ Just (t:toListS ts :< toListS ds :<- defaultRule { make = const how }) Nothing -> case lookupT (phony t) allts of Nothing -> return Nothing Just (Target ts ds how) -> return $ Just (phony t:toListS ts :< toListS ds :<- defaultRule { make = const how }) getTarget :: String -> C (Maybe Target) getTarget t = do allts <- getTargets return $ lookupT t allts `mplus` lookupT (phony t) allts clarifyTarget :: String -> C (Maybe String) clarifyTarget t = do allts <- getTargets case lookupT t allts of Just _ -> return $ Just t _ -> case lookupT (phony t) allts of Just _ -> return $ Just (phony t) _ -> return Nothing sloppyTarget :: String -> C [String] sloppyTarget "configure" = return [] sloppyTarget t = do allts <- getTargets return $ if t `elemS` keysT allts then [t] else if phony t `elemS` keysT allts then [phony t] else sloppyLookupKey t allts ++ sloppyLookupKey ('*':t) allts findWork :: String -> C StringSet findWork zzz = do putD $ "findWork called on "++zzz fw emptyS emptyS zzz where fw :: StringSet -> StringSet -> String -> C StringSet fw nw _ t | t `elemS` nw = return nw fw nw done t | t `elemS` done = return nw fw nw done t = do amb <- isBuilt t if amb then return nw else do mt <- getTarget t case mt of Nothing -> return nw Just (Target _ ds _) | nullS ds -> -- no dependencies means it always needs work! return $ addS t nw Just (Target _ ds00 _) -> do let ds0 = toListS ds00 nwds <- lookAtDeps nw ds0 if any (`elemS` nwds) ds0 then return $ addS t nwds else do tooold <- needsWork t if tooold then return $ addS t nwds else return nwds where lookAtDeps nw' [] = return nw' lookAtDeps nw' (d:ds) = do nw2 <- fw nw' (t `addS` done) d lookAtDeps nw2 ds simpleTarget :: String -> C a -> C () simpleTarget outname myrule = addTarget $ [outname] :< [] :<- defaultRule { make = const (myrule >> return ()) } addTarget :: Buildable -> C () addTarget (ts :< ds :<- r) = do withd <- rememberDirectory mapM_ clearBuilt ts ts' <- mapM processFilePathOrTarget ts ds' <- fromListS `fmap` mapM processFilePathOrTarget ds let fixt t = (t, delS t allts) allts = fromListS ts' ts'' = map fixt ts' addt (t,otherTs) = modifyTargets $ insertT t (Target otherTs ds' $ withd $ make r (ts:<ds)) clean $ clean0 r (ts:<ds) case postinst r (ts:<ds) of Just inst -> addToRule (phony "register") $ withd inst Nothing -> return () mapM_ addt ts'' -- | If you want to create a new target, you can do this using 'rule', -- which creates a build target with certain dependencies and a rule -- to do any extra actual building. rule :: [String] -- ^ list of targets simultaneously built by this rule -> [String] -- ^ list of dependencies -> C () -- ^ rule to build this target -> C () rule n deps j = addTarget $ n :< deps |<- defaultRule { make = const j } -- | Add a bit more work to be done when building target. This will -- be done /before/ the function that is already present, and thus may -- be used to prepare the environment in some way. {-# NOINLINE addToRule #-} addToRule :: String -> C () -> C () addToRule t j | unphony t == "install" = addToRule (phony "register") j addToRule targ j = do withd <- rememberDirectory modifyTargets $ adjustT' targ $ \ (Target a b c) -> Target a b (withd j >> c) where adjustT' t f m = case lookupT t m of Just _ -> adjustT t f m Nothing -> adjustT (phony t) f m -- | Add some dependencies to the specified target. If the target -- does not exist, it is created as a phony target. This is pretty -- simple, but you may care to see also the regression tests described -- in <../27-addDependencies.html> for examples. addDependencies :: String -- ^ target -> [String] -- ^ new dependencies -> C () addDependencies t ds = do ots <- maybe [] (toListS . fellowTargets) `fmap` getTarget t ds0 <- maybe emptyS dependencies `fmap` getTarget t rul <- maybe (return ()) buildrule `fmap` getTarget t t' <- maybe (phony t) id `fmap` clarifyTarget t ds' <- fromListS `fmap` mapM processFilePathOrTarget ds let ds'' = ds0 `unionS` ds' fixt tar = (tar, delS tar allts) allts = fromListS (t':ots) ts'' = map fixt (t':ots) addt (thisT,otherTs) = modifyTargets $ insertT thisT (Target otherTs ds'' rul) mapM_ clearBuilt (t':ots) mapM_ addt ts''
droundy/franchise
Distribution/Franchise/Buildable.hs
Haskell
bsd-3-clause
26,012
-- | Defines various function in the context of user interaction, -- most importantly the verbosity settings and logging mechanism module Language.Java.Paragon.Interaction (setVerbosity, getVerbosity, verbosePrint, --enableXmlOutput, getXmlOutput, -- Not used right now setCheckNull, checkNull, normalPrint, detailPrint, finePrint, debugPrint, tracePrint, panic, formatData, versionString, libraryBase, typeCheckerBase ) where import Data.IORef import Control.Monad import System.IO.Unsafe (unsafePerformIO) -- Trust me, I know what I'm doing... :-D -- Comment out to get rid of dependency on haskell-src-exts: import Language.Haskell.Exts.Parser import Language.Haskell.Exts.Pretty import Language.Java.Paragon.Monad.Base ------------------------------------------------------------- -- Verbosity in feedback {-# NOINLINE unsafeVerbosityGlobalVar #-} unsafeVerbosityGlobalVar :: IORef Int -- ^Stores the verbosity level as an Int in an IO Reference. -- Set to 1 by default. unsafeVerbosityGlobalVar = unsafePerformIO $ newIORef 1 -- | Read verbosity level from IO reference getVerbosity :: IO Int getVerbosity = readIORef unsafeVerbosityGlobalVar -- | Set the verbosity as an IO reference, i.e. 'unsafeVerbosityGlobalVar' setVerbosity :: Int -> IO () setVerbosity k = writeIORef unsafeVerbosityGlobalVar k -- | Conditional print function, comparing given and global verbosity levels verbosePrint :: MonadIO m => Int -> String -> m () verbosePrint n str = liftIO $ do k <- getVerbosity when (n <= k) $ putStrLn str -- | Mapping print functions to call to the 'verbosePrint' function with -- increasing verbosity normalPrint, detailPrint, finePrint, debugPrint, tracePrint :: MonadIO m => String -> m () normalPrint = verbosePrint 1 -- ^Feedback to the user in the normal case detailPrint = verbosePrint 2 -- ^Report individual members finePrint = verbosePrint 3 -- ^Report verbosely (default for -v) debugPrint = verbosePrint 4 -- ^Include DEBUG output tracePrint = verbosePrint 5 -- ^State and env changes -- This trace function uses haskell-src-exts to get nice formating. -- To avoid depending on this package, comment out this version and the imports above, and -- comment in the version using show below. formatData :: Show a => a -> String formatData s = case parseExp (show s) of ParseOk x -> prettyPrintStyleMode -- ribbonsPerLine adjust how eager the printer is to break lines eg in records. Style{ mode = PageMode, lineLength = 150, ribbonsPerLine = 2.5 } defaultMode x ParseFailed{} -> show s -- formatData = show unsafeCheckNullGlobalVar :: IORef Bool unsafeCheckNullGlobalVar = unsafePerformIO $ newIORef False checkNull :: IO Bool checkNull = readIORef unsafeCheckNullGlobalVar setCheckNull :: Bool -> IO () setCheckNull b = writeIORef unsafeCheckNullGlobalVar b ------------------------------------------------------------- -- Generate XML output -- [Currently unused] {- {-# NOINLINE unsafeXmlOutputGlobalVar #-} unsafeXmlOutputGlobalVar :: IORef Bool unsafeXmlOutputGlobalVar = unsafePerformIO $ newIORef False getXmlOutput :: IO Bool getXmlOutput = readIORef unsafeXmlOutputGlobalVar enableXmlOutput :: IO () enableXmlOutput = writeIORef unsafeXmlOutputGlobalVar True -} --xmlOutput :: IORef XMLNode --xmlOutput = unsafePerformIO $ newIORef $ -- XMLNode "parac" [XMLAttribute "version" versionString] [] --insertXMLNode :: XMLNode -> IO () --insertXMLNode n = readIORef (xmlOutput) >>= \x -> writeIORef xmlOutput (insertNode x n) ------------------------------------------------------------- -- | A function for generating bug report guidelines panic :: String -> String -> a panic cause extra = error $ "Panic! " ++ cause ++ " caused the impossible, \ \and the world is now about to end in 3.. 2.. 1.. \n\ \Please report as a bug at: " ++ issueTracker ++ if not (null extra) then "\nExtra information: " ++ extra else "" issueTracker :: String issueTracker = "http://code.google.com/p/paragon-java/issues/entry" versionString :: String versionString = "0.1.31" -- | Module paths for use in error reports libraryBase, typeCheckerBase :: String libraryBase = "Language.Java.Paragon" typeCheckerBase = libraryBase ++ ".TypeCheck"
bvdelft/parac2
src/Language/Java/Paragon/Interaction.hs
Haskell
bsd-3-clause
4,416
module Sexy.Instances.Cons () where import Sexy.Instances.Cons.List ()
DanBurton/sexy
src/Sexy/Instances/Cons.hs
Haskell
bsd-3-clause
72
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Duration.FR.Rules ( rules ) where import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Duration.Helpers import Duckling.Numeral.Types (NumeralData(..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Regex.Types import qualified Duckling.TimeGrain.Types as TG import Duckling.Types ruleNumeralQuotes :: Rule ruleNumeralQuotes = Rule { name = "<integer> + '\"" , pattern = [ Predicate isNatural , regex "(['\"])" ] , prod = \tokens -> case tokens of (Token Numeral NumeralData{TNumeral.value = v}: Token RegexMatch (GroupMatch (x:_)): _) -> case x of "'" -> Just . Token Duration . duration TG.Minute $ floor v "\"" -> Just . Token Duration . duration TG.Second $ floor v _ -> Nothing _ -> Nothing } ruleUneUnitofduration :: Rule ruleUneUnitofduration = Rule { name = "une <unit-of-duration>" , pattern = [ regex "une|la|le?" , dimension TimeGrain ] , prod = \tokens -> case tokens of (_: Token TimeGrain grain: _) -> Just . Token Duration $ duration grain 1 _ -> Nothing } ruleUnQuartDHeure :: Rule ruleUnQuartDHeure = Rule { name = "un quart d'heure" , pattern = [ regex "(1/4\\s?h(eure)?|(un|1) quart d'heure)" ] , prod = \_ -> Just . Token Duration $ duration TG.Minute 15 } ruleUneDemiHeure :: Rule ruleUneDemiHeure = Rule { name = "une demi heure" , pattern = [ regex "(1/2\\s?h(eure)?|(1|une) demi(e)?(\\s|-)heure)" ] , prod = \_ -> Just . Token Duration $ duration TG.Minute 30 } ruleTroisQuartsDHeure :: Rule ruleTroisQuartsDHeure = Rule { name = "trois quarts d'heure" , pattern = [ regex "(3/4\\s?h(eure)?|(3|trois) quart(s)? d'heure)" ] , prod = \_ -> Just . Token Duration $ duration TG.Minute 45 } ruleDurationEnviron :: Rule ruleDurationEnviron = Rule { name = "environ <duration>" , pattern = [ regex "environ" ] , prod = \tokens -> case tokens of -- TODO(jodent) +precision approximate (_:token:_) -> Just token _ -> Nothing } rules :: [Rule] rules = [ ruleUneUnitofduration , ruleUnQuartDHeure , ruleUneDemiHeure , ruleTroisQuartsDHeure , ruleDurationEnviron , ruleNumeralQuotes ]
facebookincubator/duckling
Duckling/Duration/FR/Rules.hs
Haskell
bsd-3-clause
2,562
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Main where import Control.Monad.Trans.Either (EitherT) import Network.Wai (Application) import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.RequestLogger (logStdoutDev) import Servant ( (:>), Get, Capture, JSON, Proxy(..), ServantErr, ServerT, serve ) type EchoAPI = "echo" :> Capture "echoIn" String :> Get '[Servant.JSON] String echoAPI :: ServerT EchoAPI (EitherT ServantErr IO) echoAPI = echo echo :: String -> EitherT ServantErr IO String echo echoIn = return echoIn app :: Application app = serve (Proxy :: Proxy EchoAPI) echoAPI main :: IO () main = run 32323 $ logStdoutDev app
zekna/toy-haskell
echo.hs
Haskell
bsd-3-clause
683
{-# LANGUAGE OverloadedStrings #-} module Xlsx.SimpleSpec (main, spec) where import Test.Hspec import Xlsx.Simple import Codec.Xlsx import Xlsx.Simple.Internal import Codec.Xlsx.Writer import Data.Time import Data.Time.LocalTime import Control.Applicative testFileName = "testD.xlsx" testSheetName = "testSheet" testBbtext :: CellData testBbtext = bbText "testBbte" testIbtext :: CellData testIbtext = ibText "estIbtex" testNbtext :: CellData testNbtext = nbText "stNbtext" testBgrtext :: CellData testBgrtext = bgrText "stBgrtex" testIgrtext :: CellData testIgrtext = igrText "stIgrtex" testNgrtext :: CellData testNgrtext = ngrText "stNgrtex" testBrtext :: CellData testBrtext = brText "stBrtext" testIrtext :: CellData testIrtext = irText "stIrtext" testNrtext :: CellData testNrtext = nrText "stNrtext" testBgtext :: CellData testBgtext = bgText "stBgtext" testIgtext :: CellData testIgtext = igText "stIgtext" testIntext :: CellData testIntext = inText "stIntext" testBbdouble :: CellData testBbdouble = bbDouble 2.781828 testIbdouble :: CellData testIbdouble = ibDouble 2.781828 testNbdouble :: CellData testNbdouble = nbDouble 2.781828 testBgrdouble :: CellData testBgrdouble = bgrDouble 2.781828 testIgrdouble :: CellData testIgrdouble = igrDouble 2.781828 testNgrdouble :: CellData testNgrdouble = ngrDouble 2.781828 testBrdouble :: CellData testBrdouble = brDouble 2.781828 testIrdouble :: CellData testIrdouble = irDouble 2.781828 testNrdouble :: CellData testNrdouble = nrDouble 2.781828 testBgdouble :: CellData testBgdouble = bgDouble 2.781828 testIgdouble :: CellData testIgdouble = igDouble 2.781828 testIndouble :: CellData testIndouble = inDouble 2.781828 main :: IO () main = hspec spec spec :: Spec spec = do describe "writeXlsxFile" $ do it "should print test data to xlsx file and exit" $ do t <- getCurrentTime let sheet3 = testSheet3 <*> [utcToLocalTime (hoursToTimeZone (-6)) t] writeXlsxFile testFileName testSheetName ([testSheet] ++ [allNumStyles] ++ [testSheet2] ++ [sheet3]) True `shouldBe` True testSheet3 = [bbDate ,ibDate ,nbDate ,bgrDate ,igrDate ,ngrDate ,brDate ,irDate ,nrDate ,bgDate ,igDate ,inDate ] allStyles = xText <$> [ 1 .. 100] <*> ["Test text"] allNumStyles = xDouble <$> [1 .. 100] <*> [1.1] testSheet2 = allStyles testSheet = [testBbtext ,testBbtext ,testIbtext ,testIbtext ,testNbtext ,testNbtext ,testBgrtext ,testBgrtext ,testIgrtext ,testIgrtext ,testNgrtext ,testNgrtext ,testBrtext ,testBrtext ,testIrtext ,testIrtext ,testNrtext ,testNrtext ,testBgtext ,testBgtext ,testIgtext ,testIgtext ,testIntext ,testIntext ,testBbdouble ,testBbdouble ,testIbdouble ,testIbdouble ,testNbdouble ,testNbdouble ,testBgrdouble ,testBgrdouble ,testIgrdouble ,testIgrdouble ,testNgrdouble ,testNgrdouble ,testBrdouble ,testBrdouble ,testIrdouble ,testIrdouble ,testNrdouble ,testNrdouble ,testBgdouble ,testBgdouble ,testIgdouble ,testIgdouble ,testIndouble ,testIndouble] ;
plow-technologies/xlsx-simple
test/Xlsx/SimpleSpec.hs
Haskell
bsd-3-clause
4,502
module WhileAS where type VarIdent = String type Label = Int -- type Selector = String type Prog = Stat -- type Prog = Prog [Dec] [Stat] -- Contains name, a list of input vars, output var, body respectively and of course -- the two labels ln and lx data Dec = Proc [VarIdent] VarIdent VarIdent Label Stat Label data AExp = Var VarIdent | IntLit Integer | AOp String AExp AExp -- | Var VarIdent (Maybe Selector) -- | Nil | Dummy deriving (Eq, Show) data BExp = BUnOp String BExp | BoolLit Bool | BOp String BExp BExp | RelOp String AExp AExp -- | POp VarIdent (Maybe Selector) deriving (Eq, Show) data Stat = Assign VarIdent AExp Label | Skip Label | Seq [Stat] | If BExp Label Stat Stat | While BExp Label Stat -- | Call VarIdent [AExp] VarIdent Label Label -- | Malloc VarIdent (Maybe Selector) Label deriving (Show, Eq)
FranklinChen/hugs98-plus-Sep2006
packages/parsec/examples/while/WhileAS.hs
Haskell
bsd-3-clause
871
{-# LANGUAGE TemplateHaskell, TypeOperators #-} -- | For more information: http://www.ietf.org/rfc/rfc2109.txt module Network.Protocol.Cookie {- todo: test please -} ( -- * Cookie datatype. Cookie (Cookie) , empty , cookie , setCookie -- * Accessing cookies. , name , value , comment , commentURL , discard , domain , maxAge , expires , path , port , secure , version -- * Collection of cookies. , Cookies , unCookies , cookies , setCookies , pickCookie , fromList , toList ) where import Prelude hiding ((.), id) import Control.Category import Control.Monad (join) import Data.Record.Label import Data.Maybe import Data.Char import Safe import Data.List import Network.Protocol.Uri.Query import qualified Data.Map as M -- | The `Cookie` data type containg one key/value pair with all the -- (potentially optional) meta-data. data Cookie = Cookie { _name :: String , _value :: String , _comment :: Maybe String , _commentURL :: Maybe String , _discard :: Bool , _domain :: Maybe String , _maxAge :: Maybe Int , _expires :: Maybe String , _path :: Maybe String , _port :: [Int] , _secure :: Bool , _version :: Int } deriving Eq $(mkLabelsNoTypes [''Cookie]) -- | Access name/key of a cookie. name :: Cookie :-> String -- | Access value of a cookie. value :: Cookie :-> String -- | Access comment of a cookie. comment :: Cookie :-> Maybe String -- | Access comment-URL of a cookie. commentURL :: Cookie :-> Maybe String -- | Access discard flag of a cookie. discard :: Cookie :-> Bool -- | Access domain of a cookie. domain :: Cookie :-> Maybe String -- | Access max-age of a cookie. maxAge :: Cookie :-> Maybe Int -- | Access expiration of a cookie. expires :: Cookie :-> Maybe String -- | Access path of a cookie. path :: Cookie :-> Maybe String -- | Access port of a cookie. port :: Cookie :-> [Int] -- | Access secure flag of a cookie. secure :: Cookie :-> Bool -- | Access version of a cookie. version :: Cookie :-> Int -- | Create an empty cookie. empty :: Cookie empty = Cookie "" "" Nothing Nothing False Nothing Nothing Nothing Nothing [] False 0 -- Cookie show instance. instance Show Cookie where showsPrec _ = showsSetCookie -- Show a semicolon separated list of attribute/value pairs. Only meta pairs -- with significant values will be pretty printed. showsSetCookie :: Cookie -> ShowS showsSetCookie c = pair (getL name c) (getL value c) . opt "comment" (getL comment c) . opt "commentURL" (getL commentURL c) . bool "discard" (getL discard c) . opt "domain" (getL domain c) . opt "maxAge" (fmap show (getL maxAge c)) . opt "expires" (getL expires c) . opt "path" (getL path c) . lst "port" (map show (getL port c)) . bool "secure" (getL secure c) . opt "version" (optval (getL version c)) where attr a = showString a val v = showString ("=" ++ v) end = showString "; " single a = attr a . end pair a v = attr a . val v . end opt a = maybe id (pair a) lst _ [] = id lst a xs = pair a (intercalate "," xs) bool _ False = id bool a True = single a optval 0 = Nothing optval i = Just (show i) showCookie :: Cookie -> String showCookie c = _name c ++ "=" ++ _value c parseSetCookie :: String -> Cookie parseSetCookie s = let p = fw (keyValues ";" "=") s in Cookie { _name = (fromMaybe "" . fmap fst . headMay) p , _value = (fromMaybe "" . join . fmap snd . headMay) p , _comment = ( join . lookup "comment") p , _commentURL = ( join . lookup "commentURL") p , _discard = (maybe False (const True) . join . lookup "discard") p , _domain = ( join . lookup "commentURL") p , _maxAge = (join . fmap readMay . join . lookup "commentURL") p , _expires = ( join . lookup "expires") p , _path = ( join . lookup "path") p , _port = (maybe [] (readDef [-1]) . join . lookup "port") p , _secure = (maybe False (const True) . join . lookup "secure") p , _version = (maybe 1 (readDef 1) . join . lookup "version") p } parseCookie :: String -> Cookie parseCookie s = let p = fw (values "=") s in empty { _name = atDef "" p 0 , _value = atDef "" p 1 } -- | Cookie parser and pretty printer as a lens. To be used in combination with -- the /Set-Cookie/ header field. setCookie :: String :<->: Cookie setCookie = parseSetCookie :<->: show -- | Cookie parser and pretty printer as a lens. To be used in combination with -- the /Cookie/ header field. cookie :: String :<->: Cookie cookie = parseCookie :<->: showCookie -- | A collection of multiple cookies. These can all be set in one single HTTP -- /Set-Cookie/ header field. data Cookies = Cookies { _unCookies :: M.Map String Cookie } deriving Eq $(mkLabelsNoTypes [''Cookies]) -- | Access raw cookie mapping from collection. unCookies :: Cookies :-> M.Map String Cookie instance Show Cookies where showsPrec _ = showsSetCookies showsSetCookies :: Cookies -> ShowS showsSetCookies = is (showString ", ") . map (shows . snd) . M.toList . getL unCookies where is _ [] = id is s (x:xs) = foldl (\a b -> a.s.b) x xs -- | Cookies parser and pretty printer as a lens. setCookies :: String :<->: Cookies setCookies = (fromList :<->: toList) . (map parseSetCookie :<->: map show) . values "," -- | Label for printing and parsing collections of cookies. cookies :: String :<->: Cookies cookies = (fromList :<->: toList) . (map parseCookie :<->: map showCookie) . values ";" -- | Case-insensitive way of getting a cookie out of a collection by name. pickCookie :: String -> Cookies :-> Maybe Cookie pickCookie n = lookupL (map toLower n) . unCookies where lookupL k = lens (M.lookup k) (flip M.alter k . const) -- | Convert a list to a cookies collection. fromList :: [Cookie] -> Cookies fromList = Cookies . M.fromList . map (\a -> (map toLower (getL name a), a)) -- | Get the cookies as a list. toList :: Cookies -> [Cookie] toList = map snd . M.toList . getL unCookies
sebastiaanvisser/salvia-protocol
src/Network/Protocol/Cookie.hs
Haskell
bsd-3-clause
6,411
module MonadLoopsExample where import Control.Monad (liftM) import Control.Monad.Loops (whileM_, unfoldM) -- | Print prompt and read lines with retry prompts until the password -- is correctly entered, then print congratulations. logIn :: IO () logIn = do putStrLn "% Enter password:" go putStrLn "$ Congratulations!" where -- Use recursion for loop go = do guess <- getLine if guess /= "secret" then do putStrLn "% Wrong password!" putStrLn "% Try again:" go else return () -- | No explicit recursion logIn2 :: IO () logIn2 = do putStrLn "% Enter password:" whileM_ (do guess <- getLine return (guess /= "secret") ) (do putStrLn "% Wrong password!" putStrLn "% Try again:" ) putStrLn "$ Congratulations!" -- | With $ syntax. logIn3 :: IO () logIn3 = do putStrLn "% Enter password:" whileM_ (do guess <- getLine return (guess /= "secret") ) $ do putStrLn "% Wrong password!" putStrLn "% Try again:" putStrLn "$ Congratulations!" -- | With lifting. logIn4 :: IO () logIn4 = do putStrLn "% Enter password:" whileM_ (liftM (\guess -> guess /= "secret") getLine) $ do putStrLn "% Wrong password!" putStrLn "% Try again:" putStrLn "$ Congratulations!" -- | With operator sectioning and <$>. logIn5 :: IO () logIn5 = do putStrLn "% Enter password:" whileM_ ((/= "secret") <$> getLine) $ do putStrLn "% Wrong password!" putStrLn "% Try again:" putStrLn "$ Congratulations!" -- | Read and collect lines from stdin until encountering "quit". readLinesUntilQuit :: IO [String] readLinesUntilQuit = do line <- getLine if line /= "quit" then do -- recursive call, to loop restOfLines <- readLinesUntilQuit return (line : restOfLines) else return [] -- | No explicit recursion. readLinesUntilQuit2 :: IO [String] readLinesUntilQuit2 = unfoldM maybeReadLine -- | Read a single line and check whether it's "quit". maybeReadLine :: IO (Maybe String) maybeReadLine = do line <- getLine return (if line /= "quit" then Just line else Nothing) readLinesUntilQuit3 :: IO [String] readLinesUntilQuit3 = unfoldM (notQuit <$> getLine) notQuit :: String -> Maybe String notQuit line = if line /= "quit" then Just line else Nothing
FranklinChen/twenty-four-days2015-of-hackage
src/MonadLoopsExample.hs
Haskell
bsd-3-clause
2,428
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE DataKinds #-} module Lib where import Types import Network.Label import Text.Read as T import System.FilePath.Posix import Numeric import Data.List divs :: Integral a => a -> a -> Bool a `divs` b = b `mod` a == 0 count :: (a -> Bool) -> [a] -> Int count p = length . filter p splitDigits :: Int -> (Int, Int, Int) splitDigits x = (d100, d10, d1) where (d100, r) = x `divMod` 100 (d10, d1) = r `divMod` 10 toWidget :: Widget a => WLabel a -> a toWidget (WLabel l) = case parseLabel l fromLabel of Left str -> error str Right a -> a read' :: String -> Int read' x = case T.readMaybe x of Just x -> x Nothing -> error$ "error parsing " ++ x labelPath :: GameState g => Path g -> g labelPath = delabel . parse pmap :: (FilePath -> FilePath) -> Path a -> Path a pmap f (Path p) = Path$ f p showAndLabel :: GameState g => Path g -> String showAndLabel p = show (pmap takeBaseName p) ++ "\t\t" ++ show (labelPath p) showE :: Double -> ShowS showE = showEFloat (Just 4) median :: Ord a => [a] -> a median [] = undefined median [x] = x median xs = let i = length xs `div` 2 in sort xs !! i median' :: [Double] -> Double median' [] = undefined median' [x] = x median' xs = let l = length xs i = l `div` 2 s = sort xs in if odd l then s !! i else (s !! i + s !! (i-1)) / 2 roundF x = fromInteger (round x :: Integer) ceilF x = fromInteger (ceiling x :: Integer) floorF x = fromInteger (floor x :: Integer)
jonascarpay/visor
src/Lib.hs
Haskell
bsd-3-clause
1,638
-- | Accessors (lenses and functions) to operate on the 'PostFiltset' of a -- clatch-like type. module Penny.Clatch.Access.PostFiltset where import Control.Lens (Lens', _2, _1) import Penny.Clatch.Types -- | Operate on the 'PostFiltset'. -- -- @ -- 'postFiltset' :: 'Lens'' 'Clatch' 'PostFiltset' -- @ postFiltset :: Lens' (a, (b, (c, (d, (e, (f, (PostFiltset, g))))))) PostFiltset postFiltset = _2 . _2 . _2 . _2 . _2 . _2 . _1
massysett/penny
penny/lib/Penny/Clatch/Access/PostFiltset.hs
Haskell
bsd-3-clause
433
-- | A pure implementation of the emulator {-# LANGUAGE GeneralizedNewtypeDeriving, Rank2Types #-} module Emulator.Monad.ST ( STEmulator , runSTEmulator ) where import Control.Monad.Reader (ReaderT, ask, runReaderT) import Control.Monad.ST (ST, runST) import Control.Monad.Trans (lift) import Emulator.Monad import Memory (Memory) import qualified Memory as Memory newtype STEmulator s a = STEmulator (ReaderT (Memory s) (ST s) a) deriving (Functor, Monad) instance MonadEmulator (STEmulator s) where load address = STEmulator $ do mem <- ask lift $ Memory.load mem address store address word = STEmulator $ do mem <- ask lift $ Memory.store mem address word runSTEmulator :: (forall s. STEmulator s a) -> a runSTEmulator emu = -- If you wonder why this isn't defined as `runST . run`... type magic. let x = run emu in runST x where run :: STEmulator s a -> ST s a run (STEmulator reader) = do mem <- Memory.new runReaderT reader mem
jaspervdj/dcpu16-hs
src/Emulator/Monad/ST.hs
Haskell
bsd-3-clause
1,033
{-# language CPP #-} -- | = Name -- -- VK_KHR_swapchain - device extension -- -- == VK_KHR_swapchain -- -- [__Name String__] -- @VK_KHR_swapchain@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 2 -- -- [__Revision__] -- 70 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_surface@ -- -- [__Contact__] -- -- - James Jones -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_swapchain] @cubanismo%0A<<Here describe the issue or question you have about the VK_KHR_swapchain extension>> > -- -- - Ian Elliott -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_swapchain] @ianelliottus%0A<<Here describe the issue or question you have about the VK_KHR_swapchain extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2017-10-06 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- -- - Interacts with Vulkan 1.1 -- -- [__Contributors__] -- -- - Patrick Doane, Blizzard -- -- - Ian Elliott, LunarG -- -- - Jesse Hall, Google -- -- - Mathias Heyer, NVIDIA -- -- - James Jones, NVIDIA -- -- - David Mao, AMD -- -- - Norbert Nopper, Freescale -- -- - Alon Or-bach, Samsung -- -- - Daniel Rakos, AMD -- -- - Graham Sellers, AMD -- -- - Jeff Vigil, Qualcomm -- -- - Chia-I Wu, LunarG -- -- - Jason Ekstrand, Intel -- -- - Matthaeus G. Chajdas, AMD -- -- - Ray Smith, ARM -- -- == Description -- -- The @VK_KHR_swapchain@ extension is the device-level companion to the -- @VK_KHR_surface@ extension. It introduces -- 'Vulkan.Extensions.Handles.SwapchainKHR' objects, which provide the -- ability to present rendering results to a surface. -- -- == New Object Types -- -- - 'Vulkan.Extensions.Handles.SwapchainKHR' -- -- == New Commands -- -- - 'acquireNextImageKHR' -- -- - 'createSwapchainKHR' -- -- - 'destroySwapchainKHR' -- -- - 'getSwapchainImagesKHR' -- -- - 'queuePresentKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'acquireNextImage2KHR' -- -- - 'getDeviceGroupPresentCapabilitiesKHR' -- -- - 'getDeviceGroupSurfacePresentModesKHR' -- -- - 'getPhysicalDevicePresentRectanglesKHR' -- -- == New Structures -- -- - 'PresentInfoKHR' -- -- - 'SwapchainCreateInfoKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'AcquireNextImageInfoKHR' -- -- - 'DeviceGroupPresentCapabilitiesKHR' -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_bind_memory2.BindImageMemoryInfo': -- -- - 'BindImageMemorySwapchainInfoKHR' -- -- - Extending 'Vulkan.Core10.Image.ImageCreateInfo': -- -- - 'ImageSwapchainCreateInfoKHR' -- -- - Extending 'PresentInfoKHR': -- -- - 'DeviceGroupPresentInfoKHR' -- -- - Extending 'SwapchainCreateInfoKHR': -- -- - 'DeviceGroupSwapchainCreateInfoKHR' -- -- == New Enums -- -- - 'SwapchainCreateFlagBitsKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'DeviceGroupPresentModeFlagBitsKHR' -- -- == New Bitmasks -- -- - 'SwapchainCreateFlagsKHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - 'DeviceGroupPresentModeFlagsKHR' -- -- == New Enum Constants -- -- - 'KHR_SWAPCHAIN_EXTENSION_NAME' -- -- - 'KHR_SWAPCHAIN_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.ImageLayout.ImageLayout': -- -- - 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR' -- -- - Extending 'Vulkan.Core10.Enums.ObjectType.ObjectType': -- -- - 'Vulkan.Core10.Enums.ObjectType.OBJECT_TYPE_SWAPCHAIN_KHR' -- -- - Extending 'Vulkan.Core10.Enums.Result.Result': -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PRESENT_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR' -- -- If -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1 Version 1.1> -- is supported: -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR' -- -- - Extending 'SwapchainCreateFlagBitsKHR': -- -- - 'SWAPCHAIN_CREATE_PROTECTED_BIT_KHR' -- -- - 'SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR' -- -- == Issues -- -- 1) Does this extension allow the application to specify the memory -- backing of the presentable images? -- -- __RESOLVED__: No. Unlike standard images, the implementation will -- allocate the memory backing of the presentable image. -- -- 2) What operations are allowed on presentable images? -- -- __RESOLVED__: This is determined by the image usage flags specified when -- creating the presentable image’s swapchain. -- -- 3) Does this extension support MSAA presentable images? -- -- __RESOLVED__: No. Presentable images are always single-sampled. -- Multi-sampled rendering must use regular images. To present the -- rendering results the application must manually resolve the multi- -- sampled image to a single-sampled presentable image prior to -- presentation. -- -- 4) Does this extension support stereo\/multi-view presentable images? -- -- __RESOLVED__: Yes. The number of views associated with a presentable -- image is determined by the @imageArrayLayers@ specified when creating a -- swapchain. All presentable images in a given swapchain use the same -- array size. -- -- 5) Are the layers of stereo presentable images half-sized? -- -- __RESOLVED__: No. The image extents always match those requested by the -- application. -- -- 6) Do the “present” and “acquire next image” commands operate on a -- queue? If not, do they need to include explicit semaphore objects to -- interlock them with queue operations? -- -- __RESOLVED__: The present command operates on a queue. The image -- ownership operation it represents happens in order with other operations -- on the queue, so no explicit semaphore object is required to synchronize -- its actions. -- -- Applications may want to acquire the next image in separate threads from -- those in which they manage their queue, or in multiple threads. To make -- such usage easier, the acquire next image command takes a semaphore to -- signal as a method of explicit synchronization. The application must -- later queue a wait for this semaphore before queuing execution of any -- commands using the image. -- -- 7) Does 'acquireNextImageKHR' block if no images are available? -- -- __RESOLVED__: The command takes a timeout parameter. Special values for -- the timeout are 0, which makes the call a non-blocking operation, and -- @UINT64_MAX@, which blocks indefinitely. Values in between will block -- for up to the specified time. The call will return when an image becomes -- available or an error occurs. It may, but is not required to, return -- before the specified timeout expires if the swapchain becomes out of -- date. -- -- 8) Can multiple presents be queued using one 'queuePresentKHR' call? -- -- __RESOLVED__: Yes. 'PresentInfoKHR' contains a list of swapchains and -- corresponding image indices that will be presented. When supported, all -- presentations queued with a single 'queuePresentKHR' call will be -- applied atomically as one operation. The same swapchain must not appear -- in the list more than once. Later extensions may provide applications -- stronger guarantees of atomicity for such present operations, and\/or -- allow them to query whether atomic presentation of a particular group of -- swapchains is possible. -- -- 9) How do the presentation and acquire next image functions notify the -- application the targeted surface has changed? -- -- __RESOLVED__: Two new result codes are introduced for this purpose: -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' - Presentation will -- still succeed, subject to the window resize behavior, but the -- swapchain is no longer configured optimally for the surface it -- targets. Applications should query updated surface information and -- recreate their swapchain at the next convenient opportunity. -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' - Failure. The -- swapchain is no longer compatible with the surface it targets. The -- application must query updated surface information and recreate the -- swapchain before presentation will succeed. -- -- These can be returned by both 'acquireNextImageKHR' and -- 'queuePresentKHR'. -- -- 10) Does the 'acquireNextImageKHR' command return a semaphore to the -- application via an output parameter, or accept a semaphore to signal -- from the application as an object handle parameter? -- -- __RESOLVED__: Accept a semaphore to signal as an object handle. This -- avoids the need to specify whether the application must destroy the -- semaphore or whether it is owned by the swapchain, and if the latter, -- what its lifetime is and whether it can be reused for other operations -- once it is received from 'acquireNextImageKHR'. -- -- 11) What types of swapchain queuing behavior should be exposed? Options -- include swap interval specification, mailbox\/most recent vs. FIFO queue -- management, targeting specific vertical blank intervals or absolute -- times for a given present operation, and probably others. For some of -- these, whether they are specified at swapchain creation time or as -- per-present parameters needs to be decided as well. -- -- __RESOLVED__: The base swapchain extension will expose 3 possible -- behaviors (of which, FIFO will always be supported): -- -- - Immediate present: Does not wait for vertical blanking period to -- update the current image, likely resulting in visible tearing. No -- internal queue is used. Present requests are applied immediately. -- -- - Mailbox queue: Waits for the next vertical blanking period to update -- the current image. No tearing should be observed. An internal -- single-entry queue is used to hold pending presentation requests. If -- the queue is full when a new presentation request is received, the -- new request replaces the existing entry, and any images associated -- with the prior entry become available for reuse by the application. -- -- - FIFO queue: Waits for the next vertical blanking period to update -- the current image. No tearing should be observed. An internal queue -- containing @numSwapchainImages@ - 1 entries is used to hold pending -- presentation requests. New requests are appended to the end of the -- queue, and one request is removed from the beginning of the queue -- and processed during each vertical blanking period in which the -- queue is non-empty -- -- Not all surfaces will support all of these modes, so the modes supported -- will be returned using a surface information query. All surfaces must -- support the FIFO queue mode. Applications must choose one of these modes -- up front when creating a swapchain. Switching modes can be accomplished -- by recreating the swapchain. -- -- 12) Can 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_MAILBOX_KHR' -- provide non-blocking guarantees for 'acquireNextImageKHR'? If so, what -- is the proper criteria? -- -- __RESOLVED__: Yes. The difficulty is not immediately obvious here. -- Naively, if at least 3 images are requested, mailbox mode should always -- have an image available for the application if the application does not -- own any images when the call to 'acquireNextImageKHR' was made. However, -- some presentation engines may have more than one “current” image, and -- would still need to block in some cases. The right requirement appears -- to be that if the application allocates the surface’s minimum number of -- images + 1 then it is guaranteed non-blocking behavior when it does not -- currently own any images. -- -- 13) Is there a way to create and initialize a new swapchain for a -- surface that has generated a 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- return code while still using the old swapchain? -- -- __RESOLVED__: Not as part of this specification. This could be useful to -- allow the application to create an “optimal” replacement swapchain and -- rebuild all its command buffers using it in a background thread at a low -- priority while continuing to use the “suboptimal” swapchain in the main -- thread. It could probably use the same “atomic replace” semantics -- proposed for recreating direct-to-device swapchains without incurring a -- mode switch. However, after discussion, it was determined some platforms -- probably could not support concurrent swapchains for the same surface -- though, so this will be left out of the base KHR extensions. A future -- extension could add this for platforms where it is supported. -- -- 14) Should there be a special value for -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@maxImageCount@ -- to indicate there are no practical limits on the number of images in a -- swapchain? -- -- __RESOLVED__: Yes. There will often be cases where there is no practical -- limit to the number of images in a swapchain other than the amount of -- available resources (i.e., memory) in the system. Trying to derive a -- hard limit from things like memory size is prone to failure. It is -- better in such cases to leave it to applications to figure such soft -- limits out via trial\/failure iterations. -- -- 15) Should there be a special value for -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@currentExtent@ -- to indicate the size of the platform surface is undefined? -- -- __RESOLVED__: Yes. On some platforms (Wayland, for example), the surface -- size is defined by the images presented to it rather than the other way -- around. -- -- 16) Should there be a special value for -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@maxImageExtent@ -- to indicate there is no practical limit on the surface size? -- -- __RESOLVED__: No. It seems unlikely such a system would exist. 0 could -- be used to indicate the platform places no limits on the extents beyond -- those imposed by Vulkan for normal images, but this query could just as -- easily return those same limits, so a special “unlimited” value does not -- seem useful for this field. -- -- 17) How should surface rotation and mirroring be exposed to -- applications? How do they specify rotation and mirroring transforms -- applied prior to presentation? -- -- __RESOLVED__: Applications can query both the supported and current -- transforms of a surface. Both are specified relative to the device’s -- “natural” display rotation and direction. The supported transforms -- indicate which orientations the presentation engine accepts images in. -- For example, a presentation engine that does not support transforming -- surfaces as part of presentation, and which is presenting to a surface -- that is displayed with a 90-degree rotation, would return only one -- supported transform bit: -- 'Vulkan.Extensions.VK_KHR_surface.SURFACE_TRANSFORM_ROTATE_90_BIT_KHR'. -- Applications must transform their rendering by the transform they -- specify when creating the swapchain in @preTransform@ field. -- -- 18) Can surfaces ever not support @VK_MIRROR_NONE@? Can they support -- vertical and horizontal mirroring simultaneously? Relatedly, should -- @VK_MIRROR_NONE@[_BIT] be zero, or bit one, and should applications be -- allowed to specify multiple pre and current mirror transform bits, or -- exactly one? -- -- __RESOLVED__: Since some platforms may not support presenting with a -- transform other than the native window’s current transform, and -- prerotation\/mirroring are specified relative to the device’s natural -- rotation and direction, rather than relative to the surface’s current -- rotation and direction, it is necessary to express lack of support for -- no mirroring. To allow this, the @MIRROR_NONE@ enum must occupy a bit in -- the flags. Since @MIRROR_NONE@ must be a bit in the bitmask rather than -- a bitmask with no values set, allowing more than one bit to be set in -- the bitmask would make it possible to describe undefined transforms such -- as @VK_MIRROR_NONE_BIT@ | @VK_MIRROR_HORIZONTAL_BIT@, or a transform -- that includes both “no mirroring” and “horizontal mirroring” -- simultaneously. Therefore, it is desirable to allow specifying all -- supported mirroring transforms using only one bit. The question then -- becomes, should there be a @VK_MIRROR_HORIZONTAL_AND_VERTICAL_BIT@ to -- represent a simultaneous horizontal and vertical mirror transform? -- However, such a transform is equivalent to a 180 degree rotation, so -- presentation engines and applications that wish to support or use such a -- transform can express it through rotation instead. Therefore, 3 -- exclusive bits are sufficient to express all needed mirroring -- transforms. -- -- 19) Should support for sRGB be required? -- -- __RESOLVED__: In the advent of UHD and HDR display devices, proper color -- space information is vital to the display pipeline represented by the -- swapchain. The app can discover the supported format\/color-space pairs -- and select a pair most suited to its rendering needs. Currently only the -- sRGB color space is supported, future extensions may provide support for -- more color spaces. See issues 23 and 24. -- -- 20) Is there a mechanism to modify or replace an existing swapchain with -- one targeting the same surface? -- -- __RESOLVED__: Yes. This is described above in the text. -- -- 21) Should there be a way to set prerotation and mirroring using native -- APIs when presenting using a Vulkan swapchain? -- -- __RESOLVED__: Yes. The transforms that can be expressed in this -- extension are a subset of those possible on native platforms. If a -- platform exposes a method to specify the transform of presented images -- for a given surface using native methods and exposes more transforms or -- other properties for surfaces than Vulkan supports, it might be -- impossible, difficult, or inconvenient to set some of those properties -- using Vulkan KHR extensions and some using the native interfaces. To -- avoid overwriting properties set using native commands when presenting -- using a Vulkan swapchain, the application can set the pretransform to -- “inherit”, in which case the current native properties will be used, or -- if none are available, a platform-specific default will be used. -- Platforms that do not specify a reasonable default or do not provide -- native mechanisms to specify such transforms should not include the -- inherit bits in the @supportedTransforms@ bitmask they return in -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'. -- -- 22) Should the content of presentable images be clipped by objects -- obscuring their target surface? -- -- __RESOLVED__: Applications can choose which behavior they prefer. -- Allowing the content to be clipped could enable more efficient -- presentation methods on some platforms, but some applications might rely -- on the content of presentable images to perform techniques such as -- partial updates or motion blurs. -- -- 23) What is the purpose of specifying a -- 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR' along with -- 'Vulkan.Core10.Enums.Format.Format' when creating a swapchain? -- -- __RESOLVED__: While Vulkan itself is color space agnostic (e.g. even the -- meaning of R, G, B and A can be freely defined by the rendering -- application), the swapchain eventually will have to present the images -- on a display device with specific color reproduction characteristics. If -- any color space transformations are necessary before an image can be -- displayed, the color space of the presented image must be known to the -- swapchain. A swapchain will only support a restricted set of color -- format and -space pairs. This set can be discovered via -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceFormatsKHR'. -- As it can be expected that most display devices support the sRGB color -- space, at least one format\/color-space pair has to be exposed, where -- the color space is -- 'Vulkan.Extensions.VK_KHR_surface.COLOR_SPACE_SRGB_NONLINEAR_KHR'. -- -- 24) How are sRGB formats and the sRGB color space related? -- -- __RESOLVED__: While Vulkan exposes a number of SRGB texture formats, -- using such formats does not guarantee working in a specific color space. -- It merely means that the hardware can directly support applying the -- non-linear transfer functions defined by the sRGB standard color space -- when reading from or writing to images of those formats. Still, it is -- unlikely that a swapchain will expose a @*_SRGB@ format along with any -- color space other than -- 'Vulkan.Extensions.VK_KHR_surface.COLOR_SPACE_SRGB_NONLINEAR_KHR'. -- -- On the other hand, non-@*_SRGB@ formats will be very likely exposed in -- pair with a SRGB color space. This means, the hardware will not apply -- any transfer function when reading from or writing to such images, yet -- they will still be presented on a device with sRGB display -- characteristics. In this case the application is responsible for -- applying the transfer function, for instance by using shader math. -- -- 25) How are the lifetimes of surfaces and swapchains targeting them -- related? -- -- __RESOLVED__: A surface must outlive any swapchains targeting it. A -- 'Vulkan.Extensions.Handles.SurfaceKHR' owns the binding of the native -- window to the Vulkan driver. -- -- 26) How can the client control the way the alpha component of swapchain -- images is treated by the presentation engine during compositing? -- -- __RESOLVED__: We should add new enum values to allow the client to -- negotiate with the presentation engine on how to treat image alpha -- values during the compositing process. Since not all platforms can -- practically control this through the Vulkan driver, a value of -- 'Vulkan.Extensions.VK_KHR_surface.COMPOSITE_ALPHA_INHERIT_BIT_KHR' is -- provided like for surface transforms. -- -- 27) Is 'createSwapchainKHR' the right function to return -- 'Vulkan.Core10.Enums.Result.ERROR_NATIVE_WINDOW_IN_USE_KHR', or should -- the various platform-specific 'Vulkan.Extensions.Handles.SurfaceKHR' -- factory functions catch this error earlier? -- -- __RESOLVED__: For most platforms, the -- 'Vulkan.Extensions.Handles.SurfaceKHR' structure is a simple container -- holding the data that identifies a native window or other object -- representing a surface on a particular platform. For the surface factory -- functions to return this error, they would likely need to register a -- reference on the native objects with the native display server somehow, -- and ensure no other such references exist. Surfaces were not intended to -- be that heavyweight. -- -- Swapchains are intended to be the objects that directly manipulate -- native windows and communicate with the native presentation mechanisms. -- Swapchains will already need to communicate with the native display -- server to negotiate allocation and\/or presentation of presentable -- images for a native surface. Therefore, it makes more sense for -- swapchain creation to be the point at which native object exclusivity is -- enforced. Platforms may choose to enforce further restrictions on the -- number of 'Vulkan.Extensions.Handles.SurfaceKHR' objects that may be -- created for the same native window if such a requirement makes sense on -- a particular platform, but a global requirement is only sensible at the -- swapchain level. -- -- == Examples -- -- Note -- -- The example code for the @VK_KHR_surface@ and @VK_KHR_swapchain@ -- extensions was removed from the appendix after revision 1.0.29. This WSI -- example code was ported to the cube demo that is shipped with the -- official Khronos SDK, and is being kept up-to-date in that location -- (see: -- <https://github.com/KhronosGroup/Vulkan-Tools/blob/master/cube/cube.c>). -- -- == Version History -- -- - Revision 1, 2015-05-20 (James Jones) -- -- - Initial draft, based on LunarG KHR spec, other KHR specs, -- patches attached to bugs. -- -- - Revision 2, 2015-05-22 (Ian Elliott) -- -- - Made many agreed-upon changes from 2015-05-21 KHR TSG meeting. -- This includes using only a queue for presentation, and having an -- explicit function to acquire the next image. -- -- - Fixed typos and other minor mistakes. -- -- - Revision 3, 2015-05-26 (Ian Elliott) -- -- - Improved the Description section. -- -- - Added or resolved issues that were found in improving the -- Description. For example, pSurfaceDescription is used -- consistently, instead of sometimes using pSurface. -- -- - Revision 4, 2015-05-27 (James Jones) -- -- - Fixed some grammatical errors and typos -- -- - Filled in the description of imageUseFlags when creating a -- swapchain. -- -- - Added a description of swapInterval. -- -- - Replaced the paragraph describing the order of operations on a -- queue for image ownership and presentation. -- -- - Revision 5, 2015-05-27 (James Jones) -- -- - Imported relevant issues from the (abandoned) -- vk_wsi_persistent_swapchain_images extension. -- -- - Added issues 6 and 7, regarding behavior of the acquire next -- image and present commands with respect to queues. -- -- - Updated spec language and examples to align with proposed -- resolutions to issues 6 and 7. -- -- - Revision 6, 2015-05-27 (James Jones) -- -- - Added issue 8, regarding atomic presentation of multiple -- swapchains -- -- - Updated spec language and examples to align with proposed -- resolution to issue 8. -- -- - Revision 7, 2015-05-27 (James Jones) -- -- - Fixed compilation errors in example code, and made related spec -- fixes. -- -- - Revision 8, 2015-05-27 (James Jones) -- -- - Added issue 9, and the related VK_SUBOPTIMAL_KHR result code. -- -- - Renamed VK_OUT_OF_DATE_KHR to VK_ERROR_OUT_OF_DATE_KHR. -- -- - Revision 9, 2015-05-27 (James Jones) -- -- - Added inline proposed resolutions (marked with [JRJ]) to some -- XXX questions\/issues. These should be moved to the issues -- section in a subsequent update if the proposals are adopted. -- -- - Revision 10, 2015-05-28 (James Jones) -- -- - Converted vkAcquireNextImageKHR back to a non-queue operation -- that uses a VkSemaphore object for explicit synchronization. -- -- - Added issue 10 to determine whether vkAcquireNextImageKHR -- generates or returns semaphores, or whether it operates on a -- semaphore provided by the application. -- -- - Revision 11, 2015-05-28 (James Jones) -- -- - Marked issues 6, 7, and 8 resolved. -- -- - Renamed VkSurfaceCapabilityPropertiesKHR to -- VkSurfacePropertiesKHR to better convey the mutable nature of -- the information it contains. -- -- - Revision 12, 2015-05-28 (James Jones) -- -- - Added issue 11 with a proposed resolution, and the related issue -- 12. -- -- - Updated various sections of the spec to match the proposed -- resolution to issue 11. -- -- - Revision 13, 2015-06-01 (James Jones) -- -- - Moved some structures to VK_EXT_KHR_swap_chain to resolve the -- specification’s issues 1 and 2. -- -- - Revision 14, 2015-06-01 (James Jones) -- -- - Added code for example 4 demonstrating how an application might -- make use of the two different present and acquire next image KHR -- result codes. -- -- - Added issue 13. -- -- - Revision 15, 2015-06-01 (James Jones) -- -- - Added issues 14 - 16 and related spec language. -- -- - Fixed some spelling errors. -- -- - Added language describing the meaningful return values for -- vkAcquireNextImageKHR and vkQueuePresentKHR. -- -- - Revision 16, 2015-06-02 (James Jones) -- -- - Added issues 17 and 18, as well as related spec language. -- -- - Removed some erroneous text added by mistake in the last update. -- -- - Revision 17, 2015-06-15 (Ian Elliott) -- -- - Changed special value from \"-1\" to \"0\" so that the data -- types can be unsigned. -- -- - Revision 18, 2015-06-15 (Ian Elliott) -- -- - Clarified the values of VkSurfacePropertiesKHR::minImageCount -- and the timeout parameter of the vkAcquireNextImageKHR function. -- -- - Revision 19, 2015-06-17 (James Jones) -- -- - Misc. cleanup. Removed resolved inline issues and fixed typos. -- -- - Fixed clarification of VkSurfacePropertiesKHR::minImageCount -- made in version 18. -- -- - Added a brief \"Image Ownership\" definition to the list of -- terms used in the spec. -- -- - Revision 20, 2015-06-17 (James Jones) -- -- - Updated enum-extending values using new convention. -- -- - Revision 21, 2015-06-17 (James Jones) -- -- - Added language describing how to use -- VK_IMAGE_LAYOUT_PRESENT_SOURCE_KHR. -- -- - Cleaned up an XXX comment regarding the description of which -- queues vkQueuePresentKHR can be used on. -- -- - Revision 22, 2015-06-17 (James Jones) -- -- - Rebased on Vulkan API version 126. -- -- - Revision 23, 2015-06-18 (James Jones) -- -- - Updated language for issue 12 to read as a proposed resolution. -- -- - Marked issues 11, 12, 13, 16, and 17 resolved. -- -- - Temporarily added links to the relevant bugs under the remaining -- unresolved issues. -- -- - Added issues 19 and 20 as well as proposed resolutions. -- -- - Revision 24, 2015-06-19 (Ian Elliott) -- -- - Changed special value for VkSurfacePropertiesKHR::currentExtent -- back to “-1” from “0”. This value will never need to be -- unsigned, and “0” is actually a legal value. -- -- - Revision 25, 2015-06-23 (Ian Elliott) -- -- - Examples now show use of function pointers for extension -- functions. -- -- - Eliminated extraneous whitespace. -- -- - Revision 26, 2015-06-25 (Ian Elliott) -- -- - Resolved Issues 9 & 10 per KHR TSG meeting. -- -- - Revision 27, 2015-06-25 (James Jones) -- -- - Added oldSwapchain member to VkSwapchainCreateInfoKHR. -- -- - Revision 28, 2015-06-25 (James Jones) -- -- - Added the “inherit” bits to the rotation and mirroring flags and -- the associated issue 21. -- -- - Revision 29, 2015-06-25 (James Jones) -- -- - Added the “clipped” flag to VkSwapchainCreateInfoKHR, and the -- associated issue 22. -- -- - Specified that presenting an image does not modify it. -- -- - Revision 30, 2015-06-25 (James Jones) -- -- - Added language to the spec that clarifies the behavior of -- vkCreateSwapchainKHR() when the oldSwapchain field of -- VkSwapchainCreateInfoKHR is not NULL. -- -- - Revision 31, 2015-06-26 (Ian Elliott) -- -- - Example of new VkSwapchainCreateInfoKHR members, “oldSwapchain” -- and “clipped”. -- -- - Example of using VkSurfacePropertiesKHR::{min|max}ImageCount to -- set VkSwapchainCreateInfoKHR::minImageCount. -- -- - Rename vkGetSurfaceInfoKHR()\'s 4th parameter to “pDataSize”, -- for consistency with other functions. -- -- - Add macro with C-string name of extension (just to header file). -- -- - Revision 32, 2015-06-26 (James Jones) -- -- - Minor adjustments to the language describing the behavior of -- “oldSwapchain” -- -- - Fixed the version date on my previous two updates. -- -- - Revision 33, 2015-06-26 (Jesse Hall) -- -- - Add usage flags to VkSwapchainCreateInfoKHR -- -- - Revision 34, 2015-06-26 (Ian Elliott) -- -- - Rename vkQueuePresentKHR()\'s 2nd parameter to “pPresentInfo”, -- for consistency with other functions. -- -- - Revision 35, 2015-06-26 (Jason Ekstrand) -- -- - Merged the VkRotationFlagBitsKHR and VkMirrorFlagBitsKHR enums -- into a single VkSurfaceTransformFlagBitsKHR enum. -- -- - Revision 36, 2015-06-26 (Jason Ekstrand) -- -- - Added a VkSurfaceTransformKHR enum that is not a bitmask. Each -- value in VkSurfaceTransformKHR corresponds directly to one of -- the bits in VkSurfaceTransformFlagBitsKHR so transforming from -- one to the other is easy. Having a separate enum means that -- currentTransform and preTransform are now unambiguous by -- definition. -- -- - Revision 37, 2015-06-29 (Ian Elliott) -- -- - Corrected one of the signatures of vkAcquireNextImageKHR, which -- had the last two parameters switched from what it is elsewhere -- in the specification and header files. -- -- - Revision 38, 2015-06-30 (Ian Elliott) -- -- - Corrected a typo in description of the vkGetSwapchainInfoKHR() -- function. -- -- - Corrected a typo in header file comment for -- VkPresentInfoKHR::sType. -- -- - Revision 39, 2015-07-07 (Daniel Rakos) -- -- - Added error section describing when each error is expected to be -- reported. -- -- - Replaced bool32_t with VkBool32. -- -- - Revision 40, 2015-07-10 (Ian Elliott) -- -- - Updated to work with version 138 of the @vulkan.h@ header. This -- includes declaring the VkSwapchainKHR type using the new -- VK_DEFINE_NONDISP_HANDLE macro, and no longer extending -- VkObjectType (which was eliminated). -- -- - Revision 41 2015-07-09 (Mathias Heyer) -- -- - Added color space language. -- -- - Revision 42, 2015-07-10 (Daniel Rakos) -- -- - Updated query mechanism to reflect the convention changes done -- in the core spec. -- -- - Removed “queue” from the name of -- VK_STRUCTURE_TYPE_QUEUE_PRESENT_INFO_KHR to be consistent with -- the established naming convention. -- -- - Removed reference to the no longer existing VkObjectType enum. -- -- - Revision 43, 2015-07-17 (Daniel Rakos) -- -- - Added support for concurrent sharing of swapchain images across -- queue families. -- -- - Updated sample code based on recent changes -- -- - Revision 44, 2015-07-27 (Ian Elliott) -- -- - Noted that support for VK_PRESENT_MODE_FIFO_KHR is required. -- That is ICDs may optionally support IMMEDIATE and MAILBOX, but -- must support FIFO. -- -- - Revision 45, 2015-08-07 (Ian Elliott) -- -- - Corrected a typo in spec file (type and variable name had wrong -- case for the imageColorSpace member of the -- VkSwapchainCreateInfoKHR struct). -- -- - Corrected a typo in header file (last parameter in -- PFN_vkGetSurfacePropertiesKHR was missing “KHR” at the end of -- type: VkSurfacePropertiesKHR). -- -- - Revision 46, 2015-08-20 (Ian Elliott) -- -- - Renamed this extension and all of its enumerations, types, -- functions, etc. This makes it compliant with the proposed -- standard for Vulkan extensions. -- -- - Switched from “revision” to “version”, including use of the -- VK_MAKE_VERSION macro in the header file. -- -- - Made improvements to several descriptions. -- -- - Changed the status of several issues from PROPOSED to RESOLVED, -- leaving no unresolved issues. -- -- - Resolved several TODOs, did miscellaneous cleanup, etc. -- -- - Revision 47, 2015-08-20 (Ian Elliott—​porting a 2015-07-29 change -- from James Jones) -- -- - Moved the surface transform enums to VK_WSI_swapchain so they -- could be reused by VK_WSI_display. -- -- - Revision 48, 2015-09-01 (James Jones) -- -- - Various minor cleanups. -- -- - Revision 49, 2015-09-01 (James Jones) -- -- - Restore single-field revision number. -- -- - Revision 50, 2015-09-01 (James Jones) -- -- - Update Example #4 to include code that illustrates how to use -- the oldSwapchain field. -- -- - Revision 51, 2015-09-01 (James Jones) -- -- - Fix example code compilation errors. -- -- - Revision 52, 2015-09-08 (Matthaeus G. Chajdas) -- -- - Corrected a typo. -- -- - Revision 53, 2015-09-10 (Alon Or-bach) -- -- - Removed underscore from SWAP_CHAIN left in -- VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR. -- -- - Revision 54, 2015-09-11 (Jesse Hall) -- -- - Described the execution and memory coherence requirements for -- image transitions to and from -- VK_IMAGE_LAYOUT_PRESENT_SOURCE_KHR. -- -- - Revision 55, 2015-09-11 (Ray Smith) -- -- - Added errors for destroying and binding memory to presentable -- images -- -- - Revision 56, 2015-09-18 (James Jones) -- -- - Added fence argument to vkAcquireNextImageKHR -- -- - Added example of how to meter a host thread based on -- presentation rate. -- -- - Revision 57, 2015-09-26 (Jesse Hall) -- -- - Replace VkSurfaceDescriptionKHR with VkSurfaceKHR. -- -- - Added issue 25 with agreed resolution. -- -- - Revision 58, 2015-09-28 (Jesse Hall) -- -- - Renamed from VK_EXT_KHR_device_swapchain to -- VK_EXT_KHR_swapchain. -- -- - Revision 59, 2015-09-29 (Ian Elliott) -- -- - Changed vkDestroySwapchainKHR() to return void. -- -- - Revision 60, 2015-10-01 (Jeff Vigil) -- -- - Added error result VK_ERROR_SURFACE_LOST_KHR. -- -- - Revision 61, 2015-10-05 (Jason Ekstrand) -- -- - Added the VkCompositeAlpha enum and corresponding structure -- fields. -- -- - Revision 62, 2015-10-12 (Daniel Rakos) -- -- - Added VK_PRESENT_MODE_FIFO_RELAXED_KHR. -- -- - Revision 63, 2015-10-15 (Daniel Rakos) -- -- - Moved surface capability queries to VK_EXT_KHR_surface. -- -- - Revision 64, 2015-10-26 (Ian Elliott) -- -- - Renamed from VK_EXT_KHR_swapchain to VK_KHR_swapchain. -- -- - Revision 65, 2015-10-28 (Ian Elliott) -- -- - Added optional pResult member to VkPresentInfoKHR, so that -- per-swapchain results can be obtained from vkQueuePresentKHR(). -- -- - Revision 66, 2015-11-03 (Daniel Rakos) -- -- - Added allocation callbacks to create and destroy functions. -- -- - Updated resource transition language. -- -- - Updated sample code. -- -- - Revision 67, 2015-11-10 (Jesse Hall) -- -- - Add reserved flags bitmask to VkSwapchainCreateInfoKHR. -- -- - Modify naming and member ordering to match API style -- conventions, and so the VkSwapchainCreateInfoKHR image property -- members mirror corresponding VkImageCreateInfo members but with -- an \'image\' prefix. -- -- - Make VkPresentInfoKHR::pResults non-const; it is an output array -- parameter. -- -- - Make pPresentInfo parameter to vkQueuePresentKHR const. -- -- - Revision 68, 2016-04-05 (Ian Elliott) -- -- - Moved the “validity” include for vkAcquireNextImage to be in its -- proper place, after the prototype and list of parameters. -- -- - Clarified language about presentable images, including how they -- are acquired, when applications can and cannot use them, etc. As -- part of this, removed language about “ownership” of presentable -- images, and replaced it with more-consistent language about -- presentable images being “acquired” by the application. -- -- - 2016-08-23 (Ian Elliott) -- -- - Update the example code, to use the final API command names, to -- not have so many characters per line, and to split out a new -- example to show how to obtain function pointers. This code is -- more similar to the LunarG “cube” demo program. -- -- - 2016-08-25 (Ian Elliott) -- -- - A note was added at the beginning of the example code, stating -- that it will be removed from future versions of the appendix. -- -- - Revision 69, 2017-09-07 (Tobias Hector) -- -- - Added interactions with Vulkan 1.1 -- -- - Revision 70, 2017-10-06 (Ian Elliott) -- -- - Corrected interactions with Vulkan 1.1 -- -- == See Also -- -- 'PresentInfoKHR', 'SwapchainCreateFlagBitsKHR', -- 'SwapchainCreateFlagsKHR', 'SwapchainCreateInfoKHR', -- 'Vulkan.Extensions.Handles.SwapchainKHR', 'acquireNextImageKHR', -- 'createSwapchainKHR', 'destroySwapchainKHR', 'getSwapchainImagesKHR', -- 'queuePresentKHR' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_swapchain Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_KHR_swapchain ( createSwapchainKHR , withSwapchainKHR , destroySwapchainKHR , getSwapchainImagesKHR , acquireNextImageKHR , acquireNextImageKHRSafe , queuePresentKHR , getDeviceGroupPresentCapabilitiesKHR , getDeviceGroupSurfacePresentModesKHR , acquireNextImage2KHR , acquireNextImage2KHRSafe , getPhysicalDevicePresentRectanglesKHR , SwapchainCreateInfoKHR(..) , PresentInfoKHR(..) , DeviceGroupPresentCapabilitiesKHR(..) , ImageSwapchainCreateInfoKHR(..) , BindImageMemorySwapchainInfoKHR(..) , AcquireNextImageInfoKHR(..) , DeviceGroupPresentInfoKHR(..) , DeviceGroupSwapchainCreateInfoKHR(..) , DeviceGroupPresentModeFlagsKHR , DeviceGroupPresentModeFlagBitsKHR( DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR , DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR , DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR , DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR , .. ) , SwapchainCreateFlagsKHR , SwapchainCreateFlagBitsKHR( SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR , SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR , SWAPCHAIN_CREATE_PROTECTED_BIT_KHR , .. ) , KHR_SWAPCHAIN_SPEC_VERSION , pattern KHR_SWAPCHAIN_SPEC_VERSION , KHR_SWAPCHAIN_EXTENSION_NAME , pattern KHR_SWAPCHAIN_EXTENSION_NAME , SurfaceKHR(..) , SwapchainKHR(..) , PresentModeKHR(..) , ColorSpaceKHR(..) , CompositeAlphaFlagBitsKHR(..) , CompositeAlphaFlagsKHR , SurfaceTransformFlagBitsKHR(..) , SurfaceTransformFlagsKHR ) where import Vulkan.CStruct.Utils (FixedArray) import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Data.Typeable (eqT) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (castPtr) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import GHC.Show (showString) import Numeric (showHex) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Data.String (IsString) import Data.Type.Equality ((:~:)(Refl)) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Data.Word (Word32) import Data.Word (Word64) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.CStruct.Extends (forgetExtensions) import Vulkan.CStruct.Utils (lowerArrayPtr) import Vulkan.NamedType ((:::)) import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.CStruct.Extends (Chain) import Vulkan.Extensions.VK_KHR_surface (ColorSpaceKHR) import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagBitsKHR) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkAcquireNextImage2KHR)) import Vulkan.Dynamic (DeviceCmds(pVkAcquireNextImageKHR)) import Vulkan.Dynamic (DeviceCmds(pVkCreateSwapchainKHR)) import Vulkan.Dynamic (DeviceCmds(pVkDestroySwapchainKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetDeviceGroupPresentCapabilitiesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetDeviceGroupSurfacePresentModesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkGetSwapchainImagesKHR)) import Vulkan.Dynamic (DeviceCmds(pVkQueuePresentKHR)) import Vulkan.Core10.Handles (Device_T) import {-# SOURCE #-} Vulkan.Extensions.VK_KHR_display_swapchain (DisplayPresentInfoKHR) import Vulkan.CStruct.Extends (Extends) import Vulkan.CStruct.Extends (Extendss) import Vulkan.CStruct.Extends (Extensible(..)) import Vulkan.Core10.FundamentalTypes (Extent2D) import Vulkan.Core10.Handles (Fence) import Vulkan.Core10.Handles (Fence(..)) import Vulkan.Core10.FundamentalTypes (Flags) import Vulkan.Core10.Enums.Format (Format) import Vulkan.Core10.Handles (Image) import Vulkan.Core10.Handles (Image(..)) import {-# SOURCE #-} Vulkan.Core12.Promoted_From_VK_KHR_image_format_list (ImageFormatListCreateInfo) import Vulkan.Core10.Enums.ImageUsageFlagBits (ImageUsageFlags) import Vulkan.Dynamic (InstanceCmds(pVkGetPhysicalDevicePresentRectanglesKHR)) import Vulkan.Core10.APIConstants (MAX_DEVICE_GROUP_SIZE) import Vulkan.CStruct.Extends (PeekChain) import Vulkan.CStruct.Extends (PeekChain(..)) import Vulkan.Core10.Handles (PhysicalDevice) import Vulkan.Core10.Handles (PhysicalDevice(..)) import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice)) import Vulkan.Core10.Handles (PhysicalDevice_T) import Vulkan.CStruct.Extends (PokeChain) import Vulkan.CStruct.Extends (PokeChain(..)) import {-# SOURCE #-} Vulkan.Extensions.VK_GGP_frame_token (PresentFrameTokenGGP) import {-# SOURCE #-} Vulkan.Extensions.VK_KHR_present_id (PresentIdKHR) import Vulkan.Extensions.VK_KHR_surface (PresentModeKHR) import {-# SOURCE #-} Vulkan.Extensions.VK_KHR_incremental_present (PresentRegionsKHR) import {-# SOURCE #-} Vulkan.Extensions.VK_GOOGLE_display_timing (PresentTimesInfoGOOGLE) import Vulkan.Core10.Handles (Queue) import Vulkan.Core10.Handles (Queue(..)) import Vulkan.Core10.Handles (Queue(Queue)) import Vulkan.Core10.Handles (Queue_T) import Vulkan.Core10.FundamentalTypes (Rect2D) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core10.Handles (Semaphore) import Vulkan.Core10.Handles (Semaphore(..)) import Vulkan.Core10.Enums.SharingMode (SharingMode) import Vulkan.CStruct.Extends (SomeStruct) import Vulkan.Core10.Enums.StructureType (StructureType) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_full_screen_exclusive (SurfaceFullScreenExclusiveInfoEXT) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_full_screen_exclusive (SurfaceFullScreenExclusiveWin32InfoEXT) import Vulkan.Extensions.Handles (SurfaceKHR) import Vulkan.Extensions.Handles (SurfaceKHR(..)) import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagBitsKHR) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_display_control (SwapchainCounterCreateInfoEXT) import {-# SOURCE #-} Vulkan.Extensions.VK_AMD_display_native_hdr (SwapchainDisplayNativeHdrCreateInfoAMD) import Vulkan.Extensions.Handles (SwapchainKHR) import Vulkan.Extensions.Handles (SwapchainKHR(..)) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.APIConstants (pattern MAX_DEVICE_GROUP_SIZE) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PRESENT_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Extensions.VK_KHR_surface (ColorSpaceKHR(..)) import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagBitsKHR(..)) import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagsKHR) import Vulkan.Extensions.VK_KHR_surface (PresentModeKHR(..)) import Vulkan.Extensions.Handles (SurfaceKHR(..)) import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagBitsKHR(..)) import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagsKHR) import Vulkan.Extensions.Handles (SwapchainKHR(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCreateSwapchainKHR :: FunPtr (Ptr Device_T -> Ptr (SomeStruct SwapchainCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr SwapchainKHR -> IO Result) -> Ptr Device_T -> Ptr (SomeStruct SwapchainCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr SwapchainKHR -> IO Result -- | vkCreateSwapchainKHR - Create a swapchain -- -- = Description -- -- If the @oldSwapchain@ parameter of @pCreateInfo@ is a valid swapchain, -- which has exclusive full-screen access, that access is released from -- @oldSwapchain@. If the command succeeds in this case, the newly created -- swapchain will automatically acquire exclusive full-screen access from -- @oldSwapchain@. -- -- Note -- -- This implicit transfer is intended to avoid exiting and entering -- full-screen exclusive mode, which may otherwise cause unwanted visual -- updates to the display. -- -- In some cases, swapchain creation /may/ fail if exclusive full-screen -- mode is requested for application control, but for some -- implementation-specific reason exclusive full-screen access is -- unavailable for the particular combination of parameters provided. If -- this occurs, 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- will be returned. -- -- Note -- -- In particular, it will fail if the @imageExtent@ member of @pCreateInfo@ -- does not match the extents of the monitor. Other reasons for failure may -- include the app not being set as high-dpi aware, or if the physical -- device and monitor are not compatible in this mode. -- -- When the 'Vulkan.Extensions.Handles.SurfaceKHR' in -- 'SwapchainCreateInfoKHR' is a display surface, then the -- 'Vulkan.Extensions.Handles.DisplayModeKHR' in display surface’s -- 'Vulkan.Extensions.VK_KHR_display.DisplaySurfaceCreateInfoKHR' is -- associated with a particular 'Vulkan.Extensions.Handles.DisplayKHR'. -- Swapchain creation /may/ fail if that -- 'Vulkan.Extensions.Handles.DisplayKHR' is not acquired by the -- application. In this scenario -- 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' is returned. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCreateSwapchainKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkCreateSwapchainKHR-pCreateInfo-parameter# @pCreateInfo@ -- /must/ be a valid pointer to a valid 'SwapchainCreateInfoKHR' -- structure -- -- - #VUID-vkCreateSwapchainKHR-pAllocator-parameter# If @pAllocator@ is -- not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkCreateSwapchainKHR-pSwapchain-parameter# @pSwapchain@ /must/ -- be a valid pointer to a 'Vulkan.Extensions.Handles.SwapchainKHR' -- handle -- -- == Host Synchronization -- -- - Host access to @pCreateInfo->surface@ /must/ be externally -- synchronized -- -- - Host access to @pCreateInfo->oldSwapchain@ /must/ be externally -- synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_NATIVE_WINDOW_IN_USE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'SwapchainCreateInfoKHR', -- 'Vulkan.Extensions.Handles.SwapchainKHR' createSwapchainKHR :: forall a io . (Extendss SwapchainCreateInfoKHR a, PokeChain a, MonadIO io) => -- | @device@ is the device to create the swapchain for. Device -> -- | @pCreateInfo@ is a pointer to a 'SwapchainCreateInfoKHR' structure -- specifying the parameters of the created swapchain. (SwapchainCreateInfoKHR a) -> -- | @pAllocator@ is the allocator used for host memory allocated for the -- swapchain object when there is no more specific allocator available (see -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation>). ("allocator" ::: Maybe AllocationCallbacks) -> io (SwapchainKHR) createSwapchainKHR device createInfo allocator = liftIO . evalContT $ do let vkCreateSwapchainKHRPtr = pVkCreateSwapchainKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkCreateSwapchainKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateSwapchainKHR is null" Nothing Nothing let vkCreateSwapchainKHR' = mkVkCreateSwapchainKHR vkCreateSwapchainKHRPtr pCreateInfo <- ContT $ withCStruct (createInfo) pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) pPSwapchain <- ContT $ bracket (callocBytes @SwapchainKHR 8) free r <- lift $ traceAroundEvent "vkCreateSwapchainKHR" (vkCreateSwapchainKHR' (deviceHandle (device)) (forgetExtensions pCreateInfo) pAllocator (pPSwapchain)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pSwapchain <- lift $ peek @SwapchainKHR pPSwapchain pure $ (pSwapchain) -- | A convenience wrapper to make a compatible pair of calls to -- 'createSwapchainKHR' and 'destroySwapchainKHR' -- -- To ensure that 'destroySwapchainKHR' is always called: pass -- 'Control.Exception.bracket' (or the allocate function from your -- favourite resource management library) as the last argument. -- To just extract the pair pass '(,)' as the last argument. -- withSwapchainKHR :: forall a io r . (Extendss SwapchainCreateInfoKHR a, PokeChain a, MonadIO io) => Device -> SwapchainCreateInfoKHR a -> Maybe AllocationCallbacks -> (io SwapchainKHR -> (SwapchainKHR -> io ()) -> r) -> r withSwapchainKHR device pCreateInfo pAllocator b = b (createSwapchainKHR device pCreateInfo pAllocator) (\(o0) -> destroySwapchainKHR device o0 pAllocator) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkDestroySwapchainKHR :: FunPtr (Ptr Device_T -> SwapchainKHR -> Ptr AllocationCallbacks -> IO ()) -> Ptr Device_T -> SwapchainKHR -> Ptr AllocationCallbacks -> IO () -- | vkDestroySwapchainKHR - Destroy a swapchain object -- -- = Description -- -- The application /must/ not destroy a swapchain until after completion of -- all outstanding operations on images that were acquired from the -- swapchain. @swapchain@ and all associated 'Vulkan.Core10.Handles.Image' -- handles are destroyed, and /must/ not be acquired or used any more by -- the application. The memory of each 'Vulkan.Core10.Handles.Image' will -- only be freed after that image is no longer used by the presentation -- engine. For example, if one image of the swapchain is being displayed in -- a window, the memory for that image /may/ not be freed until the window -- is destroyed, or another swapchain is created for the window. Destroying -- the swapchain does not invalidate the parent -- 'Vulkan.Extensions.Handles.SurfaceKHR', and a new swapchain /can/ be -- created with it. -- -- When a swapchain associated with a display surface is destroyed, if the -- image most recently presented to the display surface is from the -- swapchain being destroyed, then either any display resources modified by -- presenting images from any swapchain associated with the display surface -- /must/ be reverted by the implementation to their state prior to the -- first present performed on one of these swapchains, or such resources -- /must/ be left in their current state. -- -- If @swapchain@ has exclusive full-screen access, it is released before -- the swapchain is destroyed. -- -- == Valid Usage -- -- - #VUID-vkDestroySwapchainKHR-swapchain-01282# All uses of presentable -- images acquired from @swapchain@ /must/ have completed execution -- -- - #VUID-vkDestroySwapchainKHR-swapchain-01283# If -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @swapchain@ was created, a compatible set of callbacks -- /must/ be provided here -- -- - #VUID-vkDestroySwapchainKHR-swapchain-01284# If no -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @swapchain@ was created, @pAllocator@ /must/ be @NULL@ -- -- == Valid Usage (Implicit) -- -- - #VUID-vkDestroySwapchainKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkDestroySwapchainKHR-swapchain-parameter# If @swapchain@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @swapchain@ /must/ be -- a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-vkDestroySwapchainKHR-pAllocator-parameter# If @pAllocator@ is -- not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkDestroySwapchainKHR-commonparent# Both of @device@, and -- @swapchain@ that are valid handles of non-ignored parameters /must/ -- have been created, allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Extensions.Handles.SwapchainKHR' destroySwapchainKHR :: forall io . (MonadIO io) => -- | @device@ is the 'Vulkan.Core10.Handles.Device' associated with -- @swapchain@. Device -> -- | @swapchain@ is the swapchain to destroy. SwapchainKHR -> -- | @pAllocator@ is the allocator used for host memory allocated for the -- swapchain object when there is no more specific allocator available (see -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation>). ("allocator" ::: Maybe AllocationCallbacks) -> io () destroySwapchainKHR device swapchain allocator = liftIO . evalContT $ do let vkDestroySwapchainKHRPtr = pVkDestroySwapchainKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkDestroySwapchainKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkDestroySwapchainKHR is null" Nothing Nothing let vkDestroySwapchainKHR' = mkVkDestroySwapchainKHR vkDestroySwapchainKHRPtr pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ traceAroundEvent "vkDestroySwapchainKHR" (vkDestroySwapchainKHR' (deviceHandle (device)) (swapchain) pAllocator) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetSwapchainImagesKHR :: FunPtr (Ptr Device_T -> SwapchainKHR -> Ptr Word32 -> Ptr Image -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Ptr Word32 -> Ptr Image -> IO Result -- | vkGetSwapchainImagesKHR - Obtain the array of presentable images -- associated with a swapchain -- -- = Description -- -- If @pSwapchainImages@ is @NULL@, then the number of presentable images -- for @swapchain@ is returned in @pSwapchainImageCount@. Otherwise, -- @pSwapchainImageCount@ /must/ point to a variable set by the user to the -- number of elements in the @pSwapchainImages@ array, and on return the -- variable is overwritten with the number of structures actually written -- to @pSwapchainImages@. If the value of @pSwapchainImageCount@ is less -- than the number of presentable images for @swapchain@, at most -- @pSwapchainImageCount@ structures will be written, and -- 'Vulkan.Core10.Enums.Result.INCOMPLETE' will be returned instead of -- 'Vulkan.Core10.Enums.Result.SUCCESS', to indicate that not all the -- available presentable images were returned. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetSwapchainImagesKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetSwapchainImagesKHR-swapchain-parameter# @swapchain@ -- /must/ be a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-vkGetSwapchainImagesKHR-pSwapchainImageCount-parameter# -- @pSwapchainImageCount@ /must/ be a valid pointer to a @uint32_t@ -- value -- -- - #VUID-vkGetSwapchainImagesKHR-pSwapchainImages-parameter# If the -- value referenced by @pSwapchainImageCount@ is not @0@, and -- @pSwapchainImages@ is not @NULL@, @pSwapchainImages@ /must/ be a -- valid pointer to an array of @pSwapchainImageCount@ -- 'Vulkan.Core10.Handles.Image' handles -- -- - #VUID-vkGetSwapchainImagesKHR-commonparent# Both of @device@, and -- @swapchain@ /must/ have been created, allocated, or retrieved from -- the same 'Vulkan.Core10.Handles.Instance' -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.INCOMPLETE' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Image', -- 'Vulkan.Extensions.Handles.SwapchainKHR' getSwapchainImagesKHR :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the swapchain to query. SwapchainKHR -> io (Result, ("swapchainImages" ::: Vector Image)) getSwapchainImagesKHR device swapchain = liftIO . evalContT $ do let vkGetSwapchainImagesKHRPtr = pVkGetSwapchainImagesKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkGetSwapchainImagesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetSwapchainImagesKHR is null" Nothing Nothing let vkGetSwapchainImagesKHR' = mkVkGetSwapchainImagesKHR vkGetSwapchainImagesKHRPtr let device' = deviceHandle (device) pPSwapchainImageCount <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkGetSwapchainImagesKHR" (vkGetSwapchainImagesKHR' device' (swapchain) (pPSwapchainImageCount) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pSwapchainImageCount <- lift $ peek @Word32 pPSwapchainImageCount pPSwapchainImages <- ContT $ bracket (callocBytes @Image ((fromIntegral (pSwapchainImageCount)) * 8)) free r' <- lift $ traceAroundEvent "vkGetSwapchainImagesKHR" (vkGetSwapchainImagesKHR' device' (swapchain) (pPSwapchainImageCount) (pPSwapchainImages)) lift $ when (r' < SUCCESS) (throwIO (VulkanException r')) pSwapchainImageCount' <- lift $ peek @Word32 pPSwapchainImageCount pSwapchainImages' <- lift $ generateM (fromIntegral (pSwapchainImageCount')) (\i -> peek @Image ((pPSwapchainImages `advancePtrBytes` (8 * (i)) :: Ptr Image))) pure $ ((r'), pSwapchainImages') foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkAcquireNextImageKHRUnsafe :: FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result foreign import ccall "dynamic" mkVkAcquireNextImageKHRSafe :: FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result -- | acquireNextImageKHR with selectable safeness acquireNextImageKHRSafeOrUnsafe :: forall io . (MonadIO io) => (FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Semaphore -> Fence -> Ptr Word32 -> IO Result) -> -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain from which an image is being -- acquired. SwapchainKHR -> -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. ("timeout" ::: Word64) -> -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. Semaphore -> -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. Fence -> io (Result, ("imageIndex" ::: Word32)) acquireNextImageKHRSafeOrUnsafe mkVkAcquireNextImageKHR device swapchain timeout semaphore fence = liftIO . evalContT $ do let vkAcquireNextImageKHRPtr = pVkAcquireNextImageKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkAcquireNextImageKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquireNextImageKHR is null" Nothing Nothing let vkAcquireNextImageKHR' = mkVkAcquireNextImageKHR vkAcquireNextImageKHRPtr pPImageIndex <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkAcquireNextImageKHR" (vkAcquireNextImageKHR' (deviceHandle (device)) (swapchain) (timeout) (semaphore) (fence) (pPImageIndex)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pImageIndex <- lift $ peek @Word32 pPImageIndex pure $ (r, pImageIndex) -- | vkAcquireNextImageKHR - Retrieve the index of the next available -- presentable image -- -- == Valid Usage -- -- - #VUID-vkAcquireNextImageKHR-swapchain-01285# @swapchain@ /must/ not -- be in the retired state -- -- - #VUID-vkAcquireNextImageKHR-semaphore-01286# If @semaphore@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled -- -- - #VUID-vkAcquireNextImageKHR-semaphore-01779# If @semaphore@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ not have any -- uncompleted signal or wait operations pending -- -- - #VUID-vkAcquireNextImageKHR-fence-01287# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled and -- /must/ not be associated with any other queue command that has not -- yet completed execution on that queue -- -- - #VUID-vkAcquireNextImageKHR-semaphore-01780# @semaphore@ and @fence@ -- /must/ not both be equal to 'Vulkan.Core10.APIConstants.NULL_HANDLE' -- -- - #VUID-vkAcquireNextImageKHR-swapchain-01802# If the number of -- currently acquired images is greater than the difference between the -- number of images in @swapchain@ and the value of -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@minImageCount@ -- as returned by a call to -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- with the @surface@ used to create @swapchain@, @timeout@ /must/ not -- be @UINT64_MAX@ -- -- - #VUID-vkAcquireNextImageKHR-semaphore-03265# @semaphore@ /must/ have -- a 'Vulkan.Core12.Enums.SemaphoreType.SemaphoreType' of -- 'Vulkan.Core12.Enums.SemaphoreType.SEMAPHORE_TYPE_BINARY' -- -- == Valid Usage (Implicit) -- -- - #VUID-vkAcquireNextImageKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkAcquireNextImageKHR-swapchain-parameter# @swapchain@ /must/ -- be a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-vkAcquireNextImageKHR-semaphore-parameter# If @semaphore@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @semaphore@ /must/ be -- a valid 'Vulkan.Core10.Handles.Semaphore' handle -- -- - #VUID-vkAcquireNextImageKHR-fence-parameter# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @fence@ /must/ be a valid -- 'Vulkan.Core10.Handles.Fence' handle -- -- - #VUID-vkAcquireNextImageKHR-pImageIndex-parameter# @pImageIndex@ -- /must/ be a valid pointer to a @uint32_t@ value -- -- - #VUID-vkAcquireNextImageKHR-semaphore-parent# If @semaphore@ is a -- valid handle, it /must/ have been created, allocated, or retrieved -- from @device@ -- -- - #VUID-vkAcquireNextImageKHR-fence-parent# If @fence@ is a valid -- handle, it /must/ have been created, allocated, or retrieved from -- @device@ -- -- - #VUID-vkAcquireNextImageKHR-commonparent# Both of @device@, and -- @swapchain@ that are valid handles of non-ignored parameters /must/ -- have been created, allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- - Host access to @semaphore@ /must/ be externally synchronized -- -- - Host access to @fence@ /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.TIMEOUT' -- -- - 'Vulkan.Core10.Enums.Result.NOT_READY' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.Fence', -- 'Vulkan.Core10.Handles.Semaphore', -- 'Vulkan.Extensions.Handles.SwapchainKHR' acquireNextImageKHR :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain from which an image is being -- acquired. SwapchainKHR -> -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. ("timeout" ::: Word64) -> -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. Semaphore -> -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. Fence -> io (Result, ("imageIndex" ::: Word32)) acquireNextImageKHR = acquireNextImageKHRSafeOrUnsafe mkVkAcquireNextImageKHRUnsafe -- | A variant of 'acquireNextImageKHR' which makes a *safe* FFI call acquireNextImageKHRSafe :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain from which an image is being -- acquired. SwapchainKHR -> -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. ("timeout" ::: Word64) -> -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. Semaphore -> -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. Fence -> io (Result, ("imageIndex" ::: Word32)) acquireNextImageKHRSafe = acquireNextImageKHRSafeOrUnsafe mkVkAcquireNextImageKHRSafe foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkQueuePresentKHR :: FunPtr (Ptr Queue_T -> Ptr (SomeStruct PresentInfoKHR) -> IO Result) -> Ptr Queue_T -> Ptr (SomeStruct PresentInfoKHR) -> IO Result -- | vkQueuePresentKHR - Queue an image for presentation -- -- = Description -- -- Note -- -- There is no requirement for an application to present images in the same -- order that they were acquired - applications can arbitrarily present any -- image that is currently acquired. -- -- == Valid Usage -- -- - #VUID-vkQueuePresentKHR-pSwapchains-01292# Each element of -- @pSwapchains@ member of @pPresentInfo@ /must/ be a swapchain that is -- created for a surface for which presentation is supported from -- @queue@ as determined using a call to -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- -- - #VUID-vkQueuePresentKHR-pSwapchains-01293# If more than one member -- of @pSwapchains@ was created from a display surface, all display -- surfaces referenced that refer to the same display /must/ use the -- same display mode -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-01294# When a semaphore wait -- operation referring to a binary semaphore defined by the elements of -- the @pWaitSemaphores@ member of @pPresentInfo@ executes on @queue@, -- there /must/ be no other queues waiting on the same semaphore -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-01295# All elements of the -- @pWaitSemaphores@ member of @pPresentInfo@ /must/ be semaphores that -- are signaled, or have -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-semaphores-signaling semaphore signal operations> -- previously submitted for execution -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-03267# All elements of the -- @pWaitSemaphores@ member of @pPresentInfo@ /must/ be created with a -- 'Vulkan.Core12.Enums.SemaphoreType.SemaphoreType' of -- 'Vulkan.Core12.Enums.SemaphoreType.SEMAPHORE_TYPE_BINARY' -- -- - #VUID-vkQueuePresentKHR-pWaitSemaphores-03268# All elements of the -- @pWaitSemaphores@ member of @pPresentInfo@ /must/ reference a -- semaphore signal operation that has been submitted for execution and -- any semaphore signal operations on which it depends (if any) /must/ -- have also been submitted for execution -- -- Any writes to memory backing the images referenced by the -- @pImageIndices@ and @pSwapchains@ members of @pPresentInfo@, that are -- available before 'queuePresentKHR' is executed, are automatically made -- visible to the read access performed by the presentation engine. This -- automatic visibility operation for an image happens-after the semaphore -- signal operation, and happens-before the presentation engine accesses -- the image. -- -- Queueing an image for presentation defines a set of /queue operations/, -- including waiting on the semaphores and submitting a presentation -- request to the presentation engine. However, the scope of this set of -- queue operations does not include the actual processing of the image by -- the presentation engine. -- -- Note -- -- The origin of the native orientation of the surface coordinate system is -- not specified in the Vulkan specification; it depends on the platform. -- For most platforms the origin is by default upper-left, meaning the -- pixel of the presented 'Vulkan.Core10.Handles.Image' at coordinates -- (0,0) would appear at the upper left pixel of the platform surface -- (assuming -- 'Vulkan.Extensions.VK_KHR_surface.SURFACE_TRANSFORM_IDENTITY_BIT_KHR', -- and the display standing the right way up). -- -- If 'queuePresentKHR' fails to enqueue the corresponding set of queue -- operations, it /may/ return -- 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' or -- 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY'. If it does, the -- implementation /must/ ensure that the state and contents of any -- resources or synchronization primitives referenced is unaffected by the -- call or its failure. -- -- If 'queuePresentKHR' fails in such a way that the implementation is -- unable to make that guarantee, the implementation /must/ return -- 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST'. -- -- However, if the presentation request is rejected by the presentation -- engine with an error 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR', -- 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT', -- or 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR', the set of queue -- operations are still considered to be enqueued and thus any semaphore -- wait operation specified in 'PresentInfoKHR' will execute when the -- corresponding queue operation is complete. -- -- Calls to 'queuePresentKHR' /may/ block, but /must/ return in finite -- time. -- -- If any @swapchain@ member of @pPresentInfo@ was created with -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT', -- 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- will be returned if that swapchain does not have exclusive full-screen -- access, possibly for implementation-specific reasons outside of the -- application’s control. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkQueuePresentKHR-queue-parameter# @queue@ /must/ be a valid -- 'Vulkan.Core10.Handles.Queue' handle -- -- - #VUID-vkQueuePresentKHR-pPresentInfo-parameter# @pPresentInfo@ -- /must/ be a valid pointer to a valid 'PresentInfoKHR' structure -- -- == Host Synchronization -- -- - Host access to @queue@ /must/ be externally synchronized -- -- - Host access to @pPresentInfo->pWaitSemaphores@[] /must/ be -- externally synchronized -- -- - Host access to @pPresentInfo->pSwapchains@[] /must/ be externally -- synchronized -- -- == Command Properties -- -- \' -- -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> | -- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+ -- | - | - | Any | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'PresentInfoKHR', 'Vulkan.Core10.Handles.Queue' queuePresentKHR :: forall a io . (Extendss PresentInfoKHR a, PokeChain a, MonadIO io) => -- | @queue@ is a queue that is capable of presentation to the target -- surface’s platform on the same device as the image’s swapchain. Queue -> -- | @pPresentInfo@ is a pointer to a 'PresentInfoKHR' structure specifying -- parameters of the presentation. (PresentInfoKHR a) -> io (Result) queuePresentKHR queue presentInfo = liftIO . evalContT $ do let vkQueuePresentKHRPtr = pVkQueuePresentKHR (case queue of Queue{deviceCmds} -> deviceCmds) lift $ unless (vkQueuePresentKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkQueuePresentKHR is null" Nothing Nothing let vkQueuePresentKHR' = mkVkQueuePresentKHR vkQueuePresentKHRPtr pPresentInfo <- ContT $ withCStruct (presentInfo) r <- lift $ traceAroundEvent "vkQueuePresentKHR" (vkQueuePresentKHR' (queueHandle (queue)) (forgetExtensions pPresentInfo)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pure $ (r) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetDeviceGroupPresentCapabilitiesKHR :: FunPtr (Ptr Device_T -> Ptr DeviceGroupPresentCapabilitiesKHR -> IO Result) -> Ptr Device_T -> Ptr DeviceGroupPresentCapabilitiesKHR -> IO Result -- | vkGetDeviceGroupPresentCapabilitiesKHR - Query present capabilities from -- other physical devices -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.Device', 'DeviceGroupPresentCapabilitiesKHR' getDeviceGroupPresentCapabilitiesKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device. -- -- #VUID-vkGetDeviceGroupPresentCapabilitiesKHR-device-parameter# @device@ -- /must/ be a valid 'Vulkan.Core10.Handles.Device' handle Device -> io (DeviceGroupPresentCapabilitiesKHR) getDeviceGroupPresentCapabilitiesKHR device = liftIO . evalContT $ do let vkGetDeviceGroupPresentCapabilitiesKHRPtr = pVkGetDeviceGroupPresentCapabilitiesKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkGetDeviceGroupPresentCapabilitiesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetDeviceGroupPresentCapabilitiesKHR is null" Nothing Nothing let vkGetDeviceGroupPresentCapabilitiesKHR' = mkVkGetDeviceGroupPresentCapabilitiesKHR vkGetDeviceGroupPresentCapabilitiesKHRPtr pPDeviceGroupPresentCapabilities <- ContT (withZeroCStruct @DeviceGroupPresentCapabilitiesKHR) r <- lift $ traceAroundEvent "vkGetDeviceGroupPresentCapabilitiesKHR" (vkGetDeviceGroupPresentCapabilitiesKHR' (deviceHandle (device)) (pPDeviceGroupPresentCapabilities)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pDeviceGroupPresentCapabilities <- lift $ peekCStruct @DeviceGroupPresentCapabilitiesKHR pPDeviceGroupPresentCapabilities pure $ (pDeviceGroupPresentCapabilities) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetDeviceGroupSurfacePresentModesKHR :: FunPtr (Ptr Device_T -> SurfaceKHR -> Ptr DeviceGroupPresentModeFlagsKHR -> IO Result) -> Ptr Device_T -> SurfaceKHR -> Ptr DeviceGroupPresentModeFlagsKHR -> IO Result -- | vkGetDeviceGroupSurfacePresentModesKHR - Query present capabilities for -- a surface -- -- = Description -- -- The modes returned by this command are not invariant, and /may/ change -- in response to the surface being moved, resized, or occluded. These -- modes /must/ be a subset of the modes returned by -- 'getDeviceGroupPresentCapabilitiesKHR'. -- -- == Valid Usage -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-surface-06212# -- @surface@ /must/ be supported by all physical devices associated -- with @device@, as reported by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- or an equivalent platform-specific mechanism -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-device-parameter# -- @device@ /must/ be a valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-surface-parameter# -- @surface@ /must/ be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' -- handle -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-pModes-parameter# -- @pModes@ /must/ be a valid pointer to a -- 'DeviceGroupPresentModeFlagsKHR' value -- -- - #VUID-vkGetDeviceGroupSurfacePresentModesKHR-commonparent# Both of -- @device@, and @surface@ /must/ have been created, allocated, or -- retrieved from the same 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @surface@ /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.Device', 'DeviceGroupPresentModeFlagsKHR', -- 'Vulkan.Extensions.Handles.SurfaceKHR' getDeviceGroupSurfacePresentModesKHR :: forall io . (MonadIO io) => -- | @device@ is the logical device. Device -> -- | @surface@ is the surface. SurfaceKHR -> io (("modes" ::: DeviceGroupPresentModeFlagsKHR)) getDeviceGroupSurfacePresentModesKHR device surface = liftIO . evalContT $ do let vkGetDeviceGroupSurfacePresentModesKHRPtr = pVkGetDeviceGroupSurfacePresentModesKHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkGetDeviceGroupSurfacePresentModesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetDeviceGroupSurfacePresentModesKHR is null" Nothing Nothing let vkGetDeviceGroupSurfacePresentModesKHR' = mkVkGetDeviceGroupSurfacePresentModesKHR vkGetDeviceGroupSurfacePresentModesKHRPtr pPModes <- ContT $ bracket (callocBytes @DeviceGroupPresentModeFlagsKHR 4) free r <- lift $ traceAroundEvent "vkGetDeviceGroupSurfacePresentModesKHR" (vkGetDeviceGroupSurfacePresentModesKHR' (deviceHandle (device)) (surface) (pPModes)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pModes <- lift $ peek @DeviceGroupPresentModeFlagsKHR pPModes pure $ (pModes) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkAcquireNextImage2KHRUnsafe :: FunPtr (Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result foreign import ccall "dynamic" mkVkAcquireNextImage2KHRSafe :: FunPtr (Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result -- | acquireNextImage2KHR with selectable safeness acquireNextImage2KHRSafeOrUnsafe :: forall io . (MonadIO io) => (FunPtr (Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> Ptr Device_T -> Ptr AcquireNextImageInfoKHR -> Ptr Word32 -> IO Result) -> -- | @device@ is the device associated with @swapchain@. Device -> -- | @pAcquireInfo@ is a pointer to a 'AcquireNextImageInfoKHR' structure -- containing parameters of the acquire. ("acquireInfo" ::: AcquireNextImageInfoKHR) -> io (Result, ("imageIndex" ::: Word32)) acquireNextImage2KHRSafeOrUnsafe mkVkAcquireNextImage2KHR device acquireInfo = liftIO . evalContT $ do let vkAcquireNextImage2KHRPtr = pVkAcquireNextImage2KHR (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkAcquireNextImage2KHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquireNextImage2KHR is null" Nothing Nothing let vkAcquireNextImage2KHR' = mkVkAcquireNextImage2KHR vkAcquireNextImage2KHRPtr pAcquireInfo <- ContT $ withCStruct (acquireInfo) pPImageIndex <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkAcquireNextImage2KHR" (vkAcquireNextImage2KHR' (deviceHandle (device)) pAcquireInfo (pPImageIndex)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pImageIndex <- lift $ peek @Word32 pPImageIndex pure $ (r, pImageIndex) -- | vkAcquireNextImage2KHR - Retrieve the index of the next available -- presentable image -- -- == Valid Usage -- -- - #VUID-vkAcquireNextImage2KHR-swapchain-01803# If the number of -- currently acquired images is greater than the difference between the -- number of images in the @swapchain@ member of @pAcquireInfo@ and the -- value of -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR'::@minImageCount@ -- as returned by a call to -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- with the @surface@ used to create @swapchain@, the @timeout@ member -- of @pAcquireInfo@ /must/ not be @UINT64_MAX@ -- -- == Valid Usage (Implicit) -- -- - #VUID-vkAcquireNextImage2KHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkAcquireNextImage2KHR-pAcquireInfo-parameter# @pAcquireInfo@ -- /must/ be a valid pointer to a valid 'AcquireNextImageInfoKHR' -- structure -- -- - #VUID-vkAcquireNextImage2KHR-pImageIndex-parameter# @pImageIndex@ -- /must/ be a valid pointer to a @uint32_t@ value -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.TIMEOUT' -- -- - 'Vulkan.Core10.Enums.Result.NOT_READY' -- -- - 'Vulkan.Core10.Enums.Result.SUBOPTIMAL_KHR' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'AcquireNextImageInfoKHR', 'Vulkan.Core10.Handles.Device' acquireNextImage2KHR :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @pAcquireInfo@ is a pointer to a 'AcquireNextImageInfoKHR' structure -- containing parameters of the acquire. ("acquireInfo" ::: AcquireNextImageInfoKHR) -> io (Result, ("imageIndex" ::: Word32)) acquireNextImage2KHR = acquireNextImage2KHRSafeOrUnsafe mkVkAcquireNextImage2KHRUnsafe -- | A variant of 'acquireNextImage2KHR' which makes a *safe* FFI call acquireNextImage2KHRSafe :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @pAcquireInfo@ is a pointer to a 'AcquireNextImageInfoKHR' structure -- containing parameters of the acquire. ("acquireInfo" ::: AcquireNextImageInfoKHR) -> io (Result, ("imageIndex" ::: Word32)) acquireNextImage2KHRSafe = acquireNextImage2KHRSafeOrUnsafe mkVkAcquireNextImage2KHRSafe foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetPhysicalDevicePresentRectanglesKHR :: FunPtr (Ptr PhysicalDevice_T -> SurfaceKHR -> Ptr Word32 -> Ptr Rect2D -> IO Result) -> Ptr PhysicalDevice_T -> SurfaceKHR -> Ptr Word32 -> Ptr Rect2D -> IO Result -- | vkGetPhysicalDevicePresentRectanglesKHR - Query present rectangles for a -- surface on a physical device -- -- = Description -- -- If @pRects@ is @NULL@, then the number of rectangles used when -- presenting the given @surface@ is returned in @pRectCount@. Otherwise, -- @pRectCount@ /must/ point to a variable set by the user to the number of -- elements in the @pRects@ array, and on return the variable is -- overwritten with the number of structures actually written to @pRects@. -- If the value of @pRectCount@ is less than the number of rectangles, at -- most @pRectCount@ structures will be written, and -- 'Vulkan.Core10.Enums.Result.INCOMPLETE' will be returned instead of -- 'Vulkan.Core10.Enums.Result.SUCCESS', to indicate that not all the -- available rectangles were returned. -- -- The values returned by this command are not invariant, and /may/ change -- in response to the surface being moved, resized, or occluded. -- -- The rectangles returned by this command /must/ not overlap. -- -- == Valid Usage -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-surface-06523# -- @surface@ /must/ be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' -- handle -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-surface-06211# -- @surface@ /must/ be supported by @physicalDevice@, as reported by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- or an equivalent platform-specific mechanism -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-physicalDevice-parameter# -- @physicalDevice@ /must/ be a valid -- 'Vulkan.Core10.Handles.PhysicalDevice' handle -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-surface-parameter# -- @surface@ /must/ be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' -- handle -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-pRectCount-parameter# -- @pRectCount@ /must/ be a valid pointer to a @uint32_t@ value -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-pRects-parameter# If -- the value referenced by @pRectCount@ is not @0@, and @pRects@ is not -- @NULL@, @pRects@ /must/ be a valid pointer to an array of -- @pRectCount@ 'Vulkan.Core10.FundamentalTypes.Rect2D' structures -- -- - #VUID-vkGetPhysicalDevicePresentRectanglesKHR-commonparent# Both of -- @physicalDevice@, and @surface@ /must/ have been created, allocated, -- or retrieved from the same 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @surface@ /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.INCOMPLETE' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.PhysicalDevice', -- 'Vulkan.Core10.FundamentalTypes.Rect2D', -- 'Vulkan.Extensions.Handles.SurfaceKHR' getPhysicalDevicePresentRectanglesKHR :: forall io . (MonadIO io) => -- | @physicalDevice@ is the physical device. PhysicalDevice -> -- | @surface@ is the surface. SurfaceKHR -> io (Result, ("rects" ::: Vector Rect2D)) getPhysicalDevicePresentRectanglesKHR physicalDevice surface = liftIO . evalContT $ do let vkGetPhysicalDevicePresentRectanglesKHRPtr = pVkGetPhysicalDevicePresentRectanglesKHR (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) lift $ unless (vkGetPhysicalDevicePresentRectanglesKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPhysicalDevicePresentRectanglesKHR is null" Nothing Nothing let vkGetPhysicalDevicePresentRectanglesKHR' = mkVkGetPhysicalDevicePresentRectanglesKHR vkGetPhysicalDevicePresentRectanglesKHRPtr let physicalDevice' = physicalDeviceHandle (physicalDevice) pPRectCount <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkGetPhysicalDevicePresentRectanglesKHR" (vkGetPhysicalDevicePresentRectanglesKHR' physicalDevice' (surface) (pPRectCount) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pRectCount <- lift $ peek @Word32 pPRectCount pPRects <- ContT $ bracket (callocBytes @Rect2D ((fromIntegral (pRectCount)) * 16)) free _ <- traverse (\i -> ContT $ pokeZeroCStruct (pPRects `advancePtrBytes` (i * 16) :: Ptr Rect2D) . ($ ())) [0..(fromIntegral (pRectCount)) - 1] r' <- lift $ traceAroundEvent "vkGetPhysicalDevicePresentRectanglesKHR" (vkGetPhysicalDevicePresentRectanglesKHR' physicalDevice' (surface) (pPRectCount) ((pPRects))) lift $ when (r' < SUCCESS) (throwIO (VulkanException r')) pRectCount' <- lift $ peek @Word32 pPRectCount pRects' <- lift $ generateM (fromIntegral (pRectCount')) (\i -> peekCStruct @Rect2D (((pPRects) `advancePtrBytes` (16 * (i)) :: Ptr Rect2D))) pure $ ((r'), pRects') -- | VkSwapchainCreateInfoKHR - Structure specifying parameters of a newly -- created swapchain object -- -- = Description -- -- Upon calling 'createSwapchainKHR' with an @oldSwapchain@ that is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @oldSwapchain@ is -- retired — even if creation of the new swapchain fails. The new swapchain -- is created in the non-retired state whether or not @oldSwapchain@ is -- 'Vulkan.Core10.APIConstants.NULL_HANDLE'. -- -- Upon calling 'createSwapchainKHR' with an @oldSwapchain@ that is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', any images from @oldSwapchain@ -- that are not acquired by the application /may/ be freed by the -- implementation, which /may/ occur even if creation of the new swapchain -- fails. The application /can/ destroy @oldSwapchain@ to free all memory -- associated with @oldSwapchain@. -- -- Note -- -- Multiple retired swapchains /can/ be associated with the same -- 'Vulkan.Extensions.Handles.SurfaceKHR' through multiple uses of -- @oldSwapchain@ that outnumber calls to 'destroySwapchainKHR'. -- -- After @oldSwapchain@ is retired, the application /can/ pass to -- 'queuePresentKHR' any images it had already acquired from -- @oldSwapchain@. E.g., an application may present an image from the old -- swapchain before an image from the new swapchain is ready to be -- presented. As usual, 'queuePresentKHR' /may/ fail if @oldSwapchain@ has -- entered a state that causes -- 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' to be returned. -- -- The application /can/ continue to use a shared presentable image -- obtained from @oldSwapchain@ until a presentable image is acquired from -- the new swapchain, as long as it has not entered a state that causes it -- to return 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR'. -- -- == Valid Usage -- -- - #VUID-VkSwapchainCreateInfoKHR-surface-01270# @surface@ /must/ be a -- surface that is supported by the device as determined using -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceSupportKHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-minImageCount-01272# @minImageCount@ -- /must/ be less than or equal to the value returned in the -- @maxImageCount@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface if the returned @maxImageCount@ is not zero -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-02839# If @presentMode@ -- is not -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR' -- nor -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR', -- then @minImageCount@ /must/ be greater than or equal to the value -- returned in the @minImageCount@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-minImageCount-01383# @minImageCount@ -- /must/ be @1@ if @presentMode@ is either -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR' -- or -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-imageFormat-01273# @imageFormat@ and -- @imageColorSpace@ /must/ match the @format@ and @colorSpace@ -- members, respectively, of one of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceFormatKHR' structures -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceFormatsKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-imageExtent-01274# @imageExtent@ -- /must/ be between @minImageExtent@ and @maxImageExtent@, inclusive, -- where @minImageExtent@ and @maxImageExtent@ are members of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-imageExtent-01689# @imageExtent@ -- members @width@ and @height@ /must/ both be non-zero -- -- - #VUID-VkSwapchainCreateInfoKHR-imageArrayLayers-01275# -- @imageArrayLayers@ /must/ be greater than @0@ and less than or equal -- to the @maxImageArrayLayers@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-01427# If @presentMode@ -- is 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_IMMEDIATE_KHR', -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_MAILBOX_KHR', -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_FIFO_KHR' or -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_FIFO_RELAXED_KHR', -- @imageUsage@ /must/ be a subset of the supported usage flags present -- in the @supportedUsageFlags@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageUsage-01384# If @presentMode@ is -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR' -- or -- 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR', -- @imageUsage@ /must/ be a subset of the supported usage flags present -- in the @sharedPresentSupportedUsageFlags@ member of the -- 'Vulkan.Extensions.VK_KHR_shared_presentable_image.SharedPresentSurfaceCapabilitiesKHR' -- structure returned by -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- for @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01277# If -- @imageSharingMode@ is -- 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT', -- @pQueueFamilyIndices@ /must/ be a valid pointer to an array of -- @queueFamilyIndexCount@ @uint32_t@ values -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01278# If -- @imageSharingMode@ is -- 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT', -- @queueFamilyIndexCount@ /must/ be greater than @1@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01428# If -- @imageSharingMode@ is -- 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT', each -- element of @pQueueFamilyIndices@ /must/ be unique and /must/ be less -- than @pQueueFamilyPropertyCount@ returned by either -- 'Vulkan.Core10.DeviceInitialization.getPhysicalDeviceQueueFamilyProperties' -- or -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceQueueFamilyProperties2' -- for the @physicalDevice@ that was used to create @device@ -- -- - #VUID-VkSwapchainCreateInfoKHR-preTransform-01279# @preTransform@ -- /must/ be one of the bits present in the @supportedTransforms@ -- member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-compositeAlpha-01280# -- @compositeAlpha@ /must/ be one of the bits present in the -- @supportedCompositeAlpha@ member of the -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceCapabilitiesKHR' structure -- returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-01281# @presentMode@ -- /must/ be one of the -- 'Vulkan.Extensions.VK_KHR_surface.PresentModeKHR' values returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfacePresentModesKHR' -- for the surface -- -- - #VUID-VkSwapchainCreateInfoKHR-physicalDeviceCount-01429# If the -- logical device was created with -- 'Vulkan.Core11.Promoted_From_VK_KHR_device_group_creation.DeviceGroupDeviceCreateInfo'::@physicalDeviceCount@ -- equal to 1, @flags@ /must/ not contain -- 'SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933# If @oldSwapchain@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @oldSwapchain@ -- /must/ be a non-retired swapchain associated with native window -- referred to by @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageFormat-01778# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#swapchain-wsi-image-create-info implied image creation parameters> -- of the swapchain /must/ be supported as reported by -- 'Vulkan.Core10.DeviceInitialization.getPhysicalDeviceImageFormatProperties' -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-03168# If @flags@ contains -- 'SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR' then the @pNext@ chain -- /must/ include a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure with a @viewFormatCount@ greater than zero and -- @pViewFormats@ /must/ have an element equal to @imageFormat@ -- -- - #VUID-VkSwapchainCreateInfoKHR-pNext-04099# If a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure was included in the @pNext@ chain and -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@viewFormatCount@ -- is not zero then all of the formats in -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@pViewFormats@ -- /must/ be compatible with the @format@ as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatibility compatibility table> -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-04100# If @flags@ does not -- contain 'SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR' and the @pNext@ -- chain include a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure then -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@viewFormatCount@ -- /must/ be @0@ or @1@ -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-03187# If @flags@ contains -- 'SWAPCHAIN_CREATE_PROTECTED_BIT_KHR', then -- 'Vulkan.Extensions.VK_KHR_surface_protected_capabilities.SurfaceProtectedCapabilitiesKHR'::@supportsProtected@ -- /must/ be 'Vulkan.Core10.FundamentalTypes.TRUE' in the -- 'Vulkan.Extensions.VK_KHR_surface_protected_capabilities.SurfaceProtectedCapabilitiesKHR' -- structure returned by -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceCapabilities2KHR' -- for @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-pNext-02679# If the @pNext@ chain -- includes a -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveInfoEXT' -- structure with its @fullScreenExclusive@ member set to -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT', -- and @surface@ was created using -- 'Vulkan.Extensions.VK_KHR_win32_surface.createWin32SurfaceKHR', a -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveWin32InfoEXT' -- structure /must/ be included in the @pNext@ chain -- -- == Valid Usage (Implicit) -- -- - #VUID-VkSwapchainCreateInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR' -- -- - #VUID-VkSwapchainCreateInfoKHR-pNext-pNext# Each @pNext@ member of -- any structure (including this one) in the @pNext@ chain /must/ be -- either @NULL@ or a pointer to a valid instance of -- 'DeviceGroupSwapchainCreateInfoKHR', -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo', -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveInfoEXT', -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.SurfaceFullScreenExclusiveWin32InfoEXT', -- 'Vulkan.Extensions.VK_EXT_display_control.SwapchainCounterCreateInfoEXT', -- or -- 'Vulkan.Extensions.VK_AMD_display_native_hdr.SwapchainDisplayNativeHdrCreateInfoAMD' -- -- - #VUID-VkSwapchainCreateInfoKHR-sType-unique# The @sType@ value of -- each struct in the @pNext@ chain /must/ be unique -- -- - #VUID-VkSwapchainCreateInfoKHR-flags-parameter# @flags@ /must/ be a -- valid combination of 'SwapchainCreateFlagBitsKHR' values -- -- - #VUID-VkSwapchainCreateInfoKHR-surface-parameter# @surface@ /must/ -- be a valid 'Vulkan.Extensions.Handles.SurfaceKHR' handle -- -- - #VUID-VkSwapchainCreateInfoKHR-imageFormat-parameter# @imageFormat@ -- /must/ be a valid 'Vulkan.Core10.Enums.Format.Format' value -- -- - #VUID-VkSwapchainCreateInfoKHR-imageColorSpace-parameter# -- @imageColorSpace@ /must/ be a valid -- 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR' value -- -- - #VUID-VkSwapchainCreateInfoKHR-imageUsage-parameter# @imageUsage@ -- /must/ be a valid combination of -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlagBits' values -- -- - #VUID-VkSwapchainCreateInfoKHR-imageUsage-requiredbitmask# -- @imageUsage@ /must/ not be @0@ -- -- - #VUID-VkSwapchainCreateInfoKHR-imageSharingMode-parameter# -- @imageSharingMode@ /must/ be a valid -- 'Vulkan.Core10.Enums.SharingMode.SharingMode' value -- -- - #VUID-VkSwapchainCreateInfoKHR-preTransform-parameter# -- @preTransform@ /must/ be a valid -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceTransformFlagBitsKHR' value -- -- - #VUID-VkSwapchainCreateInfoKHR-compositeAlpha-parameter# -- @compositeAlpha@ /must/ be a valid -- 'Vulkan.Extensions.VK_KHR_surface.CompositeAlphaFlagBitsKHR' value -- -- - #VUID-VkSwapchainCreateInfoKHR-presentMode-parameter# @presentMode@ -- /must/ be a valid 'Vulkan.Extensions.VK_KHR_surface.PresentModeKHR' -- value -- -- - #VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parameter# If -- @oldSwapchain@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @oldSwapchain@ /must/ be a valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-VkSwapchainCreateInfoKHR-oldSwapchain-parent# If -- @oldSwapchain@ is a valid handle, it /must/ have been created, -- allocated, or retrieved from @surface@ -- -- - #VUID-VkSwapchainCreateInfoKHR-commonparent# Both of @oldSwapchain@, -- and @surface@ that are valid handles of non-ignored parameters -- /must/ have been created, allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR', -- 'Vulkan.Extensions.VK_KHR_surface.CompositeAlphaFlagBitsKHR', -- 'Vulkan.Core10.FundamentalTypes.Extent2D', -- 'Vulkan.Core10.Enums.Format.Format', -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlags', -- 'Vulkan.Extensions.VK_KHR_surface.PresentModeKHR', -- 'Vulkan.Core10.Enums.SharingMode.SharingMode', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SurfaceKHR', -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceTransformFlagBitsKHR', -- 'SwapchainCreateFlagsKHR', 'Vulkan.Extensions.Handles.SwapchainKHR', -- 'Vulkan.Extensions.VK_KHR_display_swapchain.createSharedSwapchainsKHR', -- 'createSwapchainKHR' data SwapchainCreateInfoKHR (es :: [Type]) = SwapchainCreateInfoKHR { -- | @pNext@ is @NULL@ or a pointer to a structure extending this structure. next :: Chain es , -- | @flags@ is a bitmask of 'SwapchainCreateFlagBitsKHR' indicating -- parameters of the swapchain creation. flags :: SwapchainCreateFlagsKHR , -- | @surface@ is the surface onto which the swapchain will present images. -- If the creation succeeds, the swapchain becomes associated with -- @surface@. surface :: SurfaceKHR , -- | @minImageCount@ is the minimum number of presentable images that the -- application needs. The implementation will either create the swapchain -- with at least that many images, or it will fail to create the swapchain. minImageCount :: Word32 , -- | @imageFormat@ is a 'Vulkan.Core10.Enums.Format.Format' value specifying -- the format the swapchain image(s) will be created with. imageFormat :: Format , -- | @imageColorSpace@ is a 'Vulkan.Extensions.VK_KHR_surface.ColorSpaceKHR' -- value specifying the way the swapchain interprets image data. imageColorSpace :: ColorSpaceKHR , -- | @imageExtent@ is the size (in pixels) of the swapchain image(s). The -- behavior is platform-dependent if the image extent does not match the -- surface’s @currentExtent@ as returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR'. -- -- Note -- -- On some platforms, it is normal that @maxImageExtent@ /may/ become @(0, -- 0)@, for example when the window is minimized. In such a case, it is not -- possible to create a swapchain due to the Valid Usage requirements. imageExtent :: Extent2D , -- | @imageArrayLayers@ is the number of views in a multiview\/stereo -- surface. For non-stereoscopic-3D applications, this value is 1. imageArrayLayers :: Word32 , -- | @imageUsage@ is a bitmask of -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlagBits' describing -- the intended usage of the (acquired) swapchain images. imageUsage :: ImageUsageFlags , -- | @imageSharingMode@ is the sharing mode used for the image(s) of the -- swapchain. imageSharingMode :: SharingMode , -- | @pQueueFamilyIndices@ is a pointer to an array of queue family indices -- having access to the images(s) of the swapchain when @imageSharingMode@ -- is 'Vulkan.Core10.Enums.SharingMode.SHARING_MODE_CONCURRENT'. queueFamilyIndices :: Vector Word32 , -- | @preTransform@ is a -- 'Vulkan.Extensions.VK_KHR_surface.SurfaceTransformFlagBitsKHR' value -- describing the transform, relative to the presentation engine’s natural -- orientation, applied to the image content prior to presentation. If it -- does not match the @currentTransform@ value returned by -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceCapabilitiesKHR', -- the presentation engine will transform the image content as part of the -- presentation operation. preTransform :: SurfaceTransformFlagBitsKHR , -- | @compositeAlpha@ is a -- 'Vulkan.Extensions.VK_KHR_surface.CompositeAlphaFlagBitsKHR' value -- indicating the alpha compositing mode to use when this surface is -- composited together with other surfaces on certain window systems. compositeAlpha :: CompositeAlphaFlagBitsKHR , -- | @presentMode@ is the presentation mode the swapchain will use. A -- swapchain’s present mode determines how incoming present requests will -- be processed and queued internally. presentMode :: PresentModeKHR , -- | @clipped@ specifies whether the Vulkan implementation is allowed to -- discard rendering operations that affect regions of the surface that are -- not visible. -- -- - If set to 'Vulkan.Core10.FundamentalTypes.TRUE', the presentable -- images associated with the swapchain /may/ not own all of their -- pixels. Pixels in the presentable images that correspond to regions -- of the target surface obscured by another window on the desktop, or -- subject to some other clipping mechanism will have undefined content -- when read back. Fragment shaders /may/ not execute for these pixels, -- and thus any side effects they would have had will not occur. -- Setting 'Vulkan.Core10.FundamentalTypes.TRUE' does not guarantee any -- clipping will occur, but allows more efficient presentation methods -- to be used on some platforms. -- -- - If set to 'Vulkan.Core10.FundamentalTypes.FALSE', presentable images -- associated with the swapchain will own all of the pixels they -- contain. -- -- Note -- -- Applications /should/ set this value to -- 'Vulkan.Core10.FundamentalTypes.TRUE' if they do not expect to read -- back the content of presentable images before presenting them or -- after reacquiring them, and if their fragment shaders do not have -- any side effects that require them to run for all pixels in the -- presentable image. clipped :: Bool , -- | @oldSwapchain@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE', or the -- existing non-retired swapchain currently associated with @surface@. -- Providing a valid @oldSwapchain@ /may/ aid in the resource reuse, and -- also allows the application to still present any images that are already -- acquired from it. oldSwapchain :: SwapchainKHR } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (SwapchainCreateInfoKHR (es :: [Type])) #endif deriving instance Show (Chain es) => Show (SwapchainCreateInfoKHR es) instance Extensible SwapchainCreateInfoKHR where extensibleTypeName = "SwapchainCreateInfoKHR" setNext SwapchainCreateInfoKHR{..} next' = SwapchainCreateInfoKHR{next = next', ..} getNext SwapchainCreateInfoKHR{..} = next extends :: forall e b proxy. Typeable e => proxy e -> (Extends SwapchainCreateInfoKHR e => b) -> Maybe b extends _ f | Just Refl <- eqT @e @SurfaceFullScreenExclusiveWin32InfoEXT = Just f | Just Refl <- eqT @e @SurfaceFullScreenExclusiveInfoEXT = Just f | Just Refl <- eqT @e @ImageFormatListCreateInfo = Just f | Just Refl <- eqT @e @SwapchainDisplayNativeHdrCreateInfoAMD = Just f | Just Refl <- eqT @e @DeviceGroupSwapchainCreateInfoKHR = Just f | Just Refl <- eqT @e @SwapchainCounterCreateInfoEXT = Just f | otherwise = Nothing instance (Extendss SwapchainCreateInfoKHR es, PokeChain es) => ToCStruct (SwapchainCreateInfoKHR es) where withCStruct x f = allocaBytes 104 $ \p -> pokeCStruct p x (f p) pokeCStruct p SwapchainCreateInfoKHR{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR) pNext'' <- fmap castPtr . ContT $ withChain (next) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'' lift $ poke ((p `plusPtr` 16 :: Ptr SwapchainCreateFlagsKHR)) (flags) lift $ poke ((p `plusPtr` 24 :: Ptr SurfaceKHR)) (surface) lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) (minImageCount) lift $ poke ((p `plusPtr` 36 :: Ptr Format)) (imageFormat) lift $ poke ((p `plusPtr` 40 :: Ptr ColorSpaceKHR)) (imageColorSpace) lift $ poke ((p `plusPtr` 44 :: Ptr Extent2D)) (imageExtent) lift $ poke ((p `plusPtr` 52 :: Ptr Word32)) (imageArrayLayers) lift $ poke ((p `plusPtr` 56 :: Ptr ImageUsageFlags)) (imageUsage) lift $ poke ((p `plusPtr` 60 :: Ptr SharingMode)) (imageSharingMode) lift $ poke ((p `plusPtr` 64 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (queueFamilyIndices)) :: Word32)) pPQueueFamilyIndices' <- ContT $ allocaBytes @Word32 ((Data.Vector.length (queueFamilyIndices)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPQueueFamilyIndices' `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (queueFamilyIndices) lift $ poke ((p `plusPtr` 72 :: Ptr (Ptr Word32))) (pPQueueFamilyIndices') lift $ poke ((p `plusPtr` 80 :: Ptr SurfaceTransformFlagBitsKHR)) (preTransform) lift $ poke ((p `plusPtr` 84 :: Ptr CompositeAlphaFlagBitsKHR)) (compositeAlpha) lift $ poke ((p `plusPtr` 88 :: Ptr PresentModeKHR)) (presentMode) lift $ poke ((p `plusPtr` 92 :: Ptr Bool32)) (boolToBool32 (clipped)) lift $ poke ((p `plusPtr` 96 :: Ptr SwapchainKHR)) (oldSwapchain) lift $ f cStructSize = 104 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR) pNext' <- fmap castPtr . ContT $ withZeroChain @es lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext' lift $ poke ((p `plusPtr` 24 :: Ptr SurfaceKHR)) (zero) lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) (zero) lift $ poke ((p `plusPtr` 36 :: Ptr Format)) (zero) lift $ poke ((p `plusPtr` 40 :: Ptr ColorSpaceKHR)) (zero) lift $ poke ((p `plusPtr` 44 :: Ptr Extent2D)) (zero) lift $ poke ((p `plusPtr` 52 :: Ptr Word32)) (zero) lift $ poke ((p `plusPtr` 56 :: Ptr ImageUsageFlags)) (zero) lift $ poke ((p `plusPtr` 60 :: Ptr SharingMode)) (zero) lift $ poke ((p `plusPtr` 80 :: Ptr SurfaceTransformFlagBitsKHR)) (zero) lift $ poke ((p `plusPtr` 84 :: Ptr CompositeAlphaFlagBitsKHR)) (zero) lift $ poke ((p `plusPtr` 88 :: Ptr PresentModeKHR)) (zero) lift $ poke ((p `plusPtr` 92 :: Ptr Bool32)) (boolToBool32 (zero)) lift $ f instance (Extendss SwapchainCreateInfoKHR es, PeekChain es) => FromCStruct (SwapchainCreateInfoKHR es) where peekCStruct p = do pNext <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ()))) next <- peekChain (castPtr pNext) flags <- peek @SwapchainCreateFlagsKHR ((p `plusPtr` 16 :: Ptr SwapchainCreateFlagsKHR)) surface <- peek @SurfaceKHR ((p `plusPtr` 24 :: Ptr SurfaceKHR)) minImageCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) imageFormat <- peek @Format ((p `plusPtr` 36 :: Ptr Format)) imageColorSpace <- peek @ColorSpaceKHR ((p `plusPtr` 40 :: Ptr ColorSpaceKHR)) imageExtent <- peekCStruct @Extent2D ((p `plusPtr` 44 :: Ptr Extent2D)) imageArrayLayers <- peek @Word32 ((p `plusPtr` 52 :: Ptr Word32)) imageUsage <- peek @ImageUsageFlags ((p `plusPtr` 56 :: Ptr ImageUsageFlags)) imageSharingMode <- peek @SharingMode ((p `plusPtr` 60 :: Ptr SharingMode)) queueFamilyIndexCount <- peek @Word32 ((p `plusPtr` 64 :: Ptr Word32)) pQueueFamilyIndices <- peek @(Ptr Word32) ((p `plusPtr` 72 :: Ptr (Ptr Word32))) pQueueFamilyIndices' <- generateM (fromIntegral queueFamilyIndexCount) (\i -> peek @Word32 ((pQueueFamilyIndices `advancePtrBytes` (4 * (i)) :: Ptr Word32))) preTransform <- peek @SurfaceTransformFlagBitsKHR ((p `plusPtr` 80 :: Ptr SurfaceTransformFlagBitsKHR)) compositeAlpha <- peek @CompositeAlphaFlagBitsKHR ((p `plusPtr` 84 :: Ptr CompositeAlphaFlagBitsKHR)) presentMode <- peek @PresentModeKHR ((p `plusPtr` 88 :: Ptr PresentModeKHR)) clipped <- peek @Bool32 ((p `plusPtr` 92 :: Ptr Bool32)) oldSwapchain <- peek @SwapchainKHR ((p `plusPtr` 96 :: Ptr SwapchainKHR)) pure $ SwapchainCreateInfoKHR next flags surface minImageCount imageFormat imageColorSpace imageExtent imageArrayLayers imageUsage imageSharingMode pQueueFamilyIndices' preTransform compositeAlpha presentMode (bool32ToBool clipped) oldSwapchain instance es ~ '[] => Zero (SwapchainCreateInfoKHR es) where zero = SwapchainCreateInfoKHR () zero zero zero zero zero zero zero zero zero mempty zero zero zero zero zero -- | VkPresentInfoKHR - Structure describing parameters of a queue -- presentation -- -- = Description -- -- Before an application /can/ present an image, the image’s layout /must/ -- be transitioned to the -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR' layout, -- or for a shared presentable image the -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_SHARED_PRESENT_KHR' -- layout. -- -- Note -- -- When transitioning the image to -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_SHARED_PRESENT_KHR' or -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR', there is -- no need to delay subsequent processing, or perform any visibility -- operations (as 'queuePresentKHR' performs automatic visibility -- operations). To achieve this, the @dstAccessMask@ member of the -- 'Vulkan.Core10.OtherTypes.ImageMemoryBarrier' /should/ be set to @0@, -- and the @dstStageMask@ parameter /should/ be set to -- 'Vulkan.Core10.Enums.PipelineStageFlagBits.PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT'. -- -- == Valid Usage -- -- - #VUID-VkPresentInfoKHR-pImageIndices-01430# Each element of -- @pImageIndices@ /must/ be the index of a presentable image acquired -- from the swapchain specified by the corresponding element of the -- @pSwapchains@ array, and the presented image subresource /must/ be -- in the -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR' or -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_SHARED_PRESENT_KHR' -- layout at the time the operation is executed on a -- 'Vulkan.Core10.Handles.Device' -- -- - #VUID-VkPresentInfoKHR-pNext-06235# If a -- 'Vulkan.Extensions.VK_KHR_present_id.PresentIdKHR' structure is -- included in the @pNext@ chain, and the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-presentId presentId> -- feature is not enabled, each @presentIds@ entry in that structure -- /must/ be NULL -- -- == Valid Usage (Implicit) -- -- - #VUID-VkPresentInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PRESENT_INFO_KHR' -- -- - #VUID-VkPresentInfoKHR-pNext-pNext# Each @pNext@ member of any -- structure (including this one) in the @pNext@ chain /must/ be either -- @NULL@ or a pointer to a valid instance of -- 'DeviceGroupPresentInfoKHR', -- 'Vulkan.Extensions.VK_KHR_display_swapchain.DisplayPresentInfoKHR', -- 'Vulkan.Extensions.VK_GGP_frame_token.PresentFrameTokenGGP', -- 'Vulkan.Extensions.VK_KHR_present_id.PresentIdKHR', -- 'Vulkan.Extensions.VK_KHR_incremental_present.PresentRegionsKHR', or -- 'Vulkan.Extensions.VK_GOOGLE_display_timing.PresentTimesInfoGOOGLE' -- -- - #VUID-VkPresentInfoKHR-sType-unique# The @sType@ value of each -- struct in the @pNext@ chain /must/ be unique -- -- - #VUID-VkPresentInfoKHR-pWaitSemaphores-parameter# If -- @waitSemaphoreCount@ is not @0@, @pWaitSemaphores@ /must/ be a valid -- pointer to an array of @waitSemaphoreCount@ valid -- 'Vulkan.Core10.Handles.Semaphore' handles -- -- - #VUID-VkPresentInfoKHR-pSwapchains-parameter# @pSwapchains@ /must/ -- be a valid pointer to an array of @swapchainCount@ valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handles -- -- - #VUID-VkPresentInfoKHR-pImageIndices-parameter# @pImageIndices@ -- /must/ be a valid pointer to an array of @swapchainCount@ @uint32_t@ -- values -- -- - #VUID-VkPresentInfoKHR-pResults-parameter# If @pResults@ is not -- @NULL@, @pResults@ /must/ be a valid pointer to an array of -- @swapchainCount@ 'Vulkan.Core10.Enums.Result.Result' values -- -- - #VUID-VkPresentInfoKHR-swapchainCount-arraylength# @swapchainCount@ -- /must/ be greater than @0@ -- -- - #VUID-VkPresentInfoKHR-commonparent# Both of the elements of -- @pSwapchains@, and the elements of @pWaitSemaphores@ that are valid -- handles of non-ignored parameters /must/ have been created, -- allocated, or retrieved from the same -- 'Vulkan.Core10.Handles.Instance' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'Vulkan.Core10.Enums.Result.Result', 'Vulkan.Core10.Handles.Semaphore', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR', 'queuePresentKHR' data PresentInfoKHR (es :: [Type]) = PresentInfoKHR { -- | @pNext@ is @NULL@ or a pointer to a structure extending this structure. next :: Chain es , -- | @pWaitSemaphores@ is @NULL@ or a pointer to an array of -- 'Vulkan.Core10.Handles.Semaphore' objects with @waitSemaphoreCount@ -- entries, and specifies the semaphores to wait for before issuing the -- present request. waitSemaphores :: Vector Semaphore , -- | @pSwapchains@ is a pointer to an array of -- 'Vulkan.Extensions.Handles.SwapchainKHR' objects with @swapchainCount@ -- entries. A given swapchain /must/ not appear in this list more than -- once. swapchains :: Vector SwapchainKHR , -- | @pImageIndices@ is a pointer to an array of indices into the array of -- each swapchain’s presentable images, with @swapchainCount@ entries. Each -- entry in this array identifies the image to present on the corresponding -- entry in the @pSwapchains@ array. imageIndices :: Vector Word32 , -- | @pResults@ is a pointer to an array of -- 'Vulkan.Core10.Enums.Result.Result' typed elements with @swapchainCount@ -- entries. Applications that do not need per-swapchain results /can/ use -- @NULL@ for @pResults@. If non-@NULL@, each entry in @pResults@ will be -- set to the 'Vulkan.Core10.Enums.Result.Result' for presenting the -- swapchain corresponding to the same index in @pSwapchains@. results :: Ptr Result } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (PresentInfoKHR (es :: [Type])) #endif deriving instance Show (Chain es) => Show (PresentInfoKHR es) instance Extensible PresentInfoKHR where extensibleTypeName = "PresentInfoKHR" setNext PresentInfoKHR{..} next' = PresentInfoKHR{next = next', ..} getNext PresentInfoKHR{..} = next extends :: forall e b proxy. Typeable e => proxy e -> (Extends PresentInfoKHR e => b) -> Maybe b extends _ f | Just Refl <- eqT @e @PresentFrameTokenGGP = Just f | Just Refl <- eqT @e @PresentTimesInfoGOOGLE = Just f | Just Refl <- eqT @e @PresentIdKHR = Just f | Just Refl <- eqT @e @DeviceGroupPresentInfoKHR = Just f | Just Refl <- eqT @e @PresentRegionsKHR = Just f | Just Refl <- eqT @e @DisplayPresentInfoKHR = Just f | otherwise = Nothing instance (Extendss PresentInfoKHR es, PokeChain es) => ToCStruct (PresentInfoKHR es) where withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p) pokeCStruct p PresentInfoKHR{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PRESENT_INFO_KHR) pNext'' <- fmap castPtr . ContT $ withChain (next) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'' lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (waitSemaphores)) :: Word32)) pPWaitSemaphores' <- ContT $ allocaBytes @Semaphore ((Data.Vector.length (waitSemaphores)) * 8) lift $ Data.Vector.imapM_ (\i e -> poke (pPWaitSemaphores' `plusPtr` (8 * (i)) :: Ptr Semaphore) (e)) (waitSemaphores) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr Semaphore))) (pPWaitSemaphores') let pSwapchainsLength = Data.Vector.length $ (swapchains) lift $ unless ((Data.Vector.length $ (imageIndices)) == pSwapchainsLength) $ throwIO $ IOError Nothing InvalidArgument "" "pImageIndices and pSwapchains must have the same length" Nothing Nothing lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) ((fromIntegral pSwapchainsLength :: Word32)) pPSwapchains' <- ContT $ allocaBytes @SwapchainKHR ((Data.Vector.length (swapchains)) * 8) lift $ Data.Vector.imapM_ (\i e -> poke (pPSwapchains' `plusPtr` (8 * (i)) :: Ptr SwapchainKHR) (e)) (swapchains) lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr SwapchainKHR))) (pPSwapchains') pPImageIndices' <- ContT $ allocaBytes @Word32 ((Data.Vector.length (imageIndices)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPImageIndices' `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (imageIndices) lift $ poke ((p `plusPtr` 48 :: Ptr (Ptr Word32))) (pPImageIndices') lift $ poke ((p `plusPtr` 56 :: Ptr (Ptr Result))) (results) lift $ f cStructSize = 64 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PRESENT_INFO_KHR) pNext' <- fmap castPtr . ContT $ withZeroChain @es lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext' lift $ f instance (Extendss PresentInfoKHR es, PeekChain es) => FromCStruct (PresentInfoKHR es) where peekCStruct p = do pNext <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ()))) next <- peekChain (castPtr pNext) waitSemaphoreCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pWaitSemaphores <- peek @(Ptr Semaphore) ((p `plusPtr` 24 :: Ptr (Ptr Semaphore))) pWaitSemaphores' <- generateM (fromIntegral waitSemaphoreCount) (\i -> peek @Semaphore ((pWaitSemaphores `advancePtrBytes` (8 * (i)) :: Ptr Semaphore))) swapchainCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pSwapchains <- peek @(Ptr SwapchainKHR) ((p `plusPtr` 40 :: Ptr (Ptr SwapchainKHR))) pSwapchains' <- generateM (fromIntegral swapchainCount) (\i -> peek @SwapchainKHR ((pSwapchains `advancePtrBytes` (8 * (i)) :: Ptr SwapchainKHR))) pImageIndices <- peek @(Ptr Word32) ((p `plusPtr` 48 :: Ptr (Ptr Word32))) pImageIndices' <- generateM (fromIntegral swapchainCount) (\i -> peek @Word32 ((pImageIndices `advancePtrBytes` (4 * (i)) :: Ptr Word32))) pResults <- peek @(Ptr Result) ((p `plusPtr` 56 :: Ptr (Ptr Result))) pure $ PresentInfoKHR next pWaitSemaphores' pSwapchains' pImageIndices' pResults instance es ~ '[] => Zero (PresentInfoKHR es) where zero = PresentInfoKHR () mempty mempty mempty zero -- | VkDeviceGroupPresentCapabilitiesKHR - Present capabilities from other -- physical devices -- -- = Description -- -- @modes@ always has 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR' set. -- -- The present mode flags are also used when presenting an image, in -- 'DeviceGroupPresentInfoKHR'::@mode@. -- -- If a device group only includes a single physical device, then @modes@ -- /must/ equal 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR'. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentModeFlagsKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'getDeviceGroupPresentCapabilitiesKHR' data DeviceGroupPresentCapabilitiesKHR = DeviceGroupPresentCapabilitiesKHR { -- | @presentMask@ is an array of -- 'Vulkan.Core10.APIConstants.MAX_DEVICE_GROUP_SIZE' @uint32_t@ masks, -- where the mask at element i is non-zero if physical device i has a -- presentation engine, and where bit j is set in element i if physical -- device i /can/ present swapchain images from physical device j. If -- element i is non-zero, then bit i /must/ be set. presentMask :: Vector Word32 , -- | @modes@ is a bitmask of 'DeviceGroupPresentModeFlagBitsKHR' indicating -- which device group presentation modes are supported. modes :: DeviceGroupPresentModeFlagsKHR } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DeviceGroupPresentCapabilitiesKHR) #endif deriving instance Show DeviceGroupPresentCapabilitiesKHR instance ToCStruct DeviceGroupPresentCapabilitiesKHR where withCStruct x f = allocaBytes 152 $ \p -> pokeCStruct p x (f p) pokeCStruct p DeviceGroupPresentCapabilitiesKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) unless ((Data.Vector.length $ (presentMask)) <= MAX_DEVICE_GROUP_SIZE) $ throwIO $ IOError Nothing InvalidArgument "" "presentMask is too long, a maximum of MAX_DEVICE_GROUP_SIZE elements are allowed" Nothing Nothing Data.Vector.imapM_ (\i e -> poke ((lowerArrayPtr ((p `plusPtr` 16 :: Ptr (FixedArray MAX_DEVICE_GROUP_SIZE Word32)))) `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (presentMask) poke ((p `plusPtr` 144 :: Ptr DeviceGroupPresentModeFlagsKHR)) (modes) f cStructSize = 152 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 144 :: Ptr DeviceGroupPresentModeFlagsKHR)) (zero) f instance FromCStruct DeviceGroupPresentCapabilitiesKHR where peekCStruct p = do presentMask <- generateM (MAX_DEVICE_GROUP_SIZE) (\i -> peek @Word32 (((lowerArrayPtr @Word32 ((p `plusPtr` 16 :: Ptr (FixedArray MAX_DEVICE_GROUP_SIZE Word32)))) `advancePtrBytes` (4 * (i)) :: Ptr Word32))) modes <- peek @DeviceGroupPresentModeFlagsKHR ((p `plusPtr` 144 :: Ptr DeviceGroupPresentModeFlagsKHR)) pure $ DeviceGroupPresentCapabilitiesKHR presentMask modes instance Storable DeviceGroupPresentCapabilitiesKHR where sizeOf ~_ = 152 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero DeviceGroupPresentCapabilitiesKHR where zero = DeviceGroupPresentCapabilitiesKHR mempty zero -- | VkImageSwapchainCreateInfoKHR - Specify that an image will be bound to -- swapchain memory -- -- == Valid Usage -- -- - #VUID-VkImageSwapchainCreateInfoKHR-swapchain-00995# If @swapchain@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', the fields of -- 'Vulkan.Core10.Image.ImageCreateInfo' /must/ match the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#swapchain-wsi-image-create-info implied image creation parameters> -- of the swapchain -- -- == Valid Usage (Implicit) -- -- - #VUID-VkImageSwapchainCreateInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR' -- -- - #VUID-VkImageSwapchainCreateInfoKHR-swapchain-parameter# If -- @swapchain@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @swapchain@ /must/ be a valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR' data ImageSwapchainCreateInfoKHR = ImageSwapchainCreateInfoKHR { -- | @swapchain@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a handle of a -- swapchain that the image will be bound to. swapchain :: SwapchainKHR } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImageSwapchainCreateInfoKHR) #endif deriving instance Show ImageSwapchainCreateInfoKHR instance ToCStruct ImageSwapchainCreateInfoKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImageSwapchainCreateInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (swapchain) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct ImageSwapchainCreateInfoKHR where peekCStruct p = do swapchain <- peek @SwapchainKHR ((p `plusPtr` 16 :: Ptr SwapchainKHR)) pure $ ImageSwapchainCreateInfoKHR swapchain instance Storable ImageSwapchainCreateInfoKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero ImageSwapchainCreateInfoKHR where zero = ImageSwapchainCreateInfoKHR zero -- | VkBindImageMemorySwapchainInfoKHR - Structure specifying swapchain image -- memory to bind to -- -- = Description -- -- If @swapchain@ is not @NULL@, the @swapchain@ and @imageIndex@ are used -- to determine the memory that the image is bound to, instead of @memory@ -- and @memoryOffset@. -- -- Memory /can/ be bound to a swapchain and use the @pDeviceIndices@ or -- @pSplitInstanceBindRegions@ members of -- 'Vulkan.Core11.Promoted_From_VK_KHR_device_groupAndVK_KHR_bind_memory2.BindImageMemoryDeviceGroupInfo'. -- -- == Valid Usage -- -- - #VUID-VkBindImageMemorySwapchainInfoKHR-imageIndex-01644# -- @imageIndex@ /must/ be less than the number of images in @swapchain@ -- -- == Valid Usage (Implicit) -- -- - #VUID-VkBindImageMemorySwapchainInfoKHR-sType-sType# @sType@ /must/ -- be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR' -- -- - #VUID-VkBindImageMemorySwapchainInfoKHR-swapchain-parameter# -- @swapchain@ /must/ be a valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR' data BindImageMemorySwapchainInfoKHR = BindImageMemorySwapchainInfoKHR { -- | @swapchain@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a swapchain -- handle. swapchain :: SwapchainKHR , -- | @imageIndex@ is an image index within @swapchain@. imageIndex :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (BindImageMemorySwapchainInfoKHR) #endif deriving instance Show BindImageMemorySwapchainInfoKHR instance ToCStruct BindImageMemorySwapchainInfoKHR where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p BindImageMemorySwapchainInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (swapchain) poke ((p `plusPtr` 24 :: Ptr Word32)) (imageIndex) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (zero) poke ((p `plusPtr` 24 :: Ptr Word32)) (zero) f instance FromCStruct BindImageMemorySwapchainInfoKHR where peekCStruct p = do swapchain <- peek @SwapchainKHR ((p `plusPtr` 16 :: Ptr SwapchainKHR)) imageIndex <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32)) pure $ BindImageMemorySwapchainInfoKHR swapchain imageIndex instance Storable BindImageMemorySwapchainInfoKHR where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero BindImageMemorySwapchainInfoKHR where zero = BindImageMemorySwapchainInfoKHR zero zero -- | VkAcquireNextImageInfoKHR - Structure specifying parameters of the -- acquire -- -- = Description -- -- If 'acquireNextImageKHR' is used, the device mask is considered to -- include all physical devices in the logical device. -- -- Note -- -- 'acquireNextImage2KHR' signals at most one semaphore, even if the -- application requests waiting for multiple physical devices to be ready -- via the @deviceMask@. However, only a single physical device /can/ wait -- on that semaphore, since the semaphore becomes unsignaled when the wait -- succeeds. For other physical devices to wait for the image to be ready, -- it is necessary for the application to submit semaphore signal -- operation(s) to that first physical device to signal additional -- semaphore(s) after the wait succeeds, which the other physical device(s) -- /can/ wait upon. -- -- == Valid Usage -- -- - #VUID-VkAcquireNextImageInfoKHR-swapchain-01675# @swapchain@ /must/ -- not be in the retired state -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-01288# If @semaphore@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-01781# If @semaphore@ is -- not 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ not have any -- uncompleted signal or wait operations pending -- -- - #VUID-VkAcquireNextImageInfoKHR-fence-01289# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' it /must/ be unsignaled and -- /must/ not be associated with any other queue command that has not -- yet completed execution on that queue -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-01782# @semaphore@ and -- @fence@ /must/ not both be equal to -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' -- -- - #VUID-VkAcquireNextImageInfoKHR-deviceMask-01290# @deviceMask@ -- /must/ be a valid device mask -- -- - #VUID-VkAcquireNextImageInfoKHR-deviceMask-01291# @deviceMask@ -- /must/ not be zero -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-03266# @semaphore@ /must/ -- have a 'Vulkan.Core12.Enums.SemaphoreType.SemaphoreType' of -- 'Vulkan.Core12.Enums.SemaphoreType.SEMAPHORE_TYPE_BINARY' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkAcquireNextImageInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR' -- -- - #VUID-VkAcquireNextImageInfoKHR-pNext-pNext# @pNext@ /must/ be -- @NULL@ -- -- - #VUID-VkAcquireNextImageInfoKHR-swapchain-parameter# @swapchain@ -- /must/ be a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-VkAcquireNextImageInfoKHR-semaphore-parameter# If @semaphore@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @semaphore@ /must/ -- be a valid 'Vulkan.Core10.Handles.Semaphore' handle -- -- - #VUID-VkAcquireNextImageInfoKHR-fence-parameter# If @fence@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @fence@ /must/ be a valid -- 'Vulkan.Core10.Handles.Fence' handle -- -- - #VUID-VkAcquireNextImageInfoKHR-commonparent# Each of @fence@, -- @semaphore@, and @swapchain@ that are valid handles of non-ignored -- parameters /must/ have been created, allocated, or retrieved from -- the same 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- - Host access to @semaphore@ /must/ be externally synchronized -- -- - Host access to @fence@ /must/ be externally synchronized -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'Vulkan.Core10.Handles.Fence', 'Vulkan.Core10.Handles.Semaphore', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'Vulkan.Extensions.Handles.SwapchainKHR', 'acquireNextImage2KHR' data AcquireNextImageInfoKHR = AcquireNextImageInfoKHR { -- | @swapchain@ is a non-retired swapchain from which an image is acquired. swapchain :: SwapchainKHR , -- | @timeout@ specifies how long the function waits, in nanoseconds, if no -- image is available. timeout :: Word64 , -- | @semaphore@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a semaphore -- to signal. semaphore :: Semaphore , -- | @fence@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE' or a fence to -- signal. fence :: Fence , -- | @deviceMask@ is a mask of physical devices for which the swapchain image -- will be ready to use when the semaphore or fence is signaled. deviceMask :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (AcquireNextImageInfoKHR) #endif deriving instance Show AcquireNextImageInfoKHR instance ToCStruct AcquireNextImageInfoKHR where withCStruct x f = allocaBytes 56 $ \p -> pokeCStruct p x (f p) pokeCStruct p AcquireNextImageInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (swapchain) poke ((p `plusPtr` 24 :: Ptr Word64)) (timeout) poke ((p `plusPtr` 32 :: Ptr Semaphore)) (semaphore) poke ((p `plusPtr` 40 :: Ptr Fence)) (fence) poke ((p `plusPtr` 48 :: Ptr Word32)) (deviceMask) f cStructSize = 56 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SwapchainKHR)) (zero) poke ((p `plusPtr` 24 :: Ptr Word64)) (zero) poke ((p `plusPtr` 48 :: Ptr Word32)) (zero) f instance FromCStruct AcquireNextImageInfoKHR where peekCStruct p = do swapchain <- peek @SwapchainKHR ((p `plusPtr` 16 :: Ptr SwapchainKHR)) timeout <- peek @Word64 ((p `plusPtr` 24 :: Ptr Word64)) semaphore <- peek @Semaphore ((p `plusPtr` 32 :: Ptr Semaphore)) fence <- peek @Fence ((p `plusPtr` 40 :: Ptr Fence)) deviceMask <- peek @Word32 ((p `plusPtr` 48 :: Ptr Word32)) pure $ AcquireNextImageInfoKHR swapchain timeout semaphore fence deviceMask instance Storable AcquireNextImageInfoKHR where sizeOf ~_ = 56 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero AcquireNextImageInfoKHR where zero = AcquireNextImageInfoKHR zero zero zero zero zero -- | VkDeviceGroupPresentInfoKHR - Mode and mask controlling which physical -- devices\' images are presented -- -- = Description -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR', then each -- element of @pDeviceMasks@ selects which instance of the swapchain image -- is presented. Each element of @pDeviceMasks@ /must/ have exactly one bit -- set, and the corresponding physical device /must/ have a presentation -- engine as reported by 'DeviceGroupPresentCapabilitiesKHR'. -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR', then each -- element of @pDeviceMasks@ selects which instance of the swapchain image -- is presented. Each element of @pDeviceMasks@ /must/ have exactly one bit -- set, and some physical device in the logical device /must/ include that -- bit in its 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@. -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR', then each element -- of @pDeviceMasks@ selects which instances of the swapchain image are -- component-wise summed and the sum of those images is presented. If the -- sum in any component is outside the representable range, the value of -- that component is undefined. Each element of @pDeviceMasks@ /must/ have -- a value for which all set bits are set in one of the elements of -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@. -- -- If @mode@ is 'DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR', -- then each element of @pDeviceMasks@ selects which instance(s) of the -- swapchain images are presented. For each bit set in each element of -- @pDeviceMasks@, the corresponding physical device /must/ have a -- presentation engine as reported by 'DeviceGroupPresentCapabilitiesKHR'. -- -- If 'DeviceGroupPresentInfoKHR' is not provided or @swapchainCount@ is -- zero then the masks are considered to be @1@. If -- 'DeviceGroupPresentInfoKHR' is not provided, @mode@ is considered to be -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR'. -- -- == Valid Usage -- -- - #VUID-VkDeviceGroupPresentInfoKHR-swapchainCount-01297# -- @swapchainCount@ /must/ equal @0@ or -- 'PresentInfoKHR'::@swapchainCount@ -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01298# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR', then each element of -- @pDeviceMasks@ /must/ have exactly one bit set, and the -- corresponding element of -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ /must/ be -- non-zero -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01299# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR', then each element of -- @pDeviceMasks@ /must/ have exactly one bit set, and some physical -- device in the logical device /must/ include that bit in its -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01300# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR', then each element of -- @pDeviceMasks@ /must/ have a value for which all set bits are set in -- one of the elements of -- 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01301# If @mode@ is -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR', then for -- each bit set in each element of @pDeviceMasks@, the corresponding -- element of 'DeviceGroupPresentCapabilitiesKHR'::@presentMask@ /must/ -- be non-zero -- -- - #VUID-VkDeviceGroupPresentInfoKHR-pDeviceMasks-01302# The value of -- each element of @pDeviceMasks@ /must/ be equal to the device mask -- passed in 'AcquireNextImageInfoKHR'::@deviceMask@ when the image -- index was last acquired -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-01303# @mode@ /must/ have -- exactly one bit set, and that bit /must/ have been included in -- 'DeviceGroupSwapchainCreateInfoKHR'::@modes@ -- -- == Valid Usage (Implicit) -- -- - #VUID-VkDeviceGroupPresentInfoKHR-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR' -- -- - #VUID-VkDeviceGroupPresentInfoKHR-pDeviceMasks-parameter# If -- @swapchainCount@ is not @0@, @pDeviceMasks@ /must/ be a valid -- pointer to an array of @swapchainCount@ @uint32_t@ values -- -- - #VUID-VkDeviceGroupPresentInfoKHR-mode-parameter# @mode@ /must/ be a -- valid 'DeviceGroupPresentModeFlagBitsKHR' value -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentModeFlagBitsKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data DeviceGroupPresentInfoKHR = DeviceGroupPresentInfoKHR { -- | @pDeviceMasks@ is a pointer to an array of device masks, one for each -- element of 'PresentInfoKHR'::pSwapchains. deviceMasks :: Vector Word32 , -- | @mode@ is a 'DeviceGroupPresentModeFlagBitsKHR' value specifying the -- device group present mode that will be used for this present. mode :: DeviceGroupPresentModeFlagBitsKHR } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (DeviceGroupPresentInfoKHR) #endif deriving instance Show DeviceGroupPresentInfoKHR instance ToCStruct DeviceGroupPresentInfoKHR where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p DeviceGroupPresentInfoKHR{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (deviceMasks)) :: Word32)) pPDeviceMasks' <- ContT $ allocaBytes @Word32 ((Data.Vector.length (deviceMasks)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPDeviceMasks' `plusPtr` (4 * (i)) :: Ptr Word32) (e)) (deviceMasks) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr Word32))) (pPDeviceMasks') lift $ poke ((p `plusPtr` 32 :: Ptr DeviceGroupPresentModeFlagBitsKHR)) (mode) lift $ f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 32 :: Ptr DeviceGroupPresentModeFlagBitsKHR)) (zero) f instance FromCStruct DeviceGroupPresentInfoKHR where peekCStruct p = do swapchainCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pDeviceMasks <- peek @(Ptr Word32) ((p `plusPtr` 24 :: Ptr (Ptr Word32))) pDeviceMasks' <- generateM (fromIntegral swapchainCount) (\i -> peek @Word32 ((pDeviceMasks `advancePtrBytes` (4 * (i)) :: Ptr Word32))) mode <- peek @DeviceGroupPresentModeFlagBitsKHR ((p `plusPtr` 32 :: Ptr DeviceGroupPresentModeFlagBitsKHR)) pure $ DeviceGroupPresentInfoKHR pDeviceMasks' mode instance Zero DeviceGroupPresentInfoKHR where zero = DeviceGroupPresentInfoKHR mempty zero -- | VkDeviceGroupSwapchainCreateInfoKHR - Structure specifying parameters of -- a newly created swapchain object -- -- = Description -- -- If this structure is not present, @modes@ is considered to be -- 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR'. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentModeFlagsKHR', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data DeviceGroupSwapchainCreateInfoKHR = DeviceGroupSwapchainCreateInfoKHR { -- | @modes@ is a bitfield of modes that the swapchain /can/ be used with. -- -- #VUID-VkDeviceGroupSwapchainCreateInfoKHR-modes-parameter# @modes@ -- /must/ be a valid combination of 'DeviceGroupPresentModeFlagBitsKHR' -- values -- -- #VUID-VkDeviceGroupSwapchainCreateInfoKHR-modes-requiredbitmask# @modes@ -- /must/ not be @0@ modes :: DeviceGroupPresentModeFlagsKHR } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (DeviceGroupSwapchainCreateInfoKHR) #endif deriving instance Show DeviceGroupSwapchainCreateInfoKHR instance ToCStruct DeviceGroupSwapchainCreateInfoKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p DeviceGroupSwapchainCreateInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr DeviceGroupPresentModeFlagsKHR)) (modes) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr DeviceGroupPresentModeFlagsKHR)) (zero) f instance FromCStruct DeviceGroupSwapchainCreateInfoKHR where peekCStruct p = do modes <- peek @DeviceGroupPresentModeFlagsKHR ((p `plusPtr` 16 :: Ptr DeviceGroupPresentModeFlagsKHR)) pure $ DeviceGroupSwapchainCreateInfoKHR modes instance Storable DeviceGroupSwapchainCreateInfoKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero DeviceGroupSwapchainCreateInfoKHR where zero = DeviceGroupSwapchainCreateInfoKHR zero type DeviceGroupPresentModeFlagsKHR = DeviceGroupPresentModeFlagBitsKHR -- | VkDeviceGroupPresentModeFlagBitsKHR - Bitmask specifying supported -- device group present modes -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_device_group VK_KHR_device_group>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_surface VK_KHR_surface>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>, -- 'DeviceGroupPresentInfoKHR', 'DeviceGroupPresentModeFlagsKHR' newtype DeviceGroupPresentModeFlagBitsKHR = DeviceGroupPresentModeFlagBitsKHR Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR' specifies that any physical -- device with a presentation engine /can/ present its own swapchain -- images. pattern DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000001 -- | 'DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR' specifies that any physical -- device with a presentation engine /can/ present swapchain images from -- any physical device in its @presentMask@. pattern DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000002 -- | 'DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR' specifies that any physical -- device with a presentation engine /can/ present the sum of swapchain -- images from any physical devices in its @presentMask@. pattern DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000004 -- | 'DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR' specifies that -- multiple physical devices with a presentation engine /can/ each present -- their own swapchain images. pattern DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR = DeviceGroupPresentModeFlagBitsKHR 0x00000008 conNameDeviceGroupPresentModeFlagBitsKHR :: String conNameDeviceGroupPresentModeFlagBitsKHR = "DeviceGroupPresentModeFlagBitsKHR" enumPrefixDeviceGroupPresentModeFlagBitsKHR :: String enumPrefixDeviceGroupPresentModeFlagBitsKHR = "DEVICE_GROUP_PRESENT_MODE_" showTableDeviceGroupPresentModeFlagBitsKHR :: [(DeviceGroupPresentModeFlagBitsKHR, String)] showTableDeviceGroupPresentModeFlagBitsKHR = [ (DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR , "LOCAL_BIT_KHR") , (DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR , "REMOTE_BIT_KHR") , (DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR , "SUM_BIT_KHR") , (DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR, "LOCAL_MULTI_DEVICE_BIT_KHR") ] instance Show DeviceGroupPresentModeFlagBitsKHR where showsPrec = enumShowsPrec enumPrefixDeviceGroupPresentModeFlagBitsKHR showTableDeviceGroupPresentModeFlagBitsKHR conNameDeviceGroupPresentModeFlagBitsKHR (\(DeviceGroupPresentModeFlagBitsKHR x) -> x) (\x -> showString "0x" . showHex x) instance Read DeviceGroupPresentModeFlagBitsKHR where readPrec = enumReadPrec enumPrefixDeviceGroupPresentModeFlagBitsKHR showTableDeviceGroupPresentModeFlagBitsKHR conNameDeviceGroupPresentModeFlagBitsKHR DeviceGroupPresentModeFlagBitsKHR type SwapchainCreateFlagsKHR = SwapchainCreateFlagBitsKHR -- | VkSwapchainCreateFlagBitsKHR - Bitmask controlling swapchain creation -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_swapchain VK_KHR_swapchain>, -- 'SwapchainCreateFlagsKHR' newtype SwapchainCreateFlagBitsKHR = SwapchainCreateFlagBitsKHR Flags deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR' specifies that the images of -- the swapchain /can/ be used to create a -- 'Vulkan.Core10.Handles.ImageView' with a different format than what the -- swapchain was created with. The list of allowed image view formats is -- specified by adding a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure to the @pNext@ chain of 'SwapchainCreateInfoKHR'. In addition, -- this flag also specifies that the swapchain /can/ be created with usage -- flags that are not supported for the format the swapchain is created -- with but are supported for at least one of the allowed image view -- formats. pattern SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR = SwapchainCreateFlagBitsKHR 0x00000004 -- | 'SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR' specifies that -- images created from the swapchain (i.e. with the @swapchain@ member of -- 'ImageSwapchainCreateInfoKHR' set to this swapchain’s handle) /must/ use -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT'. pattern SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = SwapchainCreateFlagBitsKHR 0x00000001 -- | 'SWAPCHAIN_CREATE_PROTECTED_BIT_KHR' specifies that images created from -- the swapchain are protected images. pattern SWAPCHAIN_CREATE_PROTECTED_BIT_KHR = SwapchainCreateFlagBitsKHR 0x00000002 conNameSwapchainCreateFlagBitsKHR :: String conNameSwapchainCreateFlagBitsKHR = "SwapchainCreateFlagBitsKHR" enumPrefixSwapchainCreateFlagBitsKHR :: String enumPrefixSwapchainCreateFlagBitsKHR = "SWAPCHAIN_CREATE_" showTableSwapchainCreateFlagBitsKHR :: [(SwapchainCreateFlagBitsKHR, String)] showTableSwapchainCreateFlagBitsKHR = [ (SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR , "MUTABLE_FORMAT_BIT_KHR") , (SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR, "SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR") , (SWAPCHAIN_CREATE_PROTECTED_BIT_KHR , "PROTECTED_BIT_KHR") ] instance Show SwapchainCreateFlagBitsKHR where showsPrec = enumShowsPrec enumPrefixSwapchainCreateFlagBitsKHR showTableSwapchainCreateFlagBitsKHR conNameSwapchainCreateFlagBitsKHR (\(SwapchainCreateFlagBitsKHR x) -> x) (\x -> showString "0x" . showHex x) instance Read SwapchainCreateFlagBitsKHR where readPrec = enumReadPrec enumPrefixSwapchainCreateFlagBitsKHR showTableSwapchainCreateFlagBitsKHR conNameSwapchainCreateFlagBitsKHR SwapchainCreateFlagBitsKHR type KHR_SWAPCHAIN_SPEC_VERSION = 70 -- No documentation found for TopLevel "VK_KHR_SWAPCHAIN_SPEC_VERSION" pattern KHR_SWAPCHAIN_SPEC_VERSION :: forall a . Integral a => a pattern KHR_SWAPCHAIN_SPEC_VERSION = 70 type KHR_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_swapchain" -- No documentation found for TopLevel "VK_KHR_SWAPCHAIN_EXTENSION_NAME" pattern KHR_SWAPCHAIN_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_swapchain"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_KHR_swapchain.hs
Haskell
bsd-3-clause
179,999
module Text.Highlighter.Lexers.Boo (lexer) where import Text.Regex.PCRE.Light import Text.Highlighter.Types lexer :: Lexer lexer = Lexer { lName = "Boo" , lAliases = ["boo"] , lExtensions = [".boo"] , lMimetypes = ["text/x-boo"] , lStart = root' , lFlags = [multiline] } comment' :: TokenMatcher comment' = [ tokNext "/[*]" (Arbitrary "Comment" :. Arbitrary "Multiline") Push , tokNext "[*]/" (Arbitrary "Comment" :. Arbitrary "Multiline") Pop , tok "[^/*]" (Arbitrary "Comment" :. Arbitrary "Multiline") , tok "[*/]" (Arbitrary "Comment" :. Arbitrary "Multiline") ] classname' :: TokenMatcher classname' = [ tokNext "[a-zA-Z_][a-zA-Z0-9_]*" (Arbitrary "Name" :. Arbitrary "Class") Pop ] namespace' :: TokenMatcher namespace' = [ tokNext "[a-zA-Z_][a-zA-Z0-9_.]*" (Arbitrary "Name" :. Arbitrary "Namespace") Pop ] root' :: TokenMatcher root' = [ tok "\\s+" (Arbitrary "Text") , tok "(#|//).*$" (Arbitrary "Comment" :. Arbitrary "Single") , tokNext "/[*]" (Arbitrary "Comment" :. Arbitrary "Multiline") (GoTo comment') , tok "[]{}:(),.;[]" (Arbitrary "Punctuation") , tok "\\\\\\n" (Arbitrary "Text") , tok "\\\\" (Arbitrary "Text") , tok "(in|is|and|or|not)\\b" (Arbitrary "Operator" :. Arbitrary "Word") , tok "/(\\\\\\\\|\\\\/|[^/\\s])/" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Regex") , tok "@/(\\\\\\\\|\\\\/|[^/])*/" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Regex") , tok "=\126|!=|==|<<|>>|[-+/*%=<>&^|]" (Arbitrary "Operator") , tok "(as|abstract|callable|constructor|destructor|do|import|enum|event|final|get|interface|internal|of|override|partial|private|protected|public|return|set|static|struct|transient|virtual|yield|super|and|break|cast|continue|elif|else|ensure|except|for|given|goto|if|in|is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|while|from|as)\\b" (Arbitrary "Keyword") , tok "def(?=\\s+\\(.*?\\))" (Arbitrary "Keyword") , tokNext "(def)(\\s+)" (ByGroups [(Arbitrary "Keyword"), (Arbitrary "Text")]) (GoTo funcname') , tokNext "(class)(\\s+)" (ByGroups [(Arbitrary "Keyword"), (Arbitrary "Text")]) (GoTo classname') , tokNext "(namespace)(\\s+)" (ByGroups [(Arbitrary "Keyword"), (Arbitrary "Text")]) (GoTo namespace') , tok "(?<!\\.)(true|false|null|self|__eval__|__switch__|array|assert|checked|enumerate|filter|getter|len|lock|map|matrix|max|min|normalArrayIndexing|print|property|range|rawArrayIndexing|required|typeof|unchecked|using|yieldAll|zip)\\b" (Arbitrary "Name" :. Arbitrary "Builtin") , tok "\"\"\"(\\\\|\\\"|.*?)\"\"\"" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Double") , tok "\"(\\\\|\\\"|[^\"]*?)\"" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Double") , tok "'(\\\\|\\'|[^']*?)'" (Arbitrary "Literal" :. Arbitrary "String" :. Arbitrary "Single") , tok "[a-zA-Z_][a-zA-Z0-9_]*" (Arbitrary "Name") , tok "(\\d+\\.\\d*|\\d*\\.\\d+)([fF][+-]?[0-9]+)?" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Float") , tok "[0-9][0-9\\.]*(m|ms|d|h|s)" (Arbitrary "Literal" :. Arbitrary "Number") , tok "0\\d+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Oct") , tok "0x[a-fA-F0-9]+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Hex") , tok "\\d+L" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Integer" :. Arbitrary "Long") , tok "\\d+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Integer") ] funcname' :: TokenMatcher funcname' = [ tokNext "[a-zA-Z_][a-zA-Z0-9_]*" (Arbitrary "Name" :. Arbitrary "Function") Pop ]
chemist/highlighter
src/Text/Highlighter/Lexers/Boo.hs
Haskell
bsd-3-clause
3,659
{-# LANGUAGE ForeignFunctionInterface #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Elem.LAPACK.Double -- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu> -- License : BSD3 -- Maintainer : Patrick Perry <patperry@stanford.edu> -- Stability : experimental -- module Data.Elem.LAPACK.Double where import Foreign( Ptr ) import LAPACK.CTypes foreign import ccall unsafe "LAPACK.h lapack_dgeqrf" dgeqrf :: Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dgelqf" dgelqf :: Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dormqr" dormqr :: CBLASSide -> CBLASTrans -> Int -> Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dormlq" dormlq :: CBLASSide -> CBLASTrans -> Int -> Int -> Int -> Ptr Double -> Int -> Ptr Double -> Ptr Double -> Int -> Ptr Double -> Int -> IO Int foreign import ccall unsafe "LAPACK.h lapack_dlarfg" dlarfg :: Int -> Ptr Double -> Ptr Double -> Int -> Ptr Double -> IO ()
patperry/lapack
lib/Data/Elem/LAPACK/Double.hs
Haskell
bsd-3-clause
1,270
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- module Feldspar.Core.Constructs.Integral ( INTEGRAL (..) ) where import Data.Bits import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Condition import Feldspar.Range import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Bits import Feldspar.Core.Constructs.Eq import Feldspar.Core.Constructs.Ord import Feldspar.Core.Constructs.Logic import Feldspar.Core.Constructs.Complex data INTEGRAL a where Quot :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Rem :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Div :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Mod :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) Exp :: (Type a, BoundedInt a, Size a ~ Range a) => INTEGRAL (a :-> a :-> Full a) instance Semantic INTEGRAL where semantics Quot = Sem "quot" quot semantics Rem = Sem "rem" rem semantics Div = Sem "div" div semantics Mod = Sem "mod" mod semantics Exp = Sem "(^)" (^) semanticInstances ''INTEGRAL instance EvalBind INTEGRAL where evalBindSym = evalBindSymDefault instance AlphaEq dom dom dom env => AlphaEq INTEGRAL INTEGRAL dom env where alphaEqSym = alphaEqSymDefault instance Sharable INTEGRAL instance Cumulative INTEGRAL instance SizeProp (INTEGRAL :|| Type) where sizeProp (C' Quot) (WrapFull a :* WrapFull b :* Nil) = rangeQuot (infoSize a) (infoSize b) sizeProp (C' Rem) (WrapFull a :* WrapFull b :* Nil) = rangeRem (infoSize a) (infoSize b) sizeProp (C' Div) (WrapFull a :* WrapFull b :* Nil) = rangeDiv (infoSize a) (infoSize b) sizeProp (C' Mod) (WrapFull a :* WrapFull b :* Nil) = rangeMod (infoSize a) (infoSize b) sizeProp (C' Exp) (WrapFull a :* WrapFull b :* Nil) = rangeExp (infoSize a) (infoSize b) instance ( (INTEGRAL :||Type) :<: dom , (BITS :||Type) :<: dom , (EQ :||Type) :<: dom , (ORD :||Type) :<: dom , (COMPLEX :|| Type) :<: dom , (Condition :||Type) :<: dom , (Logic :||Type) :<: dom , Cumulative dom , OptimizeSuper dom , Optimize (Condition :|| Type) dom ) => Optimize (INTEGRAL :|| Type) dom where constructFeatOpt _ (C' Quot) (a :* b :* Nil) | Just 1 <- viewLiteral b = return a {- -- TODO: Rule disabled because of cyclic imports. constructFeatOpt opts (C' Quot) (a :* b :* Nil) | Just b' <- viewLiteral b , b' > 0 , isPowerOfTwo b' , let l = log2 b' , let lLit = literalDecor l = if isNatural $ infoSize $ getInfo a then constructFeat opts (c' ShiftR) (a :* lLit :* Nil) else do aIsNeg <- constructFeat opts (c' LTH) (a :* literalDecor 0 :* Nil) a' <- constructFeat opts (c' Add) (a :* literalDecor (2^l-1) :* Nil) negCase <- constructFeat opts (c' ShiftR) (a' :* lLit :* Nil) posCase <- constructFeat opts (c' ShiftR) (a :* lLit :* Nil) constructFeat opts (c' Condition) (aIsNeg :* negCase :* posCase :* Nil) -- TODO This rule should also fire when `b` is `2^l` but not a literal. -- TODO Make a case for `isNegative $ infoSize $ getInfo a`. Note that -- `isNegative /= (not . isNatural)` -- TODO Or maybe both `isNegative` and `isPositive` are handled by the -- size-based optimization of `Condition`? -} constructFeatOpt _ (C' Rem) (a :* b :* Nil) | rangeLess sza szb , isNatural sza = return a where sza = infoSize $ getInfo a szb = infoSize $ getInfo b constructFeatOpt _ (C' Div) (a :* b :* Nil) | Just 1 <- viewLiteral b = return a constructFeatOpt opts (C' Div) (a :* b :* Nil) | IntType U _ <- infoType $ getInfo a , Just b' <- viewLiteral b , b' > 0 , isPowerOfTwo b' = constructFeat opts (c' ShiftRU) (a :* literalDecor (log2 b') :* Nil) constructFeatOpt opts (C' Div) (a :* b :* Nil) | sameSign (infoSize (getInfo a)) (infoSize (getInfo b)) = constructFeat opts (c' Quot) (a :* b :* Nil) constructFeatOpt _ (C' Mod) (a :* b :* Nil) | rangeLess sza szb , isNatural sza = return a where sza = infoSize $ getInfo a szb = infoSize $ getInfo b constructFeatOpt opts (C' Mod) (a :* b :* Nil) | sameSign (infoSize (getInfo a)) (infoSize (getInfo b)) = constructFeat opts (c' Rem) (a :* b :* Nil) constructFeatOpt _ (C' Exp) (a :* b :* Nil) | Just 1 <- viewLiteral a = return $ literalDecor 1 | Just 0 <- viewLiteral a = return $ literalDecor 0 | Just 1 <- viewLiteral b = return a | Just 0 <- viewLiteral b = return $ literalDecor 1 constructFeatOpt opts (C' Exp) (a :* b :* Nil) | Just (-1) <- viewLiteral a = do bLSB <- constructFeat opts (c' BAnd) (b :* literalDecor 1 :* Nil) bIsEven <- constructFeat opts (c' Equal) (bLSB :* literalDecor 0 :* Nil) -- TODO Use testBit? (remove EQ :<: dom and import) constructFeat opts (c' Condition) (bIsEven :* literalDecor 1 :* literalDecor (-1) :* Nil) constructFeatOpt opts a args = constructFeatUnOpt opts a args constructFeatUnOpt opts x@(C' _) = constructFeatUnOptDefault opts x -- Auxiliary functions -- shouldn't be used for negative numbers isPowerOfTwo :: (Num a, Bits a) => a -> Bool isPowerOfTwo x = x .&. (x - 1) == 0 && (x /= 0) log2 :: (BoundedInt a, Integral b) => a -> b log2 v | v <= 1 = 0 log2 v = 1 + log2 (shiftR v 1) sameSign :: BoundedInt a => Range a -> Range a -> Bool sameSign ra rb = isNatural ra && isNatural rb || isNegative ra && isNegative rb
emwap/feldspar-language
src/Feldspar/Core/Constructs/Integral.hs
Haskell
bsd-3-clause
7,822
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Rank2Types #-} module Hmlk.DataSet where import Debug.Trace import Data.IntMap (IntMap, fromList, elems, size, toList) import Data.Monoid import Data.MultiSet (findMax, insert, empty) import Data.List (maximumBy, elemIndex) import Data.Function (on) import Control.Lens hiding (rmap) import Control.Monad import Control.Monad.Trans.State import Control.Monad.Trans.Class data Attribute = Missing | Numeric Double | Nominal String | Boolean Bool deriving (Eq, Show, Ord) data Row = Row {_attributes :: [Attribute], _names :: [String]} deriving (Show) data DataSet = DataSet {_rows :: IntMap [Attribute], _names' :: [String]} makeLenses ''Row rows :: Lens' DataSet [Row] rows = lens getter (const buildRows) where getter ds = map (\x -> Row {_attributes = x, _names = _names' ds}) . elems . _rows $ ds buildRows rs = DataSet {_rows = fromList . zip [1..] . map _attributes $ rs, _names' = maybeNames rs} where maybeNames [] = [] maybeNames rs = _names . head $ rs instance Monoid Row where Row {_attributes = a1, _names = n1} `mappend` Row {_attributes = a2, _names = n2} = Row {_attributes = a1 ++ a2, _names = n1 ++ n2} mempty = Row {_attributes = [], _names = []} rmap :: (String -> Attribute -> a) -> Row -> [a] rmap f r = zipWith f (r ^. names) (r ^. attributes) namedNominals :: Row -> [(String, String)] namedNominals = map (\(x, Nominal n) -> (x, n)) . filter (isNominal . snd) . rmap (,) attr :: String -> Lens' Row Attribute attr s = lens getter setter where getter Row {_attributes = a, _names = n} = case s `elemIndex` n of Just i -> a !! i Nothing -> error "Attribute doesn't exist" setter (Row {_attributes = a, _names = n}) x = case s `elemIndex` n of Just i -> (Row {_names = n, _attributes = (a & (element i) .~ x)}) Nothing -> error "Attribute doesn't exist" dropCols :: DataSet -> (String -> Bool) -> DataSet dropCols ds f = ds & rows .~ newRows where newRows = map dropCols' (ds ^. rows) dropCols' row = row & names .~ n & attributes .~ a where a = filterW c $ row ^. attributes n = filterW c $ _names' ds c = map (\x -> not $ f x) $ _names' ds filterW :: [Bool] -> [a] -> [a] filterW ps xs = [x | (x, p) <- zip xs ps, p] numeric :: String -> Lens' Row Double numeric s = lens getter setter where getter r = case r ^. attr s of Numeric n -> n _ -> 0 setter r x = case r ^. attr s of Numeric n -> r & attr s .~ Numeric x _ -> r nominal :: String -> Lens' Row String nominal s = lens getter setter where getter r = case r ^. attr s of Nominal n -> n _ -> "" setter r x = case r ^. attr s of Nominal n -> r & attr s .~ Nominal x _ -> r addAttr :: String -> (Row -> Attribute) -> Row -> Row addAttr name f r = r & attributes <>~ [(f r)] & names <>~ [name] rmAttr :: String -> Row -> Row rmAttr name r = r & attributes %~ remove & names %~ remove where i = case name `elemIndex` (r ^. names) of Just i -> i + 1 Nothing -> error $ "Attribute " ++ name ++ " does not exist" remove l = [x | (j, x) <- zip [1..] l, j /= i] instance Show DataSet where show d@DataSet {_rows = r, _names' = n} | size r > 20 = header ++ "\n(too many rows too show: " ++ (show $ size r) ++ " - use \"dumpData\" to see them)" | otherwise = dumpData' d where paddingSize = 16 --fixme padding x = (replicate (paddingSize - length x + 1) ' ') ++ x ++ " |" header = unwords . map padding $ n dumpData' DataSet {_rows = r, _names' = n} = unlines $ header:(replicate (length header) '-'):datas where paddingSize = 16 --fixme padding x = (replicate (paddingSize - length x + 1) ' ') ++ x ++ " |" header = unwords . map padding $ n datas = [unwords . map (padding . showAttribute) $ x | (_, x) <- toList r] showAttribute (Numeric n) = show n showAttribute (Nominal n) = n showAttribute (Boolean n) = show n showAttribute Missing = "?" dumpData ds = putStrLn $ dumpData' ds numericsOf :: DataSet -> [[Double]] numericsOf ds = map (map strip . filter isNumeric) (ds ^.. rows . traverse . attributes) where strip (Numeric n) = n nominalsOf :: DataSet -> [[String]] nominalsOf ds = map (map strip . filter isNominal) (ds ^.. rows . traverse . attributes) where strip (Nominal n) = n isNumeric :: Attribute -> Bool isNumeric (Numeric n) = True isNumeric _ = False isNominal :: Attribute -> Bool isNominal (Nominal n) = True isNominal _ = False isMissing :: Attribute -> Bool isMissing Missing = True isMissing _ = False
rednum/hmlk
Hmlk/DataSet.hs
Haskell
bsd-3-clause
4,739
{-# LANGUAGE CPP, ScopedTypeVariables, MagicHash, UnboxedTuples #-} ----------------------------------------------------------------------------- -- -- GHC Interactive support for inspecting arbitrary closures at runtime -- -- Pepe Iborra (supported by Google SoC) 2006 -- ----------------------------------------------------------------------------- module RtClosureInspect( cvObtainTerm, -- :: HscEnv -> Int -> Bool -> Maybe Type -> HValue -> IO Term cvReconstructType, improveRTTIType, Term(..), isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap, isFullyEvaluated, isFullyEvaluatedTerm, termType, mapTermType, termTyVars, foldTerm, TermFold(..), foldTermM, TermFoldM(..), idTermFold, pprTerm, cPprTerm, cPprTermBase, CustomTermPrinter, -- unsafeDeepSeq, Closure(..), getClosureData, ClosureType(..), isConstr, isIndirection ) where #include "HsVersions.h" import DebuggerUtils import ByteCodeItbls ( StgInfoTable, peekItbl ) import qualified ByteCodeItbls as BCI( StgInfoTable(..) ) import BasicTypes ( HValue ) import HscTypes import DataCon import Type import qualified Unify as U import Var import TcRnMonad import TcType import TcMType import TcHsSyn ( zonkTcTypeToType, mkEmptyZonkEnv ) import TcUnify import TcEnv import TyCon import Name import VarEnv import Util import VarSet import BasicTypes ( TupleSort(UnboxedTuple) ) import TysPrim import PrelNames import TysWiredIn import DynFlags import Outputable as Ppr import GHC.Arr ( Array(..) ) import GHC.Exts import GHC.IO ( IO(..) ) import StaticFlags( opt_PprStyle_Debug ) import Control.Monad import Data.Maybe import Data.Array.Base import Data.Ix import Data.List import qualified Data.Sequence as Seq #if __GLASGOW_HASKELL__ < 709 import Data.Monoid (mappend) #endif import Data.Sequence (viewl, ViewL(..)) import Foreign.Safe import System.IO.Unsafe --------------------------------------------- -- * A representation of semi evaluated Terms --------------------------------------------- data Term = Term { ty :: RttiType , dc :: Either String DataCon -- Carries a text representation if the datacon is -- not exported by the .hi file, which is the case -- for private constructors in -O0 compiled libraries , val :: HValue , subTerms :: [Term] } | Prim { ty :: RttiType , value :: [Word] } | Suspension { ctype :: ClosureType , ty :: RttiType , val :: HValue , bound_to :: Maybe Name -- Useful for printing } | NewtypeWrap{ -- At runtime there are no newtypes, and hence no -- newtype constructors. A NewtypeWrap is just a -- made-up tag saying "heads up, there used to be -- a newtype constructor here". ty :: RttiType , dc :: Either String DataCon , wrapped_term :: Term } | RefWrap { -- The contents of a reference ty :: RttiType , wrapped_term :: Term } isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap :: Term -> Bool isTerm Term{} = True isTerm _ = False isSuspension Suspension{} = True isSuspension _ = False isPrim Prim{} = True isPrim _ = False isNewtypeWrap NewtypeWrap{} = True isNewtypeWrap _ = False isFun Suspension{ctype=Fun} = True isFun _ = False isFunLike s@Suspension{ty=ty} = isFun s || isFunTy ty isFunLike _ = False termType :: Term -> RttiType termType t = ty t isFullyEvaluatedTerm :: Term -> Bool isFullyEvaluatedTerm Term {subTerms=tt} = all isFullyEvaluatedTerm tt isFullyEvaluatedTerm Prim {} = True isFullyEvaluatedTerm NewtypeWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm RefWrap{wrapped_term=t} = isFullyEvaluatedTerm t isFullyEvaluatedTerm _ = False instance Outputable (Term) where ppr t | Just doc <- cPprTerm cPprTermBase t = doc | otherwise = panic "Outputable Term instance" ------------------------------------------------------------------------- -- Runtime Closure Datatype and functions for retrieving closure related stuff ------------------------------------------------------------------------- data ClosureType = Constr | Fun | Thunk Int | ThunkSelector | Blackhole | AP | PAP | Indirection Int | MutVar Int | MVar Int | Other Int deriving (Show, Eq) data Closure = Closure { tipe :: ClosureType , infoPtr :: Ptr () , infoTable :: StgInfoTable , ptrs :: Array Int HValue , nonPtrs :: [Word] } instance Outputable ClosureType where ppr = text . show #include "../includes/rts/storage/ClosureTypes.h" aP_CODE, pAP_CODE :: Int aP_CODE = AP pAP_CODE = PAP #undef AP #undef PAP getClosureData :: DynFlags -> a -> IO Closure getClosureData dflags a = case unpackClosure# a of (# iptr, ptrs, nptrs #) -> do let iptr' | ghciTablesNextToCode = Ptr iptr | otherwise = -- the info pointer we get back from unpackClosure# -- is to the beginning of the standard info table, -- but the Storable instance for info tables takes -- into account the extra entry pointer when -- !ghciTablesNextToCode, so we must adjust here: Ptr iptr `plusPtr` negate (wORD_SIZE dflags) itbl <- peekItbl dflags iptr' let tipe = readCType (BCI.tipe itbl) elems = fromIntegral (BCI.ptrs itbl) ptrsList = Array 0 (elems - 1) elems ptrs nptrs_data = [W# (indexWordArray# nptrs i) | I# i <- [0.. fromIntegral (BCI.nptrs itbl)-1] ] ASSERT(elems >= 0) return () ptrsList `seq` return (Closure tipe (Ptr iptr) itbl ptrsList nptrs_data) readCType :: Integral a => a -> ClosureType readCType i | i >= CONSTR && i <= CONSTR_NOCAF_STATIC = Constr | i >= FUN && i <= FUN_STATIC = Fun | i >= THUNK && i < THUNK_SELECTOR = Thunk i' | i == THUNK_SELECTOR = ThunkSelector | i == BLACKHOLE = Blackhole | i >= IND && i <= IND_STATIC = Indirection i' | i' == aP_CODE = AP | i == AP_STACK = AP | i' == pAP_CODE = PAP | i == MUT_VAR_CLEAN || i == MUT_VAR_DIRTY= MutVar i' | i == MVAR_CLEAN || i == MVAR_DIRTY = MVar i' | otherwise = Other i' where i' = fromIntegral i isConstr, isIndirection, isThunk :: ClosureType -> Bool isConstr Constr = True isConstr _ = False isIndirection (Indirection _) = True isIndirection _ = False isThunk (Thunk _) = True isThunk ThunkSelector = True isThunk AP = True isThunk _ = False isFullyEvaluated :: DynFlags -> a -> IO Bool isFullyEvaluated dflags a = do closure <- getClosureData dflags a case tipe closure of Constr -> do are_subs_evaluated <- amapM (isFullyEvaluated dflags) (ptrs closure) return$ and are_subs_evaluated _ -> return False where amapM f = sequence . amap' f -- TODO: Fix it. Probably the otherwise case is failing, trace/debug it {- unsafeDeepSeq :: a -> b -> b unsafeDeepSeq = unsafeDeepSeq1 2 where unsafeDeepSeq1 0 a b = seq a $! b unsafeDeepSeq1 i a b -- 1st case avoids infinite loops for non reducible thunks | not (isConstr tipe) = seq a $! unsafeDeepSeq1 (i-1) a b -- | unsafePerformIO (isFullyEvaluated a) = b | otherwise = case unsafePerformIO (getClosureData a) of closure -> foldl' (flip unsafeDeepSeq) b (ptrs closure) where tipe = unsafePerformIO (getClosureType a) -} ----------------------------------- -- * Traversals for Terms ----------------------------------- type TermProcessor a b = RttiType -> Either String DataCon -> HValue -> [a] -> b data TermFold a = TermFold { fTerm :: TermProcessor a a , fPrim :: RttiType -> [Word] -> a , fSuspension :: ClosureType -> RttiType -> HValue -> Maybe Name -> a , fNewtypeWrap :: RttiType -> Either String DataCon -> a -> a , fRefWrap :: RttiType -> a -> a } data TermFoldM m a = TermFoldM {fTermM :: TermProcessor a (m a) , fPrimM :: RttiType -> [Word] -> m a , fSuspensionM :: ClosureType -> RttiType -> HValue -> Maybe Name -> m a , fNewtypeWrapM :: RttiType -> Either String DataCon -> a -> m a , fRefWrapM :: RttiType -> a -> m a } foldTerm :: TermFold a -> Term -> a foldTerm tf (Term ty dc v tt) = fTerm tf ty dc v (map (foldTerm tf) tt) foldTerm tf (Prim ty v ) = fPrim tf ty v foldTerm tf (Suspension ct ty v b) = fSuspension tf ct ty v b foldTerm tf (NewtypeWrap ty dc t) = fNewtypeWrap tf ty dc (foldTerm tf t) foldTerm tf (RefWrap ty t) = fRefWrap tf ty (foldTerm tf t) foldTermM :: Monad m => TermFoldM m a -> Term -> m a foldTermM tf (Term ty dc v tt) = mapM (foldTermM tf) tt >>= fTermM tf ty dc v foldTermM tf (Prim ty v ) = fPrimM tf ty v foldTermM tf (Suspension ct ty v b) = fSuspensionM tf ct ty v b foldTermM tf (NewtypeWrap ty dc t) = foldTermM tf t >>= fNewtypeWrapM tf ty dc foldTermM tf (RefWrap ty t) = foldTermM tf t >>= fRefWrapM tf ty idTermFold :: TermFold Term idTermFold = TermFold { fTerm = Term, fPrim = Prim, fSuspension = Suspension, fNewtypeWrap = NewtypeWrap, fRefWrap = RefWrap } mapTermType :: (RttiType -> Type) -> Term -> Term mapTermType f = foldTerm idTermFold { fTerm = \ty dc hval tt -> Term (f ty) dc hval tt, fSuspension = \ct ty hval n -> Suspension ct (f ty) hval n, fNewtypeWrap= \ty dc t -> NewtypeWrap (f ty) dc t, fRefWrap = \ty t -> RefWrap (f ty) t} mapTermTypeM :: Monad m => (RttiType -> m Type) -> Term -> m Term mapTermTypeM f = foldTermM TermFoldM { fTermM = \ty dc hval tt -> f ty >>= \ty' -> return $ Term ty' dc hval tt, fPrimM = (return.) . Prim, fSuspensionM = \ct ty hval n -> f ty >>= \ty' -> return $ Suspension ct ty' hval n, fNewtypeWrapM= \ty dc t -> f ty >>= \ty' -> return $ NewtypeWrap ty' dc t, fRefWrapM = \ty t -> f ty >>= \ty' -> return $ RefWrap ty' t} termTyVars :: Term -> TyVarSet termTyVars = foldTerm TermFold { fTerm = \ty _ _ tt -> tyVarsOfType ty `plusVarEnv` concatVarEnv tt, fSuspension = \_ ty _ _ -> tyVarsOfType ty, fPrim = \ _ _ -> emptyVarEnv, fNewtypeWrap= \ty _ t -> tyVarsOfType ty `plusVarEnv` t, fRefWrap = \ty t -> tyVarsOfType ty `plusVarEnv` t} where concatVarEnv = foldr plusVarEnv emptyVarEnv ---------------------------------- -- Pretty printing of terms ---------------------------------- type Precedence = Int type TermPrinter = Precedence -> Term -> SDoc type TermPrinterM m = Precedence -> Term -> m SDoc app_prec,cons_prec, max_prec ::Int max_prec = 10 app_prec = max_prec cons_prec = 5 -- TODO Extract this info from GHC itself pprTerm :: TermPrinter -> TermPrinter pprTerm y p t | Just doc <- pprTermM (\p -> Just . y p) p t = doc pprTerm _ _ _ = panic "pprTerm" pprTermM, ppr_termM, pprNewtypeWrap :: Monad m => TermPrinterM m -> TermPrinterM m pprTermM y p t = pprDeeper `liftM` ppr_termM y p t ppr_termM y p Term{dc=Left dc_tag, subTerms=tt} = do tt_docs <- mapM (y app_prec) tt return $ cparen (not (null tt) && p >= app_prec) (text dc_tag <+> pprDeeperList fsep tt_docs) ppr_termM y p Term{dc=Right dc, subTerms=tt} {- | dataConIsInfix dc, (t1:t2:tt') <- tt --TODO fixity = parens (ppr_term1 True t1 <+> ppr dc <+> ppr_term1 True ppr t2) <+> hsep (map (ppr_term1 True) tt) -} -- TODO Printing infix constructors properly | null sub_terms_to_show = return (ppr dc) | otherwise = do { tt_docs <- mapM (y app_prec) sub_terms_to_show ; return $ cparen (p >= app_prec) $ sep [ppr dc, nest 2 (pprDeeperList fsep tt_docs)] } where sub_terms_to_show -- Don't show the dictionary arguments to -- constructors unless -dppr-debug is on | opt_PprStyle_Debug = tt | otherwise = dropList (dataConTheta dc) tt ppr_termM y p t@NewtypeWrap{} = pprNewtypeWrap y p t ppr_termM y p RefWrap{wrapped_term=t} = do contents <- y app_prec t return$ cparen (p >= app_prec) (text "GHC.Prim.MutVar#" <+> contents) -- The constructor name is wired in here ^^^ for the sake of simplicity. -- I don't think mutvars are going to change in a near future. -- In any case this is solely a presentation matter: MutVar# is -- a datatype with no constructors, implemented by the RTS -- (hence there is no way to obtain a datacon and print it). ppr_termM _ _ t = ppr_termM1 t ppr_termM1 :: Monad m => Term -> m SDoc ppr_termM1 Prim{value=words, ty=ty} = return $ repPrim (tyConAppTyCon ty) words ppr_termM1 Suspension{ty=ty, bound_to=Nothing} = return (char '_' <+> ifPprDebug (text "::" <> ppr ty)) ppr_termM1 Suspension{ty=ty, bound_to=Just n} -- | Just _ <- splitFunTy_maybe ty = return$ ptext (sLit("<function>") | otherwise = return$ parens$ ppr n <> text "::" <> ppr ty ppr_termM1 Term{} = panic "ppr_termM1 - Term" ppr_termM1 RefWrap{} = panic "ppr_termM1 - RefWrap" ppr_termM1 NewtypeWrap{} = panic "ppr_termM1 - NewtypeWrap" pprNewtypeWrap y p NewtypeWrap{ty=ty, wrapped_term=t} | Just (tc,_) <- tcSplitTyConApp_maybe ty , ASSERT(isNewTyCon tc) True , Just new_dc <- tyConSingleDataCon_maybe tc = do real_term <- y max_prec t return $ cparen (p >= app_prec) (ppr new_dc <+> real_term) pprNewtypeWrap _ _ _ = panic "pprNewtypeWrap" ------------------------------------------------------- -- Custom Term Pretty Printers ------------------------------------------------------- -- We can want to customize the representation of a -- term depending on its type. -- However, note that custom printers have to work with -- type representations, instead of directly with types. -- We cannot use type classes here, unless we employ some -- typerep trickery (e.g. Weirich's RepLib tricks), -- which I didn't. Therefore, this code replicates a lot -- of what type classes provide for free. type CustomTermPrinter m = TermPrinterM m -> [Precedence -> Term -> (m (Maybe SDoc))] -- | Takes a list of custom printers with a explicit recursion knot and a term, -- and returns the output of the first successful printer, or the default printer cPprTerm :: Monad m => CustomTermPrinter m -> Term -> m SDoc cPprTerm printers_ = go 0 where printers = printers_ go go prec t = do let default_ = Just `liftM` pprTermM go prec t mb_customDocs = [pp prec t | pp <- printers] ++ [default_] Just doc <- firstJustM mb_customDocs return$ cparen (prec>app_prec+1) doc firstJustM (mb:mbs) = mb >>= maybe (firstJustM mbs) (return . Just) firstJustM [] = return Nothing -- Default set of custom printers. Note that the recursion knot is explicit cPprTermBase :: forall m. Monad m => CustomTermPrinter m cPprTermBase y = [ ifTerm (isTupleTy.ty) (\_p -> liftM (parens . hcat . punctuate comma) . mapM (y (-1)) . subTerms) , ifTerm (\t -> isTyCon listTyCon (ty t) && subTerms t `lengthIs` 2) ppr_list , ifTerm (isTyCon intTyCon . ty) ppr_int , ifTerm (isTyCon charTyCon . ty) ppr_char , ifTerm (isTyCon floatTyCon . ty) ppr_float , ifTerm (isTyCon doubleTyCon . ty) ppr_double , ifTerm (isIntegerTy . ty) ppr_integer ] where ifTerm :: (Term -> Bool) -> (Precedence -> Term -> m SDoc) -> Precedence -> Term -> m (Maybe SDoc) ifTerm pred f prec t@Term{} | pred t = Just `liftM` f prec t ifTerm _ _ _ _ = return Nothing isTupleTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (isBoxedTupleTyCon tc) isTyCon a_tc ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (a_tc == tc) isIntegerTy ty = fromMaybe False $ do (tc,_) <- tcSplitTyConApp_maybe ty return (tyConName tc == integerTyConName) ppr_int, ppr_char, ppr_float, ppr_double, ppr_integer :: Precedence -> Term -> m SDoc ppr_int _ v = return (Ppr.int (unsafeCoerce# (val v))) ppr_char _ v = return (Ppr.char '\'' <> Ppr.char (unsafeCoerce# (val v)) <> Ppr.char '\'') ppr_float _ v = return (Ppr.float (unsafeCoerce# (val v))) ppr_double _ v = return (Ppr.double (unsafeCoerce# (val v))) ppr_integer _ v = return (Ppr.integer (unsafeCoerce# (val v))) --Note pprinting of list terms is not lazy ppr_list :: Precedence -> Term -> m SDoc ppr_list p (Term{subTerms=[h,t]}) = do let elems = h : getListTerms t isConsLast = not(termType(last elems) `eqType` termType h) is_string = all (isCharTy . ty) elems print_elems <- mapM (y cons_prec) elems if is_string then return (Ppr.doubleQuotes (Ppr.text (unsafeCoerce# (map val elems)))) else if isConsLast then return $ cparen (p >= cons_prec) $ pprDeeperList fsep $ punctuate (space<>colon) print_elems else return $ brackets $ pprDeeperList fcat $ punctuate comma print_elems where getListTerms Term{subTerms=[h,t]} = h : getListTerms t getListTerms Term{subTerms=[]} = [] getListTerms t@Suspension{} = [t] getListTerms t = pprPanic "getListTerms" (ppr t) ppr_list _ _ = panic "doList" repPrim :: TyCon -> [Word] -> SDoc repPrim t = rep where rep x | t == charPrimTyCon = text $ show (build x :: Char) | t == intPrimTyCon = text $ show (build x :: Int) | t == wordPrimTyCon = text $ show (build x :: Word) | t == floatPrimTyCon = text $ show (build x :: Float) | t == doublePrimTyCon = text $ show (build x :: Double) | t == int32PrimTyCon = text $ show (build x :: Int32) | t == word32PrimTyCon = text $ show (build x :: Word32) | t == int64PrimTyCon = text $ show (build x :: Int64) | t == word64PrimTyCon = text $ show (build x :: Word64) | t == addrPrimTyCon = text $ show (nullPtr `plusPtr` build x) | t == stablePtrPrimTyCon = text "<stablePtr>" | t == stableNamePrimTyCon = text "<stableName>" | t == statePrimTyCon = text "<statethread>" | t == proxyPrimTyCon = text "<proxy>" | t == realWorldTyCon = text "<realworld>" | t == threadIdPrimTyCon = text "<ThreadId>" | t == weakPrimTyCon = text "<Weak>" | t == arrayPrimTyCon = text "<array>" | t == smallArrayPrimTyCon = text "<smallArray>" | t == byteArrayPrimTyCon = text "<bytearray>" | t == mutableArrayPrimTyCon = text "<mutableArray>" | t == smallMutableArrayPrimTyCon = text "<smallMutableArray>" | t == mutableByteArrayPrimTyCon = text "<mutableByteArray>" | t == mutVarPrimTyCon = text "<mutVar>" | t == mVarPrimTyCon = text "<mVar>" | t == tVarPrimTyCon = text "<tVar>" | otherwise = char '<' <> ppr t <> char '>' where build ww = unsafePerformIO $ withArray ww (peek . castPtr) -- This ^^^ relies on the representation of Haskell heap values being -- the same as in a C array. ----------------------------------- -- Type Reconstruction ----------------------------------- {- Type Reconstruction is type inference done on heap closures. The algorithm walks the heap generating a set of equations, which are solved with syntactic unification. A type reconstruction equation looks like: <datacon reptype> = <actual heap contents> The full equation set is generated by traversing all the subterms, starting from a given term. The only difficult part is that newtypes are only found in the lhs of equations. Right hand sides are missing them. We can either (a) drop them from the lhs, or (b) reconstruct them in the rhs when possible. The function congruenceNewtypes takes a shot at (b) -} -- A (non-mutable) tau type containing -- existentially quantified tyvars. -- (since GHC type language currently does not support -- existentials, we leave these variables unquantified) type RttiType = Type -- An incomplete type as stored in GHCi: -- no polymorphism: no quantifiers & all tyvars are skolem. type GhciType = Type -- The Type Reconstruction monad -------------------------------- type TR a = TcM a runTR :: HscEnv -> TR a -> IO a runTR hsc_env thing = do mb_val <- runTR_maybe hsc_env thing case mb_val of Nothing -> error "unable to :print the term" Just x -> return x runTR_maybe :: HscEnv -> TR a -> IO (Maybe a) runTR_maybe hsc_env thing_inside = do { (_errs, res) <- initTc hsc_env HsSrcFile False (icInteractiveModule (hsc_IC hsc_env)) thing_inside ; return res } traceTR :: SDoc -> TR () traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti -- Semantically different to recoverM in TcRnMonad -- recoverM retains the errors in the first action, -- whereas recoverTc here does not recoverTR :: TR a -> TR a -> TR a recoverTR recover thing = do (_,mb_res) <- tryTcErrs thing case mb_res of Nothing -> recover Just res -> return res trIO :: IO a -> TR a trIO = liftTcM . liftIO liftTcM :: TcM a -> TR a liftTcM = id newVar :: Kind -> TR TcType newVar = liftTcM . newFlexiTyVarTy instTyVars :: [TyVar] -> TR ([TcTyVar], [TcType], TvSubst) -- Instantiate fresh mutable type variables from some TyVars -- This function preserves the print-name, which helps error messages instTyVars = liftTcM . tcInstTyVars type RttiInstantiation = [(TcTyVar, TyVar)] -- Associates the typechecker-world meta type variables -- (which are mutable and may be refined), to their -- debugger-world RuntimeUnk counterparts. -- If the TcTyVar has not been refined by the runtime type -- elaboration, then we want to turn it back into the -- original RuntimeUnk -- | Returns the instantiated type scheme ty', and the -- mapping from new (instantiated) -to- old (skolem) type variables instScheme :: QuantifiedType -> TR (TcType, RttiInstantiation) instScheme (tvs, ty) = liftTcM $ do { (tvs', _, subst) <- tcInstTyVars tvs ; let rtti_inst = [(tv',tv) | (tv',tv) <- tvs' `zip` tvs] ; return (substTy subst ty, rtti_inst) } applyRevSubst :: RttiInstantiation -> TR () -- Apply the *reverse* substitution in-place to any un-filled-in -- meta tyvars. This recovers the original debugger-world variable -- unless it has been refined by new information from the heap applyRevSubst pairs = liftTcM (mapM_ do_pair pairs) where do_pair (tc_tv, rtti_tv) = do { tc_ty <- zonkTcTyVar tc_tv ; case tcGetTyVar_maybe tc_ty of Just tv | isMetaTyVar tv -> writeMetaTyVar tv (mkTyVarTy rtti_tv) _ -> return () } -- Adds a constraint of the form t1 == t2 -- t1 is expected to come from walking the heap -- t2 is expected to come from a datacon signature -- Before unification, congruenceNewtypes needs to -- do its magic. addConstraint :: TcType -> TcType -> TR () addConstraint actual expected = do traceTR (text "add constraint:" <+> fsep [ppr actual, equals, ppr expected]) recoverTR (traceTR $ fsep [text "Failed to unify", ppr actual, text "with", ppr expected]) $ do { (ty1, ty2) <- congruenceNewtypes actual expected ; _ <- captureConstraints $ unifyType ty1 ty2 ; return () } -- TOMDO: what about the coercion? -- we should consider family instances -- Type & Term reconstruction ------------------------------ cvObtainTerm :: HscEnv -> Int -> Bool -> RttiType -> HValue -> IO Term cvObtainTerm hsc_env max_depth force old_ty hval = runTR hsc_env $ do -- we quantify existential tyvars as universal, -- as this is needed to be able to manipulate -- them properly let quant_old_ty@(old_tvs, old_tau) = quantifyType old_ty sigma_old_ty = mkForAllTys old_tvs old_tau traceTR (text "Term reconstruction started with initial type " <> ppr old_ty) term <- if null old_tvs then do term <- go max_depth sigma_old_ty sigma_old_ty hval term' <- zonkTerm term return $ fixFunDictionaries $ expandNewtypes term' else do (old_ty', rev_subst) <- instScheme quant_old_ty my_ty <- newVar openTypeKind when (check1 quant_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') term <- go max_depth my_ty sigma_old_ty hval new_ty <- zonkTcType (termType term) if isMonomorphic new_ty || check2 (quantifyType new_ty) quant_old_ty then do traceTR (text "check2 passed") addConstraint new_ty old_ty' applyRevSubst rev_subst zterm' <- zonkTerm term return ((fixFunDictionaries . expandNewtypes) zterm') else do traceTR (text "check2 failed" <+> parens (ppr term <+> text "::" <+> ppr new_ty)) -- we have unsound types. Replace constructor types in -- subterms with tyvars zterm' <- mapTermTypeM (\ty -> case tcSplitTyConApp_maybe ty of Just (tc, _:_) | tc /= funTyCon -> newVar openTypeKind _ -> return ty) term zonkTerm zterm' traceTR (text "Term reconstruction completed." $$ text "Term obtained: " <> ppr term $$ text "Type obtained: " <> ppr (termType term)) return term where dflags = hsc_dflags hsc_env go :: Int -> Type -> Type -> HValue -> TcM Term -- I believe that my_ty should not have any enclosing -- foralls, nor any free RuntimeUnk skolems; -- that is partly what the quantifyType stuff achieved -- -- [SPJ May 11] I don't understand the difference between my_ty and old_ty go max_depth _ _ _ | seq max_depth False = undefined go 0 my_ty _old_ty a = do traceTR (text "Gave up reconstructing a term after" <> int max_depth <> text " steps") clos <- trIO $ getClosureData dflags a return (Suspension (tipe clos) my_ty a Nothing) go max_depth my_ty old_ty a = do let monomorphic = not(isTyVarTy my_ty) -- This ^^^ is a convention. The ancestor tests for -- monomorphism and passes a type instead of a tv clos <- trIO $ getClosureData dflags a case tipe clos of -- Thunks we may want to force t | isThunk t && force -> traceTR (text "Forcing a " <> text (show t)) >> seq a (go (pred max_depth) my_ty old_ty a) -- Blackholes are indirections iff the payload is not TSO or BLOCKING_QUEUE. So we -- treat them like indirections; if the payload is TSO or BLOCKING_QUEUE, we'll end up -- showing '_' which is what we want. Blackhole -> do traceTR (text "Following a BLACKHOLE") appArr (go max_depth my_ty old_ty) (ptrs clos) 0 -- We always follow indirections Indirection i -> do traceTR (text "Following an indirection" <> parens (int i) ) go max_depth my_ty old_ty $! (ptrs clos ! 0) -- We also follow references MutVar _ | Just (tycon,[world,contents_ty]) <- tcSplitTyConApp_maybe old_ty -> do -- Deal with the MutVar# primitive -- It does not have a constructor at all, -- so we simulate the following one -- MutVar# :: contents_ty -> MutVar# s contents_ty traceTR (text "Following a MutVar") contents_tv <- newVar liftedTypeKind contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w ASSERT(isUnliftedTypeKind $ typeKind my_ty) return () (mutvar_ty,_) <- instScheme $ quantifyType $ mkFunTy contents_ty (mkTyConApp tycon [world,contents_ty]) addConstraint (mkFunTy contents_tv my_ty) mutvar_ty x <- go (pred max_depth) contents_tv contents_ty contents return (RefWrap my_ty x) -- The interesting case Constr -> do traceTR (text "entering a constructor " <> if monomorphic then parens (text "already monomorphic: " <> ppr my_ty) else Ppr.empty) Right dcname <- dataConInfoPtrToName (infoPtr clos) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing -> do -- This can happen for private constructors compiled -O0 -- where the .hi descriptor does not export them -- In such case, we return a best approximation: -- ignore the unpointed args, and recover the pointeds -- This preserves laziness, and should be safe. traceTR (text "Not constructor" <+> ppr dcname) let dflags = hsc_dflags hsc_env tag = showPpr dflags dcname vars <- replicateM (length$ elems$ ptrs clos) (newVar liftedTypeKind) subTerms <- sequence [appArr (go (pred max_depth) tv tv) (ptrs clos) i | (i, tv) <- zip [0..] vars] return (Term my_ty (Left ('<' : tag ++ ">")) a subTerms) Just dc -> do traceTR (text "Is constructor" <+> (ppr dc $$ ppr my_ty)) subTtypes <- getDataConArgTys dc my_ty subTerms <- extractSubTerms (\ty -> go (pred max_depth) ty ty) clos subTtypes return (Term my_ty (Right dc) a subTerms) -- The otherwise case: can be a Thunk,AP,PAP,etc. tipe_clos -> return (Suspension tipe_clos my_ty a Nothing) -- insert NewtypeWraps around newtypes expandNewtypes = foldTerm idTermFold { fTerm = worker } where worker ty dc hval tt | Just (tc, args) <- tcSplitTyConApp_maybe ty , isNewTyCon tc , wrapped_type <- newTyConInstRhs tc args , Just dc' <- tyConSingleDataCon_maybe tc , t' <- worker wrapped_type dc hval tt = NewtypeWrap ty (Right dc') t' | otherwise = Term ty dc hval tt -- Avoid returning types where predicates have been expanded to dictionaries. fixFunDictionaries = foldTerm idTermFold {fSuspension = worker} where worker ct ty hval n | isFunTy ty = Suspension ct (dictsView ty) hval n | otherwise = Suspension ct ty hval n extractSubTerms :: (Type -> HValue -> TcM Term) -> Closure -> [Type] -> TcM [Term] extractSubTerms recurse clos = liftM thirdOf3 . go 0 (nonPtrs clos) where go ptr_i ws [] = return (ptr_i, ws, []) go ptr_i ws (ty:tys) | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = do (ptr_i, ws, terms0) <- go ptr_i ws elem_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) | otherwise = case repType ty of UnaryRep rep_ty -> do (ptr_i, ws, term0) <- go_rep ptr_i ws ty (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, term0 : terms1) UbxTupleRep rep_tys -> do (ptr_i, ws, terms0) <- go_unary_types ptr_i ws rep_tys (ptr_i, ws, terms1) <- go ptr_i ws tys return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1) go_unary_types ptr_i ws [] = return (ptr_i, ws, []) go_unary_types ptr_i ws (rep_ty:rep_tys) = do tv <- newVar liftedTypeKind (ptr_i, ws, term0) <- go_rep ptr_i ws tv (typePrimRep rep_ty) (ptr_i, ws, terms1) <- go_unary_types ptr_i ws rep_tys return (ptr_i, ws, term0 : terms1) go_rep ptr_i ws ty rep = case rep of PtrRep -> do t <- appArr (recurse ty) (ptrs clos) ptr_i return (ptr_i + 1, ws, t) _ -> do dflags <- getDynFlags let (ws0, ws1) = splitAt (primRepSizeW dflags rep) ws return (ptr_i, ws1, Prim ty ws0) unboxedTupleTerm ty terms = Term ty (Right (tupleCon UnboxedTuple (length terms))) (error "unboxedTupleTerm: no HValue for unboxed tuple") terms -- Fast, breadth-first Type reconstruction ------------------------------------------ cvReconstructType :: HscEnv -> Int -> GhciType -> HValue -> IO (Maybe Type) cvReconstructType hsc_env max_depth old_ty hval = runTR_maybe hsc_env $ do traceTR (text "RTTI started with initial type " <> ppr old_ty) let sigma_old_ty@(old_tvs, _) = quantifyType old_ty new_ty <- if null old_tvs then return old_ty else do (old_ty', rev_subst) <- instScheme sigma_old_ty my_ty <- newVar openTypeKind when (check1 sigma_old_ty) (traceTR (text "check1 passed") >> addConstraint my_ty old_ty') search (isMonomorphic `fmap` zonkTcType my_ty) (\(ty,a) -> go ty a) (Seq.singleton (my_ty, hval)) max_depth new_ty <- zonkTcType my_ty if isMonomorphic new_ty || check2 (quantifyType new_ty) sigma_old_ty then do traceTR (text "check2 passed" <+> ppr old_ty $$ ppr new_ty) addConstraint my_ty old_ty' applyRevSubst rev_subst zonkRttiType new_ty else traceTR (text "check2 failed" <+> parens (ppr new_ty)) >> return old_ty traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty) return new_ty where dflags = hsc_dflags hsc_env -- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m () search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <> int max_depth <> text " steps") search stop expand l d = case viewl l of EmptyL -> return () x :< xx -> unlessM stop $ do new <- expand x search stop expand (xx `mappend` Seq.fromList new) $! (pred d) -- returns unification tasks,since we are going to want a breadth-first search go :: Type -> HValue -> TR [(Type, HValue)] go my_ty a = do traceTR (text "go" <+> ppr my_ty) clos <- trIO $ getClosureData dflags a case tipe clos of Blackhole -> appArr (go my_ty) (ptrs clos) 0 -- carefully, don't eval the TSO Indirection _ -> go my_ty $! (ptrs clos ! 0) MutVar _ -> do contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w tv' <- newVar liftedTypeKind world <- newVar liftedTypeKind addConstraint my_ty (mkTyConApp mutVarPrimTyCon [world,tv']) return [(tv', contents)] Constr -> do Right dcname <- dataConInfoPtrToName (infoPtr clos) traceTR (text "Constr1" <+> ppr dcname) (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname) case mb_dc of Nothing-> do -- TODO: Check this case forM [0..length (elems $ ptrs clos)] $ \i -> do tv <- newVar liftedTypeKind return$ appArr (\e->(tv,e)) (ptrs clos) i Just dc -> do arg_tys <- getDataConArgTys dc my_ty (_, itys) <- findPtrTyss 0 arg_tys traceTR (text "Constr2" <+> ppr dcname <+> ppr arg_tys) return $ [ appArr (\e-> (ty,e)) (ptrs clos) i | (i,ty) <- itys] _ -> return [] findPtrTys :: Int -- Current pointer index -> Type -- Type -> TR (Int, [(Int, Type)]) findPtrTys i ty | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty , isUnboxedTupleTyCon tc = findPtrTyss i elem_tys | otherwise = case repType ty of UnaryRep rep_ty | typePrimRep rep_ty == PtrRep -> return (i + 1, [(i, ty)]) | otherwise -> return (i, []) UbxTupleRep rep_tys -> foldM (\(i, extras) rep_ty -> if typePrimRep rep_ty == PtrRep then newVar liftedTypeKind >>= \tv -> return (i + 1, extras ++ [(i, tv)]) else return (i, extras)) (i, []) rep_tys findPtrTyss :: Int -> [Type] -> TR (Int, [(Int, Type)]) findPtrTyss i tys = foldM step (i, []) tys where step (i, discovered) elem_ty = findPtrTys i elem_ty >>= \(i, extras) -> return (i, discovered ++ extras) -- Compute the difference between a base type and the type found by RTTI -- improveType <base_type> <rtti_type> -- The types can contain skolem type variables, which need to be treated as normal vars. -- In particular, we want them to unify with things. improveRTTIType :: HscEnv -> RttiType -> RttiType -> Maybe TvSubst improveRTTIType _ base_ty new_ty = U.tcUnifyTy base_ty new_ty getDataConArgTys :: DataCon -> Type -> TR [Type] -- Given the result type ty of a constructor application (D a b c :: ty) -- return the types of the arguments. This is RTTI-land, so 'ty' might -- not be fully known. Moreover, the arg types might involve existentials; -- if so, make up fresh RTTI type variables for them -- -- I believe that con_app_ty should not have any enclosing foralls getDataConArgTys dc con_app_ty = do { let UnaryRep rep_con_app_ty = repType con_app_ty ; traceTR (text "getDataConArgTys 1" <+> (ppr con_app_ty $$ ppr rep_con_app_ty $$ ppr (tcSplitTyConApp_maybe rep_con_app_ty))) ; (_, _, subst) <- instTyVars (univ_tvs ++ ex_tvs) ; addConstraint rep_con_app_ty (substTy subst (dataConOrigResTy dc)) -- See Note [Constructor arg types] ; let con_arg_tys = substTys subst (dataConRepArgTys dc) ; traceTR (text "getDataConArgTys 2" <+> (ppr rep_con_app_ty $$ ppr con_arg_tys $$ ppr subst)) ; return con_arg_tys } where univ_tvs = dataConUnivTyVars dc ex_tvs = dataConExTyVars dc {- Note [Constructor arg types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a GADT (cf Trac #7386) data family D a b data instance D [a] a where MkT :: a -> D [a] (Maybe a) ... In getDataConArgTys * con_app_ty is the known type (from outside) of the constructor application, say D [Int] Int * The data constructor MkT has a (representation) dataConTyCon = DList, say where data DList a where MkT :: a -> DList a (Maybe a) ... So the dataConTyCon of the data constructor, DList, differs from the "outside" type, D. So we can't straightforwardly decompose the "outside" type, and we end up in the "_" branch of the case. Then we match the dataConOrigResTy of the data constructor against the outside type, hoping to get a substitution that tells how to instantiate the *representation* type constructor. This looks a bit delicate to me, but it seems to work. -} -- Soundness checks -------------------- {- This is not formalized anywhere, so hold to your seats! RTTI in the presence of newtypes can be a tricky and unsound business. Example: ~~~~~~~~~ Suppose we are doing RTTI for a partially evaluated closure t, the real type of which is t :: MkT Int, for newtype MkT a = MkT [Maybe a] The table below shows the results of RTTI and the improvement calculated for different combinations of evaluatedness and :type t. Regard the two first columns as input and the next two as output. # | t | :type t | rtti(t) | improv. | result ------------------------------------------------------------ 1 | _ | t b | a | none | OK 2 | _ | MkT b | a | none | OK 3 | _ | t Int | a | none | OK If t is not evaluated at *all*, we are safe. 4 | (_ : _) | t b | [a] | t = [] | UNSOUND 5 | (_ : _) | MkT b | MkT a | none | OK (compensating for the missing newtype) 6 | (_ : _) | t Int | [Int] | t = [] | UNSOUND If a is a minimal whnf, we run into trouble. Note that row 5 above does newtype enrichment on the ty_rtty parameter. 7 | (Just _:_)| t b |[Maybe a] | t = [], | UNSOUND | | | b = Maybe a| 8 | (Just _:_)| MkT b | MkT a | none | OK 9 | (Just _:_)| t Int | FAIL | none | OK And if t is any more evaluated than whnf, we are still in trouble. Because constraints are solved in top-down order, when we reach the Maybe subterm what we got is already unsound. This explains why the row 9 fails to complete. 10 | (Just _:_)| t Int | [Maybe a] | FAIL | OK 11 | (Just 1:_)| t Int | [Maybe Int] | FAIL | OK We can undo the failure in row 9 by leaving out the constraint coming from the type signature of t (i.e., the 2nd column). Note that this type information is still used to calculate the improvement. But we fail when trying to calculate the improvement, as there is no unifier for t Int = [Maybe a] or t Int = [Maybe Int]. Another set of examples with t :: [MkT (Maybe Int)] \equiv [[Maybe (Maybe Int)]] # | t | :type t | rtti(t) | improvement | result --------------------------------------------------------------------- 1 |(Just _:_) | [t (Maybe a)] | [[Maybe b]] | t = [] | | | | | b = Maybe a | The checks: ~~~~~~~~~~~ Consider a function obtainType that takes a value and a type and produces the Term representation and a substitution (the improvement). Assume an auxiliar rtti' function which does the actual job if recovering the type, but which may produce a false type. In pseudocode: rtti' :: a -> IO Type -- Does not use the static type information obtainType :: a -> Type -> IO (Maybe (Term, Improvement)) obtainType v old_ty = do rtti_ty <- rtti' v if monomorphic rtti_ty || (check rtti_ty old_ty) then ... else return Nothing where check rtti_ty old_ty = check1 rtti_ty && check2 rtti_ty old_ty check1 :: Type -> Bool check2 :: Type -> Type -> Bool Now, if rtti' returns a monomorphic type, we are safe. If that is not the case, then we consider two conditions. 1. To prevent the class of unsoundness displayed by rows 4 and 7 in the example: no higher kind tyvars accepted. check1 (t a) = NO check1 (t Int) = NO check1 ([] a) = YES 2. To prevent the class of unsoundness shown by row 6, the rtti type should be structurally more defined than the old type we are comparing it to. check2 :: NewType -> OldType -> Bool check2 a _ = True check2 [a] a = True check2 [a] (t Int) = False check2 [a] (t a) = False -- By check1 we never reach this equation check2 [Int] a = True check2 [Int] (t Int) = True check2 [Maybe a] (t Int) = False check2 [Maybe Int] (t Int) = True check2 (Maybe [a]) (m [Int]) = False check2 (Maybe [Int]) (m [Int]) = True -} check1 :: QuantifiedType -> Bool check1 (tvs, _) = not $ any isHigherKind (map tyVarKind tvs) where isHigherKind = not . null . fst . splitKindFunTys check2 :: QuantifiedType -> QuantifiedType -> Bool check2 (_, rtti_ty) (_, old_ty) | Just (_, rttis) <- tcSplitTyConApp_maybe rtti_ty = case () of _ | Just (_,olds) <- tcSplitTyConApp_maybe old_ty -> and$ zipWith check2 (map quantifyType rttis) (map quantifyType olds) _ | Just _ <- splitAppTy_maybe old_ty -> isMonomorphicOnNonPhantomArgs rtti_ty _ -> True | otherwise = True -- Dealing with newtypes -------------------------- {- congruenceNewtypes does a parallel fold over two Type values, compensating for missing newtypes on both sides. This is necessary because newtypes are not present in runtime, but sometimes there is evidence available. Evidence can come from DataCon signatures or from compile-time type inference. What we are doing here is an approximation of unification modulo a set of equations derived from newtype definitions. These equations should be the same as the equality coercions generated for newtypes in System Fc. The idea is to perform a sort of rewriting, taking those equations as rules, before launching unification. The caller must ensure the following. The 1st type (lhs) comes from the heap structure of ptrs,nptrs. The 2nd type (rhs) comes from a DataCon type signature. Rewriting (i.e. adding/removing a newtype wrapper) can happen in both types, but in the rhs it is restricted to the result type. Note that it is very tricky to make this 'rewriting' work with the unification implemented by TcM, where substitutions are operationally inlined. The order in which constraints are unified is vital as we cannot modify anything that has been touched by a previous unification step. Therefore, congruenceNewtypes is sound only if the types recovered by the RTTI mechanism are unified Top-Down. -} congruenceNewtypes :: TcType -> TcType -> TR (TcType,TcType) congruenceNewtypes lhs rhs = go lhs rhs >>= \rhs' -> return (lhs,rhs') where go l r -- TyVar lhs inductive case | Just tv <- getTyVar_maybe l , isTcTyVar tv , isMetaTyVar tv = recoverTR (return r) $ do Indirect ty_v <- readMetaTyVar tv traceTR $ fsep [text "(congruence) Following indirect tyvar:", ppr tv, equals, ppr ty_v] go ty_v r -- FunTy inductive case | Just (l1,l2) <- splitFunTy_maybe l , Just (r1,r2) <- splitFunTy_maybe r = do r2' <- go l2 r2 r1' <- go l1 r1 return (mkFunTy r1' r2') -- TyconApp Inductive case; this is the interesting bit. | Just (tycon_l, _) <- tcSplitTyConApp_maybe lhs , Just (tycon_r, _) <- tcSplitTyConApp_maybe rhs , tycon_l /= tycon_r = upgrade tycon_l r | otherwise = return r where upgrade :: TyCon -> Type -> TR Type upgrade new_tycon ty | not (isNewTyCon new_tycon) = do traceTR (text "(Upgrade) Not matching newtype evidence: " <> ppr new_tycon <> text " for " <> ppr ty) return ty | otherwise = do traceTR (text "(Upgrade) upgraded " <> ppr ty <> text " in presence of newtype evidence " <> ppr new_tycon) (_, vars, _) <- instTyVars (tyConTyVars new_tycon) let ty' = mkTyConApp new_tycon vars UnaryRep rep_ty = repType ty' _ <- liftTcM (unifyType ty rep_ty) -- assumes that reptype doesn't ^^^^ touch tyconApp args return ty' zonkTerm :: Term -> TcM Term zonkTerm = foldTermM (TermFoldM { fTermM = \ty dc v tt -> zonkRttiType ty >>= \ty' -> return (Term ty' dc v tt) , fSuspensionM = \ct ty v b -> zonkRttiType ty >>= \ty -> return (Suspension ct ty v b) , fNewtypeWrapM = \ty dc t -> zonkRttiType ty >>= \ty' -> return$ NewtypeWrap ty' dc t , fRefWrapM = \ty t -> return RefWrap `ap` zonkRttiType ty `ap` return t , fPrimM = (return.) . Prim }) zonkRttiType :: TcType -> TcM Type -- Zonk the type, replacing any unbound Meta tyvars -- by skolems, safely out of Meta-tyvar-land zonkRttiType = zonkTcTypeToType (mkEmptyZonkEnv zonk_unbound_meta) where zonk_unbound_meta tv = ASSERT( isTcTyVar tv ) do { tv' <- skolemiseUnboundMetaTyVar tv RuntimeUnk -- This is where RuntimeUnks are born: -- otherwise-unconstrained unification variables are -- turned into RuntimeUnks as they leave the -- typechecker's monad ; return (mkTyVarTy tv') } -------------------------------------------------------------------------------- -- Restore Class predicates out of a representation type dictsView :: Type -> Type dictsView ty = ty -- Use only for RTTI types isMonomorphic :: RttiType -> Bool isMonomorphic ty = noExistentials && noUniversals where (tvs, _, ty') = tcSplitSigmaTy ty noExistentials = isEmptyVarSet (tyVarsOfType ty') noUniversals = null tvs -- Use only for RTTI types isMonomorphicOnNonPhantomArgs :: RttiType -> Bool isMonomorphicOnNonPhantomArgs ty | UnaryRep rep_ty <- repType ty , Just (tc, all_args) <- tcSplitTyConApp_maybe rep_ty , phantom_vars <- tyConPhantomTyVars tc , concrete_args <- [ arg | (tyv,arg) <- tyConTyVars tc `zip` all_args , tyv `notElem` phantom_vars] = all isMonomorphicOnNonPhantomArgs concrete_args | Just (ty1, ty2) <- splitFunTy_maybe ty = all isMonomorphicOnNonPhantomArgs [ty1,ty2] | otherwise = isMonomorphic ty tyConPhantomTyVars :: TyCon -> [TyVar] tyConPhantomTyVars tc | isAlgTyCon tc , Just dcs <- tyConDataCons_maybe tc , dc_vars <- concatMap dataConUnivTyVars dcs = tyConTyVars tc \\ dc_vars tyConPhantomTyVars _ = [] type QuantifiedType = ([TyVar], Type) -- Make the free type variables explicit -- The returned Type should have no top-level foralls (I believe) quantifyType :: Type -> QuantifiedType -- Generalize the type: find all free and forall'd tyvars -- and return them, together with the type inside, which -- should not be a forall type. -- -- Thus (quantifyType (forall a. a->[b])) -- returns ([a,b], a -> [b]) quantifyType ty = (varSetElems (tyVarsOfType rho), rho) where (_tvs, rho) = tcSplitForAllTys ty unlessM :: Monad m => m Bool -> m () -> m () unlessM condM acc = condM >>= \c -> unless c acc -- Strict application of f at index i appArr :: Ix i => (e -> a) -> Array i e -> Int -> a appArr f a@(Array _ _ _ ptrs#) i@(I# i#) = ASSERT2(i < length(elems a), ppr(length$ elems a, i)) case indexArray# ptrs# i# of (# e #) -> f e amap' :: (t -> b) -> Array Int t -> [b] amap' f (Array i0 i _ arr#) = map g [0 .. i - i0] where g (I# i#) = case indexArray# arr# i# of (# e #) -> f e
spacekitteh/smcghc
compiler/ghci/RtClosureInspect.hs
Haskell
bsd-3-clause
52,399
module Math.Misc.Parity where import Prelude hiding (fromIntegral) import Math.Algebra.Monoid import Math.Algebra.AbelianMonoid import Data.List import Data.Hashable data Parity = Odd | Even deriving (Eq, Show) instance Hashable Parity where hash Even = 0 hash Odd = 1 opposite :: Parity -> Parity opposite Odd = Even opposite Even = Odd instance MultiplicativeMonoid Parity where Odd <*> Odd = Even Odd <*> Even = Odd Even <*> Odd = Odd Even <*> Even = Even one = Even instance AbelianMultiplicativeMonoid Parity instance Ord Parity where compare Odd Odd = EQ compare Even Even = EQ compare Even Odd = LT compare Odd Even = GT fromIntegral :: (Integral a) => a -> Parity fromIntegral m | even m = Even | otherwise = Odd fromBool :: Bool -> Parity fromBool True = Even fromBool False = Odd fromLength :: [a] -> Parity fromLength = foldl' (\p _ -> (opposite p)) Even
michiexile/hplex
pershom/src/Math/Misc/Parity.hs
Haskell
bsd-3-clause
949
---------------------------------------------------------------------------- -- | -- Module : ModuleWithoutImportList -- Copyright : (c) Sergey Vinokurov 2016 -- License : BSD3-style (see LICENSE) -- Maintainer : serg.foo@gmail.com -- Created : Thursday, 20 October 2016 ---------------------------------------------------------------------------- module ModuleWithoutImportList where import ModuleThatExportsPattern
sergv/tags-server
test-data/0006export_pattern_with_type_ghc8.0/ModuleWithoutImportList.hs
Haskell
bsd-3-clause
440
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} module ML.Vec where import ML.Nat import Control.Applicative ((<$>)) data Vec (n :: Nat) (a :: *) where Nil :: Vec Z a (:-) :: a -> Vec n a -> Vec (S n) a instance Functor (Vec n) where fmap f Nil = Nil fmap f (x :- xs) = f x :- fmap f xs instance Foldable (Vec n) where foldr f s Nil = s foldr f s (x :- xs) = foldr f (f x s) xs instance Show a => Show (Vec n a) where show Nil = "[]" show (a :- r) = show a ++ " :- " ++ show r infixr 5 :- fromList :: SNat n -> [a] -> Maybe (Vec n a) fromList SZ _ = Just Nil fromList (SS n) (x:xs) = (x :-) <$> fromList n xs fromList _ _ = Nothing toList :: Vec n a -> [a] toList Nil = [] toList (x :- xs) = x:(toList xs) vzip :: (a -> b -> c) -> Vec n a -> Vec n b -> Vec n c vzip _ Nil _ = Nil vzip f (x :- xs) (y :- ys) = f x y :- vzip f xs ys vlen :: Vec n a -> Int vlen = foldr (\_ x -> x + 1) 0 vdot :: Num a => Vec n a -> Vec n a -> a vdot v1 v2 = vsum $ vzip (*) v1 v2 vmul :: Num a => a -> Vec n a -> Vec n a vmul a = fmap (*a) vsub :: Num a => Vec n a -> Vec n a -> Vec n a vsub = vzip (-) vsum :: Num a => Vec n a -> a vsum = foldr (+) 0 vmax :: Ord a => Vec (S n) a -> a vmax (x :- xs) = foldr (max) x xs
ralphmorton/ml
src/ML/Vec.hs
Haskell
bsd-3-clause
1,319
module Data.Torrent.Types ( BEncodedT(..) , mkBString , beList , beDictUTF8L , beDictUTF8 , beDict , beDictLookup , parseBencoded , ClientHandshake(..) , parseClientHandshake , randomPeerId , PeerMessage(..) , parseW8RunLength , beEncodeByteString , beString' , beInteger , beStringUTF8 , putBInt , getBInt ) where import Data.Binary import Data.Binary.Put import Data.Binary.Get import Data.Map (Map) import qualified Data.Map as Map import qualified Codec.Binary.UTF8.Generic as UTF8 import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.Attoparsec (Parser) import qualified Data.Attoparsec.ByteString.Char8 as P import qualified Data.Attoparsec.ByteString as PB import Crypto.Hash.SHA1 import qualified Data.Serialize as Ser import Crypto.Random.API data BEncodedT = BString !ByteString | BInteger !Integer | BList ![BEncodedT] | BDict ![(BEncodedT, BEncodedT)] deriving (Show, Eq) -- | After the client protocol handshake, there comes an alternating stream of length prefixes and 'PeerMessage's data PeerMessage = -- | Messages of length zero are keepalives, and ignored. Keepalives are generally sent once every two minutes, but note that timeouts can be done much more quickly when data is expected. KeepAlive | Choke | Unchoke | Interested | NotInterested | -- | The 'Have' message's payload is a single number, the index which that downloader just completed and checked the hash of. Have Int | -- | 'Bitfield' is only ever sent as the first message. Its payload is a bitfield with each index that downloader has sent set to one and the rest set to zero. Downloaders which don't have anything yet may skip the 'bitfield' message. The first byte of the bitfield corresponds to indices 0 - 7 from high bit to low bit, respectively. The next one 8-15, etc. Spare bits at the end are set to zero. Bitfield ByteString | -- | 'Request' messages contain an index, begin, and length. The last two are byte offsets. Length is generally a power of two unless it gets truncated by the end of the file. All current implementations use 2 15 , and close connections which request an amount greater than 2 17. Request Int Int Int | -- | 'Piece' messages contain an index, begin, and piece. Note that they are correlated with request messages implicitly. It's possible for an unexpected piece to arrive if choke and unchoke messages are sent in quick succession and/or transfer is going very slowly. Piece Int Int ByteString | -- | 'Cancel' messages have the same payload as request messages. They are generally only sent towards the end of a download, during what's called 'endgame mode'. When a download is almost complete, there's a tendency for the last few pieces to all be downloaded off a single hosed modem line, taking a very long time. To make sure the last few pieces come in quickly, once requests for all pieces a given downloader doesn't have yet are currently pending, it sends requests for everything to everyone it's downloading from. To keep this from becoming horribly inefficient, it sends cancels to everyone else every time a piece arrives. Cancel Int Int Int deriving (Show, Eq) instance Binary PeerMessage where put = putPeerMessage get = getPeerMessage putPeerMessage' :: PeerMessage -> Put putPeerMessage' KeepAlive = putLazyByteString BL.empty putPeerMessage' Choke = putWord8 0x00 putPeerMessage' Unchoke = putWord8 0x01 putPeerMessage' Interested = putWord8 0x02 putPeerMessage' NotInterested = putWord8 0x03 putPeerMessage' (Have i) = do putWord8 0x04 putBInt i putPeerMessage' (Bitfield bs) = do putWord8 0x05 putByteString bs putPeerMessage' (Request i b l) = do putWord8 0x06 putBInt i putBInt b putBInt l putPeerMessage' (Piece i b bs) = do putWord8 0x07 putBInt i putBInt b putByteString bs putPeerMessage' (Cancel i b l) = do putWord8 0x08 putBInt i putBInt b putBInt l putPeerMessage :: PeerMessage -> Put putPeerMessage pm = let bs = runPut $ do putPeerMessage' $ pm flush in do putBInt $ BL.length bs putLazyByteString bs flush getPeerMessage :: Get PeerMessage getPeerMessage = do l' <- getBInt if (l' == 0) then return KeepAlive else do t <- getWord8 let l = l' - 1 case t of 0x00 -> return Choke 0x01 -> return Unchoke 0x02 -> return Interested 0x03 -> return NotInterested 0x04 -> fmap Have getBInt 0x05 -> fmap Bitfield $ getByteString l 0x06 -> do i <- getBInt b <- getBInt l <- getBInt return $ Request i b l 0x07 -> do i <- getBInt b <- getBInt bs <- getByteString $ l - 8 return $ Piece i b bs 0x08 -> do i <- getBInt b <- getBInt l <- getBInt return $ Cancel i b l putBInt :: (Integral a) => a -> Put putBInt = putWord32be . fromInteger . toInteger getBInt :: (Integral a) => Get a getBInt = fmap (fromInteger . toInteger) getWord32be mkBString :: String -> BEncodedT mkBString = BString . UTF8.fromString parseW8RunLength :: Parser String parseW8RunLength = do l <- fmap (fromInteger . toInteger) PB.anyWord8 fmap UTF8.toString $ PB.take l data ClientHandshake = ClientHandshake { hsInfoHash :: SHA1, hsPeerId :: ByteString, hsReservedBytes :: ByteString } deriving (Eq, Show) handShakeText :: String handShakeText = "BitTorrent protocol" parseTorrentMagic :: PB.Parser () parseTorrentMagic = do hs <- parseW8RunLength if (hs /= handShakeText) then fail $ "handshake is not '" ++ handShakeText ++ "'" ++ " but '" ++ hs ++ "'" else return () parseClientHandshake :: PB.Parser ClientHandshake parseClientHandshake = do -- torrent magic PB.try $ parseTorrentMagic -- reserved bytes reservedBytes <- PB.take 8 -- info hash ih' <- fmap Ser.decode $ PB.take 20 h <- case (ih') of Left err -> fail $ "unable to decode SHA1 hash: " ++ err Right h -> return h -- peer id peerid <- PB.take 20 return $ ClientHandshake h peerid reservedBytes randomPeerId :: IO ByteString randomPeerId = fmap (fst. genRandomBytes 20) getSystemRandomGen beEncodeByteString :: BEncodedT -> ByteString beEncodeByteString (BString bs) = let l = BS.length bs pfix= UTF8.fromString $ show l ++ ":" in BS.concat [pfix,bs] beEncodeByteString (BInteger i) = UTF8.fromString $ "i" ++ show i ++ "e" beEncodeByteString (BList l) = let ls = BS.concat $ map beEncodeByteString l in BS.concat [UTF8.fromString "l", ls, UTF8.fromString "e"] beEncodeByteString (BDict d) = let r [] = BS.empty r ((k,v):rs) = BS.concat $ [beEncodeByteString k, beEncodeByteString v] ++ [(r rs)] in BS.concat [UTF8.fromString "d", r d, UTF8.fromString "e"] beString' :: BEncodedT -> ByteString beString' (BString bs) = bs beString' v = error $ "beString' called on a: " ++ show v beStringUTF8 = UTF8.toString . beString' beInteger :: BEncodedT -> Integer beInteger (BInteger i) = i beInteger v = error $ "beInteger called on a: " ++ show v beList :: BEncodedT -> [BEncodedT] beList (BList l) = l beList v = error $ "beList called on a: " ++ show v beDictLookup :: String -> BEncodedT -> BEncodedT beDictLookup k = maybe (error $ "unable to lookup dict key " ++ k) id . beDict k beDict :: String -> BEncodedT -> Maybe BEncodedT beDict k d = Map.lookup k $ beDictUTF8 d beDict' :: BEncodedT -> Map ByteString BEncodedT beDict' (BDict d) = Map.fromList [(beString' k, v) | (k,v) <- d] beDict' v = error $ "beDict' called on a: " ++ show v beDictUTF8L :: BEncodedT -> [(String, BEncodedT)] beDictUTF8L (BDict d) = [(beStringUTF8 k, v) | (k,v) <- d] beDictUTF8L v = error $ "beDictUTF8L called on a: " ++ show v beDictUTF8 :: BEncodedT -> Map String BEncodedT beDictUTF8 = Map.fromList . beDictUTF8L parseString :: Parser BEncodedT parseString = do l <- P.decimal _ <- P.char ':' fmap BString $ P.take l parseInteger :: Parser BEncodedT parseInteger = do _ <- P.char 'i' d <- fmap BInteger $ P.signed P.decimal _ <- P.char 'e' return d parseList :: Parser BEncodedT parseList = do _ <- P.char 'l' fmap BList $ P.manyTill parseBencoded $ P.try $ P.char 'e' parseDict :: Parser BEncodedT parseDict = do _ <- P.char 'd' let kvp = do k <- parseString v <- parseBencoded return (k,v) fmap BDict $ P.manyTill kvp $ P.try $ P.char 'e' parseBencoded :: Parser BEncodedT parseBencoded = P.choice [parseString, parseInteger, parseList, parseDict]
alios/lcars2
Data/Torrent/Types.hs
Haskell
bsd-3-clause
8,746
module YampaSDL where import Data.IORef import FRP.Yampa as Yampa import Graphics.UI.SDL as SDL type TimeRef = IORef Int yampaSDLTimeInit :: IO TimeRef yampaSDLTimeInit = do timeRef <- newIORef (0 :: Int) _ <- yampaSDLTimeSense timeRef _ <- yampaSDLTimeSense timeRef _ <- yampaSDLTimeSense timeRef _ <- yampaSDLTimeSense timeRef return timeRef -- | Updates the time in an IO Ref and returns the time difference updateTime :: IORef Int -> Int -> IO Int updateTime timeRef newTime = do previousTime <- readIORef timeRef writeIORef timeRef newTime return (newTime - previousTime) yampaSDLTimeSense :: IORef Int -> IO Yampa.DTime yampaSDLTimeSense timeRef = do -- Get time passed since SDL init newTime <- fmap fromIntegral SDL.getTicks -- Obtain time difference dt <- updateTime timeRef newTime let dtSecs = fromIntegral dt / 100 return dtSecs
ivanperez-keera/Yampa
yampa/examples/yampa-game/YampaSDL.hs
Haskell
bsd-3-clause
907
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE EmptyDataDecls #-} -- TODO: This is a hot-spot for generating user-unfriendly error messages. It -- could use some cleaning up in this regard. (Perhaps we should be -- lifting from TypecheckedSource instead of CoreExpr?) There's also a -- lot of logic here that wouldn't be necessary if Pred and Expr were -- merged. module Language.Haskell.Liquid.Spec.CoreToLogic ( LogicM, coreToDef, coreToFun, runToLogic, logicType, strengthenResult ) where import GHC hiding (Located) import Var import Type import qualified CoreSyn as C import Literal import IdInfo import TysWiredIn import Control.Applicative import Language.Fixpoint.Misc import Language.Fixpoint.Names (dropModuleNames, propConName, isPrefixOfSym) import Language.Fixpoint.Types hiding (Def, R, simplify) import qualified Language.Fixpoint.Types as F import Language.Haskell.Liquid.GhcMisc import Language.Haskell.Liquid.GhcPlay import Language.Haskell.Liquid.Literals (mkLit) import Language.Haskell.Liquid.Types hiding (GhcInfo(..), GhcSpec (..)) import Language.Haskell.Liquid.WiredIn import Language.Haskell.Liquid.RefType import qualified Data.HashMap.Strict as M import Data.Monoid logicType :: (Reftable r) => Type -> RRType r logicType τ = fromRTypeRep $ t{ty_res = res, ty_binds = binds, ty_args = args, ty_refts = refts} where t = toRTypeRep $ ofType τ res = mkResType $ ty_res t (binds, args, refts) = unzip3 $ dropWhile (isClassType.snd3) $ zip3 (ty_binds t) (ty_args t) (ty_refts t) mkResType t {-| isBool t = propType | otherwise-} = t isBool (RApp (RTyCon{rtc_tc = c}) _ _ _) = c == boolTyCon isBool _ = False {- strengthenResult type: the refinement depends on whether the result type is a Bool or not: CASE1: measure f@logic :: X -> Prop <=> f@haskell :: x:X -> {v:Bool | (Prop v) <=> (f@logic x)} CASE2: measure f@logic :: X -> Y <=> f@haskell :: x:X -> {v:Y | v = (f@logic x)} -} strengthenResult :: Var -> SpecType -> SpecType strengthenResult v t {- | isBool res = -- traceShow ("Type for " ++ showPpr v ++ "\t OF \t" ++ show (ty_binds rep)) $ fromRTypeRep $ rep{ty_res = res `strengthen` r} | otherwise-} = -- traceShow ("Type for " ++ showPpr v ++ "\t OF \t" ++ show (ty_binds rep)) $ fromRTypeRep $ rep{ty_res = res `strengthen` r'} where rep = toRTypeRep t res = ty_res rep r' = U (exprReft (EApp f (mkA <$> vxs))) mempty mempty r = U (propReft (PBexp $ EApp f (mkA <$> vxs))) mempty mempty vxs = dropWhile (isClassType.snd) $ zip (ty_binds rep) (ty_args rep) f = dummyLoc $ varSymbol v mkA = \(x, _) -> EVar x -- if isBool t then EApp (dummyLoc propConName) [(EVar x)] else EVar x newtype LogicM a = LM {runM :: LState -> Either a String} data LState = LState { symbolMap :: LogicMap } instance Monad LogicM where return = LM . const . Left (LM m) >>= f = LM $ \s -> case m s of (Left x) -> (runM (f x)) s (Right x) -> Right x instance Functor LogicM where fmap f (LM m) = LM $ \s -> case m s of (Left x) -> Left $ f x (Right x) -> Right x instance Applicative LogicM where pure = LM . const . Left (LM f) <*> (LM m) = LM $ \s -> case (f s, m s) of (Left f , Left x ) -> Left $ f x (Right f, Left _ ) -> Right f (Left _ , Right x) -> Right x (Right _, Right x) -> Right x throw :: String -> LogicM a throw str = LM $ const $ Right str getState :: LogicM LState getState = LM $ Left runToLogic lmap (LM m) = m $ LState {symbolMap = lmap} coreToDef :: LocSymbol -> Var -> C.CoreExpr -> LogicM [Def] coreToDef x _ e = go [] $ inline_preds $ simplify e where go args (C.Lam x e) = go (x:args) e go args (C.Tick _ e) = go args e go args (C.Case _ _ t alts) | eqType t boolTy = mapM (goalt_prop (reverse $ tail args) (head args)) alts | otherwise = mapM (goalt (reverse $ tail args) (head args)) alts go _ _ = throw "Measure Functions should have a case at top level" goalt args dx ((C.DataAlt d), xs, e) = ((Def x (toArgs id args) d (Just $ ofType $ varType dx) (toArgs Just xs)) . E) <$> coreToLogic e goalt _ _ alt = throw $ "Bad alternative" ++ showPpr alt goalt_prop args dx ((C.DataAlt d), xs, e) = ((Def x (toArgs id args) d (Just $ ofType $ varType dx) (toArgs Just xs)) . P) <$> coreToPred e goalt_prop _ _ alt = throw $ "Bad alternative" ++ showPpr alt toArgs f args = [(symbol x, f $ ofType $ varType x) | x <- args] inline_preds = inline (eqType boolTy . varType) coreToFun :: LocSymbol -> Var -> C.CoreExpr -> LogicM ([Var], Either Pred Expr) coreToFun _ v e = go [] $ inline_preds $ simplify e where go acc (C.Lam x e) | isTyVar x = go acc e go acc (C.Lam x e) | isErasable x = go acc e go acc (C.Lam x e) = go (x:acc) e go acc (C.Tick _ e) = go acc e go acc e | eqType rty boolTy = (reverse acc,) . Left <$> coreToPred e | otherwise = (reverse acc,) . Right <$> coreToLogic e inline_preds = inline (eqType boolTy . varType) rty = snd $ splitFunTys $ snd $ splitForAllTys $ varType v coreToPred :: C.CoreExpr -> LogicM Pred coreToPred (C.Let b p) = subst1 <$> coreToPred p <*> makesub b coreToPred (C.Tick _ p) = coreToPred p coreToPred (C.App (C.Var v) e) | ignoreVar v = coreToPred e coreToPred (C.Var x) | x == falseDataConId = return PFalse | x == trueDataConId = return PTrue | eqType boolTy (varType x) = return $ PBexp $ EVar $ symbol x -- $ EApp (dummyLoc propConName) [(EVar $ symbol x)] coreToPred p@(C.App _ _) = toPredApp p coreToPred e = PBexp <$> coreToLogic e -- coreToPred e -- = throw ("Cannot transform to Logical Predicate:\t" ++ showPpr e) coreToLogic :: C.CoreExpr -> LogicM Expr coreToLogic (C.Let b e) = subst1 <$> coreToLogic e <*> makesub b coreToLogic (C.Tick _ e) = coreToLogic e coreToLogic (C.App (C.Var v) e) | ignoreVar v = coreToLogic e coreToLogic (C.Lit l) = case mkLit l of Nothing -> throw $ "Bad Literal in measure definition" ++ showPpr l Just i -> return i coreToLogic (C.Var x) = (symbolMap <$> getState) >>= eVarWithMap x coreToLogic e@(C.App _ _) = toLogicApp e coreToLogic (C.Case e b _ alts) | eqType (varType b) boolTy = checkBoolAlts alts >>= coreToIte e coreToLogic e = throw ("Cannot transform to Logic:\t" ++ showPpr e) checkBoolAlts :: [C.CoreAlt] -> LogicM (C.CoreExpr, C.CoreExpr) checkBoolAlts [(C.DataAlt false, [], efalse), (C.DataAlt true, [], etrue)] | false == falseDataCon, true == trueDataCon = return (efalse, etrue) checkBoolAlts [(C.DataAlt true, [], etrue), (C.DataAlt false, [], efalse)] | false == falseDataCon, true == trueDataCon = return (efalse, etrue) checkBoolAlts alts = throw ("checkBoolAlts failed on " ++ showPpr alts) coreToIte e (efalse, etrue) = do p <- coreToPred e e1 <- coreToLogic efalse e2 <- coreToLogic etrue return $ EIte p e2 e1 toPredApp :: C.CoreExpr -> LogicM Pred toPredApp p = do let (f, es) = splitArgs p f' <- tosymbol f go f' es where go f [e1, e2] | Just rel <- M.lookup (val f) brels = PAtom rel <$> (coreToLogic e1) <*> (coreToLogic e2) go f [e] | val f == symbol ("not" :: String) = PNot <$> coreToPred e go f [e1, e2] | val f == symbol ("||" :: String) = POr <$> mapM coreToPred [e1, e2] | val f == symbol ("&&" :: String) = PAnd <$> mapM coreToPred [e1, e2] | val f == symbol ("==>" :: String) = PImp <$> coreToPred e1 <*> coreToPred e2 go f es | val f == symbol ("or" :: String) = POr <$> mapM coreToPred es | val f == symbol ("and" :: String) = PAnd <$> mapM coreToPred es | otherwise = PBexp <$> toLogicApp p toLogicApp :: C.CoreExpr -> LogicM Expr toLogicApp e = do let (f, es) = splitArgs e args <- mapM coreToLogic es lmap <- symbolMap <$> getState def <- (`EApp` args) <$> tosymbol0 f (\x -> makeApp def lmap x args) <$> tosymbol' f makeApp :: Expr -> LogicMap -> Located Symbol-> [Expr] -> Expr makeApp _ _ f [e] | val f == symbol ("GHC.Num.negate" :: String) = ENeg e | val f == symbol ("GHC.Num.fromInteger" :: String) = e makeApp _ _ f [e1, e2] | Just op <- M.lookup (val f) bops = EBin op e1 e2 makeApp def lmap f es = eAppWithMap lmap f es def eVarWithMap :: Id -> LogicMap -> LogicM Expr eVarWithMap x lmap = do f' <- tosymbol' (C.Var x :: C.CoreExpr) return $ eAppWithMap lmap f' [] (EVar $ symbol x) brels :: M.HashMap Symbol Brel brels = M.fromList [ (symbol ("==" :: String), Eq) , (symbol ("/=" :: String), Ne) , (symbol (">=" :: String), Ge) , (symbol (">" :: String) , Gt) , (symbol ("<=" :: String), Le) , (symbol ("<" :: String) , Lt) ] bops :: M.HashMap Symbol Bop bops = M.fromList [ (numSymbol "+", Plus) , (numSymbol "-", Minus) , (numSymbol "*", Times) , (numSymbol "/", Div) , (numSymbol "%", Mod) ] where numSymbol :: String -> Symbol numSymbol = symbol . (++) "GHC.Num." splitArgs e = (f, reverse es) where (f, es) = go e go (C.App (C.Var i) e) | ignoreVar i = go e go (C.App f (C.Var v)) | isErasable v = go f go (C.App f e) = (f', e:es) where (f', es) = go f go f = (f, []) tosymbol (C.Var c) | isDataConId c = return $ dummyLoc $ symbol c tosymbol (C.Var x) = return $ dummyLoc $ simpleSymbolVar x tosymbol e = throw ("Bad Measure Definition:\n" ++ showPpr e ++ "\t cannot be applied") -- TODO: Remove uniques from our symbols tosymbol0 (C.Var c) | isDataConId c = return $ dummyLoc $ symbol c tosymbol0 (C.Var x) = return $ dummyLoc $ varSymbol x tosymbol0 e = throw ("Bad Measure Definition:\n" ++ showPpr e ++ "\t cannot be applied") tosymbol' (C.Var x) = return $ dummyLoc $ simpleSymbolVar' x tosymbol' e = throw ("Bad Measure Definition:\n" ++ showPpr e ++ "\t cannot be applied") makesub (C.NonRec x e) = (symbol x,) <$> coreToLogic e makesub _ = throw "Cannot make Logical Substitution of Recursive Definitions" ignoreVar i = simpleSymbolVar i `elem` ["I#"] simpleSymbolVar = dropModuleNames . symbol . showPpr . getName simpleSymbolVar' = symbol . showPpr . getName isErasable v = isPrefixOfSym (symbol ("$" :: String)) (simpleSymbolVar v) isDead = isDeadOcc . occInfo . idInfo class Simplify a where simplify :: a -> a inline :: (Id -> Bool) -> a -> a instance Simplify C.CoreExpr where simplify e@(C.Var _) = e simplify e@(C.Lit _) = e simplify (C.App e (C.Type _)) = simplify e simplify (C.App e (C.Var dict)) | isErasable dict = simplify e simplify (C.App (C.Lam x e) _) | isDead x = simplify e simplify (C.App e1 e2) = C.App (simplify e1) (simplify e2) simplify (C.Lam x e) | isTyVar x = simplify e simplify (C.Lam x e) | isErasable x = simplify e simplify (C.Lam x e) = C.Lam x (simplify e) simplify (C.Let (C.NonRec x _) e) | isErasable x = simplify e simplify (C.Let (C.Rec xes) e) | all (isErasable . fst) xes = simplify e simplify (C.Let xes e) = C.Let (simplify xes) (simplify e) simplify (C.Case e x t alts) = C.Case (simplify e) x t (filter (not . isUndefined) (simplify <$> alts)) simplify (C.Cast e _) = simplify e simplify (C.Tick _ e) = simplify e simplify (C.Coercion c) = C.Coercion c simplify (C.Type t) = C.Type t inline p (C.Let (C.NonRec x ex) e) | p x = sub (M.singleton x (inline p ex)) (inline p e) inline p (C.Let xes e) = C.Let (inline p xes) (inline p e) inline p (C.App e1 e2) = C.App (inline p e1) (inline p e2) inline p (C.Lam x e) = C.Lam x (inline p e) inline p (C.Case e x t alts) = C.Case (inline p e) x t (inline p <$> alts) inline p (C.Cast e c) = C.Cast (inline p e) c inline p (C.Tick t e) = C.Tick t (inline p e) inline _ (C.Var x) = C.Var x inline _ (C.Lit l) = C.Lit l inline _ (C.Coercion c) = C.Coercion c inline _ (C.Type t) = C.Type t isUndefined (_, _, e) = isUndefinedExpr e where -- auto generated undefined case: (\_ -> (patError @type "error message")) void isUndefinedExpr (C.App (C.Var x) _) | (show x) `elem` perrors = True isUndefinedExpr (C.Let _ e) = isUndefinedExpr e -- otherwise isUndefinedExpr _ = False perrors = ["Control.Exception.Base.patError"] instance Simplify C.CoreBind where simplify (C.NonRec x e) = C.NonRec x (simplify e) simplify (C.Rec xes) = C.Rec (mapSnd simplify <$> xes ) inline p (C.NonRec x e) = C.NonRec x (inline p e) inline p (C.Rec xes) = C.Rec (mapSnd (inline p) <$> xes) instance Simplify C.CoreAlt where simplify (c, xs, e) = (c, xs, simplify e) inline p (c, xs, e) = (c, xs, inline p e)
spinda/liquidhaskell
src/Language/Haskell/Liquid/Spec/CoreToLogic.hs
Haskell
bsd-3-clause
13,772
{- let s = "s" createSparkSessionDef $ defaultConf { confRequestedSessionName = Data.Text.pack s } execStateDef (checkDataStamps [HdfsPath (Data.Text.pack "/tmp/")]) -} module Spark.IO.StampSpec where import Test.Hspec -- import Spark.Core.Context -- import Spark.Core.Types -- import Spark.Core.Row -- import Spark.Core.Functions -- import Spark.Core.Column -- import Spark.IO.Inputs -- import Spark.Core.IntegrationUtilities import Spark.Core.SimpleAddSpec(run) spec :: Spec spec = do describe "Read a json file" $ do run "simple read" $ do let x = 1 :: Int x `shouldBe` x
krapsh/kraps-haskell
test-integration/Spark/IO/StampSpec.hs
Haskell
apache-2.0
600
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} -- | Provides functions for manipulating parts. module Music.Score.Part ( -- ** Articulation type functions Part, SetPart, -- ** Accessing parts HasParts(..), HasPart(..), HasPart', HasParts', part', parts', -- * Listing parts allParts, -- * Extracting parts extracted, extractedWithInfo, extractPart, extractParts, extractPartsWithInfo, -- * Manipulating parts -- * Part representation PartT(..), -- Part, -- HasPart(..), -- HasPart', -- PartT(..), -- getParts, (</>), rcat, ) where import Control.Applicative import Control.Comonad import Control.Lens hiding (parts, transform) import Control.Monad.Plus -- import Data.Default import Data.Foldable import Data.Functor.Couple import qualified Data.List as List import qualified Data.List as List import Data.Ord (comparing) import Data.PairMonad import Data.Ratio import Data.Semigroup import Data.Traversable import Data.Typeable import Music.Dynamics.Literal import Music.Pitch.Literal import Music.Score.Ties import Music.Score.Internal.Util (through) import Music.Time import Music.Time.Internal.Transform -- | -- Parts type. -- type family Part (s :: *) :: * -- Part s = a -- | -- Part type. -- type family SetPart (b :: *) (s :: *) :: * -- Part b s = t -- | -- Class of types that provide a single part. -- class (HasParts s t) => HasPart s t where -- | Part type. part :: Lens s t (Part s) (Part t) -- | -- Class of types that provide a part traversal. -- class (Transformable (Part s), Transformable (Part t) -- , SetPart (Part t) s ~ t ) => HasParts s t where -- | Part type. parts :: Traversal s t (Part s) (Part t) type HasPart' a = HasPart a a type HasParts' a = HasParts a a -- | -- Part type. -- part' :: (HasPart s t, s ~ t) => Lens' s (Part s) part' = part -- | -- Part type. -- parts' :: (HasParts s t, s ~ t) => Traversal' s (Part s) parts' = parts type instance Part Bool = Bool type instance SetPart a Bool = a instance (b ~ Part b, Transformable b) => HasPart Bool b where part = ($) instance (b ~ Part b, Transformable b) => HasParts Bool b where parts = ($) type instance Part Ordering = Ordering type instance SetPart a Ordering = a instance (b ~ Part b, Transformable b) => HasPart Ordering b where part = ($) instance (b ~ Part b, Transformable b) => HasParts Ordering b where parts = ($) type instance Part () = () type instance SetPart a () = a instance (b ~ Part b, Transformable b) => HasPart () b where part = ($) instance (b ~ Part b, Transformable b) => HasParts () b where parts = ($) type instance Part Int = Int type instance SetPart a Int = a instance HasPart Int Int where part = ($) instance HasParts Int Int where parts = ($) type instance Part Integer = Integer type instance SetPart a Integer = a instance HasPart Integer Integer where part = ($) instance HasParts Integer Integer where parts = ($) type instance Part Float = Float type instance SetPart a Float = a instance HasPart Float Float where part = ($) instance HasParts Float Float where parts = ($) type instance Part (c,a) = Part a type instance SetPart b (c,a) = (c,SetPart b a) type instance Part [a] = Part a type instance SetPart b [a] = [SetPart b a] type instance Part (Maybe a) = Part a type instance SetPart b (Maybe a) = Maybe (SetPart b a) type instance Part (Either c a) = Part a type instance SetPart b (Either c a) = Either c (SetPart b a) type instance Part (Aligned a) = Part a type instance SetPart b (Aligned a) = Aligned (SetPart b a) instance HasParts a b => HasParts (Aligned a) (Aligned b) where parts = _Wrapped . parts instance HasPart a b => HasPart (c, a) (c, b) where part = _2 . part instance HasParts a b => HasParts (c, a) (c, b) where parts = traverse . parts instance HasParts a b => HasParts [a] [b] where parts = traverse . parts instance HasParts a b => HasParts (Maybe a) (Maybe b) where parts = traverse . parts instance HasParts a b => HasParts (Either c a) (Either c b) where parts = traverse . parts type instance Part (Event a) = Part a type instance SetPart g (Event a) = Event (SetPart g a) instance (HasPart a b) => HasPart (Event a) (Event b) where part = from event . whilstL part instance (HasParts a b) => HasParts (Event a) (Event b) where parts = from event . whilstL parts type instance Part (Note a) = Part a type instance SetPart g (Note a) = Note (SetPart g a) instance (HasPart a b) => HasPart (Note a) (Note b) where part = from note . whilstLD part instance (HasParts a b) => HasParts (Note a) (Note b) where parts = from note . whilstLD parts -- | -- List all the parts -- allParts :: (Ord (Part a), HasParts' a) => a -> [Part a] allParts = List.nub . List.sort . toListOf parts -- | -- List all the parts -- extractPart :: (Eq (Part a), HasPart' a) => Part a -> Score a -> Score a extractPart = extractPartG extractPartG :: (Eq (Part a), MonadPlus f, HasPart' a) => Part a -> f a -> f a extractPartG p x = head $ (\p s -> filterPart (== p) s) <$> [p] <*> return x -- | -- List all the parts -- extractParts :: (Ord (Part a), HasPart' a) => Score a -> [Score a] extractParts = extractPartsG extractPartsG :: ( MonadPlus f, HasParts' (f a), HasPart' a, Part (f a) ~ Part a, Ord (Part a) ) => f a -> [f a] extractPartsG x = (\p s -> filterPart (== p) s) <$> allParts x <*> return x filterPart :: (MonadPlus f, HasPart a a) => (Part a -> Bool) -> f a -> f a filterPart p = mfilter (\x -> p (x ^. part)) extractPartsWithInfo :: (Ord (Part a), HasPart' a) => Score a -> [(Part a, Score a)] extractPartsWithInfo x = zip (allParts x) (extractParts x) extracted :: (Ord (Part a), HasPart' a{-, HasPart a b-}) => Iso (Score a) (Score b) [Score a] [Score b] extracted = iso extractParts mconcat extractedWithInfo :: (Ord (Part a), Ord (Part b), HasPart' a, HasPart' b) => Iso (Score a) (Score b) [(Part a, Score a)] [(Part b, Score b)] extractedWithInfo = iso extractPartsWithInfo $ mconcat . fmap (uncurry $ set parts') newtype PartT n a = PartT { getPartT :: (n, a) } deriving (Eq, Ord, Show, Typeable, Functor, Applicative, Comonad, Monad, Transformable) instance Wrapped (PartT p a) where type Unwrapped (PartT p a) = (p, a) _Wrapped' = iso getPartT PartT instance Rewrapped (PartT p a) (PartT p' b) type instance Part (PartT p a) = p type instance SetPart p' (PartT p a) = PartT p' a instance (Transformable p, Transformable p') => HasPart (PartT p a) (PartT p' a) where part = _Wrapped . _1 instance (Transformable p, Transformable p') => HasParts (PartT p a) (PartT p' a) where parts = _Wrapped . _1 instance (IsPitch a, Enum n) => IsPitch (PartT n a) where fromPitch l = PartT (toEnum 0, fromPitch l) instance (IsDynamics a, Enum n) => IsDynamics (PartT n a) where fromDynamics l = PartT (toEnum 0, fromDynamics l) instance Reversible a => Reversible (PartT p a) where rev = fmap rev instance Tiable a => Tiable (PartT n a) where isTieEndBeginning (PartT (_,a)) = isTieEndBeginning a toTied (PartT (v,a)) = (PartT (v,b), PartT (v,c)) where (b,c) = toTied a type instance Part (Behavior a) = Behavior (Part a) type instance SetPart (Behavior g) (Behavior a) = Behavior (SetPart g a) instance (HasPart a a, HasPart a b) => HasParts (Behavior a) (Behavior b) where parts = through part part instance (HasPart a a, HasPart a b) => HasPart (Behavior a) (Behavior b) where part = through part part type instance Part (Score a) = Part a type instance SetPart g (Score a) = Score (SetPart g a) instance (HasParts a b) => HasParts (Score a) (Score b) where parts = _Wrapped . _2 -- into NScore . _Wrapped . traverse . from event -- this needed? . whilstL parts type instance Part (Voice a) = Part a type instance SetPart g (Voice a) = Voice (SetPart g a) instance (HasParts a b) => HasParts (Voice a) (Voice b) where parts = _Wrapped . traverse . _Wrapped -- this needed? . whilstLD parts infixr 6 </> -- | -- Concatenate parts. -- rcat :: (HasParts' a, Enum (Part a)) => [Score a] -> Score a rcat = List.foldr (</>) mempty -- | -- Similar to '<>', but increases parts in the second part to prevent collision. -- (</>) :: (HasParts' a, Enum (Part a)) => Score a -> Score a -> Score a a </> b = a <> moveParts offset b where -- max voice in a + 1 offset = succ $ maximum' 0 $ fmap fromEnum $ toListOf parts a -- | -- Move down one voice (all parts). -- moveParts :: (Integral b, HasParts' a, Enum (Part a)) => b -> Score a -> Score a moveParts x = parts %~ (successor x) -- | -- Move top-part to the specific voice (other parts follow). -- moveToPart :: (Enum b, HasParts' a, Enum (Part a)) => b -> Score a -> Score a moveToPart v = moveParts (fromEnum v) iterating :: (a -> a) -> (a -> a) -> Int -> a -> a iterating f g n | n < 0 = f . iterating f g (n + 1) | n == 0 = id | n > 0 = g . iterating f g (n - 1) successor :: (Integral b, Enum a) => b -> a -> a successor n = iterating pred succ (fromIntegral n) maximum' :: (Ord a, Foldable t) => a -> t a -> a maximum' z = option z getMax . foldMap (Option . Just . Max)
music-suite/music-score
src/Music/Score/Part.hs
Haskell
bsd-3-clause
9,902
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE ViewPatterns #-} -- | Functionality for downloading packages securely for cabal's usage. module Stack.Fetch ( unpackPackages , unpackPackageIdents , fetchPackages , untar , resolvePackages , resolvePackagesAllowMissing , ResolvedPackage (..) , withCabalFiles , withCabalLoader ) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Check as Tar import qualified Codec.Archive.Tar.Entry as Tar import Codec.Compression.GZip (decompress) import Control.Applicative import Control.Concurrent.Async (Concurrently (..)) import Control.Concurrent.MVar.Lifted (modifyMVar, newMVar) import Control.Concurrent.STM import Control.Exception (assert) import Control.Exception.Safe (tryIO) import Control.Monad (join, liftM, unless, void, when) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (ask, runReaderT) import Control.Monad.Trans.Control import Control.Monad.Trans.Unlift (MonadBaseUnlift, askRunBase) import "cryptohash" Crypto.Hash (SHA256 (..)) import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Either (partitionEithers) import qualified Data.Foldable as F import Data.Function (fix) import qualified Data.Git as Git import qualified Data.Git.Ref as Git import qualified Data.Git.Storage as Git import qualified Data.Git.Storage.Object as Git import qualified Data.HashMap.Strict as HashMap import Data.List (intercalate) import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NE import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (maybeToList, catMaybes) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.String (fromString) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import Data.Text.Metrics import Data.Typeable (Typeable) import Data.Word (Word64) import Network.HTTP.Download import Path import Path.Extra (toFilePathNoTrailingSep) import Path.IO import Prelude -- Fix AMP warning import Stack.GhcPkg import Stack.PackageIndex import Stack.Types.BuildPlan import Stack.Types.Config import Stack.Types.PackageIdentifier import Stack.Types.PackageIndex import Stack.Types.PackageName import Stack.Types.Version import System.FilePath ((<.>)) import qualified System.FilePath as FP import System.IO import System.PosixCompat (setFileMode) type PackageCaches = Map PackageIdentifier (PackageIndex, PackageCache) data FetchException = Couldn'tReadIndexTarball FilePath Tar.FormatError | Couldn'tReadPackageTarball FilePath SomeException | UnpackDirectoryAlreadyExists (Set FilePath) | CouldNotParsePackageSelectors [String] | UnknownPackageNames (Set PackageName) | UnknownPackageIdentifiers (Set PackageIdentifier) String deriving Typeable instance Exception FetchException instance Show FetchException where show (Couldn'tReadIndexTarball fp err) = concat [ "There was an error reading the index tarball " , fp , ": " , show err ] show (Couldn'tReadPackageTarball fp err) = concat [ "There was an error reading the package tarball " , fp , ": " , show err ] show (UnpackDirectoryAlreadyExists dirs) = unlines $ "Unable to unpack due to already present directories:" : map (" " ++) (Set.toList dirs) show (CouldNotParsePackageSelectors strs) = "The following package selectors are not valid package names or identifiers: " ++ intercalate ", " strs show (UnknownPackageNames names) = "The following packages were not found in your indices: " ++ intercalate ", " (map packageNameString $ Set.toList names) show (UnknownPackageIdentifiers idents suggestions) = "The following package identifiers were not found in your indices: " ++ intercalate ", " (map packageIdentifierString $ Set.toList idents) ++ (if null suggestions then "" else "\n" ++ suggestions) -- | Fetch packages into the cache without unpacking fetchPackages :: (StackMiniM env m, HasConfig env) => EnvOverride -> Set PackageIdentifier -> m () fetchPackages menv idents' = do resolved <- resolvePackages menv Nothing idents Set.empty ToFetchResult toFetch alreadyUnpacked <- getToFetch Nothing resolved assert (Map.null alreadyUnpacked) (return ()) nowUnpacked <- fetchPackages' Nothing toFetch assert (Map.null nowUnpacked) (return ()) where -- Since we're just fetching tarballs and not unpacking cabal files, we can -- always provide a Nothing Git SHA idents = Map.fromList $ map (, Nothing) $ Set.toList idents' -- | Intended to work for the command line command. unpackPackages :: (StackMiniM env m, HasConfig env) => EnvOverride -> Maybe MiniBuildPlan -- ^ when looking up by name, take from this build plan -> FilePath -- ^ destination -> [String] -- ^ names or identifiers -> m () unpackPackages menv mMiniBuildPlan dest input = do dest' <- resolveDir' dest (names, idents) <- case partitionEithers $ map parse input of ([], x) -> return $ partitionEithers x (errs, _) -> throwM $ CouldNotParsePackageSelectors errs resolved <- resolvePackages menv mMiniBuildPlan (Map.fromList $ map (, Nothing) idents) (Set.fromList names) ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just dest') resolved unless (Map.null alreadyUnpacked) $ throwM $ UnpackDirectoryAlreadyExists $ Set.fromList $ map toFilePath $ Map.elems alreadyUnpacked unpacked <- fetchPackages' Nothing toFetch F.forM_ (Map.toList unpacked) $ \(ident, dest'') -> $logInfo $ T.pack $ concat [ "Unpacked " , packageIdentifierString ident , " to " , toFilePath dest'' ] where -- Possible future enhancement: parse names as name + version range parse s = case parsePackageNameFromString s of Right x -> Right $ Left x Left _ -> case parsePackageIdentifierFromString s of Left _ -> Left s Right x -> Right $ Right x -- | Ensure that all of the given package idents are unpacked into the build -- unpack directory, and return the paths to all of the subdirectories. unpackPackageIdents :: (StackMiniM env m, HasConfig env) => EnvOverride -> Path Abs Dir -- ^ unpack directory -> Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157 -> Map PackageIdentifier (Maybe GitSHA1) -> m (Map PackageIdentifier (Path Abs Dir)) unpackPackageIdents menv unpackDir mdistDir idents = do resolved <- resolvePackages menv Nothing idents Set.empty ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just unpackDir) resolved nowUnpacked <- fetchPackages' mdistDir toFetch return $ alreadyUnpacked <> nowUnpacked data ResolvedPackage = ResolvedPackage { rpIdent :: !PackageIdentifier , rpCache :: !PackageCache , rpIndex :: !PackageIndex , rpGitSHA1 :: !(Maybe GitSHA1) , rpMissingGitSHA :: !Bool } deriving Show -- | Resolve a set of package names and identifiers into @FetchPackage@ values. resolvePackages :: (StackMiniM env m, HasConfig env) => EnvOverride -> Maybe MiniBuildPlan -- ^ when looking up by name, take from this build plan -> Map PackageIdentifier (Maybe GitSHA1) -> Set PackageName -> m [ResolvedPackage] resolvePackages menv mMiniBuildPlan idents0 names0 = do eres <- go case eres of Left _ -> do updateAllIndices menv go >>= either throwM return Right x -> return x where go = r <$> resolvePackagesAllowMissing menv mMiniBuildPlan idents0 names0 r (missingNames, missingIdents, idents) | not $ Set.null missingNames = Left $ UnknownPackageNames missingNames | not $ Set.null missingIdents = Left $ UnknownPackageIdentifiers missingIdents "" | otherwise = Right idents resolvePackagesAllowMissing :: (StackMiniM env m, HasConfig env) => EnvOverride -> Maybe MiniBuildPlan -- ^ when looking up by name, take from this build plan -> Map PackageIdentifier (Maybe GitSHA1) -> Set PackageName -> m (Set PackageName, Set PackageIdentifier, [ResolvedPackage]) resolvePackagesAllowMissing menv mMiniBuildPlan idents0 names0 = do res@(_, _, resolved) <- inner if any rpMissingGitSHA resolved then do $logInfo "Missing some cabal revision files, updating indices" updateAllIndices menv res'@(_, _, resolved') <- inner -- Print an error message if any SHAs are still missing. F.forM_ (filter rpMissingGitSHA resolved') $ \rp -> F.forM_ (rpGitSHA1 rp) $ \(GitSHA1 sha) -> $logWarn $ mconcat [ "Did not find .cabal file for " , T.pack $ packageIdentifierString $ rpIdent rp , " with SHA of " , decodeUtf8 sha , " in tarball-based cache" ] return res' else return res where inner = do (caches, shaCaches) <- getPackageCaches let versions = Map.fromListWith max $ map toTuple $ Map.keys caches getNamed :: PackageName -> Maybe (PackageIdentifier, Maybe GitSHA1) getNamed = case mMiniBuildPlan of Nothing -> getNamedFromIndex Just mbp -> getNamedFromBuildPlan mbp getNamedFromBuildPlan mbp name = do mpi <- Map.lookup name $ mbpPackages mbp Just (PackageIdentifier name (mpiVersion mpi), mpiGitSHA1 mpi) getNamedFromIndex name = fmap (\ver -> (PackageIdentifier name ver, Nothing)) (Map.lookup name versions) (missingNames, idents1) = partitionEithers $ map (\name -> maybe (Left name) Right (getNamed name)) (Set.toList names0) let (missingIdents, resolved) = partitionEithers $ map (goIdent caches shaCaches) $ Map.toList $ idents0 <> Map.fromList idents1 return (Set.fromList missingNames, Set.fromList missingIdents, resolved) goIdent caches shaCaches (ident, mgitsha) = case Map.lookup ident caches of Nothing -> Left ident Just (index, cache) -> let (index', cache', mgitsha', missingGitSHA) = case mgitsha of Nothing -> (index, cache, mgitsha, False) Just gitsha -> case HashMap.lookup gitsha shaCaches of Just (index'', offsetSize) -> ( index'' , cache { pcOffsetSize = offsetSize } -- we already got the info -- about this SHA, don't do -- any lookups later , Nothing , False -- not missing, we found the Git SHA ) Nothing -> (index, cache, mgitsha, case simplifyIndexLocation (indexLocation index) of -- No surprise that there's -- nothing in the cache about -- the SHA, since this package -- comes from a Git -- repo. We'll look it up -- later when we've opened up -- the Git repo itself for -- reading. SILGit _ -> False -- Index using HTTP, so we're missing the Git SHA SILHttp _ _ -> True) in Right ResolvedPackage { rpIdent = ident , rpCache = cache' , rpIndex = index' , rpGitSHA1 = mgitsha' , rpMissingGitSHA = missingGitSHA } data ToFetch = ToFetch { tfTarball :: !(Path Abs File) , tfDestDir :: !(Maybe (Path Abs Dir)) , tfUrl :: !T.Text , tfSize :: !(Maybe Word64) , tfSHA256 :: !(Maybe ByteString) , tfCabal :: !ByteString -- ^ Contents of the .cabal file } data ToFetchResult = ToFetchResult { tfrToFetch :: !(Map PackageIdentifier ToFetch) , tfrAlreadyUnpacked :: !(Map PackageIdentifier (Path Abs Dir)) } -- | Add the cabal files to a list of idents with their caches. withCabalFiles :: (StackMiniM env m, HasConfig env) => IndexName -> [(ResolvedPackage, a)] -> (PackageIdentifier -> a -> ByteString -> IO b) -> m [b] withCabalFiles name pkgs f = do indexPath <- configPackageIndex name mgitRepo <- configPackageIndexRepo name bracket (liftIO $ openBinaryFile (toFilePath indexPath) ReadMode) (liftIO . hClose) $ \h -> let inner mgit = mapM (goPkg h mgit) pkgs in case mgitRepo of Nothing -> inner Nothing Just repo -> bracket (liftIO $ Git.openRepo $ fromString $ toFilePath repo FP.</> ".git") (liftIO . Git.closeRepo) (inner . Just) where goPkg h (Just git) (rp@(ResolvedPackage ident _pc _index (Just (GitSHA1 sha)) _missing), tf) = do let ref = Git.fromHex sha mobj <- liftIO $ tryIO $ Git.getObject git ref True case mobj of Right (Just (Git.ObjBlob (Git.Blob bs))) -> liftIO $ f ident tf (L.toStrict bs) -- fallback when the appropriate SHA isn't found e -> do $logWarn $ mconcat [ "Did not find .cabal file for " , T.pack $ packageIdentifierString ident , " with SHA of " , decodeUtf8 sha , " in the Git repository" ] $logDebug (T.pack (show e)) goPkg h Nothing (rp { rpGitSHA1 = Nothing }, tf) goPkg h _mgit (ResolvedPackage ident pc _index _mgitsha _missing, tf) = do -- Did not find warning for tarballs is handled above let OffsetSize offset size = pcOffsetSize pc liftIO $ do hSeek h AbsoluteSeek $ fromIntegral offset cabalBS <- S.hGet h $ fromIntegral size f ident tf cabalBS -- | Provide a function which will load up a cabal @ByteString@ from the -- package indices. withCabalLoader :: (StackMiniM env m, HasConfig env, MonadBaseUnlift IO m) => EnvOverride -> ((PackageIdentifier -> IO ByteString) -> m a) -> m a withCabalLoader menv inner = do env <- ask -- Want to try updating the index once during a single run for missing -- package identifiers. We also want to ensure we only update once at a -- time -- -- TODO: probably makes sense to move this concern into getPackageCaches updateRef <- liftIO $ newMVar True loadCaches <- getPackageCachesIO runInBase <- liftBaseWith $ \run -> return (void . run) unlift <- askRunBase -- TODO in the future, keep all of the necessary @Handle@s open let doLookup :: PackageIdentifier -> IO ByteString doLookup ident = do (caches, _gitSHACaches) <- loadCaches eres <- unlift $ lookupPackageIdentifierExact ident env caches case eres of Just bs -> return bs -- Update the cache and try again Nothing -> do let fuzzy = fuzzyLookupCandidates ident caches suggestions = case fuzzy of Nothing -> case typoCorrectionCandidates ident caches of Nothing -> "" Just cs -> "Perhaps you meant " <> orSeparated cs <> "?" Just cs -> "Possible candidates: " <> commaSeparated (NE.map packageIdentifierText cs) <> "." join $ modifyMVar updateRef $ \toUpdate -> if toUpdate then do runInBase $ do $logInfo $ T.concat [ "Didn't see " , T.pack $ packageIdentifierString ident , " in your package indices.\n" , "Updating and trying again." ] updateAllIndices menv _ <- getPackageCaches return () return (False, doLookup ident) else return (toUpdate, throwM $ UnknownPackageIdentifiers (Set.singleton ident) (T.unpack suggestions)) inner doLookup lookupPackageIdentifierExact :: (StackMiniM env m, HasConfig env) => PackageIdentifier -> env -> PackageCaches -> m (Maybe ByteString) lookupPackageIdentifierExact ident env caches = case Map.lookup ident caches of Nothing -> return Nothing Just (index, cache) -> do [bs] <- flip runReaderT env $ withCabalFiles (indexName index) [(ResolvedPackage { rpIdent = ident , rpCache = cache , rpIndex = index , rpGitSHA1 = Nothing , rpMissingGitSHA = False }, ())] $ \_ _ bs -> return bs return $ Just bs -- | Given package identifier and package caches, return list of packages -- with the same name and the same two first version number components found -- in the caches. fuzzyLookupCandidates :: PackageIdentifier -> PackageCaches -> Maybe (NonEmpty PackageIdentifier) fuzzyLookupCandidates (PackageIdentifier name ver) caches = let (_, zero, bigger) = Map.splitLookup zeroIdent caches zeroIdent = PackageIdentifier name $(mkVersion "0.0") sameName (PackageIdentifier n _) = n == name sameMajor (PackageIdentifier _ v) = toMajorVersion v == toMajorVersion ver in NE.nonEmpty . filter sameMajor $ maybe [] (pure . const zeroIdent) zero <> takeWhile sameName (Map.keys bigger) -- | Try to come up with typo corrections for given package identifier using -- package caches. This should be called before giving up, i.e. when -- 'fuzzyLookupCandidates' cannot return anything. typoCorrectionCandidates :: PackageIdentifier -> PackageCaches -> Maybe (NonEmpty T.Text) typoCorrectionCandidates ident = let getName = packageNameText . packageIdentifierName name = getName ident in NE.nonEmpty . Map.keys . Map.filterWithKey (const . (== 1) . damerauLevenshtein name) . Map.mapKeys getName -- | Figure out where to fetch from. getToFetch :: (StackMiniM env m, HasConfig env) => Maybe (Path Abs Dir) -- ^ directory to unpack into, @Nothing@ means no unpack -> [ResolvedPackage] -> m ToFetchResult getToFetch mdest resolvedAll = do (toFetch0, unpacked) <- liftM partitionEithers $ mapM checkUnpacked resolvedAll toFetch1 <- mapM goIndex $ Map.toList $ Map.fromListWith (++) toFetch0 return ToFetchResult { tfrToFetch = Map.unions toFetch1 , tfrAlreadyUnpacked = Map.fromList unpacked } where checkUnpacked resolved = do let ident = rpIdent resolved dirRel <- parseRelDir $ packageIdentifierString ident let mdestDir = (</> dirRel) <$> mdest mexists <- case mdestDir of Nothing -> return Nothing Just destDir -> do exists <- doesDirExist destDir return $ if exists then Just destDir else Nothing case mexists of Just destDir -> return $ Right (ident, destDir) Nothing -> do let index = rpIndex resolved d = pcDownload $ rpCache resolved targz = T.pack $ packageIdentifierString ident ++ ".tar.gz" tarball <- configPackageTarball (indexName index) ident return $ Left (indexName index, [(resolved, ToFetch { tfTarball = tarball , tfDestDir = mdestDir , tfUrl = case fmap pdUrl d of Just url | not (S.null url) -> decodeUtf8 url _ -> indexDownloadPrefix index <> targz , tfSize = fmap pdSize d , tfSHA256 = fmap pdSHA256 d , tfCabal = S.empty -- filled in by goIndex })]) goIndex (name, pkgs) = liftM Map.fromList $ withCabalFiles name pkgs $ \ident tf cabalBS -> return (ident, tf { tfCabal = cabalBS }) -- | Download the given name,version pairs into the directory expected by cabal. -- -- For each package it downloads, it will optionally unpack it to the given -- @Path@ (if present). Note that unpacking is not simply a matter of -- untarring, but also of grabbing the cabal file from the package index. The -- destinations should not include package identifiers. -- -- Returns the list of paths unpacked, including package identifiers. E.g.: -- -- @ -- fetchPackages [("foo-1.2.3", Just "/some/dest")] ==> ["/some/dest/foo-1.2.3"] -- @ -- -- Since 0.1.0.0 fetchPackages' :: (StackMiniM env m, HasConfig env) => Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157 -> Map PackageIdentifier ToFetch -> m (Map PackageIdentifier (Path Abs Dir)) fetchPackages' mdistDir toFetchAll = do connCount <- view $ configL.to configConnectionCount outputVar <- liftIO $ newTVarIO Map.empty runInBase <- liftBaseWith $ \run -> return (void . run) parMapM_ connCount (go outputVar runInBase) (Map.toList toFetchAll) liftIO $ readTVarIO outputVar where go :: (MonadIO m,MonadThrow m,MonadLogger m) => TVar (Map PackageIdentifier (Path Abs Dir)) -> (m () -> IO ()) -> (PackageIdentifier, ToFetch) -> m () go outputVar runInBase (ident, toFetch) = do req <- parseUrlThrow $ T.unpack $ tfUrl toFetch let destpath = tfTarball toFetch let toHashCheck bs = HashCheck SHA256 (CheckHexDigestByteString bs) let downloadReq = DownloadRequest { drRequest = req , drHashChecks = map toHashCheck $ maybeToList (tfSHA256 toFetch) , drLengthCheck = fromIntegral <$> tfSize toFetch , drRetryPolicy = drRetryPolicyDefault } let progressSink _ = liftIO $ runInBase $ $logInfo $ packageIdentifierText ident <> ": download" _ <- verifiedDownload downloadReq destpath progressSink identStrP <- parseRelDir $ packageIdentifierString ident F.forM_ (tfDestDir toFetch) $ \destDir -> do let innerDest = toFilePath destDir unexpectedEntries <- liftIO $ untar destpath identStrP (parent destDir) liftIO $ do case mdistDir of Nothing -> return () -- See: https://github.com/fpco/stack/issues/157 Just distDir -> do let inner = parent destDir </> identStrP oldDist = inner </> $(mkRelDir "dist") newDist = inner </> distDir exists <- doesDirExist oldDist when exists $ do -- Previously used takeDirectory, but that got confused -- by trailing slashes, see: -- https://github.com/commercialhaskell/stack/issues/216 -- -- Instead, use Path which is a bit more resilient ensureDir $ parent newDist renameDir oldDist newDist let cabalFP = innerDest FP.</> packageNameString (packageIdentifierName ident) <.> "cabal" S.writeFile cabalFP $ tfCabal toFetch atomically $ modifyTVar outputVar $ Map.insert ident destDir F.forM_ unexpectedEntries $ \(path, entryType) -> $logWarn $ "Unexpected entry type " <> entryType <> " for entry " <> T.pack path -- | Internal function used to unpack tarball. -- -- Takes a path to a .tar.gz file, the name of the directory it should contain, -- and a destination folder to extract the tarball into. Returns unexpected -- entries, as pairs of paths and descriptions. untar :: forall b1 b2. Path b1 File -> Path Rel Dir -> Path b2 Dir -> IO [(FilePath, T.Text)] untar tarPath expectedTarFolder destDirParent = do ensureDir destDirParent withBinaryFile (toFilePath tarPath) ReadMode $ \h -> do -- Avoid using L.readFile, which is more likely to leak -- resources lbs <- L.hGetContents h let rawEntries = fmap (either wrap wrap) $ Tar.checkTarbomb (toFilePathNoTrailingSep expectedTarFolder) $ Tar.read $ decompress lbs filterEntries :: Monoid w => (Tar.Entry -> (Bool, w)) -> Tar.Entries b -> (Tar.Entries b, w) -- Allow collecting warnings, Writer-monad style. filterEntries f = Tar.foldEntries (\e -> let (res, w) = f e in \(rest, wOld) -> ((if res then Tar.Next e else id) rest, wOld <> w)) (Tar.Done, mempty) (\err -> (Tar.Fail err, mempty)) extractableEntry e = case Tar.entryContent e of Tar.NormalFile _ _ -> (True, []) Tar.Directory -> (True, []) Tar.SymbolicLink _ -> (True, []) Tar.HardLink _ -> (True, []) Tar.OtherEntryType 'g' _ _ -> (False, []) Tar.OtherEntryType 'x' _ _ -> (False, []) Tar.CharacterDevice _ _ -> (False, [(path, "character device")]) Tar.BlockDevice _ _ -> (False, [(path, "block device")]) Tar.NamedPipe -> (False, [(path, "named pipe")]) Tar.OtherEntryType code _ _ -> (False, [(path, "other entry type with code " <> T.pack (show code))]) where path = Tar.fromTarPath $ Tar.entryTarPath e (entries, unexpectedEntries) = filterEntries extractableEntry rawEntries wrap :: Exception e => e -> FetchException wrap = Couldn'tReadPackageTarball (toFilePath tarPath) . toException getPerms :: Tar.Entry -> (FilePath, Tar.Permissions) getPerms e = (toFilePath destDirParent FP.</> Tar.fromTarPath (Tar.entryTarPath e), Tar.entryPermissions e) filePerms :: [(FilePath, Tar.Permissions)] filePerms = catMaybes $ Tar.foldEntries (\e -> (:) (Just $ getPerms e)) [] (const []) entries Tar.unpack (toFilePath destDirParent) entries -- Reset file permissions as they were in the tarball, but only -- for extracted entries (whence filterEntries extractableEntry above). -- See https://github.com/commercialhaskell/stack/issues/2361 mapM_ (\(fp, perm) -> setFileMode (FP.dropTrailingPathSeparator fp) perm) filePerms return unexpectedEntries parMapM_ :: (F.Foldable f,MonadIO m,MonadBaseControl IO m) => Int -> (a -> m ()) -> f a -> m () parMapM_ (max 1 -> 1) f xs = F.mapM_ f xs parMapM_ cnt f xs0 = do var <- liftIO (newTVarIO $ F.toList xs0) -- See comment on similar line in Stack.Build runInBase <- liftBaseWith $ \run -> return (void . run) let worker = fix $ \loop -> join $ atomically $ do xs <- readTVar var case xs of [] -> return $ return () x:xs' -> do writeTVar var xs' return $ do runInBase $ f x loop workers 1 = Concurrently worker workers i = Concurrently worker *> workers (i - 1) liftIO $ runConcurrently $ workers cnt orSeparated :: NonEmpty T.Text -> T.Text orSeparated xs | NE.length xs == 1 = NE.head xs | NE.length xs == 2 = NE.head xs <> " or " <> NE.last xs | otherwise = T.intercalate ", " (NE.init xs) <> ", or " <> NE.last xs commaSeparated :: NonEmpty T.Text -> T.Text commaSeparated = F.fold . NE.intersperse ", "
AndreasPK/stack
src/Stack/Fetch.hs
Haskell
bsd-3-clause
31,472
{-# LANGUAGE CPP, QuasiQuotes, TemplateHaskell, TypeFamilies #-} module Settings.StaticFiles where import Yesod.Static import qualified Yesod.Static as Static static :: FilePath -> IO Static #ifdef PRODUCTION static = Static.static #else static = Static.staticDevel #endif -- | This generates easy references to files in the static directory at compile time. -- The upside to this is that you have compile-time verification that referenced files -- exist. However, any files added to your static directory during run-time can't be -- accessed this way. You'll have to use their FilePath or URL to access them. $(staticFiles "static")
samstokes/yesodoro
Settings/StaticFiles.hs
Haskell
bsd-2-clause
644
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} module T15437A where import Language.Haskell.TH.Syntax (Q, TExp) get :: forall a. Int get = 1 foo :: forall a. Q (TExp Int) foo = [|| get @a ||]
sdiehl/ghc
testsuite/tests/th/T15437A.hs
Haskell
bsd-3-clause
252
{- Copyright 2016 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} import Distribution.Simple main = defaultMain
nomeata/codeworld
codeworld-server/Setup.hs
Haskell
apache-2.0
657
{-# LANGUAGE QuasiQuotes #-} module Lib where import QQ val = [myq|hello|]
themoritz/cabal
cabal-testsuite/PackageTests/QuasiQuotes/vanilla/Lib.hs
Haskell
bsd-3-clause
77
{-# LANGUAGE RankNTypes #-} module Rx.Scheduler.SingleThread where import Control.Monad (join, forever) import Control.Concurrent (ThreadId, forkIO, forkOS, killThread, threadDelay, yield) import Control.Concurrent.STM (atomically) import qualified Control.Concurrent.STM.TChan as TChan import Tiempo (toMicroSeconds) import Rx.Disposable ( Disposable, IDisposable(..), ToDisposable(..) , newDisposable, emptyDisposable) import Rx.Scheduler.Types -------------------------------------------------------------------------------- -- ^ A special Scheduler that works on a single thread, this type -- implements both the IScheduler and the IDisposable classtypes. data SingleThreadScheduler s = SingleThreadScheduler { _scheduler :: Scheduler s , _disposable :: Disposable } type Forker = IO () -> IO ThreadId instance IScheduler SingleThreadScheduler where immediateSchedule = immediateSchedule . _scheduler timedSchedule = timedSchedule . _scheduler instance IDisposable (SingleThreadScheduler s) where disposeVerbose = disposeVerbose . _disposable instance ToDisposable (SingleThreadScheduler s) where toDisposable = _disposable -------------------------------------------------------------------------------- _singleThread :: Forker -> IO (SingleThreadScheduler Async) _singleThread fork = do reqChan <- TChan.newTChanIO tid <- fork $ forever $ do join $ atomically $ TChan.readTChan reqChan yield disposable <- newDisposable "Scheduler.singleThread" (killThread tid) let scheduler = Scheduler { _immediateSchedule = \action -> do atomically (TChan.writeTChan reqChan action) emptyDisposable , _timedSchedule = \interval innerAction -> do let action = threadDelay (toMicroSeconds interval) >> innerAction atomically (TChan.writeTChan reqChan action) emptyDisposable } return $ SingleThreadScheduler scheduler disposable -------------------------------------------------------------------------------- -- ^ Creates a @Scheduler@ that performs work on a single unbound -- thread singleThread :: IO (SingleThreadScheduler Async) singleThread = _singleThread forkIO -- ^ Creates a @Scheduler@ that performs work on a single bound -- thread. This is particularly useful when working with async -- actions and FFI calls. singleBoundThread :: IO (SingleThreadScheduler Async) singleBoundThread = _singleThread forkOS
roman/Haskell-Reactive-Extensions
rx-scheduler/src/Rx/Scheduler/SingleThread.hs
Haskell
mit
2,507
-- Arithmetic List! -- http://www.codewars.com/kata/541da001259d9ca85d000688 module SeqList where seqlist :: Int -> Int -> Int -> [Int] seqlist f c l = take l [f, f+c ..]
gafiatulin/codewars
src/7 kyu/SeqList.hs
Haskell
mit
173
module Web.Twitter.LtxBot.Types where import Control.Monad.Reader (ReaderT) import Network.HTTP.Conduit (Manager) import Web.Twitter.Conduit (TWInfo) import Web.Twitter.Types (UserId) data LtxbotEnv = LtxbotEnv { envUserId :: UserId , envTwInfo :: TWInfo , envManager :: Manager } type LTXE m = ReaderT LtxbotEnv m
passy/ltxbot
src/Web/Twitter/LtxBot/Types.hs
Haskell
mit
372
{-# LANGUAGE FlexibleInstances #-} {-| Module : Hate.Math Description : Hate mathematical utilities License : MIT Maintainer : bananu7@o2.pl Stability : provisional Portability : full This module mostly works with primitives from @Data.Vect@, adding some utilities useful in rendering and OpenGL interoperability. -} module Hate.Math ( module Data.Vect.Float , module Hate.Math.Util , module Hate.Math.Types ) where import Data.Vect.Float import Data.Vect.Float.Instances() import Hate.Math.Types import Hate.Math.Util
maque/Hate
src/Hate/Math.hs
Haskell
mit
580
module ParserSpec where import Test.Hspec import Control.Arrow (left) import Text.ParserCombinators.Parsec (Parser) import Parser import VM spec :: Spec spec = describe "instructionsParser" $ do context "with normalInstructionsString" $ it "parses" $ parseTest instructionsParser normalInstructionsString `shouldBe` Right [Push 3, Add, Store 4] context "with commentBetweenLines" $ it "parses" $ parseTest instructionsParser commentBetweenLines `shouldBe` Right [Push 5, Add] context "with labelInstructions" $ it "parsers" $ parseTest instructionsParser labelInstructions `shouldBe` Right [Label "abc", Push 3, JumpIf "abc"] parseTest :: Parser a -> String -> Either String a parseTest p input = left show $ parse p "Spec" input normalInstructionsString :: String normalInstructionsString = "Push 3\nAdd\nStore 4\n" commentBetweenLines :: String commentBetweenLines = "# aaa\nPush 5\n# Add\nAdd\n#Push 5" labelInstructions :: String labelInstructions = "Label abc\nPush 3\nJumpIf abc"
taiki45/hs-vm
test/ParserSpec.hs
Haskell
mit
1,209
{-# LANGUAGE CPP #-} module GHCJS.DOM.Notification ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.Notification #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.Notification #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/Notification.hs
Haskell
mit
349
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Risk where import Control.Monad.Random import Control.Monad import Data.List (sort) ------------------------------------------------------------ -- Die values newtype DieValue = DV { unDV :: Int } deriving (Eq, Ord, Show, Num) first :: (a -> b) -> (a, c) -> (b, c) first f (a, c) = (f a, c) instance Random DieValue where random = first DV . randomR (1,6) randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi)) die :: Rand StdGen DieValue die = getRandom dice :: Int -> Rand StdGen [DieValue] dice n = replicateM n die ------------------------------------------------------------ -- Risk type Army = Int data Battlefield = Battlefield { attackers :: Army, defenders :: Army } deriving (Show) battle :: Battlefield -> Rand StdGen Battlefield battle bf = rollFor bf >>= \rolls -> return $ runBattle bf rolls runBattle :: Battlefield -> [(DieValue, DieValue)] -> Battlefield runBattle (Battlefield att def) rolls = Battlefield att' def' where (att', def') = foldl (\(att', def') (a, d) -> if a > d then (att', def'-1) else (att'-1, def')) (att, def) rolls rollFor :: Battlefield -> Rand StdGen [(DieValue, DieValue)] rollFor bf = let (attArmy, defArmy) = units bf attackerRolls = dice attArmy defenderRolls = dice defArmy in attackerRolls >>= \ar -> defenderRolls >>= \dr -> return $ zip (sort ar) (sort dr) units :: Battlefield -> (Army, Army) units (Battlefield att def) = let att' = if att > 1 then min (att - 1) 3 else 1 def' = min def 2 in (att', def') invade :: Battlefield -> Rand StdGen Battlefield invade bf = battle bf >>= \bf' -> if defenders bf' == 0 || attackers bf' < 2 then return bf' else invade bf' successProb :: Battlefield -> Rand StdGen Double successProb bf = replicateM 1000 (invade bf) >>= success success :: [Battlefield] -> Rand StdGen Double success bfs = return $ fromIntegral attackerWins / fromIntegral (length bfs) where attackerWins = length . filter (== 0) . map defenders $ bfs
tomwadeson/cis194
week12/Risk.hs
Haskell
mit
2,137
{-# LANGUAGE Strict #-} {-# LANGUAGE RecordWildCards #-} module WordEmbedding.HasText.Internal.Strict.Model ( binaryLogistic , computeHidden , getmWI ) where import Control.Monad.Reader import Control.Concurrent import qualified Data.Text as T import Data.Hashable (Hashable) import qualified Data.HashMap.Strict as HS import qualified Data.Vector as V import qualified Data.Vector.Unboxed.Mutable as VUM import qualified Data.Mutable as M import WordEmbedding.HasText.Internal.Strict.HasText (sigmoid) import qualified WordEmbedding.HasText.Internal.Strict.MVectorOps as HMV import WordEmbedding.HasText.Internal.Type ( Params(..) , LParams(..) , Model , MWeights(..) , WordVecRef ) -- | -- The function that update model based on formulas of the objective function and binary label. binaryLogistic :: Bool -- ^ label in Xin's tech report. (If this is True function compute about positive word. If False, negative-sampled word.) -> T.Text -- ^ a updating target word -> Model binaryLogistic label input = do (Params{..}, LParams{..}) <- ask liftIO $ do ws <- takeMVar _wordVecRef let mwo = _mwO (ws HS.! input) score <- sigmoid <$> HMV.sumDotMM mwo _hidden let alpha = _lr * (boolToNum label - score) HMV.foriM_ _grad $ \i e -> do emwo <- VUM.unsafeRead mwo i pure $! e + alpha * emwo HMV.mapi (const (alpha *)) _hidden HMV.addMM mwo _hidden putMVar _wordVecRef ws let minusLog = negate . log $! if label then score else 1.0 - score M.modifyRef' _loss (+ minusLog) where boolToNum = fromIntegral . fromEnum {-# INLINE binaryLogistic #-} computeHidden :: VUM.IOVector Double -> WordVecRef -> V.Vector T.Text -> IO () computeHidden hidden wsRef input = do ws <- readMVar wsRef mapM_ (HMV.addMM hidden) $ V.map (getmWI ws) input HMV.scale invLen hidden where inverse d = 1.0 / fromIntegral d invLen = inverse . V.length $! input {-# INLINE computeHidden #-} getmWI :: (Hashable k, Eq k) => HS.HashMap k MWeights -> k -> VUM.IOVector Double getmWI w k = _mwI $! w HS.! k {-# INLINE getmWI #-}
Nnwww/hastext
src/WordEmbedding/HasText/Internal/Strict/Model.hs
Haskell
mit
2,464
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-} module HCraft.World.Camera ( module HCraft.World.Camera.Camera , updateCamera , getCameraVolume ) where import Control.Applicative import Control.Monad import Control.Monad.Error import Control.Monad.Reader import Data.Bits import Data.List import Graphics.UI.GLFW import Graphics.Rendering.OpenGL hiding (Plane) import HCraft.Engine import HCraft.Math import HCraft.World.Chunk import HCraft.World.Camera.Camera checkCollision :: Vec3 GLfloat -> Vec3 GLfloat -> Engine (Vec3 GLfloat) checkCollision pos@(Vec3 x y z) dir@(Vec3 dx dy dz) = do let xp = x + dx + 0.5 > fromIntegral (ceiling x) yp = y + dy + 0.5 > fromIntegral (ceiling y) zp = z + dz + 0.5 > fromIntegral (ceiling z) xn = x + dx - 0.5 < fromIntegral (floor x) yn = y + dy - 0.5 < fromIntegral (floor y) zn = z + dz - 0.5 < fromIntegral (floor z) Vec3 x' y' z' = floor <$> pos cond = [ ( xp, Vec3 (-1.0) 0.0 0.0, Vec3 (x' + 1) y' z' ) , ( xn, Vec3 1.0 0.0 0.0, Vec3 (x' - 1) y' z' ) , ( zp, Vec3 0.0 0.0 (-1.0), Vec3 x' y' (z' + 1) ) , ( zn, Vec3 0.0 0.0 1.0, Vec3 x' y' (z' - 1) ) , ( yp, Vec3 0.0 (-1.0) 0.0, Vec3 x' (y' + 1) z' ) , ( yn, Vec3 0.0 1.0 0.0, Vec3 x' (y' - 1) z' ) ] test dir ( cond, norm, block ) | not cond = return dir | otherwise = do block <- getBlock block case block of Nothing -> return dir Just _ -> return (dir ^-^ (norm ^*. (norm ^.^ dir))) (pos ^+^) <$> foldM test dir cond updateCamera :: GLfloat -> Engine () updateCamera dt = do EngineState{..} <- ask -- Retrieve input size@(Size w h) <- liftIO $ get windowSize Position mx my <- liftIO $ get mousePos -- Retrieve camera info camera@Camera{..} <- liftIO $ get esCamera let Vec3 rx ry rz = cRotation Vec3 px py pz = cPosition -- Compute new parameters let aspect = fromIntegral w / fromIntegral h dx = fromIntegral (my - (h `shiftR` 1)) * (dt * 0.2) dy = fromIntegral (mx - (w `shiftR` 1)) * (dt * 0.2) rx' = max (min (rx + dx) (pi / 2 - abs dx)) (-pi / 2 + abs dx) ry' = ry - dy rz' = rz dir = Vec3 (sin ry' * cos rx') (sin rx') (cos ry' * cos rx') -- Possible move directions let dirs = [ vinv dir , dir , Vec3{ v3x = sin (ry' - pi / 2) * cos rx' , v3y = 0.0 , v3z = cos (ry' - pi / 2) * cos rx' } , Vec3{ v3x = sin (ry' + pi / 2) * cos rx' , v3y = 0.0 , v3z = cos (ry' + pi / 2) * cos rx' } ] -- Sum up active directions dirs' <- forM (zip [ CharKey 'W', CharKey 'S', CharKey 'A', CharKey 'D' ] dirs) $ \( key, dir ) -> liftIO $ getKey key >>= \status -> return $ case status of Press -> dir Release -> Vec3 0 0 0 let moveDir = foldr1 (^+^) dirs' moveDir' = if vlen moveDir < 0.1 then Vec3 0 0 0 else (moveDir ^/. vlen moveDir) ^*. 0.3 pos <- checkCollision cPosition moveDir' -- Compute new orientation liftIO $ do mousePos $= Position (w `shiftR` 1) (h `shiftR` 1) esCamera $= camera { cPosition = pos , cRotation = Vec3 rx' ry' rz' , cDirection = dir , cProjMat = mat4Persp (pi / 4) aspect cNearPlane cFarPlane , cViewMat = mat4LookAt pos (pos ^+^ dir) (Vec3 0 1 0) , cSkyMat = mat4LookAt vzero dir (Vec3 0 1 0) , cAspect = aspect } getCameraVolume :: Camera -> Frustum getCameraVolume Camera{..} = Frustum . map pnorm $ [ Plane (Vec3 (m3 + m2) (m7 + m6) (m11 + m10)) (m15 + m14) , Plane (Vec3 (m3 - m2) (m7 - m6) (m11 - m10)) (m15 - m14) , Plane (Vec3 (m3 - m1) (m7 - m5) (m11 - m9)) (m15 - m13) , Plane (Vec3 (m3 + m1) (m7 + m5) (m11 + m9)) (m15 + m13) , Plane (Vec3 (m3 + m0) (m7 + m4) (m11 + m8)) (m15 + m12) , Plane (Vec3 (m3 - m0) (m7 - m4) (m11 - m8)) (m15 - m12) ] where Mat4 c0 c1 c2 c3 = cProjMat |*| cViewMat Vec4 m0 m4 m8 m12 = c0 Vec4 m1 m5 m9 m13 = c1 Vec4 m2 m6 m10 m14 = c2 Vec4 m3 m7 m11 m15 = c3
nandor/hcraft
HCraft/World/Camera.hs
Haskell
mit
4,295
module Main where import Test.DocTest import System.Process main :: IO () main = do files <- lines <$> readProcess "find" ["src", "-type", "f", "-name", "*.hs"] [] doctest $ [] ++ files
namikingsoft/nlp100knock
test/DocTest.hs
Haskell
mit
192
data Fruit = Apple | Orange apple :: String apple = "apple" orange :: String orange = "orange" whichFrucit :: String -> Fruit --whichFrucit f = case f of -- apple -> Apple -- orange -> Orange -- --whichFrucit apple = Apple --whichFrucit orange = Orange whichFrucit "apple" = Apple whichFrucit "orange" = Orange
EricYT/real-world
src/chapter-3/BogusPattern.hs
Haskell
apache-2.0
352
-- This is the main configuration file for Propellor, and is used to build -- the propellor program. import Propellor import Propellor.CmdLine import Propellor.Property.Scheduled import qualified Propellor.Property.File as File import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.Network as Network --import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Cron as Cron --import qualified Propellor.Property.Sudo as Sudo import qualified Propellor.Property.User as User --import qualified Propellor.Property.Hostname as Hostname --import qualified Propellor.Property.Tor as Tor import qualified Propellor.Property.Docker as Docker main :: IO () main = defaultMain hosts -- The hosts propellor knows about. -- Edit this to configure propellor! hosts :: [Host] hosts = [ host "mybox.example.com" & os (System (Debian Unstable) "amd64") & Apt.stdSourcesList & Apt.unattendedUpgrades & Apt.installed ["etckeeper"] & Apt.installed ["ssh"] & User.hasSomePassword (User "root") & Network.ipv6to4 & File.dirExists "/var/www" & Docker.docked webserverContainer & Docker.garbageCollected `period` Daily & Cron.runPropellor (Cron.Times "30 * * * *") -- add more hosts here... --, host "foo.example.com" = ... ] -- A generic webserver in a Docker container. webserverContainer :: Docker.Container webserverContainer = Docker.container "webserver" (Docker.latestImage "debian") & os (System (Debian (Stable "jessie")) "amd64") & Apt.stdSourcesList & Docker.publish "80:80" & Docker.volume "/var/www:/var/www" & Apt.serviceInstalledRunning "apache2"
sjfloat/propellor
config-simple.hs
Haskell
bsd-2-clause
1,630
{-# LANGUAGE DeriveDataTypeable #-} module HEP.Parser.StdHep.ProgType where import System.Console.CmdArgs data HsStdHep = Test deriving (Show,Data,Typeable) test :: HsStdHep test = Test mode = modes [test]
wavewave/HsStdHep
lib/HEP/Parser/StdHep/ProgType.hs
Haskell
bsd-2-clause
229
{-# LANGUAGE PackageImports #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} module Propellor.Types.Core where import Propellor.Types.Info import Propellor.Types.OS import Propellor.Types.Result import Data.Monoid import "mtl" Control.Monad.RWS.Strict import Control.Monad.Catch import Control.Applicative import Prelude -- | Everything Propellor knows about a system: Its hostname, -- properties and their collected info. data Host = Host { hostName :: HostName , hostProperties :: [ChildProperty] , hostInfo :: Info } deriving (Show, Typeable) -- | Propellor's monad provides read-only access to info about the host -- it's running on, and a writer to accumulate EndActions. newtype Propellor p = Propellor { runWithHost :: RWST Host [EndAction] () IO p } deriving ( Monad , Functor , Applicative , MonadReader Host , MonadWriter [EndAction] , MonadIO , MonadCatch , MonadThrow , MonadMask ) class LiftPropellor m where liftPropellor :: m a -> Propellor a instance LiftPropellor Propellor where liftPropellor = id instance LiftPropellor IO where liftPropellor = liftIO -- | When two actions are appended together, the second action -- is only run if the first action does not fail. instance Monoid (Propellor Result) where mempty = return NoChange mappend x y = do rx <- x case rx of FailedChange -> return FailedChange _ -> do ry <- y return (rx <> ry) -- | An action that Propellor runs at the end, after trying to satisfy all -- properties. It's passed the combined Result of the entire Propellor run. data EndAction = EndAction Desc (Result -> Propellor Result) type Desc = String -- | Props is a combination of a list of properties, with their combined -- metatypes. data Props metatypes = Props [ChildProperty] -- | Since there are many different types of Properties, they cannot be put -- into a list. The simplified ChildProperty can be put into a list. data ChildProperty = ChildProperty Desc (Maybe (Propellor Result)) Info [ChildProperty] instance Show ChildProperty where show p = "property " ++ show (getDesc p) class IsProp p where setDesc :: p -> Desc -> p getDesc :: p -> Desc getChildren :: p -> [ChildProperty] addChildren :: p -> [ChildProperty] -> p -- | Gets the info of the property, combined with all info -- of all children properties. getInfoRecursive :: p -> Info -- | Info, not including info from children. getInfo :: p -> Info -- | Gets a ChildProperty representing the Property. -- You should not normally need to use this. toChildProperty :: p -> ChildProperty -- | Gets the action that can be run to satisfy a Property. -- You should never run this action directly. Use -- 'Propellor.EnsureProperty.ensureProperty` instead. getSatisfy :: p -> Maybe (Propellor Result) instance IsProp ChildProperty where setDesc (ChildProperty _ a i c) d = ChildProperty d a i c getDesc (ChildProperty d _ _ _) = d getChildren (ChildProperty _ _ _ c) = c addChildren (ChildProperty d a i c) c' = ChildProperty d a i (c ++ c') getInfoRecursive (ChildProperty _ _ i c) = i <> mconcat (map getInfoRecursive c) getInfo (ChildProperty _ _ i _) = i toChildProperty = id getSatisfy (ChildProperty _ a _ _) = a
ArchiveTeam/glowing-computing-machine
src/Propellor/Types/Core.hs
Haskell
bsd-2-clause
3,285
{-# LANGUAGE DeriveGeneric #-} module App.Roster.Types ( TeamRoster(..) , current , next , addPersonToRoster , increaseRosterIndex , decreaseRosterIndex , replaceInCurrent , replaceInNext) where import App.Roster.RosterGeneration (generateNextRoster, generatePreviousRoster) import App.Helper.Lists (replaceElem) import Data.Aeson (FromJSON, ToJSON) import Data.List import GHC.Generics data TeamRoster = TeamRoster { teamName :: String , currentRoster :: [(String,String)] , nextRoster :: [(String,String)] , pairIndex :: Int } deriving ( Generic, Show ) instance ToJSON TeamRoster instance FromJSON TeamRoster instance Eq TeamRoster where TeamRoster n1 _ _ _ == TeamRoster n2 _ _ _ = n1 == n2 -- Functions on TeamRoster current :: TeamRoster -> (String, String) current roster = let pairs = safeCurrentRoster roster idx = pairIndex roster in pairs !! idx -- TODO dont use !!. It's risky. addPersonToRoster :: TeamRoster -> String -> TeamRoster addPersonToRoster roster personName = case findOddPair $ currentRoster roster of Just oddPair -> let updatedPair = replaceEmpty oddPair personName updatedRoster = updatePair oddPair updatedPair roster newNext = generateNextRoster $ currentRoster updatedRoster in updatedRoster {nextRoster = newNext} Nothing -> let newCurrent = (currentRoster roster)++[(personName, "")] newNext = generateNextRoster $ newCurrent in roster {currentRoster = newCurrent, nextRoster = newNext} replaceInCurrent :: TeamRoster -> String -> String -> TeamRoster replaceInCurrent roster oldName newName | oldName == fst (current roster) = let newCurrent = (newName, snd (current roster)) oldCurrent = current roster in updatePair oldCurrent newCurrent roster | oldName == snd (current roster) = let newCurrent = (fst (current roster), newName) oldCurrent = current roster in updatePair oldCurrent newCurrent roster | otherwise = roster replaceInNext :: TeamRoster -> String -> String -> TeamRoster replaceInNext roster oldName newName | oldName == fst (next roster) = let newVal = (newName, snd (next roster)) oldVal = next roster in updatePair oldVal newVal roster | oldName == snd (next roster) = let newVal = (fst (next roster), newName) oldVal = next roster in updatePair oldVal newVal roster | otherwise = roster next :: TeamRoster -> (String, String) next roster = let idx = 1 + pairIndex roster in getPair idx roster increaseRosterIndex :: TeamRoster -> TeamRoster increaseRosterIndex roster | (pairIndex roster) + 1 < lengthCurrentRoster roster = roster {pairIndex = (pairIndex roster) + 1} | otherwise = calculateNextRoster roster decreaseRosterIndex :: TeamRoster -> TeamRoster decreaseRosterIndex roster | (pairIndex roster) - 1 >= 0 = roster {pairIndex = (pairIndex roster) - 1} | otherwise = calculatePreviousRoster roster -- PRIVATE updatePair :: (String, String) -> (String, String) -> TeamRoster -> TeamRoster updatePair old new roster = let newCurrent = replaceElem old new (currentRoster roster) newNext = replaceElem old new (nextRoster roster) in roster {currentRoster = newCurrent, nextRoster = newNext} calculateNextRoster :: TeamRoster -> TeamRoster calculateNextRoster roster = let newCurrent = nextRoster roster newNext = generateNextRoster newCurrent in roster {currentRoster = newCurrent, nextRoster = newNext, pairIndex = 0} calculatePreviousRoster :: TeamRoster -> TeamRoster calculatePreviousRoster roster = let newNext = currentRoster roster newCurrent = generatePreviousRoster $ newNext newIdx = (lengthCurrentRoster roster) - 1 in roster {currentRoster = newCurrent, nextRoster = newNext, pairIndex = newIdx} getPair :: Int -> TeamRoster -> (String, String) getPair idx roster | idx < lengthCurrentRoster roster = (safeCurrentRoster roster) !! idx -- TODO dont use !!. It's risky. | otherwise = (safeNextRoster roster) !! (idx - (lengthCurrentRoster roster)) lengthCurrentRoster :: TeamRoster -> Int lengthCurrentRoster roster = length (safeCurrentRoster roster) filterOutEmpty :: [(String, String)] -> [(String, String)] filterOutEmpty list = let nonEmpty (s1, s2) = s1 /= "" && s2 /= "" in filter nonEmpty list findOddPair :: [(String, String)] -> Maybe (String, String) findOddPair list = let oddPair (s1, s2) = s1 == "" || s2 == "" in find oddPair list -- Current roster with no empty tuples safeCurrentRoster :: TeamRoster -> [(String, String)] safeCurrentRoster roster = filterOutEmpty $ currentRoster roster safeNextRoster :: TeamRoster -> [(String, String)] safeNextRoster roster = filterOutEmpty $ nextRoster roster replaceEmpty :: (String, String) -> String -> (String, String) replaceEmpty pair pName | "" == fst pair = (pName, snd pair) | "" == snd pair = ((fst pair), pName) | otherwise = pair
afcastano/cafe-duty
src/App/Roster/Types.hs
Haskell
bsd-3-clause
6,268
{-# LANGUAGE TemplateHaskell #-} import Data.Angle import Debug.Trace import Lib import Object (Point(..), Vector(..), Ray(..), march, distanceFrom', Form(..)) import qualified Params import qualified System.Random as Random import Test.QuickCheck (quickCheck, quickCheckAll, (==>)) import qualified Test.QuickCheck as T import Triple import Util tolerance :: Double tolerance = 1e-8 (~=) :: Double -> Double -> Bool (~=) = aeq tolerance (^~=) :: Vec3 -> Vec3 -> Bool (^~=) = vecAeq tolerance propCross1 :: Vec3 -> Vec3 -> T.Property propCross1 v1 v2 = not (any ((0 ~=) . norm2) [v1, v2]) ==> ((v1 `dot` crossProduct) ~= 0) && ((v2 `dot` crossProduct) ~= 0) where crossProduct = v1 `cross` v2 propCross2 :: Vec3 -> Bool propCross2 v = 0 `cross` v ^~= pure 0 && v `cross` 0 ^~= pure 0 propNorm2 :: Bool propNorm2 = norm2 (Triple 3 4 5) ~= 7.0710678118654755 propNormalize1 :: Vec3 -> T.Property propNormalize1 vec = not (norm2 vec ~= 0) ==> norm2 (normalize vec) ~= 1 && x ~= y && y ~= z where Triple x y z = vec / (normalize vec) propNormalize2 :: Bool propNormalize2 = norm2 (normalize $ Triple 0 0 0) == 0 sphericalRelations :: Double -> Double -> Double -> Double -> Double -> Degrees Double -> Degrees Double -> Bool sphericalRelations x y z x' y' theta phi = x' ~= cosine phi && y' ~= sine phi && (y / x) ~= tangent phi && ((x ** 2) + (y ** 2)) ~= ((sine theta) ** 2) && z ~= cosine theta && (((x ** 2) + (y ** 2)) / (z ** 2)) ~= ((tangent theta) ** 2) propToSpherical1 :: Vec3 -> T.Property propToSpherical1 vec3 = not (norm2 vec3 ~= 0) ==> sphericalRelations x y z x' y' theta phi where Triple x y z = normalize vec3 Triple x' y' _ = normalize $ Triple x y 0 (theta, phi) = toSphericalCoords vec3 propFromSpherical1 :: Double -> Double -> T.Property propFromSpherical1 theta phi = all ((0, False, 180, True) `contains`) [theta, phi] ==> sphericalRelations x y z x' y' theta' phi' where [theta', phi'] = map Degrees [theta, phi] Triple x y z = fromSphericalCoords theta' phi' :: Vec3 Triple x' y' _ = normalize $ Triple x y 0 propFromSpherical2 :: Bool propFromSpherical2 = fromSphericalCoords 0 0 ^~= Triple 0 0 1 propToSpherical2 :: Bool propToSpherical2 = not $ any isNaN [phi, theta] where (Degrees phi, Degrees theta) = toSphericalCoords (pure 0) propSpherical1 :: Double -> Double -> T.Property propSpherical1 theta phi = (0, False, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> Degrees theta ~= theta' && Degrees phi ~= phi' where (~=) = aeq 1e-13 (theta', phi') = toSphericalCoords $ fromSphericalCoords (Degrees theta) (Degrees phi) propSpherical2 :: Vec3 -> T.Property propSpherical2 vec = not (norm2 vec ~= 0) ==> (normalize vec) ^~= vec' where (theta, phi) = toSphericalCoords vec vec' = fromSphericalCoords theta phi propRotateAbs1 :: Double -> Double -> T.Property propRotateAbs1 theta phi = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> (rotateAbs (Triple 0 0 1) theta' phi') ^~= (fromSphericalCoords theta' phi') where [theta', phi'] = map Degrees [theta, phi] propRotateAbs2 :: Double -> Double -> Vec3 -> T.Property propRotateAbs2 theta phi vector = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> norm2 vector ~= norm2 vector' where [theta', phi'] = map Degrees [theta, phi] vector' = rotateAbs vector theta' phi' propRotateAbs3 :: Double -> Double -> Vec3 -> Vec3 -> T.Property propRotateAbs3 theta phi vector1 vector2 = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi ==> (vector1 `dot` vector2) ~= (vector1' `dot` vector2') where [theta', phi'] = map Degrees [theta, phi] [vector1', vector2'] = map (\v -> rotateAbs v theta' phi') [vector1, vector2] propRotateRel :: Double -> Double -> Vec3 -> T.Property propRotateRel theta phi vector = (0, True, 180, True) `contains` theta && (0, True, 360, True) `contains` phi && not (norm2 vector ~= 0) ==> cosine theta' ~= (normalize vector `dot` normalize vector') where [theta', phi'] = map Degrees [theta, phi] vector' = rotateRel theta' phi' vector propSpecular :: Vec3 -> Vec3 -> T.Property propSpecular vector normal = not (any ((0 ~=) . norm2) [vector, normal]) ==> -- angle of incidence equals angle of reflection (normalize (-vector) `dot` normalize normal) ~= (normalize vector' `dot` normalize normal) && (projOntoSurface vector) ^~= (projOntoSurface vector') where (vector', _) = specular (Random.mkStdGen 0) 0 vector normal normal' = normalize normal projOntoSurface v = v - fmap (v `dot` normal' *) normal' defaultRay = Ray { _origin = Point $ pure 0 , _vector = Vector $ pure 0 , _gen = Random.mkStdGen 0 , _lastStruck = Nothing } propDistanceFrom' :: Vec3 -> Vec3 -> Vec3 -> Vec3 -> T.Property propDistanceFrom' origin vector normal point = not (any ((0 ~=) . norm2) [origin, vector, normal, point]) ==> (intersection - point) `dot` normal ~= 0 where intersection = march ray distance ray = defaultRay {_origin = Point origin, _vector = Vector vector} Just distance = distanceFrom' ray $ InfinitePlane (Point point) (Vector normal) propRandomRangeList :: Float -> Float -> Float -> Float -> Int -> T.Property propRandomRangeList l1 h1 l2 h2 seed = l1 > h1 && l2 > h2 ==> fst (randomRangeList gen [(l1, h1), (l2, h2)]) == [o1, o2] where gen = Random.mkStdGen seed (o1, gen') = Random.randomR (l1, h1) gen :: (Float, Random.StdGen) (o2, gen'') = Random.randomR (l2, h2) gen' :: (Float, Random.StdGen) main = do putStrLn "propCross1" quickCheck propCross1 putStrLn "propCross2" quickCheck propCross2 putStrLn "propRandomRangeList" quickCheck propRandomRangeList putStrLn "propDistanceFrom'" quickCheck propDistanceFrom' putStrLn "propNormalize1" quickCheck propNormalize1 putStrLn "propRotateAbs1" quickCheck propRotateAbs1 putStrLn "propRotateAbs2" quickCheck propRotateAbs2 putStrLn "propRotateAbs3" quickCheck propRotateAbs3 putStrLn "propRotateRel" quickCheck propRotateRel putStrLn "propSpherical1" quickCheck propSpherical1 putStrLn "propSpherical2" quickCheck propSpherical2 putStrLn "propToSpherical1" quickCheck propToSpherical1 putStrLn "propToSpherical2" quickCheck propToSpherical2 putStrLn "propFromSpherical1" quickCheck propFromSpherical1 putStrLn "propFromSpherical2" quickCheck propFromSpherical2 putStrLn "propSpecular" quickCheck propSpecular -- one offs putStrLn "propNorm2" quickCheck propNorm2 putStrLn "propNormalize2" quickCheck propNormalize2
lobachevzky/pathtracer
test/Spec.hs
Haskell
bsd-3-clause
6,754
module Sexy.Classes.Functor (Functor(..)) where class Functor f where (<$>) :: (a -> b) -> f a -> f b (<$) :: a -> f b -> f a a <$ fb = (\_ -> a) <$> fb
DanBurton/sexy
src/Sexy/Classes/Functor.hs
Haskell
bsd-3-clause
161
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE GADTs #-} module GDAL.Plugin.Compiler ( CompilerConfig (..) , Compiler , Result (..) , startCompilerWith , startCompiler , stopCompiler , compile -- * Re-exports , HscTarget (..) , def ) where import Control.Concurrent import Control.Exception ( SomeException ) import Control.Monad (void, forever) import Control.Monad.IO.Class ( MonadIO (..) ) import Data.Char (isDigit) import Data.Text (Text) import Data.String (fromString) import qualified Data.Text.Lazy as LT import Data.Text.Lazy.Builder (Builder, toLazyText) import Data.IORef (IORef, newIORef, writeIORef, readIORef, modifyIORef) import Data.Typeable (Typeable, typeOf) import Data.Monoid (mempty, mappend) import Data.Default (Default(..)) import GHC hiding (importPaths) import GHC.Paths (libdir) import ErrUtils as GHC import Exception ( ExceptionMonad, gtry, gmask ) import Outputable as GHC hiding (parens) import DynFlags as GHC import GHC.Exts (unsafeCoerce#) data Compiler = Compiler { compilerTid :: ThreadId , compilerChan :: Chan Request } data CompilerConfig = CompilerConfig { cfgLibdir :: FilePath , cfgImports :: [String] , cfgSearchPath :: [FilePath] , cfgOptions :: [String] , cfgSafeModeOn :: Bool , cfgVerbosity :: Int , cfgBuildDir :: FilePath , cfgTarget :: HscTarget } deriving Show instance Default CompilerConfig where def = CompilerConfig { cfgLibdir = libdir , cfgImports = [] , cfgSearchPath = ["."] , cfgOptions = defaultGhcOptions , cfgSafeModeOn = True , cfgVerbosity = 0 , cfgBuildDir = "gdal-hs-build" , cfgTarget = HscAsm } data Request where Compile :: forall a. Typeable a => [String] -> String -> MVar (Result a) -> Request type CompilerMessages = Text data Result a = Success a CompilerMessages | Failure SomeException CompilerMessages deriving Show startCompiler :: IO Compiler startCompiler = startCompilerWith def startCompilerWith :: CompilerConfig -> IO Compiler startCompilerWith cfg = do chan <- newChan tid <- forkIO (compilerThread chan cfg) return (Compiler tid chan) stopCompiler :: Compiler -> IO () stopCompiler = killThread . compilerTid compile :: forall a. Typeable a => Compiler -> [String] -> String -> IO (Result a) compile comp targets code = do resRef <- newEmptyMVar writeChan (compilerChan comp) (Compile targets code resRef) takeMVar resRef compilerThread :: Chan Request -> CompilerConfig -> IO () compilerThread chan cfg = do logRef <- newIORef mempty runGhc (Just (cfgLibdir cfg)) $ do dflags <- getSessionDynFlags let dflags' = (if not isInterpreted && GHC.dynamicGhc then addOptl "-lHSrts_thr-ghc8.2.1" --FIXME: Avoid hard-code . dynamicTooMkDynamicDynFlags else id) $ dflags { mainFunIs = Nothing , safeHaskell = if cfgSafeModeOn cfg then Sf_Safe else Sf_None , ghcLink = LinkInMemory , ghcMode = CompManager , hscTarget = cfgTarget cfg , ways = ways dflags ++ [WayThreaded | not isInterpreted] , importPaths = cfgSearchPath cfg , log_action = mkLogHandler logRef , verbosity = cfgVerbosity cfg , objectDir = Just (cfgBuildDir cfg) , stubDir = Just (cfgBuildDir cfg) , hiDir = Just (cfgBuildDir cfg) } isInterpreted = cfgTarget cfg == HscInterpreted setGhcOptions dflags' (cfgOptions cfg) forever $ do req <- liftIO (readChan chan) case req of Compile targets code resRef -> gmask $ \restore -> do -- gmask to make sure we're not interrupted before putting the result -- in the mvar so the requester does not hang (or throw a -- "blocked indefinetely on an mvar" exception) (eRes, msgs) <- capturingMessages logRef restore $ compileTargets cfg targets code liftIO . putMVar resRef $ case eRes of Right r -> Success r msgs Left e -> Failure e msgs capturingMessages :: (MonadIO m, ExceptionMonad m) => IORef Builder -> (m a -> m a) -> m a -> m (Either SomeException a, CompilerMessages) capturingMessages logRef restore act = do r <- gtry (restore act) liftIO $ do msgs <- LT.toStrict . toLazyText <$> readIORef logRef writeIORef logRef mempty return (r, msgs) defaultGhcOptions :: [String] defaultGhcOptions = [ "-fwarn-incomplete-patterns" , "-fwarn-incomplete-uni-patterns" , "-funbox-strict-fields" , "-Wall" , "-O" --, "-fexpose-all-unfoldings" --, "-funfolding-use-threshold500" --, "-funfolding-keeness-factor500" ] compileTargets :: forall a. Typeable a => CompilerConfig -> [String] -> String -> Ghc a compileTargets cfg targets code = do liftIO rts_revertCAFs -- make sure old modules can be unloaded setTargets =<< mapM (`guessTarget` Nothing) targets void $ load LoadAllTargets importModules (cfgImports cfg ++ targets) unsafeCoerce# <$> compileExpr (parens code ++ " :: " ++ show (typeOf (undefined :: a))) importModules:: [String] -> Ghc () importModules = GHC.setContext . map (GHC.IIDecl . import_) where import_ name = ( GHC.simpleImportDecl . GHC.mkModuleName $ name ) { GHC.ideclQualified = False } -- -- |stolen from hint parens :: String -> String parens s = concat ["(let {", foo, " =\n", s, "\n;} in ", foo, ")"] where foo = "e_1" ++ filter isDigit s mkLogHandler :: IORef Builder -> DynFlags -> t -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO () mkLogHandler r df _ severity src style msg = let renderErrMsg = GHC.showSDoc df errorEntry = mkGhcError renderErrMsg severity src style msg in modifyIORef r (`mappend` mappend errorEntry "\n") mkGhcError :: (GHC.SDoc -> String) -> GHC.Severity -> GHC.SrcSpan -> GHC.PprStyle -> GHC.MsgDoc -> Builder mkGhcError render severity src_span style msg = fromString niceErrMsg where niceErrMsg = render . GHC.withPprStyle style $ GHC.mkLocMessage severity src_span msg addOptl :: String -> DynFlags -> DynFlags addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s}) alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags alterSettings f dflags = dflags { settings = f (settings dflags) } setGhcOptions :: DynFlags -> [String] -> Ghc () setGhcOptions old_flags opts = do (new_flags,_not_parsed) <- pdf old_flags opts void $ GHC.setSessionDynFlags (updateWays new_flags) where pdf d = fmap firstTwo . GHC.parseDynamicFlags d . map GHC.noLoc firstTwo (a,b,_) = (a, map GHC.unLoc b) foreign import ccall "revertCAFs" rts_revertCAFs :: IO ()
meteogrid/gdal-plugin-hs
src/GDAL/Plugin/Compiler.hs
Haskell
bsd-3-clause
7,293
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} module Main where import Control.Applicative hiding (empty) import Control.Monad.Reader -- import Data.Generics.PlateData import System.Console.CmdArgs import System.Environment import System.IO import Text.Keepalived main :: IO () main = do n <- getProgName m <- cmdArgs (n ++ " version 0.0.1") [verify, dump] v <- verbosity runApp mainApp (AppConf m v) -- * Application types newtype App a = App { runA :: ReaderT AppConf IO a } deriving (Functor, Monad, MonadIO, MonadReader AppConf) data AppConf = AppConf { appMode :: KcMode , appVerb :: Verbosity } deriving Show runApp :: App a -> AppConf -> IO a runApp a = runReaderT (runA a) . fillInFiles where fillInFiles (AppConf m v) | files m == [] = AppConf (m { files = ["/etc/keepalived/keepalived.conf"] }) v | otherwise = AppConf m v -- * App implementations mainApp :: App () mainApp = do m <- asks appMode case m of Verify _ -> verifyApp Dump _ -> dumpApp -- Search _ _ -> searchApp -- List _ _ -> listApp verifyApp :: App () verifyApp = do m <- asks appMode parseApp (files m) msg (hPutStr stderr "lexical/syntactic verification: ") >> okApp dumpApp :: App () dumpApp = do AppConf m _ <- local (\c -> c { appVerb = Verbose }) ask parseApp (files m) >>= msg . mapM_ print {- TODO searchApp :: App () searchApp = do m <- asks appMode cs <- parseApp (files m) case target m of VRID _ -> const noopApp cs VIP _ -> const noopApp cs _ -> const noopApp cs listApp :: App () listApp = do m <- asks appMode cs <- parseApp (files m) case target m of VRID _ -> const noopApp cs VIP _ -> const noopApp cs _ -> const noopApp cs listVRID :: Data a => a -> [(Vrid, [Ipaddress])] listVRID x = [ (vrid vi, virtualIpaddress vi ++ virtualIpaddressExcluded vi) | TVrrpInstance vi <- universeBi x ] listVIP :: Data a => a -> [Ipaddress] listVIP x = concat [ virtualIpaddress vi ++ virtualIpaddressExcluded vi | TVrrpInstance vi <- universeBi x ] -} noopApp :: App () noopApp = return () -- * Util Apps parseApp :: [FilePath] -> App [KeepalivedConf] parseApp fs = do c <- forM fs $ \f -> do msg $ hPutStrLn stderr $ "parsing " ++ f liftIO $ parseFromFile f verbMsg $ mapM_ print c return c msg :: IO a -> App () msg io = do v <- asks appVerb case v of Quiet -> return () _ -> liftIO io >> return () verbMsg :: IO a -> App () verbMsg io = do v <- asks appVerb case v of Verbose -> liftIO io >> return () _ -> return () okApp :: App () okApp = msg $ hPutStrLn stderr "OK" -- * Command-line parameters data KcMode = Verify { files :: [FilePath] } | Dump { files :: [FilePath] } -- | Search { files :: [FilePath], target :: Target } -- | List { files :: [FilePath], target :: Target } deriving (Data, Typeable, Show, Eq) data Target = VRID Int | VIP String | RIP String deriving (Data, Typeable, Show, Eq) verify :: Mode KcMode verify = mode $ Verify { files = def &= args } &= text "Verify configuration files." & defMode dump :: Mode KcMode dump = mode $ Dump { files = def &= args } &= text "Dump configuration files." {- TODO search :: Mode KcMode search = mode $ Search { target = enum (VRID def) [ VRID def &= text "Search VRID (0-255)" , VIP "192.168.0.1" &= text "Search virtual IP addresses" , RIP "192.168.0.1" &= text "Search real IP addresses" ] , files = defConf &= typFile & args } &= text "Search (VRID|VIP|RIP) from configuration files." list :: Mode KcMode list = mode $ List { target = enum (VRID def) [ VRID def &= text "List VRID (0-255)" , VIP "192.168.0.1" &= text "List virtual IP addresses" , RIP "192.168.0.1" &= text "List real IP addresses" ] , files = defConf &= typFile & args } &= text "List (VRID|VIP|RIP) from configuration files." -} data Verbosity = Quiet | Normal | Verbose deriving (Show, Eq, Ord, Enum) verbosity :: IO Verbosity verbosity = do norm <- fromEnum <$> isNormal loud <- fromEnum <$> isLoud return $ toEnum $ norm + loud
maoe/kc
Kc.hs
Haskell
bsd-3-clause
4,460
module HVX.Internal.Matrix ( Mat , allMat , anyMat , diagMat , ei , fpequalsMat , lpnorm , matrixPow , reduceMat , scalarMat , zeroMat , zeroVec ) where import Numeric.LinearAlgebra import HVX.Internal.Util type Mat = Matrix Double allMat :: (Double -> Bool) -> Mat -> Bool allMat f x = all f (toList . flatten $ x) anyMat :: (Double -> Bool) -> Mat -> Bool anyMat f x = any f (toList . flatten $ x) diagMat :: Mat -> Mat diagMat = diag . flatten ei :: Int -> Int -> Mat ei n i = assoc (n, 1) 0.0 [((i, 0), 1)] fpequalsMat :: Mat -> Mat -> Bool fpequalsMat a b | ra == rb && ca == cb = all (uncurry fpequals) $ zip alist blist | otherwise = error "Two matrices with different dimensions cannot possibley be equal!" where ra = rows a rb = rows b ca = cols a cb = cols b alist = toList . flatten $ a blist = toList . flatten $ b lpnorm :: Double -> Mat -> Double lpnorm p x = sumElements y ** (1/p) where pMat = (1><1) [p] y = abs x ** pMat matrixPow :: Double -> Mat -> Mat matrixPow p = cmap (** p) reduceMat :: ([Double] -> Double) -> Mat -> Mat reduceMat f = (1><1) . (:[]) . f . toList . flatten scalarMat :: Double -> Mat scalarMat x = (1><1) [x] zeroMat :: Int -> Mat zeroMat n = konst 0.0 (n, n) zeroVec :: Int -> Mat zeroVec n = konst 0.0 (n, 1)
chrisnc/hvx
src/HVX/Internal/Matrix.hs
Haskell
bsd-3-clause
1,333
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-| Module : Stack.Sig.Sign Description : Signing Packages Copyright : (c) FPComplete.com, 2015 License : BSD3 Maintainer : Tim Dysinger <tim@fpcomplete.com> Stability : experimental Portability : POSIX -} module Stack.Sig.Sign (sign, signPackage, signTarBytes) where import Prelude () import Prelude.Compat import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip import Control.Monad (when) import Control.Monad.IO.Unlift import Control.Monad.Logger import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy as L import Data.Monoid ((<>)) import qualified Data.Text as T import Network.HTTP.Client (RequestBody (RequestBodyBS)) import Network.HTTP.Download import Network.HTTP.Simple import Network.HTTP.Types (methodPut) import Path import Path.IO import Stack.Package import Stack.Sig.GPG import Stack.Types.PackageIdentifier import Stack.Types.Sig import qualified System.FilePath as FP -- | Sign a haskell package with the given url of the signature -- service and a path to a tarball. sign #if __GLASGOW_HASKELL__ < 710 :: (Applicative m, MonadUnliftIO m, MonadLogger m, MonadThrow m) #else :: (MonadUnliftIO m, MonadLogger m, MonadThrow m) #endif => String -> Path Abs File -> m Signature sign url filePath = withRunIO $ \run -> withSystemTempDir "stack" (\tempDir -> do bytes <- liftIO (fmap GZip.decompress (BS.readFile (toFilePath filePath))) maybePath <- extractCabalFile tempDir (Tar.read bytes) case maybePath of Nothing -> throwM SigInvalidSDistTarBall Just cabalPath -> do pkg <- cabalFilePackageId (tempDir </> cabalPath) run (signPackage url pkg filePath)) where extractCabalFile tempDir (Tar.Next entry entries) = case Tar.entryContent entry of (Tar.NormalFile lbs _) -> case FP.splitFileName (Tar.entryPath entry) of (folder,file) | length (FP.splitDirectories folder) == 1 && FP.takeExtension file == ".cabal" -> do cabalFile <- parseRelFile file liftIO (BS.writeFile (toFilePath (tempDir </> cabalFile)) lbs) return (Just cabalFile) (_,_) -> extractCabalFile tempDir entries _ -> extractCabalFile tempDir entries extractCabalFile _ _ = return Nothing -- | Sign a haskell package with the given url to the signature -- service, a package tarball path (package tarball name) and a lazy -- bytestring of bytes that represent the tarball bytestream. The -- function will write the bytes to the path in a temp dir and sign -- the tarball with GPG. signTarBytes #if __GLASGOW_HASKELL__ < 710 :: (Applicative m, MonadUnliftIO m, MonadLogger m, MonadThrow m) #else :: (MonadUnliftIO m, MonadLogger m, MonadThrow m) #endif => String -> Path Rel File -> L.ByteString -> m Signature signTarBytes url tarPath bs = withRunIO $ \run -> withSystemTempDir "stack" (\tempDir -> do let tempTarBall = tempDir </> tarPath liftIO (L.writeFile (toFilePath tempTarBall) bs) run (sign url tempTarBall)) -- | Sign a haskell package given the url to the signature service, a -- @PackageIdentifier@ and a file path to the package on disk. signPackage :: (MonadIO m, MonadLogger m, MonadThrow m) => String -> PackageIdentifier -> Path Abs File -> m Signature signPackage url pkg filePath = do sig@(Signature signature) <- gpgSign filePath let (PackageIdentifier name version) = pkg fingerprint <- gpgVerify sig filePath let fullUrl = url <> "/upload/signature/" <> show name <> "/" <> show version <> "/" <> show fingerprint req <- parseUrlThrow fullUrl let put = setRequestMethod methodPut $ setRequestBody (RequestBodyBS signature) req res <- liftIO (httpLbs put) when (getResponseStatusCode res /= 200) (throwM (GPGSignException "unable to sign & upload package")) $logInfo ("Signature uploaded to " <> T.pack fullUrl) return sig
martin-kolinek/stack
src/Stack/Sig/Sign.hs
Haskell
bsd-3-clause
4,811
{-# LANGUAGE OverloadedStrings #-} import RSSBuffer import Database.Redis -- hedis import Network.Curl.Download -- download-curl, sudo apt-get libcurl4-openssl-dev import Text.XML.Light -- xml import qualified Data.List as L import Control.Monad.IO.Class import Data.Maybe import Data.Monoid import Debug.Trace import Control.Concurrent import Control.Concurrent.MVar import qualified Data.ByteString.UTF8 as T import qualified Data.ByteString as BS main :: IO () main = do conn <- connect defaultConnectInfo mvar <- newMVar conn mapM_ (\x -> forkIO (updateFeed mvar x >> return ())) allFeeds updateFeed :: MVar Connection -> Feed -> IO (Either Reply Integer) updateFeed mvar (Feed idx _ url format) = do (Right xml) <- openAsXML url let (Just rss) = extractTree format xml let (h, es) = extractFeed format rss let newEs = L.reverse es readMVar mvar >>= \conn -> runRedis conn $ do set (feedMeta idx) $ foldl (\c x -> mappend c $ T.fromString . showElement $ x) "" h -- failed pattern matches are the least of my concerns (Right top) <- lrange (feedElems idx) 0 100 let newCont = newArticles format top newEs -- liftIO . print . uniqId . head . onlyElems . parseXML $ fromJust top -- liftIO . print $ (map uniqId newCont) -- liftIO . print $ (map uniqId old) lpush (feedElems idx) $ map (T.fromString . showElement) newCont extractFeed :: FeedType -> Element -> ([Element], [Element]) extractFeed Atom xs = (filterFeed "entry" (/=) xs, filterFeed "entry" (==) xs) extractFeed RSS xs = (filterFeed "item" (/=) xs, filterFeed "item" (==) xs) filterFeed str o xs = filterChildrenName (\(QName n _ _) -> o n str) xs extractTree Atom xml = treeFind "feed" xml extractTree RSS xml = treeFind "rss" xml treeFind str xml = L.find (\(Element (QName n _ _) _ _ _) -> n == str) $ onlyElems xml -- find where the feed is up to -- we want everything AFTER the first element that matches the break pred -- TODO: several feeds have not been following the "linear time" concept. :( newArticles :: FeedType -> [BS.ByteString] -> [Element] -> [Element] newArticles ft ts = filter (\x -> (uniqId ft x) `notElem` items) where items = map ((uniqId ft) . head . onlyElems . parseXML) ts
mxswd/rss-buffer
job.hs
Haskell
bsd-3-clause
2,294
module Ghazan( module Ghazan.Area , module Ghazan.Length , module Ghazan.Liquid , module Ghazan.Numerics , module Ghazan.Speed , module Ghazan.Temperature , module Ghazan.Volume , module Ghazan.Weight , module Ghazan.Time ) where -- Source Imports import Ghazan.Area import Ghazan.Length import Ghazan.Liquid import Ghazan.Numerics import Ghazan.Speed import Ghazan.Temperature import Ghazan.Volume import Ghazan.Weight import Ghazan.Time
Cortlandd/ConversionFormulas
src/Ghazan.hs
Haskell
bsd-3-clause
479
module Main where import Control.Concurrent (forkIO) import Control.Concurrent.STM import Control.Concurrent.STM.TVar import Control.Monad.Trans (liftIO) import Data.Time import System.Environment (getArgs) import System.Process.Monitor main = do args <- getArgs putStrLn "Monitoring beginning..." time <- getCurrentTime comm <- liftIO $ atomically $ newTVar $ mkComm time doWork args comm time putStrLn "Monitoring complete" doWork args comm time = do let workerBin = head args intervalBin = head $ drop 1 args worker = Executable workerBin [] job = mkJob worker launchWorker job comm [ Interval time 3 intervalJob1 , Interval time 5 intervalJob2 ] intervalJob1 _ = putStrLn "Example interval 1" intervalJob2 _ = putStrLn "Example interval 2"
stormont/vg-process-monitor
DefaultIntervalMonitor.hs
Haskell
bsd-3-clause
872
{- (c) The GRASP Project, Glasgow University, 1994-1998 \section[TysWiredIn]{Wired-in knowledge about {\em non-primitive} types} -} {-# LANGUAGE CPP #-} -- | This module is about types that can be defined in Haskell, but which -- must be wired into the compiler nonetheless. C.f module TysPrim module TysWiredIn ( -- * All wired in things wiredInTyCons, isBuiltInOcc_maybe, -- * Bool boolTy, boolTyCon, boolTyCon_RDR, boolTyConName, trueDataCon, trueDataConId, true_RDR, falseDataCon, falseDataConId, false_RDR, promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon, -- * Ordering ltDataCon, ltDataConId, eqDataCon, eqDataConId, gtDataCon, gtDataConId, promotedOrderingTyCon, promotedLTDataCon, promotedEQDataCon, promotedGTDataCon, -- * Char charTyCon, charDataCon, charTyCon_RDR, charTy, stringTy, charTyConName, -- * Double doubleTyCon, doubleDataCon, doubleTy, doubleTyConName, -- * Float floatTyCon, floatDataCon, floatTy, floatTyConName, -- * Int intTyCon, intDataCon, intTyCon_RDR, intDataCon_RDR, intTyConName, intTy, -- * Word wordTyCon, wordDataCon, wordTyConName, wordTy, -- * List listTyCon, listTyCon_RDR, listTyConName, listTyConKey, nilDataCon, nilDataConName, nilDataConKey, consDataCon_RDR, consDataCon, consDataConName, mkListTy, mkPromotedListTy, -- * Tuples mkTupleTy, mkBoxedTupleTy, tupleTyCon, tupleDataCon, tupleTyConName, promotedTupleTyCon, promotedTupleDataCon, unitTyCon, unitDataCon, unitDataConId, unitTy, unitTyConKey, pairTyCon, unboxedUnitTyCon, unboxedUnitDataCon, unboxedSingletonTyCon, unboxedSingletonDataCon, unboxedPairTyCon, unboxedPairDataCon, cTupleTyConName, cTupleTyConNames, isCTupleTyConName, -- * Kinds typeNatKindCon, typeNatKind, typeSymbolKindCon, typeSymbolKind, -- * Parallel arrays mkPArrTy, parrTyCon, parrFakeCon, isPArrTyCon, isPArrFakeCon, parrTyCon_RDR, parrTyConName, -- * Equality predicates eqTyCon_RDR, eqTyCon, eqTyConName, eqBoxDataCon, coercibleTyCon, coercibleDataCon, coercibleClass, mkWiredInTyConName -- This is used in TcTypeNats to define the -- built-in functions for evaluation. ) where #include "HsVersions.h" import {-# SOURCE #-} MkId( mkDataConWorkId ) -- friends: import PrelNames import TysPrim -- others: import Constants ( mAX_TUPLE_SIZE, mAX_CTUPLE_SIZE ) import Module ( Module ) import Type ( mkTyConApp ) import DataCon import ConLike import Var import TyCon import Class ( Class, mkClass ) import TypeRep import RdrName import Name import NameSet ( NameSet, mkNameSet, elemNameSet ) import BasicTypes ( Arity, RecFlag(..), Boxity(..), TupleSort(..) ) import ForeignCall import Unique ( incrUnique, mkTupleTyConUnique, mkTupleDataConUnique, mkCTupleTyConUnique, mkPArrDataConUnique ) import SrcLoc ( noSrcSpan ) import Data.Array import FastString import Outputable import Util import BooleanFormula ( mkAnd ) alpha_tyvar :: [TyVar] alpha_tyvar = [alphaTyVar] alpha_ty :: [Type] alpha_ty = [alphaTy] {- ************************************************************************ * * \subsection{Wired in type constructors} * * ************************************************************************ If you change which things are wired in, make sure you change their names in PrelNames, so they use wTcQual, wDataQual, etc -} -- This list is used only to define PrelInfo.wiredInThings. That in turn -- is used to initialise the name environment carried around by the renamer. -- This means that if we look up the name of a TyCon (or its implicit binders) -- that occurs in this list that name will be assigned the wired-in key we -- define here. -- -- Because of their infinite nature, this list excludes tuples, Any and implicit -- parameter TyCons. Instead, we have a hack in lookupOrigNameCache to deal with -- these names. -- -- See also Note [Known-key names] wiredInTyCons :: [TyCon] wiredInTyCons = [ unitTyCon -- Not treated like other tuples, because -- it's defined in GHC.Base, and there's only -- one of it. We put it in wiredInTyCons so -- that it'll pre-populate the name cache, so -- the special case in lookupOrigNameCache -- doesn't need to look out for it , boolTyCon , charTyCon , doubleTyCon , floatTyCon , intTyCon , wordTyCon , listTyCon , parrTyCon , eqTyCon , coercibleTyCon , typeNatKindCon , typeSymbolKindCon ] mkWiredInTyConName :: BuiltInSyntax -> Module -> FastString -> Unique -> TyCon -> Name mkWiredInTyConName built_in modu fs unique tycon = mkWiredInName modu (mkTcOccFS fs) unique (ATyCon tycon) -- Relevant TyCon built_in mkWiredInDataConName :: BuiltInSyntax -> Module -> FastString -> Unique -> DataCon -> Name mkWiredInDataConName built_in modu fs unique datacon = mkWiredInName modu (mkDataOccFS fs) unique (AConLike (RealDataCon datacon)) -- Relevant DataCon built_in -- See Note [Kind-changing of (~) and Coercible] eqTyConName, eqBoxDataConName :: Name eqTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "~") eqTyConKey eqTyCon eqBoxDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "Eq#") eqBoxDataConKey eqBoxDataCon -- See Note [Kind-changing of (~) and Coercible] coercibleTyConName, coercibleDataConName :: Name coercibleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Coercible") coercibleTyConKey coercibleTyCon coercibleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "MkCoercible") coercibleDataConKey coercibleDataCon charTyConName, charDataConName, intTyConName, intDataConName :: Name charTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Char") charTyConKey charTyCon charDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "C#") charDataConKey charDataCon intTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Int") intTyConKey intTyCon intDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "I#") intDataConKey intDataCon boolTyConName, falseDataConName, trueDataConName :: Name boolTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Bool") boolTyConKey boolTyCon falseDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "False") falseDataConKey falseDataCon trueDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "True") trueDataConKey trueDataCon listTyConName, nilDataConName, consDataConName :: Name listTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "[]") listTyConKey listTyCon nilDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit "[]") nilDataConKey nilDataCon consDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit ":") consDataConKey consDataCon wordTyConName, wordDataConName, floatTyConName, floatDataConName, doubleTyConName, doubleDataConName :: Name wordTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Word") wordTyConKey wordTyCon wordDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "W#") wordDataConKey wordDataCon floatTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Float") floatTyConKey floatTyCon floatDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "F#") floatDataConKey floatDataCon doubleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Double") doubleTyConKey doubleTyCon doubleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "D#") doubleDataConKey doubleDataCon -- Kinds typeNatKindConName, typeSymbolKindConName :: Name typeNatKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Nat") typeNatKindConNameKey typeNatKindCon typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol") typeSymbolKindConNameKey typeSymbolKindCon parrTyConName, parrDataConName :: Name parrTyConName = mkWiredInTyConName BuiltInSyntax gHC_PARR' (fsLit "[::]") parrTyConKey parrTyCon parrDataConName = mkWiredInDataConName UserSyntax gHC_PARR' (fsLit "PArr") parrDataConKey parrDataCon boolTyCon_RDR, false_RDR, true_RDR, intTyCon_RDR, charTyCon_RDR, intDataCon_RDR, listTyCon_RDR, consDataCon_RDR, parrTyCon_RDR, eqTyCon_RDR :: RdrName boolTyCon_RDR = nameRdrName boolTyConName false_RDR = nameRdrName falseDataConName true_RDR = nameRdrName trueDataConName intTyCon_RDR = nameRdrName intTyConName charTyCon_RDR = nameRdrName charTyConName intDataCon_RDR = nameRdrName intDataConName listTyCon_RDR = nameRdrName listTyConName consDataCon_RDR = nameRdrName consDataConName parrTyCon_RDR = nameRdrName parrTyConName eqTyCon_RDR = nameRdrName eqTyConName {- ************************************************************************ * * \subsection{mkWiredInTyCon} * * ************************************************************************ -} pcNonRecDataTyCon :: Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon -- Not an enumeration, not promotable pcNonRecDataTyCon = pcTyCon False NonRecursive False -- This function assumes that the types it creates have all parameters at -- Representational role! pcTyCon :: Bool -> RecFlag -> Bool -> Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon pcTyCon is_enum is_rec is_prom name cType tyvars cons = buildAlgTyCon name tyvars (map (const Representational) tyvars) cType [] -- No stupid theta (DataTyCon cons is_enum) is_rec is_prom False -- Not in GADT syntax NoParentTyCon pcDataCon :: Name -> [TyVar] -> [Type] -> TyCon -> DataCon pcDataCon = pcDataConWithFixity False pcDataConWithFixity :: Bool -> Name -> [TyVar] -> [Type] -> TyCon -> DataCon pcDataConWithFixity infx n = pcDataConWithFixity' infx n (incrUnique (nameUnique n)) -- The Name's unique is the first of two free uniques; -- the first is used for the datacon itself, -- the second is used for the "worker name" -- -- To support this the mkPreludeDataConUnique function "allocates" -- one DataCon unique per pair of Ints. pcDataConWithFixity' :: Bool -> Name -> Unique -> [TyVar] -> [Type] -> TyCon -> DataCon -- The Name should be in the DataName name space; it's the name -- of the DataCon itself. pcDataConWithFixity' declared_infix dc_name wrk_key tyvars arg_tys tycon = data_con where data_con = mkDataCon dc_name declared_infix (map (const HsNoBang) arg_tys) [] -- No labelled fields tyvars [] -- No existential type variables [] -- No equality spec [] -- No theta arg_tys (mkTyConApp tycon (mkTyVarTys tyvars)) tycon [] -- No stupid theta (mkDataConWorkId wrk_name data_con) NoDataConRep -- Wired-in types are too simple to need wrappers modu = ASSERT( isExternalName dc_name ) nameModule dc_name wrk_occ = mkDataConWorkerOcc (nameOccName dc_name) wrk_name = mkWiredInName modu wrk_occ wrk_key (AnId (dataConWorkId data_con)) UserSyntax {- ************************************************************************ * * Kinds * * ************************************************************************ -} typeNatKindCon, typeSymbolKindCon :: TyCon -- data Nat -- data Symbol typeNatKindCon = pcTyCon False NonRecursive True typeNatKindConName Nothing [] [] typeSymbolKindCon = pcTyCon False NonRecursive True typeSymbolKindConName Nothing [] [] typeNatKind, typeSymbolKind :: Kind typeNatKind = TyConApp (promoteTyCon typeNatKindCon) [] typeSymbolKind = TyConApp (promoteTyCon typeSymbolKindCon) [] {- ************************************************************************ * * Stuff for dealing with tuples * * ************************************************************************ Note [How tuples work] See also Note [Known-key names] in PrelNames ~~~~~~~~~~~~~~~~~~~~~~ * There are three families of tuple TyCons and corresponding DataCons, expressed by the type BasicTypes.TupleSort: data TupleSort = BoxedTuple | UnboxedTuple | ConstraintTuple * All three families are AlgTyCons, whose AlgTyConRhs is TupleTyCon * BoxedTuples - A wired-in type - Data type declarations in GHC.Tuple - The data constructors really have an info table * UnboxedTuples - A wired-in type - Have a pretend DataCon, defined in GHC.Prim, but no actual declaration and no info table * ConstraintTuples - Are known-key rather than wired-in. Reason: it's awkward to have all the superclass selectors wired-in. - Declared as classes in GHC.Classes, e.g. class (c1,c2) => (c1,c2) - Given constraints: the superclasses automatically become available - Wanted constraints: there is a built-in instance instance (c1,c2) => (c1,c2) - Currently just go up to 16; beyond that you have to use manual nesting - Their OccNames look like (%,,,%), so they can easily be distinguished from term tuples. But (following Haskell) we pretty-print saturated constraint tuples with round parens; see BasicTypes.tupleParens. * In quite a lot of places things are restrcted just to BoxedTuple/UnboxedTuple, and then we used BasicTypes.Boxity to distinguish E.g. tupleTyCon has a Boxity argument * When looking up an OccName in the original-name cache (IfaceEnv.lookupOrigNameCache), we spot the tuple OccName to make sure we get the right wired-in name. This guy can't tell the difference betweeen BoxedTuple and ConstraintTuple (same OccName!), so tuples are not serialised into interface files using OccNames at all. -} isBuiltInOcc_maybe :: OccName -> Maybe Name -- Built in syntax isn't "in scope" so these OccNames -- map to wired-in Names with BuiltInSyntax isBuiltInOcc_maybe occ = case occNameString occ of "[]" -> choose_ns listTyConName nilDataConName ":" -> Just consDataConName "[::]" -> Just parrTyConName "()" -> tup_name Boxed 0 "(##)" -> tup_name Unboxed 0 '(':',':rest -> parse_tuple Boxed 2 rest '(':'#':',':rest -> parse_tuple Unboxed 2 rest _other -> Nothing where ns = occNameSpace occ parse_tuple sort n rest | (',' : rest2) <- rest = parse_tuple sort (n+1) rest2 | tail_matches sort rest = tup_name sort n | otherwise = Nothing tail_matches Boxed ")" = True tail_matches Unboxed "#)" = True tail_matches _ _ = False tup_name boxity arity = choose_ns (getName (tupleTyCon boxity arity)) (getName (tupleDataCon boxity arity)) choose_ns tc dc | isTcClsNameSpace ns = Just tc | isDataConNameSpace ns = Just dc | otherwise = pprPanic "tup_name" (ppr occ) mkTupleOcc :: NameSpace -> Boxity -> Arity -> OccName mkTupleOcc ns sort ar = mkOccName ns str where -- No need to cache these, the caching is done in mk_tuple str = case sort of Unboxed -> '(' : '#' : commas ++ "#)" Boxed -> '(' : commas ++ ")" commas = take (ar-1) (repeat ',') mkCTupleOcc :: NameSpace -> Arity -> OccName mkCTupleOcc ns ar = mkOccName ns str where str = "(%" ++ commas ++ "%)" commas = take (ar-1) (repeat ',') cTupleTyConName :: Arity -> Name cTupleTyConName arity = mkExternalName (mkCTupleTyConUnique arity) gHC_CLASSES (mkCTupleOcc tcName arity) noSrcSpan -- The corresponding DataCon does not have a known-key name cTupleTyConNames :: [Name] cTupleTyConNames = map cTupleTyConName (0 : [2..mAX_CTUPLE_SIZE]) cTupleTyConNameSet :: NameSet cTupleTyConNameSet = mkNameSet cTupleTyConNames isCTupleTyConName :: Name -> Bool isCTupleTyConName n = ASSERT2( isExternalName n, ppr n ) nameModule n == gHC_CLASSES && n `elemNameSet` cTupleTyConNameSet tupleTyCon :: Boxity -> Arity -> TyCon tupleTyCon sort i | i > mAX_TUPLE_SIZE = fst (mk_tuple sort i) -- Build one specially tupleTyCon Boxed i = fst (boxedTupleArr ! i) tupleTyCon Unboxed i = fst (unboxedTupleArr ! i) tupleTyConName :: TupleSort -> Arity -> Name tupleTyConName ConstraintTuple a = cTupleTyConName a tupleTyConName BoxedTuple a = tyConName (tupleTyCon Boxed a) tupleTyConName UnboxedTuple a = tyConName (tupleTyCon Unboxed a) promotedTupleTyCon :: Boxity -> Arity -> TyCon promotedTupleTyCon boxity i = promoteTyCon (tupleTyCon boxity i) promotedTupleDataCon :: Boxity -> Arity -> TyCon promotedTupleDataCon boxity i = promoteDataCon (tupleDataCon boxity i) tupleDataCon :: Boxity -> Arity -> DataCon tupleDataCon sort i | i > mAX_TUPLE_SIZE = snd (mk_tuple sort i) -- Build one specially tupleDataCon Boxed i = snd (boxedTupleArr ! i) tupleDataCon Unboxed i = snd (unboxedTupleArr ! i) boxedTupleArr, unboxedTupleArr :: Array Int (TyCon,DataCon) boxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Boxed i | i <- [0..mAX_TUPLE_SIZE]] unboxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Unboxed i | i <- [0..mAX_TUPLE_SIZE]] mk_tuple :: Boxity -> Int -> (TyCon,DataCon) mk_tuple boxity arity = (tycon, tuple_con) where tycon = mkTupleTyCon tc_name tc_kind arity tyvars tuple_con tup_sort prom_tc NoParentTyCon tup_sort = case boxity of Boxed -> BoxedTuple Unboxed -> UnboxedTuple prom_tc = case boxity of Boxed -> Just (mkPromotedTyCon tycon (promoteKind tc_kind)) Unboxed -> Nothing modu = case boxity of Boxed -> gHC_TUPLE Unboxed -> gHC_PRIM tc_name = mkWiredInName modu (mkTupleOcc tcName boxity arity) tc_uniq (ATyCon tycon) BuiltInSyntax tc_kind = mkArrowKinds (map tyVarKind tyvars) res_kind res_kind = case boxity of Boxed -> liftedTypeKind Unboxed -> unliftedTypeKind tyvars = take arity $ case boxity of Boxed -> alphaTyVars Unboxed -> openAlphaTyVars tuple_con = pcDataCon dc_name tyvars tyvar_tys tycon tyvar_tys = mkTyVarTys tyvars dc_name = mkWiredInName modu (mkTupleOcc dataName boxity arity) dc_uniq (AConLike (RealDataCon tuple_con)) BuiltInSyntax tc_uniq = mkTupleTyConUnique boxity arity dc_uniq = mkTupleDataConUnique boxity arity unitTyCon :: TyCon unitTyCon = tupleTyCon Boxed 0 unitTyConKey :: Unique unitTyConKey = getUnique unitTyCon unitDataCon :: DataCon unitDataCon = head (tyConDataCons unitTyCon) unitDataConId :: Id unitDataConId = dataConWorkId unitDataCon pairTyCon :: TyCon pairTyCon = tupleTyCon Boxed 2 unboxedUnitTyCon :: TyCon unboxedUnitTyCon = tupleTyCon Unboxed 0 unboxedUnitDataCon :: DataCon unboxedUnitDataCon = tupleDataCon Unboxed 0 unboxedSingletonTyCon :: TyCon unboxedSingletonTyCon = tupleTyCon Unboxed 1 unboxedSingletonDataCon :: DataCon unboxedSingletonDataCon = tupleDataCon Unboxed 1 unboxedPairTyCon :: TyCon unboxedPairTyCon = tupleTyCon Unboxed 2 unboxedPairDataCon :: DataCon unboxedPairDataCon = tupleDataCon Unboxed 2 {- ************************************************************************ * * \subsection[TysWiredIn-boxed-prim]{The ``boxed primitive'' types (@Char@, @Int@, etc)} * * ************************************************************************ -} eqTyCon :: TyCon eqTyCon = mkAlgTyCon eqTyConName (ForAllTy kv $ mkArrowKinds [k, k] constraintKind) [kv, a, b] [Nominal, Nominal, Nominal] Nothing [] -- No stupid theta (DataTyCon [eqBoxDataCon] False) NoParentTyCon NonRecursive False Nothing -- No parent for constraint-kinded types where kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k eqBoxDataCon :: DataCon eqBoxDataCon = pcDataCon eqBoxDataConName args [TyConApp eqPrimTyCon (map mkTyVarTy args)] eqTyCon where kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k args = [kv, a, b] coercibleTyCon :: TyCon coercibleTyCon = mkClassTyCon coercibleTyConName kind tvs [Nominal, Representational, Representational] rhs coercibleClass NonRecursive where kind = (ForAllTy kv $ mkArrowKinds [k, k] constraintKind) kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k tvs = [kv, a, b] rhs = DataTyCon [coercibleDataCon] False coercibleDataCon :: DataCon coercibleDataCon = pcDataCon coercibleDataConName args [TyConApp eqReprPrimTyCon (map mkTyVarTy args)] coercibleTyCon where kv = kKiVar k = mkTyVarTy kv a:b:_ = tyVarList k args = [kv, a, b] coercibleClass :: Class coercibleClass = mkClass (tyConTyVars coercibleTyCon) [] [] [] [] [] (mkAnd []) coercibleTyCon charTy :: Type charTy = mkTyConTy charTyCon charTyCon :: TyCon charTyCon = pcNonRecDataTyCon charTyConName (Just (CType "" Nothing ("HsChar",fsLit "HsChar"))) [] [charDataCon] charDataCon :: DataCon charDataCon = pcDataCon charDataConName [] [charPrimTy] charTyCon stringTy :: Type stringTy = mkListTy charTy -- convenience only intTy :: Type intTy = mkTyConTy intTyCon intTyCon :: TyCon intTyCon = pcNonRecDataTyCon intTyConName (Just (CType "" Nothing ("HsInt",fsLit "HsInt"))) [] [intDataCon] intDataCon :: DataCon intDataCon = pcDataCon intDataConName [] [intPrimTy] intTyCon wordTy :: Type wordTy = mkTyConTy wordTyCon wordTyCon :: TyCon wordTyCon = pcNonRecDataTyCon wordTyConName (Just (CType "" Nothing ("HsWord", fsLit "HsWord"))) [] [wordDataCon] wordDataCon :: DataCon wordDataCon = pcDataCon wordDataConName [] [wordPrimTy] wordTyCon floatTy :: Type floatTy = mkTyConTy floatTyCon floatTyCon :: TyCon floatTyCon = pcNonRecDataTyCon floatTyConName (Just (CType "" Nothing ("HsFloat", fsLit "HsFloat"))) [] [floatDataCon] floatDataCon :: DataCon floatDataCon = pcDataCon floatDataConName [] [floatPrimTy] floatTyCon doubleTy :: Type doubleTy = mkTyConTy doubleTyCon doubleTyCon :: TyCon doubleTyCon = pcNonRecDataTyCon doubleTyConName (Just (CType "" Nothing ("HsDouble",fsLit "HsDouble"))) [] [doubleDataCon] doubleDataCon :: DataCon doubleDataCon = pcDataCon doubleDataConName [] [doublePrimTy] doubleTyCon {- ************************************************************************ * * \subsection[TysWiredIn-Bool]{The @Bool@ type} * * ************************************************************************ An ordinary enumeration type, but deeply wired in. There are no magical operations on @Bool@ (just the regular Prelude code). {\em BEGIN IDLE SPECULATION BY SIMON} This is not the only way to encode @Bool@. A more obvious coding makes @Bool@ just a boxed up version of @Bool#@, like this: \begin{verbatim} type Bool# = Int# data Bool = MkBool Bool# \end{verbatim} Unfortunately, this doesn't correspond to what the Report says @Bool@ looks like! Furthermore, we get slightly less efficient code (I think) with this coding. @gtInt@ would look like this: \begin{verbatim} gtInt :: Int -> Int -> Bool gtInt x y = case x of I# x# -> case y of I# y# -> case (gtIntPrim x# y#) of b# -> MkBool b# \end{verbatim} Notice that the result of the @gtIntPrim@ comparison has to be turned into an integer (here called @b#@), and returned in a @MkBool@ box. The @if@ expression would compile to this: \begin{verbatim} case (gtInt x y) of MkBool b# -> case b# of { 1# -> e1; 0# -> e2 } \end{verbatim} I think this code is a little less efficient than the previous code, but I'm not certain. At all events, corresponding with the Report is important. The interesting thing is that the language is expressive enough to describe more than one alternative; and that a type doesn't necessarily need to be a straightforwardly boxed version of its primitive counterpart. {\em END IDLE SPECULATION BY SIMON} -} boolTy :: Type boolTy = mkTyConTy boolTyCon boolTyCon :: TyCon boolTyCon = pcTyCon True NonRecursive True boolTyConName (Just (CType "" Nothing ("HsBool", fsLit "HsBool"))) [] [falseDataCon, trueDataCon] falseDataCon, trueDataCon :: DataCon falseDataCon = pcDataCon falseDataConName [] [] boolTyCon trueDataCon = pcDataCon trueDataConName [] [] boolTyCon falseDataConId, trueDataConId :: Id falseDataConId = dataConWorkId falseDataCon trueDataConId = dataConWorkId trueDataCon orderingTyCon :: TyCon orderingTyCon = pcTyCon True NonRecursive True orderingTyConName Nothing [] [ltDataCon, eqDataCon, gtDataCon] ltDataCon, eqDataCon, gtDataCon :: DataCon ltDataCon = pcDataCon ltDataConName [] [] orderingTyCon eqDataCon = pcDataCon eqDataConName [] [] orderingTyCon gtDataCon = pcDataCon gtDataConName [] [] orderingTyCon ltDataConId, eqDataConId, gtDataConId :: Id ltDataConId = dataConWorkId ltDataCon eqDataConId = dataConWorkId eqDataCon gtDataConId = dataConWorkId gtDataCon {- ************************************************************************ * * \subsection[TysWiredIn-List]{The @List@ type (incl ``build'' magic)} * * ************************************************************************ Special syntax, deeply wired in, but otherwise an ordinary algebraic data types: \begin{verbatim} data [] a = [] | a : (List a) data () = () data (,) a b = (,,) a b ... \end{verbatim} -} mkListTy :: Type -> Type mkListTy ty = mkTyConApp listTyCon [ty] listTyCon :: TyCon listTyCon = pcTyCon False Recursive True listTyConName Nothing alpha_tyvar [nilDataCon, consDataCon] mkPromotedListTy :: Type -> Type mkPromotedListTy ty = mkTyConApp promotedListTyCon [ty] promotedListTyCon :: TyCon promotedListTyCon = promoteTyCon listTyCon nilDataCon :: DataCon nilDataCon = pcDataCon nilDataConName alpha_tyvar [] listTyCon consDataCon :: DataCon consDataCon = pcDataConWithFixity True {- Declared infix -} consDataConName alpha_tyvar [alphaTy, mkTyConApp listTyCon alpha_ty] listTyCon -- Interesting: polymorphic recursion would help here. -- We can't use (mkListTy alphaTy) in the defn of consDataCon, else mkListTy -- gets the over-specific type (Type -> Type) {- ************************************************************************ * * \subsection[TysWiredIn-Tuples]{The @Tuple@ types} * * ************************************************************************ The tuple types are definitely magic, because they form an infinite family. \begin{itemize} \item They have a special family of type constructors, of type @TyCon@ These contain the tycon arity, but don't require a Unique. \item They have a special family of constructors, of type @Id@. Again these contain their arity but don't need a Unique. \item There should be a magic way of generating the info tables and entry code for all tuples. But at the moment we just compile a Haskell source file\srcloc{lib/prelude/...} containing declarations like: \begin{verbatim} data Tuple0 = Tup0 data Tuple2 a b = Tup2 a b data Tuple3 a b c = Tup3 a b c data Tuple4 a b c d = Tup4 a b c d ... \end{verbatim} The print-names associated with the magic @Id@s for tuple constructors ``just happen'' to be the same as those generated by these declarations. \item The instance environment should have a magic way to know that each tuple type is an instances of classes @Eq@, @Ix@, @Ord@ and so on. \ToDo{Not implemented yet.} \item There should also be a way to generate the appropriate code for each of these instances, but (like the info tables and entry code) it is done by enumeration\srcloc{lib/prelude/InTup?.hs}. \end{itemize} -} mkTupleTy :: Boxity -> [Type] -> Type -- Special case for *boxed* 1-tuples, which are represented by the type itself mkTupleTy Boxed [ty] = ty mkTupleTy boxity tys = mkTyConApp (tupleTyCon boxity (length tys)) tys -- | Build the type of a small tuple that holds the specified type of thing mkBoxedTupleTy :: [Type] -> Type mkBoxedTupleTy tys = mkTupleTy Boxed tys unitTy :: Type unitTy = mkTupleTy Boxed [] {- ************************************************************************ * * \subsection[TysWiredIn-PArr]{The @[::]@ type} * * ************************************************************************ Special syntax for parallel arrays needs some wired in definitions. -} -- | Construct a type representing the application of the parallel array constructor mkPArrTy :: Type -> Type mkPArrTy ty = mkTyConApp parrTyCon [ty] -- | Represents the type constructor of parallel arrays -- -- * This must match the definition in @PrelPArr@ -- -- NB: Although the constructor is given here, it will not be accessible in -- user code as it is not in the environment of any compiled module except -- @PrelPArr@. -- parrTyCon :: TyCon parrTyCon = pcNonRecDataTyCon parrTyConName Nothing alpha_tyvar [parrDataCon] parrDataCon :: DataCon parrDataCon = pcDataCon parrDataConName alpha_tyvar -- forall'ed type variables [intTy, -- 1st argument: Int mkTyConApp -- 2nd argument: Array# a arrayPrimTyCon alpha_ty] parrTyCon -- | Check whether a type constructor is the constructor for parallel arrays isPArrTyCon :: TyCon -> Bool isPArrTyCon tc = tyConName tc == parrTyConName -- | Fake array constructors -- -- * These constructors are never really used to represent array values; -- however, they are very convenient during desugaring (and, in particular, -- in the pattern matching compiler) to treat array pattern just like -- yet another constructor pattern -- parrFakeCon :: Arity -> DataCon parrFakeCon i | i > mAX_TUPLE_SIZE = mkPArrFakeCon i -- build one specially parrFakeCon i = parrFakeConArr!i -- pre-defined set of constructors -- parrFakeConArr :: Array Int DataCon parrFakeConArr = array (0, mAX_TUPLE_SIZE) [(i, mkPArrFakeCon i) | i <- [0..mAX_TUPLE_SIZE]] -- build a fake parallel array constructor for the given arity -- mkPArrFakeCon :: Int -> DataCon mkPArrFakeCon arity = data_con where data_con = pcDataCon name [tyvar] tyvarTys parrTyCon tyvar = head alphaTyVars tyvarTys = replicate arity $ mkTyVarTy tyvar nameStr = mkFastString ("MkPArr" ++ show arity) name = mkWiredInName gHC_PARR' (mkDataOccFS nameStr) unique (AConLike (RealDataCon data_con)) UserSyntax unique = mkPArrDataConUnique arity -- | Checks whether a data constructor is a fake constructor for parallel arrays isPArrFakeCon :: DataCon -> Bool isPArrFakeCon dcon = dcon == parrFakeCon (dataConSourceArity dcon) -- Promoted Booleans promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon :: TyCon promotedBoolTyCon = promoteTyCon boolTyCon promotedTrueDataCon = promoteDataCon trueDataCon promotedFalseDataCon = promoteDataCon falseDataCon -- Promoted Ordering promotedOrderingTyCon , promotedLTDataCon , promotedEQDataCon , promotedGTDataCon :: TyCon promotedOrderingTyCon = promoteTyCon orderingTyCon promotedLTDataCon = promoteDataCon ltDataCon promotedEQDataCon = promoteDataCon eqDataCon promotedGTDataCon = promoteDataCon gtDataCon
urbanslug/ghc
compiler/prelude/TysWiredIn.hs
Haskell
bsd-3-clause
34,151
module Compile.Types.AbstractAssembly where import Compile.Types.Ops data AAsm = AAsm {aAssign :: [ALoc] ,aOp :: Op ,aArgs :: [AVal] } | ACtrl COp AVal | AComment String deriving Show data AVal = ALoc ALoc | AImm Int deriving Show data ALoc = AReg Int | ATemp Int deriving Show
maurer/15-411-Haskell-Base-Code
src/Compile/Types/AbstractAssembly.hs
Haskell
bsd-3-clause
379
-- 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. module Duckling.Dimensions.AF ( allDimensions ) where import Duckling.Dimensions.Types allDimensions :: [Seal Dimension] allDimensions = [ Seal Numeral ]
facebookincubator/duckling
Duckling/Dimensions/AF.hs
Haskell
bsd-3-clause
371
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.Assignment.View where import Prelude hiding (min) import Control.Arrow ((&&&)) import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy.Char8 as BsLazy import Data.Maybe (fromMaybe) import Data.Monoid import Data.String (IsString(..), fromString) import qualified Data.Time as Time import qualified Text.Blaze.Html5.Attributes as A (id) import Text.Blaze.Html5.Attributes as A hiding (id) import Text.Blaze.Html5 as H hiding (map) import Text.Printf (printf) import Bead.Controller.Pages (PageDesc) import qualified Bead.Controller.Pages as Pages import qualified Bead.Domain.Entity.Assignment as Assignment import Bead.Domain.Shared.Evaluation import Bead.View.Fay.HookIds import Bead.View.Fay.Hooks import Bead.View.Content hiding (name, option, required) import qualified Bead.View.Content.Bootstrap as Bootstrap import Bead.View.Markdown import Bead.View.Content.Assignment.Data newAssignmentContent :: PageData -> IHtml newAssignmentContent pd = do msg <- getI18N let hook = assignmentEvTypeHook -- Renders a evaluation selection or hides it if there is a submission already for the assignment, -- and renders an explanation. evalConfig <- do let evaluationTypeSelection = return $ do Bootstrap.selectionWithLabel (evHiddenValueId hook) (msg $ msg_NewAssignment_EvaluationType "Evaluation Type") (== currentEvaluationType) [ (binaryConfig, fromString . msg $ msg_NewAssignment_BinEval "Binary") , (percentageConfig 0.0, fromString . msg $ msg_NewAssignment_PctEval "Percentage") , (freeFormConfig, fromString . msg $ msg_NewAssignment_FftEval "Free form textual") ] let hiddencfg asg = return $ do let e = Assignment.evType asg showEvaluationType msg e fromString . msg $ msg_NewAssignment_EvalTypeWarn "The evaluation type can not be modified, there is a submission for the assignment." hiddenInput (evHiddenValueId hook) (encodeToFay' "selection" e) pageDataCata (const5 evaluationTypeSelection) (const5 evaluationTypeSelection) (\_tz _key asg _ts _fs _tc ev -> if ev then evaluationTypeSelection else hiddencfg asg) (const5 evaluationTypeSelection) (const7 evaluationTypeSelection) (const7 evaluationTypeSelection) (\_tz _key asg _ts _fs _tc _tm ev -> if ev then evaluationTypeSelection else hiddencfg asg) pd return $ do Bootstrap.row $ Bootstrap.colMd12 $ H.form ! A.method "post" $ H.div ! A.id (fromString $ hookId assignmentForm) $ do Bootstrap.formGroup $ do let assignmentTitleField = fromString $ fieldName assignmentNameField assignmentTitlePlaceholder = fromString $ fromAssignment (const "") (fromString . msg $ msg_NewAssignment_Title_Default "Unnamed Assignment") pd assignmentTitle = fromAssignment (fromString . Assignment.name) mempty pd Bootstrap.labelFor assignmentTitleField (fromString $ msg $ msg_NewAssignment_Title "Title") editOrReadOnly pd $ Bootstrap.textInputFieldWithDefault assignmentTitleField assignmentTitle H.p ! class_ "help-block"$ fromString . msg $ msg_NewAssignment_Info_Normal $ concat [ "Solutions may be submitted from the time of opening until the time of closing. " , "The assignment will not be visible until it is opened. " , "The assignments open and close automatically." ] -- Visibility information of the assignment H.h4 $ fromString $ msg $ msg_NewAssignment_SubmissionDeadline "Visibility" let date t = let localTime = timeZoneConverter t timeOfDay = Time.localTimeOfDay localTime in ( show $ Time.localDay localTime , printf "%02d" $ Time.todHour timeOfDay , printf "%02d" $ Time.todMin timeOfDay ) showDate (dt, hour, min) = concat [dt, " ", hour, ":", min, ":00"] startDateStringValue = showDate $ date $ pageDataCata (\_tz t _c _ts _fs -> t) (\_tz t _g _ts _fs -> t) (\_tz _k a _ts _fs _tc _ev -> Assignment.start a) (\_tz _k a _ts _tc -> Assignment.start a) (\_tz _t _c _ts _fs a _tc -> Assignment.start a) (\_tz _t _g _ts _fs a _tc -> Assignment.start a) (\_tz _k a _ts _fs _tc _tm _ev -> Assignment.start a) pd endDateStringValue = showDate $ date $ pageDataCata (\_tz t _c _ts _fs -> t) (\_tz t _g _ts _fs -> t) (\_tz _k a _ts _fs _tc _ev -> Assignment.end a) (\_tz _k a _ts _tc -> Assignment.end a) (\_tz _t _c _ts _fs a _tc -> Assignment.end a) (\_tz _t _g _ts _fs a _tc -> Assignment.end a) (\_tz _k a _ts _fs _tc _tm _ev -> Assignment.end a) pd -- Opening and closing dates of the assignment Bootstrap.formGroup $ do Bootstrap.row $ do -- Opening date of the assignment Bootstrap.colMd6 $ do let assignmentStart = fieldName assignmentStartField Bootstrap.labelFor assignmentStart $ fromString $ msg $ msg_NewAssignment_StartDate "Opens" Bootstrap.datetimePicker assignmentStart startDateStringValue isEditPage -- Closing date of the assignment Bootstrap.colMd6 $ do let assignmentEnd = fieldName assignmentEndField Bootstrap.labelFor assignmentEnd $ msg $ msg_NewAssignment_EndDate "Closes" Bootstrap.datetimePicker assignmentEnd endDateStringValue isEditPage Bootstrap.rowColMd12 $ H.hr -- Properties of the assignment H.h4 $ fromString $ msg $ msg_NewAssignment_Properties "Properties" let editable = True readOnly = False assignmentPropertiesSection ed = do let pwd = if Assignment.isPasswordProtected aas then Just (Assignment.getPassword aas) else Nothing noOfTries = if Assignment.isNoOfTries aas then Just (Assignment.getNoOfTries aas) else Nothing editable x = if ed then x else (x ! A.readonly "") readOnly = not ed assignmentAspect = fromString $ fieldName assignmentAspectField assignmentPwd = fromString $ fieldName assignmentPwdField assignmentNoOfTries = fromString $ fieldName assignmentNoOfTriesField bootstrapCheckbox $ checkBoxRO (fieldName assignmentAspectField) (Assignment.isBallotBox aas) readOnly Assignment.BallotBox (msg $ msg_NewAssignment_BallotBox "Ballot Box") Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_BallotBox $ concat [ "(Recommended for tests.) Students will not be able to access submissions and " , "their evaluations until the assignment is closed." ] bootstrapCheckbox $ checkBoxRO (fieldName assignmentAspectField) (Assignment.isIsolated aas) readOnly Assignment.Isolated (msg $ msg_NewAssignment_Isolated "Isolated") Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_Isolated $ concat [ "(Recommended for tests.) Submissions for other assignments of the course are not visible in the " , "precense of an isolated assignments. Note: If there is more than one isolated assignment for the " , "same course, all the isolated assignment and submissions will be visible for the students." ] Bootstrap.row $ Bootstrap.colMd6 $ do bootstrapCheckbox $ do checkBoxRO (fieldName assignmentAspectField) (Assignment.isNoOfTries aas) readOnly (Assignment.NoOfTries 0) (msg $ msg_NewAssignment_NoOfTries "No of tries") Bootstrap.row $ Bootstrap.colMd6 $ Bootstrap.formGroup $ editable $ numberInput assignmentNoOfTries (Just 1) (Just 1000) noOfTries ! Bootstrap.formControl Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_NoOfTries $ "Limitation the number of the submissions (per student) for the assignment." bootstrapCheckbox $ checkBoxRO (fieldName assignmentAspectField) (Assignment.isPasswordProtected aas) readOnly (Assignment.Password "") (msg $ msg_NewAssignment_PasswordProtected "Password-protected") Bootstrap.helpBlock $ msg $ msg_NewAssignment_Info_Password $ concat [ "(Recommended for tests.) Submissions may be only submitted by providing the password. " , "The teacher shall use the password during the test in order to authenticate the " , "submission for the student." ] Bootstrap.row $ Bootstrap.colMd6 $ Bootstrap.formGroup $ do H.label $ fromString $ msg $ msg_NewAssignment_Password "Password" editable $ Bootstrap.inputForFormControl ! name assignmentPwd ! type_ "text" ! value (fromString $ fromMaybe "" pwd) Bootstrap.rowColMd12 $ H.hr -- Assignment Properties pageDataCata (const5 $ assignmentPropertiesSection editable) (const5 $ assignmentPropertiesSection editable) (const7 $ assignmentPropertiesSection editable) (const5 $ assignmentPropertiesSection readOnly) (const7 $ assignmentPropertiesSection editable) (const7 $ assignmentPropertiesSection editable) (const8 $ assignmentPropertiesSection editable) pd submissionTypeSelection msg pd -- Assignment Description Bootstrap.formGroup $ do let assignmentDesc = fromString $ fieldName assignmentDescField Bootstrap.labelFor assignmentDesc $ fromString . msg $ msg_NewAssignment_Description "Description" editOrReadOnly pd $ Bootstrap.textAreaField assignmentDesc $ do fromString $ fromAssignment Assignment.desc (fromString . msg $ msg_NewAssignment_Description_Default $ unlines [ concat [ "This text shall be in markdown format. Here are some quick " , "examples:" ] , "" , " - This is a bullet list item with *emphasis* (italic)." , " - And this is another item in the list with " , " **strong** (bold). Note that the rest of the item" , " shall be aligned." , "" , concat [ "Sometimes one may want to write verbatim text, this how it can " , "be done. However, `verbatim` words may be inlined any time by " , "using the backtick (`` ` ``) symbol." ] , "" , "~~~~~" , "verbatim text" , "~~~~~" , "" , concat [ "Note that links may be also [inserted](http://haskell.org/). And " , "when everything else fails, <a>pure</a> <b>HTML code</b> " , "<i>may be embedded</i>." ] ]) pd -- Preview of the assignment let assignmentPreview a = do Bootstrap.formGroup $ do H.label $ fromString $ msg $ msg_NewAssignment_AssignmentPreview "Assignment Preview" H.div # assignmentTextDiv $ markdownToHtml $ Assignment.desc a pageDataCata (const5 empty) (const5 empty) (const7 empty) (const5 empty) (\_tz _t _key _tsType _fs a _tc -> assignmentPreview a) (\_tz _t _key _tsType _fs a _tc -> assignmentPreview a) (\_tz _k a _t _fs _tst _tm _ev -> assignmentPreview a) pd -- Assignment Test Script Selection Bootstrap.formGroup $ do testScriptSelection msg pd -- Test Case area Bootstrap.formGroup $ do testCaseArea msg pd -- Evaluation config Bootstrap.formGroup $ do let previewAndCommitForm cfg = do evalSelectionDiv hook evalConfig pageDataCata (const5 (previewAndCommitForm binaryConfig)) (const5 (previewAndCommitForm binaryConfig)) (\_timezone _key asg _tsType _files _testcase _ev -> previewAndCommitForm (Assignment.evType asg)) (\_timezone _key asg _tsInfo _testcase -> showEvaluationType msg $ Assignment.evType asg) (\_timezone _time _courses _tsType _files assignment _tccreatio -> previewAndCommitForm (Assignment.evType assignment)) (\_timezone _time _groups _tsType _files assignment _tccreation -> previewAndCommitForm (Assignment.evType assignment)) (\_timezone _key asg _tsType _files _testcase _tcmod _ev -> previewAndCommitForm (Assignment.evType asg)) pd -- Hidden course or group keys for the assignment creation pageDataCata (\_tz _t (key,_course) _tsType _fs -> hiddenInput (fieldName selectedCourse) (courseKeyMap id key)) (\_tz _t (key,_group) _tsType _fs -> hiddenInput (fieldName selectedGroup) (groupKeyMap id key)) (const7 (return ())) (const5 (return ())) (\_tz _t (key,_course) _tsType _fs _a _tc -> hiddenInput (fieldName selectedCourse) (courseKeyMap id key)) (\_tz _t (key,_group) _tsType _fs _a _tc -> hiddenInput (fieldName selectedGroup) (groupKeyMap id key)) (const8 (return ())) pd -- Submit buttons Bootstrap.row $ do let formAction page = onclick (fromString $ concat ["javascript: form.action='", routeOf page, "';"]) Bootstrap.colMd6 $ onlyOnEdit pd $ Bootstrap.submitButtonWithAttr (formAction $ pagePreview pd) (msg $ msg_NewAssignment_PreviewButton "Preview") Bootstrap.colMd6 $ onlyOnEdit pd $ Bootstrap.submitButtonWithAttr (formAction $ page pd) (msg $ msg_NewAssignment_SaveButton "Commit") Bootstrap.turnSelectionsOn where aas = fromAssignment Assignment.aspects Assignment.emptyAspects pd currentEvaluationType = fromAssignment Assignment.evType binaryConfig pd editOrReadOnly = pageDataCata (const5 id) (const5 id) (const7 id) (const5 (! A.readonly "")) (const7 id) (const7 id) (const8 id) onlyOnEdit pd t = pageDataCata (const5 t) (const5 t) (const7 t) (const5 mempty) (const7 t) (const7 t) (const8 t) pd isEditPage = pageDataCata (const5 True) (const5 True) (const7 True) (const5 False) (const7 True) (const7 True) (const8 True) pd timeZoneConverter = pageDataCata (\tz _t _c _ts _fs -> tz) (\tz _t _g _ts _fs -> tz) (\tz _k _a _ts _fs _tc _ev -> tz) (\tz _k _a _ts _tc -> tz) (\tz _t _c _ts _fs _a _tc -> tz) (\tz _t _g _ts _fs _a _tc -> tz) (\tz _k _a _ts _fs _tc _tm _ev -> tz) pd fromAssignment :: (Assignment -> a) -> a -> PageData -> a fromAssignment f d pd = maybe d f (get pd) where get (PD_Assignment _ _ a _ _ _ _) = Just a get (PD_Assignment_Preview _ _ a _ _ _ _ _) = Just a get (PD_ViewAssignment _ _ a _ __ ) = Just a get (PD_Course_Preview _ _ _ _ _ a _) = Just a get (PD_Group_Preview _ _ _ _ _ a _) = Just a get _ = Nothing -- Renders a submission type selection for all page type but the view -- which prints only the selected type submissionTypeSelection msg pd = do let submissionTypeSelection = Bootstrap.selectionWithLabel (fieldName assignmentSubmissionTypeField) (msg $ msg_NewAssignment_SubmissionType "Submission Type") (== currentSubmissionType) [ (txtSubmission, fromString . msg $ msg_NewAssignment_TextSubmission "Text") , (zipSubmission, fromString . msg $ msg_NewAssignment_ZipSubmission "Zip file") ] let showSubmissionType s = Bootstrap.readOnlyTextInputWithDefault "" (msg $ msg_NewAssignment_SubmissionType "Submission Type") (Assignment.submissionType (fromString . msg $ msg_NewAssignment_TextSubmission "Text") (fromString . msg $ msg_NewAssignment_ZipSubmission "Zip file") (Assignment.aspectsToSubmissionType $ Assignment.aspects s)) pageDataCata (const5 submissionTypeSelection) (const5 submissionTypeSelection) (const7 submissionTypeSelection) (\_timezone _key asg _tsInfo _testcase -> showSubmissionType asg) (const7 submissionTypeSelection) (const7 submissionTypeSelection) (const8 submissionTypeSelection) pd testScriptSelection :: (Translation String -> String) -> PageData -> H.Html testScriptSelection msg = pageDataCata (\_tz _t _c tsType _fs -> scriptSelection tsType) (\_tz _t _g tsType _fs -> scriptSelection tsType) (\_tz _k _a tsType _fs mts _ev -> modificationScriptSelection tsType mts) (const5 (return ())) (\_tz _t _c tsType _fs _a tc -> scriptSelectionPreview tsType tc) (\_tz _t _g tsType _fs _a tc -> scriptSelectionPreview tsType tc) (\_tz _k _a tsType _fs mts tm _ev -> modificationScriptSelectionPreview tsType mts tm) where testScriptField :: (IsString s) => s testScriptField = fieldName assignmentTestScriptField scriptSelection ts = maybe (return ()) tsSelection ts tsSelection ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Tester") (const False) (map keyValue (Nothing:map Just ts)) scriptSelectionPreview ts tcp = case tcp of (Just Nothing , _, _) -> scriptSelection ts (Just (Just tsk) , _, _) -> preview ts tsk _ -> return () where preview ts tsk = maybe (return ()) (tsSelectionPreview tsk) ts tsSelectionPreview tsk ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Tester") ((Just tsk)==) (map keyValue (Nothing:map Just ts)) modificationScriptSelection ts mts = maybe (return ()) (mtsSelection mts) ts mtsSelection mts ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Tester") (def mts) (map keyValue (Nothing:map Just ts)) where def Nothing Nothing = True def Nothing _ = False def (Just (_,_,tsk)) (Just tsk') = tsk == tsk' def _ _ = False modificationScriptSelectionPreview ts _mts tm = case (tcmpTestScriptKey tm, ts) of (Just Nothing , Just ts') -> mtsSelection' Nothing ts' (Just (Just tsk), Just ts') -> mtsSelection' (Just tsk) ts' _ -> return () where mtsSelection' tsk ts = do Bootstrap.selectionWithLabel testScriptField (msg $ msg_NewAssignment_TestScripts "Test scripts") (def tsk) (map keyValue (Nothing:map Just ts)) where def Nothing Nothing = True def Nothing _ = False def (Just tsk) (Just tsk') = tsk == tsk' def _ _ = False keyValue :: Maybe (TestScriptKey, TestScriptInfo) -> (Maybe TestScriptKey, String) keyValue Nothing = (Nothing, msg $ msg_NewAssignment_NoTesting "Assignment without testing") keyValue (Just (testScriptKey, tsInfo)) = ((Just testScriptKey), tsiName tsInfo) nothing = Nothing :: Maybe TestScriptKey -- Test Case Ares testCaseArea msg = pageDataCata (\_tz _t _c tsType fs -> createTestCaseArea fs tsType) (\_tz _t _g tsType fs -> createTestCaseArea fs tsType) (\_tz _k _a tsType fs tc _ev -> overwriteTestCaseArea fs tsType tc) (\_tz _k _a ts tc -> viewTestCaseArea ts tc) (\_tz _t _c tsType fs _a tc -> createTestCaseAreaPreview fs tsType tc) (\_tz _t _g tsType fs _a tc -> createTestCaseAreaPreview fs tsType tc) (\_tz _k _a tsType fs tc tm _ev -> overwriteTestCaseAreaPreview fs tsType tc tm) where textArea val = do Bootstrap.labelFor (fieldName assignmentTestCaseField) (msg $ msg_NewAssignment_TestCase "Test cases") editOrReadOnly pd $ Bootstrap.textAreaOptionalField (fieldName assignmentTestCaseField) (maybe mempty fromString val) createTestCaseAreaPreview fs ts tcp = case tcp of (Just Nothing , Nothing, Nothing) -> createTestCaseArea fs ts (Just _ , Just uf, Nothing) -> userFileSelection uf (Just _ , Nothing, Just f) -> textAreaPreview f _ -> return () where userFileSelection uf = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (uf==) (map keyValue fs) Bootstrap.helpBlock $ fromString (printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File")) Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue = (id &&& (usersFile id id)) textAreaPreview f = textArea (Just f) createTestCaseArea fs ts = maybe (return ()) (selectionOrTextArea) (testScriptType' ts) where selectionOrTextArea = testScriptTypeCata (textArea Nothing) usersFileSelection usersFileSelection = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (const False) (map keyValue fs) Bootstrap.helpBlock $ printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File") Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue = (id &&& (usersFile id id)) testCaseText Nothing = Nothing testCaseText (Just (_,tc,_)) = withTestCaseValue (tcValue tc) Just (const Nothing) testCaseFileName Nothing = return () testCaseFileName (Just (_,tc',_)) = fromString $ tcInfo tc' viewTestCaseArea ts tc = maybe (return ()) (selectionOrTextArea) (testScriptType'' ts) where selectionOrTextArea = testScriptTypeCata (textArea (testCaseText tc)) (usersFile) usersFile = do H.h4 $ fromString . msg $ msg_NewAssignment_TestFile "Test File" H.pre $ testCaseFileName tc overwriteTestCaseAreaPreview fs ts tc tm = maybe (return ()) (selectionOrTextAreaPreview) (testScriptType' ts) where selectionOrTextAreaPreview = testScriptTypeCata (textArea (tcmpTextTestCase tm)) -- simple (maybe (return ()) userFileSelectionPreview (tcmpFileTestCase tm)) -- zipped userFileSelectionPreview uf = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (==uf) (map keyValue ((Left ()):map Right fs)) H.pre $ testCaseFileName tc Bootstrap.helpBlock $ fromString $ printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File") Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue l@(Left ()) = (l, msg $ msg_NewAssignment_DoNotOverwrite "No changes") keyValue r@(Right uf) = (r, usersFile id id uf) overwriteTestCaseArea fs ts tc = maybe (return ()) (selectionOrTextArea) (testScriptType' ts) where selectionOrTextArea = testScriptTypeCata (textArea (testCaseText tc)) -- simple usersFileSelection -- zipped usersFileSelection = do Bootstrap.selectionOptionalWithLabel (fieldName assignmentUsersFileField) (msg $ msg_NewAssignment_TestFile "Test File") (const False) (map keyValue ((Left ()):map Right fs)) H.pre $ testCaseFileName tc Bootstrap.helpBlock $ printf (msg $ msg_NewAssignment_TestFile_Info "A file passed to the tester (containing the test data) may be set here. Files may be added on the \"%s\" subpage.") (msg $ msg_LinkText_UploadFile "Upload File") Bootstrap.buttonGroup $ i18n msg $ linkToPageBlank uploadFile where keyValue l@(Left ()) = (l, msg $ msg_NewAssignment_DoNotOverwrite "No changes") keyValue r@(Right uf) = (r, usersFile id id uf) testScriptType' Nothing = Nothing testScriptType' (Just []) = Nothing testScriptType' (Just ((_tk,tsi):_)) = Just $ tsiType tsi testScriptType'' = fmap tsiType pagePreview :: PageData -> PageDesc pagePreview = pageDataCata (\_tz _t (key,_course) _tsType _fs -> newCourseAssignmentPreview key) (\_tz _t (key,_group) _tsType _fs -> newGroupAssignmentPreview key) (\_timezone key _asg _tsType _files _testcase _ev -> modifyAssignmentPreview key) (\_tz k _a _ts _tc -> viewAssignment k) (\_tz _t (key,_course) _tsType _fs _a _tc -> newCourseAssignmentPreview key) (\_tz _t (key,_group) _tsType _fs _a _tc -> newGroupAssignmentPreview key) (\_timezone key _asg _tsType _files _testcase _tc _ev -> modifyAssignmentPreview key) page :: PageData -> PageDesc page = pageDataCata (\_tz _t (key,_course) _tsType _fs -> newCourseAssignment key) (\_tz _t (key,_group) _tsType _fs -> newGroupAssignment key) (\_tz ak _asg _tsType _files _testcase _ev -> modifyAssignment ak) (\_tz k _a _ts _tc -> viewAssignment k) (\_tz _t (key,_course) _tsType _fs _a _tc -> newCourseAssignment key) (\_tz _t (key,_group) _tsType _fs _a _tc -> newGroupAssignment key) (\_tz k _a _fs _ts _tc _tm _ev -> modifyAssignment k) showEvaluationType msg e = Bootstrap.readOnlyTextInputWithDefault "" (msg $ msg_NewAssignment_EvaluationType "Evaluation Type") (evConfigCata (fromString . msg $ msg_NewAssignment_BinaryEvaluation "Binary Evaluation") (const . fromString . msg $ msg_NewAssignment_PercentageEvaluation "Percent") (fromString . msg $ msg_NewAssignment_FreeFormEvaluation "Free Form Evaluation") e) [txtSubmission, zipSubmission] = [Assignment.TextSubmission, Assignment.ZipSubmission] currentSubmissionType = if Assignment.isZippedSubmissions aas then zipSubmission else txtSubmission -- Pages constants newCourseAssignment k = Pages.newCourseAssignment k () newGroupAssignment k = Pages.newGroupAssignment k () modifyAssignment k = Pages.modifyAssignment k () newCourseAssignmentPreview k = Pages.newCourseAssignmentPreview k () newGroupAssignmentPreview k = Pages.newGroupAssignmentPreview k () modifyAssignmentPreview k = Pages.modifyAssignmentPreview k () viewAssignment k = Pages.viewAssignment k () uploadFile = Pages.uploadFile () -- Boostrap bootstrapCheckbox tag = H.div ! A.class_ "checkbox" $ H.label $ tag
andorp/bead
src/Bead/View/Content/Assignment/View.hs
Haskell
bsd-3-clause
32,216
{-#LANGUAGE OverloadedStrings#-} {- Project name: Merge XLS files Min Zhang Date: Oct 13, 2015 Version: v.0.1.0 README: Merge columns from excel files. This program aims for more general file merging situations. However, for the time being, only merge files with exact same first column (row names), have same length (row number), and only take second column. Such as htcount output, and new Ion Proton platform RNA-seq read count output. -} import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as TextIO import qualified Data.Char as C import Control.Applicative import qualified Data.List as L import Control.Monad (fmap) import Data.Ord (comparing) import Data.Function (on) import qualified Safe as S import qualified Data.Maybe as Maybe import qualified Data.Foldable as F (all) import Data.Traversable (sequenceA) import qualified Data.ByteString.Lazy.Char8 as Bl import qualified System.IO as IO import System.Environment import System.Directory import MyText import MyTable import Util main :: IO() main = do preludeInformation paths <- getArgs let inputPaths = init paths -- print input path names into the first column of the file, to avoid confusion of samples let inputPathNames = T.concat ["samples", "\t", untab (map T.pack inputPaths), "\n"] let outputPath = S.lastDef "./outputMergeXls.txt.default" paths -- remove first column header; transpose columns to lists -- TODO: checkHeader is an automation to check if first line contains numbers or letters; if former is the case, delete first line; ducktape here now, need to make this function more reliable. inputFiles <- map (L.transpose . checkHeader) <$> mapM smartTable inputPaths -- check row names of each sample are the same checkRowNames inputFiles -- by default, use the row name of the first sample, if it is false in checkRowNames, the output will be mismatched, although it will still print the output let body = mergeColumns inputFiles let result = T.concat [inputPathNames, body] TextIO.writeFile outputPath result preludeInformation :: IO () preludeInformation = do putStrLn "mergeXls: merge columns from excel files. Note: The first row will be automatically removed." putStrLn "Usage: mergeXls input1 input2 input3 outputpath\n" -- TODO: check if first line is header or numbers checkHeader :: [a] -> [a] checkHeader [] = [] checkHeader (x:xs) = if isHeader x then xs else (x:xs) where isHeader x = True -- samples are long form (eg: [[rowname1, rowname2, rowname3, ...], [readnumber1, rn2, rn3, ...]]) checkRowNames :: Eq a => [[a]] -> IO () checkRowNames samples = do let rownames = map (S.headNote "checkRowName head, take first colunm") samples if and [a==b|a<- rownames, b<-rownames] then print "All samples have same rownames. Merged output will be printed." else print "Samples with different row names. The merged output is printed, but likely to be mismatched. Check inputs." mergeColumns :: [[[T.Text]]] -> T.Text mergeColumns inputFiles = let rownames = S.headNote "mergeColumns head call" (S.headNote "mergeColumns head call of first sample" inputFiles) counts = map (S.lastNote "mergeColumns last call") inputFiles in T.unlines $ map untab $ L.transpose $ rownames : counts
Min-/fourseq
src/utils/MergeXls.hs
Haskell
bsd-3-clause
3,324
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveFunctor #-} {-| TT is the core language of Idris. The language has: * Full dependent types * A hierarchy of universes, with cumulativity: Type : Type1, Type1 : Type2, ... * Pattern matching letrec binding * (primitive types defined externally) Some technical stuff: * Typechecker is kept as simple as possible - no unification, just a checker for incomplete terms. * We have a simple collection of tactics which we use to elaborate source programs with implicit syntax into fully explicit terms. -} module Idris.Core.TT(module Idris.Core.TT, module Idris.Core.TC) where import Idris.Core.TC import Control.Monad.State.Strict import Control.Monad.Trans.Error (Error(..)) import Debug.Trace import qualified Data.Map.Strict as Map import Data.Char import Numeric (showIntAtBase) import qualified Data.Text as T import Data.List hiding (insert) import Data.Set(Set, member, fromList, insert) import Data.Maybe (listToMaybe) import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V import qualified Data.Binary as B import Data.Binary hiding (get, put) import Foreign.Storable (sizeOf) import Util.Pretty hiding (Str) data Option = TTypeInTType | CheckConv deriving Eq -- | Source location. These are typically produced by the parser 'Idris.Parser.getFC' data FC = FC { fc_fname :: String, -- ^ Filename fc_start :: (Int, Int), -- ^ Line and column numbers for the start of the location span fc_end :: (Int, Int) -- ^ Line and column numbers for the end of the location span } -- | Ignore source location equality (so deriving classes do not compare FCs) instance Eq FC where _ == _ = True -- | FC with equality newtype FC' = FC' { unwrapFC :: FC } instance Eq FC' where FC' fc == FC' fc' = fcEq fc fc' where fcEq (FC n s e) (FC n' s' e') = n == n' && s == s' && e == e' -- | Empty source location emptyFC :: FC emptyFC = fileFC "" -- | Source location with file only fileFC :: String -> FC fileFC s = FC s (0, 0) (0, 0) {-! deriving instance Binary FC deriving instance NFData FC !-} instance Sized FC where size (FC f s e) = 4 + length f instance Show FC where show (FC f s e) = f ++ ":" ++ showLC s e where showLC (sl, sc) (el, ec) | sl == el && sc == ec = show sl ++ ":" ++ show sc | sl == el = show sl ++ ":" ++ show sc ++ "-" ++ show ec | otherwise = show sl ++ ":" ++ show sc ++ "-" ++ show el ++ ":" ++ show ec -- | Output annotation for pretty-printed name - decides colour data NameOutput = TypeOutput | FunOutput | DataOutput | MetavarOutput | PostulateOutput -- | Text formatting output data TextFormatting = BoldText | ItalicText | UnderlineText -- | Output annotations for pretty-printing data OutputAnnotation = AnnName Name (Maybe NameOutput) (Maybe String) (Maybe String) -- ^^ The name, classification, docs overview, and pretty-printed type | AnnBoundName Name Bool -- ^^ The name and whether it is implicit | AnnConst Const | AnnData String String -- ^ type, doc overview | AnnType String String -- ^ name, doc overview | AnnKeyword | AnnFC FC | AnnTextFmt TextFormatting | AnnTerm [(Name, Bool)] (TT Name) -- ^ pprint bound vars, original term | AnnSearchResult Ordering -- ^ more general, isomorphic, or more specific | AnnErr Err -- | Used for error reflection data ErrorReportPart = TextPart String | NamePart Name | TermPart Term | SubReport [ErrorReportPart] deriving (Show, Eq) -- Please remember to keep Err synchronised with -- Language.Reflection.Errors.Err in the stdlib! -- | Idris errors. Used as exceptions in the compiler, but reported to users -- if they reach the top level. data Err' t = Msg String | InternalMsg String | CantUnify Bool t t (Err' t) [(Name, t)] Int -- Int is 'score' - how much we did unify -- Bool indicates recoverability, True indicates more info may make -- unification succeed | InfiniteUnify Name t [(Name, t)] | CantConvert t t [(Name, t)] | CantSolveGoal t [(Name, t)] | UnifyScope Name Name t [(Name, t)] | CantInferType String | NonFunctionType t t | NotEquality t t | TooManyArguments Name | CantIntroduce t | NoSuchVariable Name | WithFnType t | NoTypeDecl Name | NotInjective t t t | CantResolve t | CantResolveAlts [Name] | IncompleteTerm t | UniverseError | UniqueError Universe Name | UniqueKindError Universe Name | ProgramLineComment | Inaccessible Name | NonCollapsiblePostulate Name | AlreadyDefined Name | ProofSearchFail (Err' t) | NoRewriting t | At FC (Err' t) | Elaborating String Name (Err' t) | ElaboratingArg Name Name [(Name, Name)] (Err' t) | ProviderError String | LoadingFailed String (Err' t) | ReflectionError [[ErrorReportPart]] (Err' t) | ReflectionFailed String (Err' t) deriving (Eq, Functor) type Err = Err' Term {-! deriving instance NFData Err !-} instance Sized ErrorReportPart where size (TextPart msg) = 1 + length msg size (TermPart t) = 1 + size t size (NamePart n) = 1 + size n size (SubReport rs) = 1 + size rs instance Sized Err where size (Msg msg) = length msg size (InternalMsg msg) = length msg size (CantUnify _ left right err _ score) = size left + size right + size err size (InfiniteUnify _ right _) = size right size (CantConvert left right _) = size left + size right size (UnifyScope _ _ right _) = size right size (NoSuchVariable name) = size name size (NoTypeDecl name) = size name size (NotInjective l c r) = size l + size c + size r size (CantResolve trm) = size trm size (NoRewriting trm) = size trm size (CantResolveAlts _) = 1 size (IncompleteTerm trm) = size trm size UniverseError = 1 size ProgramLineComment = 1 size (At fc err) = size fc + size err size (Elaborating _ n err) = size err size (ElaboratingArg _ _ _ err) = size err size (ProviderError msg) = length msg size (LoadingFailed fn e) = 1 + length fn + size e size _ = 1 score :: Err -> Int score (CantUnify _ _ _ m _ s) = s + score m score (CantResolve _) = 20 score (NoSuchVariable _) = 1000 score (ProofSearchFail e) = score e score (CantSolveGoal _ _) = 100000 score (InternalMsg _) = -1 score (At _ e) = score e score (ElaboratingArg _ _ _ e) = score e score (Elaborating _ _ e) = score e score _ = 0 instance Show Err where show (Msg s) = s show (InternalMsg s) = "Internal error: " ++ show s show (CantUnify rec l r e sc i) = "CantUnify " ++ show rec ++ " " ++ show l ++ " " ++ show r ++ " " ++ show e ++ " in " ++ show sc ++ " " ++ show i show (CantSolveGoal g _) = "CantSolve " ++ show g show (Inaccessible n) = show n ++ " is not an accessible pattern variable" show (ProviderError msg) = "Type provider error: " ++ msg show (LoadingFailed fn e) = "Loading " ++ fn ++ " failed: (TT) " ++ show e show ProgramLineComment = "Program line next to comment" show (At f e) = show f ++ ":" ++ show e show (ElaboratingArg f x prev e) = "Elaborating " ++ show f ++ " arg " ++ show x ++ ": " ++ show e show (Elaborating what n e) = "Elaborating " ++ what ++ show n ++ ":" ++ show e show (ProofSearchFail e) = "Proof search fail: " ++ show e show _ = "Error" instance Pretty Err OutputAnnotation where pretty (Msg m) = text m pretty (CantUnify _ l r e _ i) = text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r <+> nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i)) pretty (ProviderError msg) = text msg pretty err@(LoadingFailed _ _) = text (show err) pretty _ = text "Error" instance Error Err where strMsg = InternalMsg type TC = TC' Err instance (Pretty a OutputAnnotation) => Pretty (TC a) OutputAnnotation where pretty (OK ok) = pretty ok pretty (Error err) = text "Error" <+> colon <+> pretty err instance Show a => Show (TC a) where show (OK x) = show x show (Error str) = "Error: " ++ show str tfail :: Err -> TC a tfail e = Error e failMsg :: String -> TC a failMsg str = Error (Msg str) trun :: FC -> TC a -> TC a trun fc (OK a) = OK a trun fc (Error e) = Error (At fc e) discard :: Monad m => m a -> m () discard f = f >> return () showSep :: String -> [String] -> String showSep sep [] = "" showSep sep [x] = x showSep sep (x:xs) = x ++ sep ++ showSep sep xs pmap f (x, y) = (f x, f y) traceWhen True msg a = trace msg a traceWhen False _ a = a -- RAW TERMS ---------------------------------------------------------------- -- | Names are hierarchies of strings, describing scope (so no danger of -- duplicate names, but need to be careful on lookup). data Name = UN T.Text -- ^ User-provided name | NS Name [T.Text] -- ^ Root, namespaces | MN Int T.Text -- ^ Machine chosen names | NErased -- ^ Name of something which is never used in scope | SN SpecialName -- ^ Decorated function names | SymRef Int -- ^ Reference to IBC file symbol table (used during serialisation) deriving (Eq, Ord) txt :: String -> T.Text txt = T.pack str :: T.Text -> String str = T.unpack tnull :: T.Text -> Bool tnull = T.null thead :: T.Text -> Char thead = T.head -- Smart constructors for names, using old String style sUN :: String -> Name sUN s = UN (txt s) sNS :: Name -> [String] -> Name sNS n ss = NS n (map txt ss) sMN :: Int -> String -> Name sMN i s = MN i (txt s) {-! deriving instance Binary Name deriving instance NFData Name !-} data SpecialName = WhereN Int Name Name | WithN Int Name | InstanceN Name [T.Text] | ParentN Name T.Text | MethodN Name | CaseN Name | ElimN Name | InstanceCtorN Name deriving (Eq, Ord) {-! deriving instance Binary SpecialName deriving instance NFData SpecialName !-} sInstanceN :: Name -> [String] -> SpecialName sInstanceN n ss = InstanceN n (map T.pack ss) sParentN :: Name -> String -> SpecialName sParentN n s = ParentN n (T.pack s) instance Sized Name where size (UN n) = 1 size (NS n els) = 1 + length els size (MN i n) = 1 size _ = 1 instance Pretty Name OutputAnnotation where pretty n@(UN n') = annotate (AnnName n Nothing Nothing Nothing) $ text (T.unpack n') pretty n@(NS un s) = annotate (AnnName n Nothing Nothing Nothing) . noAnnotate $ pretty un pretty n@(MN i s) = annotate (AnnName n Nothing Nothing Nothing) $ lbrace <+> text (T.unpack s) <+> (text . show $ i) <+> rbrace pretty n@(SN s) = annotate (AnnName n Nothing Nothing Nothing) $ text (show s) instance Pretty [Name] OutputAnnotation where pretty = encloseSep empty empty comma . map pretty instance Show Name where show (UN n) = str n show (NS n s) = showSep "." (map T.unpack (reverse s)) ++ "." ++ show n show (MN _ u) | u == txt "underscore" = "_" show (MN i s) = "{" ++ str s ++ show i ++ "}" show (SN s) = show s show NErased = "_" instance Show SpecialName where show (WhereN i p c) = show p ++ ", " ++ show c show (WithN i n) = "with block in " ++ show n show (InstanceN cl inst) = showSep ", " (map T.unpack inst) ++ " instance of " ++ show cl show (MethodN m) = "method " ++ show m show (ParentN p c) = show p ++ "#" ++ T.unpack c show (CaseN n) = "case block in " ++ show n show (ElimN n) = "<<" ++ show n ++ " eliminator>>" show (InstanceCtorN n) = "constructor of " ++ show n -- Show a name in a way decorated for code generation, not human reading showCG :: Name -> String showCG (UN n) = T.unpack n showCG (NS n s) = showSep "." (map T.unpack (reverse s)) ++ "." ++ showCG n showCG (MN _ u) | u == txt "underscore" = "_" showCG (MN i s) = "{" ++ T.unpack s ++ show i ++ "}" showCG (SN s) = showCG' s where showCG' (WhereN i p c) = showCG p ++ ":" ++ showCG c ++ ":" ++ show i showCG' (WithN i n) = "_" ++ showCG n ++ "_with_" ++ show i showCG' (InstanceN cl inst) = '@':showCG cl ++ '$':showSep ":" (map T.unpack inst) showCG' (MethodN m) = '!':showCG m showCG' (ParentN p c) = showCG p ++ "#" ++ show c showCG' (CaseN c) = showCG c ++ "_case" showCG' (ElimN sn) = showCG sn ++ "_elim" showCG NErased = "_" -- |Contexts allow us to map names to things. A root name maps to a collection -- of things in different namespaces with that name. type Ctxt a = Map.Map Name (Map.Map Name a) emptyContext = Map.empty mapCtxt :: (a -> b) -> Ctxt a -> Ctxt b mapCtxt = fmap . fmap -- |Return True if the argument 'Name' should be interpreted as the name of a -- typeclass. tcname (UN xs) | T.null xs = False | otherwise = T.head xs == '@' tcname (NS n _) = tcname n tcname (SN (InstanceN _ _)) = True tcname (SN (MethodN _)) = True tcname (SN (ParentN _ _)) = True tcname _ = False implicitable (NS n _) = implicitable n implicitable (UN xs) | T.null xs = False | otherwise = isLower (T.head xs) || T.head xs == '_' implicitable (MN _ x) = not (tnull x) && thead x /= '_' implicitable _ = False nsroot (NS n _) = n nsroot n = n -- this will overwrite already existing definitions addDef :: Name -> a -> Ctxt a -> Ctxt a addDef n v ctxt = case Map.lookup (nsroot n) ctxt of Nothing -> Map.insert (nsroot n) (Map.insert n v Map.empty) ctxt Just xs -> Map.insert (nsroot n) (Map.insert n v xs) ctxt {-| Look up a name in the context, given an optional namespace. The name (n) may itself have a (partial) namespace given. Rules for resolution: - if an explicit namespace is given, return the names which match it. If none match, return all names. - if the name has has explicit namespace given, return the names which match it and ignore the given namespace. - otherwise, return all names. -} lookupCtxtName :: Name -> Ctxt a -> [(Name, a)] lookupCtxtName n ctxt = case Map.lookup (nsroot n) ctxt of Just xs -> filterNS (Map.toList xs) Nothing -> [] where filterNS [] = [] filterNS ((found, v) : xs) | nsmatch n found = (found, v) : filterNS xs | otherwise = filterNS xs nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps nsmatch (NS _ _) _ = False nsmatch looking found = True lookupCtxt :: Name -> Ctxt a -> [a] lookupCtxt n ctxt = map snd (lookupCtxtName n ctxt) lookupCtxtExact :: Name -> Ctxt a -> Maybe a lookupCtxtExact n ctxt = listToMaybe [ v | (nm, v) <- lookupCtxtName n ctxt, nm == n] deleteDefExact :: Name -> Ctxt a -> Ctxt a deleteDefExact n = Map.adjust (Map.delete n) (nsroot n) updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a updateDef n f ctxt = let ds = lookupCtxtName n ctxt in foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds toAlist :: Ctxt a -> [(Name, a)] toAlist ctxt = let allns = map snd (Map.toList ctxt) in concatMap (Map.toList) allns addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a addAlist [] ctxt = ctxt addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt) data NativeTy = IT8 | IT16 | IT32 | IT64 deriving (Show, Eq, Ord, Enum) instance Pretty NativeTy OutputAnnotation where pretty IT8 = text "Bits8" pretty IT16 = text "Bits16" pretty IT32 = text "Bits32" pretty IT64 = text "Bits64" data IntTy = ITFixed NativeTy | ITNative | ITBig | ITChar | ITVec NativeTy Int deriving (Show, Eq, Ord) intTyName :: IntTy -> String intTyName ITNative = "Int" intTyName ITBig = "BigInt" intTyName (ITFixed sized) = "B" ++ show (nativeTyWidth sized) intTyName (ITChar) = "Char" intTyName (ITVec ity count) = "B" ++ show (nativeTyWidth ity) ++ "x" ++ show count data ArithTy = ATInt IntTy | ATFloat -- TODO: Float vectors https://github.com/idris-lang/Idris-dev/issues/1723 deriving (Show, Eq, Ord) {-! deriving instance NFData IntTy deriving instance NFData NativeTy deriving instance NFData ArithTy !-} instance Pretty ArithTy OutputAnnotation where pretty (ATInt ITNative) = text "Int" pretty (ATInt ITBig) = text "BigInt" pretty (ATInt ITChar) = text "Char" pretty (ATInt (ITFixed n)) = pretty n pretty (ATInt (ITVec e c)) = pretty e <> text "x" <> (text . show $ c) pretty ATFloat = text "Float" nativeTyWidth :: NativeTy -> Int nativeTyWidth IT8 = 8 nativeTyWidth IT16 = 16 nativeTyWidth IT32 = 32 nativeTyWidth IT64 = 64 {-# DEPRECATED intTyWidth "Non-total function, use nativeTyWidth and appropriate casing" #-} intTyWidth :: IntTy -> Int intTyWidth (ITFixed n) = nativeTyWidth n intTyWidth ITNative = 8 * sizeOf (0 :: Int) intTyWidth ITChar = error "IRTS.Lang.intTyWidth: Characters have platform and backend dependent width" intTyWidth ITBig = error "IRTS.Lang.intTyWidth: Big integers have variable width" data Const = I Int | BI Integer | Fl Double | Ch Char | Str String | B8 Word8 | B16 Word16 | B32 Word32 | B64 Word64 | B8V (Vector Word8) | B16V (Vector Word16) | B32V (Vector Word32) | B64V (Vector Word64) | AType ArithTy | StrType | PtrType | ManagedPtrType | BufferType | VoidType | Forgot deriving (Eq, Ord) {-! deriving instance Binary Const deriving instance NFData Const !-} instance Sized Const where size _ = 1 instance Pretty Const OutputAnnotation where pretty (I i) = text . show $ i pretty (BI i) = text . show $ i pretty (Fl f) = text . show $ f pretty (Ch c) = text . show $ c pretty (Str s) = text s pretty (AType a) = pretty a pretty StrType = text "String" pretty BufferType = text "prim__UnsafeBuffer" pretty PtrType = text "Ptr" pretty ManagedPtrType = text "Ptr" pretty VoidType = text "Void" pretty Forgot = text "Forgot" pretty (B8 w) = text . show $ w pretty (B16 w) = text . show $ w pretty (B32 w) = text . show $ w pretty (B64 w) = text . show $ w -- | Determines whether the input constant represents a type constIsType :: Const -> Bool constIsType (I _) = False constIsType (BI _) = False constIsType (Fl _) = False constIsType (Ch _) = False constIsType (Str _) = False constIsType (B8 _) = False constIsType (B16 _) = False constIsType (B32 _) = False constIsType (B64 _) = False constIsType (B8V _) = False constIsType (B16V _) = False constIsType (B32V _) = False constIsType (B64V _) = False constIsType _ = True -- | Get the docstring for a Const constDocs :: Const -> String constDocs c@(AType (ATInt ITBig)) = "Arbitrary-precision integers" constDocs c@(AType (ATInt ITNative)) = "Fixed-precision integers of undefined size" constDocs c@(AType (ATInt ITChar)) = "Characters in some unspecified encoding" constDocs c@(AType ATFloat) = "Double-precision floating-point numbers" constDocs StrType = "Strings in some unspecified encoding" constDocs PtrType = "Foreign pointers" constDocs ManagedPtrType = "Managed pointers" constDocs BufferType = "Copy-on-write buffers" constDocs c@(AType (ATInt (ITFixed IT8))) = "Eight bits (unsigned)" constDocs c@(AType (ATInt (ITFixed IT16))) = "Sixteen bits (unsigned)" constDocs c@(AType (ATInt (ITFixed IT32))) = "Thirty-two bits (unsigned)" constDocs c@(AType (ATInt (ITFixed IT64))) = "Sixty-four bits (unsigned)" constDocs c@(AType (ATInt (ITVec IT8 16))) = "Vectors of sixteen eight-bit values" constDocs c@(AType (ATInt (ITVec IT16 8))) = "Vectors of eight sixteen-bit values" constDocs c@(AType (ATInt (ITVec IT32 4))) = "Vectors of four thirty-two-bit values" constDocs c@(AType (ATInt (ITVec IT64 2))) = "Vectors of two sixty-four-bit values" constDocs (Fl f) = "A float" constDocs (I i) = "A fixed-precision integer" constDocs (BI i) = "An arbitrary-precision integer" constDocs (Str s) = "A string of length " ++ show (length s) constDocs (Ch c) = "A character" constDocs (B8 w) = "The eight-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B16 w) = "The sixteen-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B32 w) = "The thirty-two-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B64 w) = "The sixty-four-bit value 0x" ++ showIntAtBase 16 intToDigit w "" constDocs (B8V v) = "A vector of eight-bit values" constDocs (B16V v) = "A vector of sixteen-bit values" constDocs (B32V v) = "A vector of thirty-two-bit values" constDocs (B64V v) = "A vector of sixty-four-bit values" constDocs prim = "Undocumented" data Universe = NullType | UniqueType | AllTypes deriving (Eq, Ord) instance Show Universe where show UniqueType = "UniqueType" show NullType = "NullType" show AllTypes = "Type*" data Raw = Var Name | RBind Name (Binder Raw) Raw | RApp Raw Raw | RType | RUType Universe | RForce Raw | RConstant Const deriving (Show, Eq) instance Sized Raw where size (Var name) = 1 size (RBind name bind right) = 1 + size bind + size right size (RApp left right) = 1 + size left + size right size RType = 1 size (RUType _) = 1 size (RForce raw) = 1 + size raw size (RConstant const) = size const instance Pretty Raw OutputAnnotation where pretty = text . show {-! deriving instance Binary Raw deriving instance NFData Raw !-} -- The type parameter `b` will normally be something like `TT Name` or just -- `Raw`. We do not make a type-level distinction between TT terms that happen -- to be TT types and TT terms that are not TT types. -- | All binding forms are represented in a uniform fashion. This type only represents -- the types of bindings (and their values, if any); the attached identifiers are part -- of the 'Bind' constructor for the 'TT' type. data Binder b = Lam { binderTy :: !b {-^ type annotation for bound variable-}} | Pi { binderTy :: !b, binderKind :: !b } {-^ A binding that occurs in a function type expression, e.g. @(x:Int) -> ...@ -} | Let { binderTy :: !b, binderVal :: b {-^ value for bound variable-}} -- ^ A binding that occurs in a @let@ expression | NLet { binderTy :: !b, binderVal :: b } | Hole { binderTy :: !b} | GHole { envlen :: Int, binderTy :: !b} | Guess { binderTy :: !b, binderVal :: b } | PVar { binderTy :: !b } -- ^ A pattern variable | PVTy { binderTy :: !b } deriving (Show, Eq, Ord, Functor, Foldable, Traversable) {-! deriving instance Binary Binder deriving instance NFData Binder !-} instance Sized a => Sized (Binder a) where size (Lam ty) = 1 + size ty size (Pi ty _) = 1 + size ty size (Let ty val) = 1 + size ty + size val size (NLet ty val) = 1 + size ty + size val size (Hole ty) = 1 + size ty size (GHole _ ty) = 1 + size ty size (Guess ty val) = 1 + size ty + size val size (PVar ty) = 1 + size ty size (PVTy ty) = 1 + size ty fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b) fmapMB f (Let t v) = liftM2 Let (f t) (f v) fmapMB f (NLet t v) = liftM2 NLet (f t) (f v) fmapMB f (Guess t v) = liftM2 Guess (f t) (f v) fmapMB f (Lam t) = liftM Lam (f t) fmapMB f (Pi t k) = liftM2 Pi (f t) (f k) fmapMB f (Hole t) = liftM Hole (f t) fmapMB f (GHole i t) = liftM (GHole i) (f t) fmapMB f (PVar t) = liftM PVar (f t) fmapMB f (PVTy t) = liftM PVTy (f t) raw_apply :: Raw -> [Raw] -> Raw raw_apply f [] = f raw_apply f (a : as) = raw_apply (RApp f a) as raw_unapply :: Raw -> (Raw, [Raw]) raw_unapply t = ua [] t where ua args (RApp f a) = ua (a:args) f ua args t = (t, args) -- WELL TYPED TERMS --------------------------------------------------------- -- | Universe expressions for universe checking data UExp = UVar Int -- ^ universe variable | UVal Int -- ^ explicit universe level deriving (Eq, Ord) {-! deriving instance NFData UExp !-} instance Sized UExp where size _ = 1 -- We assume that universe levels have been checked, so anything external -- can just have the same universe variable and we won't get any new -- cycles. instance Binary UExp where put x = return () get = return (UVar (-1)) instance Show UExp where show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')] | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26) show (UVal x) = show x -- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")" -- | Universe constraints data UConstraint = ULT UExp UExp -- ^ Strictly less than | ULE UExp UExp -- ^ Less than or equal to deriving Eq instance Show UConstraint where show (ULT x y) = show x ++ " < " ++ show y show (ULE x y) = show x ++ " <= " ++ show y type UCs = (Int, [UConstraint]) data NameType = Bound | Ref | DCon {nt_tag :: Int, nt_arity :: Int, nt_unique :: Bool} -- ^ Data constructor | TCon {nt_tag :: Int, nt_arity :: Int} -- ^ Type constructor deriving (Show, Ord) {-! deriving instance Binary NameType deriving instance NFData NameType !-} instance Sized NameType where size _ = 1 instance Pretty NameType OutputAnnotation where pretty = text . show instance Eq NameType where Bound == Bound = True Ref == Ref = True DCon _ a _ == DCon _ b _ = (a == b) -- ignore tag TCon _ a == TCon _ b = (a == b) -- ignore tag _ == _ = False -- | Terms in the core language. The type parameter is the type of -- identifiers used for bindings and explicit named references; -- usually we use @TT 'Name'@. data TT n = P NameType n (TT n) -- ^ named references with type -- (P for "Parameter", motivated by McKinna and Pollack's -- Pure Type Systems Formalized) | V !Int -- ^ a resolved de Bruijn-indexed variable | Bind n !(Binder (TT n)) (TT n) -- ^ a binding | App !(TT n) (TT n) -- ^ function, function type, arg | Constant Const -- ^ constant | Proj (TT n) !Int -- ^ argument projection; runtime only -- (-1) is a special case for 'subtract one from BI' | Erased -- ^ an erased term | Impossible -- ^ special case for totality checking | TType UExp -- ^ the type of types at some level | UType Universe -- ^ Uniqueness type universe (disjoint from TType) deriving (Ord, Functor) {-! deriving instance Binary TT deriving instance NFData TT !-} class TermSize a where termsize :: Name -> a -> Int instance TermSize a => TermSize [a] where termsize n [] = 0 termsize n (x : xs) = termsize n x + termsize n xs instance TermSize (TT Name) where termsize n (P _ n' _) | n' == n = 1000000 -- recursive => really big | otherwise = 1 termsize n (V _) = 1 -- for `Bind` terms, we can erroneously declare a term -- "recursive => really big" if the name of the bound -- variable is the same as the name we're using -- So generate a different name in that case. termsize n (Bind n' (Let t v) sc) = let rn = if n == n' then sMN 0 "noname" else n in termsize rn v + termsize rn sc termsize n (Bind n' b sc) = let rn = if n == n' then sMN 0 "noname" else n in termsize rn sc termsize n (App f a) = termsize n f + termsize n a termsize n (Proj t i) = termsize n t termsize n _ = 1 instance Sized a => Sized (TT a) where size (P name n trm) = 1 + size name + size n + size trm size (V v) = 1 size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy size (App l r) = 1 + size l + size r size (Constant c) = size c size Erased = 1 size (TType u) = 1 + size u instance Pretty a o => Pretty (TT a) o where pretty _ = text "test" type EnvTT n = [(n, Binder (TT n))] data Datatype n = Data { d_typename :: n, d_typetag :: Int, d_type :: (TT n), d_unique :: Bool, d_cons :: [(n, TT n)] } deriving (Show, Functor, Eq) instance Eq n => Eq (TT n) where (==) (P xt x _) (P yt y _) = x == y (==) (V x) (V y) = x == y (==) (Bind _ xb xs) (Bind _ yb ys) = xs == ys && xb == yb (==) (App fx ax) (App fy ay) = ax == ay && fx == fy (==) (TType _) (TType _) = True -- deal with constraints later (==) (Constant x) (Constant y) = x == y (==) (Proj x i) (Proj y j) = x == y && i == j (==) Erased _ = True (==) _ Erased = True (==) _ _ = False -- * A few handy operations on well typed terms: -- | A term is injective iff it is a data constructor, type constructor, -- constant, the type Type, pi-binding, or an application of an injective -- term. isInjective :: TT n -> Bool isInjective (P (DCon _ _ _) _ _) = True isInjective (P (TCon _ _) _ _) = True isInjective (Constant _) = True isInjective (TType x) = True isInjective (Bind _ (Pi _ _) sc) = True isInjective (App f a) = isInjective f isInjective _ = False -- | Count the number of instances of a de Bruijn index in a term vinstances :: Int -> TT n -> Int vinstances i (V x) | i == x = 1 vinstances i (App f a) = vinstances i f + vinstances i a vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc where instancesB (Let t v) = vinstances i v instancesB _ = 0 vinstances i t = 0 -- | Replace the outermost (index 0) de Bruijn variable with the given term instantiate :: TT n -> TT n -> TT n instantiate e = subst 0 where subst i (V x) | i == x = e subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc) subst i (App f a) = App (subst i f) (subst i a) subst i (Proj x idx) = Proj (subst i x) idx subst i t = t -- | As 'instantiate', but also decrement the indices of all de Bruijn variables -- remaining in the term, so that there are no more references to the variable -- that has been substituted. substV :: TT n -> TT n -> TT n substV x tm = dropV 0 (instantiate x tm) where dropV i (V x) | x > i = V (x - 1) | otherwise = V x dropV i (Bind x b sc) = Bind x (fmap (dropV i) b) (dropV (i+1) sc) dropV i (App f a) = App (dropV i f) (dropV i a) dropV i (Proj x idx) = Proj (dropV i x) idx dropV i t = t -- | Replace all non-free de Bruijn references in the given term with references -- to the name of their binding. explicitNames :: TT n -> TT n explicitNames (Bind x b sc) = let b' = fmap explicitNames b in Bind x b' (explicitNames (instantiate (P Bound x (binderTy b')) sc)) explicitNames (App f a) = App (explicitNames f) (explicitNames a) explicitNames (Proj x idx) = Proj (explicitNames x) idx explicitNames t = t -- | Replace references to the given 'Name'-like id with references to -- de Bruijn index 0. pToV :: Eq n => n -> TT n -> TT n pToV n = pToV' n 0 pToV' n i (P _ x _) | n == x = V i pToV' n i (Bind x b sc) -- We can assume the inner scope has been pToVed already, so continue to -- resolve names from the *outer* scope which may happen to have the same id. | n == x = Bind x (fmap (pToV' n i) b) sc | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc) pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a) pToV' n i (Proj t idx) = Proj (pToV' n i t) idx pToV' n i t = t -- increase de Bruijn indices, as if a binder has been added addBinder :: TT n -> TT n addBinder t = ab 0 t where ab top (V i) | i >= top = V (i + 1) | otherwise = V i ab top (Bind x b sc) = Bind x (fmap (ab top) b) (ab (top + 1) sc) ab top (App f a) = App (ab top f) (ab top a) ab top (Proj t idx) = Proj (ab top t) idx ab top t = t -- | Convert several names. First in the list comes out as V 0 pToVs :: Eq n => [n] -> TT n -> TT n pToVs ns tm = pToVs' ns tm 0 where pToVs' [] tm i = tm pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1)) -- | Replace de Bruijn indices in the given term with explicit references to -- the names of the bindings they refer to. It is an error if the given term -- contains free de Bruijn indices. vToP :: TT n -> TT n vToP = vToP' [] where vToP' env (V i) = let (n, b) = (env !! i) in P Bound n (binderTy b) vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in Bind n b' (vToP' ((n, b'):env) sc) vToP' env (App f a) = App (vToP' env f) (vToP' env a) vToP' env t = t -- | Replace every non-free reference to the name of a binding in -- the given term with a de Bruijn index. finalise :: Eq n => TT n -> TT n finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc)) finalise (App f a) = App (finalise f) (finalise a) finalise t = t -- Once we've finished checking everything about a term we no longer need -- the type on the 'P' so erase it so save memory pEraseType :: TT n -> TT n pEraseType (P nt t _) = P nt t Erased pEraseType (App f a) = App (pEraseType f) (pEraseType a) pEraseType (Bind n b sc) = Bind n (fmap pEraseType b) (pEraseType sc) pEraseType t = t -- | As 'instantiate', but in addition to replacing @'V' 0@, -- replace references to the given 'Name'-like id. subst :: Eq n => n {-^ The id to replace -} -> TT n {-^ The replacement term -} -> TT n {-^ The term to replace in -} -> TT n -- subst n v tm = instantiate v (pToV n tm) subst n v tm = fst $ subst' 0 tm where -- keep track of updates to save allocations - this is a big win on -- large terms in particular -- ('Maybe' would be neater here, but >>= is not the right combinator. -- Feel free to tidy up, as long as it still saves allocating when no -- substitution happens...) subst' i (V x) | i == x = (v, True) subst' i (P _ x _) | n == x = (v, True) subst' i t@(Bind x b sc) | x /= n = let (b', ub) = substB' i b (sc', usc) = subst' (i+1) sc in if ub || usc then (Bind x b' sc', True) else (t, False) subst' i t@(App f a) = let (f', uf) = subst' i f (a', ua) = subst' i a in if uf || ua then (App f' a', True) else (t, False) subst' i t@(Proj x idx) = let (x', u) = subst' i x in if u then (Proj x' idx, u) else (t, False) subst' i t = (t, False) substB' i b@(Let t v) = let (t', ut) = subst' i t (v', uv) = subst' i v in if ut || uv then (Let t' v', True) else (b, False) substB' i b@(Guess t v) = let (t', ut) = subst' i t (v', uv) = subst' i v in if ut || uv then (Guess t' v', True) else (b, False) substB' i b = let (ty', u) = subst' i (binderTy b) in if u then (b { binderTy = ty' }, u) else (b, False) -- If there are no Vs in the term (i.e. in proof state) psubst :: Eq n => n -> TT n -> TT n -> TT n psubst n v tm = s' 0 tm where s' i (V x) | x > i = V (x - 1) | x == i = v | otherwise = V x s' i (P _ x _) | n == x = v s' i (Bind x b sc) | n == x = Bind x (fmap (s' i) b) sc | otherwise = Bind x (fmap (s' i) b) (s' (i+1) sc) s' i (App f a) = App (s' i f) (s' i a) s' i (Proj t idx) = Proj (s' i t) idx s' i t = t -- | As 'subst', but takes a list of (name, substitution) pairs instead -- of a single name and substitution substNames :: Eq n => [(n, TT n)] -> TT n -> TT n substNames [] t = t substNames ((n, tm) : xs) t = subst n tm (substNames xs t) -- | Replaces all terms equal (in the sense of @(==)@) to -- the old term with the new term. substTerm :: Eq n => TT n {-^ Old term -} -> TT n {-^ New term -} -> TT n {-^ template term -} -> TT n substTerm old new = st where st t | t == old = new st (App f a) = App (st f) (st a) st (Bind x b sc) = Bind x (fmap st b) (st sc) st t = t -- | Return number of occurrences of V 0 or bound name i the term occurrences :: Eq n => n -> TT n -> Int occurrences n t = execState (no' 0 t) 0 where no' i (V x) | i == x = do num <- get; put (num + 1) no' i (P Bound x _) | n == x = do num <- get; put (num + 1) no' i (Bind n b sc) = do noB' i b; no' (i+1) sc where noB' i (Let t v) = do no' i t; no' i v noB' i (Guess t v) = do no' i t; no' i v noB' i b = no' i (binderTy b) no' i (App f a) = do no' i f; no' i a no' i (Proj x _) = no' i x no' i _ = return () -- | Returns true if V 0 and bound name n do not occur in the term noOccurrence :: Eq n => n -> TT n -> Bool noOccurrence n t = no' 0 t where no' i (V x) = not (i == x) no' i (P Bound x _) = not (n == x) no' i (Bind n b sc) = noB' i b && no' (i+1) sc where noB' i (Let t v) = no' i t && no' i v noB' i (Guess t v) = no' i t && no' i v noB' i b = no' i (binderTy b) no' i (App f a) = no' i f && no' i a no' i (Proj x _) = no' i x no' i _ = True -- | Returns all names used free in the term freeNames :: Eq n => TT n -> [n] freeNames (P _ n _) = [n] freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n]) ++ freeNames t freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n]) freeNames (App f a) = nub $ freeNames f ++ freeNames a freeNames (Proj x i) = nub $ freeNames x freeNames _ = [] -- | Return the arity of a (normalised) type arity :: TT n -> Int arity (Bind n (Pi t _) sc) = 1 + arity sc arity _ = 0 -- | Deconstruct an application; returns the function and a list of arguments unApply :: TT n -> (TT n, [TT n]) unApply t = ua [] t where ua args (App f a) = ua (a:args) f ua args t = (t, args) -- | Returns a term representing the application of the first argument -- (a function) to every element of the second argument. mkApp :: TT n -> [TT n] -> TT n mkApp f [] = f mkApp f (a:as) = mkApp (App f a) as unList :: Term -> Maybe [Term] unList tm = case unApply tm of (nil, [_]) -> Just [] (cons, ([_, x, xs])) -> do rest <- unList xs return $ x:rest (f, args) -> Nothing -- | Cast a 'TT' term to a 'Raw' value, discarding universe information and -- the types of named references and replacing all de Bruijn indices -- with the corresponding name. It is an error if there are free de -- Bruijn indices. forget :: TT Name -> Raw forget tm = forgetEnv [] tm forgetEnv :: [Name] -> TT Name -> Raw forgetEnv env (P _ n _) = Var n forgetEnv env (V i) = Var (env !! i) forgetEnv env (Bind n b sc) = let n' = uniqueName n env in RBind n' (fmap (forgetEnv env) b) (forgetEnv (n':env) sc) forgetEnv env (App f a) = RApp (forgetEnv env f) (forgetEnv env a) forgetEnv env (Constant c) = RConstant c forgetEnv env (TType i) = RType forgetEnv env (UType u) = RUType u forgetEnv env Erased = RConstant Forgot -- | Introduce a 'Bind' into the given term for each element of the -- given list of (name, binder) pairs. bindAll :: [(n, Binder (TT n))] -> TT n -> TT n bindAll [] t = t bindAll ((n, b) : bs) t = Bind n b (bindAll bs t) -- | Like 'bindAll', but the 'Binder's are 'TT' terms instead. -- The first argument is a function to map @TT@ terms to @Binder@s. -- This function might often be something like 'Lam', which directly -- constructs a @Binder@ from a @TT@ term. bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs) -- | Return a list of pairs of the names of the outermost 'Pi'-bound -- variables in the given term, together with their types. getArgTys :: TT n -> [(n, TT n)] getArgTys (Bind n (PVar _) sc) = getArgTys sc getArgTys (Bind n (PVTy _) sc) = getArgTys sc getArgTys (Bind n (Pi t _) sc) = (n, t) : getArgTys sc getArgTys _ = [] getRetTy :: TT n -> TT n getRetTy (Bind n (PVar _) sc) = getRetTy sc getRetTy (Bind n (PVTy _) sc) = getRetTy sc getRetTy (Bind n (Pi _ _) sc) = getRetTy sc getRetTy sc = sc uniqueNameFrom :: [Name] -> [Name] -> Name uniqueNameFrom (s : supply) hs | s `elem` hs = uniqueNameFrom supply hs | otherwise = s uniqueName :: Name -> [Name] -> Name uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs | otherwise = n uniqueNameSet :: Name -> Set Name -> Name uniqueNameSet n hs | n `member` hs = uniqueNameSet (nextName n) hs | otherwise = n uniqueBinders :: [Name] -> TT Name -> TT Name uniqueBinders ns = ubSet (fromList ns) where ubSet ns (Bind n b sc) = let n' = uniqueNameSet n ns ns' = insert n' ns in Bind n' (fmap (ubSet ns') b) (ubSet ns' sc) ubSet ns (App f a) = App (ubSet ns f) (ubSet ns a) ubSet ns t = t nextName (NS x s) = NS (nextName x) s nextName (MN i n) = MN (i+1) n nextName (UN x) = let (num', nm') = T.span isDigit (T.reverse x) nm = T.reverse nm' num = readN (T.reverse num') in UN (nm `T.append` txt (show (num+1))) where readN x | not (T.null x) = read (T.unpack x) readN x = 0 nextName (SN x) = SN (nextName' x) where nextName' (WhereN i f x) = WhereN i f (nextName x) nextName' (WithN i n) = WithN i (nextName n) nextName' (InstanceN n ns) = InstanceN (nextName n) ns nextName' (ParentN n ns) = ParentN (nextName n) ns nextName' (CaseN n) = CaseN (nextName n) nextName' (ElimN n) = ElimN (nextName n) nextName' (MethodN n) = MethodN (nextName n) nextName' (InstanceCtorN n) = InstanceCtorN (nextName n) type Term = TT Name type Type = Term type Env = EnvTT Name -- | an environment with de Bruijn indices 'normalised' so that they all refer to -- this environment newtype WkEnvTT n = Wk (EnvTT n) type WkEnv = WkEnvTT Name instance (Eq n, Show n) => Show (TT n) where show t = showEnv [] t itBitsName IT8 = "Bits8" itBitsName IT16 = "Bits16" itBitsName IT32 = "Bits32" itBitsName IT64 = "Bits64" instance Show Const where show (I i) = show i show (BI i) = show i show (Fl f) = show f show (Ch c) = show c show (Str s) = show s show (B8 x) = show x show (B16 x) = show x show (B32 x) = show x show (B64 x) = show x show (B8V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (B16V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (B32V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (B64V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">" show (AType ATFloat) = "Float" show (AType (ATInt ITBig)) = "Integer" show (AType (ATInt ITNative)) = "Int" show (AType (ATInt ITChar)) = "Char" show (AType (ATInt (ITFixed it))) = itBitsName it show (AType (ATInt (ITVec it c))) = itBitsName it ++ "x" ++ show c show StrType = "String" show BufferType = "prim__UnsafeBuffer" show PtrType = "Ptr" show ManagedPtrType = "ManagedPtr" show VoidType = "Void" showEnv :: (Eq n, Show n) => EnvTT n -> TT n -> String showEnv env t = showEnv' env t False showEnvDbg env t = showEnv' env t True prettyEnv env t = prettyEnv' env t False where prettyEnv' env t dbg = prettySe 10 env t dbg bracket outer inner p | inner > outer = lparen <> p <> rparen | otherwise = p prettySe p env (P nt n t) debug = pretty n <+> if debug then lbracket <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbracket else empty prettySe p env (V i) debug | i < length env = if debug then text . show . fst $ env!!i else lbracket <+> text (show i) <+> rbracket | otherwise = text "unbound" <+> text (show i) <+> text "!" prettySe p env (Bind n b@(Pi t _) sc) debug | noOccurrence n sc && not debug = bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug prettySe p env (Bind n b sc) debug = bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug prettySe p env (App f a) debug = bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug prettySe p env (Proj x i) debug = prettySe 1 env x debug <+> text ("!" ++ show i) prettySe p env (Constant c) debug = pretty c prettySe p env Erased debug = text "[_]" prettySe p env (TType i) debug = text "Type" <+> (text . show $ i) -- Render a `Binder` and its name prettySb env n (Lam t) = prettyB env "λ" "=>" n t prettySb env n (Hole t) = prettyB env "?defer" "." n t prettySb env n (Pi t _) = prettyB env "(" ") ->" n t prettySb env n (PVar t) = prettyB env "pat" "." n t prettySb env n (PVTy t) = prettyB env "pty" "." n t prettySb env n (Let t v) = prettyBv env "let" "in" n t v prettySb env n (Guess t v) = prettyBv env "??" "in" n t v -- Use `op` and `sc` to delimit `n` (a binding name) and its type -- declaration -- e.g. "λx : Int =>" for the Lam case prettyB env op sc n t debug = text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc -- Like `prettyB`, but handle the bindings that have values in addition -- to names and types prettyBv env op sc n t v debug = text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+> prettySe 10 env v debug <> text sc showEnv' env t dbg = se 10 env t where se p env (P nt n t) = show n ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else "" se p env (V i) | i < length env && i >= 0 = (show $ fst $ env!!i) ++ if dbg then "{" ++ show i ++ "}" else "" | otherwise = "!!V " ++ show i ++ "!!" se p env (Bind n b@(Pi t k) sc) | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ arrow k ++ se 10 ((n,b):env) sc where arrow (TType _) = " -> " arrow u = " [" ++ show u ++ "] -> " se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a se p env (Proj x i) = se 1 env x ++ "!" ++ show i se p env (Constant c) = show c se p env Erased = "[__]" se p env Impossible = "[impossible]" se p env (TType i) = "Type " ++ show i se p env (UType u) = show u sb env n (Lam t) = showb env "\\ " " => " n t sb env n (Hole t) = showb env "? " ". " n t sb env n (GHole i t) = showb env "?defer " ". " n t sb env n (Pi t _) = showb env "(" ") -> " n t sb env n (PVar t) = showb env "pat " ". " n t sb env n (PVTy t) = showb env "pty " ". " n t sb env n (Let t v) = showbv env "let " " in " n t v sb env n (Guess t v) = showbv env "?? " " in " n t v showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++ se 10 env v ++ sc bracket outer inner str | inner > outer = "(" ++ str ++ ")" | otherwise = str -- | Check whether a term has any holes in it - impure if so pureTerm :: TT Name -> Bool pureTerm (App f a) = pureTerm f && pureTerm a pureTerm (Bind n b sc) = notClassName n && pureBinder b && pureTerm sc where pureBinder (Hole _) = False pureBinder (Guess _ _) = False pureBinder (Let t v) = pureTerm t && pureTerm v pureBinder t = pureTerm (binderTy t) notClassName (MN _ c) | c == txt "class" = False notClassName _ = True pureTerm _ = True -- | Weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings) weakenTm :: Int -> TT n -> TT n weakenTm i t = wk i 0 t where wk i min (V x) | x >= min = V (i + x) wk i m (App f a) = App (wk i m f) (wk i m a) wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc) wk i m t = t wkb i m t = fmap (wk i m) t -- | Weaken an environment so that all the de Bruijn indices are correct according -- to the latest bound variable weakenEnv :: EnvTT n -> EnvTT n weakenEnv env = wk (length env - 1) env where wk i [] = [] wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v) weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v) weakenTmB i t = t { binderTy = weakenTm i (binderTy t) } -- | Weaken every term in the environment by the given amount weakenTmEnv :: Int -> EnvTT n -> EnvTT n weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b)) -- | Gather up all the outer 'PVar's and 'Hole's in an expression and reintroduce -- them in a canonical order orderPats :: Term -> Term orderPats tm = op [] tm where op [] (App f a) = App f (op [] a) -- for Infer terms op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc op ps (Bind n (Pi t k) sc) = op ((n, Pi t k) : ps) sc op ps sc = bindAll (sortP ps) sc sortP ps = pick [] (reverse ps) pick acc [] = reverse acc pick acc ((n, t) : ps) = pick (insert n t acc) ps insert n t [] = [(n, t)] insert n t ((n',t') : ps) | n `elem` (refsIn (binderTy t') ++ concatMap refsIn (map (binderTy . snd) ps)) = (n', t') : insert n t ps | otherwise = (n,t):(n',t'):ps refsIn :: TT Name -> [Name] refsIn (P _ n _) = [n] refsIn (Bind n b t) = nub $ nb b ++ (refsIn t \\ [n]) where nb (Let t v) = nub (refsIn t) ++ nub (refsIn v) nb (Guess t v) = nub (refsIn t) ++ nub (refsIn v) nb t = refsIn (binderTy t) refsIn (App f a) = nub (refsIn f ++ refsIn a) refsIn _ = [] -- Make sure all the pattern bindings are as far out as possible liftPats :: Term -> Term liftPats tm = let (tm', ps) = runState (getPats tm) [] in orderPats $ bindPats (reverse ps) tm' where bindPats [] tm = tm bindPats ((n, t):ps) tm | n `notElem` map fst ps = Bind n (PVar t) (bindPats ps tm) | otherwise = bindPats ps tm getPats :: Term -> State [(Name, Type)] Term getPats (Bind n (PVar t) sc) = do ps <- get put ((n, t) : ps) getPats sc getPats (Bind n (Guess t v) sc) = do t' <- getPats t v' <- getPats v sc' <- getPats sc return (Bind n (Guess t' v') sc') getPats (Bind n (Let t v) sc) = do t' <- getPats t v' <- getPats v sc' <- getPats sc return (Bind n (Let t' v') sc') getPats (Bind n (Pi t k) sc) = do t' <- getPats t k' <- getPats k sc' <- getPats sc return (Bind n (Pi t' k') sc') getPats (Bind n (Lam t) sc) = do t' <- getPats t sc' <- getPats sc return (Bind n (Lam t') sc') getPats (Bind n (Hole t) sc) = do t' <- getPats t sc' <- getPats sc return (Bind n (Hole t') sc') getPats (App f a) = do f' <- getPats f a' <- getPats a return (App f' a') getPats t = return t allTTNames :: Eq n => TT n -> [n] allTTNames = nub . allNamesIn where allNamesIn (P _ n _) = [n] allNamesIn (Bind n b t) = [n] ++ nb b ++ allNamesIn t where nb (Let t v) = allNamesIn t ++ allNamesIn v nb (Guess t v) = allNamesIn t ++ allNamesIn v nb t = allNamesIn (binderTy t) allNamesIn (App f a) = allNamesIn f ++ allNamesIn a allNamesIn _ = []
andyarvanitis/Idris-dev
src/Idris/Core/TT.hs
Haskell
bsd-3-clause
54,225
-- | Simple but usefull functions, those match no specific module. module Youtan.Utils where -- | Applies a function while the condition are met. while :: ( a -> a -> Bool ) -> ( a -> a ) -> a -> a while con f v = let step x y = if x `con` y then step ( f x ) x else x in step ( f v ) v
triplepointfive/Youtan
src/Youtan/Utils.hs
Haskell
bsd-3-clause
304
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeInType #-} module Functor where import Control.Category import Data.Functor.Compose import Data.Kind (Type) import Prelude hiding (Functor (..), id, (.)) type family Cat k :: k -> k -> Type type Catty a = Category (Cat a) class (Catty j, Catty k) => Functor (f :: j -> k) where fmap :: Cat j a b -> Cat k (f a) (f b) type instance Cat Type = (->) instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (f a) instance Functor ((,) a) where fmap f (a, b) = (a, f b) instance Functor [] where fmap = map instance Functor (Either a) where fmap _ (Left a) = Left a fmap f (Right b) = Right $ f b instance Functor ((->) a) where fmap = (.) instance (Functor f, Functor g) => Functor (Compose f g) where fmap f = Compose . fmap (fmap f) . getCompose newtype Natural (cat :: k -> k -> Type) (f :: j -> k) (g :: j -> k) = Natural { runNatural :: forall x. cat (f x) (g x) } type instance Cat (j -> k) = Natural (Cat k) instance Category k => Category (Natural k) where id = Natural id Natural f . Natural g = Natural (f . g) instance Functor (,) where fmap f = Natural $ \(a, x) -> (f a, x) instance Functor Either where fmap f = Natural $ either (Left . f) Right instance Functor f => Functor (Compose f) where fmap f = Natural $ Compose . fmap (runNatural f) . getCompose fmap1 :: (Catty j, Catty k, Functor f) => Cat j a b -> Cat k (f a x) (f b x) fmap1 = runNatural . fmap instance Functor Compose where fmap f = Natural $ Natural $ Compose . runNatural f . getCompose fmap2 :: (Catty j, Catty k, Functor f) => Cat j a b -> Cat k (f a x y) (f b x y) fmap2 = runNatural . runNatural . fmap class (Catty j, Catty k) => Contravariant (f :: j -> k) where contramap :: Cat j a b -> Cat k (f b) (f a) instance Contravariant (->) where contramap g = Natural (. g) instance (Catty k, cat ~ Cat k) => Contravariant (Natural cat) where contramap g = Natural (. g)
isovector/category-theory
src/Functor.hs
Haskell
bsd-3-clause
2,249
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 This module defines interface types and binders -} {-# LANGUAGE CPP, FlexibleInstances, BangPatterns #-} {-# LANGUAGE MultiWayIf #-} -- FlexibleInstances for Binary (DefMethSpec IfaceType) module IfaceType ( IfExtName, IfLclName, IfaceType(..), IfacePredType, IfaceKind, IfaceCoercion(..), IfaceUnivCoProv(..), IfaceTyCon(..), IfaceTyConInfo(..), IfaceTyConSort(..), IsPromoted(..), IfaceTyLit(..), IfaceTcArgs(..), IfaceContext, IfaceBndr(..), IfaceOneShot(..), IfaceLamBndr, IfaceTvBndr, IfaceIdBndr, IfaceTyConBinder, IfaceForAllBndr, ArgFlag(..), ShowForAllFlag(..), ifForAllBndrTyVar, ifForAllBndrName, ifTyConBinderTyVar, ifTyConBinderName, -- Equality testing isIfaceLiftedTypeKind, -- Conversion from IfaceTcArgs -> [IfaceType] tcArgsIfaceTypes, -- Printing pprIfaceType, pprParendIfaceType, pprPrecIfaceType, pprIfaceContext, pprIfaceContextArr, pprIfaceIdBndr, pprIfaceLamBndr, pprIfaceTvBndr, pprIfaceTyConBinders, pprIfaceBndrs, pprIfaceTcArgs, pprParendIfaceTcArgs, pprIfaceForAllPart, pprIfaceForAllPartMust, pprIfaceForAll, pprIfaceSigmaType, pprIfaceTyLit, pprIfaceCoercion, pprParendIfaceCoercion, splitIfaceSigmaTy, pprIfaceTypeApp, pprUserIfaceForAll, pprIfaceCoTcApp, pprTyTcApp, pprIfacePrefixApp, suppressIfaceInvisibles, stripIfaceInvisVars, stripInvisArgs, mkIfaceTySubst, substIfaceTyVar, substIfaceTcArgs, inDomIfaceTySubst ) where #include "HsVersions.h" import GhcPrelude import {-# SOURCE #-} TysWiredIn ( liftedRepDataConTyCon ) import DynFlags import TyCon hiding ( pprPromotionQuote ) import CoAxiom import Var import PrelNames import Name import BasicTypes import Binary import Outputable import FastString import FastStringEnv import Util import Data.Maybe( isJust ) import Data.List (foldl') import qualified Data.Semigroup as Semi {- ************************************************************************ * * Local (nested) binders * * ************************************************************************ -} type IfLclName = FastString -- A local name in iface syntax type IfExtName = Name -- An External or WiredIn Name can appear in IfaceSyn -- (However Internal or System Names never should) data IfaceBndr -- Local (non-top-level) binders = IfaceIdBndr {-# UNPACK #-} !IfaceIdBndr | IfaceTvBndr {-# UNPACK #-} !IfaceTvBndr type IfaceIdBndr = (IfLclName, IfaceType) type IfaceTvBndr = (IfLclName, IfaceKind) ifaceTvBndrName :: IfaceTvBndr -> IfLclName ifaceTvBndrName (n,_) = n type IfaceLamBndr = (IfaceBndr, IfaceOneShot) data IfaceOneShot -- See Note [Preserve OneShotInfo] in CoreTicy = IfaceNoOneShot -- and Note [The oneShot function] in MkId | IfaceOneShot {- %************************************************************************ %* * IfaceType %* * %************************************************************************ -} ------------------------------- type IfaceKind = IfaceType data IfaceType -- A kind of universal type, used for types and kinds = IfaceFreeTyVar TyVar -- See Note [Free tyvars in IfaceType] | IfaceTyVar IfLclName -- Type/coercion variable only, not tycon | IfaceLitTy IfaceTyLit | IfaceAppTy IfaceType IfaceType | IfaceFunTy IfaceType IfaceType | IfaceDFunTy IfaceType IfaceType | IfaceForAllTy IfaceForAllBndr IfaceType | IfaceTyConApp IfaceTyCon IfaceTcArgs -- Not necessarily saturated -- Includes newtypes, synonyms, tuples | IfaceCastTy IfaceType IfaceCoercion | IfaceCoercionTy IfaceCoercion | IfaceTupleTy -- Saturated tuples (unsaturated ones use IfaceTyConApp) TupleSort -- What sort of tuple? IsPromoted -- A bit like IfaceTyCon IfaceTcArgs -- arity = length args -- For promoted data cons, the kind args are omitted type IfacePredType = IfaceType type IfaceContext = [IfacePredType] data IfaceTyLit = IfaceNumTyLit Integer | IfaceStrTyLit FastString deriving (Eq) type IfaceTyConBinder = TyVarBndr IfaceTvBndr TyConBndrVis type IfaceForAllBndr = TyVarBndr IfaceTvBndr ArgFlag -- See Note [Suppressing invisible arguments] -- We use a new list type (rather than [(IfaceType,Bool)], because -- it'll be more compact and faster to parse in interface -- files. Rather than two bytes and two decisions (nil/cons, and -- type/kind) there'll just be one. data IfaceTcArgs = ITC_Nil | ITC_Vis IfaceType IfaceTcArgs -- "Vis" means show when pretty-printing | ITC_Invis IfaceKind IfaceTcArgs -- "Invis" means don't show when pretty-printing -- except with -fprint-explicit-kinds instance Semi.Semigroup IfaceTcArgs where ITC_Nil <> xs = xs ITC_Vis ty rest <> xs = ITC_Vis ty (rest Semi.<> xs) ITC_Invis ki rest <> xs = ITC_Invis ki (rest Semi.<> xs) instance Monoid IfaceTcArgs where mempty = ITC_Nil mappend = (Semi.<>) -- Encodes type constructors, kind constructors, -- coercion constructors, the lot. -- We have to tag them in order to pretty print them -- properly. data IfaceTyCon = IfaceTyCon { ifaceTyConName :: IfExtName , ifaceTyConInfo :: IfaceTyConInfo } deriving (Eq) -- | Is a TyCon a promoted data constructor or just a normal type constructor? data IsPromoted = IsNotPromoted | IsPromoted deriving (Eq) -- | The various types of TyCons which have special, built-in syntax. data IfaceTyConSort = IfaceNormalTyCon -- ^ a regular tycon | IfaceTupleTyCon !Arity !TupleSort -- ^ e.g. @(a, b, c)@ or @(#a, b, c#)@. -- The arity is the tuple width, not the tycon arity -- (which is twice the width in the case of unboxed -- tuples). | IfaceSumTyCon !Arity -- ^ e.g. @(a | b | c)@ | IfaceEqualityTyCon -- ^ A heterogeneous equality TyCon -- (i.e. eqPrimTyCon, eqReprPrimTyCon, heqTyCon) -- that is actually being applied to two types -- of the same kind. This affects pretty-printing -- only: see Note [Equality predicates in IfaceType] deriving (Eq) {- Note [Free tyvars in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nowadays (since Nov 16, 2016) we pretty-print a Type by converting to an IfaceType and pretty printing that. This eliminates a lot of pretty-print duplication, and it matches what we do with pretty-printing TyThings. It works fine for closed types, but when printing debug traces (e.g. when using -ddump-tc-trace) we print a lot of /open/ types. These types are full of TcTyVars, and it's absolutely crucial to print them in their full glory, with their unique, TcTyVarDetails etc. So we simply embed a TyVar in IfaceType with the IfaceFreeTyVar constructor. Note that: * We never expect to serialise an IfaceFreeTyVar into an interface file, nor to deserialise one. IfaceFreeTyVar is used only in the "convert to IfaceType and then pretty-print" pipeline. We do the same for covars, naturally. Note [Equality predicates in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC has several varieties of type equality (see Note [The equality types story] in TysPrim for details). In an effort to avoid confusing users, we suppress the differences during "normal" pretty printing. Specifically we display them like this: Predicate Pretty-printed as Homogeneous case Heterogeneous case ---------------- ----------------- ------------------- (~) eqTyCon ~ N/A (~~) heqTyCon ~ ~~ (~#) eqPrimTyCon ~# ~~ (~R#) eqReprPrimTyCon Coercible Coercible By "homogeneeous case" we mean cases where a hetero-kinded equality (all but the first above) is actually applied to two identical kinds. Unfortunately, determining this from an IfaceType isn't possible since we can't see through type synonyms. Consequently, we need to record whether this particular application is homogeneous in IfaceTyConSort for the purposes of pretty-printing. All this suppresses information. To get the ground truth, use -dppr-debug (see 'print_eqs' in 'ppr_equality'). See Note [The equality types story] in TysPrim. -} data IfaceTyConInfo -- Used to guide pretty-printing -- and to disambiguate D from 'D (they share a name) = IfaceTyConInfo { ifaceTyConIsPromoted :: IsPromoted , ifaceTyConSort :: IfaceTyConSort } deriving (Eq) data IfaceCoercion = IfaceReflCo Role IfaceType | IfaceFunCo Role IfaceCoercion IfaceCoercion | IfaceTyConAppCo Role IfaceTyCon [IfaceCoercion] | IfaceAppCo IfaceCoercion IfaceCoercion | IfaceForAllCo IfaceTvBndr IfaceCoercion IfaceCoercion | IfaceFreeCoVar CoVar -- See Note [Free tyvars in IfaceType] | IfaceCoVarCo IfLclName | IfaceAxiomInstCo IfExtName BranchIndex [IfaceCoercion] | IfaceUnivCo IfaceUnivCoProv Role IfaceType IfaceType | IfaceSymCo IfaceCoercion | IfaceTransCo IfaceCoercion IfaceCoercion | IfaceNthCo Int IfaceCoercion | IfaceLRCo LeftOrRight IfaceCoercion | IfaceInstCo IfaceCoercion IfaceCoercion | IfaceCoherenceCo IfaceCoercion IfaceCoercion | IfaceKindCo IfaceCoercion | IfaceSubCo IfaceCoercion | IfaceAxiomRuleCo IfLclName [IfaceCoercion] data IfaceUnivCoProv = IfaceUnsafeCoerceProv | IfacePhantomProv IfaceCoercion | IfaceProofIrrelProv IfaceCoercion | IfacePluginProv String | IfaceHoleProv Unique -- ^ See Note [Holes in IfaceUnivCoProv] {- Note [Holes in IfaceUnivCoProv] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When typechecking fails the typechecker will produce a HoleProv UnivCoProv to stand in place of the unproven assertion. While we generally don't want to let these unproven assertions leak into interface files, we still need to be able to pretty-print them as we use IfaceType's pretty-printer to render Types. For this reason IfaceUnivCoProv has a IfaceHoleProv constructor; however, we fails when asked to serialize to a IfaceHoleProv to ensure that they don't end up in an interface file. To avoid an import loop between IfaceType and TyCoRep we only keep the hole's Unique, since that is all we need to print. -} {- %************************************************************************ %* * Functions over IFaceTypes * * ************************************************************************ -} ifaceTyConHasKey :: IfaceTyCon -> Unique -> Bool ifaceTyConHasKey tc key = ifaceTyConName tc `hasKey` key isIfaceLiftedTypeKind :: IfaceKind -> Bool isIfaceLiftedTypeKind (IfaceTyConApp tc ITC_Nil) = isLiftedTypeKindTyConName (ifaceTyConName tc) isIfaceLiftedTypeKind (IfaceTyConApp tc (ITC_Vis (IfaceTyConApp ptr_rep_lifted ITC_Nil) ITC_Nil)) = tc `ifaceTyConHasKey` tYPETyConKey && ptr_rep_lifted `ifaceTyConHasKey` liftedRepDataConKey isIfaceLiftedTypeKind _ = False splitIfaceSigmaTy :: IfaceType -> ([IfaceForAllBndr], [IfacePredType], IfaceType) -- Mainly for printing purposes splitIfaceSigmaTy ty = (bndrs, theta, tau) where (bndrs, rho) = split_foralls ty (theta, tau) = split_rho rho split_foralls (IfaceForAllTy bndr ty) = case split_foralls ty of { (bndrs, rho) -> (bndr:bndrs, rho) } split_foralls rho = ([], rho) split_rho (IfaceDFunTy ty1 ty2) = case split_rho ty2 of { (ps, tau) -> (ty1:ps, tau) } split_rho tau = ([], tau) suppressIfaceInvisibles :: DynFlags -> [IfaceTyConBinder] -> [a] -> [a] suppressIfaceInvisibles dflags tys xs | gopt Opt_PrintExplicitKinds dflags = xs | otherwise = suppress tys xs where suppress _ [] = [] suppress [] a = a suppress (k:ks) (x:xs) | isInvisibleTyConBinder k = suppress ks xs | otherwise = x : suppress ks xs stripIfaceInvisVars :: DynFlags -> [IfaceTyConBinder] -> [IfaceTyConBinder] stripIfaceInvisVars dflags tyvars | gopt Opt_PrintExplicitKinds dflags = tyvars | otherwise = filterOut isInvisibleTyConBinder tyvars -- | Extract an 'IfaceTvBndr' from an 'IfaceForAllBndr'. ifForAllBndrTyVar :: IfaceForAllBndr -> IfaceTvBndr ifForAllBndrTyVar = binderVar -- | Extract the variable name from an 'IfaceForAllBndr'. ifForAllBndrName :: IfaceForAllBndr -> IfLclName ifForAllBndrName fab = ifaceTvBndrName (ifForAllBndrTyVar fab) -- | Extract an 'IfaceTvBndr' from an 'IfaceTyConBinder'. ifTyConBinderTyVar :: IfaceTyConBinder -> IfaceTvBndr ifTyConBinderTyVar = binderVar -- | Extract the variable name from an 'IfaceTyConBinder'. ifTyConBinderName :: IfaceTyConBinder -> IfLclName ifTyConBinderName tcb = ifaceTvBndrName (ifTyConBinderTyVar tcb) ifTypeIsVarFree :: IfaceType -> Bool -- Returns True if the type definitely has no variables at all -- Just used to control pretty printing ifTypeIsVarFree ty = go ty where go (IfaceTyVar {}) = False go (IfaceFreeTyVar {}) = False go (IfaceAppTy fun arg) = go fun && go arg go (IfaceFunTy arg res) = go arg && go res go (IfaceDFunTy arg res) = go arg && go res go (IfaceForAllTy {}) = False go (IfaceTyConApp _ args) = go_args args go (IfaceTupleTy _ _ args) = go_args args go (IfaceLitTy _) = True go (IfaceCastTy {}) = False -- Safe go (IfaceCoercionTy {}) = False -- Safe go_args ITC_Nil = True go_args (ITC_Vis arg args) = go arg && go_args args go_args (ITC_Invis arg args) = go arg && go_args args {- Note [Substitution on IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Substitutions on IfaceType are done only during pretty-printing to construct the result type of a GADT, and does not deal with binders (eg IfaceForAll), so it doesn't need fancy capture stuff. -} type IfaceTySubst = FastStringEnv IfaceType -- Note [Substitution on IfaceType] mkIfaceTySubst :: [(IfLclName,IfaceType)] -> IfaceTySubst -- See Note [Substitution on IfaceType] mkIfaceTySubst eq_spec = mkFsEnv eq_spec inDomIfaceTySubst :: IfaceTySubst -> IfaceTvBndr -> Bool -- See Note [Substitution on IfaceType] inDomIfaceTySubst subst (fs, _) = isJust (lookupFsEnv subst fs) substIfaceType :: IfaceTySubst -> IfaceType -> IfaceType -- See Note [Substitution on IfaceType] substIfaceType env ty = go ty where go (IfaceFreeTyVar tv) = IfaceFreeTyVar tv go (IfaceTyVar tv) = substIfaceTyVar env tv go (IfaceAppTy t1 t2) = IfaceAppTy (go t1) (go t2) go (IfaceFunTy t1 t2) = IfaceFunTy (go t1) (go t2) go (IfaceDFunTy t1 t2) = IfaceDFunTy (go t1) (go t2) go ty@(IfaceLitTy {}) = ty go (IfaceTyConApp tc tys) = IfaceTyConApp tc (substIfaceTcArgs env tys) go (IfaceTupleTy s i tys) = IfaceTupleTy s i (substIfaceTcArgs env tys) go (IfaceForAllTy {}) = pprPanic "substIfaceType" (ppr ty) go (IfaceCastTy ty co) = IfaceCastTy (go ty) (go_co co) go (IfaceCoercionTy co) = IfaceCoercionTy (go_co co) go_co (IfaceReflCo r ty) = IfaceReflCo r (go ty) go_co (IfaceFunCo r c1 c2) = IfaceFunCo r (go_co c1) (go_co c2) go_co (IfaceTyConAppCo r tc cos) = IfaceTyConAppCo r tc (go_cos cos) go_co (IfaceAppCo c1 c2) = IfaceAppCo (go_co c1) (go_co c2) go_co (IfaceForAllCo {}) = pprPanic "substIfaceCoercion" (ppr ty) go_co (IfaceFreeCoVar cv) = IfaceFreeCoVar cv go_co (IfaceCoVarCo cv) = IfaceCoVarCo cv go_co (IfaceAxiomInstCo a i cos) = IfaceAxiomInstCo a i (go_cos cos) go_co (IfaceUnivCo prov r t1 t2) = IfaceUnivCo (go_prov prov) r (go t1) (go t2) go_co (IfaceSymCo co) = IfaceSymCo (go_co co) go_co (IfaceTransCo co1 co2) = IfaceTransCo (go_co co1) (go_co co2) go_co (IfaceNthCo n co) = IfaceNthCo n (go_co co) go_co (IfaceLRCo lr co) = IfaceLRCo lr (go_co co) go_co (IfaceInstCo c1 c2) = IfaceInstCo (go_co c1) (go_co c2) go_co (IfaceCoherenceCo c1 c2) = IfaceCoherenceCo (go_co c1) (go_co c2) go_co (IfaceKindCo co) = IfaceKindCo (go_co co) go_co (IfaceSubCo co) = IfaceSubCo (go_co co) go_co (IfaceAxiomRuleCo n cos) = IfaceAxiomRuleCo n (go_cos cos) go_cos = map go_co go_prov IfaceUnsafeCoerceProv = IfaceUnsafeCoerceProv go_prov (IfacePhantomProv co) = IfacePhantomProv (go_co co) go_prov (IfaceProofIrrelProv co) = IfaceProofIrrelProv (go_co co) go_prov (IfacePluginProv str) = IfacePluginProv str go_prov (IfaceHoleProv h) = IfaceHoleProv h substIfaceTcArgs :: IfaceTySubst -> IfaceTcArgs -> IfaceTcArgs substIfaceTcArgs env args = go args where go ITC_Nil = ITC_Nil go (ITC_Vis ty tys) = ITC_Vis (substIfaceType env ty) (go tys) go (ITC_Invis ty tys) = ITC_Invis (substIfaceType env ty) (go tys) substIfaceTyVar :: IfaceTySubst -> IfLclName -> IfaceType substIfaceTyVar env tv | Just ty <- lookupFsEnv env tv = ty | otherwise = IfaceTyVar tv {- ************************************************************************ * * Functions over IFaceTcArgs * * ************************************************************************ -} stripInvisArgs :: DynFlags -> IfaceTcArgs -> IfaceTcArgs stripInvisArgs dflags tys | gopt Opt_PrintExplicitKinds dflags = tys | otherwise = suppress_invis tys where suppress_invis c = case c of ITC_Invis _ ts -> suppress_invis ts _ -> c tcArgsIfaceTypes :: IfaceTcArgs -> [IfaceType] tcArgsIfaceTypes ITC_Nil = [] tcArgsIfaceTypes (ITC_Invis t ts) = t : tcArgsIfaceTypes ts tcArgsIfaceTypes (ITC_Vis t ts) = t : tcArgsIfaceTypes ts ifaceVisTcArgsLength :: IfaceTcArgs -> Int ifaceVisTcArgsLength = go 0 where go !n ITC_Nil = n go n (ITC_Vis _ rest) = go (n+1) rest go n (ITC_Invis _ rest) = go n rest {- Note [Suppressing invisible arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use the IfaceTcArgs to specify which of the arguments to a type constructor should be displayed when pretty-printing, under the control of -fprint-explicit-kinds. See also Type.filterOutInvisibleTypes. For example, given T :: forall k. (k->*) -> k -> * -- Ordinary kind polymorphism 'Just :: forall k. k -> 'Maybe k -- Promoted we want T * Tree Int prints as T Tree Int 'Just * prints as Just * ************************************************************************ * * Pretty-printing * * ************************************************************************ -} if_print_coercions :: SDoc -- ^ if printing coercions -> SDoc -- ^ otherwise -> SDoc if_print_coercions yes no = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> if gopt Opt_PrintExplicitCoercions dflags || dumpStyle style || debugStyle style then yes else no pprIfaceInfixApp :: TyPrec -> SDoc -> SDoc -> SDoc -> SDoc pprIfaceInfixApp ctxt_prec pp_tc pp_ty1 pp_ty2 = maybeParen ctxt_prec TyOpPrec $ sep [pp_ty1, pp_tc <+> pp_ty2] pprIfacePrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc pprIfacePrefixApp ctxt_prec pp_fun pp_tys | null pp_tys = pp_fun | otherwise = maybeParen ctxt_prec TyConPrec $ hang pp_fun 2 (sep pp_tys) -- ----------------------------- Printing binders ------------------------------------ instance Outputable IfaceBndr where ppr (IfaceIdBndr bndr) = pprIfaceIdBndr bndr ppr (IfaceTvBndr bndr) = char '@' <+> pprIfaceTvBndr False bndr pprIfaceBndrs :: [IfaceBndr] -> SDoc pprIfaceBndrs bs = sep (map ppr bs) pprIfaceLamBndr :: IfaceLamBndr -> SDoc pprIfaceLamBndr (b, IfaceNoOneShot) = ppr b pprIfaceLamBndr (b, IfaceOneShot) = ppr b <> text "[OneShot]" pprIfaceIdBndr :: IfaceIdBndr -> SDoc pprIfaceIdBndr (name, ty) = parens (ppr name <+> dcolon <+> ppr ty) pprIfaceTvBndr :: Bool -> IfaceTvBndr -> SDoc pprIfaceTvBndr use_parens (tv, ki) | isIfaceLiftedTypeKind ki = ppr tv | otherwise = maybe_parens (ppr tv <+> dcolon <+> ppr ki) where maybe_parens | use_parens = parens | otherwise = id pprIfaceTyConBinders :: [IfaceTyConBinder] -> SDoc pprIfaceTyConBinders = sep . map go where go tcb = pprIfaceTvBndr True (ifTyConBinderTyVar tcb) instance Binary IfaceBndr where put_ bh (IfaceIdBndr aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceTvBndr ab) = do putByte bh 1 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceIdBndr aa) _ -> do ab <- get bh return (IfaceTvBndr ab) instance Binary IfaceOneShot where put_ bh IfaceNoOneShot = do putByte bh 0 put_ bh IfaceOneShot = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return IfaceNoOneShot _ -> do return IfaceOneShot -- ----------------------------- Printing IfaceType ------------------------------------ --------------------------------- instance Outputable IfaceType where ppr ty = pprIfaceType ty pprIfaceType, pprParendIfaceType :: IfaceType -> SDoc pprIfaceType = pprPrecIfaceType TopPrec pprParendIfaceType = pprPrecIfaceType TyConPrec pprPrecIfaceType :: TyPrec -> IfaceType -> SDoc pprPrecIfaceType prec ty = eliminateRuntimeRep (ppr_ty prec) ty ppr_ty :: TyPrec -> IfaceType -> SDoc ppr_ty _ (IfaceFreeTyVar tyvar) = ppr tyvar -- This is the main reson for IfaceFreeTyVar! ppr_ty _ (IfaceTyVar tyvar) = ppr tyvar -- See Note [TcTyVars in IfaceType] ppr_ty ctxt_prec (IfaceTyConApp tc tys) = pprTyTcApp ctxt_prec tc tys ppr_ty _ (IfaceTupleTy i p tys) = pprTuple i p tys ppr_ty _ (IfaceLitTy n) = pprIfaceTyLit n -- Function types ppr_ty ctxt_prec (IfaceFunTy ty1 ty2) = -- We don't want to lose synonyms, so we mustn't use splitFunTys here. maybeParen ctxt_prec FunPrec $ sep [ppr_ty FunPrec ty1, sep (ppr_fun_tail ty2)] where ppr_fun_tail (IfaceFunTy ty1 ty2) = (arrow <+> ppr_ty FunPrec ty1) : ppr_fun_tail ty2 ppr_fun_tail other_ty = [arrow <+> pprIfaceType other_ty] ppr_ty ctxt_prec (IfaceAppTy ty1 ty2) = if_print_coercions ppr_app_ty ppr_app_ty_no_casts where ppr_app_ty = maybeParen ctxt_prec TyConPrec $ ppr_ty FunPrec ty1 <+> ppr_ty TyConPrec ty2 -- Strip any casts from the head of the application ppr_app_ty_no_casts = case split_app_tys ty1 (ITC_Vis ty2 ITC_Nil) of (IfaceCastTy head _, args) -> ppr_ty ctxt_prec (mk_app_tys head args) _ -> ppr_app_ty split_app_tys :: IfaceType -> IfaceTcArgs -> (IfaceType, IfaceTcArgs) split_app_tys (IfaceAppTy t1 t2) args = split_app_tys t1 (t2 `ITC_Vis` args) split_app_tys head args = (head, args) mk_app_tys :: IfaceType -> IfaceTcArgs -> IfaceType mk_app_tys (IfaceTyConApp tc tys1) tys2 = IfaceTyConApp tc (tys1 `mappend` tys2) mk_app_tys t1 tys2 = foldl' IfaceAppTy t1 (tcArgsIfaceTypes tys2) ppr_ty ctxt_prec (IfaceCastTy ty co) = if_print_coercions (parens (ppr_ty TopPrec ty <+> text "|>" <+> ppr co)) (ppr_ty ctxt_prec ty) ppr_ty ctxt_prec (IfaceCoercionTy co) = if_print_coercions (ppr_co ctxt_prec co) (text "<>") ppr_ty ctxt_prec ty = maybeParen ctxt_prec FunPrec (pprIfaceSigmaType ShowForAllMust ty) {- Note [Defaulting RuntimeRep variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RuntimeRep variables are considered by many (most?) users to be little more than syntactic noise. When the notion was introduced there was a signficant and understandable push-back from those with pedagogy in mind, which argued that RuntimeRep variables would throw a wrench into nearly any teach approach since they appear in even the lowly ($) function's type, ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b which is significantly less readable than its non RuntimeRep-polymorphic type of ($) :: (a -> b) -> a -> b Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell programs, so it makes little sense to make all users pay this syntactic overhead. For this reason it was decided that we would hide RuntimeRep variables for now (see #11549). We do this by defaulting all type variables of kind RuntimeRep to PtrLiftedRep. This is done in a pass right before pretty-printing (defaultRuntimeRepVars, controlled by -fprint-explicit-runtime-reps) -} -- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g. -- -- @ -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). -- (a -> b) -> a -> b -- @ -- -- turns in to, -- -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @ -- -- We do this to prevent RuntimeRep variables from incurring a significant -- syntactic overhead in otherwise simple type signatures (e.g. ($)). See -- Note [Defaulting RuntimeRep variables] and #11549 for further discussion. -- defaultRuntimeRepVars :: IfaceType -> IfaceType defaultRuntimeRepVars = go emptyFsEnv where go :: FastStringEnv () -> IfaceType -> IfaceType go subs (IfaceForAllTy bndr ty) | isRuntimeRep var_kind , isInvisibleArgFlag (binderArgFlag bndr) -- don't default *visible* quantification -- or we get the mess in #13963 = let subs' = extendFsEnv subs var () in go subs' ty | otherwise = IfaceForAllTy (TvBndr (var, go subs var_kind) (binderArgFlag bndr)) (go subs ty) where var :: IfLclName (var, var_kind) = binderVar bndr go subs (IfaceTyVar tv) | tv `elemFsEnv` subs = IfaceTyConApp liftedRep ITC_Nil go subs (IfaceFunTy kind ty) = IfaceFunTy (go subs kind) (go subs ty) go subs (IfaceAppTy x y) = IfaceAppTy (go subs x) (go subs y) go subs (IfaceDFunTy x y) = IfaceDFunTy (go subs x) (go subs y) go subs (IfaceCastTy x co) = IfaceCastTy (go subs x) co go _ other = other liftedRep :: IfaceTyCon liftedRep = IfaceTyCon dc_name (IfaceTyConInfo IsPromoted IfaceNormalTyCon) where dc_name = getName liftedRepDataConTyCon isRuntimeRep :: IfaceType -> Bool isRuntimeRep (IfaceTyConApp tc _) = tc `ifaceTyConHasKey` runtimeRepTyConKey isRuntimeRep _ = False eliminateRuntimeRep :: (IfaceType -> SDoc) -> IfaceType -> SDoc eliminateRuntimeRep f ty = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitRuntimeReps dflags then f ty else f (defaultRuntimeRepVars ty) instance Outputable IfaceTcArgs where ppr tca = pprIfaceTcArgs tca pprIfaceTcArgs, pprParendIfaceTcArgs :: IfaceTcArgs -> SDoc pprIfaceTcArgs = ppr_tc_args TopPrec pprParendIfaceTcArgs = ppr_tc_args TyConPrec ppr_tc_args :: TyPrec -> IfaceTcArgs -> SDoc ppr_tc_args ctx_prec args = let pprTys t ts = ppr_ty ctx_prec t <+> ppr_tc_args ctx_prec ts in case args of ITC_Nil -> empty ITC_Vis t ts -> pprTys t ts ITC_Invis t ts -> pprTys t ts ------------------- pprIfaceForAllPart :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPart tvs ctxt sdoc = ppr_iface_forall_part ShowForAllWhen tvs ctxt sdoc -- | Like 'pprIfaceForAllPart', but always uses an explicit @forall@. pprIfaceForAllPartMust :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPartMust tvs ctxt sdoc = ppr_iface_forall_part ShowForAllMust tvs ctxt sdoc pprIfaceForAllCoPart :: [(IfLclName, IfaceCoercion)] -> SDoc -> SDoc pprIfaceForAllCoPart tvs sdoc = sep [ pprIfaceForAllCo tvs, sdoc ] ppr_iface_forall_part :: ShowForAllFlag -> [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc ppr_iface_forall_part show_forall tvs ctxt sdoc = sep [ case show_forall of ShowForAllMust -> pprIfaceForAll tvs ShowForAllWhen -> pprUserIfaceForAll tvs , pprIfaceContextArr ctxt , sdoc] -- | Render the "forall ... ." or "forall ... ->" bit of a type. pprIfaceForAll :: [IfaceForAllBndr] -> SDoc pprIfaceForAll [] = empty pprIfaceForAll bndrs@(TvBndr _ vis : _) = add_separator (forAllLit <+> doc) <+> pprIfaceForAll bndrs' where (bndrs', doc) = ppr_itv_bndrs bndrs vis add_separator stuff = case vis of Required -> stuff <+> arrow _inv -> stuff <> dot -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@. -- Returns both the list of not-yet-rendered binders and the doc. -- No anonymous binders here! ppr_itv_bndrs :: [IfaceForAllBndr] -> ArgFlag -- ^ visibility of the first binder in the list -> ([IfaceForAllBndr], SDoc) ppr_itv_bndrs all_bndrs@(bndr@(TvBndr _ vis) : bndrs) vis1 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_itv_bndrs bndrs vis1 in (bndrs', pprIfaceForAllBndr bndr <+> doc) | otherwise = (all_bndrs, empty) ppr_itv_bndrs [] _ = ([], empty) pprIfaceForAllCo :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCo [] = empty pprIfaceForAllCo tvs = text "forall" <+> pprIfaceForAllCoBndrs tvs <> dot pprIfaceForAllCoBndrs :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCoBndrs bndrs = hsep $ map pprIfaceForAllCoBndr bndrs pprIfaceForAllBndr :: IfaceForAllBndr -> SDoc pprIfaceForAllBndr (TvBndr tv Inferred) = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitForalls dflags then braces $ pprIfaceTvBndr False tv else pprIfaceTvBndr True tv pprIfaceForAllBndr (TvBndr tv _) = pprIfaceTvBndr True tv pprIfaceForAllCoBndr :: (IfLclName, IfaceCoercion) -> SDoc pprIfaceForAllCoBndr (tv, kind_co) = parens (ppr tv <+> dcolon <+> pprIfaceCoercion kind_co) -- | Show forall flag -- -- Unconditionally show the forall quantifier with ('ShowForAllMust') -- or when ('ShowForAllWhen') the names used are free in the binder -- or when compiling with -fprint-explicit-foralls. data ShowForAllFlag = ShowForAllMust | ShowForAllWhen pprIfaceSigmaType :: ShowForAllFlag -> IfaceType -> SDoc pprIfaceSigmaType show_forall ty = ppr_iface_forall_part show_forall tvs theta (ppr tau) where (tvs, theta, tau) = splitIfaceSigmaTy ty pprUserIfaceForAll :: [IfaceForAllBndr] -> SDoc pprUserIfaceForAll tvs = sdocWithDynFlags $ \dflags -> ppWhen (any tv_has_kind_var tvs || gopt Opt_PrintExplicitForalls dflags) $ pprIfaceForAll tvs where tv_has_kind_var (TvBndr (_,kind) _) = not (ifTypeIsVarFree kind) ------------------- -- See equivalent function in TyCoRep.hs pprIfaceTyList :: TyPrec -> IfaceType -> IfaceType -> SDoc -- Given a type-level list (t1 ': t2), see if we can print -- it in list notation [t1, ...]. -- Precondition: Opt_PrintExplicitKinds is off pprIfaceTyList ctxt_prec ty1 ty2 = case gather ty2 of (arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma (map (ppr_ty TopPrec) (ty1:arg_tys)))) (arg_tys, Just tl) -> maybeParen ctxt_prec FunPrec $ hang (ppr_ty FunPrec ty1) 2 (fsep [ colon <+> ppr_ty FunPrec ty | ty <- arg_tys ++ [tl]]) where gather :: IfaceType -> ([IfaceType], Maybe IfaceType) -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn] -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl gather (IfaceTyConApp tc tys) | tc `ifaceTyConHasKey` consDataConKey , (ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil))) <- tys , (args, tl) <- gather ty2 = (ty1:args, tl) | tc `ifaceTyConHasKey` nilDataConKey = ([], Nothing) gather ty = ([], Just ty) pprIfaceTypeApp :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> SDoc pprIfaceTypeApp prec tc args = pprTyTcApp prec tc args pprTyTcApp :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> SDoc pprTyTcApp ctxt_prec tc tys = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> pprTyTcApp' ctxt_prec tc tys dflags style pprTyTcApp' :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> DynFlags -> PprStyle -> SDoc pprTyTcApp' ctxt_prec tc tys dflags style | ifaceTyConName tc `hasKey` ipClassKey , ITC_Vis (IfaceLitTy (IfaceStrTyLit n)) (ITC_Vis ty ITC_Nil) <- tys = maybeParen ctxt_prec FunPrec $ char '?' <> ftext n <> text "::" <> ppr_ty TopPrec ty | IfaceTupleTyCon arity sort <- ifaceTyConSort info , not (debugStyle style) , arity == ifaceVisTcArgsLength tys = pprTuple sort (ifaceTyConIsPromoted info) tys | IfaceSumTyCon arity <- ifaceTyConSort info = pprSum arity (ifaceTyConIsPromoted info) tys | tc `ifaceTyConHasKey` consDataConKey , not (gopt Opt_PrintExplicitKinds dflags) , ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil)) <- tys = pprIfaceTyList ctxt_prec ty1 ty2 | tc `ifaceTyConHasKey` tYPETyConKey , ITC_Vis (IfaceTyConApp rep ITC_Nil) ITC_Nil <- tys , rep `ifaceTyConHasKey` liftedRepDataConKey = kindStar | otherwise = getPprDebug $ \dbg -> if | not dbg && tc `ifaceTyConHasKey` errorMessageTypeErrorFamKey -- Suppress detail unles you _really_ want to see -> text "(TypeError ...)" | Just doc <- ppr_equality ctxt_prec tc (tcArgsIfaceTypes tys) -> doc | otherwise -> ppr_iface_tc_app ppr_ty ctxt_prec tc tys_wo_kinds where info = ifaceTyConInfo tc tys_wo_kinds = tcArgsIfaceTypes $ stripInvisArgs dflags tys -- | Pretty-print a type-level equality. -- Returns (Just doc) if the argument is a /saturated/ application -- of eqTyCon (~) -- eqPrimTyCon (~#) -- eqReprPrimTyCon (~R#) -- hEqTyCon (~~) -- -- See Note [Equality predicates in IfaceType] -- and Note [The equality types story] in TysPrim ppr_equality :: TyPrec -> IfaceTyCon -> [IfaceType] -> Maybe SDoc ppr_equality ctxt_prec tc args | hetero_eq_tc , [k1, k2, t1, t2] <- args = Just $ print_equality (k1, k2, t1, t2) | hom_eq_tc , [k, t1, t2] <- args = Just $ print_equality (k, k, t1, t2) | otherwise = Nothing where homogeneous = case ifaceTyConSort $ ifaceTyConInfo tc of IfaceEqualityTyCon -> True _other -> False -- True <=> a heterogeneous equality whose arguments -- are (in this case) of the same kind tc_name = ifaceTyConName tc pp = ppr_ty hom_eq_tc = tc_name `hasKey` eqTyConKey -- (~) hetero_eq_tc = tc_name `hasKey` eqPrimTyConKey -- (~#) || tc_name `hasKey` eqReprPrimTyConKey -- (~R#) || tc_name `hasKey` heqTyConKey -- (~~) print_equality args = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> print_equality' args style dflags print_equality' (ki1, ki2, ty1, ty2) style dflags | print_eqs -- No magic, just print the original TyCon = ppr_infix_eq (ppr tc) | hetero_eq_tc , print_kinds || not homogeneous = ppr_infix_eq (text "~~") | otherwise = if tc_name `hasKey` eqReprPrimTyConKey then pprIfacePrefixApp ctxt_prec (text "Coercible") [pp TyConPrec ty1, pp TyConPrec ty2] else pprIfaceInfixApp ctxt_prec (char '~') (pp TyOpPrec ty1) (pp TyOpPrec ty2) where ppr_infix_eq eq_op = pprIfaceInfixApp ctxt_prec eq_op (parens (pp TopPrec ty1 <+> dcolon <+> pp TyOpPrec ki1)) (parens (pp TopPrec ty2 <+> dcolon <+> pp TyOpPrec ki2)) print_kinds = gopt Opt_PrintExplicitKinds dflags print_eqs = gopt Opt_PrintEqualityRelations dflags || dumpStyle style || debugStyle style pprIfaceCoTcApp :: TyPrec -> IfaceTyCon -> [IfaceCoercion] -> SDoc pprIfaceCoTcApp ctxt_prec tc tys = ppr_iface_tc_app ppr_co ctxt_prec tc tys ppr_iface_tc_app :: (TyPrec -> a -> SDoc) -> TyPrec -> IfaceTyCon -> [a] -> SDoc ppr_iface_tc_app pp _ tc [ty] | tc `ifaceTyConHasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty) | tc `ifaceTyConHasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty) ppr_iface_tc_app pp ctxt_prec tc tys | tc `ifaceTyConHasKey` starKindTyConKey || tc `ifaceTyConHasKey` liftedTypeKindTyConKey || tc `ifaceTyConHasKey` unicodeStarKindTyConKey = kindStar -- Handle unicode; do not wrap * in parens | not (isSymOcc (nameOccName (ifaceTyConName tc))) = pprIfacePrefixApp ctxt_prec (ppr tc) (map (pp TyConPrec) tys) | [ty1,ty2] <- tys -- Infix, two arguments; -- we know nothing of precedence though = pprIfaceInfixApp ctxt_prec (ppr tc) (pp TyOpPrec ty1) (pp TyOpPrec ty2) | otherwise = pprIfacePrefixApp ctxt_prec (parens (ppr tc)) (map (pp TyConPrec) tys) pprSum :: Arity -> IsPromoted -> IfaceTcArgs -> SDoc pprSum _arity is_promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = tcArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI is_promoted <> sumParens (pprWithBars (ppr_ty TopPrec) args') pprTuple :: TupleSort -> IsPromoted -> IfaceTcArgs -> SDoc pprTuple ConstraintTuple IsNotPromoted ITC_Nil = text "() :: Constraint" -- All promoted constructors have kind arguments pprTuple sort IsPromoted args = let tys = tcArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI IsPromoted <> tupleParens sort (pprWithCommas pprIfaceType args') pprTuple sort promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = tcArgsIfaceTypes args args' = case sort of UnboxedTuple -> drop (length tys `div` 2) tys _ -> tys in pprPromotionQuoteI promoted <> tupleParens sort (pprWithCommas pprIfaceType args') pprIfaceTyLit :: IfaceTyLit -> SDoc pprIfaceTyLit (IfaceNumTyLit n) = integer n pprIfaceTyLit (IfaceStrTyLit n) = text (show n) pprIfaceCoercion, pprParendIfaceCoercion :: IfaceCoercion -> SDoc pprIfaceCoercion = ppr_co TopPrec pprParendIfaceCoercion = ppr_co TyConPrec ppr_co :: TyPrec -> IfaceCoercion -> SDoc ppr_co _ (IfaceReflCo r ty) = angleBrackets (ppr ty) <> ppr_role r ppr_co ctxt_prec (IfaceFunCo r co1 co2) = maybeParen ctxt_prec FunPrec $ sep (ppr_co FunPrec co1 : ppr_fun_tail co2) where ppr_fun_tail (IfaceFunCo r co1 co2) = (arrow <> ppr_role r <+> ppr_co FunPrec co1) : ppr_fun_tail co2 ppr_fun_tail other_co = [arrow <> ppr_role r <+> pprIfaceCoercion other_co] ppr_co _ (IfaceTyConAppCo r tc cos) = parens (pprIfaceCoTcApp TopPrec tc cos) <> ppr_role r ppr_co ctxt_prec (IfaceAppCo co1 co2) = maybeParen ctxt_prec TyConPrec $ ppr_co FunPrec co1 <+> pprParendIfaceCoercion co2 ppr_co ctxt_prec co@(IfaceForAllCo {}) = maybeParen ctxt_prec FunPrec $ pprIfaceForAllCoPart tvs (pprIfaceCoercion inner_co) where (tvs, inner_co) = split_co co split_co (IfaceForAllCo (name, _) kind_co co') = let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'') split_co co' = ([], co') -- Why these two? See Note [TcTyVars in IfaceType] ppr_co _ (IfaceFreeCoVar covar) = ppr covar ppr_co _ (IfaceCoVarCo covar) = ppr covar ppr_co ctxt_prec (IfaceUnivCo IfaceUnsafeCoerceProv r ty1 ty2) = maybeParen ctxt_prec TyConPrec $ text "UnsafeCo" <+> ppr r <+> pprParendIfaceType ty1 <+> pprParendIfaceType ty2 ppr_co _ctxt_prec (IfaceUnivCo (IfaceHoleProv u) _ _ _) = braces $ ppr u ppr_co _ (IfaceUnivCo _ _ ty1 ty2) = angleBrackets ( ppr ty1 <> comma <+> ppr ty2 ) ppr_co ctxt_prec (IfaceInstCo co ty) = maybeParen ctxt_prec TyConPrec $ text "Inst" <+> pprParendIfaceCoercion co <+> pprParendIfaceCoercion ty ppr_co ctxt_prec (IfaceAxiomRuleCo tc cos) = maybeParen ctxt_prec TyConPrec $ ppr tc <+> parens (interpp'SP cos) ppr_co ctxt_prec (IfaceAxiomInstCo n i cos) = ppr_special_co ctxt_prec (ppr n <> brackets (ppr i)) cos ppr_co ctxt_prec (IfaceSymCo co) = ppr_special_co ctxt_prec (text "Sym") [co] ppr_co ctxt_prec (IfaceTransCo co1 co2) = maybeParen ctxt_prec TyOpPrec $ ppr_co TyOpPrec co1 <+> semi <+> ppr_co TyOpPrec co2 ppr_co ctxt_prec (IfaceNthCo d co) = ppr_special_co ctxt_prec (text "Nth:" <> int d) [co] ppr_co ctxt_prec (IfaceLRCo lr co) = ppr_special_co ctxt_prec (ppr lr) [co] ppr_co ctxt_prec (IfaceSubCo co) = ppr_special_co ctxt_prec (text "Sub") [co] ppr_co ctxt_prec (IfaceCoherenceCo co1 co2) = ppr_special_co ctxt_prec (text "Coh") [co1,co2] ppr_co ctxt_prec (IfaceKindCo co) = ppr_special_co ctxt_prec (text "Kind") [co] ppr_special_co :: TyPrec -> SDoc -> [IfaceCoercion] -> SDoc ppr_special_co ctxt_prec doc cos = maybeParen ctxt_prec TyConPrec (sep [doc, nest 4 (sep (map pprParendIfaceCoercion cos))]) ppr_role :: Role -> SDoc ppr_role r = underscore <> pp_role where pp_role = case r of Nominal -> char 'N' Representational -> char 'R' Phantom -> char 'P' ------------------- instance Outputable IfaceTyCon where ppr tc = pprPromotionQuote tc <> ppr (ifaceTyConName tc) pprPromotionQuote :: IfaceTyCon -> SDoc pprPromotionQuote tc = pprPromotionQuoteI $ ifaceTyConIsPromoted $ ifaceTyConInfo tc pprPromotionQuoteI :: IsPromoted -> SDoc pprPromotionQuoteI IsNotPromoted = empty pprPromotionQuoteI IsPromoted = char '\'' instance Outputable IfaceCoercion where ppr = pprIfaceCoercion instance Binary IfaceTyCon where put_ bh (IfaceTyCon n i) = put_ bh n >> put_ bh i get bh = do n <- get bh i <- get bh return (IfaceTyCon n i) instance Binary IsPromoted where put_ bh IsNotPromoted = putByte bh 0 put_ bh IsPromoted = putByte bh 1 get bh = do n <- getByte bh case n of 0 -> return IsNotPromoted 1 -> return IsPromoted _ -> fail "Binary(IsPromoted): fail)" instance Binary IfaceTyConSort where put_ bh IfaceNormalTyCon = putByte bh 0 put_ bh (IfaceTupleTyCon arity sort) = putByte bh 1 >> put_ bh arity >> put_ bh sort put_ bh (IfaceSumTyCon arity) = putByte bh 2 >> put_ bh arity put_ bh IfaceEqualityTyCon = putByte bh 3 get bh = do n <- getByte bh case n of 0 -> return IfaceNormalTyCon 1 -> IfaceTupleTyCon <$> get bh <*> get bh 2 -> IfaceSumTyCon <$> get bh _ -> return IfaceEqualityTyCon instance Binary IfaceTyConInfo where put_ bh (IfaceTyConInfo i s) = put_ bh i >> put_ bh s get bh = IfaceTyConInfo <$> get bh <*> get bh instance Outputable IfaceTyLit where ppr = pprIfaceTyLit instance Binary IfaceTyLit where put_ bh (IfaceNumTyLit n) = putByte bh 1 >> put_ bh n put_ bh (IfaceStrTyLit n) = putByte bh 2 >> put_ bh n get bh = do tag <- getByte bh case tag of 1 -> do { n <- get bh ; return (IfaceNumTyLit n) } 2 -> do { n <- get bh ; return (IfaceStrTyLit n) } _ -> panic ("get IfaceTyLit " ++ show tag) instance Binary IfaceTcArgs where put_ bh tk = case tk of ITC_Vis t ts -> putByte bh 0 >> put_ bh t >> put_ bh ts ITC_Invis t ts -> putByte bh 1 >> put_ bh t >> put_ bh ts ITC_Nil -> putByte bh 2 get bh = do c <- getByte bh case c of 0 -> do t <- get bh ts <- get bh return $! ITC_Vis t ts 1 -> do t <- get bh ts <- get bh return $! ITC_Invis t ts 2 -> return ITC_Nil _ -> panic ("get IfaceTcArgs " ++ show c) ------------------- -- Some notes about printing contexts -- -- In the event that we are printing a singleton context (e.g. @Eq a@) we can -- omit parentheses. However, we must take care to set the precedence correctly -- to TyOpPrec, since something like @a :~: b@ must be parenthesized (see -- #9658). -- -- When printing a larger context we use 'fsep' instead of 'sep' so that -- the context doesn't get displayed as a giant column. Rather than, -- instance (Eq a, -- Eq b, -- Eq c, -- Eq d, -- Eq e, -- Eq f, -- Eq g, -- Eq h, -- Eq i, -- Eq j, -- Eq k, -- Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- -- we want -- -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, -- Eq j, Eq k, Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- | Prints "(C a, D b) =>", including the arrow. -- Used when we want to print a context in a type, so we -- use FunPrec to decide whether to parenthesise a singleton -- predicate; e.g. Num a => a -> a pprIfaceContextArr :: [IfacePredType] -> SDoc pprIfaceContextArr [] = empty pprIfaceContextArr [pred] = ppr_ty FunPrec pred <+> darrow pprIfaceContextArr preds = ppr_parend_preds preds <+> darrow -- | Prints a context or @()@ if empty -- You give it the context precedence pprIfaceContext :: TyPrec -> [IfacePredType] -> SDoc pprIfaceContext _ [] = text "()" pprIfaceContext prec [pred] = ppr_ty prec pred pprIfaceContext _ preds = ppr_parend_preds preds ppr_parend_preds :: [IfacePredType] -> SDoc ppr_parend_preds preds = parens (fsep (punctuate comma (map ppr preds))) instance Binary IfaceType where put_ _ (IfaceFreeTyVar tv) = pprPanic "Can't serialise IfaceFreeTyVar" (ppr tv) put_ bh (IfaceForAllTy aa ab) = do putByte bh 0 put_ bh aa put_ bh ab put_ bh (IfaceTyVar ad) = do putByte bh 1 put_ bh ad put_ bh (IfaceAppTy ae af) = do putByte bh 2 put_ bh ae put_ bh af put_ bh (IfaceFunTy ag ah) = do putByte bh 3 put_ bh ag put_ bh ah put_ bh (IfaceDFunTy ag ah) = do putByte bh 4 put_ bh ag put_ bh ah put_ bh (IfaceTyConApp tc tys) = do { putByte bh 5; put_ bh tc; put_ bh tys } put_ bh (IfaceCastTy a b) = do { putByte bh 6; put_ bh a; put_ bh b } put_ bh (IfaceCoercionTy a) = do { putByte bh 7; put_ bh a } put_ bh (IfaceTupleTy s i tys) = do { putByte bh 8; put_ bh s; put_ bh i; put_ bh tys } put_ bh (IfaceLitTy n) = do { putByte bh 9; put_ bh n } get bh = do h <- getByte bh case h of 0 -> do aa <- get bh ab <- get bh return (IfaceForAllTy aa ab) 1 -> do ad <- get bh return (IfaceTyVar ad) 2 -> do ae <- get bh af <- get bh return (IfaceAppTy ae af) 3 -> do ag <- get bh ah <- get bh return (IfaceFunTy ag ah) 4 -> do ag <- get bh ah <- get bh return (IfaceDFunTy ag ah) 5 -> do { tc <- get bh; tys <- get bh ; return (IfaceTyConApp tc tys) } 6 -> do { a <- get bh; b <- get bh ; return (IfaceCastTy a b) } 7 -> do { a <- get bh ; return (IfaceCoercionTy a) } 8 -> do { s <- get bh; i <- get bh; tys <- get bh ; return (IfaceTupleTy s i tys) } _ -> do n <- get bh return (IfaceLitTy n) instance Binary IfaceCoercion where put_ bh (IfaceReflCo a b) = do putByte bh 1 put_ bh a put_ bh b put_ bh (IfaceFunCo a b c) = do putByte bh 2 put_ bh a put_ bh b put_ bh c put_ bh (IfaceTyConAppCo a b c) = do putByte bh 3 put_ bh a put_ bh b put_ bh c put_ bh (IfaceAppCo a b) = do putByte bh 4 put_ bh a put_ bh b put_ bh (IfaceForAllCo a b c) = do putByte bh 5 put_ bh a put_ bh b put_ bh c put_ _ (IfaceFreeCoVar cv) = pprPanic "Can't serialise IfaceFreeCoVar" (ppr cv) put_ bh (IfaceCoVarCo a) = do putByte bh 6 put_ bh a put_ bh (IfaceAxiomInstCo a b c) = do putByte bh 7 put_ bh a put_ bh b put_ bh c put_ bh (IfaceUnivCo a b c d) = do putByte bh 8 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfaceSymCo a) = do putByte bh 9 put_ bh a put_ bh (IfaceTransCo a b) = do putByte bh 10 put_ bh a put_ bh b put_ bh (IfaceNthCo a b) = do putByte bh 11 put_ bh a put_ bh b put_ bh (IfaceLRCo a b) = do putByte bh 12 put_ bh a put_ bh b put_ bh (IfaceInstCo a b) = do putByte bh 13 put_ bh a put_ bh b put_ bh (IfaceCoherenceCo a b) = do putByte bh 14 put_ bh a put_ bh b put_ bh (IfaceKindCo a) = do putByte bh 15 put_ bh a put_ bh (IfaceSubCo a) = do putByte bh 16 put_ bh a put_ bh (IfaceAxiomRuleCo a b) = do putByte bh 17 put_ bh a put_ bh b get bh = do tag <- getByte bh case tag of 1 -> do a <- get bh b <- get bh return $ IfaceReflCo a b 2 -> do a <- get bh b <- get bh c <- get bh return $ IfaceFunCo a b c 3 -> do a <- get bh b <- get bh c <- get bh return $ IfaceTyConAppCo a b c 4 -> do a <- get bh b <- get bh return $ IfaceAppCo a b 5 -> do a <- get bh b <- get bh c <- get bh return $ IfaceForAllCo a b c 6 -> do a <- get bh return $ IfaceCoVarCo a 7 -> do a <- get bh b <- get bh c <- get bh return $ IfaceAxiomInstCo a b c 8 -> do a <- get bh b <- get bh c <- get bh d <- get bh return $ IfaceUnivCo a b c d 9 -> do a <- get bh return $ IfaceSymCo a 10-> do a <- get bh b <- get bh return $ IfaceTransCo a b 11-> do a <- get bh b <- get bh return $ IfaceNthCo a b 12-> do a <- get bh b <- get bh return $ IfaceLRCo a b 13-> do a <- get bh b <- get bh return $ IfaceInstCo a b 14-> do a <- get bh b <- get bh return $ IfaceCoherenceCo a b 15-> do a <- get bh return $ IfaceKindCo a 16-> do a <- get bh return $ IfaceSubCo a 17-> do a <- get bh b <- get bh return $ IfaceAxiomRuleCo a b _ -> panic ("get IfaceCoercion " ++ show tag) instance Binary IfaceUnivCoProv where put_ bh IfaceUnsafeCoerceProv = putByte bh 1 put_ bh (IfacePhantomProv a) = do putByte bh 2 put_ bh a put_ bh (IfaceProofIrrelProv a) = do putByte bh 3 put_ bh a put_ bh (IfacePluginProv a) = do putByte bh 4 put_ bh a put_ _ (IfaceHoleProv _) = pprPanic "Binary(IfaceUnivCoProv) hit a hole" empty -- See Note [Holes in IfaceUnivCoProv] get bh = do tag <- getByte bh case tag of 1 -> return $ IfaceUnsafeCoerceProv 2 -> do a <- get bh return $ IfacePhantomProv a 3 -> do a <- get bh return $ IfaceProofIrrelProv a 4 -> do a <- get bh return $ IfacePluginProv a _ -> panic ("get IfaceUnivCoProv " ++ show tag) instance Binary (DefMethSpec IfaceType) where put_ bh VanillaDM = putByte bh 0 put_ bh (GenericDM t) = putByte bh 1 >> put_ bh t get bh = do h <- getByte bh case h of 0 -> return VanillaDM _ -> do { t <- get bh; return (GenericDM t) }
ezyang/ghc
compiler/iface/IfaceType.hs
Haskell
bsd-3-clause
54,462
module Lab3 where ----------------------------------------------------------------------------------------------------------------------------- -- LIST COMPREHENSIONS ------------------------------------------------------------------------------------------------------------------------------ -- =================================== -- Ex. 0 - 2 -- =================================== evens :: [Integer] -> [Integer] evens xs = [x | x<-xs, x `mod` 2 == 0] -- =================================== -- Ex. 3 - 4 -- =================================== -- complete the following line with the correct type signature for this function -- squares :: ... squares :: Integer -> [Integer] squares n = [x*x | x<-[1..n]] sumSquares :: Integer -> Integer sumSquares n = sum (squares n) -- =================================== -- Ex. 5 - 7 -- =================================== -- complete the following line with the correct type signature for this function -- squares' :: ... squares' m n = [x*x | x<-[n+1..m+n]] sumSquares' :: Integer -> Integer sumSquares' x = sum . uncurry squares' $ (x, x) -- =================================== -- Ex. 8 -- =================================== coords :: Integer -> Integer -> [(Integer,Integer)] coords x y = [(x',y') | x'<-[0..x], y'<-[0..y]]
javier-alvarez/myhaskell
lab3.hs
Haskell
bsd-3-clause
1,282
module Core.Pretty where import Text.PrettyPrint import Core.AST import Core.Parser prettyProgram :: CoreProgram -> String prettyProgram = render . semiSep . map prettyDefn semiSep :: [Doc] -> Doc semiSep = vcat . punctuate semi spaceSep :: [String] -> Doc spaceSep = sep . map text prettyDefn :: CoreDefn -> Doc prettyDefn (name, args, e) = text name <+> spaceSep args <+> equals <+> prettyExp e prettyExp :: CoreExpr -> Doc prettyExp (Var n) = text n prettyExp (Num n) = int n prettyExp (Constr i j) = text "Pack" <> braces (int i <> text "," <> int j) prettyExp (App e1 e2) = prettyExp e1 <+> parensIf (isAtomic e2) (prettyExp e2) where parensIf p doc | p = parens doc | otherwise = doc prettyExp (Let isRec defs e) = text (if isRec then "letrec" else "let") <+> nest 1 (prettyDefs defs) $$ text "in" <+> prettyExp e prettyExp (Case e alts) = text "case" <+> prettyExp e <+> text "of" <+> nest 1 (prettyAlts alts) prettyExp (Lam args e) = parens $ text "\\" <> spaceSep args <> dot <+> prettyExp e where dot = text "." prettyDefs :: [(Name, CoreExpr)] -> Doc prettyDefs = semiSep . map prettyDef prettyDef :: (Name, CoreExpr) -> Doc prettyDef (name, e) = text name <+> equals <+> prettyExp e prettyAlts :: [CoreAlt] -> Doc prettyAlts = semiSep . map prettyAlt prettyAlt :: CoreAlt -> Doc prettyAlt (i, args, e) = carots (int i) <+> spaceSep args <+> text "->" <+> prettyExp e where carots x = text "<" <> x <> text ">"
WraithM/CoreCompiler
src/Core/Pretty.hs
Haskell
bsd-3-clause
1,463
-- | Addable ------------------------------------------------------------------------------ {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} module Constraint.Addable where ------------------------------------------------------------------------------ import Structure ------------------------------------------------------------------------------ -- | The Class class (Value a, Value b, Value c) => Addable a b c | a b -> c where add :: Guard a -> Guard b -> Guard c -- the return type of add is known ------------------------------------------------------------------------------ -- | The Operator data Addition a b c where Addition :: (Expression a n, Expression b m, Addable n m c) => a -> b -> Addition a b c -- a & b determine n & m which determine c ------------------------------------------------------------------------------ -- ALL OPERATORS ARE EXPRESSIONS instance (Value c) => Expression (Addition a b c) c where evaluate (Addition a b) = add (evaluate a) (evaluate b) -- ALL EXPRESSIONS ARE SHOWABLE instance Show (Addition a b c) where show (Addition a b) = "(" ++ show a ++ "+" ++ show b ++ ")" ------------------------------------------------------------------------------ -- EXTENSIONS TO ALREADY DEFINED VALUES
Conflagrationator/HMath
src/Constraint/Addable.hs
Haskell
bsd-3-clause
1,356
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} module Games.Melee ( Melee (..), PlayerState (..), ) where import Lib import Vector import Types import Network import Network.Label import Layers import Data.Singletons.Prelude.List import Data.List.Split import Control.Monad import System.FilePath.Posix import Buffer -- | Game definition for SSBM. data Melee = Menu | Ingame !PlayerState !Int !PlayerState !Int | Win !PlayerState !Int deriving (Eq, Show) -- | The state of a player in a game data PlayerState = PlayerState { stocks :: !Int -- ^ Stocks , percent :: !Int -- ^ Percentage } deriving (Eq, Show) instance Pretty PlayerState where pretty (PlayerState s p) = stockstring s ++ " " ++ show p ++ "%" where stockstring n = replicate n 'O' ++ replicate (4-n) ' ' instance Transitions PlayerState where PlayerState s p ->? PlayerState s' p' | s' == s && p' >= p && p' - p < 80 = True | p > 0 && p' == 0 = s' == s - 1 | otherwise = False instance Transitions Melee where a ->? b | a == b = True Menu ->? Menu = True Menu ->? Ingame (PlayerState 4 0) _ (PlayerState 4 0) _ = True Win _ _ ->? Menu = True Ingame p1 q1 p2 q2 ->? Win p q | stocks p1 == 1 && p == p2 && q == q2 = True | stocks p2 == 1 && p == p1 && q == q1 = True Ingame p1 q1 p2 q2 ->? Ingame p1' q1' p2' q2' = and [ q1 == q1', q2 == q2' , p1 ->? p1', p2 ->? p2' ] _ ->? _ = False instance GameState Melee where type Title Melee = "Melee" type ScreenWidth Melee = 584 type ScreenHeight Melee = 480 type Widgets Melee = '[Melee] label st = LabelVec$ toLabel st :- Nil delabel (LabelVec (WLabel l :- Nil)) = case parseLabel l (fromLabel :: LabelParser Melee) of Left err -> error err Right s -> s rootDir = Path "/Users/joni/tmp/" parse = fromFilename instance Pretty Melee where pretty Menu = "Menu" pretty (Win p q) = "Player " ++ show q ++ " wins with " ++ pretty p pretty (Ingame p1 q1 p2 q2) = "P" ++ show q1 ++ ": " ++ pretty p1 ++ "\t\tP" ++ show q2 ++ ": " ++ pretty p2 instance Widget Melee where type Width Melee = 140 type Height Melee = 120 type Parent Melee = Melee type DataShape Melee = '[ 10, 10, 10, 5 ] type Positions Melee = '[ '(16, 356) , '(156, 356) , '(294, 356) , '(432, 356) ] type SampleWidth Melee = 42 type SampleHeight Melee = 42 type NetConfig Melee = '[ Convolution 12 3 5 5 38 38 , Pool , ReLU , Convolution 32 12 8 8 12 12 , ReLU , Flatten , FC 4608 1024 , ReLU , FC 1024 (Sum (DataShape Melee)) , MultiSoftMax (DataShape Melee) ] params = Params (LearningParameters 1e-4 0.9 1e-7) toLabel Menu = WLabel$ fill 0 toLabel (Win p q) = WLabel$ get 1 <-> get 2 <-> get 3 <-> get 4 where get n | n == q = playerLabel p | otherwise = fill 0 toLabel (Ingame p1 q1 p2 q2) = WLabel$ get 1 <-> get 2 <-> get 3 <-> get 4 where get n | n == q1 = playerLabel p1 | n == q2 = playerLabel p2 | otherwise = fill 0 fromLabel = do players <- replicateM 4 playerParser case count ingame players of 2 -> let [(p1, q1), (p2, q2)] = filter (ingame.fst) $ zip players [1..] in return$! Ingame p1 q1 p2 q2 1 -> return$! let (p,q) = head (filter (ingame.fst) $ zip players [1..]) in Win p q _ -> return Menu ingame :: PlayerState -> Bool ingame (PlayerState 0 _) = False ingame _ = True playerLabel :: PlayerState -> LabelComposite 1 '[10, 10, 10, 5] playerLabel (PlayerState 0 _) = fill 0 playerLabel (PlayerState stocks percent) = singleton d100 <|> singleton d10 <|> singleton d1 <|> singleton stocks where (d100, d10, d1) = splitDigits percent playerParser :: LabelParser PlayerState playerParser = do d100 <- pop d10 <- pop d1 <- pop stocks <- pop let dmg = 100 * d100 + 10 * d10 + 1 * d1 return $! mkPlayerState stocks dmg mkPlayerState :: Int -> Int -> PlayerState mkPlayerState 0 _ = PlayerState 0 0 mkPlayerState s p | s < 0 || s > 4 = error$ "PlayerState with " ++ show s ++ " stocks" | p < 0 || p > 999 = error$ "PlayerState with " ++ show p ++ " percent" | otherwise = PlayerState s p fromFilename :: Path a -> LabelVec Melee fromFilename (Path (wordsBy (=='_') . takeWhile (/='.') . takeBaseName -> [ "shot", _, "psd", psd, "st", st , "p1", "g", g1, "c", _, "s", read' -> s1, "p", read' -> p1 , "p2", "g", g2, "c", _, "s", read' -> s2, "p", read' -> p2 , "p3", "g", g3, "c", _, "s", read' -> s3, "p", read' -> p3 , "p4", "g", g4, "c", _, "s", read' -> s4, "p", read' -> p4 ] )) | psd == "1" || st == "0" = LabelVec$ WLabel (fill 0) :- Nil | otherwise = LabelVec$ WLabel (get g1 s1 p1 <-> get g2 s2 p2 <-> get g3 s3 p3 <-> get g4 s4 p4) :- Nil where get "0" _ _ = fill 0 get "1" s p = playerLabel $ mkPlayerState s p get _ _ _ = error "Error while parsing filename" fromFilename (Path p) = error$ "Invalid filename: " ++ p
jonascarpay/visor
src/Games/Melee.hs
Haskell
bsd-3-clause
5,931
{-# LANGUAGE DataKinds, NegativeLiterals #-} module GibbsOptBucket where import Data.Number.LogFloat hiding (product) import Prelude hiding (product, exp, log, (**)) import Language.Hakaru.Runtime.LogFloatPrelude import Language.Hakaru.Types.Sing import qualified System.Random.MWC as MWC import Control.Monad prog = lam $ \ topic_prior0 -> lam $ \ word_prior1 -> lam $ \ z2 -> lam $ \ w3 -> lam $ \ doc4 -> lam $ \ docUpdate5 -> categorical (array (size topic_prior0) $ \ zNew丏6 -> product (nat_ 0) (size topic_prior0) (\ i7 -> product (nat_ 0) (size word_prior1) (\ i丣8 -> product (nat_ 0) (let_ (bucket (nat_ 0) (size w3) ((r_fanout (r_split (\ (i丙11,()) -> docUpdate5 == doc4 ! i丙11) (r_index (\ () -> size word_prior1) (\ (i丙11,()) -> w3 ! i丙11) (r_add (\ (i丙11,(i丣12,())) -> nat_ 1))) r_nop) r_nop))) $ \ summary10 -> case_ (i7 == zNew丏6) [branch ptrue (case_ (case_ summary10 [branch (ppair PVar PVar) (\ y13 z14 -> y13)]) [branch (ppair PVar PVar) (\ y15 z16 -> y15)] ! i丣8), branch pfalse (nat_ 0)]) (\ j9 -> nat2prob (let_ (bucket (nat_ 0) (size w3) ((r_split (\ (i丙18,()) -> doc4 ! i丙18 == docUpdate5) r_nop (r_index (\ () -> size topic_prior0) (\ (i丙18,()) -> z2 ! (doc4 ! i丙18)) (r_index (\ (i19,()) -> size word_prior1) (\ (i丙18,(i19,())) -> w3 ! i丙18) (r_add (\ (i丙18,(i丣20,(i19,()))) -> nat_ 1))))))) $ \ summary17 -> case_ summary17 [branch (ppair PVar PVar) (\ y21 z22 -> z22)] ! i7 ! i丣8) + nat2prob j9 + word_prior1 ! i丣8))) * ((let_ (bucket (nat_ 0) (size z2) ((r_split (\ (i丙24,()) -> i丙24 == docUpdate5) r_nop (r_index (\ () -> size topic_prior0) (\ (i丙24,()) -> z2 ! i丙24) (r_add (\ (i丙24,(zNew丏25,())) -> nat_ 1)))))) $ \ summary23 -> nat2prob (case_ summary23 [branch (ppair PVar PVar) (\ y26 z27 -> z27)] ! zNew丏6)) + topic_prior0 ! zNew丏6) * recip (nat2prob (summate (nat_ 0) (size z2) (\ i丙28 -> case_ (i丙28 == docUpdate5) [branch ptrue (nat_ 0), branch pfalse (case_ (z2 ! i丙28 < nat_ 0) [branch ptrue (nat_ 0), branch pfalse (nat_ 1)])])) + summate (nat_ 0) (size topic_prior0) (\ i丙29 -> topic_prior0 ! i丙29)) * recip (product (nat_ 0) (size topic_prior0) (\ i30 -> product (nat_ 0) (let_ (bucket (nat_ 0) (size w3) ((r_fanout (r_split (\ (i丙33,()) -> w3 ! i丙33 < nat_ 0) r_nop (r_split (\ (i丙33,()) -> docUpdate5 == doc4 ! i丙33) (r_add (\ (i丙33,()) -> nat_ 1)) r_nop)) r_nop))) $ \ summary32 -> case_ (i30 == zNew丏6) [branch ptrue (case_ (case_ (case_ summary32 [branch (ppair PVar PVar) (\ y34 z35 -> y34)]) [branch (ppair PVar PVar) (\ y36 z37 -> z37)]) [branch (ppair PVar PVar) (\ y38 z39 -> y38)]), branch pfalse (nat_ 0)]) (\ i丣31 -> nat2prob (let_ (bucket (nat_ 0) (size w3) ((r_split (\ (i丙41,()) -> w3 ! i丙41 < nat_ 0) r_nop (r_split (\ (i丙41,()) -> doc4 ! i丙41 == docUpdate5) r_nop (r_index (\ () -> size topic_prior0) (\ (i丙41,()) -> z2 ! (doc4 ! i丙41)) (r_add (\ (i丙41,(i42,())) -> nat_ 1))))))) $ \ summary40 -> case_ (case_ summary40 [branch (ppair PVar PVar) (\ y43 z44 -> z44)]) [branch (ppair PVar PVar) (\ y45 z46 -> z46)] ! i30) + nat2prob i丣31 + summate (nat_ 0) (size word_prior1) (\ i丙47 -> word_prior1 ! i丙47)))))
zaxtax/naive_bayes
GibbsOptBucket.hs
Haskell
bsd-3-clause
13,002
{-# LANGUAGE OverloadedStrings #-} -- | Module : Network.MPD.Util -- Copyright : (c) Ben Sinclair 2005-2009, Joachim Fasting 2010 -- License : MIT (see LICENSE) -- Maintainer : Joachim Fasting <joachim.fasting@gmail.com> -- Stability : alpha -- -- Utilities. module Network.MPD.Util ( parseDate, parseIso8601, formatIso8601, parseNum, parseFrac, parseBool, showBool, breakChar, parseTriple, toAssoc, toAssocList, splitGroups, read ) where import Control.Arrow import Data.Time.Format (ParseTime, parseTime, FormatTime, formatTime) import System.Locale (defaultTimeLocale) import qualified Prelude import Prelude hiding (break, take, drop, dropWhile, read) import Data.ByteString.Char8 (break, drop, dropWhile, ByteString) import qualified Data.ByteString.UTF8 as UTF8 import Data.String import Control.Applicative import qualified Data.Attoparsec.ByteString.Char8 as A -- | Like Prelude.read, but works with ByteString. read :: Read a => ByteString -> a read = Prelude.read . UTF8.toString -- Break a string by character, removing the separator. breakChar :: Char -> ByteString -> (ByteString, ByteString) breakChar c = second (drop 1) . break (== c) -- Parse a date value. -- > parseDate "2008" = Just 2008 -- > parseDate "2008-03-01" = Just 2008 parseDate :: ByteString -> Maybe Int parseDate = parseMaybe p where p = A.decimal <* A.skipMany (A.char '-' <|> A.digit) -- Parse date in iso 8601 format parseIso8601 :: (ParseTime t) => ByteString -> Maybe t parseIso8601 = parseTime defaultTimeLocale iso8601Format . UTF8.toString formatIso8601 :: FormatTime t => t -> String formatIso8601 = formatTime defaultTimeLocale iso8601Format iso8601Format :: String iso8601Format = "%FT%TZ" -- Parse a positive or negative integer value, returning 'Nothing' on failure. parseNum :: (Read a, Integral a) => ByteString -> Maybe a parseNum = parseMaybe (A.signed A.decimal) -- Parse C style floating point value, returning 'Nothing' on failure. parseFrac :: (Fractional a, Read a) => ByteString -> Maybe a parseFrac = parseMaybe p where p = A.string "nan" *> pure (Prelude.read "NaN") <|> A.string "inf" *> pure (Prelude.read "Infinity") <|> A.string "-inf" *> pure (Prelude.read "-Infinity") <|> A.rational -- Inverts 'parseBool'. showBool :: IsString a => Bool -> a -- FIXME: can we change the type to (Bool -> ByteString)? showBool x = if x then "1" else "0" -- Parse a boolean response value. parseBool :: ByteString -> Maybe Bool parseBool = parseMaybe p where p = A.char '1' *> pure True <|> A.char '0' *> pure False -- Break a string into triple. parseTriple :: Char -> (ByteString -> Maybe a) -> ByteString -> Maybe (a, a, a) parseTriple c f s = let (u, u') = breakChar c s (v, w) = breakChar c u' in case (f u, f v, f w) of (Just a, Just b, Just c') -> Just (a, b, c') _ -> Nothing -- Break a string into a key-value pair, separating at the first ':'. toAssoc :: ByteString -> (ByteString, ByteString) toAssoc = second (dropWhile (== ' ') . drop 1) . break (== ':') toAssocList :: [ByteString] -> [(ByteString, ByteString)] toAssocList = map toAssoc -- Takes an association list with recurring keys and groups each cycle of keys -- with their values together. There can be several keys that begin cycles, -- (the elements of the first parameter). splitGroups :: [ByteString] -> [(ByteString, ByteString)] -> [[(ByteString, ByteString)]] splitGroups groupHeads = go where go [] = [] go (x:xs) = let (ys, zs) = Prelude.break isGroupHead xs in (x:ys) : go zs isGroupHead = (`elem` groupHeads) . fst -- A helper for running a Parser, turning errors into Nothing. parseMaybe :: A.Parser a -> ByteString -> Maybe a parseMaybe p s = either (const Nothing) Just $ A.parseOnly (p <* A.endOfInput) s
beni55/libmpd-haskell
src/Network/MPD/Util.hs
Haskell
mit
4,001
module Spark.Core.ContextSpec where import Test.Hspec import Spark.Core.Functions spec :: Spec spec = do describe "Basic routines to get something out" $ do it "should print a node" $ do let x = dataset ([1 ,2, 3, 4]::[Int]) x `shouldBe` x -- b = nodeToBundle (untyped x) in -- trace (pretty b) $ -- 1 `shouldBe` 1
krapsh/kraps-haskell
test/Spark/Core/ContextSpec.hs
Haskell
apache-2.0
366
{-# LANGUAGE TransformListComp #-} oldest :: [Int] -> [String] oldest tbl = [ "str" | n <- tbl , then id ]
mpickering/ghc-exactprint
tests/examples/ghc710/TransformListComp.hs
Haskell
bsd-3-clause
147
module Blockchain.Mining ( nonceIsValid' ) where import Control.Monad.IO.Class import Control.Monad.Trans.State import qualified Data.Array.IO as A import qualified Data.Binary as Bin import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Word import Blockchain.Context import Blockchain.Data.BlockDB import Blockchain.ExtWord import Blockchain.Util import Numeric import Cache import Constants import Dataset import Hashimoto import Debug.Trace word32Unpack::B.ByteString->[Word32] word32Unpack s | B.null s = [] word32Unpack s | B.length s >= 4 = Bin.decode (BL.fromStrict $ B.take 4 s) : word32Unpack (B.drop 4 s) word32Unpack s = error "word32Unpack called for ByteString of length not a multiple of 4" powFunc'::B.ByteString->Block->IO Integer powFunc' dataset b = --trace (show $ headerHashWithoutNonce b) $ fmap (byteString2Integer . snd) $ hashimoto (headerHashWithoutNonce b) (B.pack $ word64ToBytes $ blockDataNonce $ blockBlockData b) (fromInteger $ fullSize 0) -- (fromInteger . (calcDataset 0 !)) (A.newListArray (0,15) . word32Unpack . B.take 64 . (flip B.drop dataset) . (64 *) . fromIntegral) nonceIsValid'::Block->ContextM Bool nonceIsValid' b = do cxt <- get val <- liftIO $ powFunc' (miningDataset cxt) b {- liftIO $ putStrLn (showHex val "") liftIO $ putStrLn (showHex ( val * blockDataDifficulty (blockBlockData b) ) "") -} return $ val * blockDataDifficulty (blockBlockData b) < (2::Integer)^(256::Integer)
jamshidh/ethereum-client-haskell
src/Blockchain/Mining.hs
Haskell
bsd-3-clause
1,605
module Utils where -- | -- -- >>> split "foo bar baz" -- ["foo","bar baz"] -- >>> split "foo bar baz" -- ["foo","bar baz"] split :: String -> [String] split xs = [ys, dropWhile isSpace zs] where isSpace = (== ' ') (ys,zs) = break isSpace xs -- | -- -- >>> splitN 0 "foo bar baz" -- ["foo","bar baz"] -- >>> splitN 2 "foo bar baz" -- ["foo","bar baz"] -- >>> splitN 3 "foo bar baz" -- ["foo","bar","baz"] splitN :: Int -> String -> [String] splitN n xs | n <= 2 = split xs | otherwise = let [ys,zs] = split xs in ys : splitN (n - 1) zs
cabrera/ghc-mod
src/Utils.hs
Haskell
bsd-3-clause
581
module Bead.Persistence.SQL.FileSystem where import Control.Applicative ((<$>)) import Control.DeepSeq (deepseq) import Control.Monad import Control.Monad.IO.Class import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as BS import Data.List (isSuffixOf) import Data.Maybe import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import System.Directory import qualified System.Directory as Dir import System.FilePath import System.IO import System.Posix.Types (COff(..)) import System.Posix.Files (getFileStatus, fileSize, modificationTime) import Bead.Domain.Entities import Bead.Domain.Relationships import Bead.Domain.Types datadir = "data" testOutgoingDir = "test-outgoing" testIncomingDir = "test-incoming" userDir = "user" testOutgoingDataDir = joinPath [datadir, testOutgoingDir] testIncomingDataDir = joinPath [datadir, testIncomingDir] userDataDir = joinPath [datadir, userDir] fsDirs = [ datadir , testOutgoingDataDir , testIncomingDataDir , userDataDir ] class DirName d where dirName :: d -> FilePath instance DirName Username where dirName = usernameCata ((datadir </> "user") </>) instance DirName TestJobKey where dirName (TestJobKey k) = joinPath [datadir, testOutgoingDir, k] fileLoad :: (MonadIO io) => FilePath -> io String fileLoad fname = liftIO $ do h <- openFile fname ReadMode hSetEncoding h utf8 s <- hGetContents h s `deepseq` hClose h return s fileSave :: (MonadIO io) => FilePath -> String -> io () fileSave fname s = liftIO $ do handler <- openFile fname WriteMode hSetEncoding handler utf8 hPutStr handler s hClose handler fileSaveBS :: (MonadIO io) => FilePath -> ByteString -> io () fileSaveBS fname s = liftIO $ do handler <- openFile fname WriteMode hSetEncoding handler utf8 BS.hPutStr handler s hClose handler filterDirContents :: (MonadIO io) => (FilePath -> IO Bool) -> FilePath -> io [FilePath] filterDirContents f p = liftIO $ do content <- liftM (filter (\d -> not $ or [d == ".", d == ".."])) $ getDirectoryContents p filterM f $ map jp content where jp x = joinPath [p, x] getSubDirectories :: (MonadIO io) => FilePath -> io [FilePath] getSubDirectories = filterDirContents doesDirectoryExist getFilesInFolder :: (MonadIO io) => FilePath -> io [FilePath] getFilesInFolder = filterDirContents doesFileExist -- * initFS :: (MonadIO io) => io () initFS = liftIO $ mapM_ createDirWhenDoesNotExist fsDirs where createDirWhenDoesNotExist d = do existDir <- doesDirectoryExist d unless existDir . createDirectory $ d removeFS :: (MonadIO io) => io () removeFS = liftIO $ removeDirectoryRecursive datadir isSetUpFS :: (MonadIO io) => io Bool isSetUpFS = liftIO . fmap and $ mapM doesDirectoryExist fsDirs createDirectoryLocked :: FilePath -> (FilePath -> IO ()) -> IO () createDirectoryLocked d m = do let d' = d <.> "locked" createDirectory d' m d' renameDirectory d' d createUserFileDir :: (MonadIO io) => Username -> io () createUserFileDir u = liftIO $ forM_ ["private-files", "public-files" ] $ \d -> do let dir = dirName u </> d exists <- doesDirectoryExist dir unless exists $ createDirectoryIfMissing True dir copyUsersFile :: (MonadIO io) => Username -> FilePath -> UsersFile -> io () copyUsersFile username tmpPath userfile = liftIO $ do createUserFileDir username let dirname = dirName username publicDir = dirname </> "public-files" privateDir = dirname </> "private-files" Dir.copyFile tmpPath $ usersFile (publicDir </>) (privateDir </>) userfile -- Calculates the file modification time in UTC time from the File status fileModificationInUTCTime = posixSecondsToUTCTime . realToFrac . modificationTime listFiles :: (MonadIO io) => Username -> io [(UsersFile, FileInfo)] listFiles username = liftIO $ do createUserFileDir username let dirname = dirName username privateFiles <- f (dirname </> "private-files") UsersPrivateFile publicFiles <- f (dirname </> "public-files") UsersPublicFile return $ privateFiles ++ publicFiles where f dir typ = do paths <- getFilesInFolder dir forM paths $ \path -> do status <- getFileStatus path let info = FileInfo (fileOffsetToInt $ fileSize status) (fileModificationInUTCTime status) return (typ $ takeFileName path, info) fileOffsetToInt (COff x) = fromIntegral x getFile :: (MonadIO io) => Username -> UsersFile -> io FilePath getFile username userfile = liftIO $ do createUserFileDir username let dirname = dirName username publicDir = dirname </> "public-files" privateDir = dirname </> "private-files" usersFile (f publicDir) (f privateDir) userfile where f dir fn = do let fname = dir </> fn exists <- doesFileExist fname unless exists $ error $ concat [ "File (", fn, ") does not exist in users folder (" , show username, ")" ] return fname -- Collects the test script, test case and the submission and copies them to the -- the directory named after the submission key placed in the test-outgoing directory saveTestJob :: (MonadIO io) => SubmissionKey -> Submission -> TestScript -> TestCase -> io () saveTestJob sk submission testScript testCase = liftIO $ do -- If there is a test case, we copy the information to the desired let tjk = submissionKeyToTestJobKey sk tjPath = dirName tjk exists <- doesDirectoryExist tjPath when exists $ error $ concat ["Test job directory already exist:", show tjk] createDirectoryLocked tjPath $ \p -> do fileSave (p </> "script") (tsScript testScript) -- Save Simple or Zipped Submission withSubmissionValue (solution submission) (flip fileSave) (flip fileSaveBS) (p </> "submission") -- Save Simple or Zipped Test Case withTestCaseValue (tcValue testCase) (flip fileSave) (flip fileSaveBS) (p </> "tests") -- Insert the feedback info for the file system part of the database. This method is -- used by the tests only, and serves as a model for interfacing with the outside world. insertTestFeedback :: (MonadIO io) => SubmissionKey -> FeedbackInfo -> io () insertTestFeedback sk info = liftIO $ do let sDir = submissionKeyMap (testIncomingDataDir </>) sk <.> "locked" createDirectoryIfMissing True sDir let student comment = fileSave (sDir </> "public") comment admin comment = fileSave (sDir </> "private") comment result bool = fileSave (sDir </> "result") (show bool) feedbackInfo result student admin evaluated info where evaluated _ _ = error "insertTestComment: Evaluation should not be inserted by test." finalizeTestFeedback :: (MonadIO io) => SubmissionKey -> io () finalizeTestFeedback sk = liftIO $ do let sDir = submissionKeyMap (testIncomingDataDir </>) sk renameDirectory (sDir <.> "locked") sDir -- Test Feedbacks are stored in the persistence layer, in the test-incomming directory -- each one in a file, named after an existing submission in the system testFeedbacks :: (MonadIO io) => io [(SubmissionKey, Feedback)] testFeedbacks = liftIO (createFeedbacks =<< processables) where processables = filter (not . (`isSuffixOf` ".locked")) <$> getSubDirectories testIncomingDataDir createFeedbacks = fmap join . mapM createFeedback createFeedback path = do let sk = SubmissionKey . last $ splitDirectories path addKey x = (sk, x) files <- getFilesInFolder path fmap (map addKey . catMaybes) $ forM files $ \file -> do fileDate <- fileModificationInUTCTime <$> getFileStatus file let (_dir,fname) = splitFileName file feedback f = Feedback f fileDate case fname of "private" -> Just . feedback . MessageForAdmin <$> fileLoad file "public" -> Just . feedback . MessageForStudent <$> fileLoad file "result" -> Just . feedback . TestResult . readMaybeErr file <$> fileLoad file _ -> return Nothing where readMaybeErr :: (Read a) => FilePath -> String -> a readMaybeErr fp = fromMaybe (error $ "Non-parseable data in file: " ++ fp) . readMaybe -- Deletes the comments (test-agent and message as well) -- contained file from the test-incomming directory, named after -- an existing submission deleteTestFeedbacks :: (MonadIO io) => SubmissionKey -> io () deleteTestFeedbacks = liftIO . submissionKeyMap (removeDirectoryRecursive . (testIncomingDataDir </>)) -- Removes the file if exists, otherwise do nothing removeFileIfExists :: FilePath -> IO () removeFileIfExists path = do exists <- doesFileExist path when exists $ removeFile path
pgj/bead
src/Bead/Persistence/SQL/FileSystem.hs
Haskell
bsd-3-clause
8,847
-- | Support for basic table drawing. module Brick.Widgets.Table ( -- * Types Table , ColumnAlignment(..) , RowAlignment(..) , TableException(..) -- * Construction , table -- * Configuration , alignLeft , alignRight , alignCenter , alignTop , alignMiddle , alignBottom , setColAlignment , setRowAlignment , setDefaultColAlignment , setDefaultRowAlignment , surroundingBorder , rowBorders , columnBorders -- * Rendering , renderTable ) where import Control.Monad (forM) import qualified Control.Exception as E import Data.List (transpose, intersperse, nub) import qualified Data.Map as M import Graphics.Vty (imageHeight, imageWidth) import Brick.Types import Brick.Widgets.Core import Brick.Widgets.Center import Brick.Widgets.Border -- | Column alignment modes. data ColumnAlignment = AlignLeft -- ^ Align all cells to the left. | AlignCenter -- ^ Center the content horizontally in all cells in the column. | AlignRight -- ^ Align all cells to the right. deriving (Eq, Show, Read) -- | Row alignment modes. data RowAlignment = AlignTop -- ^ Align all cells to the top. | AlignMiddle -- ^ Center the content vertically in all cells in the row. | AlignBottom -- ^ Align all cells to the bottom. deriving (Eq, Show, Read) -- | A table creation exception. data TableException = TEUnequalRowSizes -- ^ Rows did not all have the same number of cells. | TEInvalidCellSizePolicy -- ^ Some cells in the table did not use the 'Fixed' size policy for -- both horizontal and vertical sizing. deriving (Eq, Show, Read) instance E.Exception TableException where -- | A table data structure. data Table n = Table { columnAlignments :: M.Map Int ColumnAlignment , rowAlignments :: M.Map Int RowAlignment , tableRows :: [[Widget n]] , defaultColumnAlignment :: ColumnAlignment , defaultRowAlignment :: RowAlignment , drawSurroundingBorder :: Bool , drawRowBorders :: Bool , drawColumnBorders :: Bool } -- | Construct a new table. -- -- The argument is the list of rows, with each element of the argument -- list being the columns of the respective row. -- -- By default, all columns are left-aligned. Use the alignment functions -- in this module to change that behavior. -- -- By default, all rows are top-aligned. Use the alignment functions in -- this module to change that behavior. -- -- By default, the table will draw borders between columns, between -- rows, and around the outside of the table. Border-drawing behavior -- can be configured with the API in this module. Note that tables -- always draw with 'joinBorders' enabled. -- -- All cells of all rows MUST use the 'Fixed' growth policy for both -- horizontal and vertical growth. If the argument list contains -- any cells that use the 'Greedy' policy, this will raise a -- 'TableException'. -- -- All rows must have the same number of cells. If not, this will raise -- a 'TableException'. table :: [[Widget n]] -> Table n table rows = if not allFixed then E.throw TEInvalidCellSizePolicy else if not allSameLength then E.throw TEUnequalRowSizes else t where allSameLength = length (nub (length <$> rows)) <= 1 allFixed = all fixedRow rows fixedRow = all fixedCell fixedCell w = hSize w == Fixed && vSize w == Fixed t = Table { columnAlignments = mempty , rowAlignments = mempty , tableRows = rows , drawSurroundingBorder = True , drawRowBorders = True , drawColumnBorders = True , defaultColumnAlignment = AlignLeft , defaultRowAlignment = AlignTop } -- | Configure whether the table draws a border on its exterior. surroundingBorder :: Bool -> Table n -> Table n surroundingBorder b t = t { drawSurroundingBorder = b } -- | Configure whether the table draws borders between its rows. rowBorders :: Bool -> Table n -> Table n rowBorders b t = t { drawRowBorders = b } -- | Configure whether the table draws borders between its columns. columnBorders :: Bool -> Table n -> Table n columnBorders b t = t { drawColumnBorders = b } -- | Align the specified column to the right. The argument is the column -- index, starting with zero. alignRight :: Int -> Table n -> Table n alignRight = setColAlignment AlignRight -- | Align the specified column to the left. The argument is the column -- index, starting with zero. alignLeft :: Int -> Table n -> Table n alignLeft = setColAlignment AlignLeft -- | Align the specified column to center. The argument is the column -- index, starting with zero. alignCenter :: Int -> Table n -> Table n alignCenter = setColAlignment AlignCenter -- | Align the specified row to the top. The argument is the row index, -- starting with zero. alignTop :: Int -> Table n -> Table n alignTop = setRowAlignment AlignTop -- | Align the specified row to the middle. The argument is the row -- index, starting with zero. alignMiddle :: Int -> Table n -> Table n alignMiddle = setRowAlignment AlignMiddle -- | Align the specified row to bottom. The argument is the row index, -- starting with zero. alignBottom :: Int -> Table n -> Table n alignBottom = setRowAlignment AlignBottom -- | Set the alignment for the specified column index (starting at -- zero). setColAlignment :: ColumnAlignment -> Int -> Table n -> Table n setColAlignment a col t = t { columnAlignments = M.insert col a (columnAlignments t) } -- | Set the alignment for the specified row index (starting at -- zero). setRowAlignment :: RowAlignment -> Int -> Table n -> Table n setRowAlignment a row t = t { rowAlignments = M.insert row a (rowAlignments t) } -- | Set the default column alignment for columns with no explicitly -- configured alignment. setDefaultColAlignment :: ColumnAlignment -> Table n -> Table n setDefaultColAlignment a t = t { defaultColumnAlignment = a } -- | Set the default row alignment for rows with no explicitly -- configured alignment. setDefaultRowAlignment :: RowAlignment -> Table n -> Table n setDefaultRowAlignment a t = t { defaultRowAlignment = a } -- | Render the table. renderTable :: Table n -> Widget n renderTable t = joinBorders $ (if drawSurroundingBorder t then border else id) $ Widget Fixed Fixed $ do let rows = tableRows t cellResults <- forM rows $ mapM render let rowHeights = rowHeight <$> cellResults colWidths = colWidth <$> byColumn allRowAligns = (\i -> M.findWithDefault (defaultRowAlignment t) i (rowAlignments t)) <$> [0..length rowHeights - 1] allColAligns = (\i -> M.findWithDefault (defaultColumnAlignment t) i (columnAlignments t)) <$> [0..length byColumn - 1] rowHeight = maximum . fmap (imageHeight . image) colWidth = maximum . fmap (imageWidth . image) byColumn = transpose cellResults toW = Widget Fixed Fixed . return totalHeight = sum rowHeights applyColAlignment align width w = Widget Fixed Fixed $ do result <- render w case align of AlignLeft -> return result AlignCenter -> render $ hLimit width $ hCenter $ toW result AlignRight -> render $ padLeft (Pad (width - imageWidth (image result))) $ toW result applyRowAlignment rHeight align result = case align of AlignTop -> toW result AlignMiddle -> vLimit rHeight $ vCenter $ toW result AlignBottom -> vLimit rHeight $ padTop Max $ toW result mkColumn (hAlign, width, colCells) = do let paddedCells = flip map (zip3 allRowAligns rowHeights colCells) $ \(vAlign, rHeight, cell) -> applyColAlignment hAlign width $ applyRowAlignment rHeight vAlign cell maybeRowBorders = if drawRowBorders t then intersperse (hLimit width hBorder) else id render $ vBox $ maybeRowBorders paddedCells columns <- mapM mkColumn $ zip3 allColAligns colWidths byColumn let maybeColumnBorders = if drawColumnBorders t then let rowBorderHeight = if drawRowBorders t then length rows - 1 else 0 in intersperse (vLimit (totalHeight + rowBorderHeight) vBorder) else id render $ hBox $ maybeColumnBorders $ toW <$> columns
sjakobi/brick
src/Brick/Widgets/Table.hs
Haskell
bsd-3-clause
8,997
----------------------------------------------------------------------------- -- | -- Module : Plugins.StdinReader -- Copyright : (c) Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- A plugin for reading from `stdin`. -- -- Exports: -- - `StdinReader` to safely display stdin content (striping actions). -- - `UnsafeStdinReader` to display stdin content as-is. -- ----------------------------------------------------------------------------- module Plugins.StdinReader (StdinReader(..)) where import Prelude import System.Posix.Process import System.Exit import System.IO import Control.Exception (SomeException(..), handle) import Plugins import Actions (stripActions) data StdinReader = StdinReader | UnsafeStdinReader deriving (Read, Show) instance Exec StdinReader where start stdinReader cb = do s <- handle (\(SomeException e) -> do hPrint stderr e; return "") (hGetLineSafe stdin) cb $ escape stdinReader s eof <- isEOF if eof then exitImmediately ExitSuccess else start stdinReader cb escape :: StdinReader -> String -> String escape StdinReader = stripActions escape UnsafeStdinReader = id
dragosboca/xmobar
src/Plugins/StdinReader.hs
Haskell
bsd-3-clause
1,286
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Mezzo.Compose.Harmony -- Description : Harmony composition units -- Copyright : (c) Dima Szamozvancev -- License : MIT -- -- Maintainer : ds709@cam.ac.uk -- Stability : experimental -- Portability : portable -- -- Literals for chords and progressions. -- ----------------------------------------------------------------------------- module Mezzo.Compose.Harmony where import Mezzo.Model import Mezzo.Compose.Types import Mezzo.Compose.Builder import Mezzo.Compose.Templates import Mezzo.Compose.Basic import GHC.TypeLits infixr 5 :+ -- * Functional harmony terms -- | Type of harmonic terms in some key. type InKey k v = KeyS k -> v toProg :: InKey k (PhraseList p) -> InKey k (Prog p) toProg _ = const Prog -- ** Progressions -- | Create a new musical progression from the given time signature and progression schema. prog :: ValidProg r t p => InKey k (PhraseList p) -> Music (Sig :: Signature t k r) (FromProg p t) prog ik = Progression ((toProg ik) KeyS) -- ** Phrases -- | List of phrases in a progression parameterised by the key, ending with a cadence. data PhraseList (p :: ProgType k l) where -- | A cadential phrase, ending the progression. Cdza :: Cad c -> KeyS k -> PhraseList (CadPhrase c) -- | Add a new phrase to the beginning of the progression. (:+) :: InKey k (Phr p) -> InKey k (PhraseList ps) -> KeyS k -> PhraseList (p := ps) -- | Create a new cadential phrase. cadence :: InKey k (Cad c) -> InKey k (PhraseList (CadPhrase c)) cadence c = \k -> Cdza (c k) k -- | Dominant-tonic phrase. ph_I :: InKey k (Ton (t :: Tonic k l)) -> InKey k (Phr (PhraseI t :: Phrase k l)) ph_I _ = const Phr -- | Dominant-tonic phrase. ph_VI :: InKey k (Dom (d :: Dominant k l1)) -> InKey k (Ton (t :: Tonic k (l - l1))) -> InKey k (Phr (PhraseVI d t :: Phrase k l)) ph_VI _ _ = const Phr -- | Tonic-dominant-tonic phrase. ph_IVI :: InKey k (Ton (t1 :: Tonic k (l2 - l1))) -> InKey k (Dom (d :: Dominant k l1)) -> InKey k (Ton (t2 :: Tonic k (l - l2))) -> InKey k (Phr (PhraseIVI t1 d t2 :: Phrase k l)) ph_IVI _ _ _ = const Phr -- ** Cadences -- | Authentic V-I dominant cadence. auth_V_I :: InKey k (Cad (AuthCad (DegChord :: DegreeC V MajQ k Inv1 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) auth_V_I = const Cad -- | Authentic V7-I dominant seventh cadence. auth_V7_I :: InKey k (Cad (AuthCad7 (DegChord :: DegreeC V DomQ k Inv2 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) auth_V7_I = const Cad -- | Authentic vii-I leading tone cadence. auth_vii_I :: InKey k (Cad (AuthCadVii (DegChord :: DegreeC VII DimQ k Inv1 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) auth_vii_I = const Cad -- | Authentic cadential 6-4 cadence. auth_64_V7_I :: InKey k (Cad (AuthCad64 (DegChord :: DegreeC I (KeyToQual k) k Inv2 Oct3) (DegChord :: DegreeC V DomQ k Inv3 Oct2) (DegChord :: DegreeC I (KeyToQual k) k Inv1 Oct3))) auth_64_V7_I = const Cad -- | Deceptive V-iv cadence. decept_V_iv :: InKey k (Cad (DeceptCad (DegChord :: DegreeC V DomQ k Inv2 Oct2) (DegChord :: DegreeC VI (KeyToOtherQual k) k Inv1 Oct2))) decept_V_iv = const Cad -- | Full cadence, starting with a subdominant. full :: InKey k (Sub s) -> InKey k (Cad c) -> InKey k (Cad (FullCad s c)) full _ _ = const Cad -- | End progression without an explicit cadence. end :: InKey k (PhraseList (CadPhrase NoCad)) end = cadence $ const Cad -- ** Tonic chords -- | Tonic chord. ton :: InKey k (Ton (TonT (DegChord :: DegreeC I (KeyToQual k) k Inv0 Oct3))) ton = const Ton -- | Doubled tonics. ton_T_T :: InKey k (Ton ton1) -> InKey k (Ton ton2) -> InKey k (Ton (TonTT ton1 ton2)) ton_T_T _ _ = const Ton -- ** Dominants -- | Dominant (V) chord. dom_V :: InKey k (Dom (DomVM (DegChord :: DegreeC V MajQ k Inv2 Oct2))) dom_V = const Dom -- | Dominant seventh (V7) chord. dom_V7 :: InKey k (Dom (DomV7 (DegChord :: DegreeC V DomQ k Inv2 Oct2))) dom_V7 = const Dom -- | Dominant leading tone (vii) chord. dom_vii0 :: InKey k (Dom (DomVii0 (DegChord :: DegreeC VII DimQ k Inv1 Oct2))) dom_vii0 = const Dom -- | Secondary dominant - dominant (V/V-V7) chord. dom_II_V7 :: InKey k (Dom (DomSecD (DegChord :: DegreeC II DomQ k Inv0 Oct3) (DegChord :: DegreeC V DomQ k Inv2 Oct2))) dom_II_V7 = const Dom -- | Subdominant followed by a dominant. dom_S_D :: InKey k (Sub subdom) -> InKey k (Dom dom) -> InKey k (Dom (DomSD subdom dom)) dom_S_D _ _ = const Dom -- | Dominant followed by another dominant. dom_D_D :: InKey k (Dom dom1) -> InKey k (Dom dom2) -> InKey k (Dom (DomDD dom1 dom2)) dom_D_D _ _ = const Dom -- ** Subdominants -- | Subdominant fourth (IV) chord. subdom_IV :: InKey k (Sub (SubIV (DegChord :: DegreeC IV (KeyToQual k) k Inv2 Oct2))) subdom_IV = const Sub -- | Subdominant minor second (ii) chord. subdom_ii :: IsMajor k "ii subdominant" => InKey k (Sub (SubIIm (DegChord :: DegreeC II MinQ k Inv0 Oct3))) subdom_ii = const Sub -- | Subdominant third-fourth (iii-IV) progression. subdom_iii_IV :: IsMajor k "iii-IV subdominant" => InKey k (Sub (SubIIImIVM (DegChord :: DegreeC III MinQ k Inv0 Oct3) (DegChord :: DegreeC IV MajQ k Inv3 Oct2))) subdom_iii_IV = const Sub -- | Doubled subdominants. subdom_S_S :: InKey k (Sub sub1) -> InKey k (Sub sub2) -> InKey k (Sub (SubSS sub1 sub2)) subdom_S_S _ _ = const Sub -- * Time signatures -- | Duple meter (2/4). duple :: TimeSig 2 duple = TimeSig -- | Triple meter (3/4). triple :: TimeSig 3 triple = TimeSig -- | Quadruple meter (4/4). quadruple :: TimeSig 4 quadruple = TimeSig -- * Key literals mkKeyLits
DimaSamoz/mezzo
src/Mezzo/Compose/Harmony.hs
Haskell
mit
5,690
module Mockups.Parsers.Element where import Control.Applicative import Data.Attoparsec.Char8 import Mockups.Elements.Element import Mockups.Parsers.Common import Mockups.Parsers.Img import Mockups.Parsers.Txt import Mockups.Parsers.Box eltParser :: IndentLevel -> Parser Element eltParser lvl = do simpleEltParser lvl <|> containerParser lvl containerParser :: IndentLevel -> Parser Element containerParser lvl = do indentParser lvl containerAttr <- boxParser endOfLine children <- many $ eltParser (lvl + 1) return $ Container containerAttr children simpleEltParser:: IndentLevel -> Parser Element simpleEltParser lvl = do indentParser lvl simpleAttr <- imgParser <|> txtParser endOfLine return $ SimpleElement simpleAttr
ostapneko/tiny-mockups
src/main/Mockups/Parsers/Element.hs
Haskell
mit
863
module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Yesod.Auth.OAuth2.Github (oauth2Github) import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import Yesod.Form.I18n.Russian (russianFormMessage) data App = App { appSettings :: AppSettings , appStatic :: Static , appConnPool :: ConnectionPool , appHttpManager :: Manager , appLogger :: Logger } instance HasHttpManager App where getHttpManager = appHttpManager mkYesodData "App" $(parseRoutesFile "config/routes") mkMessage "App" "messages" "ru" type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) instance Yesod App where approot = ApprootMaster $ appRoot . appSettings makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 120 "config/client_session_key.aes" defaultLayout widget = do mmsg <- getMessage mauth <- maybeAuth pc <- widgetToPageContent $ do addStylesheetRemote "http://fonts.googleapis.com/css?family=PT+Sans:400,700&subset=cyrillic,latin" addStylesheetRemote "http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700&subset=latin,cyrillic" addStylesheetRemote "https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" addStylesheetRemote "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" addStylesheet $ StaticR css_default_css $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") authRoute _ = Just $ AuthR LoginR isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized isAuthorized BlogPostsR True = authenticated isAuthorized NewBlogPostR _ = authenticated isAuthorized (EditBlogPostR id') _ = authorizeBlogPost id' isAuthorized (BlogPostR id') True = authorizeBlogPost id' isAuthorized CategoriesR True = authorizeAdmin isAuthorized NewCategoryR _ = authorizeAdmin isAuthorized (EditCategoryR _) _ = authorizeAdmin isAuthorized (CategoryR _) True = authorizeAdmin isAuthorized TagsR True = authorizeAdmin isAuthorized NewTagR _ = authorizeAdmin isAuthorized (EditTagR _) _ = authorizeAdmin isAuthorized (TagR _) True = authorizeAdmin isAuthorized UsersR True = authorizeAdmin isAuthorized NewUserR _ = authorizeAdmin isAuthorized (EditUserR id') _ = authorizeProfile id' isAuthorized (UserR id') True = authorizeProfile id' isAuthorized _ _ = return Authorized addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger authenticated :: Handler AuthResult authenticated = do mauth <- maybeAuth return $ maybe AuthenticationRequired (const Authorized) mauth authorizeAdmin :: Handler AuthResult authorizeAdmin = do mauth <- maybeAuth case mauth of Nothing -> return AuthenticationRequired Just (Entity _ u) | userAdmin u -> return Authorized | otherwise -> unauthorizedI MsgAuthNotAnAdmin authorizeBlogPost :: BlogPostId -> Handler AuthResult authorizeBlogPost blogPostId = do blogPost <- runDB $ get404 blogPostId let authorId = blogPostAuthorId blogPost mauth <- maybeAuth case mauth of Nothing -> return AuthenticationRequired Just (Entity id' u) | userAdmin u -> return Authorized | id' == authorId -> return Authorized | otherwise -> unauthorizedI MsgAuthNotAnAdmin authorizeProfile :: UserId -> Handler AuthResult authorizeProfile userId = do mauth <- maybeAuth case mauth of Nothing -> return AuthenticationRequired Just (Entity id' u) | userAdmin u -> return Authorized | id' == userId -> return Authorized | otherwise -> unauthorizedI MsgAuthNotAnAdmin instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId loginDest _ = HomeR logoutDest _ = HomeR redirectToReferer _ = False getAuthId creds = runDB $ do $(logDebug) $ "Extra account information: " <> (pack . show $ extra) x <- getBy $ UniqueUser ident case x of Just (Entity uid _) -> return $ Just uid Nothing -> do let name = lookupExtra "login" avatarUrl = lookupExtra "avatar_url" fmap Just $ insert $ User ident name avatarUrl False where ident = credsIdent creds extra = credsExtra creds lookupExtra key = fromMaybe (error "No " <> key <> " in extra credentials") (lookup key extra) authPlugins app = mapMaybe mkPlugin . appOA2Providers $ appSettings app where mkPlugin (OA2Provider{..}) = case (oa2provider, oa2clientId, oa2clientSecret) of (_, _, "not-configured") -> Nothing (_, "not-configured", _) -> Nothing ("github", cid, sec) -> Just $ oauth2Github (pack cid) (pack sec) _ -> Nothing authHttpManager = getHttpManager instance YesodAuthPersist App instance RenderMessage App FormMessage where renderMessage _ _ = russianFormMessage
ruHaskell/ruhaskell-yesod
Foundation.hs
Haskell
mit
6,464
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- import Text.Printf import Data.List -- unbiased coin, probability of landing heads is 0.5 -- Expected value is sum(pi*vi) for all i computeExpectedValue :: [Int] -> Double computeExpectedValue = foldl' (\acc n -> (fromIntegral n)* 0.5 + acc) 0.0 main :: IO () main = do nstr <- getContents let ns = map read . tail . lines $ nstr putStrLn . printf "%.1f\n" $ computeExpectedValue ns
cbrghostrider/Hacking
HackerRank/Mathematics/Probability/bdayGift.hs
Haskell
mit
804
import Data.Char import Data.List digitize :: Int -> [Int] digitize x = map digitToInt $ show x palindrome :: Eq a => [a] -> Bool palindrome xs = xs == (reverse xs) numdrome :: Int -> Bool numdrome = palindrome . digitize list = [x |a <- [1..999], b <- [1..999], let x = a*b] largestDrome = last $ sort $ filter numdrome list
johnprock/euler
p4.hs
Haskell
mit
332
module Main where import Data.ByteString.Char8 as C8 (ByteString(..),readFile,unpack) import Data.List (intercalate) import System.Console.GetOpt (OptDescr(..),ArgDescr(..),ArgOrder(..),getOpt,usageInfo) import System.Environment (getArgs) import System.Exit (ExitCode(..),exitSuccess,exitWith) import Debug.Trace (trace) import Core (CDevice(..),CSequencer(..),CComponent(..),CInst(..),CArgType(..),CFormatAtom(..),SInst(..),SArgType(..)) import Configs (parseSequencersCfg,parseComponentsCfg,parseDeviceCfg) import Compiler (compile) data ClOptions = ClOptions { clOptionsOutFile :: String, clOptionsTextFile :: String, clOptionsSequencersFile :: String, clOptionsComponentsFile :: String, clOptionsDeviceFile :: String} deriving (Show) clHeader :: String clHeader = "seqasm [OPTION..] SOURCEFILE" clOptions :: [OptDescr (ClOptions -> ClOptions)] clOptions = [Option ['o'] ["outfile"] (ReqArg (\x -> (\ opts -> opts {clOptionsOutFile = x})) "File") "Output File", Option ['t'] ["textdebug"] (ReqArg (\x -> (\ opts -> opts {clOptionsTextFile = x})) "File") "Output Debug Text File", Option ['s'] ["sequencers"] (ReqArg (\x -> (\ opts -> opts {clOptionsSequencersFile = x})) "File") "Sequencers File", Option ['c'] ["components"] (ReqArg (\x -> (\ opts -> opts {clOptionsComponentsFile = x})) "File") "Components File", Option ['d'] ["device"] (ReqArg (\x -> (\ opts -> opts {clOptionsDeviceFile = x})) "File") "Device File"] main :: IO () main = do args <- getArgs case getOpt Permute clOptions args of (optArgs,[sourceFile],[]) -> do let options = foldr (\ x i -> x i) (ClOptions "" "" "" "" "") optArgs sequencersText <- C8.readFile $ clOptionsSequencersFile options componentsText <- C8.readFile $ clOptionsComponentsFile options deviceText <- C8.readFile $ clOptionsDeviceFile options sourceText <- C8.readFile $ sourceFile let parseResult = do sequencers <- parseSequencersCfg sequencersText components <- parseComponentsCfg componentsText device <- parseDeviceCfg sequencers components deviceText result <- compile device $ C8.unpack sourceText return result case parseResult of Right (result,resultText) -> do writeFile (clOptionsOutFile options) result writeFile (clOptionsTextFile options) resultText exitSuccess Left errorMessages -> do putStrLn errorMessages exitWith (ExitFailure 1) (_,_,errorMessages) -> do putStrLn $ intercalate "\n" errorMessages ++ usageInfo clHeader clOptions exitWith (ExitFailure 2)
horia141/bachelor-thesis
dev/SeqAsm/Main.hs
Haskell
mit
2,850
module GHCJS.DOM.CSSValueList ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/CSSValueList.hs
Haskell
mit
42
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE PatternGuards, MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts, FlexibleInstances, TypeSynonymInstances, UndecidableInstances, OverloadedStrings, MultiWayIf #-} module Basic.Eval (run, runProg, Eval(..) )where import Basic.Doub hiding (D) import Basic.AST import Basic.Type import Basic.Parser (parseDoubs) -- for INPUT import Data.Char (isNumber) import Data.Maybe (fromMaybe) import Data.Monoid import Data.List (uncons) import Data.List.Split (splitOn) import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Vector ((!?)) import qualified Data.Vector as V import qualified Data.Vector.Mutable as V (write) import Text.Printf (printf) import Text.Show.Pretty (ppShow, pPrint) import Control.Monad import Control.Monad.State import Control.Monad.Except import Control.Monad.Extra import System.Random import System.IO (hFlush, stdout) data Val = S Text | N Doub | A Dims (Vec Val) instance Eq Val where S a == S b = a == b N a == N b = a == b _ == _ = False instance TC Val where unifies = Yes . typeof typeof (S _) = Stringy typeof (N _) = Numeric typeof (A _ v) = maybe None typeof $ v !? 0 instance Show Val where showsPrec p v = case v of S t -> showString $ T.unpack t N d -> showString $ show d A dim v -> showString $ show v emptyString, zero :: Val emptyString = S T.empty zero = N 0 data VMErr = BadSubscript PC -- | On what line did it happen? Dims -- | What was the index used? Dims -- | What was the upper (inclusive) limit? | BadAddress PC -- | On what line did it happen? Int -- | What was the address? | BadType PC -- | On what line did it happen? Type -- | Expected this Type -- | Got this | NextError -- | Next without For PC -- | On what line did it happen? | ForError -- | For without Next PC -- | On what line did it happen? | WendError -- | Wend without While PC -- | On what line did it happen? | WhileError -- | While without Wend PC -- | On what line did it happen? | RetError -- | RETURN without GOSUB PC -- | On what line did it happen? instance Show VMErr where showsPrec p e = showString $ case e of BadSubscript linum tried real -> printf "on line %d ==> bad subscript: %M, for array with dim %M" linum tried real BadAddress pc targ -> printf "on line $d ==> bad target of a GOTO|GOSUB: %d" pc targ BadType pc expc got -> printf "on line %d ==> type mismatch: expected %T, got %T" pc expc got NextError pc -> printf "on line %d ==> NEXT without FOR" pc ForError pc -> printf "on line %d ==> FOR without NEXT" pc RetError pc -> printf "on line %d ==> RETURN without having called GOSUB" pc WendError pc -> printf "on line %d ==> WEND without WHILE" pc WhileError pc -> printf "on line %d ==> WHILE without WEND" pc type PC = Int data FlowCTX = InFor { lstart :: PC -- | Where to go each iteration repeat , lvar :: Var -- | Variable we loop over , toEnter :: Expr -- | test for entry , mstep :: VMState () -- | What to do each time we come back } | InWhile { lstart :: PC -- | Where to go each iteration repeat , toEnter :: Expr -- | test for loop entry, 0 => don't enter } | InSub { lstart :: PC -- | address to return to on a RET } instance Show FlowCTX where showsPrec p c = case c of InFor s v e _ -> showString $ "FOR start: " ++ show s ++ " var: " ++ show v InWhile s _ -> showString $ "WHILE start: " ++ show s InSub s -> showString $ "SUB start: " ++ show s data EvalState = EV { heap :: Map Var Val , pc :: Int , linumMap :: Map Int Int , flowStack :: [FlowCTX] , prog :: Vec Stmt } pushFlow :: (PC -> FlowCTX) -> VMState() pushFlow mkCtx = do ev <- get let oldStack = flowStack ev ctx = mkCtx $ pc ev put ev{flowStack = ctx : oldStack} logCtx ("new context: " ++ show ctx) st <- flowStack <$> get logCtx ("stack is \n" ++ ppShow st) popFlow :: VMState (Maybe FlowCTX) popFlow = do ev <- get case flowStack ev of [] -> logCtx "popped from empty stack" >> pure Nothing x:xs -> logCtx ("popped " ++ show x) >> put ev{flowStack = xs} >> pure (Just x) peekFlow :: VMState (Maybe FlowCTX) peekFlow = do mctx <- uncons . flowStack <$> get pure $ fst <$> mctx pushRet :: VMState () pushRet = pushFlow (InSub . succ) pushFor :: Var -> Expr -> VMState () -> VMState () pushFor var test step = pushFlow $ \pc -> InFor (1 + pc) var test step pushWhile :: Expr -> VMState() pushWhile e = pushFlow $ \pc -> InWhile (1 + pc) e getLineMap :: VMState (Map Int Int) getLineMap = linumMap <$> get getPC :: VMState PC getPC = pc <$> get getProg :: VMState (Vec Stmt) getProg = prog <$> get setPC :: PC -> VMState () setPC newPC = do ev <- get put ev{pc = newPC} incrPC :: VMState () incrPC = getPC >>= setPC . succ getRealLine :: VMState Int getRealLine = (M.!) <$> getLineMap <*> getPC asIndex :: Val -> VMState Int asIndex (N d) = pure $ floor d asIndex s = badType Numeric $ typeof s badAddr :: Int -> VMState a badAddr i = do l <- getRealLine throwError $ BadAddress l i badIdx :: Dims -> Dims -> VMState a badIdx tried real = do l <- getRealLine throwError $ BadSubscript l tried real badType :: Type -> Type -> VMState a badType expect actual = do l <- getRealLine throwError $ BadType l expect actual forError, nextError, whileError, wendError :: VMState a nextError = getRealLine >>= throwError . NextError forError = getRealLine >>= throwError . ForError wendError = getRealLine >>= throwError . WendError whileError = getRealLine >>= throwError . WhileError retError = getRealLine >>= throwError . RetError getVar :: Var -> VMState Val getVar v = accessVar v Nothing setVar :: Var -> Val -> VMState Val setVar var = accessVar var . Just accessVar :: Var -> Maybe Val -> VMState Val accessVar var mval = do ev <- get let oldHeap = heap ev (new, old) <- validate var mval $ M.lookup var oldHeap whenJust mval $ const (put ev{heap = M.insert var new oldHeap}) pure old -- | Validate does the heavy lifting for variable getting and setting. It -- checks index bounds and returns default values for variables that can -- have them (non-array vars). validate :: Var -- | variable we're accessing -> Maybe Val -- | Maybe we want to change it -> Maybe Val -- | What the heap says we have -> VMState (Val, Val) -- | (new, old) validate var mval Nothing = case var of SArr _ d@(Dims l) -> badIdx d (Dims $ Lit (LNum 0) <$ l) NArr _ d@(Dims l) -> badIdx d (Dims $ Lit (LNum 0) <$ l) SVar _ -> pure $ (fromMaybe emptyString mval, emptyString) NVar _ -> pure $ (fromMaybe zero mval, zero) validate var mval (Just v@(S _)) = pure $ (fromMaybe v mval, v) validate var mval (Just v@(N _)) = pure $ (fromMaybe v mval, v) validate var mval (Just a@(A adim v)) = setAt l a where dim@(Dims l) = dimsOf var idxErr = badIdx dim adim setAt :: [Expr] -> Val -> VMState (Val, Val) setAt [] v@(S _) = pure (fromMaybe v mval, v) setAt [] v@(N _) = pure (fromMaybe v mval, v) setAt (e:es) (A _ vec) = eval e >>= asIndex >>= \idx -> if idx <= V.length vec && idx > 0 then do (new, old) <- setAt es (vec V.! (idx - 1)) pure (A adim $ V.modify (\v -> V.write v (idx - 1) new) vec, old) else idxErr setAt _ _ = idxErr type VMState = ExceptT VMErr (StateT EvalState IO) logExpr, logLine, logStmt, logCtx, logEnd, logFor, logGoto :: String -> VMState () logg :: String -> VMState () loggHelp :: Int -> String -> VMState () logExpr = loggHelp 0 logLine = loggHelp 1 logStmt = loggHelp 2 logCtx = loggHelp 3 logEnd = loggHelp 4 logFor = loggHelp 5 logGoto = loggHelp 6 logg = loggHelp 100 loggHelp n = case n of -- _ -> const (pure ()) -- All 0 -> const (pure ()) -- Expr 1 -> const (pure ()) -- Line 2 -> const (pure ()) -- Stmt 3 -> const (pure ()) -- Ctx 4 -> const (pure ()) -- End 5 -> const (pure ()) -- For 6 -> const (pure ()) -- Goto _ -> liftIO . putStrLn class Eval a b | a -> b where eval :: a -> VMState b runProg :: Vec Stmt -> Map Int Int -> IO () runProg prg lmap = let init = EV { heap = M.empty , pc = 0 , linumMap = lmap , flowStack = [] , prog = prg } in do ret <- runStateT (runExceptT run) init case ret of (Left err, s) -> putStrLn "ERRORS:" >> print err (Right _, s )-> pure () run :: VMState () run = do pc <- getPC logLine $ "running line " ++ show pc prog <- getProg case prog !? pc of Nothing -> logEnd "Done" Just s -> eval s >> run instance Eval Stmt () where eval s = logStmt ("eval Statement : " ++ show s) >> case s of REM t -> incrPC NOP -> incrPC GOTO i -> goto i GOSUB i -> pushRet >> goto i ONGOTO e addrs -> ongoto e addrs ONGOSUB e addrs -> pushRet >> ongoto e addrs LET var e -> eval e >>= setVar var >> incrPC -- NEXT without any vars specified implicitly NEXT vs -> handleNext vs -- This is a doozy FOR var start end mstep -> do N s <- maybe (pure $ N 1) eval mstep N e <- eval end let test = if s < 0 then Prim (Gt (Var var) (Lit $ LNum e)) else Prim (Lte (Var var) (Lit $ LNum e)) let eachLoop = do res <- eval (Prim (Add (Var var) (Lit $ LNum s))) setVar var res >> pure () eval start >>= setVar var N v <- eval test if v /= 0 then pushFor var test eachLoop >> incrPC else do prog <- getProg let isNext (NEXT _) = True isNext _ = False case V.findIndex isNext prog of Nothing -> forError Just i -> setPC i WHILE mexpr -> do let test = fromMaybe (Lit $ LNum 1) mexpr N enter <- eval test if enter /= 0 then pushWhile test >> incrPC else do prog <- getProg let isWend (WEND _) = True isWend _ = False case V.findIndex isWend prog of Nothing -> whileError Just i -> setPC i WEND mexpr -> do N escape <- eval $ fromMaybe (Lit $ LNum 0) mexpr ctx <- popFlow case ctx of Just (InWhile lstart reenter) -> do N goback <- eval reenter if escape /= 0 || goback == 0 then incrPC else setPC lstart _ -> wendError IF _ _ _ -> error "IF statements should have been converted to IFGO by now" IFGO e i _ -> do N choice <- eval e if choice /= 0 then goto i else incrPC DIM dims -> mapM_ mkdim dims where stringName = ("$" `T.isSuffixOf`) mkdim (name, d@(Dims es)) = do ev <- get sizes <- mapM (eval >=> asIndex) es let oldHeap = heap ev (var, baseval) | stringName name = (SArr name d, emptyString) | otherwise = (NArr name d, zero) val = foldr mkArr baseval sizes mkArr size val = A d (V.replicate size val) put ev{heap = M.insert var val oldHeap} incrPC RET -> whileM $ do ctx <- popFlow logCtx ("returning, found ctx: " ++ show ctx) case ctx of Nothing -> retError Just (InSub start) -> setPC start >> pure False Just _ -> pure True END -> getProg >>= setPC . length -- jump to end PRINT [] -> liftIO (putStrLn "") >> incrPC PRINT args -> do foldM printArg 0 args case last args of PSem _ -> incrPC _ -> liftIO (putStrLn "") >> incrPC where printArg l a = case a of PTab e -> do val <- asIndex =<< eval e if val <= l then pure l else liftIO $ putStr (replicate (val - l) ' ') >> pure val PSem e -> printDelim "" " " e l PCom e -> printDelim "\t" "\t" e l PReg e -> printDelim "" " " e l printDelim sdel ndel e len = do v <- eval e case v of S str -> do liftIO $ T.putStr str liftIO $ putStr sdel pure (len + T.length str) N n -> let str = show n ++ ndel in liftIO $ putStr str >> pure (len + length str) INPUT mtext vars -> do whenJust mtext (liftIO . T.putStr) liftIO $ hFlush stdout inputs <- loopM takeInput [] mapM_ (uncurry setVar) $ zip vars inputs incrPC where ty = typeof $ head vars filt = case ty of Stringy -> \line -> pure [S line] Numeric -> \line -> case parseDoubs line of Just vals -> pure $ map N vals Nothing -> do putStrLn $ "Couldn't parse " ++ show line pure [] takeInput ls = do new <- liftIO (filt =<< T.getLine) let acc = ls ++ new if length acc >= length vars then pure (Right acc) else do liftIO $ putStr "\n??" >> hFlush stdout pure (Left acc) goto :: PC -> VMState () goto i = logGoto ("GOing to " ++ show i) >> ifM ((i <) . V.length <$> getProg) (setPC i) (badAddr i) ongoto e addrs = do i <- asIndex =<< eval e if i > 0 && i <= length addrs then goto (addrs !! (i - 1)) else incrPC -- `handleNext`, `matchFors` and `decideFor` manage the logic necessary for -- determining how to respond to a NEXT statement. The argument lets it -- determine whether the NEXT was invoked with variables (e.g. `NEXT I, J`) or -- without. `handlNext` is used with loopM, returning a Right value holding the -- address to goto once it's determined or a Left value if it needs to keep -- popping contexts. There are some opportunities for BASIC runtime errors -- here: If a NEXT references a variable that isn't an iterator of some loop, or -- if we are not, in fact, inside a loop. handleNext [] = loopM matchFors Nothing >>= setPC handleNext vs = loopM matchFors (Just vs) >>= setPC matchFors mvs = do -- We don't necessarily want to pop a context; that only happens -- when the loop terminates. Since that _should_ happen less often, -- we'll peek at it first, and actually pop it later if necessary. ctx <- peekFlow case ctx of -- No loop context on the stack: NEXT without FOR error Nothing -> nextError Just (InFor start lvar test eachLoop) -> do case mvs of -- Implicit NEXT: The InFor we found is the one we use. -- Don't give `decide` more variables to test if the loop -- terminal condition is met. Nothing -> logFor "implicit next" >> decideFor test eachLoop [] start -- Explicit NEXT Just (var:rest) -- The InFor is the one we want if its loop variable is -- the same as the one at the head of the list. We -- give `decide` the `rest` of the variables, in case -- the terminal condition is met and we need to test -- another variable. | lvar == var -> logFor "found the right var" >> decideFor test eachLoop rest start -- If the variables don't match, we keep looking for -- the correct loop context. This means we don't -- change the list of variables NEXT was given. | otherwise -> logFor "popping for missed var" >> popFlow >> pure (Left $ Just (var:rest)) -- Only reached when NEXT invoked with explicit variables. -- If a variable that isn't an iterator of a FOR loop is -- specified, we'll get a "NEXT without FOR" error Just [] -> nextError -- Context is not a For loop: can't invoke NEXT -- when the innermost context is a WHILE or SUB Just _ -> nextError -- We need a lot of context to determine how to proceed once a the -- right InFor context is found. decideFor :: Expr -- Expression to test for loop re-entry -> VMState () -- VMState update -> [Var] -> PC -> VMState (Either (Maybe [Var]) PC) decideFor test loop more start = do -- `loop` is the state-changing update that increments -- or decrements the loop variable. loop N enter <- eval test logFor $ "test is " ++ show test logFor $ "result is " ++ show enter pc <- getPC -- If `enter` is True, we jump back to the loop start if | enter /= 0 -> pure (Right start) -- Else, if there are no more variables to test, we simply move -- on to the next statement | null more -> popFlow >> pure (Right $ pc + 1) -- If there _are_ variables remaining, we need to keep popping -- contexts to determine where to go | otherwise -> popFlow >> pure (Left $ Just more) instance Eval Var Val where eval = getVar -- much nicer than Stmt instance Eval Expr Val where eval e = do logExpr ("evaling " ++ show e) res <- case e of Lit l -> eval l Prim op -> eval op Paren e -> eval e Var v -> eval v logExpr ("got " ++ show res) pure res instance Eval (Op Expr) Val where eval o = case o of Rnd a -> do n <- eval a case n of N d | d < 0 -> error "RND seeding not implemented yet" | d == 1 -> liftIO randomIO >>= pure . N | otherwise -> liftIO (randomRIO (0, d)) >>= pure . N Chp a -> do N d <- eval a pure (N $ fromIntegral $ floor d) Neg a -> do N d <- eval a pure . N $ negate d Not a -> do N d <- eval a pure $ if d == 0 then N 1 else N 0 Add a b -> case typeof a of Stringy -> do S l <- eval a S r <- eval b pure $ S (l <> r) Numeric -> numericOp a b (+) Sub a b -> numericOp a b (-) Div a b -> numericOp a b (/) Mul a b -> numericOp a b (*) Pow a b -> numericOp a b (**) Mod a b -> numericOp a b (%) And a b -> numericOp a b (.&.) Or a b -> numericOp a b (.|.) Xor a b -> numericOp a b xor Eq a b -> overloadedOp a b (fromBool (==)) Neq a b -> overloadedOp a b (fromBool (/=)) Gt a b -> overloadedOp a b (fromBool (>)) Gte a b -> overloadedOp a b (fromBool (>=)) Lt a b -> overloadedOp a b (fromBool (<)) Lte a b -> overloadedOp a b (fromBool (<=)) -- | Turn a comparison operator into a C-like operator, returning 1 for True -- and 0 for False. fromBool :: Ord a => (a -> a -> Bool) -> (a -> a -> Doub) fromBool op a b | a `op` b = 1 | otherwise = 0 numericOp a b op = do N l <- eval a N r <- eval b pure $ N (l `op` r) -- Helper for evaluating operators that work on Numerics and Strings overloadedOp :: Expr -> Expr -- Holy crap! A practical use of RankNTypes -> (forall a . Ord a => a -> a -> Doub) -> VMState Val overloadedOp a b op = do l <- eval a r <- eval b case (l, r) of -- This is why we need RankNTypes. The `op` is valid for any type installed -- in Ord. Without higher rank types, trying to use it here will fail -- unification because it could only be inferred as an operator on Text or Doub (S x, S y) -> pure $ N (x `op` y) (N x, N y) -> pure $ N (x `op` y) (S _, _ ) -> badType Stringy Numeric _ -> badType Numeric Stringy instance Eval Literal Val where eval (LNum d) = pure $ N d eval (LStr d) = pure $ S d
dmringo/pure-basic
src/Basic/Eval.hs
Haskell
mit
21,557
import Data.Maybe (Maybe (..)) import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit hiding (path) import Test.HUnit.Base (Assertion) -- modules we will test import M3U.Common (EXTINF (..), M3U (..), M3UEntry (..)) import M3U.Read (fromFile) import M3U.Write (toOrderedMarkdown, toYAML) -- the first couple items here are hand constructed data used for testing -- purposes. -- data EXTINF = EXTINF { seconds ∷ Int , artist ∷ String , title ∷ String } testEXTINF :: EXTINF testEXTINF = EXTINF { seconds = 60 , artist = "testartist1" , title = "testtitle1" } -- data M3U = M3U { entries ∷ [M3UEntry] } deriving (Eq) testM3U :: M3U testM3U = M3U { entries = [ M3UEntry { info = Nothing , path = "testpath1" } , M3UEntry { info = Just testEXTINF , path = "testpath2" } , M3UEntry { info = Nothing , path = "testpath3" } ] } yamlExpected :: String yamlExpected = "- path: testpath1\n- path: testpath2\n title: testtitle1\n artist: testartist1\n- path: testpath3\n" toYAMLTest :: Assertion toYAMLTest = assertEqual "toYAMLPrefix" yamlExpected (toYAML testM3U) main :: IO () main = defaultMainWithOpts [ testCase "toYAML" toYAMLTest ] mempty
siddharthist/m3u-convert
test/Main.hs
Haskell
mit
1,796
module Handler.Home where import Data.Maybe (fromJust) import Import import qualified GitHub as GH getHomeR :: Handler Html getHomeR = maybeAuthId >>= homeHandler _repository :: GH.Repository -> Widget _repository repo = $(widgetFile "_repository") homeHandler :: Maybe UserId -> Handler Html homeHandler Nothing = defaultLayout $ do setTitle "ScrumBut | Sign in" $(widgetFile "sign_in") homeHandler (Just userId) = do user <- runDB $ get userId let token = userToken $ fromJust user client <- GH.newClient token userRepos <- GH.fetchRepos client orgs <- GH.fetchOrgs client orgRepos <- concat <$> mapM (GH.fetchOrgRepos client) orgs defaultLayout $ do setTitle "ScrumBut | Repositories" $(widgetFile "repositories")
jspahrsummers/ScrumBut
Handler/Home.hs
Haskell
mit
790
module Antiqua.Graphics.Colors( module Antiqua.Graphics.Colors, Color, rgb, dim, mult, mix ) where import Antiqua.Graphics.Color black :: Color black = rgb 0 0 0 white :: Color white = rgb 255 255 255 grey :: Color grey = rgb 128 128 128 darkGrey :: Color darkGrey = rgb 64 64 64 brown :: Color brown = rgb 150 75 0 red :: Color red = rgb 255 0 0 darkRed :: Color darkRed = rgb 128 0 0 green :: Color green = rgb 0 255 0 darkGreen :: Color darkGreen = rgb 0 128 0 blue :: Color blue = rgb 0 0 255 darkBlue :: Color darkBlue = rgb 0 0 128 yellow :: Color yellow = rgb 255 255 0
olive/antiqua-prime
src/Antiqua/Graphics/Colors.hs
Haskell
mit
614
module Sing2 where fstString :: [Char] -> [Char] fstString x = x ++ " river" sndString :: [Char] -> [Char] sndString x = x ++ " than a mile" sing = if (x > y) then fstString x else sndString y where x = "Moon" y = "wider"
Numberartificial/workflow
haskell-first-principles/haskell-from-first-principles-master/05/05.08.08-fix-it-2.hs
Haskell
mit
241
{- Advent of Code: Day 1 Santa is trying to deliver presents in a large apartment building, but he can't find the right floor. The directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors. For example: (()) and ()() both result in floor 0. ((( and (()(()( both result in floor 3. ))((((( also results in floor 3. ()) and ))( both result in floor -1 (the first basement level). ))) and )())()) both result in floor -3. To what floor do the instructions take Santa? -} -- Part one findFloor :: [Char] -> Int findFloor directions = parseElements directions 0 where parseElements :: [Char] -> Int -> Int parseElements [] floor = floor parseElements (x:xs) floor | x == '(' = parseElements xs (floor+1) | x == ')' = parseElements xs (floor-1) | otherwise = error ("Invalid element: " ++ (show x)) {- - --- Part Two --- Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on. For example: ) causes him to enter the basement at character position 1. ()()) causes him to enter the basement at character position 5. What is the position of the character that causes Santa to first enter the basement? -} findBasementEntryPosition :: [Char] -> Int findBasementEntryPosition directions = findPosition directions 0 1 where findPosition :: [Char] -> Int -> Int -> Int findPosition [] floor position = error ("Santa never enters the basement") findPosition (x:xs) floor position | x == ')' && floor == 0 = position | x == '(' = findPosition xs (floor+1) (position+1) | x == ')' = findPosition xs (floor-1) (position+1) | otherwise = error ("Invalid element: " ++ (show x))
samueljackson92/advent-of-code
day1/day1.hs
Haskell
mit
2,109
module Control.Process( idP, (<.>), next, recursively, module Control.Process.Show, module Control.Process.Update, module Control.Process.Class ) where import Control.Process.Show import Control.Process.Update import Control.Process.Class import Types.Synonyms import Types.TextlunkyCommand import Types.GameState import Control.Monad.Trans.Free -- NB. if we change the type to: -- type Process state cmd r = -- FreeF cmd r () (FreeT cmd (state) r) -> StateT state IO r -- then the current Process is: -- Process GameState TextlunkyCommand () -- which is interesting because we might be able to form something new from it, -- but this is on the backburner because I don't really care that much. -- Just think it's interesting for discussion later. -- process Id idP :: Process idP = const $ return () infixr 9 <.> (<.>) :: Process -> Process -> Process pA <.> pB = \cmd -> pA cmd >> pB cmd recursively :: (Textlunky () -> Global GameState ()) -> Process -> UnwrappedCommand -> Global GameState () recursively f g cmd = do g cmd f (next cmd) next :: UnwrappedCommand -> Textlunky () next (Pure _) = return () next (Free End) = return () next (Free (Move d x)) = x next (Free (MoveTo e x)) = x next (Free (Pickup _ x)) = x next (Free (DropItem x)) = x next (Free (Jump _ x)) = x next (Free (Attack _ x)) = x next (Free (ShootD _ x)) = x next (Free (ShootE _ x)) = x next (Free (ShootSelf x)) = x next (Free (Throw _ x)) = x next (Free (Rope x)) = x next (Free (Bomb _ x)) = x next (Free (OpenGoldChest x)) = x next (Free (OpenChest x)) = x next (Free (ExitLevel x)) = x next (Free (DropDown x)) = x next (Free (Look _ x)) = x next (Free (Walls x)) = x next (Free (ShowEntities x)) = x next (Free (ShowFull x)) = x next (Free (ShowMe x)) = x next (Free (YOLO x)) = x
5outh/textlunky
src/Control/Process.hs
Haskell
mit
1,980
----------------------------------------------------------------------- -- -- Haskell: The Craft of Functional Programming, 3e -- Simon Thompson -- (c) Addison-Wesley, 1996-2011. -- -- PicturesSVG -- -- The Pictures functionality implemented by translation -- SVG (Scalable Vector Graphics) -- -- These Pictures could be rendered by conversion to ASCII art, -- but instead are rendered into SVG, which can then be viewed in -- a browser: google chrome does a good job. -- ----------------------------------------------------------------------- module PicturesSVG where import System.IO import Test.QuickCheck import Control.Monad (liftM, liftM2) -- Pictures represened by a type of trees, so this is a deep -- embedding. data Picture = Img Image | Above Picture Picture | Beside Picture Picture | Over Picture Picture | FlipH Picture | FlipV Picture | Invert Picture | Empty deriving (Eq,Show) -- Coordinates are pairs (x,y) of integers -- -- o------> x axis -- | -- | -- V -- y axis type Point = (Int,Int) -- The Point in an Image gives the dimensions of the image in pixels. data Image = Image Name Point deriving (Eq,Show) data Name = Name String deriving (Eq,Show) -- -- The functions over Pictures -- above, beside, over :: Picture -> Picture -> Picture above x Empty = x above Empty x = x above x y = Above x y beside Empty x = x beside x Empty = x beside x y = Beside x y over x Empty = x over Empty x = x over x y = Over x y -- flipH is flip in a horizontal axis -- flipV is flip in a vertical axis -- negative negates each pixel -- The definitions of flipH, flipV, negative push the -- constructors through the binary operations to the images -- at the leaves. -- Original implementation incorrect: it pushed the -- flipH and flipV through all constructors ... -- Now it distributes appropriately over Above, Beside and Over. flipH, flipV, invert :: Picture -> Picture flipH (Above pic1 pic2) = (flipH pic2) `Above` (flipH pic1) flipH (Beside pic1 pic2) = (flipH pic1) `Beside` (flipH pic2) flipH (Over pic1 pic2) = (flipH pic1) `Over` (flipH pic2) flipH pic = FlipH pic flipV (Above pic1 pic2) = (flipV pic1) `Above` (flipV pic2) flipV (Beside pic1 pic2) = (flipV pic2) `Beside` (flipV pic1) flipV (Over pic1 pic2) = (flipV pic1) `Over` (flipV pic2) flipV pic = FlipV pic invert = Invert invertColour = Invert -- Convert an Image to a Picture img :: Image -> Picture img = Img -- -- Library functions -- -- Dimensions of pictures width,height :: Picture -> Int width (Img (Image _ (x,_))) = x width (Above pic1 pic2) = max (width pic1) (width pic2) width (Beside pic1 pic2) = (width pic1) + (width pic2) width (Over pic1 pic2) = max (width pic1) (width pic2) width (FlipH pic) = width pic width (FlipV pic) = width pic width (Invert pic) = width pic height (Img (Image _ (x,y))) = y height (Above pic1 pic2) = (height pic1) + (height pic2) height (Beside pic1 pic2) = max (height pic1) (height pic2) height (Over pic1 pic2) = max (height pic1) (height pic2) height (FlipH pic) = height pic height (FlipV pic) = height pic height (Invert pic) = height pic -- -- Converting pictures to a list of basic images. -- -- A Filter represents which of the actions of flipH, flipV -- and invert is to be applied to an image in forming a -- Basic picture. data Filter = Filter {fH, fV, neg :: Bool} deriving (Show) newFilter = Filter False False False data Basic = Basic Image Point Filter deriving (Show) -- Flatten a picture into a list of Basic pictures. -- The Point argument gives the origin for the coversion of the -- argument. flatten :: Point -> Picture -> [Basic] flatten (x,y) (Img image) = [Basic image (x,y) newFilter] flatten (x,y) (Above pic1 pic2) = flatten (x,y) pic1 ++ flatten (x, y + height pic1) pic2 flatten (x,y) (Beside pic1 pic2) = flatten (x,y) pic1 ++ flatten (x + width pic1 , y) pic2 flatten (x,y) (Over pic1 pic2) = flatten (x,y) pic2 ++ flatten (x,y) pic1 flatten (x,y) (FlipH pic) = map flipFH $ flatten (x,y) pic flatten (x,y) (FlipV pic) = map flipFV $ flatten (x,y) pic flatten (x,y) (Invert pic) = map flipNeg $ flatten (x,y) pic flatten (x,y) Empty = [] -- flip one of the flags for transforms / filter flipFH (Basic img (x,y) f@(Filter {fH=boo})) = Basic img (x,y) f{fH = not boo} flipFV (Basic img (x,y) f@(Filter {fV=boo})) = Basic img (x,y) f{fV = not boo} flipNeg (Basic img (x,y) f@(Filter {neg=boo})) = Basic img (x,y) f{neg = not boo} -- -- Convert a Basic picture to an SVG image, represented by a String. -- convert :: Basic -> String convert (Basic (Image (Name name) (width, height)) (x,y) (Filter fH fV neg)) = "\n <image x=\"" ++ show x ++ "\" y=\"" ++ show y ++ "\" width=\"" ++ show width ++ "\" height=\"" ++ show height ++ "\" xlink:href=\"" ++ name ++ "\"" ++ flipPart ++ negPart ++ "/>\n" where flipPart = if fH && not fV then " transform=\"translate(0," ++ show (2*y + height) ++ ") scale(1,-1)\" " else if fV && not fH then " transform=\"translate(" ++ show (2*x + width) ++ ",0) scale(-1,1)\" " else if fV && fH then " transform=\"translate(" ++ show (2*x + width) ++ "," ++ show (2*y + height) ++ ") scale(-1,-1)\" " else "" negPart = if neg then " filter=\"url(#negative)\"" else "" -- Outputting a picture. -- The effect of this is to write the SVG code into a file -- whose path is hardwired into the code. Could easily modify so -- that it is an argument of the call, and indeed could also call -- the browser to update on output. render :: Picture -> IO () render pic = let picList = flatten (0,0) pic svgString = concat (map convert picList) newFile = preamble ++ svgString ++ postamble in do outh <- openFile "svgOut.xml" WriteMode hPutStrLn outh newFile hClose outh -- Preamble and postamble: boilerplate XML code. preamble = "<svg width=\"100%\" height=\"100%\" version=\"1.1\"\n" ++ "xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n" ++ "<filter id=\"negative\">\n" ++ "<feColorMatrix type=\"matrix\"\n"++ "values=\"-1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 1 1 1 0 0\" />\n" ++ "</filter>\n" postamble = "\n</svg>\n" -- -- Examples -- whiteSquare = Img $ Image (Name "images/white.jpg") (50,50) blackSquare = Img $ Image (Name "images/black.jpg") (50,50) king = Img $ Image (Name "images/king.png") (50,50) queen = Img $ Image (Name "images/queen.png") (50,50) bishop = Img $ Image (Name "images/bishop.png") (50,50) knight = Img $ Image (Name "images/knight.png") (50,50) rook = Img $ Image (Name "images/rook.png") (50,50) pawn = Img $ Image (Name "images/pawn.png") (50,50) clear = Img $ Image (Name "images/clear.png") (50,50) horse = Img $ Image (Name "images/blk_horse_head.jpg") (150, 200) repeatH n img | n > 0 = foldl1 beside (replicate n img) | otherwise = error "The first argument to repeatH should be greater than 1" repeatV n img | n > 0 = foldl1 above (replicate n img) | otherwise = error "The first argument to repeatV should be greater than 1"
PavelClaudiuStefan/FMI
An_3_Semestru_1/ProgramareDeclarativa/Laboratoare/Laborator2/PicturesSVG.hs
Haskell
cc0-1.0
7,699
squaresList n = [i ^ 2 | i <- [1..n]] pairsList x y = [(a, b) | a <- [1..x], b <- [10..y]] -- nested two loop concat xss = [x | xs <- xss, x <- xs] -- loop with guard evens n = [x | x <- [1..n], even x] factors n = [x | x <- [1..n], n `mod` x == 0] prime n = factors n == [1, n] primes n = [x | x <- [1..n], prime x] pairs a b = [(x, y) | x <- a, y <- b] pairsOfAdj xs = zip xs (tail xs) qsort :: Ord a => [a] -> [a] qsort [] = [] qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger where smaller = [a | a <- xs, a <= x] larger = [b | b <- xs, b > x] isSorted :: Ord a => [a] -> Bool isSorted xs = and [x <= y | (x, y) <- pairsOfAdj xs] positions :: Eq a => a -> [a] -> [Int] positions x xs = [i | (i, n) <- zip [1..n] xs, n == x] where n = length xs --lowers xs = length [x | x <- xs, isLower x] pyths n = [(x, y, z) | x <- [1..n], y <- [1..n], z <- [1..n], x ^ 2 + y ^ 2 == z ^ 2] -- no is perfect if sum of its factor = number itself perfects n = [x | x <- [1..n], isPerfect x] where isPerfect a = sum (init(factors a)) == a divides :: Int -> Int -> Bool divides n a = n `mod` a == 0 divisors :: Int -> [Int] divisors n = [x | x <- [1..n], divides n x] riffle a b = Main.concat [[x, y] | (x, y) <- zip a b]
dongarerahul/edx-haskell
chapter4.hs
Haskell
apache-2.0
1,242
ans :: [Int] -> [String] ans (x:y:xs) = replicate x $ replicate y '#' printRec :: [[String]] -> IO() printRec [] = return () printRec (s:sx) = do mapM_ putStrLn s putStrLn "" printRec sx main = do c <- getContents let t = map (map read) $ map words $ lines c :: [[Int]] i = takeWhile (/= [0,0]) t o = map ans i printRec o
a143753/AOJ
ITP1_5_A.hs
Haskell
apache-2.0
352
{-# OPTIONS_GHC -fno-warn-orphans #-} {- BoardTest.hs Copyright (c) 2014 by Sebastien Soudan. Apache License Version 2.0, January 2004 -} module BoardTest where import Board import Data.Maybe (isNothing) import Test.QuickCheck (Arbitrary (..)) import Test.QuickCheck.Gen (choose, elements) prop_evalBoard :: Bool prop_evalBoard = evalBoard initialBoard == 0 prop_elementAt :: Bool prop_elementAt = elementAt (Pos (0,0)) initialBoard == Just (Piece Rook Black) prop_elementAt2 :: Bool prop_elementAt2 = isNothing $ elementAt (Pos (4,4)) initialBoard prop_elementAt3 :: Bool prop_elementAt3 = elementAt (Pos (7,7)) initialBoard == Just (Piece Rook White) instance Arbitrary PieceType where arbitrary = elements [Pawn, Rook, Queen, King, Bishop, Knight] instance Arbitrary PieceColor where arbitrary = elements [Black, White] instance Arbitrary Pos where arbitrary = do x <- choose (0,7) y <- choose (0,7) return $ Pos (x, y) prop_valuePiece :: PieceType -> Bool prop_valuePiece ptype = valuePiece (Piece ptype Black) == valuePiece (Piece ptype White) prop_deleteSquare :: Pos -> Bool prop_deleteSquare pos = isNothing $ elementAt pos updatedBoard where updatedBoard = deleteSquare pos initialBoard prop_movePieceOnBoard :: Pos -> Pos -> Bool prop_movePieceOnBoard origin destination = let originalBoard = initialBoard movedBoard = movePieceOnBoard originalBoard origin destination in elementAt destination movedBoard == elementAt origin originalBoard && (isNothing (elementAt origin movedBoard) || origin == destination)
ssoudan/hsChess
test/BoardTest.hs
Haskell
apache-2.0
1,746
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- {-# OPTIONS_GHC -fno-warn-unused-matches -fno-warn-incomplete-patterns #-} {-# LANGUAGE CPP, OverloadedStrings #-} module Server where import Control.Exception import Data.HashMap.Strict as Map import Network.Socket import System.IO import Thrift import Thrift.Server import ThriftTest import ThriftTest_Iface import ThriftTest_Types data TestHandler = TestHandler instance ThriftTest_Iface TestHandler where testVoid a = return () testString a (Just s) = do print s; return s testByte a (Just x) = do print x; return x testI32 a (Just x) = do print x; return x testI64 a (Just x) = do print x; return x testDouble a (Just x) = do print x; return x testFloat a (Just x) = do print x; return x testStruct a (Just x) = do print x; return x testNest a (Just x) = do print x; return x testMap a (Just x) = do print x; return x testSet a (Just x) = do print x; return x testList a (Just x) = do print x; return x testEnum a (Just x) = do print x; return x testTypedef a (Just x) = do print x; return x testMapMap a (Just x) = return (Map.fromList [(1,Map.fromList [(2,2)])]) testInsanity a (Just x) = return (Map.fromList [(1,Map.fromList [(ONE,x)])]) testMulti a a1 a2 a3 a4 a5 a6 = return (Xtruct Nothing Nothing Nothing Nothing) testException a c = throw (Xception (Just 1) (Just "bya")) testMultiException a c1 c2 = throw (Xception (Just 1) (Just "bya")) testOneway a (Just i) = print i main :: IO () main = catch (runThreadedServer (accepter p) TestHandler process 9090) (\(TransportExn s t) -> print s) where accepter p s = do (s', _) <- accept s h <- socketToHandle s' ReadWriteMode return (p h, p h)
facebook/fbthrift
thrift/test/hs/Server.hs
Haskell
apache-2.0
2,531
-- | -- Module : Statistics.Matrix.Mutable -- Copyright : (c) 2014 Bryan O'Sullivan -- License : BSD3 -- -- Basic mutable matrix operations. module Statistics.Matrix.Mutable ( MMatrix(..) , MVector , replicate , thaw , bounds , unsafeFreeze , unsafeRead , unsafeWrite , unsafeModify , immutably , unsafeBounds ) where import Control.Applicative ((<$>)) import Control.DeepSeq (NFData(..)) import Control.Monad.ST (ST) import Statistics.Matrix.Types (Matrix(..), MMatrix(..), MVector) import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as M import Prelude hiding (replicate) replicate :: Int -> Int -> Double -> ST s (MMatrix s) replicate r c k = MMatrix r c 0 <$> M.replicate (r*c) k thaw :: Matrix -> ST s (MMatrix s) thaw (Matrix r c e v) = MMatrix r c e <$> U.thaw v unsafeFreeze :: MMatrix s -> ST s Matrix unsafeFreeze (MMatrix r c e mv) = Matrix r c e <$> U.unsafeFreeze mv unsafeRead :: MMatrix s -> Int -> Int -> ST s Double unsafeRead mat r c = unsafeBounds mat r c M.unsafeRead {-# INLINE unsafeRead #-} unsafeWrite :: MMatrix s -> Int -> Int -> Double -> ST s () unsafeWrite mat row col k = unsafeBounds mat row col $ \v i -> M.unsafeWrite v i k {-# INLINE unsafeWrite #-} unsafeModify :: MMatrix s -> Int -> Int -> (Double -> Double) -> ST s () unsafeModify mat row col f = unsafeBounds mat row col $ \v i -> do k <- M.unsafeRead v i M.unsafeWrite v i (f k) {-# INLINE unsafeModify #-} -- | Given row and column numbers, calculate the offset into the flat -- row-major vector. bounds :: MMatrix s -> Int -> Int -> (MVector s -> Int -> r) -> r bounds (MMatrix rs cs _ mv) r c k | r < 0 || r >= rs = error "row out of bounds" | c < 0 || c >= cs = error "column out of bounds" | otherwise = k mv $! r * cs + c {-# INLINE bounds #-} -- | Given row and column numbers, calculate the offset into the flat -- row-major vector, without checking. unsafeBounds :: MMatrix s -> Int -> Int -> (MVector s -> Int -> r) -> r unsafeBounds (MMatrix _ cs _ mv) r c k = k mv $! r * cs + c {-# INLINE unsafeBounds #-} immutably :: NFData a => MMatrix s -> (Matrix -> a) -> ST s a immutably mmat f = do k <- f <$> unsafeFreeze mmat rnf k `seq` return k {-# INLINE immutably #-}
fpco/statistics
Statistics/Matrix/Mutable.hs
Haskell
bsd-2-clause
2,298