code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
main :: IO () main = readLn >>= print . solve solve :: Integer -> Integer solve p = sum [ n | n <- [1..p], isPalindromeNr n, isPalindromeBin (toBinary n) ] -- Test whether a given number is palindromic isPalindromeNr :: Integer -> Bool isPalindromeNr n | n `mod` 10 == 0 = False isPalindromeNr n | otherwise = l == reverse l where l = show n -- Test wether a given list of binary digits represents a binary palindrome isPalindromeBin :: [Integer] -> Bool isPalindromeBin n | head n == 0 = False isPalindromeBin n | otherwise = n == reverse n -- Convert a decimal number to a list of binary digits. toBinary :: Integer -> [Integer] toBinary 0 = [0] toBinary n = reverse (helper n) where helper 0 = [] helper x = let (q,r) = x `divMod` 2 in r : helper q
NorfairKing/project-euler
036/haskell/solution.hs
gpl-2.0
780
2
10
178
315
149
166
16
2
-- memoization import qualified Data.Vector as V c :: Int -> Int -> Integer c n m = (cn n) !! m where cn 0 = 1:(repeat 0) cn n = let s = (cn $ n - 1) in zipWith (+) (0:s) s getComp :: Int -> Int -> V.Vector (V.Vector Integer) getComp n m = c where c = V.fromList [ V.fromList [ f i j | j <- [0..min i m]] | i <- [0..n]] where f x y | y == 0 = 1 | x == y = 1 | otherwise = c V.! (x-1) V.! y + c V.! (x-1) V.! (y-1) comp n m = getComp 100 100 V.! n V.! m
FiveEye/playground
lang/combinations.hs
gpl-2.0
507
11
12
173
354
168
186
12
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} module PetaVision.Data.KMeans (ClusterCenter ,Shape(..) ,KMeansModel(..) ,kmeans ,computeSoftAssignment) where import Control.Arrow ((&&&)) import Control.Monad as M import Data.Binary import Data.List as L import Data.Vector as V import Data.Vector.Unboxed as VU import GHC.Generics import PetaVision.Utility.Parallel import System.Random data Shape = Shape {rows :: Int ,cols :: Int ,channels :: Int ,stride :: Int} deriving (Show,Generic) instance Binary Shape where put (Shape r c ch st) = do put r put c put ch put st get = do r <- get c <- get ch <- get st <- get return $! Shape r c ch st type ClusterCenter = V.Vector (VU.Vector Double) data KMeansModel = KMeansModel {shape :: Shape ,clusterSize :: V.Vector Int ,center :: ClusterCenter } instance Binary KMeansModel where put (KMeansModel sh cs c) = do put sh put . V.toList $ cs put . L.map VU.toList . V.toList $ c get = do sh <- get cs <- get xs <- get return $! KMeansModel sh (V.fromList cs) . V.fromList . L.map VU.fromList $ xs type Assignment = V.Vector Int randomClusterCenterPP :: [VU.Vector Double] -> Int -> [V.Vector (VU.Vector Double)] -> IO [VU.Vector Double] randomClusterCenterPP !centers !0 _ = return centers randomClusterCenterPP [] !n xs = do randomNumber <- M.replicateM (L.length xs) . V.replicateM (V.length . L.head $ xs) . randomRIO $ ((0,1) :: (Double,Double)) let ys = V.concat $ parZipWith rdeepseq (\x' r' -> V.map fst . V.filter (\(_,p') -> p' > 0.5) $ V.zip x' r') xs randomNumber randomClusterCenterPP [VU.map (/ fromIntegral (V.length ys)) . V.foldl1' (VU.zipWith (+)) $ ys] (n - 1) xs randomClusterCenterPP !centers !n xs = do randomNumber <- M.replicateM (L.length xs) . V.replicateM (V.length . L.head $ xs) . randomRIO $ ((0,1) :: (Double,Double)) let ys = parMap rdeepseq (\vec' -> V.map (\x' -> L.minimum $ L.map (distFunc x') centers) vec') xs zs = parMap rdeepseq V.sum ys s = L.sum zs as = V.concat $ parZipWith3 rdeepseq (\xs' ys' rs' -> V.map fst . V.filter snd $ V.zipWith3 (\x' y' r' -> if y' / s > r' then (x',True) else (x',False)) xs' ys' rs') xs ys randomNumber center = VU.map (/ fromIntegral (V.length as)) . V.foldl1' (VU.zipWith (+)) $ as if V.length as == 0 then randomClusterCenterPP centers n xs else randomClusterCenterPP (center : centers) (n - 1) xs {-# INLINE computeAssignmentP #-} computeAssignmentP :: ClusterCenter -> [V.Vector (VU.Vector Double)] -> [Assignment] computeAssignmentP = parMap rdeepseq . computeAssignment {-# INLINE computeMeanP #-} computeMeanP :: Int -> Int -> [Assignment] -> [V.Vector (VU.Vector Double)] -> [V.Vector (VU.Vector Double)] computeMeanP k nf = parZipWith rdeepseq (computeMean k nf) {-# INLINE computeDistortionP #-} computeDistortionP :: ClusterCenter -> [Assignment] -> [V.Vector (VU.Vector Double)] -> Double computeDistortionP clusterCenter assignments = L.sum . parZipWith rdeepseq (computeDistortion clusterCenter) assignments {-# INLINE meanList2ClusterCenter #-} meanList2ClusterCenter :: [V.Vector (VU.Vector Double)] -> [V.Vector (VU.Vector Double)] -> IO ClusterCenter meanList2ClusterCenter vecs xss = M.liftM V.fromList . randomClusterCenterPP zs (k - L.length zs) $ xss where xs = L.map (V.map (\x -> if VU.any isNaN x then (undefined,0) else (x,1))) vecs ys = L.foldl' (V.zipWith (\(s,count) (vec,n) -> if n == 0 then (s,count) else (VU.zipWith (+) s vec,count + 1))) (V.replicate k (VU.replicate nf 0,(0 :: Double))) $ xs zs = V.toList . V.map (\(s,count) -> VU.map (/ count) s) . V.filter (\(_,count) -> count /= 0) $ ys nf = VU.length . V.head . L.head $ vecs k = V.length . L.head $ vecs computeClusterSize :: Int -> [Assignment] -> V.Vector Int computeClusterSize k xs = V.accumulate (+) (V.replicate k 0) $ V.zip vec (V.replicate (V.length vec) 1) where vec = V.concat xs kmeans :: ParallelParams -> Int -> Shape -> [VU.Vector Double] -> IO KMeansModel kmeans parallelParams k sh xs = do randomCenter <- randomClusterCenterPP [] k ys go (V.fromListN k randomCenter) (fromIntegral (maxBound :: Int)) $ ys where nf = VU.length . L.head $ xs ys = L.map V.fromList . splitList (div (L.length xs) (numThread parallelParams)) $ xs go !center lastDistortion zs = do let assignment = computeAssignmentP center zs distortion = computeDistortionP center assignment zs print distortion if distortion >= lastDistortion then return $! KMeansModel sh (computeClusterSize k assignment) center else do newCenter <- meanList2ClusterCenter (computeMeanP k nf assignment zs) zs go newCenter distortion zs computeSoftAssignment :: ParallelParams -> ClusterCenter -> [VU.Vector Double] -> [VU.Vector Double] computeSoftAssignment parallelParams center = parMapChunk parallelParams rdeepseq (\x -> let dist = V.map (distFunc x) center mean = V.sum dist / fromIntegral (V.length center) in V.convert . V.map (\y -> max 0 (mean - y)) $ dist) {-# INLINE computeAssignment #-} computeAssignment :: ClusterCenter -> V.Vector (VU.Vector Double) -> Assignment computeAssignment cluster = V.map (\x -> V.minIndex . V.map (distFunc x) $ cluster) {-# INLINE computeMean #-} computeMean :: Int -> Int -> Assignment -> V.Vector (VU.Vector Double) -> V.Vector (VU.Vector Double) computeMean k nf assignmet = V.map (\(s,count) -> VU.map (/ count) s) . V.accumulate (\(s,count) vec -> (VU.zipWith (+) s vec,count + 1)) (V.replicate k (VU.replicate nf 0,0)) . V.zip assignmet {-# INLINE computeDistortion #-} computeDistortion :: ClusterCenter -> Assignment -> V.Vector (VU.Vector Double) -> Double computeDistortion clusterCenter assignments = V.sum . V.zipWith (\assignment vec -> distFunc vec (clusterCenter V.! assignment)) assignments {-# INLINE distFunc #-} distFunc :: VU.Vector Double -> VU.Vector Double -> Double distFunc vec1 vec2 = VU.sum $ VU.zipWith (\a b -> (a - b) ^ (2 :: Int)) vec1 vec2 {-# INLINE splitList #-} splitList :: Int -> [a] -> [[a]] splitList _ [] = [] splitList n ys = as : splitList n bs where (as,bs) = L.splitAt n ys
XinhuaZhang/PetaVisionHaskell
PetaVision/Data/KMeans.hs
gpl-3.0
8,476
0
20
3,445
2,639
1,367
1,272
257
3
module Common ( cleanEnvironment, cleanEnvironmentP, testParameters ) where import Control.Monad ( when ) import Data.ByteString.Lazy.Char8 ( pack ) import Ltc.Store ( Store(..) ) import Ltc.Store.Simple ( Simple, OpenParameters(..) ) import Network.BSD ( getHostName ) import System.Directory ( doesDirectoryExist, removeDirectoryRecursive , doesFileExist, removeFile ) import System.IO.Unsafe ( unsafePerformIO ) import Test.HUnit import Test.QuickCheck.Monadic as QCM ---------------------- -- Cleanup ---------------------- -- | Test an assertion in a clean environment and cleanup afterwards. cleanEnvironment :: [FilePath] -> Assertion -> Assertion cleanEnvironment files ass = do mapM_ rmrf files ass cleanEnvironmentP :: [FilePath] -> PropertyM IO a -> PropertyM IO a cleanEnvironmentP files prop = do run $ mapM_ rmrf files prop ---------------------- -- Helpers ---------------------- -- | Remove a file or a directory recursively. rmrf :: FilePath -> IO () rmrf fp = do dde <- doesDirectoryExist fp when dde $ removeDirectoryRecursive fp dfe <- doesFileExist fp when dfe $ removeFile fp ---------------------- -- Repeated values ---------------------- testParameters :: OpenParameters Simple testParameters = SimpleParameters { location = "test-store" , useCompression = False , nodeName = pack hostname , createIfMissing = True , forceOpen = False } where hostname = unsafePerformIO getHostName
scvalex/ltc
test/Common.hs
gpl-3.0
1,619
0
8
400
347
195
152
34
1
{- Module : Tubes.Util Description : Optional stream processing utilities Copyright : (c) 2014-2016 Gatlin Johnson <gatlin@niltag.net> License : GPL-3 Maintainer : gatlin@niltag.net Stability : experimental -} {-# LANGUAGE RankNTypes #-} module Tubes.Util ( Tubes.Util.stop , Tubes.Util.cat , Tubes.Util.for , Tubes.Util.each , Tubes.Util.every , Tubes.Util.map , Tubes.Util.drop , Tubes.Util.take , Tubes.Util.takeWhile , Tubes.Util.filter , Tubes.Util.unyield , Tubes.Util.pass , Tubes.Util.mapM , Tubes.Util.sequence , Tubes.Util.lfold ) where import Prelude hiding (map, mapM) import Control.Monad (forever, unless, replicateM_, when) import Control.Monad.Trans import Control.Monad.Trans.Free import Control.Monad.IO.Class import Data.Foldable import Data.Monoid (Monoid, mappend, mempty) import System.IO import Data.Functor.Identity import Tubes.Core -- * Tube utilities -- | Loops over a 'Tube' and gives each 'yield'ed value to the continuation. for :: Monad m => Tube a b m r -> (b -> Tube a c m s) -> Tube a c m r for src body = liftT src >>= go where go (Pure x) = return x go (Free src') = runTubeF src' (\f -> wrap $ awaitF (\x -> liftT (f x) >>= go)) (\(v,k) -> do body v liftT k >>= go) {-# RULES "for t yield" forall t. for t yield = t #-} -- | A default tube to end a series when no further processing is required. stop :: Monad m => Tube a () m r stop = map (const ()) -- | Continuously relays any values it receives. cat :: Monad m => Tube a a m r cat = forever $ do x <- await yield x {-# RULES "cat >< t" forall t. cat >< t = t ; "t >< cat" forall t. t >< cat = t #-} each :: (Monad m, Foldable t) => t b -> Tube () b m () each as = Data.Foldable.mapM_ yield as every :: (Foldable t, Monad m) => t b -> Tube () (Maybe b) m () every xs = ((each xs) >< map Just) >> yield Nothing -- | Transforms all incoming values according to some function. map :: (Monad m) => (a -> b) -> Tube a b m r map f = for cat (\x -> yield (f x)) {-# RULES "t >< map f" forall t f . t >< map f = for t (\y -> yield (f y)) ; "map f >< t" forall t f . map f >< t = (do a <- await return (f a) ) >< t #-} -- | Refuses to yield the first @n@ values it receives. drop :: Monad m => Int -> Tube a a m r drop 0 = cat drop n = await >> Tubes.Util.drop (n-1) {-# INLINABLE Tubes.Util.drop #-} -- | Yields only values satisfying some predicate. filter :: Monad m => (a -> Bool) -> Tube a a m r filter pred = for cat (\x -> when (pred x) (yield x)) -- | Terminates the stream upon receiving a value violating the predicate takeWhile :: Monad m => (a -> Bool) -> Tube a a m () takeWhile pred = go where go = do a <- await if (pred a) then do yield a go else return () -- | Relay only the first @n@ elements of a stream. take :: Monad m => Int -> Tube a a m () take 0 = return () take n = do await >>= yield Tubes.Util.take (n-1) {-# INLINABLE Tubes.Util.take #-} -- | Taps the next value from a source, maybe. unyield :: Monad m => Tube x b m () -> m (Maybe (b, Tube x b m ())) unyield tsk = do tsk' <- runFreeT tsk case tsk' of Pure _ -> return Nothing Free tsk'' -> do let res = runTubeF tsk'' diverge (\(v, k) -> Just (v, k)) return res -- | Similar to 'unyield' but it first sends a value through the tube. pass :: Monad m => a -> Tube a b m () -> m (Maybe (b, Tube a b m ())) pass arg tb = do mtb <- runFreeT tb case mtb of Free tb' -> do let k = runTubeF tb' (\ak -> ak arg) diverge unyield k Pure _ -> return Nothing -- | Similar to 'map' except it maps a monadic function instead of a pure one. mapM :: Monad m => (a -> m b) -> Tube a b m r mapM f = for cat (\a -> do b <- lift $ f a yield b) -- | Evaluates and extracts a pure value from a monadic one. sequence :: Monad m => Tube (m a) a m r sequence = mapM id -- * Pump utilities {- | Constructs a resumable left fold. Example usage: @ summer :: Pump () Int Identity Int summer = lfold (+) (\x -> ((),x)) 0 main :: IO () main = do result <- stream const (duplicate summer) $ each [1..10] putStrLn . show . extract $ result -- "55" result2 <- stream const (duplicate result) $ each [11..20] putStrLn . show . extract $ result2 -- "210" @ -} lfold :: (x -> a -> x) -> (x -> (b, x)) -> x -> Pump b a Identity x lfold step done init = pumpT (Identity init) (\(Identity xs) x -> Identity (step xs x)) (\(Identity xs) -> Identity <$> done xs)
gatlin/tubes
Tubes/Util.hs
gpl-3.0
4,759
0
19
1,361
1,466
759
707
113
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} -- Copyright (c) 2011, Diego Souza -- 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 <ORGANIZATION> 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 TikTok.Plugins.Jenkins ( new ) where import Control.Exception as E import Control.Monad.Reader import Control.Applicative import qualified Data.ByteString as B import Data.Maybe import Data.Aeson import Network.SimpleIRC.Core import Network.SimpleIRC.Messages import Network.HTTP import TikTok.Bot import TikTok.Plugins.ByteStringHelpers import TikTok.Plugins.JsonHelpers data HudsonPlugin = HudsonPlugin { endpoint :: String } type Endpoint = String type JobName = String data Status = Bad | Good deriving (Ord,Eq) newtype LJenkinsStatus = LJenkinsStatus { allStatus :: [JenkinsStatus] } data JenkinsStatus = JenkinsStatus { jobName :: JobName , jobStatus :: Status , jobUrl :: String } new :: Endpoint -> Plugin new e = Plugin (eventHandler (HudsonPlugin e)) "hudson" sameStatus :: JenkinsStatus -> JenkinsStatus -> Bool sameStatus j0 j1 = (jobStatus j0) == (jobStatus j1) eventHandler :: HudsonPlugin -> Event -> Bot () eventHandler hp (EvtPrivmsg m) = do { irc <- asks ircConn ; dest <- liftIO $ getDest irc m ; case (mMsg m) of "!hudson url" -> sayPrivmsg dest (tobs $ endpoint hp) "!hudson status" -> do { hstatus <- liftIO $ getStatus hp ; mapM_ (sayPrivmsg dest . tobs . show) hstatus ; sayPrivmsg dest "-- *** --" } mjob -> withJob mjob $ \j -> do { mstatus <- liftIO $ getJobStatus hp (frombs j) ; case mstatus of Nothing -> return () Just st -> sayPrivmsg dest (tobs $ show st) } } eventHandler _ _ = return () ignoreErrors :: (MonadPlus m) => IO (m a) -> IO (m a) ignoreErrors m = E.catch m (\(SomeException _) -> return mzero) getJobStatus :: HudsonPlugin -> JobName -> IO (Maybe JenkinsStatus) getJobStatus hp j = ignoreErrors (simpleHTTP (getRequest apiUrl) >>= fmap readJSON . getResponseBody) where apiUrl = (endpoint hp) ++ "/job/" ++ j ++ "/api/json" getStatus :: HudsonPlugin -> IO [JenkinsStatus] getStatus hp = ignoreErrors $ do { rsp <- simpleHTTP (getRequest apiUrl) ; jsonVal <- fmap readJSON (getResponseBody rsp) ; return $ head (maybeToList (fmap allStatus jsonVal)) } where apiUrl = (endpoint hp) ++ "/api/json" withJob :: B.ByteString -> (B.ByteString -> Bot ()) -> Bot () withJob raw f | "!hudson status " `B.isPrefixOf` raw = f (B.drop 15 raw) | otherwise = return () instance FromJSON Status where parseJSON (String "blue") = return Good parseJSON (String _) = return Bad parseJSON _ = mzero instance FromJSON JenkinsStatus where parseJSON (Object v) = JenkinsStatus <$> v .: "name" <*> v .: "color" <*> v .: "url" parseJSON _ = mzero instance FromJSON LJenkinsStatus where parseJSON (Object v) = LJenkinsStatus <$> v .: "jobs" parseJSON _ = mzero instance Show JenkinsStatus where show h = "-- " ++ jobName h ++ ": " ++ show (jobStatus h) instance Show Status where show Bad = "*bad*" show Good = "_good_"
dgvncsz0f/tiktok
src/main/TikTok/Plugins/Jenkins.hs
gpl-3.0
5,091
0
20
1,432
1,073
567
506
77
4
module Handler.CommonSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "robots.txt" $ do it "gives a 200" $ do get RobotsR statusIs 200 it "has correct User-agent" $ do get RobotsR bodyContains "User-agent: *" describe "favicon.ico" $ do it "gives a 200" $ do get FaviconR statusIs 200 -- vim:set expandtab:
tmcl/katalogo
backend/sqlite/test/Handler/CommonSpec.hs
gpl-3.0
442
0
14
162
115
50
65
15
1
{-# LANGUAGE CPP #-} {-| hledger-web - a hledger add-on providing a web interface. Copyright (c) 2007-2011 Simon Michael <simon@joyful.com> Released under GPL version 3 or later. -} module Main where -- import Control.Concurrent (forkIO, threadDelay) import Data.Maybe import Data.Text(pack) import Network.Wai.Handler.Warp (run) #if PRODUCTION #else import Network.Wai.Middleware.Debug (debug) #endif import System.Console.GetOpt import System.Exit (exitFailure) import System.IO.Storage (withStore, putValue) import Text.Printf import Yesod.Helpers.Static import Hledger.Cli import Hledger.Cli.Tests (runTestsOrExit) import Hledger.Data import Prelude hiding (putStr, putStrLn) import Hledger.Utils.UTF8 (putStr, putStrLn) import App import AppRun (withApp) import EmbeddedFiles (createFilesIfMissing) progname_web = progname_cli ++ "-web" options_web :: [OptDescr Opt] options_web = [ Option "" ["base-url"] (ReqArg BaseUrl "URL") "use this base url (default http://localhost:PORT)" ,Option "" ["port"] (ReqArg Port "N") "serve on tcp port N (default 5000)" ] usage_preamble_web = "Usage: hledger-web [OPTIONS] [PATTERNS]\n" ++ "\n" ++ "Reads your ~/.journal file, or another specified by $LEDGER or -f, and\n" ++ "starts a web ui server. Also attempts to start a web browser (unless --debug).\n" ++ "\n" usage_options_web = usageInfo "hledger-web options:" options_web ++ "\n" usage_web = concat [ usage_preamble_web ,usage_options_web ,usage_options_cli ,usage_postscript_cli ] main :: IO () main = do (opts, args) <- parseArgumentsWith $ options_cli++options_web run opts args where run opts args | Help `elem` opts = putStr usage_web | Version `elem` opts = putStrLn $ progversionstr progname_web | BinaryFilename `elem` opts = putStrLn $ binaryfilename progname_web | otherwise = withJournalDo opts args "web" web -- | The web command. web :: [Opt] -> [String] -> Journal -> IO () web opts args j = do created <- createFilesIfMissing if created then do putStrLn $ "Installing support files in "++datadir++" - done, please run again." exitFailure else do putStrLn $ "Running self-tests..." runTestsOrExit opts args putStrLn $ "Using support files in "++datadir let host = defhost port = fromMaybe defport $ portFromOpts opts baseurl = fromMaybe (printf "http://%s:%d" host port) $ baseUrlFromOpts opts -- unless (Debug `elem` opts) $ forkIO (browser baseurl) >> return () server baseurl port opts args j -- browser :: String -> IO () -- browser baseurl = do -- threadDelay $ fromIntegral browserstartdelay -- putStrLn "Attempting to start a web browser" -- openBrowserOn baseurl >> return () server :: String -> Int -> [Opt] -> [String] -> Journal -> IO () server baseurl port opts args j = do printf "Starting http server on port %d with base url %s\n" port baseurl let a = App{getStatic=static staticdir ,appRoot=pack baseurl ,appOpts=opts ,appArgs=args ,appJournal=j } withStore "hledger" $ do putValue "hledger" "journal" j #if PRODUCTION withApp a (run port) #else withApp a (run port . debug) #endif
trygvis/hledger
hledger-web/hledger-web.hs
gpl-3.0
3,368
0
16
783
721
387
334
71
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.File.Projects.Locations.Instances.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates an instance. When creating from a backup, the capacity of the -- new instance needs to be equal to or larger than the capacity of the -- backup (and also equal to or larger than the minimum capacity of the -- tier). -- -- /See:/ <https://cloud.google.com/filestore/ Cloud Filestore API Reference> for @file.projects.locations.instances.create@. module Network.Google.Resource.File.Projects.Locations.Instances.Create ( -- * REST Resource ProjectsLocationsInstancesCreateResource -- * Creating a Request , projectsLocationsInstancesCreate , ProjectsLocationsInstancesCreate -- * Request Lenses , plicParent , plicInstanceId , plicXgafv , plicUploadProtocol , plicAccessToken , plicUploadType , plicPayload , plicCallback ) where import Network.Google.File.Types import Network.Google.Prelude -- | A resource alias for @file.projects.locations.instances.create@ method which the -- 'ProjectsLocationsInstancesCreate' request conforms to. type ProjectsLocationsInstancesCreateResource = "v1" :> Capture "parent" Text :> "instances" :> QueryParam "instanceId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Instance :> Post '[JSON] Operation -- | Creates an instance. When creating from a backup, the capacity of the -- new instance needs to be equal to or larger than the capacity of the -- backup (and also equal to or larger than the minimum capacity of the -- tier). -- -- /See:/ 'projectsLocationsInstancesCreate' smart constructor. data ProjectsLocationsInstancesCreate = ProjectsLocationsInstancesCreate' { _plicParent :: !Text , _plicInstanceId :: !(Maybe Text) , _plicXgafv :: !(Maybe Xgafv) , _plicUploadProtocol :: !(Maybe Text) , _plicAccessToken :: !(Maybe Text) , _plicUploadType :: !(Maybe Text) , _plicPayload :: !Instance , _plicCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsInstancesCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plicParent' -- -- * 'plicInstanceId' -- -- * 'plicXgafv' -- -- * 'plicUploadProtocol' -- -- * 'plicAccessToken' -- -- * 'plicUploadType' -- -- * 'plicPayload' -- -- * 'plicCallback' projectsLocationsInstancesCreate :: Text -- ^ 'plicParent' -> Instance -- ^ 'plicPayload' -> ProjectsLocationsInstancesCreate projectsLocationsInstancesCreate pPlicParent_ pPlicPayload_ = ProjectsLocationsInstancesCreate' { _plicParent = pPlicParent_ , _plicInstanceId = Nothing , _plicXgafv = Nothing , _plicUploadProtocol = Nothing , _plicAccessToken = Nothing , _plicUploadType = Nothing , _plicPayload = pPlicPayload_ , _plicCallback = Nothing } -- | Required. The instance\'s project and location, in the format -- projects\/{project_id}\/locations\/{location}. In Cloud Filestore, -- locations map to GCP zones, for example **us-west1-b**. plicParent :: Lens' ProjectsLocationsInstancesCreate Text plicParent = lens _plicParent (\ s a -> s{_plicParent = a}) -- | Required. The name of the instance to create. The name must be unique -- for the specified project and location. plicInstanceId :: Lens' ProjectsLocationsInstancesCreate (Maybe Text) plicInstanceId = lens _plicInstanceId (\ s a -> s{_plicInstanceId = a}) -- | V1 error format. plicXgafv :: Lens' ProjectsLocationsInstancesCreate (Maybe Xgafv) plicXgafv = lens _plicXgafv (\ s a -> s{_plicXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plicUploadProtocol :: Lens' ProjectsLocationsInstancesCreate (Maybe Text) plicUploadProtocol = lens _plicUploadProtocol (\ s a -> s{_plicUploadProtocol = a}) -- | OAuth access token. plicAccessToken :: Lens' ProjectsLocationsInstancesCreate (Maybe Text) plicAccessToken = lens _plicAccessToken (\ s a -> s{_plicAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plicUploadType :: Lens' ProjectsLocationsInstancesCreate (Maybe Text) plicUploadType = lens _plicUploadType (\ s a -> s{_plicUploadType = a}) -- | Multipart request metadata. plicPayload :: Lens' ProjectsLocationsInstancesCreate Instance plicPayload = lens _plicPayload (\ s a -> s{_plicPayload = a}) -- | JSONP plicCallback :: Lens' ProjectsLocationsInstancesCreate (Maybe Text) plicCallback = lens _plicCallback (\ s a -> s{_plicCallback = a}) instance GoogleRequest ProjectsLocationsInstancesCreate where type Rs ProjectsLocationsInstancesCreate = Operation type Scopes ProjectsLocationsInstancesCreate = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsInstancesCreate'{..} = go _plicParent _plicInstanceId _plicXgafv _plicUploadProtocol _plicAccessToken _plicUploadType _plicCallback (Just AltJSON) _plicPayload fileService where go = buildClient (Proxy :: Proxy ProjectsLocationsInstancesCreateResource) mempty
brendanhay/gogol
gogol-file/gen/Network/Google/Resource/File/Projects/Locations/Instances/Create.hs
mpl-2.0
6,377
0
18
1,408
869
509
360
127
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AccessContextManager.AccessPolicies.ServicePerimeters.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Get a Service Perimeter by resource name. -- -- /See:/ <https://cloud.google.com/access-context-manager/docs/reference/rest/ Access Context Manager API Reference> for @accesscontextmanager.accessPolicies.servicePerimeters.get@. module Network.Google.Resource.AccessContextManager.AccessPolicies.ServicePerimeters.Get ( -- * REST Resource AccessPoliciesServicePerimetersGetResource -- * Creating a Request , accessPoliciesServicePerimetersGet , AccessPoliciesServicePerimetersGet -- * Request Lenses , apspgXgafv , apspgUploadProtocol , apspgAccessToken , apspgUploadType , apspgName , apspgCallback ) where import Network.Google.AccessContextManager.Types import Network.Google.Prelude -- | A resource alias for @accesscontextmanager.accessPolicies.servicePerimeters.get@ method which the -- 'AccessPoliciesServicePerimetersGet' request conforms to. type AccessPoliciesServicePerimetersGetResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ServicePerimeter -- | Get a Service Perimeter by resource name. -- -- /See:/ 'accessPoliciesServicePerimetersGet' smart constructor. data AccessPoliciesServicePerimetersGet = AccessPoliciesServicePerimetersGet' { _apspgXgafv :: !(Maybe Xgafv) , _apspgUploadProtocol :: !(Maybe Text) , _apspgAccessToken :: !(Maybe Text) , _apspgUploadType :: !(Maybe Text) , _apspgName :: !Text , _apspgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccessPoliciesServicePerimetersGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apspgXgafv' -- -- * 'apspgUploadProtocol' -- -- * 'apspgAccessToken' -- -- * 'apspgUploadType' -- -- * 'apspgName' -- -- * 'apspgCallback' accessPoliciesServicePerimetersGet :: Text -- ^ 'apspgName' -> AccessPoliciesServicePerimetersGet accessPoliciesServicePerimetersGet pApspgName_ = AccessPoliciesServicePerimetersGet' { _apspgXgafv = Nothing , _apspgUploadProtocol = Nothing , _apspgAccessToken = Nothing , _apspgUploadType = Nothing , _apspgName = pApspgName_ , _apspgCallback = Nothing } -- | V1 error format. apspgXgafv :: Lens' AccessPoliciesServicePerimetersGet (Maybe Xgafv) apspgXgafv = lens _apspgXgafv (\ s a -> s{_apspgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). apspgUploadProtocol :: Lens' AccessPoliciesServicePerimetersGet (Maybe Text) apspgUploadProtocol = lens _apspgUploadProtocol (\ s a -> s{_apspgUploadProtocol = a}) -- | OAuth access token. apspgAccessToken :: Lens' AccessPoliciesServicePerimetersGet (Maybe Text) apspgAccessToken = lens _apspgAccessToken (\ s a -> s{_apspgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). apspgUploadType :: Lens' AccessPoliciesServicePerimetersGet (Maybe Text) apspgUploadType = lens _apspgUploadType (\ s a -> s{_apspgUploadType = a}) -- | Required. Resource name for the Service Perimeter. Format: -- \`accessPolicies\/{policy_id}\/servicePerimeters\/{service_perimeters_id}\` apspgName :: Lens' AccessPoliciesServicePerimetersGet Text apspgName = lens _apspgName (\ s a -> s{_apspgName = a}) -- | JSONP apspgCallback :: Lens' AccessPoliciesServicePerimetersGet (Maybe Text) apspgCallback = lens _apspgCallback (\ s a -> s{_apspgCallback = a}) instance GoogleRequest AccessPoliciesServicePerimetersGet where type Rs AccessPoliciesServicePerimetersGet = ServicePerimeter type Scopes AccessPoliciesServicePerimetersGet = '["https://www.googleapis.com/auth/cloud-platform"] requestClient AccessPoliciesServicePerimetersGet'{..} = go _apspgName _apspgXgafv _apspgUploadProtocol _apspgAccessToken _apspgUploadType _apspgCallback (Just AltJSON) accessContextManagerService where go = buildClient (Proxy :: Proxy AccessPoliciesServicePerimetersGetResource) mempty
brendanhay/gogol
gogol-accesscontextmanager/gen/Network/Google/Resource/AccessContextManager/AccessPolicies/ServicePerimeters/Get.hs
mpl-2.0
5,327
0
15
1,120
696
407
289
107
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CodeDeploy.ListDeploymentInstances -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Lists the Amazon EC2 instances for a deployment within the AWS user account. -- -- <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListDeploymentInstances.html> module Network.AWS.CodeDeploy.ListDeploymentInstances ( -- * Request ListDeploymentInstances -- ** Request constructor , listDeploymentInstances -- ** Request lenses , ldiDeploymentId , ldiInstanceStatusFilter , ldiNextToken -- * Response , ListDeploymentInstancesResponse -- ** Response constructor , listDeploymentInstancesResponse -- ** Response lenses , ldirInstancesList , ldirNextToken ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CodeDeploy.Types import qualified GHC.Exts data ListDeploymentInstances = ListDeploymentInstances { _ldiDeploymentId :: Text , _ldiInstanceStatusFilter :: List "instanceStatusFilter" InstanceStatus , _ldiNextToken :: Maybe Text } deriving (Eq, Read, Show) -- | 'ListDeploymentInstances' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ldiDeploymentId' @::@ 'Text' -- -- * 'ldiInstanceStatusFilter' @::@ ['InstanceStatus'] -- -- * 'ldiNextToken' @::@ 'Maybe' 'Text' -- listDeploymentInstances :: Text -- ^ 'ldiDeploymentId' -> ListDeploymentInstances listDeploymentInstances p1 = ListDeploymentInstances { _ldiDeploymentId = p1 , _ldiNextToken = Nothing , _ldiInstanceStatusFilter = mempty } -- | The unique ID of a deployment. ldiDeploymentId :: Lens' ListDeploymentInstances Text ldiDeploymentId = lens _ldiDeploymentId (\s a -> s { _ldiDeploymentId = a }) -- | A subset of instances to list, by status: -- -- Pending: Include in the resulting list those instances with pending -- deployments. InProgress: Include in the resulting list those instances with -- in-progress deployments. Succeeded: Include in the resulting list those -- instances with succeeded deployments. Failed: Include in the resulting list -- those instances with failed deployments. Skipped: Include in the resulting -- list those instances with skipped deployments. Unknown: Include in the -- resulting list those instances with deployments in an unknown state. ldiInstanceStatusFilter :: Lens' ListDeploymentInstances [InstanceStatus] ldiInstanceStatusFilter = lens _ldiInstanceStatusFilter (\s a -> s { _ldiInstanceStatusFilter = a }) . _List -- | An identifier that was returned from the previous list deployment instances -- call, which can be used to return the next set of deployment instances in the -- list. ldiNextToken :: Lens' ListDeploymentInstances (Maybe Text) ldiNextToken = lens _ldiNextToken (\s a -> s { _ldiNextToken = a }) data ListDeploymentInstancesResponse = ListDeploymentInstancesResponse { _ldirInstancesList :: List "instancesList" Text , _ldirNextToken :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ListDeploymentInstancesResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ldirInstancesList' @::@ ['Text'] -- -- * 'ldirNextToken' @::@ 'Maybe' 'Text' -- listDeploymentInstancesResponse :: ListDeploymentInstancesResponse listDeploymentInstancesResponse = ListDeploymentInstancesResponse { _ldirInstancesList = mempty , _ldirNextToken = Nothing } -- | A list of instance IDs. ldirInstancesList :: Lens' ListDeploymentInstancesResponse [Text] ldirInstancesList = lens _ldirInstancesList (\s a -> s { _ldirInstancesList = a }) . _List -- | If the amount of information that is returned is significantly large, an -- identifier will also be returned, which can be used in a subsequent list -- deployment instances call to return the next set of deployment instances in -- the list. ldirNextToken :: Lens' ListDeploymentInstancesResponse (Maybe Text) ldirNextToken = lens _ldirNextToken (\s a -> s { _ldirNextToken = a }) instance ToPath ListDeploymentInstances where toPath = const "/" instance ToQuery ListDeploymentInstances where toQuery = const mempty instance ToHeaders ListDeploymentInstances instance ToJSON ListDeploymentInstances where toJSON ListDeploymentInstances{..} = object [ "deploymentId" .= _ldiDeploymentId , "nextToken" .= _ldiNextToken , "instanceStatusFilter" .= _ldiInstanceStatusFilter ] instance AWSRequest ListDeploymentInstances where type Sv ListDeploymentInstances = CodeDeploy type Rs ListDeploymentInstances = ListDeploymentInstancesResponse request = post "ListDeploymentInstances" response = jsonResponse instance FromJSON ListDeploymentInstancesResponse where parseJSON = withObject "ListDeploymentInstancesResponse" $ \o -> ListDeploymentInstancesResponse <$> o .:? "instancesList" .!= mempty <*> o .:? "nextToken"
dysinger/amazonka
amazonka-codedeploy/gen/Network/AWS/CodeDeploy/ListDeploymentInstances.hs
mpl-2.0
5,977
0
12
1,196
674
407
267
77
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Blogger.Pages.Publish -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Publishes a page. -- -- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API v3 Reference> for @blogger.pages.publish@. module Network.Google.Resource.Blogger.Pages.Publish ( -- * REST Resource PagesPublishResource -- * Creating a Request , pagesPublish , PagesPublish -- * Request Lenses , pagaXgafv , pagaUploadProtocol , pagaAccessToken , pagaUploadType , pagaBlogId , pagaPageId , pagaCallback ) where import Network.Google.Blogger.Types import Network.Google.Prelude -- | A resource alias for @blogger.pages.publish@ method which the -- 'PagesPublish' request conforms to. type PagesPublishResource = "v3" :> "blogs" :> Capture "blogId" Text :> "pages" :> Capture "pageId" Text :> "publish" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Post '[JSON] Page -- | Publishes a page. -- -- /See:/ 'pagesPublish' smart constructor. data PagesPublish = PagesPublish' { _pagaXgafv :: !(Maybe Xgafv) , _pagaUploadProtocol :: !(Maybe Text) , _pagaAccessToken :: !(Maybe Text) , _pagaUploadType :: !(Maybe Text) , _pagaBlogId :: !Text , _pagaPageId :: !Text , _pagaCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PagesPublish' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pagaXgafv' -- -- * 'pagaUploadProtocol' -- -- * 'pagaAccessToken' -- -- * 'pagaUploadType' -- -- * 'pagaBlogId' -- -- * 'pagaPageId' -- -- * 'pagaCallback' pagesPublish :: Text -- ^ 'pagaBlogId' -> Text -- ^ 'pagaPageId' -> PagesPublish pagesPublish pPagaBlogId_ pPagaPageId_ = PagesPublish' { _pagaXgafv = Nothing , _pagaUploadProtocol = Nothing , _pagaAccessToken = Nothing , _pagaUploadType = Nothing , _pagaBlogId = pPagaBlogId_ , _pagaPageId = pPagaPageId_ , _pagaCallback = Nothing } -- | V1 error format. pagaXgafv :: Lens' PagesPublish (Maybe Xgafv) pagaXgafv = lens _pagaXgafv (\ s a -> s{_pagaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pagaUploadProtocol :: Lens' PagesPublish (Maybe Text) pagaUploadProtocol = lens _pagaUploadProtocol (\ s a -> s{_pagaUploadProtocol = a}) -- | OAuth access token. pagaAccessToken :: Lens' PagesPublish (Maybe Text) pagaAccessToken = lens _pagaAccessToken (\ s a -> s{_pagaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pagaUploadType :: Lens' PagesPublish (Maybe Text) pagaUploadType = lens _pagaUploadType (\ s a -> s{_pagaUploadType = a}) pagaBlogId :: Lens' PagesPublish Text pagaBlogId = lens _pagaBlogId (\ s a -> s{_pagaBlogId = a}) pagaPageId :: Lens' PagesPublish Text pagaPageId = lens _pagaPageId (\ s a -> s{_pagaPageId = a}) -- | JSONP pagaCallback :: Lens' PagesPublish (Maybe Text) pagaCallback = lens _pagaCallback (\ s a -> s{_pagaCallback = a}) instance GoogleRequest PagesPublish where type Rs PagesPublish = Page type Scopes PagesPublish = '["https://www.googleapis.com/auth/blogger"] requestClient PagesPublish'{..} = go _pagaBlogId _pagaPageId _pagaXgafv _pagaUploadProtocol _pagaAccessToken _pagaUploadType _pagaCallback (Just AltJSON) bloggerService where go = buildClient (Proxy :: Proxy PagesPublishResource) mempty
brendanhay/gogol
gogol-blogger/gen/Network/Google/Resource/Blogger/Pages/Publish.hs
mpl-2.0
4,676
0
19
1,168
779
452
327
115
1
module TestImport ( module TestImport , module X ) where import Application (makeFoundation, makeLogWare) #if MIN_VERSION_classy_prelude(1, 0, 0) import ClassyPrelude as X hiding (delete, deleteBy, Handler) #else import ClassyPrelude as X hiding (delete, deleteBy) #endif import Database.Persist as X hiding (get) import Database.Persist.Sql (SqlPersistM, SqlBackend, runSqlPersistMPool, rawExecute, rawSql, unSingle, connEscapeName) import Foundation as X import Model as X import Test.Hspec as X import Text.Shakespeare.Text (st) import Yesod.Default.Config2 (useEnv, loadYamlSettings) import Yesod.Auth as X import Yesod.Test as X runDB :: SqlPersistM a -> YesodExample App a runDB query = do app <- getTestYesod liftIO $ runDBWithApp app query runDBWithApp :: App -> SqlPersistM a -> IO a runDBWithApp app query = runSqlPersistMPool query (appConnPool app) withApp :: SpecWith (TestApp App) -> Spec withApp = before $ do settings <- loadYamlSettings ["config/test-settings.yml", "config/secret.yml", "config/settings.yml"] [] useEnv foundation <- makeFoundation settings wipeDB foundation logWare <- liftIO $ makeLogWare foundation return (foundation, logWare) -- This function will truncate all of the tables in your database. -- 'withApp' calls it before each test, creating a clean environment for each -- spec to run in. wipeDB :: App -> IO () wipeDB app = runDBWithApp app $ do tables <- getTables sqlBackend <- ask let escapedTables = map (connEscapeName sqlBackend . DBName) tables query = "TRUNCATE TABLE " ++ intercalate ", " escapedTables rawExecute query [] getTables :: MonadIO m => ReaderT SqlBackend m [Text] getTables = do tables <- rawSql [st| SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'; |] [] return $ map unSingle tables -- | Authenticate as a user. This relies on the `auth-dummy-login: true` flag -- being set in test-settings.yaml, which enables dummy authentication in -- Foundation.hs authenticateAs :: Entity User -> YesodExample App () authenticateAs (Entity _ u) = do request $ do setMethod "POST" addPostParam "ident" $ userName u setUrl $ AuthR $ PluginR "dummy" [] -- | Create a user. createUser :: Text -> YesodExample App (Entity User) createUser ident = do runDB $ insertEntity User { userName = ident , userEmail = ident }
Lasokki/omanet
test/TestImport.hs
agpl-3.0
2,579
0
14
620
607
323
284
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Data.Geometry.WindingOrderSpec where import Test.Hspec (Spec, describe, it, shouldBe) import qualified Data.Geometry.WindingOrder as WindingOrder import qualified Data.SpecHelper as SpecHelper simplePolygonPts :: [(Double, Double)] simplePolygonPts = [(0, 0), (4, 0), (4, 4), (0, 4), (0, 0)] smallNegativePolyPts :: [(Double, Double)] smallNegativePolyPts = [(3, 4), (5, 11), (12, 8), (9, 5), (5, 6), (3, 4)] largePositivePolyPts :: [(Double, Double)] largePositivePolyPts = [(3186, 2048), (3186, 2037), (3197, 2037), (3197, 2048), (3186, 2048)] rewoundSimplePolygonPts :: [(Double, Double)] rewoundSimplePolygonPts = [(0, 0), (0, 4), (4, 4), (4, 0), (0,0)] rewoundSmallNegativePolyPts :: [(Double, Double)] rewoundSmallNegativePolyPts = [(3, 4), (5, 6), (9, 5), (12, 8), (5, 11), (3, 4)] rewoundLargePositivePolyPts :: [(Double, Double)] rewoundLargePositivePolyPts = [(3186, 2048), (3197, 2048), (3197, 2037), (3186, 2037), (3186, 2048)] spec :: Spec spec = testShoelace testShoelace :: Spec testShoelace = do describe "areas" $ do it "Small set of points 2" $ WindingOrder.surveyor (SpecHelper.listToSequenceGeo simplePolygonPts) `shouldBe` 16 it "Small set of points" $ WindingOrder.surveyor (SpecHelper.listToSequenceGeo smallNegativePolyPts) `shouldBe` (-30) it "Large set of points" $ WindingOrder.surveyor (SpecHelper.listToSequenceGeo largePositivePolyPts) `shouldBe` 121 describe "winding order" $ do it "Small set of points 2" $ WindingOrder.isClockwise (SpecHelper.listToSequenceGeo simplePolygonPts) `shouldBe` False it "Small set of points" $ WindingOrder.isClockwise (SpecHelper.listToSequenceGeo smallNegativePolyPts) `shouldBe` True it "Large set of points" $ WindingOrder.isClockwise (SpecHelper.listToSequenceGeo largePositivePolyPts) `shouldBe` False describe "rewind" $ do it "Small set of points 2" $ WindingOrder.rewind (SpecHelper.listToSequenceGeo simplePolygonPts) `shouldBe` SpecHelper.listToSequenceGeo rewoundSimplePolygonPts it "Small set of points" $ WindingOrder.rewind (SpecHelper.listToSequenceGeo smallNegativePolyPts) `shouldBe` SpecHelper.listToSequenceGeo rewoundSmallNegativePolyPts it "Large set of points" $ WindingOrder.rewind (SpecHelper.listToSequenceGeo largePositivePolyPts) `shouldBe` SpecHelper.listToSequenceGeo rewoundLargePositivePolyPts describe "ensure order" $ do it "Small set of points 2" $ WindingOrder.ensureOrder WindingOrder.Clockwise (SpecHelper.listToSequenceGeo simplePolygonPts) `shouldBe` SpecHelper.listToSequenceGeo rewoundSimplePolygonPts it "Large set of points" $ WindingOrder.ensureOrder WindingOrder.AntiClockwise (SpecHelper.listToSequenceGeo largePositivePolyPts) `shouldBe` SpecHelper.listToSequenceGeo largePositivePolyPts
sitewisely/zellige
test/Data/Geometry/WindingOrderSpec.hs
apache-2.0
2,910
0
15
453
863
494
369
48
1
{-# LANGUAGE FlexibleInstances #-} module Lycopene.Database.Relational.Decode.Sprint where import Data.UUID (fromString) import Lycopene.Database.Relational.Decode.Prim import qualified Lycopene.Core as Core import qualified Lycopene.Database.Relational.Sprint as Sp sprint :: Decode Sp.Sprint Core.Sprint sprint = Core.Sprint <$> decoder (fromString . Sp.sprintId) <?> "sprintId" <*> decoder Sp.name <*> decoder Sp.description <*> decoder (fmap Core.toDate . Sp.startOn) <*> decoder (fmap Core.toDate . Sp.endOn) <*> decoder (sprintStatus . Sp.status) <?> "projectStatus" sprintStatus :: Int -> Maybe Core.SprintStatus sprintStatus 0 = Just Core.SprintFinished sprintStatus 1 = Just Core.SprintRunning sprintStatus _ = Nothing
utky/lycopene
src/Lycopene/Database/Relational/Decode/Sprint.hs
apache-2.0
778
0
16
132
215
116
99
19
1
----------------------------------------------------------------------------- -- | -- Module : Haddock.Backends.Html -- Copyright : (c) Simon Marlow 2003-2006, -- David Waern 2006-2009, -- Mark Lentczner 2010, -- Mateusz Kowalczyk 2013 -- License : BSD-like -- -- Maintainer : haddock@projects.haskell.org -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- {-# LANGUAGE CPP, NamedFieldPuns #-} module Haddock.Backends.Xhtml ( ppHtml, copyHtmlBits, ppHtmlIndex, ppHtmlContents, ) where import Prelude hiding (div) import Haddock.Backends.Xhtml.Decl import Haddock.Backends.Xhtml.DocMarkup import Haddock.Backends.Xhtml.Layout import Haddock.Backends.Xhtml.Names import Haddock.Backends.Xhtml.Themes import Haddock.Backends.Xhtml.Types import Haddock.Backends.Xhtml.Utils import Haddock.ModuleTree import Haddock.Types import Haddock.Version import Haddock.Utils import Haddock.Utils.Json import Text.XHtml hiding ( name, title, p, quote ) import Haddock.GhcUtils import Control.Monad ( when, unless ) import Data.Char ( toUpper, isSpace ) import Data.List ( sortBy, isPrefixOf, intercalate, intersperse ) import Data.Maybe import System.FilePath hiding ( (</>) ) import System.Directory import Data.Map ( Map ) import qualified Data.Map as Map hiding ( Map ) import qualified Data.Set as Set hiding ( Set ) import Data.Ord ( comparing ) import DynFlags (Language(..)) import GHC hiding ( NoLink, moduleInfo,LexicalFixity(..) ) import Name -------------------------------------------------------------------------------- -- * Generating HTML documentation -------------------------------------------------------------------------------- ppHtml :: DynFlags -> String -- ^ Title -> Maybe String -- ^ Package -> [Interface] -> [InstalledInterface] -- ^ Reexported interfaces -> FilePath -- ^ Destination directory -> Maybe (MDoc GHC.RdrName) -- ^ Prologue text, maybe -> Themes -- ^ Themes -> Maybe String -- ^ The mathjax URL (--mathjax) -> SourceURLs -- ^ The source URL (--source) -> WikiURLs -- ^ The wiki URL (--wiki) -> Maybe String -- ^ The contents URL (--use-contents) -> Maybe String -- ^ The index URL (--use-index) -> Bool -- ^ Whether to use unicode in output (--use-unicode) -> QualOption -- ^ How to qualify names -> Bool -- ^ Output pretty html (newlines and indenting) -> Bool -- ^ Also write Quickjump index -> IO () ppHtml dflags doctitle maybe_package ifaces reexported_ifaces odir prologue themes maybe_mathjax_url maybe_source_url maybe_wiki_url maybe_contents_url maybe_index_url unicode qual debug withQuickjump = do let visible_ifaces = filter visible ifaces visible i = OptHide `notElem` ifaceOptions i when (isNothing maybe_contents_url) $ ppHtmlContents dflags odir doctitle maybe_package themes maybe_mathjax_url maybe_index_url maybe_source_url maybe_wiki_url (map toInstalledIface visible_ifaces ++ reexported_ifaces) False -- we don't want to display the packages in a single-package contents prologue debug (makeContentsQual qual) when (isNothing maybe_index_url) $ do ppHtmlIndex odir doctitle maybe_package themes maybe_mathjax_url maybe_contents_url maybe_source_url maybe_wiki_url (map toInstalledIface visible_ifaces ++ reexported_ifaces) debug when withQuickjump $ ppJsonIndex odir maybe_source_url maybe_wiki_url unicode qual visible_ifaces mapM_ (ppHtmlModule odir doctitle themes maybe_mathjax_url maybe_source_url maybe_wiki_url maybe_contents_url maybe_index_url unicode qual debug) visible_ifaces copyHtmlBits :: FilePath -> FilePath -> Themes -> Bool -> IO () copyHtmlBits odir libdir themes withQuickjump = do let libhtmldir = joinPath [libdir, "html"] copyCssFile f = copyFile f (combine odir (takeFileName f)) copyLibFile f = copyFile (joinPath [libhtmldir, f]) (joinPath [odir, f]) mapM_ copyCssFile (cssFiles themes) copyLibFile haddockJsFile copyCssFile (joinPath [libhtmldir, quickJumpCssFile]) when withQuickjump (copyLibFile jsQuickJumpFile) return () headHtml :: String -> Themes -> Maybe String -> Html headHtml docTitle themes mathjax_url = header << [ meta ! [httpequiv "Content-Type", content "text/html; charset=UTF-8"], thetitle << docTitle, styleSheet themes, thelink ! [ rel "stylesheet", thetype "text/css", href quickJumpCssFile] << noHtml, script ! [src haddockJsFile, emptyAttr "async", thetype "text/javascript"] << noHtml, script ! [src mjUrl, thetype "text/javascript"] << noHtml ] where mjUrl = maybe "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML" id mathjax_url srcButton :: SourceURLs -> Maybe Interface -> Maybe Html srcButton (Just src_base_url, _, _, _) Nothing = Just (anchor ! [href src_base_url] << "Source") srcButton (_, Just src_module_url, _, _) (Just iface) = let url = spliceURL (Just $ ifaceOrigFilename iface) (Just $ ifaceMod iface) Nothing Nothing src_module_url in Just (anchor ! [href url] << "Source") srcButton _ _ = Nothing wikiButton :: WikiURLs -> Maybe Module -> Maybe Html wikiButton (Just wiki_base_url, _, _) Nothing = Just (anchor ! [href wiki_base_url] << "User Comments") wikiButton (_, Just wiki_module_url, _) (Just mdl) = let url = spliceURL Nothing (Just mdl) Nothing Nothing wiki_module_url in Just (anchor ! [href url] << "User Comments") wikiButton _ _ = Nothing contentsButton :: Maybe String -> Maybe Html contentsButton maybe_contents_url = Just (anchor ! [href url] << "Contents") where url = fromMaybe contentsHtmlFile maybe_contents_url indexButton :: Maybe String -> Maybe Html indexButton maybe_index_url = Just (anchor ! [href url] << "Index") where url = fromMaybe indexHtmlFile maybe_index_url bodyHtml :: String -> Maybe Interface -> SourceURLs -> WikiURLs -> Maybe String -> Maybe String -> Html -> Html bodyHtml doctitle iface maybe_source_url maybe_wiki_url maybe_contents_url maybe_index_url pageContent = body << [ divPackageHeader << [ unordList (catMaybes [ srcButton maybe_source_url iface, wikiButton maybe_wiki_url (ifaceMod <$> iface), contentsButton maybe_contents_url, indexButton maybe_index_url]) ! [theclass "links", identifier "page-menu"], nonEmptySectionName << doctitle ], divContent << pageContent, divFooter << paragraph << ( "Produced by " +++ (anchor ! [href projectUrl] << toHtml projectName) +++ (" version " ++ projectVersion) ) ] moduleInfo :: Interface -> Html moduleInfo iface = let info = ifaceInfo iface doOneEntry :: (String, HaddockModInfo GHC.Name -> Maybe String) -> Maybe HtmlTable doOneEntry (fieldName, field) = field info >>= \a -> return (th << fieldName <-> td << a) entries :: [HtmlTable] entries = maybeToList copyrightsTable ++ mapMaybe doOneEntry [ ("License",hmi_license), ("Maintainer",hmi_maintainer), ("Stability",hmi_stability), ("Portability",hmi_portability), ("Safe Haskell",hmi_safety), ("Language", lg) ] ++ extsForm where lg inf = case hmi_language inf of Nothing -> Nothing Just Haskell98 -> Just "Haskell98" Just Haskell2010 -> Just "Haskell2010" multilineRow :: String -> [String] -> HtmlTable multilineRow title xs = (th ! [valign "top"]) << title <-> td << (toLines xs) where toLines = mconcat . intersperse br . map toHtml copyrightsTable :: Maybe HtmlTable copyrightsTable = fmap (multilineRow "Copyright" . split) (hmi_copyright info) where split = map (trim . filter (/= ',')) . lines extsForm | OptShowExtensions `elem` ifaceOptions iface = let fs = map (dropOpt . show) (hmi_extensions info) in case map stringToHtml fs of [] -> [] [x] -> extField x -- don't use a list for a single extension xs -> extField $ unordList xs ! [theclass "extension-list"] | otherwise = [] where extField x = return $ th << "Extensions" <-> td << x dropOpt x = if "Opt_" `isPrefixOf` x then drop 4 x else x in case entries of [] -> noHtml _ -> table ! [theclass "info"] << aboves entries -------------------------------------------------------------------------------- -- * Generate the module contents -------------------------------------------------------------------------------- ppHtmlContents :: DynFlags -> FilePath -> String -> Maybe String -> Themes -> Maybe String -> Maybe String -> SourceURLs -> WikiURLs -> [InstalledInterface] -> Bool -> Maybe (MDoc GHC.RdrName) -> Bool -> Qualification -- ^ How to qualify names -> IO () ppHtmlContents dflags odir doctitle _maybe_package themes mathjax_url maybe_index_url maybe_source_url maybe_wiki_url ifaces showPkgs prologue debug qual = do let tree = mkModuleTree dflags showPkgs [(instMod iface, toInstalledDescription iface) | iface <- ifaces , not (instIsSig iface)] sig_tree = mkModuleTree dflags showPkgs [(instMod iface, toInstalledDescription iface) | iface <- ifaces , instIsSig iface] html = headHtml doctitle themes mathjax_url +++ bodyHtml doctitle Nothing maybe_source_url maybe_wiki_url Nothing maybe_index_url << [ ppPrologue qual doctitle prologue, ppSignatureTree qual sig_tree, ppModuleTree qual tree ] createDirectoryIfMissing True odir writeFile (joinPath [odir, contentsHtmlFile]) (renderToString debug html) ppPrologue :: Qualification -> String -> Maybe (MDoc GHC.RdrName) -> Html ppPrologue _ _ Nothing = noHtml ppPrologue qual title (Just doc) = divDescription << (h1 << title +++ docElement thediv (rdrDocToHtml qual doc)) ppSignatureTree :: Qualification -> [ModuleTree] -> Html ppSignatureTree qual ts = divModuleList << (sectionName << "Signatures" +++ mkNodeList qual [] "n" ts) ppModuleTree :: Qualification -> [ModuleTree] -> Html ppModuleTree _ [] = mempty ppModuleTree qual ts = divModuleList << (sectionName << "Modules" +++ mkNodeList qual [] "n" ts) mkNodeList :: Qualification -> [String] -> String -> [ModuleTree] -> Html mkNodeList qual ss p ts = case ts of [] -> noHtml _ -> unordList (zipWith (mkNode qual ss) ps ts) where ps = [ p ++ '.' : show i | i <- [(1::Int)..]] mkNode :: Qualification -> [String] -> String -> ModuleTree -> Html mkNode qual ss p (Node s leaf _pkg srcPkg short ts) = htmlModule <+> shortDescr +++ htmlPkg +++ subtree where modAttrs = case (ts, leaf) of (_:_, Nothing) -> collapseControl p "module" (_, _ ) -> [theclass "module"] cBtn = case (ts, leaf) of (_:_, Just _) -> thespan ! collapseControl p "" << spaceHtml (_, _ ) -> noHtml -- We only need an explicit collapser button when the module name -- is also a leaf, and so is a link to a module page. Indeed, the -- spaceHtml is a minor hack and does upset the layout a fraction. htmlModule = thespan ! modAttrs << (cBtn +++ case leaf of Just m -> ppModule m Nothing -> toHtml s ) shortDescr = maybe noHtml (origDocToHtml qual) short htmlPkg = maybe noHtml (thespan ! [theclass "package"] <<) srcPkg subtree = if null ts then noHtml else collapseDetails p DetailsOpen ( thesummary ! [ theclass "hide-when-js-enabled" ] << "Submodules" +++ mkNodeList qual (s:ss) p ts ) -------------------------------------------------------------------------------- -- * Generate the index -------------------------------------------------------------------------------- ppJsonIndex :: FilePath -> SourceURLs -- ^ The source URL (--source) -> WikiURLs -- ^ The wiki URL (--wiki) -> Bool -> QualOption -> [Interface] -> IO () ppJsonIndex odir maybe_source_url maybe_wiki_url unicode qual_opt ifaces = do createDirectoryIfMissing True odir writeFile (joinPath [odir, indexJsonFile]) (encodeToString modules) where modules :: Value modules = Array (concatMap goInterface ifaces) goInterface :: Interface -> [Value] goInterface iface = concatMap (goExport mdl qual) (ifaceRnExportItems iface) where aliases = ifaceModuleAliases iface qual = makeModuleQual qual_opt aliases mdl mdl = ifaceMod iface goExport :: Module -> Qualification -> ExportItem DocName -> [Value] goExport mdl qual item | Just item_html <- processExport True links_info unicode qual item = [ Object [ "display_html" .= String (showHtmlFragment item_html) , "name" .= String (intercalate " " (map nameString names)) , "module" .= String (moduleString mdl) , "link" .= String (fromMaybe "" (listToMaybe (map (nameLink mdl) names))) ] ] | otherwise = [] where names = exportName item ++ exportSubs item exportSubs :: ExportItem DocName -> [DocName] exportSubs ExportDecl { expItemSubDocs } = map fst expItemSubDocs exportSubs _ = [] exportName :: ExportItem DocName -> [DocName] exportName ExportDecl { expItemDecl } = getMainDeclBinder $ unLoc expItemDecl exportName ExportNoDecl { expItemName } = [expItemName] exportName _ = [] nameString :: NamedThing name => name -> String nameString = occNameString . nameOccName . getName nameLink :: NamedThing name => Module -> name -> String nameLink mdl = moduleNameUrl' (moduleName mdl) . nameOccName . getName links_info = (maybe_source_url, maybe_wiki_url) ppHtmlIndex :: FilePath -> String -> Maybe String -> Themes -> Maybe String -> Maybe String -> SourceURLs -> WikiURLs -> [InstalledInterface] -> Bool -> IO () ppHtmlIndex odir doctitle _maybe_package themes maybe_mathjax_url maybe_contents_url maybe_source_url maybe_wiki_url ifaces debug = do let html = indexPage split_indices Nothing (if split_indices then [] else index) createDirectoryIfMissing True odir when split_indices $ do mapM_ (do_sub_index index) initialChars -- Let's add a single large index as well for those who don't know exactly what they're looking for: let mergedhtml = indexPage False Nothing index writeFile (joinPath [odir, subIndexHtmlFile merged_name]) (renderToString debug mergedhtml) writeFile (joinPath [odir, indexHtmlFile]) (renderToString debug html) where indexPage showLetters ch items = headHtml (doctitle ++ " (" ++ indexName ch ++ ")") themes maybe_mathjax_url +++ bodyHtml doctitle Nothing maybe_source_url maybe_wiki_url maybe_contents_url Nothing << [ if showLetters then indexInitialLetterLinks else noHtml, if null items then noHtml else divIndex << [sectionName << indexName ch, buildIndex items] ] indexName ch = "Index" ++ maybe "" (\c -> " - " ++ [c]) ch merged_name = "All" buildIndex items = table << aboves (map indexElt items) -- an arbitrary heuristic: -- too large, and a single-page will be slow to load -- too small, and we'll have lots of letter-indexes with only one -- or two members in them, which seems inefficient or -- unnecessarily hard to use. split_indices = length index > 150 indexInitialLetterLinks = divAlphabet << unordList (map (\str -> anchor ! [href (subIndexHtmlFile str)] << str) $ [ [c] | c <- initialChars , any ((==c) . toUpper . head . fst) index ] ++ [merged_name]) -- todo: what about names/operators that start with Unicode -- characters? -- Exports beginning with '_' can be listed near the end, -- presumably they're not as important... but would be listed -- with non-split index! initialChars = [ 'A'..'Z' ] ++ ":!#$%&*+./<=>?@\\^|-~" ++ "_" do_sub_index this_ix c = unless (null index_part) $ writeFile (joinPath [odir, subIndexHtmlFile [c]]) (renderToString debug html) where html = indexPage True (Just c) index_part index_part = [(n,stuff) | (n,stuff) <- this_ix, toUpper (head n) == c] index :: [(String, Map GHC.Name [(Module,Bool)])] index = sortBy cmp (Map.toAscList full_index) where cmp (n1,_) (n2,_) = comparing (map toUpper) n1 n2 -- for each name (a plain string), we have a number of original HsNames that -- it can refer to, and for each of those we have a list of modules -- that export that entity. Each of the modules exports the entity -- in a visible or invisible way (hence the Bool). full_index :: Map String (Map GHC.Name [(Module,Bool)]) full_index = Map.fromListWith (flip (Map.unionWith (++))) (concatMap getIfaceIndex ifaces) getIfaceIndex iface = [ (getOccString name , Map.fromList [(name, [(mdl, name `Set.member` visible)])]) | name <- instExports iface ] where mdl = instMod iface visible = Set.fromList (instVisibleExports iface) indexElt :: (String, Map GHC.Name [(Module,Bool)]) -> HtmlTable indexElt (str, entities) = case Map.toAscList entities of [(nm,entries)] -> td ! [ theclass "src" ] << toHtml str <-> indexLinks nm entries many_entities -> td ! [ theclass "src" ] << toHtml str <-> td << spaceHtml </> aboves (zipWith (curry doAnnotatedEntity) [1..] many_entities) doAnnotatedEntity :: (Integer, (Name, [(Module, Bool)])) -> HtmlTable doAnnotatedEntity (j,(nm,entries)) = td ! [ theclass "alt" ] << toHtml (show j) <+> parens (ppAnnot (nameOccName nm)) <-> indexLinks nm entries ppAnnot n | not (isValOcc n) = toHtml "Type/Class" | isDataOcc n = toHtml "Data Constructor" | otherwise = toHtml "Function" indexLinks nm entries = td ! [ theclass "module" ] << hsep (punctuate comma [ if visible then linkId mdl (Just nm) << toHtml (moduleString mdl) else toHtml (moduleString mdl) | (mdl, visible) <- entries ]) -------------------------------------------------------------------------------- -- * Generate the HTML page for a module -------------------------------------------------------------------------------- ppHtmlModule :: FilePath -> String -> Themes -> Maybe String -> SourceURLs -> WikiURLs -> Maybe String -> Maybe String -> Bool -> QualOption -> Bool -> Interface -> IO () ppHtmlModule odir doctitle themes maybe_mathjax_url maybe_source_url maybe_wiki_url maybe_contents_url maybe_index_url unicode qual debug iface = do let mdl = ifaceMod iface aliases = ifaceModuleAliases iface mdl_str = moduleString mdl mdl_str_annot = mdl_str ++ if ifaceIsSig iface then " (signature)" else "" mdl_str_linked | ifaceIsSig iface = mdl_str +++ " (signature" +++ sup << ("[" +++ anchor ! [href signatureDocURL] << "?" +++ "]" ) +++ ")" | otherwise = toHtml mdl_str real_qual = makeModuleQual qual aliases mdl html = headHtml mdl_str_annot themes maybe_mathjax_url +++ bodyHtml doctitle (Just iface) maybe_source_url maybe_wiki_url maybe_contents_url maybe_index_url << [ divModuleHeader << (moduleInfo iface +++ (sectionName << mdl_str_linked)), ifaceToHtml maybe_source_url maybe_wiki_url iface unicode real_qual ] createDirectoryIfMissing True odir writeFile (joinPath [odir, moduleHtmlFile mdl]) (renderToString debug html) signatureDocURL :: String signatureDocURL = "https://wiki.haskell.org/Module_signature" ifaceToHtml :: SourceURLs -> WikiURLs -> Interface -> Bool -> Qualification -> Html ifaceToHtml maybe_source_url maybe_wiki_url iface unicode qual = ppModuleContents qual exports (not . null $ ifaceRnOrphanInstances iface) +++ description +++ synopsis +++ divInterface (maybe_doc_hdr +++ bdy +++ orphans) where exports = numberSectionHeadings (ifaceRnExportItems iface) -- todo: if something has only sub-docs, or fn-args-docs, should -- it be measured here and thus prevent omitting the synopsis? has_doc ExportDecl { expItemMbDoc = (Documentation mDoc mWarning, _) } = isJust mDoc || isJust mWarning has_doc (ExportNoDecl _ _) = False has_doc (ExportModule _) = False has_doc _ = True no_doc_at_all = not (any has_doc exports) description | isNoHtml doc = doc | otherwise = divDescription $ sectionName << "Description" +++ doc where doc = docSection Nothing qual (ifaceRnDoc iface) -- omit the synopsis if there are no documentation annotations at all synopsis | no_doc_at_all = noHtml | otherwise = divSynopsis $ collapseDetails "syn" DetailsClosed ( thesummary << "Synopsis" +++ shortDeclList ( mapMaybe (processExport True linksInfo unicode qual) exports ) ! collapseToggle "syn" "" ) -- if the documentation doesn't begin with a section header, then -- add one ("Documentation"). maybe_doc_hdr = case exports of [] -> noHtml ExportGroup {} : _ -> noHtml _ -> h1 << "Documentation" bdy = foldr (+++) noHtml $ mapMaybe (processExport False linksInfo unicode qual) exports orphans = ppOrphanInstances linksInfo (ifaceRnOrphanInstances iface) False unicode qual linksInfo = (maybe_source_url, maybe_wiki_url) ppModuleContents :: Qualification -> [ExportItem DocName] -> Bool -- ^ Orphans sections -> Html ppModuleContents qual exports orphan | null sections && not orphan = noHtml | otherwise = contentsDiv where contentsDiv = divTableOfContents << ( sectionName << "Contents" +++ unordList (sections ++ orphanSection)) (sections, _leftovers{-should be []-}) = process 0 exports orphanSection | orphan = [ linkedAnchor "section.orphans" << "Orphan instances" ] | otherwise = [] process :: Int -> [ExportItem DocName] -> ([Html],[ExportItem DocName]) process _ [] = ([], []) process n items@(ExportGroup lev id0 doc : rest) | lev <= n = ( [], items ) | otherwise = ( html:secs, rest2 ) where html = linkedAnchor (groupId id0) << docToHtmlNoAnchors (Just id0) qual (mkMeta doc) +++ mk_subsections ssecs (ssecs, rest1) = process lev rest (secs, rest2) = process n rest1 process n (_ : rest) = process n rest mk_subsections [] = noHtml mk_subsections ss = unordList ss -- we need to assign a unique id to each section heading so we can hyperlink -- them from the contents: numberSectionHeadings :: [ExportItem DocName] -> [ExportItem DocName] numberSectionHeadings = go 1 where go :: Int -> [ExportItem DocName] -> [ExportItem DocName] go _ [] = [] go n (ExportGroup lev _ doc : es) = ExportGroup lev (show n) doc : go (n+1) es go n (other:es) = other : go n es processExport :: Bool -> LinksInfo -> Bool -> Qualification -> ExportItem DocName -> Maybe Html processExport _ _ _ _ ExportDecl { expItemDecl = L _ (InstD _) } = Nothing -- Hide empty instances processExport summary _ _ qual (ExportGroup lev id0 doc) = nothingIf summary $ groupHeading lev id0 << docToHtml (Just id0) qual (mkMeta doc) processExport summary links unicode qual (ExportDecl decl pats doc subdocs insts fixities splice) = processDecl summary $ ppDecl summary links decl pats doc insts fixities subdocs splice unicode qual processExport summary _ _ qual (ExportNoDecl y []) = processDeclOneLiner summary $ ppDocName qual Prefix True y processExport summary _ _ qual (ExportNoDecl y subs) = processDeclOneLiner summary $ ppDocName qual Prefix True y +++ parenList (map (ppDocName qual Prefix True) subs) processExport summary _ _ qual (ExportDoc doc) = nothingIf summary $ docSection_ Nothing qual doc processExport summary _ _ _ (ExportModule mdl) = processDeclOneLiner summary $ toHtml "module" <+> ppModule mdl nothingIf :: Bool -> a -> Maybe a nothingIf True _ = Nothing nothingIf False a = Just a processDecl :: Bool -> Html -> Maybe Html processDecl True = Just processDecl False = Just . divTopDecl trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace processDeclOneLiner :: Bool -> Html -> Maybe Html processDeclOneLiner True = Just processDeclOneLiner False = Just . divTopDecl . declElem groupHeading :: Int -> String -> Html -> Html groupHeading lev id0 = linkedAnchor grpId . groupTag lev ! [identifier grpId] where grpId = groupId id0 groupTag :: Int -> Html -> Html groupTag lev | lev == 1 = h1 | lev == 2 = h2 | lev == 3 = h3 | otherwise = h4
Fuuzetsu/haddock
haddock-api/src/Haddock/Backends/Xhtml.hs
bsd-2-clause
26,470
0
23
7,088
7,009
3,607
3,402
-1
-1
module Data.CRF.Chain1.Constrained.Util ( partition ) where import Data.List (transpose) partition :: Int -> [a] -> [[a]] partition n = transpose . group n where group _ [] = [] group k xs = take k xs : (group k $ drop k xs)
kawu/crf-chain1-constrained
src/Data/CRF/Chain1/Constrained/Util.hs
bsd-2-clause
241
0
10
59
111
60
51
8
2
-------------------------------------------------------------------------------- module Copilot.Kind.Light.Prover ( module Data.Default , Options (..) , lightProver ) where import Copilot.Kind.IL.Translate import Copilot.Kind.IL import qualified Copilot.Core as Core import qualified Copilot.Kind.Light.SMT as SMT import Control.Monad import Data.Default import Copilot.Kind.Prover import qualified Data.Map as Map import Data.Map (Map) -------------------------------------------------------------------------------- data Options = Options { -- The maximum number of steps of the k-induction algorithm the prover runs -- before giving up. kTimeout :: Integer -- If `onlyBmc` is set to `True`, the prover will only search for -- counterexamples and won't try to prove the properties discharged to it. , onlyBmc :: Bool -- If `debugMode` is set to `True`, the SMTLib queries produced by the -- prover are displayed in the standard output. , debugMode :: Bool } instance Default Options where def = Options { kTimeout = 100 , debugMode = False , onlyBmc = False } data ProverST = ProverST { options :: Options , spec :: Spec } lightProver :: Options -> Prover lightProver options = Prover { proverName = "Light" , hasFeature = \case GiveCex -> False HandleAssumptions -> True , startProver = \spec -> return $ ProverST options (translate spec) , askProver = ask , closeProver = const $ return () } -------------------------------------------------------------------------------- -- | Checks the Copilot specification with k-induction ask :: ProverST -> [PropId] -> PropId -> IO Output ask (ProverST opts (Spec {modelInit, modelRec, properties, sequences, unintFuns})) assumptionsIds toCheckId = do baseSolver <- SMT.startNewSolver "base" sequences unintFuns (debugMode opts) stepSolver <- SMT.startNewSolver "step" sequences unintFuns (debugMode opts) SMT.assume baseSolver modelInit' SMT.assume stepSolver modelRec' res <- indStep 0 baseSolver stepSolver mapM_ SMT.exit [baseSolver, stepSolver] return res where at = evalAt assumptions = selectProps assumptionsIds properties toCheck = selectProps [toCheckId] properties modelInit' = modelInit ++ map (at $ Fixed 0) assumptions modelRec' = modelRec ++ assumptions indStep k baseSolver stepSolver | k > kTimeout opts = let msg = "after " ++ show (kTimeout opts) ++ " iterations" in return (Output Unknown [msg]) | otherwise = do let base' = map (at $ Fixed k) modelRec' step' = map (at $ _n_plus (k + 1)) modelRec' ++ map (at $ _n_plus k) toCheck baseInv = map (at $ Fixed k) toCheck nextInv = map (at $ _n_plus (k + 1)) toCheck SMT.assume baseSolver base' SMT.assume stepSolver step' SMT.entailed baseSolver baseInv >>= \case SMT.Sat -> return $ Output (Invalid Nothing) [] SMT.Unknown -> return $ Output Unknown ["undecidable"] SMT.Unsat -> do if onlyBmc opts then indStep (k + 1) baseSolver stepSolver else SMT.entailed stepSolver nextInv >>= \case SMT.Sat -> indStep (k + 1) baseSolver stepSolver SMT.Unsat -> return $ Output Valid [] SMT.Unknown -> return $ Output Unknown ["undecidable"] selectProps :: [PropId] -> Map PropId Constraint -> [Constraint] selectProps propIds properties = [c | (id, c) <- Map.toList properties, id `elem` propIds] --------------------------------------------------------------------------------
jonathan-laurent/copilot-kind
src/Copilot/Kind/Light/Prover.hs
bsd-3-clause
3,924
0
23
1,107
956
509
447
-1
-1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE TypeApplications #-} {-# language ConstraintKinds #-} {-# language DataKinds #-} {-# language FlexibleContexts #-} {-# language FlexibleInstances #-} {-# language FunctionalDependencies #-} {-# language MultiParamTypeClasses #-} {-# language ScopedTypeVariables #-} {-# language TypeFamilies #-} {-# language TypeOperators #-} {-# language UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Generics.Wrapped -- Copyright : (C) 2020 Csongor Kiss -- License : BSD3 -- Maintainer : Csongor Kiss <kiss.csongor.kiss@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- Derive an isomorphism between a newtype and its wrapped type. -- ----------------------------------------------------------------------------- module Data.Generics.Wrapped ( Wrapped (..) , wrappedTo , wrappedFrom , _Unwrapped , _Wrapped ) where import Optics.Core import Optics.Internal.Optic import "generic-lens-core" Data.Generics.Internal.Wrapped (Context, derived) -- | @since 1.1.0.0 _Unwrapped :: Wrapped s t a b => Iso s t a b _Unwrapped = wrappedIso {-# inline _Unwrapped #-} -- | @since 1.1.0.0 _Wrapped :: Wrapped s t a b => Iso b a t s _Wrapped = re wrappedIso {-# inline _Wrapped #-} -- | @since 1.1.0.0 class Wrapped s t a b | s -> a, t -> b where -- | @since 1.1.0.0 wrappedIso :: Iso s t a b -- | @since 1.1.0.0 wrappedTo :: forall s a. Wrapped s s a a => s -> a wrappedTo s = view (wrappedIso @s @s @a @a) s {-# INLINE wrappedTo #-} -- | @since 1.1.0.0 wrappedFrom :: forall s a. Wrapped s s a a => a -> s wrappedFrom a = view (re wrappedIso) a {-# INLINE wrappedFrom #-} instance Context s t a b => Wrapped s t a b where wrappedIso = Optic derived {-# INLINE wrappedIso #-}
kcsongor/generic-lens
generic-optics/src/Data/Generics/Wrapped.hs
bsd-3-clause
1,885
0
8
333
341
200
141
39
1
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-} {-# OPTIONS_GHC -fcontext-stack42 #-} module Games.Chaos2010.Database.Closest_enemy_to_selected_piece where import Games.Chaos2010.Database.Fields import Database.HaskellDB.DBLayout type Closest_enemy_to_selected_piece = Record (HCons (LVPair X (Expr (Maybe Int))) (HCons (LVPair Y (Expr (Maybe Int))) HNil)) closest_enemy_to_selected_piece :: Table Closest_enemy_to_selected_piece closest_enemy_to_selected_piece = baseTable "closest_enemy_to_selected_piece"
JakeWheat/Chaos-2010
Games/Chaos2010/Database/Closest_enemy_to_selected_piece.hs
bsd-3-clause
581
0
15
108
104
58
46
13
1
module Blockchain.Data.Address ( Address(..), prvKey2Address, pubKey2Address, getNewAddress_unsafe ) where import Control.Monad import qualified Crypto.Hash.SHA3 as C import Data.Binary import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import Data.Maybe import Network.Haskoin.Crypto hiding (Address) import Network.Haskoin.Internals hiding (Address) import Numeric import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import Blockchain.Data.RLP import Blockchain.SHA import Blockchain.Util newtype Address = Address Word160 deriving (Show, Eq, Ord) instance Pretty Address where pretty (Address x) = yellow $ text $ padZeros 40 $ showHex x "" instance Binary Address where put (Address x) = sequence_ $ fmap put $ word160ToBytes $ fromIntegral x get = do bytes <- replicateM 20 get let byteString = B.pack bytes return (Address $ fromInteger $ byteString2Integer byteString) prvKey2Address::PrvKey->Address prvKey2Address prvKey = Address $ fromInteger $ byteString2Integer $ C.hash 256 $ BL.toStrict $ encode x `BL.append` encode y --B16.encode $ hash 256 $ BL.toStrict $ encode x `BL.append` encode y where PubKey point = derivePubKey prvKey x = fromMaybe (error "getX failed in prvKey2Address") $ getX point y = fromMaybe (error "getY failed in prvKey2Address") $ getY point pubKey2Address::PubKey->Address pubKey2Address (PubKey point) = Address $ fromInteger $ byteString2Integer $ C.hash 256 $ BL.toStrict $ encode x `BL.append` encode y --B16.encode $ hash 256 $ BL.toStrict $ encode x `BL.append` encode y where x = fromMaybe (error "getX failed in prvKey2Address") $ getX point y = fromMaybe (error "getY failed in prvKey2Address") $ getY point pubKey2Address (PubKeyU _) = error "Missing case in pubKey2Address: PubKeyU" instance RLPSerializable Address where rlpEncode (Address a) = RLPString $ BLC.unpack $ encode a rlpDecode (RLPString s) = Address $ decode $ BLC.pack s rlpDecode x = error ("Malformed rlp object sent to rlp2Address: " ++ show x) getNewAddress_unsafe::Address->Integer->Address getNewAddress_unsafe a n = let theHash = hash $ rlpSerialize $ RLPArray [rlpEncode a, rlpEncode n] in decode $ BL.drop 12 $ encode theHash
jamshidh/ethereum-data-leveldb
src/Blockchain/Data/Address.hs
bsd-3-clause
2,317
0
12
395
687
361
326
48
1
module Test where test :: Int -> IO () test n = case n + 3 of 0 -> putStrLn "0 case" 1 -> putStrLn "1 case" _ -> putStrLn "default case"
hecrj/haskell-format
test/specs/case-of-multiline-target/input.hs
bsd-3-clause
146
0
8
41
61
30
31
7
3
{-# LANGUAGE ScopedTypeVariables #-} module Handler.Test where import ClassyPrelude import Util testHandler :: Handler a b testHandler = do State numb <- getState liftIO $ print (asString "ok1") u <- db getFirstUser [Single a] <- db get4 lucid $ h1_ [] $ do toS (asString "ok") toS numb toS (asInt a) where get4 :: Req [Single Int] get4 = rawSql "select 2 + ?" [toPersistValue (2::Int)] getFirstUser :: Req (Maybe (Entity User)) getFirstUser = selectFirst [] [Desc UserEmail]
rvion/ride
web-playground/src/Handler/Test.hs
bsd-3-clause
552
0
12
154
202
97
105
18
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module Debug where import qualified Data.ByteString.Char8 as B import Data.Monoid ((<>)) -- Debugging. Instrument fns w/ log output to see what's happening. -- IMPORTANT!!! Must be absolute path. debugFile ∷ FilePath debugFile = "/tmp/tagFS.log" dbg ∷ String → IO () dbg msg = B.appendFile debugFile (B.pack msg <> "\n")
marklar/TagFS
src/Debug.hs
bsd-3-clause
430
0
9
94
80
48
32
9
1
{-# LANGUAGE TypeOperators #-} module Data.Rope.Annotation.Product ( (:*:)(..) , fstF , sndF ) where import Control.Applicative hiding (empty) import Data.Monoid (mappend) import Data.Foldable (Foldable, foldMap) import Data.Traversable (Traversable(traverse)) import Data.Rope.Annotation infixr 5 :*: -- | A 'Rope' 'Annotation' product. data (f :*: g) a = f a :*: g a fstF :: (f :*: g) a -> f a fstF ~(f :*: _) = f sndF :: (f :*: g) a -> g a sndF ~(_ :*: g) = g instance (Functor f, Functor g) => Functor (f :*: g) where fmap f (a :*: b) = fmap f a :*: fmap f b instance (Applicative f, Applicative g) => Applicative (f :*: g) where pure a = pure a :*: pure a (f :*: g) <*> (a :*: b) = (f <*> a) :*: (g <*> b) instance (Foldable f, Foldable g) => Foldable (f :*: g) where foldMap f (a :*: b) = foldMap f a `mappend` foldMap f b instance (Traversable f, Traversable g) => Traversable (f :*: g) where traverse f (a :*: b) = (:*:) <$> traverse f a <*> traverse f b instance (MonoidalAnn f, MonoidalAnn g) => MonoidalAnn (f :*: g) where emptyAnn = emptyAnn :*: emptyAnn appendAnn r (a :*: a') s (b :*: b') = appendAnn r a s b :*: appendAnn r a' s b' instance (PackableAnn f, PackableAnn g) => PackableAnn (f :*: g) where packAnn r = packAnn r :*: packAnn r snocAnn r n (f :*: g) = snocAnn r n f :*: snocAnn r n g consAnn n r (f :*: g) = consAnn n r f :*: consAnn n r g instance (BreakableAnn f, BreakableAnn g) => BreakableAnn (f :*: g) where dropAnn n r (f :*: g) = dropAnn n r f :*: dropAnn n r g takeAnn n r (f :*: g) = takeAnn n r f :*: takeAnn n r g splitAtAnn n r (f :*: g) = (f' :*: g' , f'' :*: g'') where (f',f'') = splitAtAnn n r f (g',g'') = splitAtAnn n r g
ekmett/rope
Data/Rope/Annotation/Product.hs
bsd-3-clause
1,779
53
9
458
886
475
411
39
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeOperators #-} module Drive.Browser.Types ( BrowserF (..) , Url (..) , SupportsBrowser , browserToDescribeI , execBrowser ) where import qualified Control.Monad.IO.Class as IOC import qualified Data.Text as Text import qualified Drive as D import qualified Drive.Browser.Commands as C import qualified Test.WebDriver.Class as W.Cl import Data.Aeson import Data.Functor (($>)) import Data.Monoid ((<>)) import Data.Text (Text) import Drive.Browser.Ref import Drive.Describe newtype Url = Url String deriving instance Show Url deriving instance Eq Url deriving instance ToJSON Url data BrowserF a = GoToUrl Url a | Refresh a | ReadTitle (Text -> a) | ClickOn Ref a | Clear Ref a | SendText Ref Text a | PressEnter Ref a | ReadText Ref (Text -> a) | Sleep Int a deriving (Functor) instance (Show a) => Show (BrowserF a) where show (GoToUrl u a) = "GoToUrl (" ++ show u ++ ") " ++ show a show _ = undefined instance (Eq a) => Eq (BrowserF a) where (==) (GoToUrl u1 a1) (GoToUrl u2 a2) = (u1 == u2) && (a1 == a2) (==) _ _ = undefined instance (ToJSON a) => ToJSON (BrowserF a) where toJSON = undefined browserToDescribeI :: BrowserF a -> DescribeP a browserToDescribeI (GoToUrl (Url u) a) = logGoToUrl u $> a browserToDescribeI (Refresh a) = logRefresh $> a browserToDescribeI (ReadTitle a) = logReadTitle $> a "some page title" browserToDescribeI (ClickOn r a) = logClick r $> a browserToDescribeI (Clear r a) = logClear r $> a browserToDescribeI (SendText r t a) = logSendText r t $> a browserToDescribeI (PressEnter r a) = logPressEnter r $> a browserToDescribeI (ReadText r a) = logReadText r $> a "from read text" browserToDescribeI (Sleep n a) = logSleep n $> a logGoToUrl :: String -> D.Free DescribeF () logGoToUrl u = verbose ("open (" <> Text.pack u <> ")") logRefresh :: D.Free DescribeF () logRefresh = verbose "refresh" logReadTitle :: D.Free DescribeF () logReadTitle = verbose "read page title" logClick :: Ref -> D.Free DescribeF () logClick r = verbose ("click (" <> showRef r <> ")") logClear :: Ref -> D.Free DescribeF () logClear r = verbose ("clear (" <> showRef r <> ")") logSendText :: Ref -> Text -> D.Free DescribeF () logSendText r t = verbose ("sendtext (" <> showRef r <> ", " <> t <> ")") logPressEnter :: Ref -> D.Free DescribeF () logPressEnter r = verbose ("pressenter (" <> showRef r <> ")") logReadText :: Ref -> D.Free DescribeF () logReadText r = verbose ("readtext (" <> showRef r <> ")") logSleep :: Int -> D.Free DescribeF () logSleep n = warn ("sleep (" <> Text.pack (show n) <> ")") type SupportsBrowser m = (W.Cl.WebDriver m, IOC.MonadIO m) execBrowser :: (SupportsBrowser m) => BrowserF a -> m a execBrowser (GoToUrl (Url u) a) = a <$ C.openPage u execBrowser (Refresh a) = a <$ C.refresh execBrowser (ReadTitle a) = a <$> C.readTitle execBrowser (ClickOn r a) = a <$ C.click r execBrowser (Clear r a) = a <$ C.clear r execBrowser (SendText r t a) = a <$ C.sendKeys r t execBrowser (PressEnter r a) = a <$ C.pressEnter r execBrowser (ReadText r a) = a <$> C.getText r execBrowser (Sleep n a) = a <$ C.delay n
palf/free-driver
packages/drive-browser/lib/Drive/Browser/Types.hs
bsd-3-clause
3,768
0
11
1,014
1,297
679
618
97
1
{-# LANGUAGE TypeFamilies, FlexibleInstances #-} module Main where import Graphics.ChalkBoard.O import Graphics.ChalkBoard --import Graphics.ChalkBoard.O.Internals import qualified Graphics.ChalkBoard.Font as Font import Numeric import Data.Boolean import Data.Char {- test choose = x (x . (x `ss` choose)) ss f g x = f . (g x) {- test2 :: a -> O (a -> a -> Bool -> a) test2 x = x (x (x choose)) -} test2 a b = pure choose <*> a <*> b x :: (O a -> O b) -> O (a -> b) x = undefined test4 = x (x . (x .) . choose) test5 = xdot (xdot xdot .) (choose) choose4 :: O a -> O a -> O a -> O Int -> O a choose4 = undefined test6 f = xdot (xdot (xdot xdot .) .) choose4 test7 f = x ((xdot (xdot xdot .) .) choose4) class F x where type Fx x collect :: x -> Fx x instance F (O a) where type Fx (O a) = O a instance F b => F (O a -> b) where type Fx (O a -> b) = O (a -> Fx b) xx :: (b -> O b1) -> (O a -> b) -> O (a -> b1) xx f g = x (f . g) xdot :: (a -> O a1 -> O b) -> a -> O (a1 -> b) xdot f g = x (f g) xx2 :: (b -> O b1) -> (O a -> b) -> O (a -> b1) xx2 f g = xdot (f .) g mx :: (t -> t1 -> O a -> O b) -> t -> t1 -> O (a -> b) mx c f g = x (f `c` g) mx2 :: (t -> O a -> O b) -> t -> O (a -> b) mx2 c f = x (c f) --test3 choose = xdot (xdot (xdot choose)) instance Functor O where {} instance Applicative O where {} -} main = do font <- Font.initFont "../../Arial.ttf" 0 let (w,h) = (800,600) startChalkBoard [BoardSize w h] $ \ cb -> main2 cb font 0.03 (w,h) main2 cb font sz (w,h) = do sp <- Font.lineSpacing font sz --print sp (title,titleSP) <- Font.label font sz ("Logistics of Moving Satellites in Space") --print titleSP (point1, sp1) <- Font.label font (0.5*sz) ([chr 0x25cf] ++ " KU supplied 4 ''binaries'', one for each problem.") (point2, sp2) <- Font.label font (0.5*sz) ([chr 0x25cf] ++ " We also provided specification of small virtual machine, to run these binaries.") (point3, sp3) <- Font.label font (0.5*sz) ([chr 0x25cf] ++ " Contestants write the VM, then interact with the virtual actuators and sensors.") --" Contestants write the VM, then interact with virtual actuators to fire rockets " ++ -- "and virtual sensors to detect location in orbit.") (point4, sp4) <- Font.label font (0.5*sz) ([chr 0x25cf] ++ " Contestants upload an audit trail of what actuator fires when.") (point5, sp5) <- Font.label font (0.5*sz) ([chr 0x25cf] ++ " We replay these on our local VM, validate the score, and update a leader board.") (point6, sp6) <- Font.label font (0.5*sz) ([chr 0x25cf] ++ " At the end of the contest, teams upload their final source files.") (point7, sp7) <- Font.label font (0.5*sz) ([chr 0x25cf] ++ " We further evaluate and validate the top 10 scoring entries to determine the winners.") --} --let over2 a b = over b a let slide = mix black white <$> ( (makeTitle (w,h) titleSP title) `over` (makeBullets (w,h) sp sp1 [point1, point2, point3, point4, point5, point6, point7]) ) let scaling = (fromIntegral h) / (fromIntegral w) scaledSlide = if (w > h) then scaleXY (scaling,1) $ slide else scaleXY (1,1.0/scaling) $ slide drawChalkBoard cb scaledSlide writeChalkBoard cb "testFont1.jpeg" exitChalkBoard cb makeTitle :: (Int,Int) -> Float -> Board UI -> Board UI makeTitle (wboard,hboard) size lbl = scale (0.9) $ move (-0.5015,0.45) $ scale (1/size) $ lbl makeBullets :: (Int,Int) -> Float -> Float -> [Board UI] -> Board UI makeBullets (w,h) sp size lbls = makeBullets_ (w,h) sp size lbls 0 makeBullets_ :: (Int,Int) -> Float -> Float -> [Board UI] -> Int -> Board UI makeBullets_ (_,_) _ _ [] _ = (boardOf 0) makeBullets_ (w,h) sp size (lbl:lbls) lines = (makeBullet (w,h) sp size lines lbl) `over` (makeBullets_ (w,h) sp size lbls (lines+1)) makeBullet :: (Int,Int) -> Float -> Float -> Int -> Board UI -> Board UI makeBullet (w,h) sp size lines lbl = if (w > h) then move (-(1-fontSize)/2-(1-scaling)/2,0) $ scale (fontSize) $ move (-0.5015,spacing) $ scale (1/size) $ lbl else move (-(1-fontSize)/2,0) $ scale (fontSize) $ move (-0.5015,spacing) $ scale (1/size) $ lbl where fontSize = 0.6 spacing = 0.25 - (fromIntegral lines)*perLine perLine = (fromIntegral h)/sp*6/(fromIntegral h)--(sp)/(fromIntegral h) scaling = (fromIntegral h) / (fromIntegral w) {- \begin{frame}[fragile] \frametitle{Logistics of Moving Satellites in Space} \begin{itemize} \item KU supplied 4 ``binaries'', one for each problem. \item We also provided specification of small virtual machine, to run these binaries. \item Contestants write the VM, and interact with virtual actuators, to fire rockets, and virtual sensors, to detect location in orbit. \item Contestants upload an audit trail of what actuator fires when. \item We replay these on our local VM, and validate the score, and update a leader board. \item At the end of the contest, teams upload their source files. \item Only looking at top 10, to determine the winners. \end{itemize} \end{frame} -}
andygill/chalkboard2
tests/font1/Main.hs
bsd-3-clause
5,783
28
19
1,822
1,255
688
567
48
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} module Snap.Snaplet.ReCaptcha.Example ( -- * Main main , initSample -- * Necessities , sampleTemplate -- * Implementation , initBlog ) where import qualified Blaze.ByteString.Builder as Blaze import Heist import Heist.Compiled import Snap import Snap.Snaplet.Heist.Compiled import Snap.Snaplet.ReCaptcha import Control.Lens import qualified Data.ByteString.Char8 as BS import Data.Monoid import Data.Text (Text) -- | Simple sample snaplet, built using 'ReCaptcha' in order to demonstrate how -- one might use it in the scenario of adding comments to a blog. data Sample = Sample { _recaptcha :: !(Snaplet ReCaptcha) , _heist :: !(Snaplet (Heist Sample)) , _blog :: !(Snaplet Blog) } -- | Not actually a blog data Blog = Blog { _currentPost :: !(Maybe BS.ByteString) } makeLenses ''Sample makeLenses ''Blog instance HasReCaptcha Sample where captchaLens = subSnaplet recaptcha instance HasHeist Sample where heistLens = subSnaplet heist -- | A "blog" snaplet which reads hypothetical "posts" by their 'id', routing -- GET on \/posts\/:id to display a post, and POST on \/posts\/:id to add a -- comment to them. For loose, useless definitions of "post" and "comment" - -- this snaplet is only for demonstration purposes. initBlog :: forall b. (HasReCaptcha b, HasHeist b) => Snaplet (Heist b) -> SnapletInit b Blog initBlog heist = makeSnaplet "blog" "simple blog" Nothing $ do me <- getLens addRoutes -- Hypothetical comments are just sent as POST to the respective post they -- are replying to [("/posts/:id", method GET displayPost <|> method POST commentOnPost)] addConfig heist $ mempty &~ do -- Just 'blog-post' to be whatever is in 'post' at the time -- (hopefully set by 'displayPost' after being routed to /posts/:id) scCompiledSplices .= ("blog-post" ## pureSplice Blaze.fromByteString . lift $ do post' <- withTop' me (use currentPost) case post' of Just post -> return post Nothing -> fail "Couldn't find that.") return (Blog Nothing) where displayPost :: Handler b Blog () displayPost = do Just postId <- getParam "id" currentPost .= Just ("there is no post #" <> postId <> ". only me.") render "recaptcha-example" <|> fail "Couldn't load recaptcha-example.tpl" commentOnPost :: Handler b Blog () commentOnPost = do Just postId <- getParam "id" Just captcha <- getPostParam "g-recaptcha-response" checkCaptcha <|> fail "Bad captcha response." -- if we reach here, the captcha was OK Just name <- getPostParam "name" Just email <- getPostParam "email" Just content <- getPostParam "content" writeBS $ BS.concat [postId, " < (", name,", ", email, ", ", content, ")"] -- | Heist template, written to $PWD\/snaplets\/heist\/recaptcha-example.tpl -- -- >sampleTemplate ≈ -- > <html> -- > <head> -- > <recaptcha-script /> -- > </head> -- > <body> -- > <form method='POST'> -- > <input type='text' name='name' placeholder='Name'> -- > <input type='text' name='email' placeholder='Email'> -- > <br> -- > <textarea class='field' name='content' rows='20' placeholder='Content'></textarea> -- > <br> -- > <recaptcha-div /> -- > <input type='submit' value='Comment'> -- > </form> -- > </body> -- > </html> -- sampleTemplate :: Text sampleTemplate = "<html>\ \ <head>\ \ <recaptcha-script />\ \ </head>\ \ <body>\ \ <form method='POST'>\ \ <input type='text' name='name' placeholder='Name'>\ \ <input type='text' name='email' placeholder='Email'>\ \ <br>\ \ <textarea class='field' name='content' rows='20' placeholder='Content'></textarea>\ \ <br>\ \ <recaptcha-div />\ \ <input type='submit' value='Comment'>\ \ </form>\ \ </body>\ \</html>" -- | Requires 'snaplets/heist/templates/sample.tpl' - a suggested version of which -- is available in this module as 'sampleTemplate'. -- -- This simple asks for your site and private key through stdin. initSample :: SnapletInit Sample Sample initSample = makeSnaplet "sample" "" Nothing $ do h <- nestSnaplet "heist" heist (heistInit "templates") c <- nestSnaplet "submit" recaptcha (initReCaptcha (Just h)) t <- nestSnaplet "blog" blog (initBlog h) return (Sample c h t) -- | @ 'main' = 'serveSnaplet' 'defaultConfig' 'initSample' @ -- -- You can load this into GHCi and run it, with full logging to stdout/stderr -- -- >>> :main --verbose --access-log= --error-log= main :: IO () main = serveSnaplet defaultConfig initSample
lpeterse/snaplet-recaptcha
src/Snap/Snaplet/ReCaptcha/Example.hs
bsd-3-clause
4,933
0
19
1,135
792
419
373
-1
-1
{-+ Some definitions to support type annotations and the dictionary translation for base language declarations (the D structure). -} module TiDinst where import Maybe(isJust) import HsDeclStruct import HsDeclMaps(mapDI) import HsGuardsStruct(HsRhs(..)) import HasBaseStruct import SubstituteBaseStruct import Substitute import TI hiding (Subst) import TiDkc(Dinst) import MUtils(( # )) instance (Types i e,Types i p,Types i ds) => Types i (Dinst i e p ds) where tmap f = mapDI id (tmap f) (tmap f) (tmap f) f (map f) id instance (HasId i p,HasCoreSyntax i p) => HasAbstr i (Dinst i e p ds) where abstract [] d = d abstract xs d = case d of HsFunBind s matches -> HsFunBind s (abstract xs matches) HsPatBind s p rhs ds -> case isVar p of Just x -> HsFunBind s [abstract xs (HsMatch s x [] rhs ds)] _ -> error (show s++": Bug in TiD.hs: tried to overload a pattern binding.") _ -> d -- HsPrimitiveTypeDecl s cntxt nm -> -- HsPrimitiveBind s nm t -> instance (HasBaseStruct d (Dinst i e p ds),HasCoreSyntax i p,HasDef ds d, Eq i,FreeNames i e,FreeNames i ds,FreeNames i p, HasId i e,MapExp e ds,Subst i e, AddDeclsType i ds) => HasLocalDef i e (Dinst i e p ds) where letvar x@(i:>:_) e d = case d of HsFunBind s matches -> HsFunBind s (letvar x e matches) HsPatBind s p rhs ds -> if in_p || HsVar i `elem` freeVars (rhs,ds) then if in_p || not is_id then -- No substitution in patterns yet (for overloaded literals) HsPatBind s p rhs (appendDef (letvarD s x e) ds) else esubst1 var e i d else d where in_p = HsVar i `elem` freeVars p is_id = isJust (isId e) _ -> d -- !! instance HasCoreSyntax i p => HasAbstr i (HsMatchI i e p ds) where abstract xs (HsMatch s n ps rhs ds) = HsMatch s n (map var xs++ps) rhs ds instance (HasBaseStruct d (Dinst i e p ds),HasCoreSyntax i p,HasDef ds d, Eq i,FreeNames i e,FreeNames i ds,FreeNames i p, HasId i e,MapExp e ds,Subst i e, AddDeclsType i ds) => HasLocalDef i e (HsMatchI i e p ds) where letvar x@(i:>:_) e m@(HsMatch s n ps rhs ds) = if in_p || HsVar i `elem` freeVars (rhs,ds) then if in_p || not is_id then m' -- No substitution in patterns yet (for overloaded literals) else esubst1 var e i m else m where m' = HsMatch s n ps rhs (appendDef (letvarD s x e) ds) in_p = HsVar i `elem` freeVars ps is_id = isJust (isId e) letvarD s (x:>:t) e = addDeclsType ([],[HsVar x:>:mono t]) $ oneDef (hsSimpleBind s x e) hsSimpleBind s x e = hsSimpleBind' s x e noDef hsSimpleBind' s x e = hsPatBind s (var x) (HsBody e)
forste/haReFork
tools/base/TI/TiDinst.hs
bsd-3-clause
2,724
28
18
736
1,122
583
539
-1
-1
module Main where import Assembler import CodeGenerator import System.Environment(getArgs) main :: IO () main = do xs <- getArgs if length xs /= 2 then putStrLn "Usage: scheme2luac-exe INPUT_FILE OUTPUT_FILE" else parseAndWrite (head xs) (head $ tail xs)
adamrk/scheme2luac
app/Main.hs
bsd-3-clause
270
0
11
53
84
44
40
10
2
{-# OPTIONS_GHC -fno-cse #-} {-# OPTIONS_GHC -fno-full-laziness #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE BangPatterns #-} module Trace( clearTrace , traceNames , CanBeTraced , traceValues , trace , traceSample , forceSignal ) where import Common(HasDoubleRepresentation(..)) import System.IO.Unsafe import qualified Data.Map as M import Data.IORef import Control.Applicative((<$>)) import Signal(Signal,mapS,fromListS,takeS) import Fixed(Resolution(..)) import Statistics.Sample.KernelDensity import qualified Data.Vector.Unboxed as U import Viewer import Plot import Graphics.PDF import Displayable import Internal import Control.DeepSeq import Text.Printf import qualified Graphics.PDF as PDF import qualified Debug.Trace as T debug a = T.trace (show a) a data CanBeTraced = forall a. (HasDoubleRepresentation a,Resolution a) => CBT !a instance HasDoubleRepresentation CanBeTraced where toDouble (CBT a) = toDouble a fromDouble = error "Can't create a CanBeTraced from a double" instance Resolution CanBeTraced where smallestValue (CBT a) = CBT (smallestValue a) maxValue (CBT a) = CBT (maxValue a) minValue (CBT a) = CBT (minValue a) signedFormat (CBT a) = signedFormat a bitWidth (CBT a) = bitWidth a {-# NOINLINE globalTrace #-} globalTrace :: IORef (M.Map String [CanBeTraced]) globalTrace = unsafePerformIO $ newIORef (M.empty) clearTrace :: IO () clearTrace = writeIORef globalTrace M.empty traceNames :: IO [String] traceNames = M.keys <$> (readIORef globalTrace) getTrace :: String -> IO (Maybe [CanBeTraced]) getTrace name = M.lookup name <$> (readIORef globalTrace) removeZeroAndLog :: [Double] -> [Double] -> ([Double],[Double]) removeZeroAndLog a b = unzip . map (\(t,x) -> (t, log x)) . filter ((> 0) . snd ) . zip a $ b traceValues :: String -> IO () traceValues s = do let statStyle = LabelStyle 10 Centered PDF.S r <- getTrace s case r of Nothing -> return () Just l -> do let h = head l sm = toDouble (smallestValue h) mi = toDouble (minValue h) ma = toDouble (maxValue h) triplePartition ta tb !la !lb !lc [] = (la,lb,lc) triplePartition ta tb !la !lb !lc (a:h) | ta a = triplePartition ta tb (a:la) lb lc h | tb a = triplePartition ta tb la (a:lb) lc h | otherwise = triplePartition ta tb la lb (a:lc) h (negatives, nulls, positives) = triplePartition (<0) (==0) [] [] [] (map toDouble l) positiveSat | null positives = 0 :: Double | otherwise = 100*fromIntegral (length (filter (== ma) positives)) / fromIntegral (length positives) negativeSat | null negatives = 0 :: Double | otherwise = 100*fromIntegral (length (filter (== mi) negatives)) / fromIntegral (length negatives) nullValues | null nulls = 0 :: Double | otherwise = 100*fromIntegral (length nulls) / fromIntegral (length l) drawHist bmi bma l h label theTitle = do let targetLine wi hi (ptF,_) = do withNewContext $ do strokeColor $ Rgb 1.0 0.8 0.8 let start = (log bma) - (log bmi) (xa :+ ya) = ptF ((log bmi),(-start)) (xb :+ yb) = ptF ((log bma),0) stroke $ Line xa ya xb yb tickv mav mbv = map (\t -> (fromIntegral t)/(fromIntegral 10)*(mbv-mav) + mav) ([0..10] :: [Int]) tickh _ _ = let mav = log bmi mbv = log bma in map (\t -> (fromIntegral t)/(fromIntegral 10)*(mbv-mav) + mav) ([0..10] :: [Int]) plotStyle = (defaultPlotStyle { title = theTitle , verticalLabel = Just "Log density" , horizontalLabel = Just $ "Log amplitude (" ++ label ++ ")" , horizontalTickValues = tickh , verticalTickValues = tickv , epilog = targetLine , axis = False , horizontalBounds = Just (log bmi, log bma) }) if null l then do (\_ -> \_ -> return (R Nothing Nothing), \_ -> \_ -> \_ -> return ()) else do let (t,p) = kde_ 32 (log bmi) (log bma) (U.fromList (map log l)) lt' = U.toList t lp' = let templ = U.toList p s = sum templ in map (/ s) templ (lt,lp) = removeZeroAndLog lt' lp' let r = (log bma - log bmi) / fromIntegral (length lp) drawing $ discreteSignalsWithStyle (length lt) plotStyle [ AS (fromListS 0 lp)] let (wi,he) = (\(x,y) -> (fromIntegral x, fromIntegral y)) $ viewerSize if (signedFormat h) then do let posD = drawHist sm ma positives (he / 2 - 10) "pos" (Just "Log density of log amplitude") negD = drawHist sm (-mi) (map negate negatives) (he / 2 - 10) "neg" Nothing pict = Pair posD negD $ \pos -> \neg -> do withNewContext $ do applyMatrix $ translate (0 :+ (he/2 + 10)) pos withNewContext $ do neg drawStringLabel statStyle ((printf "negative max: %2.3f %%" negativeSat) :: String) (leftMargin defaultPlotStyle + (wi / 4.0)) (he / 2 - 10) 100 20 drawStringLabel statStyle ((printf "nulls: %2.3f %%" nullValues) :: String) (leftMargin defaultPlotStyle + (2.0*wi/4.0)) (he/2 - 10) 100 20 drawStringLabel statStyle ((printf "positive max: %2.3f %%" positiveSat) :: String) (leftMargin defaultPlotStyle + (3.0*wi/4.0)) (he/2 - 10) 100 20 display pict else do let dD = drawHist sm ma positives (he - 40) "unsigned" (Just "Log density of log amplitude") pict = Mono dD $ \d -> do withNewContext $ do applyMatrix $ translate (0 :+ 40) d drawStringLabel statStyle ((printf "nulls: %2.3f %%" nullValues) :: String) (leftMargin defaultPlotStyle + wi / 3.0) 10 100 20 drawStringLabel statStyle ((printf "positive max: %2.3f %%" positiveSat) :: String) (leftMargin defaultPlotStyle + (2*wi/3.0)) 10 100 20 display pict {-# NOINLINE traceSample #-} traceSample :: (HasDoubleRepresentation a, Resolution a) => String -> a -> a traceSample s a = unsafePerformIO $ do nv <- M.insertWith' (++) s [CBT a] <$> (readIORef globalTrace) writeIORef globalTrace nv return a {-# NOINLINE trace #-} trace :: (HasDoubleRepresentation a, Resolution a) => String -> Signal a -> Signal a trace s = mapS (traceSample s) {-# NOINLINE myTake #-} myTake :: NFData a => Int -> [a] -> [a] myTake 0 l = [] myTake i (h:l) = h:myTake (i-1) l myTake _ [] = [] {-# NOINLINE forceSignal #-} forceSignal :: (NFData a, Show a) => Int -> Signal a -> IO () forceSignal i (Signal s) = do let l = myTake i s l `deepseq` return ()
alpheccar/Signal
Trace.hs
bsd-3-clause
8,932
0
32
3,981
2,655
1,369
1,286
165
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeOperators #-} module Api.User where import Control.Monad.Except import Control.Monad.Reader (ReaderT, runReaderT) import Control.Monad.Reader.Class import Data.Int (Int64) import Database.Persist.Postgresql (Entity (..), fromSqlKey, insert, get, selectFirst, selectList, (==.)) import Network.Wai (Application) import Servant import Config (App (..), Config (..)) import Models type UserAPI = "users" :> Get '[JSON] [Entity User] :<|> "users" :> Capture "userId" (Key User) :> Get '[JSON] (User) :<|> "users" :> ReqBody '[JSON] User :> Post '[JSON] Int64 -- | The server that runs the UserAPI userServer :: ServerT UserAPI App userServer = allUsers :<|> singleUser :<|> createUser -- | Returns all users in the database. allUsers :: App [Entity User] allUsers = runDb (selectList [] []) -- | Returns a user by name or throws a 404 error. singleUser :: Key User -> App (User) singleUser userId = do maybeUser <- runDb (get userId) case maybeUser of Nothing -> throwError err404 Just person -> return person -- | Creates a user in the database. createUser :: User -> App Int64 createUser p = do newUser <- runDb (insert (User (userName p) (userEmail p))) return $ fromSqlKey newUser
Fisbang/fisbang-api
src/Api/User.hs
bsd-3-clause
1,586
0
14
506
407
222
185
35
2
module CacheDNS.Cache.AtomicLRU ( AtomicLRU , newAtomicLRU , fromList , toList , maxSize , insert , lookup , delete , pop , size , modifyAtomicLRU , modifyAtomicLRU' ) where import Prelude hiding ( lookup ) import CacheDNS.Cache.LRU.Atomic
DavidAlphaFox/CacheDNS
src/CacheDNS/Cache/AtomicLRU.hs
bsd-3-clause
294
0
5
90
61
41
20
15
0
{-# LANGUAGE OverloadedStrings #-} module Main where import Lucid as L import qualified Data.Text.Lazy.IO as T main :: IO () main = T.putStrLn . renderText $ do htmlBody htmlBody :: Html () htmlBody = do doctype_ h2_ $ h2_ "hoeg" return ()
kiripon/gh-pages
templates-hs/default.hs
bsd-3-clause
250
0
8
52
84
46
38
12
1
{-# LANGUAGE DeriveDataTypeable #-} module Main where import System.Environment (getArgs, withArgs) import System.Time import Data.Version (showVersion) import Network.HostName import Text.Twine import qualified Data.ByteString as BS import System.Console.CmdArgs import Paths_kif_parser import Text.KIF import Text.KIF.Parser data Params = Params { output :: OutputType, configuration :: String, file :: FilePath } deriving (Show, Data, Typeable) data OutputType = JUnit | Markdown | JSON deriving (Show, Data, Typeable) params :: Params params = Params { configuration = "" &= help "An optional text that is displayed as the test description", output = JUnit &= argPos 0, file = def &= typ "FILE" &= argPos 1 } getParams :: IO Params getParams = cmdArgs $ params &= program "kif-parser" &= versionArg [explicit, name "version", name "v", summary summaryText] &= summary summaryText &= details ["Process Keep It Functional log files"] summaryText :: String summaryText = "kif-parser " ++ showVersion version ++ ", Jan Christiansen" main :: IO () main = do args <- getArgs params <- (if null args then withArgs ["--help"] else id) getParams case output params of JUnit -> readKIF (file params) >>= kifToJUnit (configuration params) >>= BS.putStr Markdown -> readKIF (file params) >>= kifToMarkdown (configuration params) >>= BS.putStr JSON -> readKIF (file params) >>= kifToJSON (configuration params) >>= BS.putStr kifToJUnit :: String -> KIFTest -> IO BS.ByteString kifToJUnit config kifTest = do timeStamp <- getClockTime hostName <- getHostName context <- makeContext $ do "configuration" =: config "timeStamp" =: show timeStamp "hostName" =: hostName "test" =: mapStrings escapeXML kifTest filePath <- getDataFileName "templates/junit.tmpl" evalTemplate filePath context escapeXML :: String -> String escapeXML = concatMap esc where esc c = case c of '"' -> "&quot;" '\'' -> "&apos;" '<' -> "&lt;" '>' -> "&gt;" '&' -> "&amp;" _ -> [c] kifToMarkdown :: String -> KIFTest -> IO BS.ByteString kifToMarkdown config kifTest = do context <- makeContext $ do "configuration" =: config "test" =: kifTest filePath <- getDataFileName "templates/markdown.tmpl" evalTemplate filePath context kifToJSON :: String -> KIFTest -> IO BS.ByteString kifToJSON config kifTest = do context <- makeContext $ do "configuration" =: escapeJSON config "test" =: mapStrings escapeJSON kifTest filePath <- getDataFileName "templates/json.tmpl" evalTemplate filePath context escapeJSON :: String -> String escapeJSON str = "\"" ++ concatMap esc str ++ "\"" where esc c = case c of '"' -> "\\\"" '\\' -> "\\\\" '/' -> "\\/" '\NUL' -> "\\u0000" '\SOH' -> "\\u0001" '\STX' -> "\\u0002" '\ETX' -> "\\u0003" '\EOT' -> "\\u0004" '\ENQ' -> "\\u0005" '\ACK' -> "\\u0006" '\a' -> "\\u0007" '\b' -> "\\b" '\t' -> "\\t" '\n' -> "\\n" '\v' -> "\\u000b" '\f' -> "\\f" '\r' -> "\\r" '\SO' -> "\\u000e" '\SI' -> "\\u000f" '\DLE' -> "\\u0010" '\DC1' -> "\\u0011" '\DC2' -> "\\u0012" '\DC3' -> "\\u0013" '\DC4' -> "\\u0014" '\NAK' -> "\\u0015" '\SYN' -> "\\u0016" '\ETB' -> "\\u0017" '\CAN' -> "\\u0018" '\EM' -> "\\u0019" '\SUB' -> "\\u001a" '\ESC' -> "\\u001b" '\FS' -> "\\u001c" '\GS' -> "\\u001d" '\RS' -> "\\u001e" '\US' -> "\\u001f" '\DEL' -> "\\u007f" _ -> [c]
plancalculus/kif-parser
Main.hs
bsd-3-clause
3,752
0
14
1,008
1,049
526
523
117
37
module LLVM.VisualizeGraph ( OutputType(..), visualizeGraph ) where import GHC.Conc ( getNumCapabilities ) import Control.Arrow import Control.Concurrent.ParallelIO.Local import Control.Monad ( when ) import qualified Data.ByteString as BS import Data.GraphViz import Data.Maybe ( isNothing ) import System.Directory import System.FilePath import System.FilePath.Glob import Paths_llvm_tools import LLVM.Analysis import LLVM.Analysis.Util.Testing ( buildModule ) import LLVM.Parse ( defaultParserOptions, parseLLVMFile ) import LLVM.HtmlWrapper import LLVM.SvgInspection data OutputType = CanvasOutput GraphvizCanvas | FileOutput GraphvizOutput | HtmlOutput deriving (Show) -- | Visualize a graph-based analysis with graphviz. It handles many -- common options including both file and canvas output. visualizeGraph :: (ToGraphviz a) => FilePath -- ^ Input file name -> Maybe FilePath -- ^ Output file name -> OutputType -- ^ Type of output requested -> [String] -- ^ Module optimization flags -> (Module -> [(String, a)]) -- ^ A function to turn a Module into some graphs -> IO () visualizeGraph inFile outFile fmt optOptions fromModule = do let p = parseLLVMFile defaultParserOptions m <- buildModule [] optOptions p inFile let gs = fromModule m case fmt of HtmlOutput -> do when (isNothing outFile) $ ioError $ userError "Output directory not specified" -- Make a directory for all of the output and render each graph -- with graphviz to svg format. For each svg, create an html -- wrapper page (with an index page). The html page should be simple -- and just embed the SVG and load svgpan (and maybe jquery) let Just outFile' = outFile gdir = outFile' </> "graphs" createDirectoryIfMissing True gdir let jsAndCss = [ "OpenLayers.js" , "jquery-1.7.1.js" , "showGraph.js" , "graph.css" ] mapM_ (installStaticFile gdir) jsAndCss installStaticSubdir "img" gdir caps <- getNumCapabilities let actions = map (makeFunctionPage toGraphviz gdir) gs withPool caps $ \capPool -> parallel_ capPool actions writeHtmlIndex outFile' (map fst gs) -- If we are showing canvases, ignore function names CanvasOutput o -> mapM_ (\(_,g) -> runGraphvizCanvas' (toGraphviz g) o) gs FileOutput o -> do when (isNothing outFile) $ ioError $ userError "Output file not specified" let Just outFile' = outFile case gs of [(_, g)] -> runGraphviz (toGraphviz g) o outFile' >> return () _ -> do -- If we have more than one function, put all of them in -- the given directory createDirectoryIfMissing True outFile' mapM_ (writeDotGraph toGraphviz outFile' o) gs installStaticFile :: FilePath -> FilePath -> IO () installStaticFile dir name = do file <- getDataFileName ("share" </> name) copyFile file (dir </> name) -- | Install all of the files in the given subdir of the datadir to a -- destdir. The subdir is created (this is basically cp -R). installStaticSubdir :: FilePath -> FilePath -> IO () installStaticSubdir sdir destdir = do dd <- getDataDir let patt = dd </> "share" </> sdir </> "*" files <- namesMatching patt let toDest f = destdir </> sdir </> takeFileName f let namesAndDests = map (id &&& toDest) files createDirectoryIfMissing True (destdir </> sdir) mapM_ (uncurry copyFile) namesAndDests makeFunctionPage :: (PrintDotRepr dg n) => (a -> dg n) -> FilePath -> (FilePath, a) -> IO () makeFunctionPage toGraph gdir (fname, g) = do let svgname = gdir </> gfilename dg = toGraph g -- Use the more general graphvizWithHandle so that we can read the -- generated image before writing it to disk. This lets us extract -- its dimensions. The other alternative is to just use the default -- graphviz to create a file and then read the file - this led to -- races when writing with multiple threads. This approach is -- safer. dims <- graphvizWithHandle (commandFor dg) dg Svg $ \h -> do svgContent <- BS.hGetContents h BS.writeFile svgname svgContent return (getSvgSize svgContent) let Just (w, h) = dims writeHtmlWrapper gdir hfilename gfilename fname w h where gfilename = fname <.> "svg" hfilename = fname <.> "html" writeDotGraph :: (PrintDotRepr dg n) => (a -> dg n) -> FilePath -> GraphvizOutput -> (FilePath, a) -> IO () writeDotGraph toGraph dirname o (funcName, g) = runGraphviz (toGraph g) o filename >> return () where filename = dirname </> funcName <.> toExt o toExt :: GraphvizOutput -> String toExt o = case o of Canon -> "dot" XDot {} -> "dot" Eps -> "eps" Fig -> "fig" Jpeg -> "jpg" Pdf -> "pdf" Png -> "png" Ps -> "ps" Ps2 -> "ps" Svg -> "svg" _ -> error $ "Unsupported format: " ++ show o
travitch/llvm-tools
src/LLVM/VisualizeGraph.hs
bsd-3-clause
5,241
0
19
1,471
1,251
636
615
111
11
{-# LANGUAGE ScopedTypeVariables #-} module Data.Picture.Output ( writePbm, savePbm, writePicToProcess, savePic, displayPic ) where import Control.Monad import System.IO import Control.Monad.Primitive import System.Posix.IO import System.Posix.Process import qualified Control.Exception(try, IOException) import Data.Picture.Output.Pbm as X import Data.Picture.Picture -- | Write a 'Picture' to a 'FilePath' in the file format corresponding to the -- file extension of the path. savePic :: FilePath -> Picture RealWorld -> IO () savePic name = writePicToProcess "convert" ["-", name] -- | Display a 'Picture' using Imagemagick displayPic :: Picture RealWorld -> IO () displayPic = writePicToProcess "display" [] -- | Write a 'Picture' to a process writePicToProcess :: FilePath -- ^ name of the executable -> [String] -- ^ arguments -> Picture RealWorld -> IO () writePicToProcess cmd args pic = pOpen cmd args $ writePbm pic pOpen :: FilePath -> [String] -> (Handle -> IO a) -> IO a pOpen fp args func = do pipepair <- createPipe pid <- do p <- Control.Exception.try (forkProcess $ childstuff pipepair) case p of Right x -> return x Left (e :: Control.Exception.IOException) -> fail ("Error in fork: " ++ show e) retval <- callfunc pipepair let rv = seq retval retval void $ getProcessStatus True False pid return rv where callfunc pipepair = do closeFd (fst pipepair) h <- fdToHandle (snd pipepair) x <- func h hClose h return $! x childstuff pipepair = do void $ dupTo (fst pipepair) stdInput closeFd $ fst pipepair closeFd $ snd pipepair executeFile fp True args Nothing
jbaum98/graphics
src/Data/Picture/Output.hs
bsd-3-clause
1,762
0
16
432
505
253
252
47
2
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1996-1998 TcHsSyn: Specialisations of the @HsSyn@ syntax for the typechecker This module is an extension of @HsSyn@ syntax, for use in the type checker. -} {-# LANGUAGE CPP, TupleSections #-} module TcHsSyn ( mkHsConApp, mkHsDictLet, mkHsApp, hsLitType, hsLPatType, hsPatType, mkHsAppTy, mkSimpleHsAlt, nlHsIntLit, shortCutLit, hsOverLitName, conLikeResTy, -- * re-exported from TcMonad TcId, TcIdSet, -- * Zonking -- | For a description of "zonking", see Note [What is zonking?] -- in TcMType zonkTopDecls, zonkTopExpr, zonkTopLExpr, zonkTopBndrs, zonkTyBndrsX, zonkTyBinders, emptyZonkEnv, mkEmptyZonkEnv, zonkTcTypeToType, zonkTcTypeToTypes, zonkTyVarOcc, zonkCoToCo, zonkTcKindToKind, zonkEvBinds, -- * Validity checking checkForRepresentationPolymorphism ) where #include "HsVersions.h" import HsSyn import Id import TcRnMonad import PrelNames import TcType import TcMType import TcEvidence import TysPrim import TysWiredIn import Type import TyCoRep ( TyBinder(..) ) import TyCon import Coercion import ConLike import DataCon import Name import Var import VarSet import VarEnv import DynFlags import Literal import BasicTypes import Maybes import SrcLoc import Bag import Outputable import Util import qualified GHC.LanguageExtensions as LangExt import Control.Monad import Data.List ( partition ) import Control.Arrow ( second ) {- ************************************************************************ * * \subsection[mkFailurePair]{Code for pattern-matching and other failures} * * ************************************************************************ Note: If @hsLPatType@ doesn't bear a strong resemblance to @exprType@, then something is wrong. -} hsLPatType :: OutPat Id -> Type hsLPatType (L _ pat) = hsPatType pat hsPatType :: Pat Id -> Type hsPatType (ParPat pat) = hsLPatType pat hsPatType (WildPat ty) = ty hsPatType (VarPat (L _ var)) = idType var hsPatType (BangPat pat) = hsLPatType pat hsPatType (LazyPat pat) = hsLPatType pat hsPatType (LitPat lit) = hsLitType lit hsPatType (AsPat var _) = idType (unLoc var) hsPatType (ViewPat _ _ ty) = ty hsPatType (ListPat _ ty Nothing) = mkListTy ty hsPatType (ListPat _ _ (Just (ty,_))) = ty hsPatType (PArrPat _ ty) = mkPArrTy ty hsPatType (TuplePat _ bx tys) = mkTupleTy bx tys hsPatType (ConPatOut { pat_con = L _ con, pat_arg_tys = tys }) = conLikeResTy con tys hsPatType (SigPatOut _ ty) = ty hsPatType (NPat _ _ _ ty) = ty hsPatType (NPlusKPat _ _ _ _ _ ty) = ty hsPatType (CoPat _ _ ty) = ty hsPatType p = pprPanic "hsPatType" (ppr p) hsLitType :: HsLit -> TcType hsLitType (HsChar _ _) = charTy hsLitType (HsCharPrim _ _) = charPrimTy hsLitType (HsString _ _) = stringTy hsLitType (HsStringPrim _ _) = addrPrimTy hsLitType (HsInt _ _) = intTy hsLitType (HsIntPrim _ _) = intPrimTy hsLitType (HsWordPrim _ _) = wordPrimTy hsLitType (HsInt64Prim _ _) = int64PrimTy hsLitType (HsWord64Prim _ _) = word64PrimTy hsLitType (HsInteger _ _ ty) = ty hsLitType (HsRat _ ty) = ty hsLitType (HsFloatPrim _) = floatPrimTy hsLitType (HsDoublePrim _) = doublePrimTy -- Overloaded literals. Here mainly because it uses isIntTy etc shortCutLit :: DynFlags -> OverLitVal -> TcType -> Maybe (HsExpr TcId) shortCutLit dflags (HsIntegral src i) ty | isIntTy ty && inIntRange dflags i = Just (HsLit (HsInt src i)) | isWordTy ty && inWordRange dflags i = Just (mkLit wordDataCon (HsWordPrim src i)) | isIntegerTy ty = Just (HsLit (HsInteger src i ty)) | otherwise = shortCutLit dflags (HsFractional (integralFractionalLit i)) ty -- The 'otherwise' case is important -- Consider (3 :: Float). Syntactically it looks like an IntLit, -- so we'll call shortCutIntLit, but of course it's a float -- This can make a big difference for programs with a lot of -- literals, compiled without -O shortCutLit _ (HsFractional f) ty | isFloatTy ty = Just (mkLit floatDataCon (HsFloatPrim f)) | isDoubleTy ty = Just (mkLit doubleDataCon (HsDoublePrim f)) | otherwise = Nothing shortCutLit _ (HsIsString src s) ty | isStringTy ty = Just (HsLit (HsString src s)) | otherwise = Nothing mkLit :: DataCon -> HsLit -> HsExpr Id mkLit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit) ------------------------------ hsOverLitName :: OverLitVal -> Name -- Get the canonical 'fromX' name for a particular OverLitVal hsOverLitName (HsIntegral {}) = fromIntegerName hsOverLitName (HsFractional {}) = fromRationalName hsOverLitName (HsIsString {}) = fromStringName {- ************************************************************************ * * \subsection[BackSubst-HsBinds]{Running a substitution over @HsBinds@} * * ************************************************************************ The rest of the zonking is done *after* typechecking. The main zonking pass runs over the bindings a) to convert TcTyVars to TyVars etc, dereferencing any bindings etc b) convert unbound TcTyVar to Void c) convert each TcId to an Id by zonking its type The type variables are converted by binding mutable tyvars to immutable ones and then zonking as normal. The Ids are converted by binding them in the normal Tc envt; that way we maintain sharing; eg an Id is zonked at its binding site and they all occurrences of that Id point to the common zonked copy It's all pretty boring stuff, because HsSyn is such a large type, and the environment manipulation is tiresome. -} -- Confused by zonking? See Note [What is zonking?] in TcMType. type UnboundTyVarZonker = TcTyVar -> TcM Type -- How to zonk an unbound type variable -- Note [Zonking the LHS of a RULE] -- | A ZonkEnv carries around several bits. -- The UnboundTyVarZonker just zaps unbouned meta-tyvars to Any (as -- defined in zonkTypeZapping), except on the LHS of rules. See -- Note [Zonking the LHS of a RULE]. The (TyCoVarEnv TyVar) and is just -- an optimisation: when binding a tyvar or covar, we zonk the kind right away -- and add a mapping to the env. This prevents re-zonking the kind at -- every occurrence. But this is *just* an optimisation. -- The final (IdEnv Var) optimises zonking for -- Ids. It is knot-tied. We must be careful never to put coercion variables -- (which are Ids, after all) in the knot-tied env, because coercions can -- appear in types, and we sometimes inspect a zonked type in this module. -- -- Confused by zonking? See Note [What is zonking?] in TcMType. data ZonkEnv = ZonkEnv UnboundTyVarZonker (TyCoVarEnv TyVar) (IdEnv Var) -- What variables are in scope -- Maps an Id or EvVar to its zonked version; both have the same Name -- Note that all evidence (coercion variables as well as dictionaries) -- are kept in the ZonkEnv -- Only *type* abstraction is done by side effect -- Is only consulted lazily; hence knot-tying instance Outputable ZonkEnv where ppr (ZonkEnv _ _ty_env var_env) = vcat (map ppr (varEnvElts var_env)) -- The EvBinds have to already be zonked, but that's usually the case. emptyZonkEnv :: ZonkEnv emptyZonkEnv = mkEmptyZonkEnv zonkTypeZapping mkEmptyZonkEnv :: UnboundTyVarZonker -> ZonkEnv mkEmptyZonkEnv zonker = ZonkEnv zonker emptyVarEnv emptyVarEnv -- | Extend the knot-tied environment. extendIdZonkEnvRec :: ZonkEnv -> [Var] -> ZonkEnv extendIdZonkEnvRec (ZonkEnv zonk_ty ty_env id_env) ids -- NB: Don't look at the var to decide which env't to put it in. That -- would end up knot-tying all the env'ts. = ZonkEnv zonk_ty ty_env (extendVarEnvList id_env [(id,id) | id <- ids]) -- Given coercion variables will actually end up here. That's OK though: -- coercion variables are never looked up in the knot-tied env't, so zonking -- them simply doesn't get optimised. No one gets hurt. An improvement (?) -- would be to do SCC analysis in zonkEvBinds and then only knot-tie the -- recursive groups. But perhaps the time it takes to do the analysis is -- more than the savings. extendZonkEnv :: ZonkEnv -> [Var] -> ZonkEnv extendZonkEnv (ZonkEnv zonk_ty tyco_env id_env) vars = ZonkEnv zonk_ty (extendVarEnvList tyco_env [(tv,tv) | tv <- tycovars]) (extendVarEnvList id_env [(id,id) | id <- ids]) where (tycovars, ids) = partition isTyCoVar vars extendIdZonkEnv1 :: ZonkEnv -> Var -> ZonkEnv extendIdZonkEnv1 (ZonkEnv zonk_ty ty_env id_env) id = ZonkEnv zonk_ty ty_env (extendVarEnv id_env id id) extendTyZonkEnv1 :: ZonkEnv -> TyVar -> ZonkEnv extendTyZonkEnv1 (ZonkEnv zonk_ty ty_env id_env) ty = ZonkEnv zonk_ty (extendVarEnv ty_env ty ty) id_env setZonkType :: ZonkEnv -> UnboundTyVarZonker -> ZonkEnv setZonkType (ZonkEnv _ ty_env id_env) zonk_ty = ZonkEnv zonk_ty ty_env id_env zonkEnvIds :: ZonkEnv -> [Id] zonkEnvIds (ZonkEnv _ _ id_env) = varEnvElts id_env zonkIdOcc :: ZonkEnv -> TcId -> Id -- Ids defined in this module should be in the envt; -- ignore others. (Actually, data constructors are also -- not LocalVars, even when locally defined, but that is fine.) -- (Also foreign-imported things aren't currently in the ZonkEnv; -- that's ok because they don't need zonking.) -- -- Actually, Template Haskell works in 'chunks' of declarations, and -- an earlier chunk won't be in the 'env' that the zonking phase -- carries around. Instead it'll be in the tcg_gbl_env, already fully -- zonked. There's no point in looking it up there (except for error -- checking), and it's not conveniently to hand; hence the simple -- 'orElse' case in the LocalVar branch. -- -- Even without template splices, in module Main, the checking of -- 'main' is done as a separate chunk. zonkIdOcc (ZonkEnv _zonk_ty _ty_env id_env) id | isLocalVar id = lookupVarEnv id_env id `orElse` id | otherwise = id zonkIdOccs :: ZonkEnv -> [TcId] -> [Id] zonkIdOccs env ids = map (zonkIdOcc env) ids -- zonkIdBndr is used *after* typechecking to get the Id's type -- to its final form. The TyVarEnv give zonkIdBndr :: ZonkEnv -> TcId -> TcM Id zonkIdBndr env id = do ty' <- zonkTcTypeToType env (idType id) ensureNotRepresentationPolymorphic ty' (text "In the type of binder" <+> quotes (ppr id)) return (setIdType id ty') zonkIdBndrs :: ZonkEnv -> [TcId] -> TcM [Id] zonkIdBndrs env ids = mapM (zonkIdBndr env) ids zonkTopBndrs :: [TcId] -> TcM [Id] zonkTopBndrs ids = zonkIdBndrs emptyZonkEnv ids zonkFieldOcc :: ZonkEnv -> FieldOcc TcId -> TcM (FieldOcc Id) zonkFieldOcc env (FieldOcc lbl sel) = fmap (FieldOcc lbl) $ zonkIdBndr env sel zonkEvBndrsX :: ZonkEnv -> [EvVar] -> TcM (ZonkEnv, [Var]) zonkEvBndrsX = mapAccumLM zonkEvBndrX zonkEvBndrX :: ZonkEnv -> EvVar -> TcM (ZonkEnv, EvVar) -- Works for dictionaries and coercions zonkEvBndrX env var = do { var' <- zonkEvBndr env var ; return (extendZonkEnv env [var'], var') } zonkEvBndr :: ZonkEnv -> EvVar -> TcM EvVar -- Works for dictionaries and coercions -- Does not extend the ZonkEnv zonkEvBndr env var = do { let var_ty = varType var ; ty <- {-# SCC "zonkEvBndr_zonkTcTypeToType" #-} zonkTcTypeToType env var_ty ; return (setVarType var ty) } zonkEvVarOcc :: ZonkEnv -> EvVar -> TcM EvTerm zonkEvVarOcc env v | isCoVar v = EvCoercion <$> zonkCoVarOcc env v | otherwise = return (EvId $ zonkIdOcc env v) zonkTyBndrsX :: ZonkEnv -> [TyVar] -> TcM (ZonkEnv, [TyVar]) zonkTyBndrsX = mapAccumLM zonkTyBndrX zonkTyBndrX :: ZonkEnv -> TyVar -> TcM (ZonkEnv, TyVar) -- This guarantees to return a TyVar (not a TcTyVar) -- then we add it to the envt, so all occurrences are replaced zonkTyBndrX env tv = ASSERT( isImmutableTyVar tv ) do { ki <- zonkTcTypeToType env (tyVarKind tv) -- Internal names tidy up better, for iface files. ; let tv' = mkTyVar (tyVarName tv) ki ; return (extendTyZonkEnv1 env tv', tv') } zonkTyBinders :: ZonkEnv -> [TcTyBinder] -> TcM (ZonkEnv, [TyBinder]) zonkTyBinders = mapAccumLM zonkTyBinder zonkTyBinder :: ZonkEnv -> TcTyBinder -> TcM (ZonkEnv, TyBinder) zonkTyBinder env (Anon ty) = (env, ) <$> (Anon <$> zonkTcTypeToType env ty) zonkTyBinder env (Named tv vis) = do { (env', tv') <- zonkTyBndrX env tv ; return (env', Named tv' vis) } zonkTopExpr :: HsExpr TcId -> TcM (HsExpr Id) zonkTopExpr e = zonkExpr emptyZonkEnv e zonkTopLExpr :: LHsExpr TcId -> TcM (LHsExpr Id) zonkTopLExpr e = zonkLExpr emptyZonkEnv e zonkTopDecls :: Bag EvBind -> LHsBinds TcId -> [LRuleDecl TcId] -> [LVectDecl TcId] -> [LTcSpecPrag] -> [LForeignDecl TcId] -> TcM ([Id], Bag EvBind, LHsBinds Id, [LForeignDecl Id], [LTcSpecPrag], [LRuleDecl Id], [LVectDecl Id]) zonkTopDecls ev_binds binds rules vects imp_specs fords = do { (env1, ev_binds') <- zonkEvBinds emptyZonkEnv ev_binds ; (env2, binds') <- zonkRecMonoBinds env1 binds -- Top level is implicitly recursive ; rules' <- zonkRules env2 rules ; vects' <- zonkVects env2 vects ; specs' <- zonkLTcSpecPrags env2 imp_specs ; fords' <- zonkForeignExports env2 fords ; return (zonkEnvIds env2, ev_binds', binds', fords', specs', rules', vects') } --------------------------------------------- zonkLocalBinds :: ZonkEnv -> HsLocalBinds TcId -> TcM (ZonkEnv, HsLocalBinds Id) zonkLocalBinds env EmptyLocalBinds = return (env, EmptyLocalBinds) zonkLocalBinds _ (HsValBinds (ValBindsIn {})) = panic "zonkLocalBinds" -- Not in typechecker output zonkLocalBinds env (HsValBinds (ValBindsOut binds sigs)) = do { (env1, new_binds) <- go env binds ; return (env1, HsValBinds (ValBindsOut new_binds sigs)) } where go env [] = return (env, []) go env ((r,b):bs) = do { (env1, b') <- zonkRecMonoBinds env b ; (env2, bs') <- go env1 bs ; return (env2, (r,b'):bs') } zonkLocalBinds env (HsIPBinds (IPBinds binds dict_binds)) = do new_binds <- mapM (wrapLocM zonk_ip_bind) binds let env1 = extendIdZonkEnvRec env [ n | L _ (IPBind (Right n) _) <- new_binds] (env2, new_dict_binds) <- zonkTcEvBinds env1 dict_binds return (env2, HsIPBinds (IPBinds new_binds new_dict_binds)) where zonk_ip_bind (IPBind n e) = do n' <- mapIPNameTc (zonkIdBndr env) n e' <- zonkLExpr env e return (IPBind n' e') --------------------------------------------- zonkRecMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (ZonkEnv, LHsBinds Id) zonkRecMonoBinds env binds = fixM (\ ~(_, new_binds) -> do { let env1 = extendIdZonkEnvRec env (collectHsBindsBinders new_binds) ; binds' <- zonkMonoBinds env1 binds ; return (env1, binds') }) --------------------------------------------- zonkMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (LHsBinds Id) zonkMonoBinds env binds = mapBagM (zonk_lbind env) binds zonk_lbind :: ZonkEnv -> LHsBind TcId -> TcM (LHsBind Id) zonk_lbind env = wrapLocM (zonk_bind env) zonk_bind :: ZonkEnv -> HsBind TcId -> TcM (HsBind Id) zonk_bind env bind@(PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty}) = do { (_env, new_pat) <- zonkPat env pat -- Env already extended ; new_grhss <- zonkGRHSs env zonkLExpr grhss ; new_ty <- zonkTcTypeToType env ty ; return (bind { pat_lhs = new_pat, pat_rhs = new_grhss, pat_rhs_ty = new_ty }) } zonk_bind env (VarBind { var_id = var, var_rhs = expr, var_inline = inl }) = do { new_var <- zonkIdBndr env var ; new_expr <- zonkLExpr env expr ; return (VarBind { var_id = new_var, var_rhs = new_expr, var_inline = inl }) } zonk_bind env bind@(FunBind { fun_id = L loc var, fun_matches = ms , fun_co_fn = co_fn }) = do { new_var <- zonkIdBndr env var ; (env1, new_co_fn) <- zonkCoFn env co_fn ; new_ms <- zonkMatchGroup env1 zonkLExpr ms ; return (bind { fun_id = L loc new_var, fun_matches = new_ms , fun_co_fn = new_co_fn }) } zonk_bind env (AbsBinds { abs_tvs = tyvars, abs_ev_vars = evs , abs_ev_binds = ev_binds , abs_exports = exports , abs_binds = val_binds }) = ASSERT( all isImmutableTyVar tyvars ) do { (env0, new_tyvars) <- zonkTyBndrsX env tyvars ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_ev_binds) <- zonkTcEvBinds_s env1 ev_binds ; (new_val_bind, new_exports) <- fixM $ \ ~(new_val_binds, _) -> do { let env3 = extendIdZonkEnvRec env2 (collectHsBindsBinders new_val_binds) ; new_val_binds <- zonkMonoBinds env3 val_binds ; new_exports <- mapM (zonkExport env3) exports ; return (new_val_binds, new_exports) } ; return (AbsBinds { abs_tvs = new_tyvars, abs_ev_vars = new_evs , abs_ev_binds = new_ev_binds , abs_exports = new_exports, abs_binds = new_val_bind }) } where zonkExport env (ABE{ abe_wrap = wrap , abe_poly = poly_id , abe_mono = mono_id, abe_prags = prags }) = do new_poly_id <- zonkIdBndr env poly_id (_, new_wrap) <- zonkCoFn env wrap new_prags <- zonkSpecPrags env prags return (ABE{ abe_wrap = new_wrap , abe_poly = new_poly_id , abe_mono = zonkIdOcc env mono_id , abe_prags = new_prags }) zonk_bind env outer_bind@(AbsBindsSig { abs_tvs = tyvars , abs_ev_vars = evs , abs_sig_export = poly , abs_sig_prags = prags , abs_sig_ev_bind = ev_bind , abs_sig_bind = lbind }) | L bind_loc bind@(FunBind { fun_id = L loc local , fun_matches = ms , fun_co_fn = co_fn }) <- lbind = ASSERT( all isImmutableTyVar tyvars ) do { (env0, new_tyvars) <- zonkTyBndrsX env tyvars ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_ev_bind) <- zonkTcEvBinds env1 ev_bind -- Inline zonk_bind (FunBind ...) because we wish to skip -- the check for representation-polymorphic binders. The -- local binder in the FunBind in an AbsBindsSig is never actually -- bound in Core -- indeed, that's the whole point of AbsBindsSig. -- just calling zonk_bind causes #11405. ; new_local <- updateVarTypeM (zonkTcTypeToType env2) local ; (env3, new_co_fn) <- zonkCoFn env2 co_fn ; new_ms <- zonkMatchGroup env3 zonkLExpr ms -- If there is a representation polymorphism problem, it will -- be caught here: ; new_poly_id <- zonkIdBndr env2 poly ; new_prags <- zonkSpecPrags env2 prags ; let new_val_bind = L bind_loc (bind { fun_id = L loc new_local , fun_matches = new_ms , fun_co_fn = new_co_fn }) ; return (AbsBindsSig { abs_tvs = new_tyvars , abs_ev_vars = new_evs , abs_sig_export = new_poly_id , abs_sig_prags = new_prags , abs_sig_ev_bind = new_ev_bind , abs_sig_bind = new_val_bind }) } | otherwise = pprPanic "zonk_bind" (ppr outer_bind) zonk_bind env (PatSynBind bind@(PSB { psb_id = L loc id , psb_args = details , psb_def = lpat , psb_dir = dir })) = do { id' <- zonkIdBndr env id ; details' <- zonkPatSynDetails env details ; (env1, lpat') <- zonkPat env lpat ; (_env2, dir') <- zonkPatSynDir env1 dir ; return $ PatSynBind $ bind { psb_id = L loc id' , psb_args = details' , psb_def = lpat' , psb_dir = dir' } } zonkPatSynDetails :: ZonkEnv -> HsPatSynDetails (Located TcId) -> TcM (HsPatSynDetails (Located Id)) zonkPatSynDetails env = traverse (wrapLocM $ zonkIdBndr env) zonkPatSynDir :: ZonkEnv -> HsPatSynDir TcId -> TcM (ZonkEnv, HsPatSynDir Id) zonkPatSynDir env Unidirectional = return (env, Unidirectional) zonkPatSynDir env ImplicitBidirectional = return (env, ImplicitBidirectional) zonkPatSynDir env (ExplicitBidirectional mg) = do mg' <- zonkMatchGroup env zonkLExpr mg return (env, ExplicitBidirectional mg') zonkSpecPrags :: ZonkEnv -> TcSpecPrags -> TcM TcSpecPrags zonkSpecPrags _ IsDefaultMethod = return IsDefaultMethod zonkSpecPrags env (SpecPrags ps) = do { ps' <- zonkLTcSpecPrags env ps ; return (SpecPrags ps') } zonkLTcSpecPrags :: ZonkEnv -> [LTcSpecPrag] -> TcM [LTcSpecPrag] zonkLTcSpecPrags env ps = mapM zonk_prag ps where zonk_prag (L loc (SpecPrag id co_fn inl)) = do { (_, co_fn') <- zonkCoFn env co_fn ; return (L loc (SpecPrag (zonkIdOcc env id) co_fn' inl)) } {- ************************************************************************ * * \subsection[BackSubst-Match-GRHSs]{Match and GRHSs} * * ************************************************************************ -} zonkMatchGroup :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> MatchGroup TcId (Located (body TcId)) -> TcM (MatchGroup Id (Located (body Id))) zonkMatchGroup env zBody (MG { mg_alts = L l ms, mg_arg_tys = arg_tys , mg_res_ty = res_ty, mg_origin = origin }) = do { ms' <- mapM (zonkMatch env zBody) ms ; arg_tys' <- zonkTcTypeToTypes env arg_tys ; res_ty' <- zonkTcTypeToType env res_ty ; return (MG { mg_alts = L l ms', mg_arg_tys = arg_tys' , mg_res_ty = res_ty', mg_origin = origin }) } zonkMatch :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> LMatch TcId (Located (body TcId)) -> TcM (LMatch Id (Located (body Id))) zonkMatch env zBody (L loc (Match mf pats _ grhss)) = do { (env1, new_pats) <- zonkPats env pats ; new_grhss <- zonkGRHSs env1 zBody grhss ; return (L loc (Match mf new_pats Nothing new_grhss)) } ------------------------------------------------------------------------- zonkGRHSs :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> GRHSs TcId (Located (body TcId)) -> TcM (GRHSs Id (Located (body Id))) zonkGRHSs env zBody (GRHSs grhss (L l binds)) = do (new_env, new_binds) <- zonkLocalBinds env binds let zonk_grhs (GRHS guarded rhs) = do (env2, new_guarded) <- zonkStmts new_env zonkLExpr guarded new_rhs <- zBody env2 rhs return (GRHS new_guarded new_rhs) new_grhss <- mapM (wrapLocM zonk_grhs) grhss return (GRHSs new_grhss (L l new_binds)) {- ************************************************************************ * * \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr} * * ************************************************************************ -} zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id] zonkLExpr :: ZonkEnv -> LHsExpr TcId -> TcM (LHsExpr Id) zonkExpr :: ZonkEnv -> HsExpr TcId -> TcM (HsExpr Id) zonkLExprs env exprs = mapM (zonkLExpr env) exprs zonkLExpr env expr = wrapLocM (zonkExpr env) expr zonkExpr env (HsVar (L l id)) = return (HsVar (L l (zonkIdOcc env id))) zonkExpr _ (HsIPVar id) = return (HsIPVar id) zonkExpr _ (HsOverLabel l) = return (HsOverLabel l) zonkExpr env (HsLit (HsRat f ty)) = do new_ty <- zonkTcTypeToType env ty return (HsLit (HsRat f new_ty)) zonkExpr _ (HsLit lit) = return (HsLit lit) zonkExpr env (HsOverLit lit) = do { lit' <- zonkOverLit env lit ; return (HsOverLit lit') } zonkExpr env (HsLam matches) = do new_matches <- zonkMatchGroup env zonkLExpr matches return (HsLam new_matches) zonkExpr env (HsLamCase matches) = do new_matches <- zonkMatchGroup env zonkLExpr matches return (HsLamCase new_matches) zonkExpr env (HsApp e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (HsApp new_e1 new_e2) zonkExpr env (HsAppTypeOut e t) = do new_e <- zonkLExpr env e return (HsAppTypeOut new_e t) -- NB: the type is an HsType; can't zonk that! zonkExpr _ e@(HsRnBracketOut _ _) = pprPanic "zonkExpr: HsRnBracketOut" (ppr e) zonkExpr env (HsTcBracketOut body bs) = do bs' <- mapM zonk_b bs return (HsTcBracketOut body bs') where zonk_b (PendingTcSplice n e) = do e' <- zonkLExpr env e return (PendingTcSplice n e') zonkExpr _ (HsSpliceE s) = WARN( True, ppr s ) -- Should not happen return (HsSpliceE s) zonkExpr env (OpApp e1 op fixity e2) = do new_e1 <- zonkLExpr env e1 new_op <- zonkLExpr env op new_e2 <- zonkLExpr env e2 return (OpApp new_e1 new_op fixity new_e2) zonkExpr env (NegApp expr op) = do (env', new_op) <- zonkSyntaxExpr env op new_expr <- zonkLExpr env' expr return (NegApp new_expr new_op) zonkExpr env (HsPar e) = do new_e <- zonkLExpr env e return (HsPar new_e) zonkExpr env (SectionL expr op) = do new_expr <- zonkLExpr env expr new_op <- zonkLExpr env op return (SectionL new_expr new_op) zonkExpr env (SectionR op expr) = do new_op <- zonkLExpr env op new_expr <- zonkLExpr env expr return (SectionR new_op new_expr) zonkExpr env (ExplicitTuple tup_args boxed) = do { new_tup_args <- mapM zonk_tup_arg tup_args ; return (ExplicitTuple new_tup_args boxed) } where zonk_tup_arg (L l (Present e)) = do { e' <- zonkLExpr env e ; return (L l (Present e')) } zonk_tup_arg (L l (Missing t)) = do { t' <- zonkTcTypeToType env t ; return (L l (Missing t')) } zonkExpr env (HsCase expr ms) = do new_expr <- zonkLExpr env expr new_ms <- zonkMatchGroup env zonkLExpr ms return (HsCase new_expr new_ms) zonkExpr env (HsIf Nothing e1 e2 e3) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_e3 <- zonkLExpr env e3 return (HsIf Nothing new_e1 new_e2 new_e3) zonkExpr env (HsIf (Just fun) e1 e2 e3) = do (env1, new_fun) <- zonkSyntaxExpr env fun new_e1 <- zonkLExpr env1 e1 new_e2 <- zonkLExpr env1 e2 new_e3 <- zonkLExpr env1 e3 return (HsIf (Just new_fun) new_e1 new_e2 new_e3) zonkExpr env (HsMultiIf ty alts) = do { alts' <- mapM (wrapLocM zonk_alt) alts ; ty' <- zonkTcTypeToType env ty ; return $ HsMultiIf ty' alts' } where zonk_alt (GRHS guard expr) = do { (env', guard') <- zonkStmts env zonkLExpr guard ; expr' <- zonkLExpr env' expr ; return $ GRHS guard' expr' } zonkExpr env (HsLet (L l binds) expr) = do (new_env, new_binds) <- zonkLocalBinds env binds new_expr <- zonkLExpr new_env expr return (HsLet (L l new_binds) new_expr) zonkExpr env (HsDo do_or_lc (L l stmts) ty) = do (_, new_stmts) <- zonkStmts env zonkLExpr stmts new_ty <- zonkTcTypeToType env ty return (HsDo do_or_lc (L l new_stmts) new_ty) zonkExpr env (ExplicitList ty wit exprs) = do (env1, new_wit) <- zonkWit env wit new_ty <- zonkTcTypeToType env1 ty new_exprs <- zonkLExprs env1 exprs return (ExplicitList new_ty new_wit new_exprs) where zonkWit env Nothing = return (env, Nothing) zonkWit env (Just fln) = second Just <$> zonkSyntaxExpr env fln zonkExpr env (ExplicitPArr ty exprs) = do new_ty <- zonkTcTypeToType env ty new_exprs <- zonkLExprs env exprs return (ExplicitPArr new_ty new_exprs) zonkExpr env expr@(RecordCon { rcon_con_expr = con_expr, rcon_flds = rbinds }) = do { new_con_expr <- zonkExpr env con_expr ; new_rbinds <- zonkRecFields env rbinds ; return (expr { rcon_con_expr = new_con_expr , rcon_flds = new_rbinds }) } zonkExpr env (RecordUpd { rupd_expr = expr, rupd_flds = rbinds , rupd_cons = cons, rupd_in_tys = in_tys , rupd_out_tys = out_tys, rupd_wrap = req_wrap }) = do { new_expr <- zonkLExpr env expr ; new_in_tys <- mapM (zonkTcTypeToType env) in_tys ; new_out_tys <- mapM (zonkTcTypeToType env) out_tys ; new_rbinds <- zonkRecUpdFields env rbinds ; (_, new_recwrap) <- zonkCoFn env req_wrap ; return (RecordUpd { rupd_expr = new_expr, rupd_flds = new_rbinds , rupd_cons = cons, rupd_in_tys = new_in_tys , rupd_out_tys = new_out_tys, rupd_wrap = new_recwrap }) } zonkExpr env (ExprWithTySigOut e ty) = do { e' <- zonkLExpr env e ; return (ExprWithTySigOut e' ty) } zonkExpr env (ArithSeq expr wit info) = do (env1, new_wit) <- zonkWit env wit new_expr <- zonkExpr env expr new_info <- zonkArithSeq env1 info return (ArithSeq new_expr new_wit new_info) where zonkWit env Nothing = return (env, Nothing) zonkWit env (Just fln) = second Just <$> zonkSyntaxExpr env fln zonkExpr env (PArrSeq expr info) = do new_expr <- zonkExpr env expr new_info <- zonkArithSeq env info return (PArrSeq new_expr new_info) zonkExpr env (HsSCC src lbl expr) = do new_expr <- zonkLExpr env expr return (HsSCC src lbl new_expr) zonkExpr env (HsTickPragma src info srcInfo expr) = do new_expr <- zonkLExpr env expr return (HsTickPragma src info srcInfo new_expr) -- hdaume: core annotations zonkExpr env (HsCoreAnn src lbl expr) = do new_expr <- zonkLExpr env expr return (HsCoreAnn src lbl new_expr) -- arrow notation extensions zonkExpr env (HsProc pat body) = do { (env1, new_pat) <- zonkPat env pat ; new_body <- zonkCmdTop env1 body ; return (HsProc new_pat new_body) } -- StaticPointers extension zonkExpr env (HsStatic expr) = HsStatic <$> zonkLExpr env expr zonkExpr env (HsWrap co_fn expr) = do (env1, new_co_fn) <- zonkCoFn env co_fn new_expr <- zonkExpr env1 expr return (HsWrap new_co_fn new_expr) zonkExpr _ e@(HsUnboundVar {}) = return e zonkExpr _ expr = pprPanic "zonkExpr" (ppr expr) ------------------------------------------------------------------------- {- Note [Skolems in zonkSyntaxExpr] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider rebindable syntax with something like (>>=) :: (forall x. blah) -> (forall y. blah') -> blah'' The x and y become skolems that are in scope when type-checking the arguments to the bind. This means that we must extend the ZonkEnv with these skolems when zonking the arguments to the bind. But the skolems are different between the two arguments, and so we should theoretically carry around different environments to use for the different arguments. However, this becomes a logistical nightmare, especially in dealing with the more exotic Stmt forms. So, we simplify by making the critical assumption that the uniques of the skolems are different. (This assumption is justified by the use of newUnique in TcMType.instSkolTyCoVarX.) Now, we can safely just extend one environment. -} -- See Note [Skolems in zonkSyntaxExpr] zonkSyntaxExpr :: ZonkEnv -> SyntaxExpr TcId -> TcM (ZonkEnv, SyntaxExpr Id) zonkSyntaxExpr env (SyntaxExpr { syn_expr = expr , syn_arg_wraps = arg_wraps , syn_res_wrap = res_wrap }) = do { (env0, res_wrap') <- zonkCoFn env res_wrap ; expr' <- zonkExpr env0 expr ; (env1, arg_wraps') <- mapAccumLM zonkCoFn env0 arg_wraps ; return (env1, SyntaxExpr { syn_expr = expr' , syn_arg_wraps = arg_wraps' , syn_res_wrap = res_wrap' }) } ------------------------------------------------------------------------- zonkLCmd :: ZonkEnv -> LHsCmd TcId -> TcM (LHsCmd Id) zonkCmd :: ZonkEnv -> HsCmd TcId -> TcM (HsCmd Id) zonkLCmd env cmd = wrapLocM (zonkCmd env) cmd zonkCmd env (HsCmdWrap w cmd) = do { (env1, w') <- zonkCoFn env w ; cmd' <- zonkCmd env1 cmd ; return (HsCmdWrap w' cmd') } zonkCmd env (HsCmdArrApp e1 e2 ty ho rl) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_ty <- zonkTcTypeToType env ty return (HsCmdArrApp new_e1 new_e2 new_ty ho rl) zonkCmd env (HsCmdArrForm op fixity args) = do new_op <- zonkLExpr env op new_args <- mapM (zonkCmdTop env) args return (HsCmdArrForm new_op fixity new_args) zonkCmd env (HsCmdApp c e) = do new_c <- zonkLCmd env c new_e <- zonkLExpr env e return (HsCmdApp new_c new_e) zonkCmd env (HsCmdLam matches) = do new_matches <- zonkMatchGroup env zonkLCmd matches return (HsCmdLam new_matches) zonkCmd env (HsCmdPar c) = do new_c <- zonkLCmd env c return (HsCmdPar new_c) zonkCmd env (HsCmdCase expr ms) = do new_expr <- zonkLExpr env expr new_ms <- zonkMatchGroup env zonkLCmd ms return (HsCmdCase new_expr new_ms) zonkCmd env (HsCmdIf eCond ePred cThen cElse) = do { (env1, new_eCond) <- zonkWit env eCond ; new_ePred <- zonkLExpr env1 ePred ; new_cThen <- zonkLCmd env1 cThen ; new_cElse <- zonkLCmd env1 cElse ; return (HsCmdIf new_eCond new_ePred new_cThen new_cElse) } where zonkWit env Nothing = return (env, Nothing) zonkWit env (Just w) = second Just <$> zonkSyntaxExpr env w zonkCmd env (HsCmdLet (L l binds) cmd) = do (new_env, new_binds) <- zonkLocalBinds env binds new_cmd <- zonkLCmd new_env cmd return (HsCmdLet (L l new_binds) new_cmd) zonkCmd env (HsCmdDo (L l stmts) ty) = do (_, new_stmts) <- zonkStmts env zonkLCmd stmts new_ty <- zonkTcTypeToType env ty return (HsCmdDo (L l new_stmts) new_ty) zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id) zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd zonk_cmd_top :: ZonkEnv -> HsCmdTop TcId -> TcM (HsCmdTop Id) zonk_cmd_top env (HsCmdTop cmd stack_tys ty ids) = do new_cmd <- zonkLCmd env cmd new_stack_tys <- zonkTcTypeToType env stack_tys new_ty <- zonkTcTypeToType env ty new_ids <- mapSndM (zonkExpr env) ids return (HsCmdTop new_cmd new_stack_tys new_ty new_ids) ------------------------------------------------------------------------- zonkCoFn :: ZonkEnv -> HsWrapper -> TcM (ZonkEnv, HsWrapper) zonkCoFn env WpHole = return (env, WpHole) zonkCoFn env (WpCompose c1 c2) = do { (env1, c1') <- zonkCoFn env c1 ; (env2, c2') <- zonkCoFn env1 c2 ; return (env2, WpCompose c1' c2') } zonkCoFn env (WpFun c1 c2 t1) = do { (env1, c1') <- zonkCoFn env c1 ; (env2, c2') <- zonkCoFn env1 c2 ; t1' <- zonkTcTypeToType env2 t1 ; return (env2, WpFun c1' c2' t1') } zonkCoFn env (WpCast co) = do { co' <- zonkCoToCo env co ; return (env, WpCast co') } zonkCoFn env (WpEvLam ev) = do { (env', ev') <- zonkEvBndrX env ev ; return (env', WpEvLam ev') } zonkCoFn env (WpEvApp arg) = do { arg' <- zonkEvTerm env arg ; return (env, WpEvApp arg') } zonkCoFn env (WpTyLam tv) = ASSERT( isImmutableTyVar tv ) do { (env', tv') <- zonkTyBndrX env tv ; return (env', WpTyLam tv') } zonkCoFn env (WpTyApp ty) = do { ty' <- zonkTcTypeToType env ty ; return (env, WpTyApp ty') } zonkCoFn env (WpLet bs) = do { (env1, bs') <- zonkTcEvBinds env bs ; return (env1, WpLet bs') } ------------------------------------------------------------------------- zonkOverLit :: ZonkEnv -> HsOverLit TcId -> TcM (HsOverLit Id) zonkOverLit env lit@(OverLit { ol_witness = e, ol_type = ty }) = do { ty' <- zonkTcTypeToType env ty ; e' <- zonkExpr env e ; return (lit { ol_witness = e', ol_type = ty' }) } ------------------------------------------------------------------------- zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id) zonkArithSeq env (From e) = do new_e <- zonkLExpr env e return (From new_e) zonkArithSeq env (FromThen e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (FromThen new_e1 new_e2) zonkArithSeq env (FromTo e1 e2) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 return (FromTo new_e1 new_e2) zonkArithSeq env (FromThenTo e1 e2 e3) = do new_e1 <- zonkLExpr env e1 new_e2 <- zonkLExpr env e2 new_e3 <- zonkLExpr env e3 return (FromThenTo new_e1 new_e2 new_e3) ------------------------------------------------------------------------- zonkStmts :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> [LStmt TcId (Located (body TcId))] -> TcM (ZonkEnv, [LStmt Id (Located (body Id))]) zonkStmts env _ [] = return (env, []) zonkStmts env zBody (s:ss) = do { (env1, s') <- wrapLocSndM (zonkStmt env zBody) s ; (env2, ss') <- zonkStmts env1 zBody ss ; return (env2, s' : ss') } zonkStmt :: ZonkEnv -> (ZonkEnv -> Located (body TcId) -> TcM (Located (body Id))) -> Stmt TcId (Located (body TcId)) -> TcM (ZonkEnv, Stmt Id (Located (body Id))) zonkStmt env _ (ParStmt stmts_w_bndrs mzip_op bind_op bind_ty) = do { (env1, new_bind_op) <- zonkSyntaxExpr env bind_op ; new_bind_ty <- zonkTcTypeToType env1 bind_ty ; new_stmts_w_bndrs <- mapM (zonk_branch env1) stmts_w_bndrs ; let new_binders = [b | ParStmtBlock _ bs _ <- new_stmts_w_bndrs, b <- bs] env2 = extendIdZonkEnvRec env1 new_binders ; new_mzip <- zonkExpr env2 mzip_op ; return (env2, ParStmt new_stmts_w_bndrs new_mzip new_bind_op new_bind_ty) } where zonk_branch env1 (ParStmtBlock stmts bndrs return_op) = do { (env2, new_stmts) <- zonkStmts env1 zonkLExpr stmts ; (env3, new_return) <- zonkSyntaxExpr env2 return_op ; return (ParStmtBlock new_stmts (zonkIdOccs env3 bndrs) new_return) } zonkStmt env zBody (RecStmt { recS_stmts = segStmts, recS_later_ids = lvs, recS_rec_ids = rvs , recS_ret_fn = ret_id, recS_mfix_fn = mfix_id , recS_bind_fn = bind_id, recS_bind_ty = bind_ty , recS_later_rets = later_rets, recS_rec_rets = rec_rets , recS_ret_ty = ret_ty }) = do { (env1, new_bind_id) <- zonkSyntaxExpr env bind_id ; (env2, new_mfix_id) <- zonkSyntaxExpr env1 mfix_id ; (env3, new_ret_id) <- zonkSyntaxExpr env2 ret_id ; new_bind_ty <- zonkTcTypeToType env3 bind_ty ; new_rvs <- zonkIdBndrs env3 rvs ; new_lvs <- zonkIdBndrs env3 lvs ; new_ret_ty <- zonkTcTypeToType env3 ret_ty ; let env4 = extendIdZonkEnvRec env3 new_rvs ; (env5, new_segStmts) <- zonkStmts env4 zBody segStmts -- Zonk the ret-expressions in an envt that -- has the polymorphic bindings in the envt ; new_later_rets <- mapM (zonkExpr env5) later_rets ; new_rec_rets <- mapM (zonkExpr env5) rec_rets ; return (extendIdZonkEnvRec env3 new_lvs, -- Only the lvs are needed RecStmt { recS_stmts = new_segStmts, recS_later_ids = new_lvs , recS_rec_ids = new_rvs, recS_ret_fn = new_ret_id , recS_mfix_fn = new_mfix_id, recS_bind_fn = new_bind_id , recS_bind_ty = new_bind_ty , recS_later_rets = new_later_rets , recS_rec_rets = new_rec_rets, recS_ret_ty = new_ret_ty }) } zonkStmt env zBody (BodyStmt body then_op guard_op ty) = do (env1, new_then_op) <- zonkSyntaxExpr env then_op (env2, new_guard_op) <- zonkSyntaxExpr env1 guard_op new_body <- zBody env2 body new_ty <- zonkTcTypeToType env2 ty return (env2, BodyStmt new_body new_then_op new_guard_op new_ty) zonkStmt env zBody (LastStmt body noret ret_op) = do (env1, new_ret) <- zonkSyntaxExpr env ret_op new_body <- zBody env1 body return (env, LastStmt new_body noret new_ret) zonkStmt env _ (TransStmt { trS_stmts = stmts, trS_bndrs = binderMap , trS_by = by, trS_form = form, trS_using = using , trS_ret = return_op, trS_bind = bind_op , trS_bind_arg_ty = bind_arg_ty , trS_fmap = liftM_op }) = do { ; (env1, bind_op') <- zonkSyntaxExpr env bind_op ; bind_arg_ty' <- zonkTcTypeToType env1 bind_arg_ty ; (env2, stmts') <- zonkStmts env1 zonkLExpr stmts ; by' <- fmapMaybeM (zonkLExpr env2) by ; using' <- zonkLExpr env2 using ; (env3, return_op') <- zonkSyntaxExpr env2 return_op ; binderMap' <- mapM (zonkBinderMapEntry env3) binderMap ; liftM_op' <- zonkExpr env3 liftM_op ; let env3' = extendIdZonkEnvRec env3 (map snd binderMap') ; return (env3', TransStmt { trS_stmts = stmts', trS_bndrs = binderMap' , trS_by = by', trS_form = form, trS_using = using' , trS_ret = return_op', trS_bind = bind_op' , trS_bind_arg_ty = bind_arg_ty' , trS_fmap = liftM_op' }) } where zonkBinderMapEntry env (oldBinder, newBinder) = do let oldBinder' = zonkIdOcc env oldBinder newBinder' <- zonkIdBndr env newBinder return (oldBinder', newBinder') zonkStmt env _ (LetStmt (L l binds)) = do (env1, new_binds) <- zonkLocalBinds env binds return (env1, LetStmt (L l new_binds)) zonkStmt env zBody (BindStmt pat body bind_op fail_op bind_ty) = do { (env1, new_bind) <- zonkSyntaxExpr env bind_op ; new_bind_ty <- zonkTcTypeToType env1 bind_ty ; new_body <- zBody env1 body ; (env2, new_pat) <- zonkPat env1 pat ; (_, new_fail) <- zonkSyntaxExpr env1 fail_op ; return (env2, BindStmt new_pat new_body new_bind new_fail new_bind_ty) } -- Scopes: join > ops (in reverse order) > pats (in forward order) -- > rest of stmts zonkStmt env _zBody (ApplicativeStmt args mb_join body_ty) = do { (env1, new_mb_join) <- zonk_join env mb_join ; (env2, new_args) <- zonk_args env1 args ; new_body_ty <- zonkTcTypeToType env2 body_ty ; return (env2, ApplicativeStmt new_args new_mb_join new_body_ty) } where zonk_join env Nothing = return (env, Nothing) zonk_join env (Just j) = second Just <$> zonkSyntaxExpr env j get_pat (_, ApplicativeArgOne pat _) = pat get_pat (_, ApplicativeArgMany _ _ pat) = pat replace_pat pat (op, ApplicativeArgOne _ a) = (op, ApplicativeArgOne pat a) replace_pat pat (op, ApplicativeArgMany a b _) = (op, ApplicativeArgMany a b pat) zonk_args env args = do { (env1, new_args_rev) <- zonk_args_rev env (reverse args) ; (env2, new_pats) <- zonkPats env1 (map get_pat args) ; return (env2, zipWith replace_pat new_pats (reverse new_args_rev)) } -- these need to go backward, because if any operators are higher-rank, -- later operators may introduce skolems that are in scope for earlier -- arguments zonk_args_rev env ((op, arg) : args) = do { (env1, new_op) <- zonkSyntaxExpr env op ; new_arg <- zonk_arg env1 arg ; (env2, new_args) <- zonk_args_rev env1 args ; return (env2, (new_op, new_arg) : new_args) } zonk_args_rev env [] = return (env, []) zonk_arg env (ApplicativeArgOne pat expr) = do { new_expr <- zonkLExpr env expr ; return (ApplicativeArgOne pat new_expr) } zonk_arg env (ApplicativeArgMany stmts ret pat) = do { (env1, new_stmts) <- zonkStmts env zonkLExpr stmts ; new_ret <- zonkExpr env1 ret ; return (ApplicativeArgMany new_stmts new_ret pat) } ------------------------------------------------------------------------- zonkRecFields :: ZonkEnv -> HsRecordBinds TcId -> TcM (HsRecordBinds TcId) zonkRecFields env (HsRecFields flds dd) = do { flds' <- mapM zonk_rbind flds ; return (HsRecFields flds' dd) } where zonk_rbind (L l fld) = do { new_id <- wrapLocM (zonkFieldOcc env) (hsRecFieldLbl fld) ; new_expr <- zonkLExpr env (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldLbl = new_id , hsRecFieldArg = new_expr })) } zonkRecUpdFields :: ZonkEnv -> [LHsRecUpdField TcId] -> TcM [LHsRecUpdField TcId] zonkRecUpdFields env = mapM zonk_rbind where zonk_rbind (L l fld) = do { new_id <- wrapLocM (zonkFieldOcc env) (hsRecUpdFieldOcc fld) ; new_expr <- zonkLExpr env (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldLbl = fmap ambiguousFieldOcc new_id , hsRecFieldArg = new_expr })) } ------------------------------------------------------------------------- mapIPNameTc :: (a -> TcM b) -> Either (Located HsIPName) a -> TcM (Either (Located HsIPName) b) mapIPNameTc _ (Left x) = return (Left x) mapIPNameTc f (Right x) = do r <- f x return (Right r) {- ************************************************************************ * * \subsection[BackSubst-Pats]{Patterns} * * ************************************************************************ -} zonkPat :: ZonkEnv -> OutPat TcId -> TcM (ZonkEnv, OutPat Id) -- Extend the environment as we go, because it's possible for one -- pattern to bind something that is used in another (inside or -- to the right) zonkPat env pat = wrapLocSndM (zonk_pat env) pat zonk_pat :: ZonkEnv -> Pat TcId -> TcM (ZonkEnv, Pat Id) zonk_pat env (ParPat p) = do { (env', p') <- zonkPat env p ; return (env', ParPat p') } zonk_pat env (WildPat ty) = do { ty' <- zonkTcTypeToType env ty ; ensureNotRepresentationPolymorphic ty' (text "In a wildcard pattern") ; return (env, WildPat ty') } zonk_pat env (VarPat (L l v)) = do { v' <- zonkIdBndr env v ; return (extendIdZonkEnv1 env v', VarPat (L l v')) } zonk_pat env (LazyPat pat) = do { (env', pat') <- zonkPat env pat ; return (env', LazyPat pat') } zonk_pat env (BangPat pat) = do { (env', pat') <- zonkPat env pat ; return (env', BangPat pat') } zonk_pat env (AsPat (L loc v) pat) = do { v' <- zonkIdBndr env v ; (env', pat') <- zonkPat (extendIdZonkEnv1 env v') pat ; return (env', AsPat (L loc v') pat') } zonk_pat env (ViewPat expr pat ty) = do { expr' <- zonkLExpr env expr ; (env', pat') <- zonkPat env pat ; ty' <- zonkTcTypeToType env ty ; return (env', ViewPat expr' pat' ty') } zonk_pat env (ListPat pats ty Nothing) = do { ty' <- zonkTcTypeToType env ty ; (env', pats') <- zonkPats env pats ; return (env', ListPat pats' ty' Nothing) } zonk_pat env (ListPat pats ty (Just (ty2,wit))) = do { (env', wit') <- zonkSyntaxExpr env wit ; ty2' <- zonkTcTypeToType env' ty2 ; ty' <- zonkTcTypeToType env' ty ; (env'', pats') <- zonkPats env' pats ; return (env'', ListPat pats' ty' (Just (ty2',wit'))) } zonk_pat env (PArrPat pats ty) = do { ty' <- zonkTcTypeToType env ty ; (env', pats') <- zonkPats env pats ; return (env', PArrPat pats' ty') } zonk_pat env (TuplePat pats boxed tys) = do { tys' <- mapM (zonkTcTypeToType env) tys ; (env', pats') <- zonkPats env pats ; return (env', TuplePat pats' boxed tys') } zonk_pat env p@(ConPatOut { pat_arg_tys = tys, pat_tvs = tyvars , pat_dicts = evs, pat_binds = binds , pat_args = args, pat_wrap = wrapper }) = ASSERT( all isImmutableTyVar tyvars ) do { new_tys <- mapM (zonkTcTypeToType env) tys ; (env0, new_tyvars) <- zonkTyBndrsX env tyvars -- Must zonk the existential variables, because their -- /kind/ need potential zonking. -- cf typecheck/should_compile/tc221.hs ; (env1, new_evs) <- zonkEvBndrsX env0 evs ; (env2, new_binds) <- zonkTcEvBinds env1 binds ; (env3, new_wrapper) <- zonkCoFn env2 wrapper ; (env', new_args) <- zonkConStuff env3 args ; return (env', p { pat_arg_tys = new_tys, pat_tvs = new_tyvars, pat_dicts = new_evs, pat_binds = new_binds, pat_args = new_args, pat_wrap = new_wrapper}) } zonk_pat env (LitPat lit) = return (env, LitPat lit) zonk_pat env (SigPatOut pat ty) = do { ty' <- zonkTcTypeToType env ty ; (env', pat') <- zonkPat env pat ; return (env', SigPatOut pat' ty') } zonk_pat env (NPat (L l lit) mb_neg eq_expr ty) = do { (env1, eq_expr') <- zonkSyntaxExpr env eq_expr ; (env2, mb_neg') <- case mb_neg of Nothing -> return (env1, Nothing) Just n -> second Just <$> zonkSyntaxExpr env1 n ; lit' <- zonkOverLit env2 lit ; ty' <- zonkTcTypeToType env2 ty ; return (env2, NPat (L l lit') mb_neg' eq_expr' ty') } zonk_pat env (NPlusKPat (L loc n) (L l lit1) lit2 e1 e2 ty) = do { (env1, e1') <- zonkSyntaxExpr env e1 ; (env2, e2') <- zonkSyntaxExpr env1 e2 ; n' <- zonkIdBndr env2 n ; lit1' <- zonkOverLit env2 lit1 ; lit2' <- zonkOverLit env2 lit2 ; ty' <- zonkTcTypeToType env2 ty ; return (extendIdZonkEnv1 env2 n', NPlusKPat (L loc n') (L l lit1') lit2' e1' e2' ty') } zonk_pat env (CoPat co_fn pat ty) = do { (env', co_fn') <- zonkCoFn env co_fn ; (env'', pat') <- zonkPat env' (noLoc pat) ; ty' <- zonkTcTypeToType env'' ty ; return (env'', CoPat co_fn' (unLoc pat') ty') } zonk_pat _ pat = pprPanic "zonk_pat" (ppr pat) --------------------------- zonkConStuff :: ZonkEnv -> HsConDetails (OutPat TcId) (HsRecFields id (OutPat TcId)) -> TcM (ZonkEnv, HsConDetails (OutPat Id) (HsRecFields id (OutPat Id))) zonkConStuff env (PrefixCon pats) = do { (env', pats') <- zonkPats env pats ; return (env', PrefixCon pats') } zonkConStuff env (InfixCon p1 p2) = do { (env1, p1') <- zonkPat env p1 ; (env', p2') <- zonkPat env1 p2 ; return (env', InfixCon p1' p2') } zonkConStuff env (RecCon (HsRecFields rpats dd)) = do { (env', pats') <- zonkPats env (map (hsRecFieldArg . unLoc) rpats) ; let rpats' = zipWith (\(L l rp) p' -> L l (rp { hsRecFieldArg = p' })) rpats pats' ; return (env', RecCon (HsRecFields rpats' dd)) } -- Field selectors have declared types; hence no zonking --------------------------- zonkPats :: ZonkEnv -> [OutPat TcId] -> TcM (ZonkEnv, [OutPat Id]) zonkPats env [] = return (env, []) zonkPats env (pat:pats) = do { (env1, pat') <- zonkPat env pat ; (env', pats') <- zonkPats env1 pats ; return (env', pat':pats') } {- ************************************************************************ * * \subsection[BackSubst-Foreign]{Foreign exports} * * ************************************************************************ -} zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id] zonkForeignExports env ls = mapM (wrapLocM (zonkForeignExport env)) ls zonkForeignExport :: ZonkEnv -> ForeignDecl TcId -> TcM (ForeignDecl Id) zonkForeignExport env (ForeignExport { fd_name = i, fd_co = co, fd_fe = spec }) = return (ForeignExport { fd_name = fmap (zonkIdOcc env) i , fd_sig_ty = undefined, fd_co = co , fd_fe = spec }) zonkForeignExport _ for_imp = return for_imp -- Foreign imports don't need zonking zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id] zonkRules env rs = mapM (wrapLocM (zonkRule env)) rs zonkRule :: ZonkEnv -> RuleDecl TcId -> TcM (RuleDecl Id) zonkRule env (HsRule name act (vars{-::[RuleBndr TcId]-}) lhs fv_lhs rhs fv_rhs) = do { unbound_tkv_set <- newMutVar emptyVarSet ; let kind_var_set = identify_kind_vars vars env_rule = setZonkType env (zonkTvCollecting kind_var_set unbound_tkv_set) -- See Note [Zonking the LHS of a RULE] ; (env_inside, new_bndrs) <- mapAccumLM zonk_bndr env_rule vars ; new_lhs <- zonkLExpr env_inside lhs ; new_rhs <- zonkLExpr env_inside rhs ; unbound_tkvs <- readMutVar unbound_tkv_set ; let final_bndrs :: [LRuleBndr Var] final_bndrs = map (noLoc . RuleBndr . noLoc) (varSetElemsWellScoped unbound_tkvs) ++ new_bndrs ; return $ HsRule name act final_bndrs new_lhs fv_lhs new_rhs fv_rhs } where zonk_bndr env (L l (RuleBndr (L loc v))) = do { (env', v') <- zonk_it env v ; return (env', L l (RuleBndr (L loc v'))) } zonk_bndr _ (L _ (RuleBndrSig {})) = panic "zonk_bndr RuleBndrSig" zonk_it env v | isId v = do { v' <- zonkIdBndr env v ; return (extendIdZonkEnvRec env [v'], v') } | otherwise = ASSERT( isImmutableTyVar v) zonkTyBndrX env v -- DV: used to be return (env,v) but that is plain -- wrong because we may need to go inside the kind -- of v and zonk there! -- returns the set of type variables mentioned in the kind of another -- type. This is used only when -XPolyKinds is not set. identify_kind_vars :: [LRuleBndr TcId] -> TyVarSet identify_kind_vars rule_bndrs = let vars = map strip_rulebndr rule_bndrs in unionVarSets (map (\v -> if isTyVar v then tyCoVarsOfType (tyVarKind v) else emptyVarSet) vars) strip_rulebndr (L _ (RuleBndr (L _ v))) = v strip_rulebndr (L _ (RuleBndrSig {})) = panic "strip_rulebndr zonkRule" zonkVects :: ZonkEnv -> [LVectDecl TcId] -> TcM [LVectDecl Id] zonkVects env = mapM (wrapLocM (zonkVect env)) zonkVect :: ZonkEnv -> VectDecl TcId -> TcM (VectDecl Id) zonkVect env (HsVect s v e) = do { v' <- wrapLocM (zonkIdBndr env) v ; e' <- zonkLExpr env e ; return $ HsVect s v' e' } zonkVect env (HsNoVect s v) = do { v' <- wrapLocM (zonkIdBndr env) v ; return $ HsNoVect s v' } zonkVect _env (HsVectTypeOut s t rt) = return $ HsVectTypeOut s t rt zonkVect _ (HsVectTypeIn _ _ _ _) = panic "TcHsSyn.zonkVect: HsVectTypeIn" zonkVect _env (HsVectClassOut c) = return $ HsVectClassOut c zonkVect _ (HsVectClassIn _ _) = panic "TcHsSyn.zonkVect: HsVectClassIn" zonkVect _env (HsVectInstOut i) = return $ HsVectInstOut i zonkVect _ (HsVectInstIn _) = panic "TcHsSyn.zonkVect: HsVectInstIn" {- ************************************************************************ * * Constraints and evidence * * ************************************************************************ -} zonkEvTerm :: ZonkEnv -> EvTerm -> TcM EvTerm zonkEvTerm env (EvId v) = ASSERT2( isId v, ppr v ) zonkEvVarOcc env v zonkEvTerm env (EvCoercion co) = do { co' <- zonkCoToCo env co ; return (EvCoercion co') } zonkEvTerm env (EvCast tm co) = do { tm' <- zonkEvTerm env tm ; co' <- zonkCoToCo env co ; return (mkEvCast tm' co') } zonkEvTerm _ (EvLit l) = return (EvLit l) zonkEvTerm env (EvTypeable ty ev) = do { ev' <- zonkEvTypeable env ev ; ty' <- zonkTcTypeToType env ty ; return (EvTypeable ty' ev') } zonkEvTerm env (EvCallStack cs) = case cs of EvCsEmpty -> return (EvCallStack cs) EvCsPushCall n l tm -> do { tm' <- zonkEvTerm env tm ; return (EvCallStack (EvCsPushCall n l tm')) } zonkEvTerm env (EvSuperClass d n) = do { d' <- zonkEvTerm env d ; return (EvSuperClass d' n) } zonkEvTerm env (EvDFunApp df tys tms) = do { tys' <- zonkTcTypeToTypes env tys ; tms' <- mapM (zonkEvTerm env) tms ; return (EvDFunApp (zonkIdOcc env df) tys' tms') } zonkEvTerm env (EvDelayedError ty msg) = do { ty' <- zonkTcTypeToType env ty ; return (EvDelayedError ty' msg) } zonkEvTypeable :: ZonkEnv -> EvTypeable -> TcM EvTypeable zonkEvTypeable env (EvTypeableTyCon ts) = do { ts' <- mapM (zonkEvTerm env) ts ; return $ EvTypeableTyCon ts' } zonkEvTypeable env (EvTypeableTyApp t1 t2) = do { t1' <- zonkEvTerm env t1 ; t2' <- zonkEvTerm env t2 ; return (EvTypeableTyApp t1' t2') } zonkEvTypeable env (EvTypeableTyLit t1) = do { t1' <- zonkEvTerm env t1 ; return (EvTypeableTyLit t1') } zonkTcEvBinds_s :: ZonkEnv -> [TcEvBinds] -> TcM (ZonkEnv, [TcEvBinds]) zonkTcEvBinds_s env bs = do { (env, bs') <- mapAccumLM zonk_tc_ev_binds env bs ; return (env, [EvBinds (unionManyBags bs')]) } zonkTcEvBinds :: ZonkEnv -> TcEvBinds -> TcM (ZonkEnv, TcEvBinds) zonkTcEvBinds env bs = do { (env', bs') <- zonk_tc_ev_binds env bs ; return (env', EvBinds bs') } zonk_tc_ev_binds :: ZonkEnv -> TcEvBinds -> TcM (ZonkEnv, Bag EvBind) zonk_tc_ev_binds env (TcEvBinds var) = zonkEvBindsVar env var zonk_tc_ev_binds env (EvBinds bs) = zonkEvBinds env bs zonkEvBindsVar :: ZonkEnv -> EvBindsVar -> TcM (ZonkEnv, Bag EvBind) zonkEvBindsVar env (EvBindsVar ref _) = do { bs <- readMutVar ref ; zonkEvBinds env (evBindMapBinds bs) } zonkEvBinds :: ZonkEnv -> Bag EvBind -> TcM (ZonkEnv, Bag EvBind) zonkEvBinds env binds = {-# SCC "zonkEvBinds" #-} fixM (\ ~( _, new_binds) -> do { let env1 = extendIdZonkEnvRec env (collect_ev_bndrs new_binds) ; binds' <- mapBagM (zonkEvBind env1) binds ; return (env1, binds') }) where collect_ev_bndrs :: Bag EvBind -> [EvVar] collect_ev_bndrs = foldrBag add [] add (EvBind { eb_lhs = var }) vars = var : vars zonkEvBind :: ZonkEnv -> EvBind -> TcM EvBind zonkEvBind env bind@(EvBind { eb_lhs = var, eb_rhs = term }) = do { var' <- {-# SCC "zonkEvBndr" #-} zonkEvBndr env var -- Optimise the common case of Refl coercions -- See Note [Optimise coercion zonking] -- This has a very big effect on some programs (eg Trac #5030) ; term' <- case getEqPredTys_maybe (idType var') of Just (r, ty1, ty2) | ty1 `eqType` ty2 -> return (EvCoercion (mkTcReflCo r ty1)) _other -> zonkEvTerm env term ; return (bind { eb_lhs = var', eb_rhs = term' }) } {- ************************************************************************ * * Zonking types * * ************************************************************************ Note [Zonking the LHS of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We need to gather the type variables mentioned on the LHS so we can quantify over them. Example: data T a = C foo :: T a -> Int foo C = 1 {-# RULES "myrule" foo C = 1 #-} After type checking the LHS becomes (foo a (C a)) and we do not want to zap the unbound tyvar 'a' to (), because that limits the applicability of the rule. Instead, we want to quantify over it! It's easiest to get zonkTvCollecting to gather the free tyvars here. Attempts to do so earlier are tiresome, because (a) the data type is big and (b) finding the free type vars of an expression is necessarily monadic operation. (consider /\a -> f @ b, where b is side-effected to a) And that in turn is why ZonkEnv carries the function to use for type variables! Note [Zonking mutable unbound type or kind variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In zonkTypeZapping, we zonk mutable but unbound type or kind variables to an arbitrary type. We know if they are unbound even though we don't carry an environment, because at the binding site for a variable we bind the mutable var to a fresh immutable one. So the mutable store plays the role of an environment. If we come across a mutable variable that isn't so bound, it must be completely free. We zonk the expected kind to make sure we don't get some unbound meta variable as the kind. Note that since we have kind polymorphism, zonk_unbound_tyvar will handle both type and kind variables. Consider the following datatype: data Phantom a = Phantom Int The type of Phantom is (forall (k : *). forall (a : k). Int). Both `a` and `k` are unbound variables. We want to zonk this to (forall (k : Any *). forall (a : Any (Any *)). Int). Note [Optimise coercion zonking] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When optimising evidence binds we may come across situations where a coercion looks like cv = ReflCo ty or cv1 = cv2 where the type 'ty' is big. In such cases it is a waste of time to zonk both * The variable on the LHS * The coercion on the RHS Rather, we can zonk the variable, and if its type is (ty ~ ty), we can just use Refl on the right, ignoring the actual coercion on the RHS. This can have a very big effect, because the constraint solver sometimes does go to a lot of effort to prove Refl! (Eg when solving 10+3 = 10+3; cf Trac #5030) -} zonkTyVarOcc :: ZonkEnv -> TyVar -> TcM TcType zonkTyVarOcc env@(ZonkEnv zonk_unbound_tyvar tv_env _) tv | isTcTyVar tv = case tcTyVarDetails tv of SkolemTv {} -> lookup_in_env RuntimeUnk {} -> lookup_in_env FlatSkol ty -> zonkTcTypeToType env ty MetaTv { mtv_ref = ref } -> do { cts <- readMutVar ref ; case cts of Flexi -> do { kind <- {-# SCC "zonkKind1" #-} zonkTcTypeToType env (tyVarKind tv) ; zonk_unbound_tyvar (setTyVarKind tv kind) } Indirect ty -> do { zty <- zonkTcTypeToType env ty -- Small optimisation: shortern-out indirect steps -- so that the old type may be more easily collected. ; writeMutVar ref (Indirect zty) ; return zty } } | otherwise = lookup_in_env where lookup_in_env -- Look up in the env just as we do for Ids = case lookupVarEnv tv_env tv of Nothing -> mkTyVarTy <$> updateTyVarKindM (zonkTcTypeToType env) tv Just tv' -> return (mkTyVarTy tv') zonkCoVarOcc :: ZonkEnv -> CoVar -> TcM Coercion zonkCoVarOcc env@(ZonkEnv _ tyco_env _) cv | Just cv' <- lookupVarEnv tyco_env cv -- don't look in the knot-tied env = return $ mkCoVarCo cv' | otherwise = mkCoVarCo <$> updateVarTypeM (zonkTcTypeToType env) cv zonkCoHole :: ZonkEnv -> CoercionHole -> Role -> Type -> Type -- these are all redundant with -- the details in the hole, -- unzonked -> TcM Coercion zonkCoHole env h r t1 t2 = do { contents <- unpackCoercionHole_maybe h ; case contents of Just co -> do { co <- zonkCoToCo env co ; checkCoercionHole co h r t1 t2 } -- This next case should happen only in the presence of -- (undeferred) type errors. Originally, I put in a panic -- here, but that caused too many uses of `failIfErrsM`. Nothing -> do { traceTc "Zonking unfilled coercion hole" (ppr h) ; when debugIsOn $ whenNoErrs $ MASSERT2( False , text "Type-correct unfilled coercion hole" <+> ppr h ) ; t1 <- zonkTcTypeToType env t1 ; t2 <- zonkTcTypeToType env t2 ; return $ mkHoleCo h r t1 t2 } } zonk_tycomapper :: TyCoMapper ZonkEnv TcM zonk_tycomapper = TyCoMapper { tcm_smart = True -- Establish type invariants -- See Note [Type-checking inside the knot] in TcHsType , tcm_tyvar = zonkTyVarOcc , tcm_covar = zonkCoVarOcc , tcm_hole = zonkCoHole , tcm_tybinder = \env tv _vis -> zonkTyBndrX env tv } -- Confused by zonking? See Note [What is zonking?] in TcMType. zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type zonkTcTypeToType = mapType zonk_tycomapper zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type] zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys -- | Used during kind-checking in TcTyClsDecls, where it's more convenient -- to keep the binders and result kind separate. zonkTcKindToKind :: [TcTyBinder] -> TcKind -> TcM ([TyBinder], Kind) zonkTcKindToKind binders res_kind = do { (env, binders') <- zonkTyBinders emptyZonkEnv binders ; res_kind' <- zonkTcTypeToType env res_kind ; return (binders', res_kind') } zonkCoToCo :: ZonkEnv -> Coercion -> TcM Coercion zonkCoToCo = mapCoercion zonk_tycomapper zonkTvCollecting :: TyVarSet -> TcRef TyVarSet -> UnboundTyVarZonker -- This variant collects unbound type variables in a mutable variable -- Works on both types and kinds zonkTvCollecting kind_vars unbound_tv_set tv = do { poly_kinds <- xoptM LangExt.PolyKinds ; if tv `elemVarSet` kind_vars && not poly_kinds then defaultKindVar tv else do { ty_or_tv <- zonkQuantifiedTyVarOrType tv ; case ty_or_tv of Right ty -> return ty Left tv' -> do { tv_set <- readMutVar unbound_tv_set ; writeMutVar unbound_tv_set (extendVarSet tv_set tv') ; return (mkTyVarTy tv') } } } zonkTypeZapping :: UnboundTyVarZonker -- This variant is used for everything except the LHS of rules -- It zaps unbound type variables to (), or some other arbitrary type -- Works on both types and kinds zonkTypeZapping tv = do { let ty | isRuntimeRepVar tv = ptrRepLiftedTy | otherwise = anyTypeOfKind (tyVarKind tv) ; writeMetaTyVar tv ty ; return ty } --------------------------------------- {- Note [Unboxed tuples in representation polymorphism check] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Recall that all types that have values (that is, lifted and unlifted types) have kinds that look like (TYPE rep), where (rep :: RuntimeRep) tells how the values are represented at runtime. Lifted types have kind (TYPE PtrRepLifted) (for which * is just a synonym) and, say, Int# has kind (TYPE IntRep). It would be terrible if the code generator came upon a binder of a type whose kind is something like TYPE r, where r is a skolem type variable. The code generator wouldn't know what to do. So we eliminate that case here. Although representation polymorphism and the RuntimeRep type catch most ways of abusing unlifted types, it still isn't quite satisfactory around unboxed tuples. That's because all unboxed tuple types have kind TYPE UnboxedTupleRep, which is clearly a lie: it doesn't actually tell you what the representation is. Naively, when checking for representation polymorphism, you might think we can just look for free variables in a type's RuntimeRep. But this misses the UnboxedTupleRep case. So, instead, we handle unboxed tuples specially. Only after unboxed tuples are handled do we look for free tyvars in a RuntimeRep. We must still be careful in the UnboxedTupleRep case. A binder whose type has kind UnboxedTupleRep is OK -- only as long as the type is really an unboxed tuple, which the code generator treats specially. So we do this: 1. Check if the type is an unboxed tuple. If so, recur. 2. Check if the kind is TYPE UnboxedTupleRep. If so, error. 3. Check if the kind has any free variables. If so, error. In case 1, we have a type that looks like (# , #) PtrRepLifted IntRep Bool Int# recalling that (# , #) :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep). TYPE r1 -> TYPE r2 -> TYPE UnboxedTupleRep It's tempting just to look at the RuntimeRep arguments to make sure that they are devoid of free variables and not UnboxedTupleRep. This naive check, though, fails on nested unboxed tuples, like (# Int#, (# Bool, Void# #) #). Thus, instead of looking at the RuntimeRep args to the unboxed tuple constructor, we look at the types themselves. Here are a few examples: type family F r :: TYPE r x :: (F r :: TYPE r) -- REJECTED: simple representation polymorphism where r is an in-scope type variable of kind RuntimeRep x :: (F PtrRepLifted :: TYPE PtrRepLifted) -- OK x :: (F IntRep :: TYPE IntRep) -- OK x :: (F UnboxedTupleRep :: TYPE UnboxedTupleRep) -- REJECTED x :: ((# Int, Bool #) :: TYPE UnboxedTupleRep) -- OK -} -- | According to the rules around representation polymorphism -- (see https://ghc.haskell.org/trac/ghc/wiki/NoSubKinds), no binder -- can have a representation-polymorphic type. This check ensures -- that we respect this rule. It is a bit regrettable that this error -- occurs in zonking, after which we should have reported all errors. -- But it's hard to see where else to do it, because this can be discovered -- only after all solving is done. And, perhaps most importantly, this -- isn't really a compositional property of a type system, so it's -- not a terrible surprise that the check has to go in an awkward spot. ensureNotRepresentationPolymorphic :: Type -- its zonked type -> SDoc -- where this happened -> TcM () ensureNotRepresentationPolymorphic ty doc = whenNoErrs $ -- sometimes we end up zonking bogus definitions of type -- forall a. a. See, for example, test ghci/scripts/T9140 checkForRepresentationPolymorphism doc ty -- See Note [Unboxed tuples in representation polymorphism check] checkForRepresentationPolymorphism :: SDoc -> Type -> TcM () checkForRepresentationPolymorphism extra ty | Just (tc, tys) <- splitTyConApp_maybe ty , isUnboxedTupleTyCon tc = mapM_ (checkForRepresentationPolymorphism extra) (dropRuntimeRepArgs tys) | runtime_rep `eqType` unboxedTupleRepDataConTy = addErr (vcat [ text "The type" <+> quotes (ppr tidy_ty) <+> text "is not an unboxed tuple," , text "and yet its kind suggests that it has the representation" , text "of an unboxed tuple. This is not allowed." ] $$ extra) | not (isEmptyVarSet (tyCoVarsOfType runtime_rep)) = addErr $ hang (text "A representation-polymorphic type is not allowed here:") 2 (vcat [ text "Type:" <+> ppr tidy_ty , text "Kind:" <+> ppr tidy_ki ]) $$ extra | otherwise = return () where ki = typeKind ty runtime_rep = getRuntimeRepFromKind "check_type" ki (tidy_env, tidy_ty) = tidyOpenType emptyTidyEnv ty tidy_ki = tidyType tidy_env (typeKind ty)
tjakway/ghcjvm
compiler/typecheck/TcHsSyn.hs
bsd-3-clause
73,896
33
20
21,031
19,175
9,736
9,439
-1
-1
{-# LANGUAGE Rank2Types #-} -- | a compatible interface to 'log-warper' -- logging output is directed to 'katip' module Pos.Util.Wlog ( -- * CanLog CanLog (..) , WithLogger -- * Pure logging , dispatchEvents , LogEvent (..) , NamedPureLogger (..) , launchNamedPureLog , runNamedPureLog -- * Setup , setupLogging , setupLogging' , setupTestLogging -- * Logging functions , logDebug , logError , logInfo , logNotice , logWarning , logMessage -- * LoggerName , LoggerName , LoggerNameBox (..) , HasLoggerName (..) , usingLoggerName , addLoggerName , setLoggerName -- * LoggerConfig , LoggerConfig (..) , lcTree , parseLoggerConfig -- * Builders for 'LoggerConfig' , productionB -- * Severity , Severity (..) -- * Saving Changes , retrieveLogContent -- * Logging messages with a condition , logMCond -- * Utility functions , removeAllHandlers , centiUtcTimeF , setLogPrefix , getLinesLogged ) where import Pos.Util.Log (LoggerName, Severity (..)) import Pos.Util.Log.LoggerConfig (LoggerConfig (..), lcTree, parseLoggerConfig, setLogPrefix) import Pos.Util.Wlog.Compatibility (CanLog (..), HasLoggerName (..), LogEvent (..), LoggerNameBox (..), NamedPureLogger (..), WithLogger, addLoggerName, centiUtcTimeF, dispatchEvents, getLinesLogged, launchNamedPureLog, logDebug, logError, logInfo, logMCond, logMessage, logNotice, logWarning, productionB, removeAllHandlers, retrieveLogContent, runNamedPureLog, setLoggerName, setupLogging, setupLogging', setupTestLogging, usingLoggerName)
input-output-hk/pos-haskell-prototype
util/src/Pos/Util/Wlog.hs
mit
2,065
0
6
770
303
211
92
47
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Network.Wai.Handler.Warp.RequestHeader ( parseHeaderLines , parseByteRanges ) where import Control.Exception (throwIO) import Control.Monad (when) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as B (unpack, readInteger) import Data.ByteString.Internal (ByteString(..), memchr) import qualified Data.CaseInsensitive as CI import Data.Word (Word8) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr (Ptr, plusPtr, minusPtr, nullPtr) import Foreign.Storable (peek) import qualified Network.HTTP.Types as H import qualified Network.HTTP.Types.URI as H import Network.Wai.Handler.Warp.Types import qualified Network.HTTP.Types.Header as HH -- $setup -- >>> :set -XOverloadedStrings ---------------------------------------------------------------- parseHeaderLines :: [ByteString] -> IO (H.Method ,ByteString -- Path ,ByteString -- Path, parsed ,ByteString -- Query ,H.HttpVersion ,H.RequestHeaders ) parseHeaderLines [] = throwIO $ NotEnoughLines [] parseHeaderLines (firstLine:otherLines) = do (method, path', query, httpversion) <- parseRequestLine firstLine let path = H.extractPath path' hdr = map parseHeader otherLines return (method, path', path, query, httpversion, hdr) ---------------------------------------------------------------- -- | -- -- >>> parseRequestLine "GET / HTTP/1.1" -- ("GET","/","",HTTP/1.1) -- >>> parseRequestLine "POST /cgi/search.cgi?key=foo HTTP/1.0" -- ("POST","/cgi/search.cgi","?key=foo",HTTP/1.0) -- >>> parseRequestLine "GET " -- *** Exception: Warp: Invalid first line of request: "GET " -- >>> parseRequestLine "GET /NotHTTP UNKNOWN/1.1" -- *** Exception: Warp: Request line specified a non-HTTP request parseRequestLine :: ByteString -> IO (H.Method ,ByteString -- Path ,ByteString -- Query ,H.HttpVersion) parseRequestLine requestLine@(PS fptr off len) = withForeignPtr fptr $ \ptr -> do when (len < 14) $ throwIO baderr let methodptr = ptr `plusPtr` off limptr = methodptr `plusPtr` len lim0 = fromIntegral len pathptr0 <- memchr methodptr 32 lim0 -- ' ' when (pathptr0 == nullPtr || (limptr `minusPtr` pathptr0) < 11) $ throwIO baderr let pathptr = pathptr0 `plusPtr` 1 lim1 = fromIntegral (limptr `minusPtr` pathptr0) httpptr0 <- memchr pathptr 32 lim1 -- ' ' when (httpptr0 == nullPtr || (limptr `minusPtr` httpptr0) < 9) $ throwIO baderr let httpptr = httpptr0 `plusPtr` 1 lim2 = fromIntegral (httpptr0 `minusPtr` pathptr) checkHTTP httpptr !hv <- httpVersion httpptr queryptr <- memchr pathptr 63 lim2 -- '?' let !method = bs ptr methodptr pathptr0 !path | queryptr == nullPtr = bs ptr pathptr httpptr0 | otherwise = bs ptr pathptr queryptr !query | queryptr == nullPtr = S.empty | otherwise = bs ptr queryptr httpptr0 return (method,path,query,hv) where baderr = BadFirstLine $ B.unpack requestLine check :: Ptr Word8 -> Int -> Word8 -> IO () check p n w = do w0 <- peek $ p `plusPtr` n when (w0 /= w) $ throwIO NonHttp checkHTTP httpptr = do check httpptr 0 72 -- 'H' check httpptr 1 84 -- 'T' check httpptr 2 84 -- 'T' check httpptr 3 80 -- 'P' check httpptr 4 47 -- '/' check httpptr 6 46 -- '.' httpVersion httpptr = do major <- peek $ httpptr `plusPtr` 5 minor <- peek $ httpptr `plusPtr` 7 if major == (49 :: Word8) && minor == (49 :: Word8) then return H.http11 else return H.http10 bs ptr p0 p1 = PS fptr o l where o = p0 `minusPtr` ptr l = p1 `minusPtr` p0 ---------------------------------------------------------------- -- | -- -- >>> parseHeader "Content-Length:47" -- ("Content-Length","47") -- >>> parseHeader "Accept-Ranges: bytes" -- ("Accept-Ranges","bytes") -- >>> parseHeader "Host: example.com:8080" -- ("Host","example.com:8080") -- >>> parseHeader "NoSemiColon" -- ("NoSemiColon","") parseHeader :: ByteString -> H.Header parseHeader s = let (k, rest) = S.breakByte 58 s -- ':' rest' = S.dropWhile (\c -> c == 32 || c == 9) $ S.drop 1 rest in (CI.mk k, rest') parseByteRanges :: S.ByteString -> Maybe HH.ByteRanges parseByteRanges bs1 = do bs2 <- stripPrefix "bytes=" bs1 (r, bs3) <- range bs2 ranges (r:) bs3 where range bs2 = case stripPrefix "-" bs2 of Just bs3 -> do (i, bs4) <- B.readInteger bs3 Just (HH.ByteRangeSuffix i, bs4) Nothing -> do (i, bs3) <- B.readInteger bs2 bs4 <- stripPrefix "-" bs3 case B.readInteger bs4 of Nothing -> Just (HH.ByteRangeFrom i, bs4) Just (j, bs5) -> Just (HH.ByteRangeFromTo i j, bs5) ranges front bs3 = case stripPrefix "," bs3 of Nothing -> Just (front []) Just bs4 -> do (r, bs5) <- range bs4 ranges (front . (r:)) bs5 stripPrefix x y | x `S.isPrefixOf` y = Just (S.drop (S.length x) y) | otherwise = Nothing
sol/wai
warp/Network/Wai/Handler/Warp/RequestHeader.hs
mit
5,551
0
18
1,599
1,526
811
715
114
4
{-# LANGUAGE CPP #-} module Main where import PostgREST.App (postgrest) import PostgREST.Config (AppConfig (..), minimumPgVersion, prettyVersion, readOptions) import PostgREST.DbStructure (getDbStructure, getPgVersion) import PostgREST.Error (encodeError) import PostgREST.OpenAPI (isMalformedProxyUri) import PostgREST.Types (DbStructure, Schema, PgVersion(..)) import Protolude hiding (hPutStrLn, replace) import Control.Retry (RetryStatus, capDelay, exponentialBackoff, retrying, rsPreviousDelay) import qualified Data.ByteString as BS import qualified Data.ByteString.Base64 as B64 import Data.IORef (IORef, atomicWriteIORef, newIORef, readIORef) import Data.String (IsString (..)) import Data.Text (pack, replace, stripPrefix, strip) import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Data.Text.IO (hPutStrLn) import qualified Hasql.Pool as P import qualified Hasql.Session as H import Network.Wai.Handler.Warp (defaultSettings, runSettings, setHost, setPort, setServerName, setTimeout) import System.IO (BufferMode (..), hSetBuffering) #ifndef mingw32_HOST_OS import System.Posix.Signals #endif {-| The purpose of this worker is to fill the refDbStructure created in 'main' with the 'DbStructure' returned from calling 'getDbStructure'. This method is meant to be called by multiple times by the same thread, but does nothing if the previous invocation has not terminated. In all cases this method does not halt the calling thread, the work is preformed in a separate thread. Note: 'atomicWriteIORef' is essentially a lazy semaphore that prevents two threads from running 'connectionWorker' at the same time. Background thread that does the following : 1. Tries to connect to pg server and will keep trying until success. 2. Checks if the pg version is supported and if it's not it kills the main program. 3. Obtains the dbStructure. 4. If 2 or 3 fail to give their result it means the connection is down so it goes back to 1, otherwise it finishes his work successfully. -} connectionWorker :: ThreadId -- ^ This thread is killed if pg version is unsupported -> P.Pool -- ^ The PostgreSQL connection pool -> Schema -- ^ Schema PostgREST is serving up -> IORef (Maybe DbStructure) -- ^ mutable reference to 'DbStructure' -> IORef Bool -- ^ Used as a binary Semaphore -> IO () connectionWorker mainTid pool schema refDbStructure refIsWorkerOn = do isWorkerOn <- readIORef refIsWorkerOn unless isWorkerOn $ do atomicWriteIORef refIsWorkerOn True void $ forkIO work where work = do atomicWriteIORef refDbStructure Nothing putStrLn ("Attempting to connect to the database..." :: Text) connected <- connectingSucceeded pool when connected $ do result <- P.use pool $ do actualPgVersion <- getPgVersion unless (actualPgVersion >= minimumPgVersion) $ liftIO $ do hPutStrLn stderr ("Cannot run in this PostgreSQL version, PostgREST needs at least " <> pgvName minimumPgVersion) killThread mainTid dbStructure <- getDbStructure schema actualPgVersion liftIO $ atomicWriteIORef refDbStructure $ Just dbStructure case result of Left e -> do putStrLn ("Failed to query the database. Retrying." :: Text) hPutStrLn stderr (toS $ encodeError e) work Right _ -> do atomicWriteIORef refIsWorkerOn False putStrLn ("Connection successful" :: Text) {-| Used by 'connectionWorker' to check if the provided db-uri lets the application access the PostgreSQL database. This method is used the first time the connection is tested, but only to test before calling 'getDbStructure' inside the 'connectionWorker' method. The connection tries are capped, but if the connection times out no error is thrown, just 'False' is returned. -} connectingSucceeded :: P.Pool -> IO Bool connectingSucceeded pool = retrying (capDelay 32000000 $ exponentialBackoff 1000000) shouldRetry (const $ P.release pool >> isConnectionSuccessful) where isConnectionSuccessful :: IO Bool isConnectionSuccessful = do testConn <- P.use pool $ H.sql "SELECT 1" case testConn of Left e -> hPutStrLn stderr (toS $ encodeError e) >> pure False _ -> pure True shouldRetry :: RetryStatus -> Bool -> IO Bool shouldRetry rs isConnSucc = do delay <- pure $ fromMaybe 0 (rsPreviousDelay rs) `div` 1000000 itShould <- pure $ not isConnSucc when itShould $ putStrLn $ "Attempting to reconnect to the database in " <> (show delay::Text) <> " seconds..." return itShould {-| This is where everything starts. -} main :: IO () main = do -- -- LineBuffering: the entire output buffer is flushed whenever a newline is -- output, the buffer overflows, a hFlush is issued or the handle is closed -- -- NoBuffering: output is written immediately and never stored in the buffer hSetBuffering stdout LineBuffering hSetBuffering stdin LineBuffering hSetBuffering stderr NoBuffering -- -- readOptions builds the 'AppConfig' from the config file specified on the -- command line conf <- loadSecretFile =<< readOptions let host = configHost conf port = configPort conf proxy = configProxyUri conf pgSettings = toS (configDatabase conf) -- is the db-uri appSettings = setHost ((fromString . toS) host) -- Warp settings . setPort port . setServerName (toS $ "postgrest/" <> prettyVersion) . setTimeout 3600 $ defaultSettings -- -- Checks that the provided proxy uri is formated correctly, -- does not test if it works here. when (isMalformedProxyUri $ toS <$> proxy) $ panic "Malformed proxy uri, a correct example: https://example.com:8443/basePath" putStrLn $ ("Listening on port " :: Text) <> show (configPort conf) -- -- create connection pool with the provided settings, returns either -- a 'Connection' or a 'ConnectionError'. Does not throw. pool <- P.acquire (configPool conf, 10, pgSettings) -- -- To be filled in by connectionWorker refDbStructure <- newIORef Nothing -- -- Helper ref to make sure just one connectionWorker can run at a time refIsWorkerOn <- newIORef False -- -- This is passed to the connectionWorker method so it can kill the main -- thread if the PostgreSQL's version is not supported. mainTid <- myThreadId -- -- Sets the refDbStructure connectionWorker mainTid pool (configSchema conf) refDbStructure refIsWorkerOn -- -- Only for systems with signals: -- -- releases the connection pool whenever the program is terminated, -- see issue #268 -- -- Plus the SIGHUP signal updates the internal 'DbStructure' by running -- 'connectionWorker' exactly as before. #ifndef mingw32_HOST_OS forM_ [sigINT, sigTERM] $ \sig -> void $ installHandler sig (Catch $ do P.release pool throwTo mainTid UserInterrupt ) Nothing void $ installHandler sigHUP ( Catch $ connectionWorker mainTid pool (configSchema conf) refDbStructure refIsWorkerOn ) Nothing #endif -- -- run the postgrest application runSettings appSettings $ postgrest conf refDbStructure pool (connectionWorker mainTid pool (configSchema conf) refDbStructure refIsWorkerOn) {-| The purpose of this function is to load the JWT secret from a file if configJwtSecret is actually a filepath and replaces some characters if the JWT is base64 encoded. The reason some characters need to be replaced is because JWT is actually base64url encoded which must be turned into just base64 before decoding. To check if the JWT secret is provided is in fact a file path, it must be decoded as 'Text' to be processed. decodeUtf8: Decode a ByteString containing UTF-8 encoded text that is known to be valid. -} loadSecretFile :: AppConfig -> IO AppConfig loadSecretFile conf = extractAndTransform mSecret where mSecret = decodeUtf8 <$> configJwtSecret conf isB64 = configJwtSecretIsBase64 conf -- -- The Text (variable name secret) here is mSecret from above which is the JWT -- decoded as Utf8 -- -- stripPrefix: Return the suffix of the second string if its prefix matches -- the entire first string. -- -- The configJwtSecret is a filepath instead of the JWT secret itself if the -- secret has @ as its prefix. extractAndTransform :: Maybe Text -> IO AppConfig extractAndTransform Nothing = return conf extractAndTransform (Just secret) = fmap setSecret $ transformString isB64 =<< case stripPrefix "@" secret of Nothing -> return . encodeUtf8 $ secret Just filename -> chomp <$> BS.readFile (toS filename) where chomp bs = fromMaybe bs (BS.stripSuffix "\n" bs) -- -- Turns the Base64url encoded JWT into Base64 transformString :: Bool -> ByteString -> IO ByteString transformString False t = return t transformString True t = case B64.decode $ encodeUtf8 $ strip $ replaceUrlChars $ decodeUtf8 t of Left errMsg -> panic $ pack errMsg Right bs -> return bs setSecret bs = conf {configJwtSecret = Just bs} -- -- replace: Replace every occurrence of one substring with another replaceUrlChars = replace "_" "/" . replace "-" "+" . replace "." "="
ruslantalpa/postgrest
main/Main.hs
mit
10,362
0
22
3,010
1,624
841
783
159
5
module Aar.Lexer.Token where import Text.ParserCombinators.Parsec data Token = TokInt !SourcePos !Integer deriving (Show, Eq)
aar-lang/aar
lib/Aar/Lexer/Token.hs
gpl-3.0
150
0
7
38
37
21
16
8
0
{- Copyright 2019 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. -} program = blank foo = blank
alphalambda/codeworld
codeworld-compiler/test/testcases/indentedDecl/source.hs
apache-2.0
639
2
5
122
19
7
12
-1
-1
{-# LANGUAGE StandaloneDeriving, FlexibleContexts #-} {-# OPTIONS -Wall #-} import Control.Applicative import Data.Foldable import Data.Traversable import Prelude hiding(mapM) data Zero a = Zero a data Succ n a = Succ (n a) a deriving instance (Show a) => Show (Zero a) deriving instance (Show a, Show (n a)) => Show (Succ n a) instance Foldable Zero where foldMap = foldMapDefault instance Functor Zero where fmap = fmapDefault instance Traversable Zero where traverse f (Zero x) = Zero <$> f x instance (Traversable n) => Foldable (Succ n) where foldMap = foldMapDefault instance (Traversable n) => Functor (Succ n) where fmap = fmapDefault instance (Traversable n) => Traversable (Succ n) where traverse f (Succ x y) = Succ <$> traverse f x <*> f y v1 :: Zero Int v1 = Zero 0 v2 :: Succ Zero Int v2 = Succ (Zero 4) 2 v4 :: Succ (Succ (Succ Zero)) Int v4 = Succ (Succ (Succ (Zero 1) 3) 4) 1 main :: IO () main = do print $ v1 print $ v2 print $ v4 _ <- mapM print v4 return ()
nushio3/Paraiso
attic/Traversable/TraversableVector.hs
bsd-3-clause
1,012
4
11
216
468
227
241
35
1
{-# LANGUAGE CPP, RankNTypes #-} {- | Module : GHC.Vis.View.List Copyright : (c) Dennis Felsing License : 3-Clause BSD-style Maintainer : dennis@felsin9.de -} module GHC.Vis.View.List ( export, #ifdef SDL_WINDOW getState, draw, updateBoundingBoxes, #endif redraw, click, move, updateObjects ) where import Graphics.UI.Gtk (PangoRectangle(..), layoutGetExtents, showLayout, PangoLayout(..), WidgetClass(..), widgetGetAllocation, widgetGetDrawWindow, renderWithDrawable, widgetQueueDraw, ascent, layoutSetFontDescription, FontMetrics(..), layoutCopy, layoutSetText, layoutGetContext, fontDescriptionFromString, fontDescriptionSetSize, contextGetLanguage, contextGetMetrics, createLayout) import qualified Graphics.UI.Gtk as Gtk import Graphics.Rendering.Cairo hiding (width, height, x, y) import Control.Concurrent import Control.Monad import Data.IORef import Data.List import System.IO.Unsafe import GHC.Vis.Types hiding (State, View(..)) import GHC.Vis.View.Common import GHC.HeapView (Box) type Rectangle = (Double, Double, Double, Double) data State = State { objects :: [(Box, String, [VisObject])] , bounds :: [(String, Rectangle)] , hover :: Maybe String , totalSize :: Rectangle } type RGB = (Double, Double, Double) state :: IORef State state = unsafePerformIO $ newIORef $ State [] [] Nothing (0, 0, 1, 1) layout' :: IORef (Maybe PangoLayout) layout' = unsafePerformIO $ newIORef Nothing fontName :: String fontName = "Sans" --fontName = "Times Roman" --fontName = "DejaVu Sans" --fontName = "Lucida Grande" fontSize :: Double fontSize = 15 colorName :: RGB colorName = (0.5,1,0.5) colorNameHighlighted :: RGB colorNameHighlighted = (0,1,0) colorLink :: RGB colorLink = (0.5,0.5,1) colorLinkHighlighted :: RGB colorLinkHighlighted = (0.25,0.25,1) colorThunk :: RGB colorThunk = (1,0.5,0.5) colorThunkHighlighted :: RGB colorThunkHighlighted = (1,0,0) colorFunction :: RGB colorFunction = (1,1,0.5) colorFunctionHighlighted :: RGB colorFunctionHighlighted = (1,1,0) padding :: Double padding = 5 -- | Draw visualization to screen, called on every update or when it's -- requested from outside the program. redraw :: WidgetClass w => w -> IO () redraw canvas = do s <- readIORef state Gtk.Rectangle _ _ rw2 rh2 <- widgetGetAllocation canvas (size, boundingBoxes) <- render canvas (draw s rw2 rh2) modifyIORef state (\s' -> s' {totalSize = size, bounds = boundingBoxes}) #ifdef SDL_WINDOW getState :: IO State getState = readIORef state updateBoundingBoxes :: [(String, Rectangle)] -> IO () updateBoundingBoxes boundingBoxes = do modifyIORef state (\s' -> s' {bounds = boundingBoxes}) #endif -- | Export the visualization to an SVG file export :: DrawFunction -> String -> IO () export drawFn file = do s <- readIORef state let (_, _, xSize, ySize) = totalSize s drawFn file xSize ySize (\surface -> renderWith surface (draw s 0 0)) return () draw :: State -> Int -> Int -> Render (Rectangle, [(String, Rectangle)]) draw s rw2 rh2 = do let os = objects s objs = map (\(_,_,x) -> x) os --boxes = map (\(x,_,_) -> x) os names = map ((++ ": ") . (\(_,x,_) -> x)) os layout <- pangoEmptyLayout liftIO $ writeIORef layout' $ Just layout nameWidths <- mapM (width . Unnamed) names pos <- mapM height objs widths <- mapM (mapM width) objs vS <- liftIO $ readIORef visState let rw = 0.98 * fromIntegral rw2 rh = fromIntegral rh2 maxNameWidth = maximum nameWidths widths2 = 1 : map (\ws -> maxNameWidth + sum ws) widths sw = maximum widths2 sh = sum (map (+ 30) pos) - 15 (sx,sy) = (zoomRatio vS * min (rw / sw) (rh / sh), sx) (ox2,oy2) = position vS (ox,oy) = (ox2 - (zoomRatio vS - 1) * rw / 2, oy2 - (zoomRatio vS - 1) * rh / 2) translate ox oy unless (rw2 == 0 || rh2 == 0) $ scale sx sy let rpos = scanl (\a b -> a + b + 30) 30 pos result <- mapM (drawEntry s maxNameWidth 0) (zip3 objs rpos names) return ((0, 0, sw, sh), map (\(o, (x,y,w,h)) -> (o, (x*sx+ox,y*sy+oy,w*sx,h*sy))) $ concat result) render :: WidgetClass w => w -> Render b -> IO b render canvas r = do win <- widgetGetDrawWindow canvas renderWithDrawable win r -- | Handle a mouse click. If an object was clicked an 'UpdateSignal' is sent -- that causes the object to be evaluated and the screen to be updated. click :: IO () click = do s <- readIORef state hm <- inHistoryMode when (not hm) $ case hover s of Just t -> do evaluate t -- Without forkIO it would hang indefinitely if some action is currently -- executed void $ forkIO $ putMVar visSignal UpdateSignal _ -> return () -- | Handle a mouse move. Causes an 'UpdateSignal' if the mouse is hovering a -- different object now, so the object gets highlighted and the screen -- updated. move :: WidgetClass w => w -> IO () move canvas = do vS <- readIORef visState oldS <- readIORef state let oldHover = hover oldS modifyIORef state $ \s' -> ( let (mx, my) = mousePos vS check (o, (x,y,w,h)) = if x <= mx && mx <= x + w && y <= my && my <= y + h then Just o else Nothing in s' {hover = msum $ map check (bounds s')} ) s <- readIORef state unless (oldHover == hover s) $ widgetQueueDraw canvas -- | Something might have changed on the heap, update the view. updateObjects :: [NamedBox] -> IO () updateObjects boxes = do os <- parseBoxes --(h, is) <- multiBuildHeapGraph 100 $ map fst boxes -- This is wrong --let os = visHeapGraph (zipWith (\(b,i) (b',n) -> (i,n)) is boxes) h let objs = zipWith (\(y,x) z -> (x,intercalate ", " y,z)) boxes os modifyIORef state (\s -> s {objects = objs, hover = Nothing}) drawEntry :: State -> Double -> Double -> ([VisObject], Double, String) -> Render [(String, Rectangle)] drawEntry s nameWidth xPos (obj, pos, name) = do save translate xPos pos moveTo 0 0 drawBox s $ Unnamed name translate nameWidth 0 moveTo 0 0 boundingBoxes <- mapM (drawBox s) obj restore return $ map (\(o, (x,y,w,h)) -> (o, (x+nameWidth,y+pos,w,h))) $ concat boundingBoxes drawBox :: State -> VisObject -> Render [(String, Rectangle)] drawBox _ o@(Unnamed content) = do (x,_) <- getCurrentPoint wc <- width o (layout, metrics) <- pangoLayout content let fa = ascent metrics moveTo (x + padding/2) (-fa) setSourceRGB 0 0 0 showLayout layout moveTo (x + wc) 0 return [] drawBox s o@(Thunk target) = drawFunctionLink s o target colorThunk colorThunkHighlighted drawBox s o@(Function target) = drawFunctionLink s o target colorFunction colorFunctionHighlighted drawBox s o@(Link target) = drawFunctionLink s o target colorLink colorLinkHighlighted drawBox s o@(Named name content) = do (x,_) <- getCurrentPoint hc <- height content wc <- width o (layout, metrics) <- pangoLayout name (_, PangoRectangle _ _ xa fh) <- liftIO $ layoutGetExtents layout let fa = ascent metrics let (ux, uy, uw, uh) = ( x , -fa - padding , wc , fh + 10 + hc ) setLineCap LineCapRound roundedRect ux uy uw uh setColor s name colorName colorNameHighlighted fillAndSurround moveTo ux (hc + 5 - fa - padding) lineTo (ux + uw) (hc + 5 - fa - padding) stroke save moveTo (x + padding) 0 bb <- mapM (drawBox s) content restore moveTo (x + uw/2 - xa/2) (hc + 7.5 - padding - fa) showLayout layout moveTo (x + wc) 0 return $ concat bb ++ [(name, (ux, uy, uw, uh))] pangoLayout :: String -> Render (PangoLayout, FontMetrics) pangoLayout text = do --layout <- createLayout text mbLayout <- liftIO $ readIORef layout' layout'' <- case mbLayout of Just layout''' -> return layout''' Nothing -> do layout''' <- pangoEmptyLayout liftIO $ writeIORef layout' $ Just layout''' return layout''' layout <- liftIO $ layoutCopy layout'' liftIO $ layoutSetText layout text context <- liftIO $ layoutGetContext layout --fo <- liftIO $ cairoContextGetFontOptions context --fontOptionsSetAntialias fo AntialiasDefault --fontOptionsSetHintStyle fo HintStyleNone --fontOptionsSetHintMetrics fo HintMetricsOff --liftIO $ cairoContextSetFontOptions context fo --liftIO $ layoutContextChanged layout -- This does not work with "Times Roman", but it works with a font that is -- installed on the system --font <- liftIO fontDescriptionNew --liftIO $ fontDescriptionSetFamily font "Nimbus Roman No9 L, Regular" --liftIO $ fontDescriptionSetFamily font "Times Roman" --liftIO $ fontDescriptionSetSize font fontSize' -- Only fontDescriptionFromString works as expected, choosing a similar -- alternative font when the selected one is not available font <- liftIO $ fontDescriptionFromString fontName liftIO $ fontDescriptionSetSize font fontSize --liftIO $ layoutSetFontDescription layout (Just font) language <- liftIO $ contextGetLanguage context metrics <- liftIO $ contextGetMetrics context font language return (layout, metrics) pangoEmptyLayout :: Render PangoLayout pangoEmptyLayout = do layout <- createLayout "" liftIO $ do font <- fontDescriptionFromString fontName fontDescriptionSetSize font fontSize layoutSetFontDescription layout (Just font) return layout --font <- fontDescriptionFromString fontName --cairoCreateContext Nothing drawFunctionLink :: State -> VisObject -> String -> RGB -> RGB -> Render [(String, Rectangle)] drawFunctionLink s o target color1 color2 = do (x,_) <- getCurrentPoint (layout, metrics) <- pangoLayout target (_, PangoRectangle _ _ _ fh) <- liftIO $ layoutGetExtents layout let fa = ascent metrics wc <- width o let (ux, uy, uw, uh) = ( x , (-fa) - padding , wc , fh + 10 ) setLineCap LineCapRound roundedRect ux uy uw uh setColor s target color1 color2 fillAndSurround moveTo (x + padding) (-fa) showLayout layout moveTo (x + wc) 0 return [(target, (ux, uy, uw, uh))] setColor :: State -> String -> RGB -> RGB -> Render () setColor s name (r,g,b) (r',g',b') = case hover s of Just t -> if t == name then setSourceRGB r' g' b' else setSourceRGB r g b _ -> setSourceRGB r g b fillAndSurround :: Render () fillAndSurround = do fillPreserve setSourceRGB 0 0 0 stroke roundedRect :: Double -> Double -> Double -> Double -> Render () roundedRect x y w h = do moveTo x (y + pad) lineTo x (y + h - pad) arcNegative (x + pad) (y + h - pad) pad pi (pi/2) lineTo (x + w - pad) (y + h) arcNegative (x + w - pad) (y + h - pad) pad (pi/2) 0 lineTo (x + w) (y + pad) arcNegative (x + w - pad) (y + pad) pad 0 (-pi/2) lineTo (x + pad) y arcNegative (x + pad) (y + pad) pad (-pi/2) (-pi) closePath --where pad = 1/10 * min w h where pad = 5 height :: [VisObject] -> Render Double height xs = do (layout, _) <- pangoLayout "" (_, PangoRectangle _ _ _ ya) <- liftIO $ layoutGetExtents layout let go (Named _ ys) = (ya + 15) + maxGo ys go (Unnamed _) = ya go (Link _) = ya + 2 * padding go (Thunk _) = ya + 2 * padding go (Function _) = ya + 2 * padding maxGo = maximum . (0 :) . map go return $ maxGo xs width :: VisObject -> Render Double width (Named x ys) = do nameWidth <- simpleWidth x $ 2 * padding w2s <- mapM width ys return $ max nameWidth $ sum w2s + 2 * padding width (Unnamed x) = simpleWidth x padding width (Link x) = simpleWidth x $ 2 * padding width (Thunk x) = simpleWidth x $ 2 * padding width (Function x) = simpleWidth x $ 2 * padding simpleWidth :: String -> Double -> Render Double simpleWidth x pad = do (layout, _) <- pangoLayout x (_, PangoRectangle _ _ xa _) <- liftIO $ layoutGetExtents layout return $ xa + pad
bgamari/ghc-vis
src/GHC/Vis/View/List.hs
bsd-3-clause
12,030
0
23
2,847
4,338
2,242
2,096
274
5
{-# LANGUAGE Haskell98, BangPatterns #-} {-# LINE 1 "Data/ByteString/Lazy/Search/Internal/BoyerMoore.hs" #-} {-# LANGUAGE BangPatterns #-} {-# OPTIONS_HADDOCK hide, prune #-} -- | -- Module : Data.ByteString.Lazy.Search.Internal.BoyerMoore -- Copyright : Daniel Fischer -- Chris Kuklewicz -- Licence : BSD3 -- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com> -- Stability : Provisional -- Portability : non-portable (BangPatterns) -- -- Fast overlapping Boyer-Moore search of both strict and lazy -- 'S.ByteString' values. Breaking, splitting and replacing -- using the Boyer-Moore algorithm. -- -- Descriptions of the algorithm can be found at -- <http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140> -- and -- <http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm> -- -- Original authors: Daniel Fischer (daniel.is.fischer at googlemail.com) and -- Chris Kuklewicz (haskell at list.mightyreason.com). module Data.ByteString.Lazy.Search.Internal.BoyerMoore ( matchLL , matchSL -- Non-overlapping , matchNOL -- Replacing substrings -- replacing , replaceAllL -- Breaking on substrings -- breaking , breakSubstringL , breakAfterL , breakFindAfterL -- Splitting on substrings -- splitting , splitKeepEndL , splitKeepFrontL , splitDropL ) where import Data.ByteString.Search.Internal.Utils (occurs, suffShifts, ldrop, lsplit, keep, release, strictify) import Data.ByteString.Search.Substitution import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.ByteString.Unsafe (unsafeIndex) import Data.Array.Base (unsafeAt) import Data.Word (Word8) import Data.Int (Int64) -- overview -- -- This module exports three search functions for searching in lazy -- ByteSrings, one for searching non-overlapping occurrences of a strict -- pattern, and one each for searchin overlapping occurrences of a strict -- resp. lazy pattern. The common base name is @match@, the suffix -- indicates the type of search. These functions -- return (for a non-empty pattern) a list of all the indices of the target -- string where an occurrence of the pattern begins, if some occurrences -- overlap, all starting indices are reported. The list is produced lazily, -- so not necessarily the entire target string is searched. -- -- The behaviour of these functions when given an empty pattern has changed. -- Formerly, the @matchXY@ functions returned an empty list then, now it's -- @[0 .. 'length' target]@. -- -- Newly added are functions to replace all (non-overlapping) occurrences -- of a pattern within a string, functions to break ByteStrings at the first -- occurrence of a pattern and functions to split ByteStrings at each -- occurrence of a pattern. None of these functions does copying, so they -- don't introduce large memory overhead. -- -- Internally, a lazy pattern is always converted to a strict ByteString, -- which is necessary for an efficient implementation of the algorithm. -- The limit this imposes on the length of the pattern is probably -- irrelevant in practice, but perhaps it should be mentioned. -- This also means that the @matchL*@ functions are mere convenience wrappers. -- Except for the initial 'strictify'ing, there's no difference between lazy -- and strict patterns, they call the same workers. There is, however, a -- difference between strict and lazy target strings. -- For the new functions, no such wrappers are provided, you have to -- 'strictify' lazy patterns yourself. -- caution -- -- When working with a lazy target string, the relation between the pattern -- length and the chunk size can play a big r&#244;le. -- Crossing chunk boundaries is relatively expensive, so when that becomes -- a frequent occurrence, as may happen when the pattern length is close -- to or larger than the chunk size, performance is likely to degrade. -- If it is needed, steps can be taken to ameliorate that effect, but unless -- entirely separate functions are introduced, that would hurt the -- performance for the more common case of patterns much shorter than -- the default chunk size. -- performance -- -- In general, the Boyer-Moore algorithm is the most efficient method to -- search for a pattern inside a string, so most of the time, you'll want -- to use the functions of this module, hence this is where the most work -- has gone. Very short patterns are an exception to this, for those you -- should consider using a finite automaton -- ("Data.ByteString.Search.DFA.Array"). That is also often the better -- choice for searching longer periodic patterns in a lazy ByteString -- with many matches. -- -- Operating on a strict target string is mostly faster than on a lazy -- target string, but the difference is usually small (according to my -- tests). -- -- The known exceptions to this rule of thumb are -- -- [long targets] Then the smaller memory footprint of a lazy target often -- gives (much) better performance. -- -- [high number of matches] When there are very many matches, strict target -- strings are much faster, especially if the pattern is periodic. -- -- If both conditions hold, either may outweigh the other. -- complexity -- -- Preprocessing the pattern is /O/(@patternLength@ + &#963;) in time and -- space (&#963; is the alphabet size, 256 here) for all functions. -- The time complexity of the searching phase for @matchXY@ -- is /O/(@targetLength@ \/ @patternLength@) in the best case. -- For non-periodic patterns, the worst case complexity is -- /O/(@targetLength@), but for periodic patterns, the worst case complexity -- is /O/(@targetLength@ * @patternLength@) for the original Boyer-Moore -- algorithm. -- -- The searching functions in this module now contain a modification which -- drastically improves the performance for periodic patterns. -- I believe that for strict target strings, the worst case is now -- /O/(@targetLength@) also for periodic patterns and for lazy target strings, -- my semi-educated guess is -- /O/(@targetLength@ * (1 + @patternLength@ \/ @chunkSize@)). -- I may be very wrong, though. -- -- The other functions don't have to deal with possible overlapping -- patterns, hence the worst case complexity for the processing phase -- is /O/(@targetLength@) (respectively /O/(@firstIndex + patternLength@) -- for the breaking functions if the pattern occurs). -- currying -- -- These functions can all be usefully curried. Given only a pattern -- the curried version will compute the supporting lookup tables only -- once, allowing for efficient re-use. Similarly, the curried -- 'matchLL' and 'matchLS' will compute the concatenated pattern only -- once. -- overflow -- -- The current code uses @Int@ to keep track of the locations in the -- target string. If the length of the pattern plus the length of any -- strict chunk of the target string is greater than -- @'maxBound' :: 'Int'@ then this will overflow causing an error. We -- try to detect this and call 'error' before a segfault occurs. ------------------------------------------------------------------------------ -- Wrappers -- ------------------------------------------------------------------------------ -- matching -- -- These functions find the indices of all (possibly overlapping) -- occurrences of a pattern in a target string. -- If the pattern is empty, the result is @[0 .. length target]@. -- If the pattern is much shorter than the target string -- and the pattern does not occur very near the beginning of the target, -- -- > not . null $ matchSS pattern target -- -- is a much more efficient version of 'S.isInfixOf'. -- | @'matchLL'@ finds the starting indices of all possibly overlapping -- occurrences of the pattern in the target string. -- It is a simple wrapper for 'Data.ByteString.Lazy.Search.indices'. -- If the pattern is empty, the result is @[0 .. 'length' target]@. {-# INLINE matchLL #-} matchLL :: L.ByteString -- ^ Lazy pattern -> L.ByteString -- ^ Lazy target string -> [Int64] -- ^ Offsets of matches matchLL pat = search . L.toChunks where search = lazySearcher True (strictify pat) -- | @'matchSL'@ finds the starting indices of all possibly overlapping -- occurrences of the pattern in the target string. -- It is an alias for 'Data.ByteString.Lazy.Search.indices'. -- If the pattern is empty, the result is @[0 .. 'length' target]@. {-# INLINE matchSL #-} matchSL :: S.ByteString -- ^ Strict pattern -> L.ByteString -- ^ Lazy target string -> [Int64] -- ^ Offsets of matches matchSL pat = search . L.toChunks where search = lazySearcher True pat -- | @'matchNOL'@ finds the indices of all non-overlapping occurrences -- of the pattern in the lazy target string. {-# INLINE matchNOL #-} matchNOL :: S.ByteString -- ^ Strict pattern -> L.ByteString -- ^ Lazy target string -> [Int64] -- ^ Offsets of matches matchNOL pat = search . L.toChunks where search = lazySearcher False pat -- replacing -- -- These functions replace all (non-overlapping) occurrences of a pattern -- in the target string. If some occurrences overlap, the earliest is -- replaced and replacing continues at the index after the replaced -- occurrence, for example -- -- > replaceAllL \"ana\" \"olog\" \"banana\" == \"bologna\", -- > replaceAllS \"abacab\" \"u\" \"abacabacabacab\" == \"uacu\", -- > replaceAllS \"aa\" \"aaa\" \"aaaa\" == \"aaaaaa\". -- -- Equality of pattern and substitution is not checked, but -- -- > pat == sub => 'strictify' (replaceAllS pat sub str) == str, -- > pat == sub => replaceAllL pat sub str == str. -- -- The result is a lazily generated lazy ByteString, the first chunks will -- generally be available before the entire target has been scanned. -- If the pattern is empty, but not the substitution, the result is -- equivalent to @'cycle' sub@. {-# INLINE replaceAllL #-} replaceAllL :: Substitution rep => S.ByteString -- ^ Pattern to replace -> rep -- ^ Substitution string -> L.ByteString -- ^ Target string -> L.ByteString -- ^ Lazy result replaceAllL pat | S.null pat = \sub -> prependCycle sub | S.length pat == 1 = let breaker = lazyBreak pat repl subst strs | null strs = [] | otherwise = case breaker strs of (pre, mtch) -> pre ++ case mtch of [] -> [] _ -> subst (repl subst (ldrop 1 mtch)) in \sub -> let repl1 = repl (substitution sub) in L.fromChunks . repl1 . L.toChunks | otherwise = let repl = lazyRepl pat in \sub -> let repl1 = repl (substitution sub) in L.fromChunks . repl1 . L.toChunks -- breaking -- -- Break a string on a pattern. The first component of the result -- contains the prefix of the string before the first occurrence of the -- pattern, the second component contains the remainder. -- The following relations hold: -- -- > breakSubstringX \"\" str = (\"\", str) -- > not (pat `isInfixOf` str) == null (snd $ breakSunbstringX pat str) -- > True == case breakSubstringX pat str of -- > (x, y) -> not (pat `isInfixOf` x) -- > && (null y || pat `isPrefixOf` y) -- | The analogous function for a lazy target string. -- The first component is generated lazily, so parts of it can be -- available before the pattern is detected (or found to be absent). {-# INLINE breakSubstringL #-} breakSubstringL :: S.ByteString -- ^ Pattern to break on -> L.ByteString -- ^ String to break up -> (L.ByteString, L.ByteString) -- ^ Prefix and remainder of broken string breakSubstringL pat = breaker . L.toChunks where lbrk = lazyBreak pat breaker strs = let (f, b) = lbrk strs in (L.fromChunks f, L.fromChunks b) breakAfterL :: S.ByteString -> L.ByteString -> (L.ByteString, L.ByteString) breakAfterL pat | S.null pat = \str -> (L.empty, str) breakAfterL pat = breaker' . L.toChunks where !patLen = S.length pat breaker = lazyBreak pat breaker' strs = let (pre, mtch) = breaker strs (pl, a) = if null mtch then ([],[]) else lsplit patLen mtch in (L.fromChunks (pre ++ pl), L.fromChunks a) breakFindAfterL :: S.ByteString -> L.ByteString -> ((L.ByteString, L.ByteString), Bool) breakFindAfterL pat | S.null pat = \str -> ((L.empty, str), True) breakFindAfterL pat = breaker' . L.toChunks where !patLen = S.length pat breaker = lazyBreak pat breaker' strs = let (pre, mtch) = breaker strs (pl, a) = if null mtch then ([],[]) else lsplit patLen mtch in ((L.fromChunks (pre ++ pl), L.fromChunks a), not (null mtch)) -- splitting -- -- These functions implement various splitting strategies. -- -- If the pattern to split on is empty, all functions return an -- infinite list of empty ByteStrings. -- Otherwise, the names are rather self-explanatory. -- -- For nonempty patterns, the following relations hold: -- -- > concat (splitKeepXY pat str) == str -- > concat ('Data.List.intersperse' pat (splitDropX pat str)) == str. -- -- All fragments except possibly the last in the result of -- @splitKeepEndX pat@ end with @pat@, none of the fragments contains -- more than one occurrence of @pat@ or is empty. -- -- All fragments except possibly the first in the result of -- @splitKeepFrontX pat@ begin with @pat@, none of the fragments -- contains more than one occurrence of @patq or is empty. -- -- > splitDropX pat str == map dropPat (splitKeepFrontX pat str) -- > where -- > patLen = length pat -- > dropPat frag -- > | pat `isPrefixOf` frag = drop patLen frag -- > | otherwise = frag -- -- but @splitDropX@ is a little more efficient than that. {-# INLINE splitKeepEndL #-} splitKeepEndL :: S.ByteString -- ^ Pattern to split on -> L.ByteString -- ^ String to split -> [L.ByteString] -- ^ List of fragments splitKeepEndL pat | S.null pat = const (repeat L.empty) | otherwise = let splitter = lazySplitKeepEnd pat in map L.fromChunks . splitter . L.toChunks {-# INLINE splitKeepFrontL #-} splitKeepFrontL :: S.ByteString -- ^ Pattern to split on -> L.ByteString -- ^ String to split -> [L.ByteString] -- ^ List of fragments splitKeepFrontL pat | S.null pat = const (repeat L.empty) | otherwise = let splitter = lazySplitKeepFront pat in map L.fromChunks . splitter . L.toChunks {-# INLINE splitDropL #-} splitDropL :: S.ByteString -- ^ Pattern to split on -> L.ByteString -- ^ String to split -> [L.ByteString] -- ^ List of fragments splitDropL pat | S.null pat = const (repeat L.empty) | otherwise = let splitter = lazySplitDrop pat in map L.fromChunks . splitter . L.toChunks ------------------------------------------------------------------------------ -- Search Functions -- ------------------------------------------------------------------------------ lazySearcher :: Bool -> S.ByteString -> [S.ByteString] -> [Int64] lazySearcher _ !pat | S.null pat = let zgo !prior [] = [prior] zgo prior (!str : rest) = let !l = S.length str !prior' = prior + fromIntegral l in [prior + fromIntegral i | i <- [0 .. l-1]] ++ zgo prior' rest in zgo 0 | S.length pat == 1 = let !w = S.head pat ixes = S.elemIndices w go _ [] = [] go !prior (!str : rest) = let !prior' = prior + fromIntegral (S.length str) in map ((+ prior) . fromIntegral) (ixes str) ++ go prior' rest in go 0 lazySearcher !overlap pat = searcher where {-# INLINE patAt #-} patAt :: Int -> Word8 patAt !i = unsafeIndex pat i !patLen = S.length pat !patEnd = patLen - 1 {-# INLINE preEnd #-} preEnd = patEnd - 1 !maxLen = maxBound - patLen !occT = occurs pat -- for bad-character-shift !suffT = suffShifts pat -- for good-suffix-shift !skip = if overlap then unsafeAt suffT 0 else patLen -- shift after a complete match !kept = patLen - skip -- length of known prefix after full match !pe = patAt patEnd -- last pattern byte for fast comparison {-# INLINE occ #-} occ !w = unsafeAt occT (fromIntegral w) {-# INLINE suff #-} suff !i = unsafeAt suffT i searcher lst = case lst of [] -> [] (h : t) -> if maxLen < S.length h then error "Overflow in BoyerMoore.lazySearcher" else seek 0 [] h t 0 patEnd -- seek is used to position the "zipper" of (past, str, future) to the -- correct S.ByteString to search. This is done by ensuring that -- 0 <= strPos < strLen, where strPos = diffPos + patPos. -- Note that future is not a strict parameter. The bytes being compared -- will then be (strAt strPos) and (patAt patPos). -- Splitting this into specialised versions is possible, but it would -- only be useful if the pattern length is close to (or larger than) -- the chunk size. For ordinary patterns of at most a few hundred bytes, -- the overhead of yet more code-paths and larger code size will probably -- outweigh the small gains in the relatively rare calls to seek. seek :: Int64 -> [S.ByteString] -> S.ByteString -> [S.ByteString] -> Int -> Int -> [Int64] seek !prior !past !str future !diffPos !patPos | strPos < 0 = -- need to look at previous chunk case past of (h : t) -> let !hLen = S.length h in seek (prior - fromIntegral hLen) t h (str : future) (diffPos + hLen) patPos [] -> error "seek back too far!" | strEnd < strPos = -- need to look at next chunk if there is case future of (h : t) -> let {-# INLINE prior' #-} prior' = prior + fromIntegral strLen !diffPos' = diffPos - strLen {-# INLINE past' #-} past' = release (-diffPos') (str : past) in if maxLen < S.length h then error "Overflow in BoyerMoore.lazySearcher" else seek prior' past' h t diffPos' patPos [] -> [] | patPos == patEnd = checkEnd strPos | diffPos < 0 = matcherN diffPos patPos | otherwise = matcherP diffPos patPos where !strPos = diffPos + patPos !strLen = S.length str !strEnd = strLen - 1 !maxDiff = strLen - patLen {-# INLINE strAt #-} strAt !i = unsafeIndex str i -- While comparing the last byte of the pattern, the bad- -- character-shift is always at least as large as the good- -- suffix-shift. Eliminating the unnecessary memory reads and -- comparison speeds things up noticeably. checkEnd !sI -- index in string to compare to last of pattern | strEnd < sI = seek prior past str future (sI - patEnd) patEnd | otherwise = case strAt sI of !c | c == pe -> if sI < patEnd then case sI of 0 -> seek prior past str future (-patEnd) preEnd _ -> matcherN (sI - patEnd) preEnd else matcherP (sI - patEnd) preEnd | otherwise -> checkEnd (sI + patEnd + occ c) -- Once the last byte has matched, we enter the full matcher -- diff is the offset of the window, patI the index of the -- pattern byte to compare next. -- matcherN is the tight loop that walks backwards from the end -- of the pattern checking for matching bytes. The offset is -- always negative, so no complete match can occur here. -- When a byte matches, we need to check whether we've reached -- the front of this chunk, otherwise whether we need the next. matcherN !diff !patI = case strAt (diff + patI) of !c | c == patAt patI -> if diff + patI == 0 then seek prior past str future diff (patI - 1) else matcherN diff (patI - 1) | otherwise -> let {-# INLINE badShift #-} badShift = patI + occ c {-# INLINE goodShift #-} goodShift = suff patI !diff' = diff + max badShift goodShift in if maxDiff < diff' then seek prior past str future diff' patEnd else checkEnd (diff' + patEnd) -- matcherP is the tight loop for non-negative offsets. -- When the pattern is shifted, we must check whether we leave -- the current chunk, otherwise we only need to check for a -- complete match. matcherP !diff !patI = case strAt (diff + patI) of !c | c == patAt patI -> if patI == 0 then prior + fromIntegral diff : let !diff' = diff + skip in if maxDiff < diff' then seek prior past str future diff' patEnd else if skip == patLen then checkEnd (diff' + patEnd) else afterMatch diff' patEnd else matcherP diff (patI - 1) | otherwise -> let {-# INLINE badShift #-} badShift = patI + occ c {-# INLINE goodShift #-} goodShift = suff patI !diff' = diff + max badShift goodShift in if maxDiff < diff' then seek prior past str future diff' patEnd else checkEnd (diff' + patEnd) -- After a full match, we know how long a prefix of the pattern -- still matches. Do not re-compare the prefix to prevent O(m*n) -- behaviour for periodic patterns. -- This breaks down at chunk boundaries, but except for long -- patterns with a short period, that shouldn't matter much. afterMatch !diff !patI = case strAt (diff + patI) of !c | c == patAt patI -> if patI == kept then prior + fromIntegral diff : let !diff' = diff + skip in if maxDiff < diff' then seek prior past str future diff' patEnd else afterMatch diff' patEnd else afterMatch diff (patI - 1) | patI == patEnd -> checkEnd (diff + (2*patEnd) + occ c) | otherwise -> let {-# INLINE badShift #-} badShift = patI + occ c {-# INLINE goodShift #-} goodShift = suff patI !diff' = diff + max badShift goodShift in if maxDiff < diff' then seek prior past str future diff' patEnd else checkEnd (diff' + patEnd) ------------------------------------------------------------------------------ -- Breaking Functions -- ------------------------------------------------------------------------------ -- Ugh! Code duplication ahead! -- But we want to get the first component lazily, so it's no good to find -- the first index (if any) and then split. -- Therefore bite the bullet and copy most of the code of lazySearcher. -- No need for afterMatch here, fortunately. lazyBreak ::S.ByteString -> [S.ByteString] -> ([S.ByteString], [S.ByteString]) lazyBreak !pat | S.null pat = \lst -> ([],lst) | S.length pat == 1 = let !w = S.head pat go [] = ([], []) go (!str : rest) = case S.elemIndices w str of [] -> let (pre, post) = go rest in (str : pre, post) (i:_) -> if i == 0 then ([], str : rest) else ([S.take i str], S.drop i str : rest) in go lazyBreak pat = breaker where !patLen = S.length pat !patEnd = patLen - 1 !occT = occurs pat !suffT = suffShifts pat !maxLen = maxBound - patLen !pe = patAt patEnd {-# INLINE patAt #-} patAt !i = unsafeIndex pat i {-# INLINE occ #-} occ !w = unsafeAt occT (fromIntegral w) {-# INLINE suff #-} suff !i = unsafeAt suffT i breaker lst = case lst of [] -> ([],[]) (h:t) -> if maxLen < S.length h then error "Overflow in BoyerMoore.lazyBreak" else seek [] h t 0 patEnd seek :: [S.ByteString] -> S.ByteString -> [S.ByteString] -> Int -> Int -> ([S.ByteString], [S.ByteString]) seek !past !str future !offset !patPos | strPos < 0 = case past of [] -> error "not enough past!" (h : t) -> seek t h (str : future) (offset + S.length h) patPos | strEnd < strPos = case future of [] -> (foldr (flip (.) . (:)) id past [str], []) (h : t) -> let !off' = offset - strLen (past', !discharge) = keep (-off') (str : past) in if maxLen < S.length h then error "Overflow in BoyerMoore.lazyBreak (future)" else let (pre,post) = seek past' h t off' patPos in (foldr (flip (.) . (:)) id discharge pre, post) | patPos == patEnd = checkEnd strPos | offset < 0 = matcherN offset patPos | otherwise = matcherP offset patPos where {-# INLINE strAt #-} strAt !i = unsafeIndex str i !strLen = S.length str !strEnd = strLen - 1 !maxOff = strLen - patLen !strPos = offset + patPos checkEnd !sI | strEnd < sI = seek past str future (sI - patEnd) patEnd | otherwise = case strAt sI of !c | c == pe -> if sI < patEnd then (if sI == 0 then seek past str future (-patEnd) (patEnd - 1) else matcherN (sI - patEnd) (patEnd - 1)) else matcherP (sI - patEnd) (patEnd - 1) | otherwise -> checkEnd (sI + patEnd + occ c) matcherN !off !patI = case strAt (off + patI) of !c | c == patAt patI -> if off + patI == 0 then seek past str future off (patI - 1) else matcherN off (patI - 1) | otherwise -> let !off' = off + max (suff patI) (patI + occ c) in if maxOff < off' then seek past str future off' patEnd else checkEnd (off' + patEnd) matcherP !off !patI = case strAt (off + patI) of !c | c == patAt patI -> if patI == 0 then let !pre = if off == 0 then [] else [S.take off str] !post = S.drop off str in (foldr (flip (.) . (:)) id past pre, post:future) else matcherP off (patI - 1) | otherwise -> let !off' = off + max (suff patI) (patI + occ c) in if maxOff < off' then seek past str future off' patEnd else checkEnd (off' + patEnd) ------------------------------------------------------------------------------ -- Splitting Functions -- ------------------------------------------------------------------------------ -- non-empty pattern lazySplitKeepFront :: S.ByteString -> [S.ByteString] -> [[S.ByteString]] lazySplitKeepFront pat = splitter' where !patLen = S.length pat breaker = lazyBreak pat splitter' strs = case splitter strs of ([]:rest) -> rest other -> other splitter [] = [] splitter strs = case breaker strs of (pre, mtch) -> pre : case mtch of [] -> [] _ -> case lsplit patLen mtch of (pt, rst) -> if null rst then [pt] else let (h : t) = splitter rst in (pt ++ h) : t -- non-empty pattern lazySplitKeepEnd :: S.ByteString -> [S.ByteString] -> [[S.ByteString]] lazySplitKeepEnd pat = splitter where !patLen = S.length pat breaker = lazyBreak pat splitter [] = [] splitter strs = case breaker strs of (pre, mtch) -> let (h : t) = if null mtch then [[]] else case lsplit patLen mtch of (pt, rst) -> pt : splitter rst in (pre ++ h) : t lazySplitDrop :: S.ByteString -> [S.ByteString] -> [[S.ByteString]] lazySplitDrop pat = splitter where !patLen = S.length pat breaker = lazyBreak pat splitter [] = [] splitter strs = splitter' strs splitter' [] = [[]] splitter' strs = case breaker strs of (pre,mtch) -> pre : case mtch of [] -> [] _ -> splitter' (ldrop patLen mtch) ------------------------------------------------------------------------------ -- Replacing Functions -- ------------------------------------------------------------------------------ {- These would be really nice. Unfortunately they're too slow, so instead, there's another instance of almost the same code as in lazySearcher below. -- variant of below lazyFRepl :: S.ByteString -> ([S.ByteString] -> [S.ByteString]) -> [S.ByteString] -> [S.ByteString] lazyFRepl pat = repl where !patLen = S.length pat breaker = lazyBreak pat repl sub = replacer where replacer [] = [] replacer strs = let (pre, mtch) = breaker strs in pre ++ case mtch of [] -> [] _ -> sub (replacer (ldrop patLen mtch)) -- This is nice and short. I really hope it's performing well! lazyBRepl :: S.ByteString -> S.ByteString -> [S.ByteString] -> [S.ByteString] lazyBRepl pat !sub = replacer where !patLen = S.length pat breaker = lazyBreak pat replacer [] = [] replacer strs = let (pre, mtch) = breaker strs in pre ++ case mtch of [] -> [] _ -> sub : replacer (ldrop patLen mtch) -} -- Yet more code duplication. -- -- Benchmark it against an implementation using lazyBreak and, -- unless it's significantly faster, NUKE IT!! -- -- Sigh, it is significantly faster. 10 - 25 %. -- I could live with the 10, but 25 is too much. -- -- Hmm, maybe an implementation via -- replace pat sub = L.intercalate sub . split pat -- would be competitive now. -- TODO: test speed and space usage. -- -- replacing loop for lazy ByteStrings as list of chunks, -- called only for non-empty patterns lazyRepl :: S.ByteString -> ([S.ByteString] -> [S.ByteString]) -> [S.ByteString] -> [S.ByteString] lazyRepl pat = replacer where !patLen = S.length pat !patEnd = patLen - 1 !occT = occurs pat !suffT = suffShifts pat !maxLen = maxBound - patLen !pe = patAt patEnd {-# INLINE patAt #-} patAt !i = unsafeIndex pat i {-# INLINE occ #-} occ !w = unsafeAt occT (fromIntegral w) {-# INLINE suff #-} suff !i = unsafeAt suffT i replacer sub lst = case lst of [] -> [] (h:t) -> if maxLen < S.length h then error "Overflow in BoyerMoore.lazyRepl" else seek [] h t 0 patEnd where chop _ [] = [] chop !k (!str : rest) | k < s = if maxLen < (s - k) then error "Overflow in BoyerMoore.lazyRepl (chop)" else seek [] (S.drop k str) rest 0 patEnd | otherwise = chop (k-s) rest where !s = S.length str seek :: [S.ByteString] -> S.ByteString -> [S.ByteString] -> Int -> Int -> [S.ByteString] seek !past !str fut !offset !patPos | strPos < 0 = case past of [] -> error "not enough past!" (h : t) -> seek t h (str : fut) (offset + S.length h) patPos | strEnd < strPos = case fut of [] -> foldr (flip (.) . (:)) id past [str] (h : t) -> let !off' = offset - strLen (past', !discharge) = keep (-off') (str : past) in if maxLen < S.length h then error "Overflow in BoyerMoore.lazyRepl (future)" else foldr (flip (.) . (:)) id discharge $ seek past' h t off' patPos | patPos == patEnd = checkEnd strPos | offset < 0 = matcherN offset patPos | otherwise = matcherP offset patPos where {-# INLINE strAt #-} strAt !i = unsafeIndex str i !strLen = S.length str !strEnd = strLen - 1 !maxOff = strLen - patLen !strPos = offset + patPos checkEnd !sI | strEnd < sI = seek past str fut (sI - patEnd) patEnd | otherwise = case strAt sI of !c | c == pe -> if sI < patEnd then (if sI == 0 then seek past str fut (-patEnd) (patEnd - 1) else matcherN (sI - patEnd) (patEnd - 1)) else matcherP (sI - patEnd) (patEnd - 1) | otherwise -> checkEnd (sI + patEnd + occ c) matcherN !off !patI = case strAt (off + patI) of !c | c == patAt patI -> if off + patI == 0 then seek past str fut off (patI - 1) else matcherN off (patI - 1) | otherwise -> let !off' = off + max (suff patI) (patI + occ c) in if maxOff < off' then seek past str fut off' patEnd else checkEnd (off' + patEnd) matcherP !off !patI = case strAt (off + patI) of !c | c == patAt patI -> if patI == 0 then foldr (flip (.) . (:)) id past $ let pre = if off == 0 then id else (S.take off str :) in pre . sub $ let !p = off + patLen in if p < strLen then seek [] (S.drop p str) fut 0 patEnd else chop (p - strLen) fut else matcherP off (patI - 1) | otherwise -> let !off' = off + max (suff patI) (patI + occ c) in if maxOff < off' then seek past str fut off' patEnd else checkEnd (off' + patEnd)
phischu/fragnix
tests/packages/scotty/Data.ByteString.Lazy.Search.Internal.BoyerMoore.hs
bsd-3-clause
37,937
0
26
13,821
6,899
3,569
3,330
500
20
{-# LANGUAGE DisambiguateRecordFields #-} {-# LANGUAGE NamedFieldPuns #-} module VerifyCropSpanGeneration where import Verify.Graphics.Vty.Prelude import Verify.Graphics.Vty.Image import Verify.Graphics.Vty.Picture import Verify.Graphics.Vty.Span import Graphics.Vty.Debug import Graphics.Vty.PictureToSpans import Verify import qualified Data.Vector as Vector cropOpDisplayOps :: (Int -> Image -> Image) -> Int -> Image -> (DisplayOps, Image) cropOpDisplayOps cropOp v i = let iOut = cropOp v i p = picForImage iOut w = MockWindow (imageWidth iOut) (imageHeight iOut) in (displayOpsForPic p (regionForWindow w), iOut) widthCropOutputColumns :: (Int -> Image -> Image) -> SingleAttrSingleSpanStack -> NonNegative Int -> Property widthCropOutputColumns cropOp s (NonNegative w) = stackWidth s > w ==> let (ops, iOut) = cropOpDisplayOps cropOp w (stackImage s) in verifyAllSpansHaveWidth iOut ops w heightCropOutputColumns :: (Int -> Image -> Image) -> SingleAttrSingleSpanStack -> NonNegative Int -> Property heightCropOutputColumns cropOp s (NonNegative h) = stackHeight s > h ==> let (ops, _) = cropOpDisplayOps cropOp h (stackImage s) in displayOpsRows ops == h cropRightOutputColumns :: SingleAttrSingleSpanStack -> NonNegative Int -> Property cropRightOutputColumns = widthCropOutputColumns cropRight cropLeftOutputColumns :: SingleAttrSingleSpanStack -> NonNegative Int -> Property cropLeftOutputColumns = widthCropOutputColumns cropLeft cropTopOutputRows :: SingleAttrSingleSpanStack -> NonNegative Int -> Property cropTopOutputRows = heightCropOutputColumns cropTop cropBottomOutputRows :: SingleAttrSingleSpanStack -> NonNegative Int -> Property cropBottomOutputRows = heightCropOutputColumns cropBottom -- TODO: known benign failure. cropRightAndLeftRejoinedEquivalence :: SingleAttrSingleSpanStack -> Property cropRightAndLeftRejoinedEquivalence stack = imageWidth (stackImage stack) `mod` 2 == 0 ==> let i = stackImage stack -- the right part is made by cropping the image from the left. iR = cropLeft (imageWidth i `div` 2) i -- the left part is made by cropping the image from the right iL = cropRight (imageWidth i `div` 2) i iAlt = iL <|> iR iOps = displayOpsForImage i iAltOps = displayOpsForImage iAlt in verifyOpsEquality iOps iAltOps cropTopAndBottomRejoinedEquivalence :: SingleAttrSingleSpanStack -> Property cropTopAndBottomRejoinedEquivalence stack = imageHeight (stackImage stack) `mod` 2 == 0 ==> let i = stackImage stack -- the top part is made by cropping the image from the bottom. iT = cropBottom (imageHeight i `div` 2) i -- the bottom part is made by cropping the image from the top. iB = cropTop (imageHeight i `div` 2) i iAlt = iT <-> iB in displayOpsForImage i == displayOpsForImage iAlt tests :: IO [Test] tests = return [ verify "cropping from the bottom produces display operations covering the expected rows" cropBottomOutputRows , verify "cropping from the top produces display operations covering the expected rows" cropTopOutputRows , verify "cropping from the left produces display operations covering the expected columns" cropLeftOutputColumns , verify "cropping from the right produces display operations covering the expected columns" cropRightOutputColumns -- TODO: known benign failure. -- , verify "the output of a stack is the same as that stack cropped left & right and joined together" -- cropRightAndLeftRejoinedEquivalence , verify "the output of a stack is the same as that stack cropped top & bottom and joined together" cropTopAndBottomRejoinedEquivalence ]
jtdaugherty/vty
test/VerifyCropSpanGeneration.hs
bsd-3-clause
3,941
0
13
896
770
405
365
68
1
main :: IO () main = fail "this always fails for the test"
juhp/stack
test/integration/tests/3959-order-of-flags/files/test/Spec.hs
bsd-3-clause
59
0
7
13
24
10
14
2
1
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- This is a purely internal module for (un-)marshaling PixelInternalFormat. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat ( PixelInternalFormat(..), marshalPixelInternalFormat, marshalPixelInternalFormat', unmarshalPixelInternalFormat, ) where import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- data PixelInternalFormat = Alpha' | DepthComponent' | Luminance' | LuminanceAlpha' | Intensity | R8 | R16 | RG8 | RG16 | RGB' | RGBA' | SRGB | SRGBAlpha | SLuminance | SLuminanceAlpha | Alpha4 | Alpha8 | Alpha12 | Alpha16 | DepthComponent16 | DepthComponent24 | DepthComponent32 | Luminance4 | Luminance8 | Luminance12 | Luminance16 | Luminance4Alpha4 | Luminance6Alpha2 | Luminance8Alpha8 | Luminance12Alpha4 | Luminance12Alpha12 | Luminance16Alpha16 | Intensity4 | Intensity8 | Intensity12 | Intensity16 | R3G3B2 | RGB4 | RGB5 | RGB8 | RGB10 | RGB12 | RGB16 | RGBA2 | RGBA4 | RGB5A1 | RGBA8 | RGB10A2 | RGBA12 | RGBA16 | SRGB8 | SRGB8Alpha8 | R16F | RG16F | RGB16F | RGBA16F | R32F | RG32F | RGB32F | RGBA32F | R8I | R8UI | R16I | R16UI | R32I | R32UI | RG8I | RG8UI | RG16I | RG16UI | RG32I | RG32UI | RGB8I | RGB8UI | RGB16I | RGB16UI | RGB32I | RGB32UI | RGBA8I | RGBA8UI | RGBA16I | RGBA16UI | RGBA32I | RGBA32UI | SLuminance8 | SLuminance8Alpha8 | CompressedAlpha | CompressedLuminance | CompressedLuminanceAlpha | CompressedIntensity | CompressedRed | CompressedRG | CompressedRGB | CompressedRGBA | CompressedSRGB | CompressedSRGBAlpha | CompressedSLuminance | CompressedSLuminanceAlpha | CompressedRedRGTC1 | CompressedSignedRedRGTC1 | CompressedRG_RGTC2 | CompressedSignedRG_RGTC2 | DepthComponent32f | Depth32fStencil8 | RGB9E5 | R11fG11fB10f | StencilIndex1 | StencilIndex4 | StencilIndex8 | StencilIndex16 deriving ( Eq, Ord, Show ) marshalPixelInternalFormat :: PixelInternalFormat -> GLint marshalPixelInternalFormat x = fromIntegral $ case x of Alpha' -> gl_ALPHA DepthComponent' -> gl_DEPTH_COMPONENT Luminance' -> gl_LUMINANCE LuminanceAlpha' -> gl_LUMINANCE_ALPHA R8 -> gl_R8 R16 -> gl_R16 RG8 -> gl_RG8 RG16 -> gl_RG16 RGB' -> gl_RGB RGBA' -> gl_RGBA SRGB -> gl_SRGB SRGBAlpha -> gl_SRGB_ALPHA SLuminance -> gl_SLUMINANCE SLuminanceAlpha -> gl_SLUMINANCE_ALPHA Alpha4 -> gl_ALPHA4 Alpha8 -> gl_ALPHA8 Alpha12 -> gl_ALPHA12 Alpha16 -> gl_ALPHA16 DepthComponent16 -> gl_DEPTH_COMPONENT16 DepthComponent24 -> gl_DEPTH_COMPONENT24 DepthComponent32 -> gl_DEPTH_COMPONENT32 Luminance4 -> gl_LUMINANCE4 Luminance8 -> gl_LUMINANCE8 Luminance12 -> gl_LUMINANCE12 Luminance16 -> gl_LUMINANCE16 Luminance4Alpha4 -> gl_LUMINANCE4_ALPHA4 Luminance6Alpha2 -> gl_LUMINANCE6_ALPHA2 Luminance8Alpha8 -> gl_LUMINANCE8_ALPHA8 Luminance12Alpha4 -> gl_LUMINANCE12_ALPHA4 Luminance12Alpha12 -> gl_LUMINANCE12_ALPHA12 Luminance16Alpha16 -> gl_LUMINANCE16_ALPHA16 Intensity -> gl_INTENSITY Intensity4 -> gl_INTENSITY4 Intensity8 -> gl_INTENSITY8 Intensity12 -> gl_INTENSITY12 Intensity16 -> gl_INTENSITY16 R3G3B2 -> gl_R3_G3_B2 RGB4 -> gl_RGB4 RGB5 -> gl_RGB5 RGB8 -> gl_RGB8 RGB10 -> gl_RGB10 RGB12 -> gl_RGB12 RGB16 -> gl_RGB16 RGBA2 -> gl_RGBA2 RGBA4 -> gl_RGBA4 RGB5A1 -> gl_RGB5_A1 RGBA8 -> gl_RGBA8 RGB10A2 -> gl_RGB10_A2 RGBA12 -> gl_RGBA12 RGBA16 -> gl_RGBA16 SRGB8 -> gl_SRGB8 SRGB8Alpha8 -> gl_SRGB8_ALPHA8 R16F -> gl_R16F RG16F -> gl_RG16F RGB16F -> gl_RGB16F RGBA16F -> gl_RGBA16F R32F -> gl_R32F RG32F -> gl_RG32F RGB32F -> gl_RGB32F RGBA32F -> gl_RGBA32F R8I -> gl_R8I R8UI -> gl_R8UI R16I -> gl_R16I R16UI -> gl_R16UI R32I -> gl_R32I R32UI -> gl_R32UI RG8I -> gl_RG8I RG8UI -> gl_RG8UI RG16I -> gl_RG16I RG16UI -> gl_RG16UI RG32I -> gl_R32I RG32UI -> gl_R32UI RGB8I -> gl_RGB8I RGB8UI -> gl_RGB8UI RGB16I -> gl_RGB16I RGB16UI -> gl_RGB16UI RGB32I -> gl_RGB32I RGB32UI -> gl_RGB32UI RGBA8I -> gl_RGBA8I RGBA8UI -> gl_RGBA8UI RGBA16I -> gl_RGBA16I RGBA16UI -> gl_RGBA16UI RGBA32I -> gl_RGBA32I RGBA32UI -> gl_RGBA32UI SLuminance8 -> gl_SLUMINANCE8 SLuminance8Alpha8 -> gl_SLUMINANCE8_ALPHA8 CompressedAlpha -> gl_COMPRESSED_ALPHA CompressedLuminance -> gl_COMPRESSED_LUMINANCE CompressedLuminanceAlpha -> gl_COMPRESSED_LUMINANCE_ALPHA CompressedIntensity -> gl_COMPRESSED_INTENSITY CompressedRed -> gl_COMPRESSED_RED CompressedRG -> gl_COMPRESSED_RG CompressedRGB -> gl_COMPRESSED_RGB CompressedRGBA -> gl_COMPRESSED_RGBA CompressedSRGB -> gl_COMPRESSED_SRGB CompressedSRGBAlpha -> gl_COMPRESSED_SRGB_ALPHA CompressedSLuminance -> gl_COMPRESSED_SLUMINANCE CompressedSLuminanceAlpha -> gl_COMPRESSED_SLUMINANCE_ALPHA CompressedRedRGTC1 -> gl_COMPRESSED_RED_RGTC1 CompressedSignedRedRGTC1 -> gl_COMPRESSED_SIGNED_RED_RGTC1 CompressedRG_RGTC2 -> gl_COMPRESSED_RG_RGTC2 CompressedSignedRG_RGTC2 -> gl_COMPRESSED_SIGNED_RG_RGTC2 DepthComponent32f -> gl_DEPTH_COMPONENT32F Depth32fStencil8 -> gl_DEPTH32F_STENCIL8 RGB9E5 -> gl_RGB9_E5 R11fG11fB10f -> gl_R11F_G11F_B10F StencilIndex1 -> gl_STENCIL_INDEX1 StencilIndex4 -> gl_STENCIL_INDEX4 StencilIndex8 -> gl_STENCIL_INDEX8 StencilIndex16 -> gl_STENCIL_INDEX16 -- *sigh* The OpenGL API is sometimes a bit creative in its usage of types... marshalPixelInternalFormat' :: PixelInternalFormat -> GLenum marshalPixelInternalFormat' = fromIntegral . marshalPixelInternalFormat unmarshalPixelInternalFormat :: GLint -> PixelInternalFormat unmarshalPixelInternalFormat x | y == gl_ALPHA = Alpha' | y == gl_DEPTH_COMPONENT = DepthComponent' | y == gl_LUMINANCE = Luminance' | y == gl_LUMINANCE_ALPHA = LuminanceAlpha' | y == gl_RGB = RGB' | y == gl_RGBA = RGBA' | y == gl_SRGB = SRGB | y == gl_SRGB_ALPHA = SRGBAlpha | y == gl_SLUMINANCE = SLuminance | y == gl_SLUMINANCE_ALPHA = SLuminanceAlpha | y == gl_ALPHA4 = Alpha4 | y == gl_ALPHA8 = Alpha8 | y == gl_ALPHA12 = Alpha12 | y == gl_ALPHA16 = Alpha16 | y == gl_DEPTH_COMPONENT16 = DepthComponent16 | y == gl_DEPTH_COMPONENT24 = DepthComponent24 | y == gl_DEPTH_COMPONENT32 = DepthComponent32 | y == gl_LUMINANCE4 = Luminance4 | y == gl_LUMINANCE8 = Luminance8 | y == gl_LUMINANCE12 = Luminance12 | y == gl_LUMINANCE16 = Luminance16 | y == gl_LUMINANCE4_ALPHA4 = Luminance4Alpha4 | y == gl_LUMINANCE6_ALPHA2 = Luminance6Alpha2 | y == gl_LUMINANCE8_ALPHA8 = Luminance8Alpha8 | y == gl_LUMINANCE12_ALPHA4 = Luminance12Alpha4 | y == gl_LUMINANCE12_ALPHA12 = Luminance12Alpha12 | y == gl_LUMINANCE16_ALPHA16 = Luminance16Alpha16 | y == gl_INTENSITY = Intensity | y == gl_INTENSITY4 = Intensity4 | y == gl_INTENSITY8 = Intensity8 | y == gl_INTENSITY12 = Intensity12 | y == gl_INTENSITY16 = Intensity16 | y == gl_R3_G3_B2 = R3G3B2 | y == gl_RGB4 = RGB4 | y == gl_RGB5 = RGB5 | y == gl_RGB8 = RGB8 | y == gl_RGB10 = RGB10 | y == gl_RGB12 = RGB12 | y == gl_RGB16 = RGB16 | y == gl_RGBA2 = RGBA2 | y == gl_RGBA4 = RGBA4 | y == gl_RGB5_A1 = RGB5A1 | y == gl_RGBA8 = RGBA8 | y == gl_RGB10_A2 = RGB10A2 | y == gl_RGBA12 = RGBA12 | y == gl_RGBA16 = RGBA16 | y == gl_SRGB8 = SRGB8 | y == gl_SRGB8_ALPHA8 = SRGB8Alpha8 | y == gl_R16F = R16F | y == gl_RG16F = RG16F | y == gl_RGB16F = RGB16F | y == gl_RGBA16F = RGBA16F | y == gl_R32F = R32F | y == gl_RG32F = RG32F | y == gl_RGB32F = RGB32F | y == gl_RGBA32F = RGBA32F | y == gl_R8I = R8I | y == gl_R8UI = R8UI | y == gl_R16I = R16I | y == gl_R16UI = R16UI | y == gl_R32I = R32I | y == gl_R32UI = R32UI | y == gl_RG8I = RG8I | y == gl_RG8UI = RG8UI | y == gl_RG16I = RG16I | y == gl_RG16UI = RG16UI | y == gl_R32I = RG32I | y == gl_R32UI = RG32UI | y == gl_RGB8I = RGB8I | y == gl_RGB8UI = RGB8UI | y == gl_RGB16I = RGB16I | y == gl_RGB16UI = RGB16UI | y == gl_RGB32I = RGB32I | y == gl_RGB32UI = RGB32UI | y == gl_RGBA8I = RGBA8I | y == gl_RGBA8UI = RGBA8UI | y == gl_RGBA16I = RGBA16I | y == gl_RGBA16UI = RGBA16UI | y == gl_RGBA32I = RGBA32I | y == gl_RGBA32UI = RGBA32UI | y == gl_SLUMINANCE8 = SLuminance8 | y == gl_SLUMINANCE8_ALPHA8 = SLuminance8Alpha8 | y == gl_COMPRESSED_ALPHA = CompressedAlpha | y == gl_COMPRESSED_LUMINANCE = CompressedLuminance | y == gl_COMPRESSED_LUMINANCE_ALPHA = CompressedLuminanceAlpha | y == gl_COMPRESSED_INTENSITY = CompressedIntensity | y == gl_COMPRESSED_RED = CompressedRed | y == gl_COMPRESSED_RG = CompressedRG | y == gl_COMPRESSED_RGB = CompressedRGB | y == gl_COMPRESSED_RGBA = CompressedRGBA | y == gl_COMPRESSED_SRGB = CompressedSRGB | y == gl_COMPRESSED_SRGB_ALPHA = CompressedSRGBAlpha | y == gl_COMPRESSED_SLUMINANCE = CompressedSLuminance | y == gl_COMPRESSED_SLUMINANCE_ALPHA = CompressedSLuminanceAlpha | y == gl_COMPRESSED_RED_RGTC1 = CompressedRedRGTC1 | y == gl_COMPRESSED_SIGNED_RED_RGTC1 = CompressedSignedRedRGTC1 | y == gl_COMPRESSED_RG_RGTC2 = CompressedRG_RGTC2 | y == gl_COMPRESSED_SIGNED_RG_RGTC2 = CompressedSignedRG_RGTC2 | y == gl_DEPTH_COMPONENT32F = DepthComponent32f | y == gl_DEPTH32F_STENCIL8 = Depth32fStencil8 | y == gl_RGB9_E5 = RGB9E5 | y == gl_STENCIL_INDEX1 = StencilIndex1 | y == gl_STENCIL_INDEX4 = StencilIndex4 | y == gl_STENCIL_INDEX8 = StencilIndex8 | y == gl_STENCIL_INDEX16 = StencilIndex16 -- legacy values | y == 1 = Luminance' | y == 2 = LuminanceAlpha' | y == 3 = RGB' | y == 4 = RGBA' | otherwise = error ("unmarshalPixelInternalFormat: illegal value " ++ show x) where y = fromIntegral x -- Note: The following formats are still missing, it's a bit unclear how to -- handle these nicely. From the EXT_texture_sRGB spec: -- -- Accepted by the <internalformat> parameter of TexImage2D, CopyTexImage2D, -- and CompressedTexImage2DARB and the <format> parameter of -- CompressedTexSubImage2DARB: -- -- COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C -- COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D -- COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E -- COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/Texturing/PixelInternalFormat.hs
bsd-3-clause
11,131
0
9
2,511
2,579
1,313
1,266
344
110
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Plug-n-Hack | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
983
95
29
158
429
224
205
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 1 #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Typeable.Lens -- Copyright : (C) 2012-15 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : Rank2Types -- ---------------------------------------------------------------------------- module Data.Typeable.Lens ( _cast , _gcast ) where import Control.Lens import Data.Typeable import Data.Maybe #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif -- | A 'Traversal'' for working with a 'cast' of a 'Typeable' value. _cast :: (Typeable s, Typeable a) => Traversal' s a _cast f s = case cast s of Just a -> fromMaybe (error "_cast: recast failed") . cast <$> f a Nothing -> pure s {-# INLINE _cast #-} -- | A 'Traversal'' for working with a 'gcast' of a 'Typeable' value. _gcast :: (Typeable s, Typeable a) => Traversal' (c s) (c a) _gcast f s = case gcast s of Just a -> fromMaybe (error "_gcast: recast failed") . gcast <$> f a Nothing -> pure s {-# INLINE _gcast #-}
danidiaz/lens
src/Data/Typeable/Lens.hs
bsd-3-clause
1,235
0
12
219
228
125
103
18
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , NoImplicitPrelude , ForeignFunctionInterface , ExistentialQuantification #-} #ifdef __GLASGOW_HASKELL__ {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} #endif #include "Typeable.h" ----------------------------------------------------------------------------- -- | -- Module : Control.OldException -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (extended exceptions) -- -- This module provides support for raising and catching both built-in -- and user-defined exceptions. -- -- In addition to exceptions thrown by 'IO' operations, exceptions may -- be thrown by pure code (imprecise exceptions) or by external events -- (asynchronous exceptions), but may only be caught in the 'IO' monad. -- For more details, see: -- -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones, -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson, -- in /PLDI'99/. -- -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton -- Jones, Andy Moran and John Reppy, in /PLDI'01/. -- ----------------------------------------------------------------------------- module Control.OldException {-# DEPRECATED "Future versions of base will not support the old exceptions style. Please switch to extensible exceptions." #-} ( -- * The Exception type Exception(..), -- instance Eq, Ord, Show, Typeable New.IOException, -- instance Eq, Ord, Show, Typeable New.ArithException(..), -- instance Eq, Ord, Show, Typeable New.ArrayException(..), -- instance Eq, Ord, Show, Typeable New.AsyncException(..), -- instance Eq, Ord, Show, Typeable -- * Throwing exceptions throwIO, -- :: Exception -> IO a throw, -- :: Exception -> a ioError, -- :: IOError -> IO a #ifdef __GLASGOW_HASKELL__ -- XXX Need to restrict the type of this: New.throwTo, -- :: ThreadId -> Exception -> a #endif -- * Catching Exceptions -- |There are several functions for catching and examining -- exceptions; all of them may only be used from within the -- 'IO' monad. -- ** The @catch@ functions catch, -- :: IO a -> (Exception -> IO a) -> IO a catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a -- ** The @handle@ functions handle, -- :: (Exception -> IO a) -> IO a -> IO a handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a -- ** The @try@ functions try, -- :: IO a -> IO (Either Exception a) tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a) -- ** The @evaluate@ function evaluate, -- :: a -> IO a -- ** The @mapException@ function mapException, -- :: (Exception -> Exception) -> a -> a -- ** Exception predicates -- $preds ioErrors, -- :: Exception -> Maybe IOError arithExceptions, -- :: Exception -> Maybe ArithException errorCalls, -- :: Exception -> Maybe String dynExceptions, -- :: Exception -> Maybe Dynamic assertions, -- :: Exception -> Maybe String asyncExceptions, -- :: Exception -> Maybe AsyncException userErrors, -- :: Exception -> Maybe String -- * Dynamic exceptions -- $dynamic throwDyn, -- :: Typeable ex => ex -> b #ifdef __GLASGOW_HASKELL__ throwDynTo, -- :: Typeable ex => ThreadId -> ex -> b #endif catchDyn, -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a -- * Asynchronous Exceptions -- $async -- ** Asynchronous exception control -- |The following two functions allow a thread to control delivery of -- asynchronous exceptions during a critical region. block, -- :: IO a -> IO a unblock, -- :: IO a -> IO a -- *** Applying @block@ to an exception handler -- $block_handler -- *** Interruptible operations -- $interruptible -- * Assertions assert, -- :: Bool -> a -> a -- * Utilities bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO () bracket_, -- :: IO a -> IO b -> IO c -> IO () bracketOnError, finally, -- :: IO a -> IO b -> IO a #ifdef __GLASGOW_HASKELL__ setUncaughtExceptionHandler, -- :: (Exception -> IO ()) -> IO () getUncaughtExceptionHandler -- :: IO (Exception -> IO ()) #endif ) where #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Show -- import GHC.IO ( IO ) import GHC.IO.Handle.FD ( stdout ) import qualified GHC.IO as New import qualified GHC.IO.Exception as New import GHC.Conc hiding (setUncaughtExceptionHandler, getUncaughtExceptionHandler) import Data.IORef ( IORef, newIORef, readIORef, writeIORef ) import Foreign.C.String ( CString, withCString ) import GHC.IO.Handle ( hFlush ) #endif #ifdef __HUGS__ import Prelude hiding (catch) import Hugs.Prelude as New (ExitCode(..)) #endif import qualified Control.Exception as New import Control.Exception ( toException, fromException, throw, block, unblock, mask, evaluate, throwIO ) import System.IO.Error hiding ( catch, try ) import System.IO.Unsafe (unsafePerformIO) import Data.Dynamic import Data.Either import Data.Maybe #ifdef __NHC__ import System.IO.Error (catch, ioError) import IO (bracket) import DIOError -- defn of IOError type -- minimum needed for nhc98 to pretend it has Exceptions type Exception = IOError type IOException = IOError data ArithException data ArrayException data AsyncException throwIO :: Exception -> IO a throwIO = ioError throw :: Exception -> a throw = unsafePerformIO . throwIO evaluate :: a -> IO a evaluate x = x `seq` return x ioErrors :: Exception -> Maybe IOError ioErrors e = Just e arithExceptions :: Exception -> Maybe ArithException arithExceptions = const Nothing errorCalls :: Exception -> Maybe String errorCalls = const Nothing dynExceptions :: Exception -> Maybe Dynamic dynExceptions = const Nothing assertions :: Exception -> Maybe String assertions = const Nothing asyncExceptions :: Exception -> Maybe AsyncException asyncExceptions = const Nothing userErrors :: Exception -> Maybe String userErrors (UserError _ s) = Just s userErrors _ = Nothing block :: IO a -> IO a block = id unblock :: IO a -> IO a unblock = id assert :: Bool -> a -> a assert True x = x assert False _ = throw (UserError "" "Assertion failed") #endif ----------------------------------------------------------------------------- -- Catching exceptions -- |This is the simplest of the exception-catching functions. It -- takes a single argument, runs it, and if an exception is raised -- the \"handler\" is executed, with the value of the exception passed as an -- argument. Otherwise, the result is returned as normal. For example: -- -- > catch (openFile f ReadMode) -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e)) -- -- For catching exceptions in pure (non-'IO') expressions, see the -- function 'evaluate'. -- -- Note that due to Haskell\'s unspecified evaluation order, an -- expression may return one of several possible exceptions: consider -- the expression @error \"urk\" + 1 \`div\` 0@. Does -- 'catch' execute the handler passing -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@? -- -- The answer is \"either\": 'catch' makes a -- non-deterministic choice about which exception to catch. If you -- call it again, you might get a different exception back. This is -- ok, because 'catch' is an 'IO' computation. -- -- Note that 'catch' catches all types of exceptions, and is generally -- used for \"cleaning up\" before passing on the exception using -- 'throwIO'. It is not good practice to discard the exception and -- continue, without first checking the type of the exception (it -- might be a 'ThreadKilled', for example). In this case it is usually better -- to use 'catchJust' and select the kinds of exceptions to catch. -- -- Also note that the "Prelude" also exports a function called -- 'Prelude.catch' with a similar type to 'Control.OldException.catch', -- except that the "Prelude" version only catches the IO and user -- families of exceptions (as required by Haskell 98). -- -- We recommend either hiding the "Prelude" version of 'Prelude.catch' -- when importing "Control.OldException": -- -- > import Prelude hiding (catch) -- -- or importing "Control.OldException" qualified, to avoid name-clashes: -- -- > import qualified Control.OldException as C -- -- and then using @C.catch@ -- catch :: IO a -- ^ The computation to run -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised -> IO a -- note: bundling the exceptions is done in the New.Exception -- instance of Exception; see below. catch = New.catch -- | The function 'catchJust' is like 'catch', but it takes an extra -- argument which is an /exception predicate/, a function which -- selects which type of exceptions we\'re interested in. There are -- some predefined exception predicates for useful subsets of -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example, -- to catch just calls to the 'error' function, we could use -- -- > result <- catchJust errorCalls thing_to_try handler -- -- Any other exceptions which are not matched by the predicate -- are re-raised, and may be caught by an enclosing -- 'catch' or 'catchJust'. catchJust :: (Exception -> Maybe b) -- ^ Predicate to select exceptions -> IO a -- ^ Computation to run -> (b -> IO a) -- ^ Handler -> IO a catchJust p a handler = catch a handler' where handler' e = case p e of Nothing -> throw e Just b -> handler b -- | A version of 'catch' with the arguments swapped around; useful in -- situations where the code for the handler is shorter. For example: -- -- > do handle (\e -> exitWith (ExitFailure 1)) $ -- > ... handle :: (Exception -> IO a) -> IO a -> IO a handle = flip catch -- | A version of 'catchJust' with the arguments swapped around (see -- 'handle'). handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a handleJust p = flip (catchJust p) ----------------------------------------------------------------------------- -- 'mapException' -- | This function maps one exception into another as proposed in the -- paper \"A semantics for imprecise exceptions\". -- Notice that the usage of 'unsafePerformIO' is safe here. mapException :: (Exception -> Exception) -> a -> a mapException f v = unsafePerformIO (catch (evaluate v) (\x -> throw (f x))) ----------------------------------------------------------------------------- -- 'try' and variations. -- | Similar to 'catch', but returns an 'Either' result which is -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an -- exception was raised and its value is @e@. -- -- > try a = catch (Right `liftM` a) (return . Left) -- -- Note: as with 'catch', it is only polite to use this variant if you intend -- to re-throw the exception after performing whatever cleanup is needed. -- Otherwise, 'tryJust' is generally considered to be better. -- -- Also note that "System.IO.Error" also exports a function called -- 'System.IO.Error.try' with a similar type to 'Control.OldException.try', -- except that it catches only the IO and user families of exceptions -- (as required by the Haskell 98 @IO@ module). try :: IO a -> IO (Either Exception a) try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e)) -- | A variant of 'try' that takes an exception predicate to select -- which exceptions are caught (c.f. 'catchJust'). If the exception -- does not match the predicate, it is re-thrown. tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a) tryJust p a = do r <- try a case r of Right v -> return (Right v) Left e -> case p e of Nothing -> throw e Just b -> return (Left b) ----------------------------------------------------------------------------- -- Dynamic exceptions -- $dynamic -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an -- interface for throwing and catching exceptions of type 'Dynamic' -- (see "Data.Dynamic") which allows exception values of any type in -- the 'Typeable' class to be thrown and caught. -- | Raise any value as an exception, provided it is in the -- 'Typeable' class. throwDyn :: Typeable exception => exception -> b #ifdef __NHC__ throwDyn exception = throw (UserError "" "dynamic exception") #else throwDyn exception = throw (DynException (toDyn exception)) #endif #ifdef __GLASGOW_HASKELL__ -- | A variant of 'throwDyn' that throws the dynamic exception to an -- arbitrary thread (GHC only: c.f. 'throwTo'). throwDynTo :: Typeable exception => ThreadId -> exception -> IO () throwDynTo t exception = New.throwTo t (DynException (toDyn exception)) #endif /* __GLASGOW_HASKELL__ */ -- | Catch dynamic exceptions of the required type. All other -- exceptions are re-thrown, including dynamic exceptions of the wrong -- type. -- -- When using dynamic exceptions it is advisable to define a new -- datatype to use for your exception type, to avoid possible clashes -- with dynamic exceptions used in other libraries. -- catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a #ifdef __NHC__ catchDyn m k = m -- can't catch dyn exceptions in nhc98 #else catchDyn m k = New.catch m handler where handler ex = case ex of (DynException dyn) -> case fromDynamic dyn of Just exception -> k exception Nothing -> throw ex _ -> throw ex #endif ----------------------------------------------------------------------------- -- Exception Predicates -- $preds -- These pre-defined predicates may be used as the first argument to -- 'catchJust', 'tryJust', or 'handleJust' to select certain common -- classes of exceptions. #ifndef __NHC__ ioErrors :: Exception -> Maybe IOError arithExceptions :: Exception -> Maybe New.ArithException errorCalls :: Exception -> Maybe String assertions :: Exception -> Maybe String dynExceptions :: Exception -> Maybe Dynamic asyncExceptions :: Exception -> Maybe New.AsyncException userErrors :: Exception -> Maybe String ioErrors (IOException e) = Just e ioErrors _ = Nothing arithExceptions (ArithException e) = Just e arithExceptions _ = Nothing errorCalls (ErrorCall e) = Just e errorCalls _ = Nothing assertions (AssertionFailed e) = Just e assertions _ = Nothing dynExceptions (DynException e) = Just e dynExceptions _ = Nothing asyncExceptions (AsyncException e) = Just e asyncExceptions _ = Nothing userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e) userErrors _ = Nothing #endif ----------------------------------------------------------------------------- -- Some Useful Functions -- | When you want to acquire a resource, do some work with it, and -- then release the resource, it is a good idea to use 'bracket', -- because 'bracket' will install the necessary exception handler to -- release the resource in the event that an exception is raised -- during the computation. If an exception is raised, then 'bracket' will -- re-raise the exception (after performing the release). -- -- A common example is opening a file: -- -- > bracket -- > (openFile "filename" ReadMode) -- > (hClose) -- > (\handle -> do { ... }) -- -- The arguments to 'bracket' are in this order so that we can partially apply -- it, e.g.: -- -- > withFile name mode = bracket (openFile name mode) hClose -- #ifndef __NHC__ bracket :: IO a -- ^ computation to run first (\"acquire resource\") -> (a -> IO b) -- ^ computation to run last (\"release resource\") -> (a -> IO c) -- ^ computation to run in-between -> IO c -- returns the value from the in-between computation bracket before after thing = mask $ \restore -> do a <- before r <- catch (restore (thing a)) (\e -> do { _ <- after a; throw e }) _ <- after a return r #endif -- | A specialised variant of 'bracket' with just a computation to run -- afterward. -- finally :: IO a -- ^ computation to run first -> IO b -- ^ computation to run afterward (even if an exception -- was raised) -> IO a -- returns the value from the first computation a `finally` sequel = mask $ \restore -> do r <- catch (restore a) (\e -> do { _ <- sequel; throw e }) _ <- sequel return r -- | A variant of 'bracket' where the return value from the first computation -- is not required. bracket_ :: IO a -> IO b -> IO c -> IO c bracket_ before after thing = bracket before (const after) (const thing) -- | Like bracket, but only performs the final action if there was an -- exception raised by the in-between computation. bracketOnError :: IO a -- ^ computation to run first (\"acquire resource\") -> (a -> IO b) -- ^ computation to run last (\"release resource\") -> (a -> IO c) -- ^ computation to run in-between -> IO c -- returns the value from the in-between computation bracketOnError before after thing = mask $ \restore -> do a <- before catch (restore (thing a)) (\e -> do { _ <- after a; throw e }) -- ----------------------------------------------------------------------------- -- Asynchronous exceptions {- $async #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to external influences, and can be raised at any point during execution. 'StackOverflow' and 'HeapOverflow' are two examples of system-generated asynchronous exceptions. The primary source of asynchronous exceptions, however, is 'throwTo': > throwTo :: ThreadId -> Exception -> IO () 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one running thread to raise an arbitrary exception in another thread. The exception is therefore asynchronous with respect to the target thread, which could be doing anything at the time it receives the exception. Great care should be taken with asynchronous exceptions; it is all too easy to introduce race conditions by the over zealous use of 'throwTo'. -} {- $block_handler There\'s an implied 'mask_' around every exception handler in a call to one of the 'catch' family of functions. This is because that is what you want most of the time - it eliminates a common race condition in starting an exception handler, because there may be no exception handler on the stack to handle another exception if one arrives immediately. If asynchronous exceptions are blocked on entering the handler, though, we have time to install a new exception handler before being interrupted. If this weren\'t the default, one would have to write something like > mask $ \restore -> > catch (restore (...)) > (\e -> handler) If you need to unblock asynchronous exceptions again in the exception handler, just use 'unblock' as normal. Note that 'try' and friends /do not/ have a similar default, because there is no exception handler in this case. If you want to use 'try' in an asynchronous-exception-safe way, you will need to use 'mask'. -} {- $interruptible Some operations are /interruptible/, which means that they can receive asynchronous exceptions even in the scope of a 'mask'. Any function which may itself block is defined as interruptible; this includes 'Control.Concurrent.MVar.takeMVar' (but not 'Control.Concurrent.MVar.tryTakeMVar'), and most operations which perform some I\/O with the outside world. The reason for having interruptible operations is so that we can write things like > mask $ \restore -> do > a <- takeMVar m > catch (restore (...)) > (\e -> ...) if the 'Control.Concurrent.MVar.takeMVar' was not interruptible, then this particular combination could lead to deadlock, because the thread itself would be blocked in a state where it can\'t receive any asynchronous exceptions. With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be safe in the knowledge that the thread can receive exceptions right up until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds. Similar arguments apply for other interruptible operations like 'System.IO.openFile'. -} #if !(__GLASGOW_HASKELL__ || __NHC__) assert :: Bool -> a -> a assert True x = x assert False _ = throw (AssertionFailed "") #endif #ifdef __GLASGOW_HASKELL__ {-# NOINLINE uncaughtExceptionHandler #-} uncaughtExceptionHandler :: IORef (Exception -> IO ()) uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler) where defaultHandler :: Exception -> IO () defaultHandler ex = do (hFlush stdout) `New.catchAny` (\ _ -> return ()) let msg = case ex of Deadlock -> "no threads to run: infinite loop or deadlock?" ErrorCall s -> s other -> showsPrec 0 other "" withCString "%s" $ \cfmt -> withCString msg $ \cmsg -> errorBelch cfmt cmsg -- don't use errorBelch() directly, because we cannot call varargs functions -- using the FFI. foreign import ccall unsafe "HsBase.h errorBelch2" errorBelch :: CString -> CString -> IO () setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO () setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler getUncaughtExceptionHandler :: IO (Exception -> IO ()) getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler #endif -- ------------------------------------------------------------------------ -- Exception datatype and operations -- |The type of exceptions. Every kind of system-generated exception -- has a constructor in the 'Exception' type, and values of other -- types may be injected into 'Exception' by coercing them to -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions: -- "Control.OldException\#DynamicExceptions"). data Exception = ArithException New.ArithException -- ^Exceptions raised by arithmetic -- operations. (NOTE: GHC currently does not throw -- 'ArithException's except for 'DivideByZero'). | ArrayException New.ArrayException -- ^Exceptions raised by array-related -- operations. (NOTE: GHC currently does not throw -- 'ArrayException's). | AssertionFailed String -- ^This exception is thrown by the -- 'assert' operation when the condition -- fails. The 'String' argument contains the -- location of the assertion in the source program. | AsyncException New.AsyncException -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.OldException\#AsynchronousExceptions"). | BlockedOnDeadMVar -- ^The current thread was executing a call to -- 'Control.Concurrent.MVar.takeMVar' that could never return, -- because there are no other references to this 'MVar'. | BlockedIndefinitely -- ^The current thread was waiting to retry an atomic memory transaction -- that could never become possible to complete because there are no other -- threads referring to any of the TVars involved. | NestedAtomically -- ^The runtime detected an attempt to nest one STM transaction -- inside another one, presumably due to the use of -- 'unsafePeformIO' with 'atomically'. | Deadlock -- ^There are no runnable threads, so the program is -- deadlocked. The 'Deadlock' exception is -- raised in the main thread only (see also: "Control.Concurrent"). | DynException Dynamic -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.OldException\#DynamicExceptions"). | ErrorCall String -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String' -- argument of 'ErrorCall' is the string passed to 'error' when it was -- called. | ExitException New.ExitCode -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and -- 'System.Exit.exitFailure'). The 'ExitCode' argument is the value passed -- to 'System.Exit.exitWith'. An unhandled 'ExitException' exception in the -- main thread will cause the program to be terminated with the given -- exit code. | IOException New.IOException -- ^These are the standard IO exceptions generated by -- Haskell\'s @IO@ operations. See also "System.IO.Error". | NoMethodError String -- ^An attempt was made to invoke a class method which has -- no definition in this instance, and there was no default -- definition given in the class declaration. GHC issues a -- warning when you compile an instance which has missing -- methods. | NonTermination -- ^The current thread is stuck in an infinite loop. This -- exception may or may not be thrown when the program is -- non-terminating. | PatternMatchFail String -- ^A pattern matching failure. The 'String' argument should contain a -- descriptive message including the function name, source file -- and line number. | RecConError String -- ^An attempt was made to evaluate a field of a record -- for which no value was given at construction time. The -- 'String' argument gives the location of the -- record construction in the source program. | RecSelError String -- ^A field selection was attempted on a constructor that -- doesn\'t have the requested field. This can happen with -- multi-constructor records when one or more fields are -- missing from some of the constructors. The -- 'String' argument gives the location of the -- record selection in the source program. | RecUpdError String -- ^An attempt was made to update a field in a record, -- where the record doesn\'t have the requested field. This can -- only occur with multi-constructor records, when one or more -- fields are missing from some of the constructors. The -- 'String' argument gives the location of the -- record update in the source program. INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception") -- helper type for simplifying the type casting logic below data Caster = forall e . New.Exception e => Caster (e -> Exception) instance New.Exception Exception where -- We need to collect all the sorts of exceptions that used to be -- bundled up into the Exception type, and rebundle them for -- legacy handlers. fromException exc0 = foldr tryCast Nothing casters where tryCast (Caster f) e = case fromException exc0 of Just exc -> Just (f exc) _ -> e casters = [Caster (\exc -> ArithException exc), Caster (\exc -> ArrayException exc), Caster (\(New.AssertionFailed err) -> AssertionFailed err), Caster (\exc -> AsyncException exc), Caster (\New.BlockedIndefinitelyOnMVar -> BlockedOnDeadMVar), Caster (\New.BlockedIndefinitelyOnSTM -> BlockedIndefinitely), Caster (\New.NestedAtomically -> NestedAtomically), Caster (\New.Deadlock -> Deadlock), Caster (\exc -> DynException exc), Caster (\(New.ErrorCall err) -> ErrorCall err), Caster (\exc -> ExitException exc), Caster (\exc -> IOException exc), Caster (\(New.NoMethodError err) -> NoMethodError err), Caster (\New.NonTermination -> NonTermination), Caster (\(New.PatternMatchFail err) -> PatternMatchFail err), Caster (\(New.RecConError err) -> RecConError err), Caster (\(New.RecSelError err) -> RecSelError err), Caster (\(New.RecUpdError err) -> RecUpdError err), -- Anything else gets taken as a Dynamic exception. It's -- important that we put all exceptions into the old Exception -- type somehow, or throwing a new exception wouldn't cause -- the cleanup code for bracket, finally etc to happen. Caster (\exc -> DynException (toDyn (exc :: New.SomeException)))] -- Unbundle exceptions. toException (ArithException exc) = toException exc toException (ArrayException exc) = toException exc toException (AssertionFailed err) = toException (New.AssertionFailed err) toException (AsyncException exc) = toException exc toException BlockedOnDeadMVar = toException New.BlockedIndefinitelyOnMVar toException BlockedIndefinitely = toException New.BlockedIndefinitelyOnSTM toException NestedAtomically = toException New.NestedAtomically toException Deadlock = toException New.Deadlock -- If a dynamic exception is a SomeException then resurrect it, so -- that bracket, catch+throw etc rethrow the same exception even -- when the exception is in the new style. -- If it's not a SomeException, then just throw the Dynamic. toException (DynException exc) = case fromDynamic exc of Just exc' -> exc' Nothing -> toException exc toException (ErrorCall err) = toException (New.ErrorCall err) toException (ExitException exc) = toException exc toException (IOException exc) = toException exc toException (NoMethodError err) = toException (New.NoMethodError err) toException NonTermination = toException New.NonTermination toException (PatternMatchFail err) = toException (New.PatternMatchFail err) toException (RecConError err) = toException (New.RecConError err) toException (RecSelError err) = toException (New.RecSelError err) toException (RecUpdError err) = toException (New.RecUpdError err) instance Show Exception where showsPrec _ (IOException err) = shows err showsPrec _ (ArithException err) = shows err showsPrec _ (ArrayException err) = shows err showsPrec _ (ErrorCall err) = showString err showsPrec _ (ExitException err) = showString "exit: " . shows err showsPrec _ (NoMethodError err) = showString err showsPrec _ (PatternMatchFail err) = showString err showsPrec _ (RecSelError err) = showString err showsPrec _ (RecConError err) = showString err showsPrec _ (RecUpdError err) = showString err showsPrec _ (AssertionFailed err) = showString err showsPrec _ (DynException err) = showString "exception :: " . showsTypeRep (dynTypeRep err) showsPrec _ (AsyncException e) = shows e showsPrec p BlockedOnDeadMVar = showsPrec p New.BlockedIndefinitelyOnMVar showsPrec p BlockedIndefinitely = showsPrec p New.BlockedIndefinitelyOnSTM showsPrec p NestedAtomically = showsPrec p New.NestedAtomically showsPrec p NonTermination = showsPrec p New.NonTermination showsPrec p Deadlock = showsPrec p New.Deadlock instance Eq Exception where IOException e1 == IOException e2 = e1 == e2 ArithException e1 == ArithException e2 = e1 == e2 ArrayException e1 == ArrayException e2 = e1 == e2 ErrorCall e1 == ErrorCall e2 = e1 == e2 ExitException e1 == ExitException e2 = e1 == e2 NoMethodError e1 == NoMethodError e2 = e1 == e2 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2 RecSelError e1 == RecSelError e2 = e1 == e2 RecConError e1 == RecConError e2 = e1 == e2 RecUpdError e1 == RecUpdError e2 = e1 == e2 AssertionFailed e1 == AssertionFailed e2 = e1 == e2 DynException _ == DynException _ = False -- incomparable AsyncException e1 == AsyncException e2 = e1 == e2 BlockedOnDeadMVar == BlockedOnDeadMVar = True NonTermination == NonTermination = True NestedAtomically == NestedAtomically = True Deadlock == Deadlock = True _ == _ = False
ssaavedra/liquidhaskell
benchmarks/base-4.5.1.0/Control/OldException.hs
bsd-3-clause
33,136
0
16
8,144
4,355
2,385
1,970
-1
-1
{-# OPTIONS -fno-warn-unused-imports #-} #include "HsConfigure.h" -- #hide module Data.Time.LocalTime.TimeOfDay ( -- * Time of day TimeOfDay(..),midnight,midday,makeTimeOfDayValid, utcToLocalTimeOfDay,localToUTCTimeOfDay, timeToTimeOfDay,timeOfDayToTime, dayFractionToTimeOfDay,timeOfDayToDayFraction ) where import Data.Time.LocalTime.TimeZone import Data.Time.Calendar.Private import Data.Time.Clock import Control.DeepSeq import Data.Typeable import Data.Fixed #if LANGUAGE_Rank2Types import Data.Data #endif -- | Time of day as represented in hour, minute and second (with picoseconds), typically used to express local time of day. data TimeOfDay = TimeOfDay { -- | range 0 - 23 todHour :: Int, -- | range 0 - 59 todMin :: Int, -- | Note that 0 <= todSec < 61, accomodating leap seconds. -- Any local minute may have a leap second, since leap seconds happen in all zones simultaneously todSec :: Pico } deriving (Eq,Ord #if LANGUAGE_DeriveDataTypeable #if LANGUAGE_Rank2Types #if HAS_DataPico ,Data, Typeable #endif #endif #endif ) instance NFData TimeOfDay where rnf (TimeOfDay h m s) = h `deepseq` m `deepseq` s `seq` () -- FIXME: Data.Fixed had no NFData instances yet at time of writing -- | Hour zero midnight :: TimeOfDay midnight = TimeOfDay 0 0 0 -- | Hour twelve midday :: TimeOfDay midday = TimeOfDay 12 0 0 instance Show TimeOfDay where show (TimeOfDay h m s) = (show2 (Just '0') h) ++ ":" ++ (show2 (Just '0') m) ++ ":" ++ (show2Fixed (Just '0') s) makeTimeOfDayValid :: Int -> Int -> Pico -> Maybe TimeOfDay makeTimeOfDayValid h m s = do _ <- clipValid 0 23 h _ <- clipValid 0 59 m _ <- clipValid 0 60.999999999999 s return (TimeOfDay h m s) -- | Convert a ToD in UTC to a ToD in some timezone, together with a day adjustment. utcToLocalTimeOfDay :: TimeZone -> TimeOfDay -> (Integer,TimeOfDay) utcToLocalTimeOfDay zone (TimeOfDay h m s) = (fromIntegral (div h' 24),TimeOfDay (mod h' 24) (mod m' 60) s) where m' = m + timeZoneMinutes zone h' = h + (div m' 60) -- | Convert a ToD in some timezone to a ToD in UTC, together with a day adjustment. localToUTCTimeOfDay :: TimeZone -> TimeOfDay -> (Integer,TimeOfDay) localToUTCTimeOfDay zone = utcToLocalTimeOfDay (minutesToTimeZone (negate (timeZoneMinutes zone))) posixDayLength :: DiffTime posixDayLength = fromInteger 86400 -- | Get a TimeOfDay given a time since midnight. -- Time more than 24h will be converted to leap-seconds. timeToTimeOfDay :: DiffTime -> TimeOfDay timeToTimeOfDay dt | dt >= posixDayLength = TimeOfDay 23 59 (60 + (realToFrac (dt - posixDayLength))) timeToTimeOfDay dt = TimeOfDay (fromInteger h) (fromInteger m) s where s' = realToFrac dt s = mod' s' 60 m' = div' s' 60 m = mod' m' 60 h = div' m' 60 -- | Find out how much time since midnight a given TimeOfDay is. timeOfDayToTime :: TimeOfDay -> DiffTime timeOfDayToTime (TimeOfDay h m s) = ((fromIntegral h) * 60 + (fromIntegral m)) * 60 + (realToFrac s) -- | Get a TimeOfDay given the fraction of a day since midnight. dayFractionToTimeOfDay :: Rational -> TimeOfDay dayFractionToTimeOfDay df = timeToTimeOfDay (realToFrac (df * 86400)) -- | Get the fraction of a day since midnight given a TimeOfDay. timeOfDayToDayFraction :: TimeOfDay -> Rational timeOfDayToDayFraction tod = realToFrac (timeOfDayToTime tod) / realToFrac posixDayLength
beni55/haste-compiler
libraries/time/lib/Data/Time/LocalTime/TimeOfDay.hs
bsd-3-clause
3,343
14
13
572
857
464
393
54
1
module Feature.AuthSpec where -- {{{ Imports import Test.Hspec import Test.Hspec.Wai import Test.Hspec.Wai.JSON import Network.HTTP.Types import SpecHelper -- }}} spec :: Spec spec = beforeAll (clearTable "postgrest.auth") . afterAll_ (clearTable "postgrest.auth") $ around withApp $ describe "authorization" $ do it "hides tables that anonymous does not own" $ get "/authors_only" `shouldRespondWith` 404 it "indicates login failure (BasicAuth)" $ do let auth = authHeaderBasic "postgrest_test_author" "fakefake" request methodGet "/authors_only" [auth] "" `shouldRespondWith` 401 it "allows users with permissions to see their tables (BasicAuth)" $ do _ <- post "/postgrest/users" [json| { "id":"jdoe", "pass": "1234", "role": "postgrest_test_author" } |] let auth = authHeaderBasic "jdoe" "1234" request methodGet "/authors_only" [auth] "" `shouldRespondWith` 200 it "allows users to login (JWT)" $ do _ <- post "/postgrest/users" [json| { "id":"jdoe", "pass": "1234", "role": "postgrest_test_author" } |] post "/postgrest/tokens" [json| { "id":"jdoe", "pass": "1234" } |] `shouldRespondWith` ResponseMatcher { matchBody = Just [json| {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.y4vZuu1dDdwAl0-S00MCRWRYMlJ5YAMSir6Es6WtWx0"} |] , matchStatus = 201 , matchHeaders = ["Content-Type" <:> "application/json"] } it "indicates login failure (JWT)" $ do _ <- post "/postgrest/users" [json| { "id":"jdoe", "pass": "1234", "role": "postgrest_test_author" } |] post "/postgrest/tokens" [json| { "id":"jdoe", "pass": "NOPE" } |] `shouldRespondWith` ResponseMatcher { matchBody = Just [json| {"message":"Failed authentication."} |] , matchStatus = 401 , matchHeaders = ["Content-Type" <:> "application/json"] } it "allows users with permissions to see their tables (JWT)" $ do _ <- post "/postgrest/users" [json| { "id":"jdoe", "pass": "1234", "role": "postgrest_test_author" } |] let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.y4vZuu1dDdwAl0-S00MCRWRYMlJ5YAMSir6Es6WtWx0" request methodGet "/authors_only" [auth] "" `shouldRespondWith` 200
nayosx/postgrest
test/Feature/AuthSpec.hs
mit
2,361
0
15
436
425
229
196
-1
-1
module MyLibModule where main :: IO () main = error ""
themoritz/cabal
cabal-testsuite/PackageTests/AutogenModules/SrcDist/MyLibModule.hs
bsd-3-clause
56
0
6
12
22
12
10
3
1
{-# LANGUAGE TypeFamilies #-} module T10534 where import T10534a newtype instance DF a = MkDF () unsafeCoerce :: a -> b unsafeCoerce = silly
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T10534.hs
bsd-3-clause
145
0
6
28
37
22
15
6
1
{-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -freduction-depth=50 #-} module CoqLNOutputThmFv where import Data.Maybe ( catMaybes ) import Text.Printf ( printf ) import AST import ASTAnalysis import ComputationMonad import CoqLNOutputCommon import CoqLNOutputCombinators fvThms :: ASTAnalysis -> [[NtRoot]] -> M String fvThms aa nts = do { fv_close_recs <- mapM (local . fv_close_rec aa) nts ; fv_closes <- mapM (local . fv_close aa) nts ; fv_open_lower_recs <- mapM (local . fv_open_lower_rec aa) nts ; fv_open_lowers <- mapM (local . fv_open_lower aa) nts ; fv_open_upper_recs <- mapM (local . fv_open_upper_rec aa) nts ; fv_open_uppers <- mapM (local . fv_open_upper aa) nts ; fv_subst_freshs <- mapM (local . fv_subst_fresh aa) nts ; fv_subst_lowers <- mapM (local . fv_subst_lower aa) nts ; fv_subst_notins <- mapM (local . fv_subst_notin aa) nts ; fv_subst_uppers <- mapM (local . fv_subst_upper aa) nts ; return $ printf "Ltac %s ::= auto with set %s; tauto.\n\ \Ltac %s ::= autorewrite with %s.\n\ \\n" defaultAuto hintDb defaultAutoRewr hintDb ++ concat fv_close_recs ++ concat fv_closes ++ concat fv_open_lower_recs ++ concat fv_open_lowers ++ concat fv_open_upper_recs ++ concat fv_open_uppers ++ concat fv_subst_freshs ++ concat fv_subst_lowers ++ concat fv_subst_notins ++ concat fv_subst_uppers ++ "\n" } {- | @fv (close_rec n x e) [=] remove x (fv e)@. -} fv_close_rec :: ASTAnalysis -> [NtRoot] -> M String fv_close_rec aaa nt1s = do { thms <- processNt1Nt2Mv2' aaa nt1s thm ; names <- processNt1Nt2Mv2' aaa nt1s name ; proofs <- processNt1Nt2Mv2' aaa nt1s pf ; let proof = map head proofs ; mutualLemmaText2 Resolve Rewrite Hide [hintDb] Prop names thms proof } where pf _ _ _ _ _ _ = do { types <- processNt1 aaa nt1s ntType ; return $ mutPfStart Prop types ++ defaultSimp ++ "; " ++ fsetdecTac ++ "." } name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; close_fn <- closeRecName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ close_fn } thm aa nt1 _ mv2 _ mv2' | mv2 == mv2' = do { k <- newName bvarRoot ; e <- newName nt1 ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; close_fn <- closeRecName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [=] %s %s (%s %s)" e x k fv_fn close_fn k x e mvSetRemove x fv_fn e } thm aa nt1 _ mv2 _ mv2' | otherwise = do { k <- newName bvarRoot ; e <- newName nt1 ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; close_fn <- closeRecName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [=] %s %s" e x k fv_fn close_fn k x e fv_fn e } {- | @fv (close x e) [=] remove x (fv e)@. -} fv_close :: ASTAnalysis -> [NtRoot] -> M String fv_close aaa nt1s = do { gens <- processNt1Nt2Mv2' aaa nt1s gen ; names <- processNt1Nt2Mv2' aaa nt1s name ; lemmaText2 Resolve Rewrite NoHide [hintDb] names gens } where name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; close_fn <- closeName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ close_fn } gen aa nt1 _ mv2 _ mv2' | mv2 == mv2' = do { e <- newName nt1 ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; close_fn <- closeName aa nt1 mv2' ; let stmt = printf "forall %s %s,\n\ \ %s (%s %s %s) [=] %s %s (%s %s)" e x fv_fn close_fn x e mvSetRemove x fv_fn e ; let proof = printf "unfold %s; %s." close_fn defaultSimp ; return (stmt, proof) } gen aa nt1 _ mv2 _ mv2' | otherwise = do { e <- newName nt1 ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; close_fn <- closeName aa nt1 mv2' ; let stmt = printf "forall %s %s,\n\ \ %s (%s %s %s) [=] %s %s" e x fv_fn close_fn x e fv_fn e ; let proof = printf "unfold %s; %s." close_fn defaultSimp ; return (stmt, proof) } {- | @fv e [<=] fv (open_rec k e' e)@. -} fv_open_lower_rec :: ASTAnalysis -> [NtRoot] -> M String fv_open_lower_rec aaa nt1s = do { thms <- processNt1Nt2Mv2' aaa nt1s thm ; names <- processNt1Nt2Mv2' aaa nt1s name ; proofs <- processNt1Nt2Mv2' aaa nt1s pf ; let proof = map head proofs ; mutualLemmaText2 Resolve NoRewrite Hide [hintDb] Prop names thms proof } where pf _ _ _ _ _ _ = do { types <- processNt1 aaa nt1s ntType ; return $ mutPfStart Prop types ++ defaultSimp ++ "; " ++ fsetdecTac ++ "." } name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; open_fn <- openRecName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ open_fn ++ "_lower" } thm aa nt1 _ mv2 nt2' mv2' = do { k <- newName bvarRoot ; e <- newName nt1 ; u <- newName nt2' ; fv_fn <- fvName aa nt1 mv2 ; open_fn <- openRecName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s %s [<=] %s (%s %s %s %s)" e u k fv_fn e fv_fn open_fn k u e } {- | @fv e [<=] fv (open e e')@. -} fv_open_lower :: ASTAnalysis -> [NtRoot] -> M String fv_open_lower aaa nt1s = do { gens <- processNt1Nt2Mv2' aaa nt1s gen ; names <- processNt1Nt2Mv2' aaa nt1s name ; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens } where name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; open_fn <- openName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ open_fn ++ "_lower" } gen aa nt1 _ mv2 nt2' mv2' = do { e <- newName nt1 ; u <- newName nt2' ; fv_fn <- fvName aa nt1 mv2 ; open_fn <- openName aa nt1 mv2' -- ORDER TO OPEN ; let stmt = printf "forall %s %s,\n\ \ %s %s [<=] %s (%s %s %s)" e u fv_fn e fv_fn open_fn e u ; let proof = printf "unfold %s; %s." open_fn defaultSimp ; return (stmt, proof) } {- | @fv (open_rec n e' e) [<=] fv e' `union` fv e@. -} fv_open_upper_rec :: ASTAnalysis -> [NtRoot] -> M String fv_open_upper_rec aaa nt1s = do { thms <- processNt1Nt2Mv2' aaa nt1s thm ; names <- processNt1Nt2Mv2' aaa nt1s name ; proofs <- processNt1Nt2Mv2' aaa nt1s pf ; let proof = map head proofs ; mutualLemmaText2 Resolve NoRewrite Hide [hintDb] Prop names thms proof } where pf _ _ _ _ _ _ = do { types <- processNt1 aaa nt1s ntType ; return $ mutPfStart Prop types ++ defaultSimp ++ "; " ++ fsetdecTac ++ "." } name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; open_fn <- openRecName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ open_fn ++ "_upper" } thm aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2 nt2' = do { k <- newName bvarRoot ; e <- newName nt1 ; u <- newName nt2' ; open_fn <- openRecName aa nt1 mv2' ; fv_fn <- fvName aa nt1 mv2 ; fv_fn2 <- fvName aa nt2' mv2 ; return $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [<=] %s %s %s %s %s" e u k fv_fn open_fn k u e fv_fn2 u mvSetUnion fv_fn e } thm aa nt1 _ mv2 nt2' mv2' | otherwise = do { k <- newName bvarRoot ; e <- newName nt1 ; u <- newName nt2' ; open_fn <- openRecName aa nt1 mv2' ; fv_fn <- fvName aa nt1 mv2 ; return $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [<=] %s %s" e u k fv_fn open_fn k u e fv_fn e } {- | @fv (open e e') [<=] fv e `union` fv e'@. -} fv_open_upper :: ASTAnalysis -> [NtRoot] -> M String fv_open_upper aaa nt1s = do { gens <- processNt1Nt2Mv2' aaa nt1s gen ; names <- processNt1Nt2Mv2' aaa nt1s name ; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens } where name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; open_fn <- openName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ open_fn ++ "_upper" } gen aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2 nt2' = do { e <- newName nt1 ; u <- newName nt2' ; open_fn <- openName aa nt1 mv2' ; fv_fn <- fvName aa nt1 mv2 ; fv_fn2 <- fvName aa nt2' mv2 -- ORDER TO OPEN ; let stmt = printf "forall %s %s,\n\ \ %s (%s %s %s) [<=] %s %s %s %s %s" e u fv_fn open_fn e u fv_fn2 u mvSetUnion fv_fn e ; let proof = printf "unfold %s; %s." open_fn defaultSimp ; return (stmt, proof) } gen aa nt1 _ mv2 nt2' mv2' | otherwise = do { e <- newName nt1 ; u <- newName nt2' ; open_fn <- openName aa nt1 mv2' ; fv_fn <- fvName aa nt1 mv2 -- ORDER TO OPEN ; let stmt = printf "forall %s %s,\n\ \ %s (%s %s %s) [<=] %s %s" e u fv_fn open_fn e u fv_fn e ; let proof = printf "unfold %s; %s." open_fn defaultSimp ; return (stmt, proof) } {- | @x `notin` fv e -> fv (subst e' x e) [=] fv e@. -} fv_subst_fresh :: ASTAnalysis -> [NtRoot] -> M String fv_subst_fresh aaa nt1s = do { thms' <- processNt1Nt2Mv2' aaa nt1s thm ; names' <- processNt1Nt2Mv2' aaa nt1s name ; proofs' <- processNt1Nt2Mv2' aaa nt1s pf ; let thms = filter (not . null) $ map catMaybes thms' ; let names = filter (not . null) $ map catMaybes names' ; let proofs = filter (not . null) $ map catMaybes proofs' ; let proof = map head proofs ; mutualLemmaText2 Resolve Rewrite NoHide [hintDb] Prop names thms proof } where pf aa _ nt2 mv2 nt2' mv2' | mv2 == mv2' || not (canBindIn aa nt2 nt2') = do { types <- processNt1 aaa nt1s ntType ; return $ Just $ mutPfStart Prop types ++ defaultSimp ++ "; " ++ fsetdecTac ++ "." } pf _ _ _ _ _ _ | otherwise = return Nothing name aa nt1 nt2' mv2 nt2 mv2' | mv2 == mv2' || not (canBindIn aa nt2 nt2') = do { fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ Just $ fv_fn ++ "_" ++ subst_fn ++ "_fresh" } name _ _ _ _ _ _ | otherwise = return Nothing thm aa nt1 _ mv2 nt2' mv2' | mv2 == mv2' = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ Just $ printf "forall %s %s %s,\n\ \ %s %s %s %s ->\n\ \ %s (%s %s %s %s) [=] %s %s" e u x x mvSetNotin fv_fn e fv_fn subst_fn u x e fv_fn e } thm aa nt1 nt2 mv2 nt2' mv2' | not (canBindIn aa nt2 nt2') = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ Just $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [=] %s %s" e u x fv_fn subst_fn u x e fv_fn e } thm _ _ _ _ _ _ | otherwise = return Nothing {- | @remove x (fv e) [<=] fv (subst e' x e)@. -} fv_subst_lower :: ASTAnalysis -> [NtRoot] -> M String fv_subst_lower aaa nt1s = do { thms <- processNt1Nt2Mv2' aaa nt1s thm ; names <- processNt1Nt2Mv2' aaa nt1s name ; proofs <- processNt1Nt2Mv2' aaa nt1s pf ; let proof = map head proofs ; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof } where pf _ _ _ _ _ _ = do { types <- processNt1 aaa nt1s ntType ; return $ mutPfStart Prop types ++ defaultSimp ++ "; " ++ fsetdecTac ++ "." } name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ subst_fn ++ "_lower" } thm aa nt1 _ mv2 nt2' mv2' | mv2 == mv2' = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s %s (%s %s) [<=] %s (%s %s %s %s)" e u x mvSetRemove x fv_fn e fv_fn subst_fn u x e } thm aa nt1 _ mv2 nt2' mv2' | otherwise = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s %s [<=] %s (%s %s %s %s)" e u x fv_fn e fv_fn subst_fn u x e } {- | @x `notin` fv (subst u y e)@ when @x `notin` fv u@ and @x `notin` fv e@. -} fv_subst_notin :: ASTAnalysis -> [NtRoot] -> M String fv_subst_notin aaa nt1s = do { thms <- processNt1Nt2Mv2' aaa nt1s thm ; names <- processNt1Nt2Mv2' aaa nt1s name ; proofs <- processNt1Nt2Mv2' aaa nt1s pf ; let proof = map head proofs ; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof } where pf _ _ _ _ _ _ = do { types <- processNt1 aaa nt1s ntType ; return $ mutPfStart Prop types ++ defaultSimp ++ "; " ++ fsetdecTac ++ "." } name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ subst_fn ++ "_notin" } fvHyp nt2 nt2' y fv u | canBindIn aaa nt2 nt2' = printf " %s %s %s %s ->\n" y mvSetNotin fv u | otherwise = "" thm aa nt1 nt2 mv2 nt2' mv2' = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; y <- newName mv2 ; fv_fn <- fvName aa nt1 mv2 ; fv_fn' <- fvName aa nt2' mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ printf "forall %s %s %s %s,\n\ \ %s %s %s %s ->\n\ \%s\ \ %s %s %s (%s %s %s %s)" e u x y y mvSetNotin fv_fn e (fvHyp nt2 nt2' y fv_fn' u) y mvSetNotin fv_fn subst_fn u x e } {- | @fv (subst e' x e) [<=] fv e' `union` remove x (fv e)@. -} fv_subst_upper :: ASTAnalysis -> [NtRoot] -> M String fv_subst_upper aaa nt1s = do { thms <- processNt1Nt2Mv2' aaa nt1s thm ; names <- processNt1Nt2Mv2' aaa nt1s name ; proofs <- processNt1Nt2Mv2' aaa nt1s pf ; let proof = map head proofs ; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof } where pf _ _ _ _ _ _ = do { types <- processNt1 aaa nt1s ntType ; return $ mutPfStart Prop types ++ defaultSimp ++ "; " ++ fsetdecTac ++ "." } name aa nt1 _ mv2 _ mv2' = do { fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ fv_fn ++ "_" ++ subst_fn ++ "_upper" } thm aa nt1 _ mv2 nt2' mv2' | mv2 == mv2' = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; fv_fn2 <- fvName aa nt2' mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [<=] %s %s %s %s %s (%s %s)" e u x fv_fn subst_fn u x e fv_fn2 u mvSetUnion mvSetRemove x fv_fn e } thm aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2 nt2' = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; fv_fn2 <- fvName aa nt2' mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [<=] %s %s %s %s %s" e u x fv_fn subst_fn u x e fv_fn2 u mvSetUnion fv_fn e } thm aa nt1 _ mv2 nt2' mv2' | otherwise = do { e <- newName nt1 ; u <- newName nt2' ; x <- newName mv2' ; fv_fn <- fvName aa nt1 mv2 ; subst_fn <- substName aa nt1 mv2' ; return $ printf "forall %s %s %s,\n\ \ %s (%s %s %s %s) [<=] %s %s" e u x fv_fn subst_fn u x e fv_fn e }
plclub/lngen
src/CoqLNOutputThmFv.hs
mit
19,614
0
19
8,973
5,301
2,565
2,736
352
5
pe6 :: Int -> Int pe6 n = (sum [1..n]) ^ 2 - (sum $ map (^ 2) [1..n]) main :: IO() main = do print $ pe6 100
kittttttan/pe
haskell/pe6.hs
mit
114
0
9
34
93
45
48
5
1
-- Lambda -- ref: https://wiki.haskell.org/Lambda_calculus
Airtnp/Freshman_Simple_Haskell_Lib
Incomplete/Lambda.hs
mit
58
0
2
4
4
3
1
1
0
{-# LANGUAGE CPP #-} -- Shamelessly stolen from snap-loader-dynamic module System.TestLoop.Internal.Signal (protectHandlers) where ------------------------------------------------------------------------------ import Control.Exception (bracket) #ifdef mingw32_HOST_OS ------------- -- windows -- ------------- ------------------------------------------------------------------------------ import GHC.ConsoleHandler as C saveHandlers :: IO C.Handler saveHandlers = C.installHandler Ignore restoreHandlers :: C.Handler -> IO C.Handler restoreHandlers = C.installHandler ------------------------------------------------------------------------------ #else ----------- -- posix -- ----------- ------------------------------------------------------------------------------ import qualified System.Posix.Signals as S helper :: S.Handler -> S.Signal -> IO S.Handler helper handler signal = S.installHandler signal handler Nothing signals :: [S.Signal] signals = [ S.sigQUIT , S.sigINT , S.sigHUP , S.sigTERM ] saveHandlers :: IO [S.Handler] saveHandlers = mapM (helper S.Ignore) signals restoreHandlers :: [S.Handler] -> IO [S.Handler] restoreHandlers h = sequence $ zipWith helper h signals ------------------------------------------------------------------------------ #endif ---------- -- both -- ---------- ------------------------------------------------------------------------------ protectHandlers :: IO a -> IO a protectHandlers a = bracket saveHandlers restoreHandlers (const a) ------------------------------------------------------------------------------
roman/testloop
src/System/TestLoop/Internal/Signal.hs
mit
1,919
0
7
496
125
75
50
17
1
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-} module ViewModels.LoginGoogleAuthError where import Data.Text import Data.Data data LoginGoogleAuthError = LoginGoogleAuthError { errorDescripton :: Text } deriving (Data, Typeable)
itsuart/fdc_archivist
src/ViewModels/LoginGoogleAuthError.hs
mit
243
0
8
30
43
26
17
7
0
prop_RevRev xs = reverse (reverse xs) == xs where types = xs::[Int]
ostera/asdf
haskell/QuickCheck.hs
mit
70
1
8
14
38
18
20
2
1
module Main where import Data.Char main = do { str <- getContents; putStrLn (map toUpper str); }
dicander/progp_haskell
upper_case.hs
mit
101
0
9
21
39
22
17
5
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE ViewPatterns #-} -- A small bidirectional type checker for intensional intuitionistic type -- theory, structured around judgements as an organizing principle. The -- checking judgement ("M checks at type T") is analytic, and the inferring -- judgement is synthetic ("M has a type"). -- -- It is written using Weirich's Unbound, mainly because it was easy enough to -- use and fighting Bound to work with contexts was not something I wanted to -- spend time on. -- -- This has very good error-reporting: that is, all whenever we attempt to -- verify a judgement, we leave a breadcrumb behind such that if we refute the -- judgement, we know exactly where that occured. module Main where import Control.Applicative import Control.Monad.Error.Class import Control.Monad.Trace.Class import Control.Monad.Trace.ErrorTrace import Control.Monad.Trans import Control.Monad.Trans.Trace import Prelude.Unicode import Unbound.LocallyNameless hiding (Equal, Refl, to) import TT.Tm import TT.Tele import TT.Judgement.Class import TT.Judgement.Hypothetical import TT.Judgement.Bidirectional newtype Judge α = Judge { _judge ∷ TraceT TraceTag Refutation FreshM α } deriving (Monad, Functor, Alternative, Applicative, MonadTrace TraceTag, MonadError Refutation) instance Fresh Judge where fresh = Judge ∘ lift ∘ fresh runJudge ∷ Judge α → Either (ErrorTrace TraceTag Refutation) α runJudge = runFreshM ∘ runTraceT ∘ _judge testFailure ∷ Judge () testFailure = judge $ Empty ⊢ Refl Ax :⇐ Id (Plus Unit Unit) (Ax,Ax) testFailure2 ∷ Judge () testFailure2 = judge $ Empty ⊢ Inl Ax :⇐ Plus Unit Ax test ∷ Judge () test = do let tm = Lam $ bind (string2Name "α") $ Lam $ bind (string2Name "x") $ Inl (V $ string2Name "x") let ty = Pi (Univ 0) $ bind (string2Name "α") $ Pi (V $ string2Name "α") $ bind (string2Name "x") $ Plus (V $ string2Name "α") Unit judge $ Empty ⊢ tm :⇐ ty
jonsterling/itt-bidirectional
src/Main.hs
mit
2,485
0
16
436
483
269
214
52
1
module Main where -- internal imports import Poplog.Parser import Poplog.Evaluator import Repl -- Main main :: IO () main = conditionalRepl parseProlog eval "Prolog"
joshrule/poplog
src/examples/Main.hs
mit
168
0
6
26
41
24
17
6
1
module Properties (properties) where import Test.QuickCheck import Test.Framework.Providers.QuickCheck2 (testProperty) import MineSweeper instance Arbitrary Event where arbitrary = elements [Mark, Check] instance Arbitrary CleanCell where arbitrary = do numAdjacentMine <- elements [0..8] return $ CleanCell numAdjacentMine instance Arbitrary MineCell where arbitrary = elements [MineCell] instance Arbitrary CellState where arbitrary = undefined isUncheckedCell :: CellState -> Bool isUncheckedCell cs = case cs of Unchecked mc -> True otherwise -> False prop_flagged_cell_does_not_go_to_checked_state :: Cell -> Event -> Bool prop_flagged_cell_does_not_go_to_checked_state cell evt = let flagged = Unchecked (Flag cell) in isUncheckedCell $ nextState flagged evt --properties :: [Test] properties = [ testProperty "flag_guards_events" prop_flagged_cell_does_not_go_to_checked_state ]
zlqhem/MineSweeper
tests/Properties.hs
mit
923
0
11
138
223
117
106
24
2
-- SYNTAX TEST "source.haskell" module Test where -- it understands record syntax data Car1 = Car1 { -- ^ meta.declaration.type.data meta.declaration.type.data.record.block keyword.operator.record.begin -- ^^^^ meta.declaration.type.data meta.type-signature entity.name.type -- ^^^^ meta.declaration.type.data entity.name.tag company :: String, -- ^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration keyword.other.double-colon -- ^^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name -- ^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type support.class.prelude.String model :: String, -- ^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration keyword.other.double-colon -- ^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type support.class.prelude.String -- ^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name year :: Int -- ^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration keyword.other.double-colon -- ^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name -- ^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type support.class.prelude.Int } deriving (Show) -- ^^^^ meta.declaration.type.data meta.deriving entity.other.inherited-class -- ^^^^^^^^ meta.declaration.type.data meta.deriving keyword.other -- ^ meta.declaration.type.data meta.declaration.type.data.record.block keyword.operator.record.end -- it understands comments in records data Car2 = Car2 { company2 :: String, -- comment -- ^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type support.class.prelude.String -- ^^^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name -- model :: String, -- commented field -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature comment.line.double-dash year2 :: Int -- another comment -- ^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type support.class.prelude.Int -- ^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name } -- it understands comments in start of records newtype Car3 = Car3 { -- company :: String -- ^^^^^^^^^^^^^^^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block comment.line.double-dash model3 :: String -- ^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type support.class.prelude.String -- ^^^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name } --------------- regression test for #65 --------------- -- it works without space data Foo = Foo{bar :: Int} -- ^ meta.declaration.type.data meta.declaration.type.data.record.block keyword.operator.record.begin -- ^ meta.declaration.type.data meta.declaration.type.data.record.block keyword.operator.record.end -- ^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type -- ^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name -- ^^^ meta.declaration.type.data entity.name.tag -- ^^^ meta.declaration.type.data meta.type-signature entity.name.type -- it works with space data Foo1 = Foo1 {bar1 :: Int} -- ^ meta.declaration.type.data meta.declaration.type.data.record.block keyword.operator.record.begin -- ^ meta.declaration.type.data meta.declaration.type.data.record.block keyword.operator.record.end -- ^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration meta.type-signature entity.name.type support.class.prelude.Int -- ^^^^ meta.declaration.type.data meta.declaration.type.data.record.block meta.record-field.type-declaration entity.other.attribute-name -- ^^^^ meta.declaration.type.data entity.name.tag -- ^^^^ meta.declaration.type.data meta.type-signature entity.name.type f :: a f = undefined -- >> =source.haskell
atom-haskell/language-haskell
spec/fixture/record.hs
mit
5,303
0
8
670
159
117
42
15
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE CPP #-} module Yesod.Core.Dispatch ( -- * Quasi-quoted routing parseRoutes , parseRoutesNoCheck , parseRoutesFile , parseRoutesFileNoCheck , mkYesod -- ** More fine-grained , mkYesodData , mkYesodSubData , mkYesodDispatch , mkYesodSubDispatch -- ** Path pieces , PathPiece (..) , PathMultiPiece (..) , Texts -- * Convert to WAI , toWaiApp , toWaiAppPlain , warp , warpDebug , warpEnv , mkDefaultMiddlewares , defaultMiddlewaresNoLogging -- * WAI subsites , WaiSubsite (..) ) where import Prelude hiding (exp) import Yesod.Core.Internal.TH import Language.Haskell.TH.Syntax (qLocation) import Web.PathPieces import qualified Network.Wai as W import Data.ByteString.Lazy.Char8 () import Data.Text (Text) import Data.Monoid (mappend) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Blaze.ByteString.Builder import Network.HTTP.Types (status301) import Yesod.Routes.Parse import Yesod.Core.Types import Yesod.Core.Class.Yesod import Yesod.Core.Class.Dispatch import Yesod.Core.Internal.Run import Safe (readMay) import System.Environment (getEnvironment) import Network.Wai.Middleware.Autohead import Network.Wai.Middleware.AcceptOverride import Network.Wai.Middleware.RequestLogger import Network.Wai.Middleware.Gzip import Network.Wai.Middleware.MethodOverride import qualified Network.Wai.Handler.Warp import System.Log.FastLogger import Control.Monad.Logger import Control.Monad (when) import qualified Paths_yesod_core import Data.Version (showVersion) import qualified System.Random.MWC as MWC -- | Convert the given argument into a WAI application, executable with any WAI -- handler. This function will provide no middlewares; if you want commonly -- used middlewares, please use 'toWaiApp'. toWaiAppPlain :: YesodDispatch site => site -> IO W.Application toWaiAppPlain site = do logger <- makeLogger site sb <- makeSessionBackend site gen <- MWC.createSystemRandom return $ toWaiAppYre $ YesodRunnerEnv { yreLogger = logger , yreSite = site , yreSessionBackend = sb , yreGen = gen } toWaiAppYre :: YesodDispatch site => YesodRunnerEnv site -> W.Application toWaiAppYre yre req = case cleanPath site $ W.pathInfo req of Left pieces -> sendRedirect site pieces req Right pieces -> yesodDispatch yre req { W.pathInfo = pieces } where site = yreSite yre sendRedirect :: Yesod master => master -> [Text] -> W.Application sendRedirect y segments' env sendResponse = sendResponse $ W.responseLBS status301 [ ("Content-Type", "text/plain") , ("Location", Blaze.ByteString.Builder.toByteString dest') ] "Redirecting" where dest = joinPath y (resolveApproot y env) segments' [] dest' = if S.null (W.rawQueryString env) then dest else (dest `mappend` Blaze.ByteString.Builder.fromByteString (W.rawQueryString env)) -- | Same as 'toWaiAppPlain', but provides a default set of middlewares. This -- set may change with future releases, but currently covers: -- -- * Logging -- -- * GZIP compression -- -- * Automatic HEAD method handling -- -- * Request method override with the _method query string parameter -- -- * Accept header override with the _accept query string parameter toWaiApp :: YesodDispatch site => site -> IO W.Application toWaiApp site = do logger <- makeLogger site toWaiAppLogger logger site toWaiAppLogger :: YesodDispatch site => Logger -> site -> IO W.Application toWaiAppLogger logger site = do sb <- makeSessionBackend site gen <- MWC.createSystemRandom let yre = YesodRunnerEnv { yreLogger = logger , yreSite = site , yreSessionBackend = sb , yreGen = gen } messageLoggerSource site logger $(qLocation >>= liftLoc) "yesod-core" LevelInfo (toLogStr ("Application launched" :: S.ByteString)) middleware <- mkDefaultMiddlewares logger return $ middleware $ toWaiAppYre yre -- | A convenience method to run an application using the Warp webserver on the -- specified port. Automatically calls 'toWaiApp'. Provides a default set of -- middlewares. This set may change at any point without a breaking version -- number. Currently, it includes: -- -- If you need more fine-grained control of middlewares, please use 'toWaiApp' -- directly. -- -- Since 1.2.0 warp :: YesodDispatch site => Int -> site -> IO () warp port site = do logger <- makeLogger site toWaiAppLogger logger site >>= Network.Wai.Handler.Warp.runSettings ( Network.Wai.Handler.Warp.setPort port $ Network.Wai.Handler.Warp.setServerName serverValue $ Network.Wai.Handler.Warp.setOnException (\_ e -> when (shouldLog' e) $ messageLoggerSource site logger $(qLocation >>= liftLoc) "yesod-core" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) $ Network.Wai.Handler.Warp.defaultSettings) where shouldLog' = Network.Wai.Handler.Warp.defaultShouldDisplayException serverValue :: S8.ByteString serverValue = S8.pack $ concat [ "Warp/" , Network.Wai.Handler.Warp.warpVersion , " + Yesod/" , showVersion Paths_yesod_core.version , " (core)" ] -- | A default set of middlewares. -- -- Since 1.2.0 mkDefaultMiddlewares :: Logger -> IO W.Middleware mkDefaultMiddlewares logger = do logWare <- mkRequestLogger def { destination = Network.Wai.Middleware.RequestLogger.Logger $ loggerSet logger , outputFormat = Apache FromSocket } return $ logWare . defaultMiddlewaresNoLogging -- | All of the default middlewares, excluding logging. -- -- Since 1.2.12 defaultMiddlewaresNoLogging :: W.Middleware defaultMiddlewaresNoLogging = acceptOverride . autohead . gzip def . methodOverride -- | Deprecated synonym for 'warp'. warpDebug :: YesodDispatch site => Int -> site -> IO () warpDebug = warp {-# DEPRECATED warpDebug "Please use warp instead" #-} -- | Runs your application using default middlewares (i.e., via 'toWaiApp'). It -- reads port information from the PORT environment variable, as used by tools -- such as Keter and the FP Complete School of Haskell. -- -- Note that the exact behavior of this function may be modified slightly over -- time to work correctly with external tools, without a change to the type -- signature. warpEnv :: YesodDispatch site => site -> IO () warpEnv site = do env <- getEnvironment case lookup "PORT" env of Nothing -> error $ "warpEnv: no PORT environment variable found" Just portS -> case readMay portS of Nothing -> error $ "warpEnv: invalid PORT environment variable: " ++ show portS Just port -> warp port site
wujf/yesod
yesod-core/Yesod/Core/Dispatch.hs
mit
7,356
0
19
1,765
1,378
781
597
154
3
module Recipes where import Macros cheesyChickenBroccoli = Meal "Cheesy Chicken Broccoli and Rice Casserole" 2 [ (Ingredient "Olive Oil" 14 0 0 (Unit 14 "g")), (Ingredient "Cream of Chicken Soup (with herbs), 10oz" 8 9 2 (Unit 0.5 "cup")) .* 2.5, -- (Ingredient "Cream of Chicken Soup, Healthy Request 10oz" -- 2 9 1 (Unit 0.5 "cup")) .* 2.5, Ingredient "Long-grained White Rice, raw" 1.2 148 13 (Unit 185 "g"), (Ingredient "Swanson's Chicken Broth" 0.5 1 1 (Unit 1 "cup")) .* 2.25, (Ingredient "Garlic, raw" 0.1 4 0.8 (Unit 12 "g")), (Ingredient "Shallots, raw" 0.1 8.4 1.3 (Unit 50 "g")), (Ingredient "Brown Mushrooms (Italian or Crimini), raw" 0.1 3.5 2.1 (Unit 85 "g")) .* 3, (Ingredient "Broccoli, raw" 0.4 6.6 2.8 (Unit 100 "g")), (Ingredient "Chicken Breast (Raw)" 11.2 0 209.5 (Unit 2 "lb")) ./ 4, (Ingredient "Carrots, raw" 0.2 9.6 0.9 (Unit 100 "g")) ] bakedBananaOatmeal = Meal "Baked Banana Walnut Rasin Oatmeal" 6 [ (Ingredient "Almon Milk, unsweetened" 2.4 8 1 (Unit 1 "cup")), (Ingredient "Egg" 5 0 6 (Unit 1 "large")), -- (Ingredient "Walnut" 19 4 4.3 (Unit 30 "g")), (Ingredient "PB2 - Traditional" 1.5 5 5 (Unit 12 "g")) .* 3, (Ingredient "Cocoa powder (Hershey's)" 0.5 3 1 (Unit 5 "g")), (Ingredient "Banana (medium - 6.5oz)" 0.4 27 1.3 (Unit 1 "medium")) .* 3, (Ingredient "Quaker Oats - Old Fashioned" 3 27 5 (Unit 40 "g")) .* 3.5, (Ingredient "Rasins" 0 31 1 (Unit 40 "g")) .* 1.5, (Ingredient "Baking powder" 0 0 0 (Unit 0.5 "tsp")), (Ingredient "Baking soda" 0 0 0 (Unit 0.5 "tsp")), (Ingredient "Salt" 0 0 0 (Unit 0.25 "tsp")) ] chickenEnchiladaCasserole = Meal "Chicken Enchilada Rice Casserole" 6 [ (Ingredient "White Rice (Raw)" 2.4 295.8 26.4 (Unit 2 "Cup")), (Ingredient "Chicken Breast (Raw)" 11.2 0 209.5 (Unit 2 "lb")) ./ 2, (Ingredient "Enchilada Sauce" 0 4 0 (Unit 0.25 "Cup")) .* 13, (Ingredient "Refried Beans" 0 16 6 (Unit 0.5 "Cup")) .* 3.5, (Ingredient "Corn kernels" 0 18 0 (Unit 90 "g")), (Ingredient "Cheese" 9 1 7 (Unit 28 "g")) .* 4, (Ingredient "Black Beans (drained)" 0.5 22 7 (Unit 130 "g")) .* 3.5, (Ingredient "Onion" 0 11.1 1 (Unit 110 "g")) ] mexicanBeefAndRiceCasserole = Meal "Mexican beef and rice casserole" 6 [ (Ingredient "Ground beef, (93:7)" 8 0 24 (Unit 4 "oz")) .* 4, (Ingredient "Cheese" 9 1 7 (Unit 28 "g")) .* 4, (Ingredient "White Rice, Raw" 2.4 295.8 26.4 (Unit 2 "Cup")) ./ 2, (Ingredient "Spinach, raw" 1.3 11.9 9.4 (Unit 11.5 "oz")), (Ingredient "Corn kernels" 0 21 2 (Unit 90 "g")) .* 2, (Ingredient "Salsa" 0 2 0 (Unit 30 "ml")) .* 4, (Ingredient "Onion" 0 11.1 1 (Unit 110 "g")), (Ingredient "Fire roasted tomato" 0 6 1 (Unit 123 "g")) .* 3.5, (Ingredient "Swanson's Chicken Broth" 0.5 1 1 (Unit 1 "cup")) .* 2 ] appleCoffeeCake = Meal "Apple Coffee Cake" 8 [ (Ingredient "Apple Sauce (Unsweetened)" 0 18 0 (Unit 122 "g")), (Ingredient "Brown Sugar, lightly packed (3/4 cup)" 0 150 0 (Unit 150 "g")), (Ingredient "Egg" 5 0 6 (Unit 1 "large")), (Ingredient "All Purpose White flour" 1.2 95.4 12.9 (Unit 4.4 "oz")), (Ingredient "Baking soda" 0 0 0 (Unit 0.5 "tsp")), (Ingredient "Cinnamon" 0 0 0 (Unit 0.5 "tsp")), (Ingredient "Non-fat Greek Yogurt (fage)" 0 9 23 (Unit 227 "g")) ./ 2, (Ingredient "Vanilla extract" 0 0 0 (Unit 0.5 "tsp")), (Ingredient "Diced Apple" 0.3 20.7 0.4 (Unit 150 "g")), Meal "Topping" 1 [ (Ingredient "Brown Sugar" 0 12.7 0 (Unit 13 "g")) .* 3, (Ingredient "White flour" 0.3 21.6 2.9 (Unit 1 "oz")), (Ingredient "Butter" 14 0 0 (Unit 1 "tbsp")) .* 2 ] ] sweetPotatoBurrito = Meal "Sweet Potato Breakfast Burrito" 8 [ (Ingredient "Olive oil" 14 0 0 (Unit 14 "g")), (Ingredient "Onion" 0 11.1 1 (Unit 110 "g")) .* 2, (Ingredient "Garlic" 0 1 0 (Unit 1 "clove(s)")) .* 3, (Ingredient "Sweet Potato, cubed" 0.1 57 4.5 (Unit 10 "oz")), (Ingredient "Zucchini, diced" 0.4 4.3 1.5 (Unit 4.4 "oz")) .* 1.5, (Ingredient "Chili Powder" 0 0 0 (Unit 0.5 "tsp")), (Ingredient "Cumin" 0 0 0 (Unit 0.25 "tsp")), (Ingredient "Salt" 0 0 0 (Unit 0.25 "tsp")), (Ingredient "Ground pepper" 0 0 0 (Unit 0.25 "tsp")), (Ingredient "Tortillas" 4.5 30 4 (Unit 1 "serving")) .* 8, Meal "Scrambled Eggs" 1 [ (Ingredient "Egg" 5 0 6 (Unit 1 "large")) .* 8, (Ingredient "Spinach, finely chopped" 0.2 2.2 1.7 (Unit 2.2 "oz")), (Ingredient "Salt" 0 0 0 (Unit 0.25 "tsp")), (Ingredient "Ground pepper" 0 0 0 (Unit 0.25 "tsp")), (Ingredient "Cooking spray" 0 0 0 (Unit 1 "spray")) ] ] pastaSauceWith food = Meal "Butternut Squash Pasta Sauce" servings [ (Ingredient "Butter" 12.2 0 0 (Unit 15 "g")) .* 2, (Ingredient "Onion" 0.2 15 1.8 (Unit 160 "g")), (Ingredient "Garlic" 0.05 1 0.2 (Unit 3 "clove")), (Ingredient "Butternut Squash (cubed)" 0.1 16.4 1.4 (Unit 140 "g")) .* 3, (Ingredient "Swanson's Chicken Broth" 0.5 1 1 (Unit 1 "cup")), (Ingredient "Thyme" 0 0 0 (Unit 1 "tbsp")) .* 1.5, (Ingredient "Sage" 0.3 1.2 0.2 (Unit 2 "g")) .* 1.5, (Ingredient "Milk 1%" 2.5 12.3 8.1 (Unit 1 "cup")), food .* (fi servings) ] where servings = 6 lunchBurrito = Meal "Beef Avocado Burrito" servings [ (Ingredient "Soft Tortilla" 4 37 5 (Unit 1 "serving")) .* (fi servings), (Ingredient "Ground beef, (93:7)" 8 0 24 (Unit 4 "oz")) .* 4, (Ingredient "Spinach, raw" 1.3 11.9 9.4 (Unit 11.5 "oz")), (Ingredient "Fire roasted tomato" 0 6 1 (Unit 123 "g")) .* 3.5, (Ingredient "Avocado" 11.7 6.8 1.6 (Unit 80 "g")) .* (fi servings) ] where servings = 6 chickenSalad = Meal "Chicken salad" 6 [ Ingredient "Chicken breast, poached" 5.6 0 104.7 (Unit 1 "lb") .* 2, Ingredient "Celery" 0 0 0 (Unit 0.5 "cup"), Ingredient "Onion" 0.1 15.2 1.4 (Unit 150 "g"), Ingredient "Raisins" 0.4 63 2.5 (Unit 80 "g"), Ingredient "Pita" 2 34 8 (Unit 1 "count") .* 6, Ingredient "Almonds" 35.4 13.8 14.9 (Unit 70 "g"), Ingredient "Greek Yogurt" 0 9 23 (Unit 227 "g") .* 1.3 ] overNightOats = Meal "Overnight oats" 1 [ ((Ingredient "Oats, old fashioned" 3 27 5 (Unit 40 "g")) .* 2) ./ 3, Ingredient "Greek yogurt" 0 9 23 (Unit 227 "g") ./ 4, Ingredient "Low fat Milk" 2.4 12.2 8.5 (Unit 8 "oz") ./ 4, Ingredient "Almond butter" 9.4 3.4 2.4 (Unit 17 "g"), Ingredient "Honey" 0 25 0.1 (Unit 25 "g"), Ingredient "Chia seed" 9 10 6 (Unit 26 "g") ./ 2 ] tunaCasserole = Meal "Tuna casserole" 4 [ Ingredient "Tuna" 0.5 0 13 (Unit 2 "oz") .* 4.5, -- 12oz can Ingredient "Egg noodle" 3 40 8 (Unit 56 "g") .* 6, -- 2 cups Ingredient "Peas" 0 12 5 (Unit 90 "g") .* 2.5, Ingredient "Cream of mushrooms" 6 8 1 (Unit 1.5 "cup") .* 2.5, Ingredient "Whole milk" 2.4 12 8 (Unit 244 "g"), Ingredient "Cheddar cheese" 10 1 8 (Unit 1 "oz") .* 3 ] turkeyBurito = Meal "Beef Avocado Burrito" servings [ (Ingredient "Soft Tortilla" 4 37 5 (Unit 1 "serving")) .* (fi servings), (Ingredient "Ground turkey, (93:7)" 8 0 22 (Unit 4 "oz")) .* 4, (Ingredient "Egg" 5 0 6 (Unit 1 "large")) .* (fi (servings * 2)), (Ingredient "Sweet potato" 0.1 27 2.1 (Unit 133 "grams")) .* 4, Ingredient "Oil" 15 0 0 (Unit 15 "g"), Ingredient "Onion" 0.1 16.2 1.5 (Unit 5.6 "oz"), (Ingredient "Avocado" 3.1 1.7 0.4 (Unit 20 "g")) .* (fi servings) ] where servings = 6
ladinu/macros
recipes.hs
mit
7,548
0
13
1,828
2,981
1,538
1,443
149
1
import Control.Monad.Cont main = do forM_ [1..3] $ \i -> do print i forM_ [7..9] $ \j -> do print j withBreak $ \break -> forM_ [1..] $ \_ -> do p "loop" break () where withBreak = (`runContT` return) . callCC p = liftIO . putStrLn
theDrake/haskell-experiments
for.hs
mit
272
4
14
87
142
66
76
12
1
{-| Module : CLI Description : Command-line evocation argument processing Copyright : (c) chop-lang, 2015 License : MIT Maintainer : carterhinsley@gmail.com -} module CLI ( ArgResult(..) , processArgs ) where import System.Environment (getArgs) -- | Contains data gathered from command-line arguments data ArgResult = ParseData { ebnfFile :: IO String, input :: IO String } -- | Retrieve command-line arguments, evaluate them, then wrap them back up in -- the IO monad. processArgs :: IO [ArgResult] processArgs = do args <- getArgs if null args then error "You must supply an EBNF file. RTFM for more info." else return . evalArgs $ args -- | Evaluate arguments and return some ArgResults containing information about -- the arguments. evalArgs :: [String] -> [ArgResult] evalArgs [filePath] = [ ParseData { ebnfFile = readFile filePath, input = getContents } ] evalArgs (x:_) = error $ "Argument `" ++ x ++ "' unrecognized. Please RTFM." evalArgs _ = error "Invalid arguments. Please RTFM."
chop-lang/parsebnf
src/CLI.hs
mit
1,038
0
9
204
191
108
83
16
2
module SafePrelude where safeHead :: [a] -> Maybe a safeHead [] = Nothing safeHead (x:_) = Just x
Muzietto/transformerz
haskell/hunit/SafePrelude.hs
mit
109
0
7
29
47
25
22
4
1
{-# LANGUAGE OverloadedStrings #-} module Unison.NameSegment where import Unison.Prelude import qualified Data.Text as Text import qualified Unison.Hashable as H import Unison.Util.Alphabetical (Alphabetical, compareAlphabetical) -- Represents the parts of a name between the `.`s newtype NameSegment = NameSegment { toText :: Text } deriving (Eq, Ord) instance Alphabetical NameSegment where compareAlphabetical n1 n2 = compareAlphabetical (toText n1) (toText n2) -- Split text into segments. A smarter version of `Text.splitOn` that handles -- the name `.` properly. segments' :: Text -> [Text] segments' n = go split where split = Text.splitOn "." n go [] = [] go ("" : "" : z) = "." : go z go ("" : z) = go z go (x : y) = x : go y -- Same as reverse . segments', but produces the output as a -- lazy list, suitable for suffix-based ordering purposes or -- building suffix tries. Examples: -- -- reverseSegments' "foo.bar.baz" => ["baz","bar","foo"] -- reverseSegments' ".foo.bar.baz" => ["baz","bar","foo"] -- reverseSegments' ".." => ["."] -- reverseSegments' "Nat.++" => ["++","Nat"] -- reverseSegments' "Nat.++.zoo" => ["zoo","++","Nat"] reverseSegments' :: Text -> [Text] reverseSegments' = go where go "" = [] go t = let seg0 = Text.takeWhileEnd (/= '.') t seg = if Text.null seg0 then Text.takeEnd 1 t else seg0 rem = Text.dropEnd (Text.length seg + 1) t in seg : go rem instance H.Hashable NameSegment where tokens s = [H.Text (toText s)] isEmpty :: NameSegment -> Bool isEmpty ns = toText ns == mempty isPrefixOf :: NameSegment -> NameSegment -> Bool isPrefixOf n1 n2 = Text.isPrefixOf (toText n1) (toText n2) toString :: NameSegment -> String toString = Text.unpack . toText instance Show NameSegment where show = Text.unpack . toText instance IsString NameSegment where fromString = NameSegment . Text.pack
unisonweb/platform
unison-core/src/Unison/NameSegment.hs
mit
1,968
0
15
434
499
270
229
36
4
{-# language TypeFamilies #-} {-# language TypeOperators, GADTs #-} {-# language FlexibleInstances, FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2016 Marco Zocca -- License : GPL-3 (see LICENSE) -- Maintainer : zocca.marco gmail -- Stability : provisional -- Portability : portable -- ----------------------------------------------------------------------------- module Data.Sparse.Common ( module X, insertRowWith, insertRow, insertColWith, insertCol, diagonalSM, outerProdSV, (><), toSV, svToSM, lookupRowSM, extractCol, extractRow, extractVectorDenseWith, extractRowDense, extractColDense, extractDiagDense, extractSubRow, extractSubCol, extractSubRow_RK, extractSubCol_RK, fromRowsL, fromRowsV, fromColsV, fromColsL, toRowsL, toColsL) where -- import Control.Exception -- import Control.Exception.Common -- import Control.Monad.Catch import Data.Sparse.Utils as X import Data.Sparse.PPrint as X import Data.Sparse.Types as X import Data.Sparse.Internal.IntMap2 -- as X import qualified Data.Sparse.Internal.IntM as I import Data.Sparse.Internal.IntM (IntM(..)) import Data.Sparse.SpMatrix as X import Data.Sparse.SpVector as X -- import Data.Sparse.Internal.CSR as X import Numeric.Eps as X import Numeric.LinearAlgebra.Class as X import qualified Data.IntMap.Strict as IM import GHC.Exts import Data.Complex -- import Control.Applicative -- import Data.Traversable import Data.Maybe (fromMaybe, maybe) import qualified Data.Vector as V -- withBoundsSM m ij e f -- | isValidIxSM m ij = f m ij -- | otherwise = error e -- | Modify the size of a SpVector. Do not use directly resizeSV :: Int -> SpVector a -> SpVector a resizeSV d2 (SV _ sv) = SV d2 sv -- | Remap the keys of a SpVector. Do not use directly mapKeysSV :: (IM.Key -> IM.Key) -> SpVector a -> SpVector a mapKeysSV fk (SV d sv) = SV d $ I.mapKeys fk sv -- * Insert row/column vector in matrix -- | Insert row , using the provided row index transformation function insertRowWith :: (IxCol -> IxCol) -> SpMatrix a -> SpVector a -> IM.Key -> SpMatrix a insertRowWith fj (SM (m, n) im) (SV d sv) i | not (inBounds0 m i) = error "insertRowWith : index out of bounds" | n >= d = SM (m,n) $ I.insert i (insertOrUnion i sv' im) im | otherwise = error $ "insertRowWith : incompatible dimensions " ++ show (n, d) where sv' = I.mapKeys fj sv insertOrUnion i' sv' im' = maybe sv' (I.union sv') (I.lookup i' im') -- | Insert row insertRow :: SpMatrix a -> SpVector a -> IM.Key -> SpMatrix a insertRow = insertRowWith id -- | Insert column, using the provided row index transformation function insertColWith :: (IxRow -> IxRow) -> SpMatrix a -> SpVector a -> IxCol -> SpMatrix a insertColWith fi smm sv j | not (inBounds0 n j) = error "insertColWith : index out of bounds" | m >= mv = insIM2 smm vl j | otherwise = error $ "insertColWith : incompatible dimensions " ++ show (m,mv) where (m, n) = dim smm mv = dim sv vl = toListSV sv insIM2 im2 ((i,x):xs) j' = insIM2 (insertSpMatrix (fi i) j' x im2) xs j' insIM2 im2 [] _ = im2 -- | Insert column insertCol :: SpMatrix a -> SpVector a -> IxCol -> SpMatrix a insertCol = insertColWith id -- * Outer vector product -- | Outer product outerProdSV, (><) :: Num a => SpVector a -> SpVector a -> SpMatrix a outerProdSV v1 v2 = fromListSM (m, n) ixy where m = dim v1 n = dim v2 ixy = [(i,j, x * y) | (i,x) <- toListSV v1 , (j, y) <- toListSV v2] (><) = outerProdSV -- * Diagonal matrix -- | Fill the diagonal of a SpMatrix with the components of a SpVector diagonalSM :: SpVector a -> SpMatrix a diagonalSM sv = ifoldSV iins (zeroSM n n) sv where n = dim sv iins i = insertSpMatrix i i -- * Matrix-vector conversions -- | promote a SV to SM svToSM :: SpVector a -> SpMatrix a svToSM (SV n d) = SM (n, 1) $ I.singleton 0 d -- |Demote (n x 1) or (1 x n) SpMatrix to SpVector toSV :: SpMatrix a -> SpVector a toSV (SM (m, n) im) = SV d im' where im' | m < n = snd . head . toList $ im | otherwise = fmap g im g = snd . head . toList d | m==1 && n==1 = 1 | m==1 && n>1 = n | n==1 && m>1 = m | otherwise = error $ "toSV : incompatible matrix dimension " ++ show (m,n) -- | Lookup a row in a SpMatrix; returns an SpVector with the row, if this is non-empty lookupRowSM :: SpMatrix a -> IxRow -> Maybe (SpVector a) lookupRowSM sm i = SV (ncols sm) <$> I.lookup i (dat sm) -- * Extract a SpVector from an SpMatrix -- ** Sparse extract -- |Extract ith row extractRow :: SpMatrix a -> IxRow -> SpVector a extractRow m i | inBounds0 (nrows m) i = fromMaybe (zeroSV (ncols m)) (lookupRowSM m i) | otherwise = error $ unwords ["extractRow : index",show i,"out of bounds"] -- |Extract jth column extractCol :: SpMatrix a -> IxCol -> SpVector a extractCol m j = toSV $ extractColSM m j -- ** Dense extract (default == 0) -- | Generic extraction function extractVectorDenseWith :: Num a => (Int -> (IxRow, IxCol)) -> SpMatrix a -> SpVector a extractVectorDenseWith f mm = fromListDenseSV n $ foldr ins [] ll where ll = [0 .. n - 1] (_, n) = dim mm ins i acc = mm @@ f i : acc -- | Extract ith row (dense) extractRowDense :: Num a => SpMatrix a -> IxRow -> SpVector a extractRowDense mm iref = extractVectorDenseWith (\j -> (iref, j)) mm -- | Extract jth column extractColDense :: Num a => SpMatrix a -> IxCol -> SpVector a extractColDense mm jref = extractVectorDenseWith (\i -> (i, jref)) mm -- | Extract the diagonal extractDiagDense :: Num a => SpMatrix a -> SpVector a extractDiagDense = extractVectorDenseWith (\i -> (i, i)) -- | extract row interval (all entries between columns j1 and j2, INCLUDED, are returned) -- extractSubRow :: SpMatrix a -> IxRow -> (IxCol, IxCol) -> SpVector a -- extractSubRow m i (j1, j2) = case lookupRowSM m i of -- Nothing -> zeroSV (ncols m) -- Just rv -> ifilterSV (\j _ -> j >= j1 && j <= j2) rv -- |", returning in Maybe -- extractSubRow :: SpMatrix a -> IxRow -> (Int, Int) -> Maybe (SpVector a) -- extractSubRow m i (j1, j2) = -- resizeSV (j2 - j1) . ifilterSV (\j _ -> j >= j1 && j <= j2) <$> lookupRowSM m i -- | Extract an interval of SpVector components, changing accordingly the resulting SpVector size. Keys are _not_ rebalanced, i.e. components are still labeled according with respect to the source matrix. extractSubRow :: SpMatrix a -> IxRow -> (Int, Int) -> SpVector a extractSubRow m i (j1, j2) = fromMaybe (zeroSV deltaj) vfilt where deltaj = j2 - j1 + 1 vfilt = resizeSV deltaj . ifilterSV (\j _ -> j >= j1 && j <= j2) <$> lookupRowSM m i -- | extract row interval, rebalance keys by subtracting lowest one extractSubRow_RK :: SpMatrix a -> IxRow -> (IxCol, IxCol) -> SpVector a extractSubRow_RK m i (j1, j2) = mapKeysSV (subtract j1) $ extractSubRow m i (j1, j2) -- toSV $ extractSubRowSM_RK m i (j1, j2) -- | extract column interval extractSubCol :: SpMatrix a -> IxCol -> (IxRow, IxRow) -> SpVector a extractSubCol m j (i1, i2) = toSV $ extractSubColSM m j (i1, i2) -- | extract column interval, rebalance keys by subtracting lowest one extractSubCol_RK :: SpMatrix a -> IxCol -> (IxRow, IxRow) -> SpVector a extractSubCol_RK m j (i1, i2) = toSV $ extractSubColSM_RK m j (i1, i2) -- ** Matrix action on a vector {- FIXME : matVec is more general than SpVector's : \m v -> fmap (`dot` v) m :: (Normed f1, Num b, Functor f) => f (f1 b) -> f1 b -> f b -} instance (InnerSpace t, Scalar t ~ t) => LinearVectorSpace (SpVector t) where type MatrixType (SpVector t) = SpMatrix t (#>) = matVecSD (<#) = vecMatSD matVecSD :: (InnerSpace t, Scalar t ~ t) => SpMatrix t -> SpVector t -> SpVector t matVecSD (SM (nr, nc) mdata) (SV n sv) | nc == n = SV nr $ fmap (`dotu` sv) mdata | otherwise = error $ "matVec : mismatched dimensions " ++ show (nc, n) -- |Vector-on-matrix (FIXME : transposes matrix: more costly than `matVec`, I think) vecMatSD :: (InnerSpace t, Scalar t ~ t) => SpVector t -> SpMatrix t -> SpVector t vecMatSD (SV n sv) (SM (nr, nc) mdata) | n == nr = SV nc $ fmap (`dotu` sv) (transposeIM2 mdata) | otherwise = error $ "vecMat : mismatching dimensions " ++ show (n, nr) -- | Un-conjugated inner product, to be used in matrix-vector product dotu :: (Foldable t, Num a, Set t) => t a -> t a -> a dotu u v = sum $ liftI2 (*) u v -- -- generalized matVec : we require a function `rowsf` that produces a functor of elements of a Hilbert space (the rows of `m`) -- matVecG :: (Hilbert v, Functor f, f (Scalar v) ~ v) => (m -> f v) -> m -> v -> v -- matVecG rowsf m v = fmap (`dot` v) (rowsf m) -- matVecGA -- :: (Hilbert v, Traversable t, t (Scalar v) ~ v) => -- (m -> t v) -> m -> v -> v -- matVecGA rowsf m v = traverse (<.> v) (rowsf m) -- -- -- Really, a matrix is just notation for a linear map between two finite-dimensional Hilbert spaces, i.e. -- matVec :: (Hilbert u, Hilbert v) => (u -> v) -> u -> v -- which is a specialization of a function application operator like ($) :: (a -> b) -> a -> b -- -- -- from `vector-space` -- data a -* b where -- Dot :: VectorSpace b => b -> (b -* Scalar b) -- (:&&) :: (a -* c) -> (a -* d) -> (a -* (c, d)) -- a,c,d should be constrained -- apply :: Hilbert a => (a -* b) -> (a -> b) -- apply (Dot b) = dot b -- apply (f :&& g) = apply f &&& apply g -- where (u &&& v) a = (u a, v a) -- (&&&) from Control.Arrow -- -- type a :~ b = Scalar a ~ Scalar b -- | Pack a list of SpVectors as rows of an SpMatrix fromRowsL :: [SpVector a] -> SpMatrix a fromRowsL = fromRowsV . V.fromList -- | Pack a list of SpVectors as columns an SpMatrix fromColsL :: [SpVector a] -> SpMatrix a fromColsL = fromColsV . V.fromList -- | Unpack the rows of an SpMatrix into a list of SpVectors toRowsL :: SpMatrix a -> [SpVector a] toRowsL aa = map (extractRow aa) [0 .. m-1] where (m,n) = dim aa -- | Unpack the columns of an SpMatrix into a list of SpVectors toColsL :: SpMatrix a -> [SpVector a] toColsL aa = map (extractCol aa) [0 .. n-1] where (m,n) = dim aa -- | Pack a V.Vector of SpVectors as columns of an SpMatrix fromColsV :: V.Vector (SpVector a) -> SpMatrix a fromColsV qv = V.ifoldl' ins (zeroSM m n) qv where n = V.length qv m = dim $ V.head qv ins mm i c = insertCol mm c i -- | Pack a V.Vector of SpVectors as rows of an SpMatrix fromRowsV :: V.Vector (SpVector a) -> SpMatrix a fromRowsV qv = V.ifoldl' ins (zeroSM m n) qv where m = V.length qv n = dim $ V.head qv ins mm i c = insertRow mm c i -- * Pretty printing showNz :: (Epsilon a, Show a) => a -> String showNz x | nearZero x = " _ " | otherwise = show x toDenseRow :: Num a => SpMatrix a -> IM.Key -> [a] toDenseRow sm irow = fmap (\icol -> sm @@ (irow,icol)) [0..ncols sm-1] prdR, prdC :: PPrintOptions prdR = PPOpts 4 2 7 -- reals prdC = PPOpts 4 2 16 -- complex values -- -- printDenseSM :: (Show t, Num t) => SpMatrix t -> IO () -- printDenseSM :: (ScIx c ~ (Int, Int), FDSize c ~ (Int, Int), SpContainer c a, Show a, Epsilon a) => c a -> IO () printDenseSM sm = do newline putStrLn $ sizeStrSM sm newline prd0 sm printDenseSM0 :: (SpMatrix a -> IxRow -> Int -> String) -> SpMatrix a -> IO () printDenseSM0 f sm = do printDenseSM' sm 5 5 newline where printDenseSM' sm' nromax ncomax = mapM_ putStrLn rr_' where (nr, _) = (nrows sm, ncols sm) rr_ = map (\i -> f sm' i ncomax) [0..nr-1] rr_' | nr > nromax = take (nromax - 2) rr_ ++ [" ... "] ++[last rr_] | otherwise = rr_ printDenseSM0r :: SpMatrix Double -> IO () printDenseSM0r sm = printDenseSM0 g sm where g sm' irow ncolmax = printDN (ncols sm') ncolmax prdR $ toDenseRow sm' irow printDenseSM0c :: SpMatrix (Complex Double) -> IO () printDenseSM0c sm = printDenseSM0 g sm where g sm' irow ncolmax = printCN (ncols sm') ncolmax prdC $ toDenseRow sm' irow -- printDenseSV :: (Show t, Epsilon t) => SpVector t -> IO () printDenseSV :: PrintDense (SpVector a) => SpVector a -> IO () printDenseSV sv = do newline putStrLn $ sizeStrSV sv newline prd0 sv printDenseSV0r :: SpVector Double -> IO () printDenseSV0r = printDenseSV0 g where g l n = printDN l n prdR printDenseSV0c :: SpVector (Complex Double) -> IO () printDenseSV0c = printDenseSV0 g where g l n = printCN l n prdC printDenseSV0 :: Num a => (Int -> Int -> [a] -> String) -> SpVector a -> IO () printDenseSV0 f sv = do printDenseSV' (svDim sv) 5 newline where printDenseSV' l n = putStrLn (f l n vd) vd = toDenseListSV sv -- ** Pretty printer typeclass instance PrintDense (SpVector Double) where prd = printDenseSV prd0 = printDenseSV0r instance PrintDense (SpVector (Complex Double)) where prd = printDenseSV prd0 = printDenseSV0c instance PrintDense (SpMatrix Double) where prd = printDenseSM prd0 = printDenseSM0r instance PrintDense (SpMatrix (Complex Double)) where prd = printDenseSM prd0 = printDenseSM0c -- instance (Elt a, Show a) => PrintDense (CsrMatrix a) where -- prd = printDenseSM
ocramz/sparse-linear-algebra
src/Data/Sparse/Common.hs
gpl-3.0
13,227
0
14
2,984
3,799
1,984
1,815
202
2
-- * heading -- | comment commented = commented
evolutics/haskell-formatter
testsuite/resources/source/comments/empty_lines/between_comments_of_same_declaration/3/Input.hs
gpl-3.0
51
1
4
12
11
5
6
1
1
{-# LANGUAGE ScopedTypeVariables, MultiParamTypeClasses, FlexibleContexts, MultiWayIf, TypeOperators, DeriveDataTypeable #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module FJ where import Data.Data import Data.Typeable import Data.List import Data.Maybe import Data.Either import Data.Tuple import Data.Foldable import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.Graph as Graph import Data.Generics.Uniplate.Data import Control.Applicative import Control.Monad import Control.Monad.Except import Control.Monad.Trans.Class as Trans import Control.Monad.Trans.Maybe import Control.Arrow (second) import Text.PrettyPrint import Test.QuickCheck import qualified Test.LazySmallCheck as LSC type f $ a = f a newtype Name = Name { unName :: String } deriving (Show, Eq, Ord, Data, Typeable) type ClassName = Name type FieldName = Name type MethodName = Name newtype Prog = Prog { classes :: [Class] } deriving (Eq, Data, Typeable) instance Show Prog where show = render . prettyProg data CachedProg = CachedProg { cchProg :: Prog , cchSupertypes :: Map ClassName [ClassName] , cchFields :: Map ClassName [Field] , cchMethods :: Map ClassName [Method] } deriving (Eq, Show) data Class = Class { className :: Name , superclass :: ClassName , fields :: [Field] , constructor :: Constructor , methods :: [Method] } deriving (Show, Eq, Data, Typeable) data Field = Field { fieldType :: ClassName , fieldName :: Name } deriving (Show, Eq, Data, Typeable) data Constructor = Constructor { constructorArguments :: [Field] , constructorSuperArguments :: [Field] } deriving (Show, Eq, Data, Typeable) data Method = Method { methodReturnType :: ClassName , methodName :: Name , methodParameters :: [(ClassName, Name)] , methodBodyExpr :: Expr } deriving (Show, Eq, Data, Typeable) data Expr = Var { exprType :: Maybe ClassName, varName :: Name } | FieldAccess { exprType :: Maybe ClassName, fieldAccessTarget :: Expr, fieldAccessName :: FieldName } | MethodCall { exprType :: Maybe ClassName, methodCallTarget :: Expr, methodCallName :: MethodName, methodCallArgs :: [Expr] } | New { exprType :: Maybe ClassName, newInstanceClassName :: ClassName, newInstanceArgs :: [Expr] } | Cast { exprType :: Maybe ClassName, castClassName :: ClassName, castTarget :: Expr } deriving (Show, Eq, Data, Typeable) -- Serial instance LSC.Serial Prog where series = LSC.cons1 Prog instance LSC.Serial Class where series = LSC.cons5 Class instance LSC.Serial Field where series = LSC.cons2 Field instance LSC.Serial Constructor where series = LSC.cons2 Constructor instance LSC.Serial Method where series = LSC.cons4 Method instance LSC.Serial Expr where series = LSC.cons1 (Var Nothing) LSC.\/ LSC.cons2 (FieldAccess Nothing) LSC.\/ LSC.cons3 (MethodCall Nothing) LSC.\/ LSC.cons2 (New Nothing) LSC.\/ LSC.cons2 (Cast Nothing) instance LSC.Serial Name where series = LSC.cons1 Name -- Generators unique :: Eq a => [a] -> Bool unique xs = nub xs == xs newtype Readable = Readable { getReadable :: String } instance Arbitrary Readable where arbitrary = do len <- (getSmall . getPositive) <$> arbitrary Readable <$> vectorOf len (elements (['A' .. 'Z'] ++ ['a'..'z'])) updateCachedProg :: CachedProg -> Class -> Maybe CachedProg updateCachedProg cprog class' = let prog = cchProg cprog super = superclass class' supertypes = cchSupertypes cprog allFields = cchFields cprog allMethods = cchMethods cprog in if | Just supersuperty <- Map.lookup (superclass class') supertypes , Just superFields <- Map.lookup (superclass class') allFields , Just superMethods <- Map.lookup (superclass class') allMethods -> return cprog { cchProg = prog { classes = class' : classes prog } , cchSupertypes = Map.insert (className class') ( superclass class' : supersuperty) supertypes , cchFields = Map.insert (className class') ( fields class' ++ superFields) allFields , cchMethods = Map.insert (className class') ( methods class' ++ superMethods) allMethods } | otherwise -> Nothing emptyCachedProg :: CachedProg emptyCachedProg = CachedProg (Prog []) (Map.singleton (Name "Object") []) (Map.singleton (Name "Object") []) (Map.singleton (Name "Object") []) makeCached :: Prog -> Maybe CachedProg makeCached prog = let classKeyMap = Map.fromList $ zipWith (\(cn, c) k -> (cn, (c, k))) (map (\c -> (className c, c)) $ classes prog) [1..] (g,vm) = Graph.graphFromEdges' $ map (\(cn, (c, k)) -> (c, k, toList (snd <$> Map.lookup (superclass c) classKeyMap))) (Map.toList classKeyMap) in foldlM updateCachedProg emptyCachedProg . map ((\(c,_,_) -> c) . vm) $ reverse $ Graph.topSort g genProgramScoped :: Int -> Gen Prog genProgramScoped size = do cnames <- nub <$> resize (size `div` 2) (listOf1 genName) _objc : cs <- reverse <$> foldrM (\cn gp1 -> (: gp1) <$> ((\(c,fs,ms,sp) -> (c,fs,ms,Just sp)) <$> genClassP1Scoped gp1 cn (size `div` length cnames))) [(Name "Object", [], [], Nothing)] cnames let cs' = map (\(c,fs,ms,Just sp) -> (c,fs,ms,sp)) cs cchProg <$> foldlM (\prevProg ci -> (fromJust . updateCachedProg prevProg) <$> genClassScoped prevProg cs' ci (size `div` length cs')) emptyCachedProg [0 .. length cs' - 1] genClassP1Scoped :: [(ClassName, [FieldName], [(MethodName, Int)], Maybe ClassName)] -> ClassName -> Int -> Gen (ClassName, [FieldName], [(MethodName, Int)], ClassName) genClassP1Scoped prevClasses cn size = do (super, superfs, superms, _) <- elements prevClasses (,,,) <$> pure cn <*> ((superfs ++) <$> (nub <$> resize (size `div` 2) (listOf genName))) <*> ((superms ++) <$> (nub <$> resize (size `div` 2) (listOf ((,) <$> genName <*> ((getSmall . getPositive) <$> arbitrary))))) <*> pure super genClassScoped :: CachedProg -> [(ClassName, [FieldName], [(MethodName, Int)], ClassName)] -> Int -> Int -> Gen Class genClassScoped prevProg classes index size = do let (cn, fs, ms, sn) = classes !! index let Just sfvals = fieldsOf prevProg sn let allcs = map (\(c,fs,_,_) -> (c, length fs)) classes let allfs = concatMap (\(_,fs,_,_) -> fs) classes let allms = concatMap (\(_,_,ms,_) -> ms) classes let specificfs = fs \\ map fieldName sfvals fieldvals <- mapM (genFieldScoped (map (\(c,_,_,_) -> c) classes)) specificfs Class cn sn fieldvals (Constructor (sfvals ++ fieldvals) sfvals) <$> mapM (\m -> genMethodScoped allcs allfs allms m ((size - length fs) `div` length ms)) ms genFieldScoped :: [ClassName] -> FieldName -> Gen Field genFieldScoped classes fn = Field <$> elements classes <*> pure fn genMethodScoped :: [(ClassName, Int)] -> [FieldName] -> [(MethodName, Int)] -> (MethodName, Int) -> Int -> Gen Method genMethodScoped classes fields methods (methodnm, argcount) size = do params <- zip <$> vectorOf argcount (fst <$> elements classes) <*> (vectorOf argcount genName `suchThat` unique) Method <$> (fst <$> elements classes) <*> pure methodnm <*> pure params <*> genExprScoped classes fields methods (map snd params ++ [Name "this"]) size genExprScoped :: [(ClassName, Int)] -> [FieldName] -> [(MethodName, Int)] -> [Name] -> Int -> Gen Expr genExprScoped classes fields methods env = go where go size = oneof $ [ Var Nothing <$> elements env | not (null env) ] ++ [ FieldAccess Nothing <$> go (size - 1) <*> elements fields | not (null fields) && size > 0 ] ++ [ do (m, argcount) <- elements methods MethodCall Nothing <$> go (size `div` (argcount + 1) ) <*> pure m <*> vectorOf argcount (go (size - 1)) | not (null methods) && size > 0 ] ++ [ do (c, argcount) <- elements classes New Nothing <$> pure c <*> vectorOf argcount (go (size `div` (argcount + 1))) | not (null classes) && size > 0 ] ++ [ Cast Nothing <$> (fst <$> elements classes) <*> go (size - 1) | not (null classes) && size > 0 ] genName :: Gen Name genName = (Name . getReadable) <$> arbitrary genProgramTyped :: Int -> Gen (Maybe Prog) genProgramTyped size = do classCount <- choose (1, floor . sqrt . fromIntegral $ size) _objc:classesP1 <- reverse <$> foldrM (\_ prevClasses -> (:) <$> fmap (second Just) (genClassP1Typed (reverse prevClasses)) <*> pure prevClasses) [(Name "Object", Nothing)] [0..classCount - 1] let size' = (max 0 $ size - classCount) `div` classCount let classesP1' = map (\(cn, Just scn) -> (cn,scn)) classesP1 _objc:classesP2 <- (reverse . fst) <$> foldlM (\(prevClasses, _:nextClasses) cp1 -> (,) <$> ((:) <$> ((\(cn,fs,ms,scn) -> (cn,fs,ms,Just scn)) <$> genClassP2Typed (reverse prevClasses) nextClasses cp1 size') <*> pure prevClasses) <*> pure nextClasses) ([(Name "Object", [], [], Nothing)], classesP1') classesP1' let classesP2' = fmap (\(cn,fs,ms, Just scn) -> (cn,fs,ms,scn)) classesP2 (cchProg <$>) <$> runMaybeT (foldlM (\prevProg ci -> (fromJust . updateCachedProg prevProg) <$> MaybeT (genClassTyped prevProg classesP2' ci (size' `div` 2))) emptyCachedProg [0 .. length classesP2' - 1]) genClassP1Typed :: [(ClassName, Maybe ClassName)] -> Gen (ClassName, ClassName) genClassP1Typed prevClasses = do super <- frequency $ fmap (\(c,_) -> (if unName c == "Object" then 1 else 5, return c)) prevClasses (,) <$> genName <*> pure super genClassP2Typed :: [(ClassName, [Field], [(MethodName, [ClassName], ClassName)], Maybe ClassName)] -> [(ClassName, ClassName)] -> (ClassName, ClassName) -> Int -> Gen (ClassName, [Field], [(MethodName, [ClassName], ClassName)], ClassName) genClassP2Typed prevClasses nextClasses (cn, scn) size = do -- TODO figure out sizing and proportions let Just (_, superfs, superms, _) = find (\(nm,_,_,_) -> scn == nm) prevClasses let allclasses = (1, return $ Name "Object") : fmap (\c -> (5, return c)) (map (\(nm,_,_,_) -> nm) prevClasses ++ [cn] ++ map fst nextClasses) (,,,) <$> pure cn <*> ((superfs ++) <$> (nub <$> resize (size `div` 3) (listOf (Field <$> frequency allclasses <*> genName)))) <*> ((superms ++) <$> (nub <$> resize (size `div` 3) (listOf ((,,) <$> genName <*> resize (size `div` 4) (listOf (frequency allclasses)) <*> frequency allclasses)))) <*> pure scn genClassTyped :: CachedProg -> [(ClassName, [Field], [(MethodName, [ClassName], ClassName)], ClassName)] -> Int -> Int -> Gen (Maybe Class) genClassTyped prevProg classes index size = runMaybeT $ do let (cn, fs, ms, sn) = classes !! index let cms = map (\(mn, atys, rty) -> (cn, mn, atys, rty)) ms let supertypes = foldl' (\prevSupers (c,_,_,sc) -> let Just scsupers = Map.lookup sc prevSupers in Map.insert c (sc:scsupers) prevSupers) (Map.singleton (Name "Object") []) classes let allcs = map (\(c,fs,_,_) -> (c, map fieldName fs)) classes let allfs = concatMap (\(c,fs,_,_) -> map (\f -> (c, fieldName f, fieldType f)) fs) classes let allms = concatMap (\(c,_,ms,_) -> map (\(mn, atys, rty) -> (c, mn, atys, rty)) ms) classes let Just sfvals = fieldsOf prevProg sn let specificfs = fs \\ sfvals Class cn sn specificfs (Constructor fs sfvals) <$> mapM (\m -> MaybeT $ genMethodTyped supertypes allcs allfs allms m ((max 0 $ size - length specificfs) `div` length cms)) cms genMethodTyped :: Map ClassName [ClassName] -> [(ClassName, [ClassName])] -> [(ClassName, FieldName, ClassName)] -> [(ClassName, MethodName, [ClassName], ClassName)] -> (ClassName, MethodName, [ClassName], ClassName) -> Int -> Gen (Maybe Method) genMethodTyped supertypes constructors fields methods (mclass, methodnm, argtys, retty) size = runMaybeT $ do params <- Trans.lift (zip argtys <$> (vectorOf (length argtys) ((Name . getReadable) <$> arbitrary) `suchThat` unique)) body <- MaybeT (join <$> (genExprTyped supertypes constructors fields methods (params ++ [(mclass, Name "this")]) Nothing retty size `suchThatMaybe` isJust)) -- Try with some backtracking return $ Method retty methodnm params body genExprTyped :: Map ClassName [ClassName] -> [(ClassName, [ClassName])] -> [(ClassName, FieldName, ClassName)] -> [(ClassName, MethodName, [ClassName], ClassName)] -> [(ClassName, Name)] -> Maybe ClassName -> ClassName -> Int -> Gen (Maybe Expr) genExprTyped supertypes constructors fields methods env = go where go :: Maybe ClassName -> ClassName -> Int -> Gen (Maybe Expr) go targetSubType targetSuperType size = if not (null possibleValues) then oneof possibleValues else return Nothing where possibleValues = [(Just . Var Nothing . snd) <$> elements possibleVars | not (null possibleVars)] ++ [runMaybeT $ do (tty, fnm, _fty) <- Trans.lift $ elements possibleFields texpr <- MaybeT $ go Nothing tty (size - 1) return $ FieldAccess Nothing texpr fnm | not (null possibleFields) && size > 0 ] ++ [runMaybeT $ do (tty, mnm, atys, _retty) <- Trans.lift $ elements possibleMethods let size' = size `div` (length atys + 1) texpr <- MaybeT $ go Nothing tty size' aexprs <- mapM (MaybeT . flip (go Nothing) size') atys return $ MethodCall Nothing texpr mnm aexprs | not (null possibleMethods) && size > 0] ++ [runMaybeT $ do (tty, atys) <- Trans.lift $ elements possibleConstructors let size' = size `div` length atys aexprs <- mapM (MaybeT . flip (go Nothing) size') atys return $ New Nothing tty aexprs | not (null possibleConstructors) && size > 0] ++ [runMaybeT $ do castTy <- MaybeT $ genType supertypes targetSubType targetSuperType castExpr <- MaybeT $ go Nothing castTy (size - 1) return $ Cast Nothing castTy castExpr | size > 0] ++ [runMaybeT $ do castTy <- MaybeT $ genType supertypes targetSubType targetSuperType castExpr <- MaybeT $ go (Just castTy) (Name "Object") (size - 1) return $ Cast Nothing castTy castExpr | size > 0] possibleConstructors = filter (\(ty, _argtys) -> withinBounds ty) constructors possibleFields = filter (\(_ety, _fn, fty) -> withinBounds fty) fields possibleMethods = filter (\(_ety, _mn, _argtys, retty) -> withinBounds retty) methods possibleVars = filter (\(xty, _xn) -> withinBounds xty) env withinBounds ty = any (targetSuperType `elem`) ((ty :) <$> Map.lookup ty supertypes) && all (\subty -> any (ty `elem`) ((subty :) <$> Map.lookup subty supertypes)) targetSubType genType :: Map ClassName [ClassName] -> Maybe ClassName -> ClassName -> Gen (Maybe ClassName) genType supertypes lty hty = if not (null possibletys) then Just <$> elements possibletys else return Nothing where hsubtys = Map.keys $ Map.filter (hty `elem`) supertypes possibletys = filter (\hsty -> all (hsty `elem`) (lty >>= (`Map.lookup` supertypes))) hsubtys -- Checking infixr 6 :=>: data MethodType = [ClassName] :=>: ClassName deriving (Show, Eq) isSubtype :: CachedProg -> ClassName -> ClassName -> Bool isSubtype p c1 c2 = c1 == c2 || any (c2 `elem`) (Map.lookup c1 (cchSupertypes p)) fieldsOf :: CachedProg -> ClassName -> Maybe [Field] fieldsOf p = flip Map.lookup (cchFields p) methodsOf :: CachedProg -> ClassName -> Maybe [Method] methodsOf p = flip Map.lookup (cchMethods p) methodType :: CachedProg -> MethodName -> ClassName -> Maybe MethodType methodType prog mn cn = do mets <- reverse <$> methodsOf prog cn m <- find ((== mn) . methodName) mets return (map fst (methodParameters m) :=>: methodReturnType m) methodBody :: CachedProg -> MethodName -> ClassName -> Maybe Expr methodBody prog mn cn = do mets <- reverse <$> methodsOf prog cn m <- find ((== mn) . methodName) mets return (methodBodyExpr m) checkScope :: Prog -> Bool checkScope prog = case makeCached prog of Just cprog -> all (checkClassScope cprog) (classes prog) Nothing -> False checkClassScope :: CachedProg -> Class -> Bool checkClassScope prog (Class cn sn cflds (Constructor iflds sflds) meths) = iflds == sflds ++ cflds && elem sflds (fieldsOf prog sn) && all (checkMethodScope prog) meths checkMethodScope :: CachedProg -> Method -> Bool checkMethodScope prog (Method _rty _mnm pars mbody) = checkExpressionScope prog (map snd pars ++ [Name "this"]) mbody checkExpressionScope :: CachedProg -> [Name] -> Expr -> Bool checkExpressionScope _prog env (Var Nothing nm) = nm `elem` env checkExpressionScope prog env (FieldAccess Nothing e f) = checkExpressionScope prog env e && any ((== f) . fieldName) (concat . Map.elems . cchFields $ prog) checkExpressionScope prog env (MethodCall Nothing e m es) = checkExpressionScope prog env e && any (\m' -> length (methodParameters m') == length es && ((== m) . methodName $ m')) (concat . Map.elems . cchMethods $ prog) && all (checkExpressionScope prog env) es checkExpressionScope prog env (New Nothing c es) = length (let Just fs = fieldsOf prog c in fs) == length es && all (checkExpressionScope prog env) es checkExpressionScope prog env (Cast Nothing _c e) = checkExpressionScope prog env e checkExpressionScope prog env _ = False checkTypes :: CachedProg -> Maybe CachedProg checkTypes prog = makeCached =<< (Prog <$> mapM (checkClassType prog) (classes . cchProg $ prog)) checkClassType :: CachedProg -> Class -> Maybe Class checkClassType prog (Class cn sn cflds (Constructor iflds sflds) meths) = do guard $ iflds == sflds ++ cflds guard $ elem sflds (fieldsOf prog sn) meths' <- mapM (checkMethodType prog cn) meths return (Class cn sn cflds (Constructor iflds sflds) meths') checkMethodType :: CachedProg -> ClassName -> Method -> Maybe Method checkMethodType prog cn (Method rty mnm pars mbody) = do csuper:_ <- Map.lookup cn (cchSupertypes prog) guard $ all (\(sparty :=>: srty) -> map fst pars == sparty && rty == srty) (methodType prog mnm csuper) (bodyty, mbody') <- typeExpression prog (pars ++ [(cn, Name "this")]) mbody guard $ isSubtype prog bodyty rty return $ Method rty mnm pars mbody' typeExpression :: CachedProg -> [(ClassName, Name)] -> Expr -> Maybe (ClassName, Expr) -- a pair of result type and type-annotated expression typeExpression prog env (Var Nothing x) = let xty = lookup x (map swap env) in (,) <$> xty <*> return (Var xty x) typeExpression prog env (FieldAccess Nothing e0 fi) = do (e0ty, e0') <- typeExpression prog env e0 fs <- fieldsOf prog e0ty fty <- fieldType <$> find ((== fi) . fieldName) fs return (fty, FieldAccess (Just fty) e0' fi) typeExpression prog env (MethodCall Nothing e0 m es) = do (e0ty, e0') <- typeExpression prog env e0 (parstys :=>: mrety) <- methodType prog m e0ty guard $ length es == length parstys (ets, es') <- unzip <$> mapM (typeExpression prog env) es guard $ all (uncurry (isSubtype prog)) (zip ets parstys) return (mrety, MethodCall (Just mrety) e0' m es') typeExpression prog env (New Nothing cn es) = do fts <- map fieldType <$> fieldsOf prog cn guard $ length es == length fts (ets, es') <- unzip <$> mapM (typeExpression prog env) es guard $ all (uncurry (isSubtype prog)) (zip ets fts) return (cn, New (Just cn) cn es') typeExpression prog env (Cast Nothing tc e) = do (_ety, e') <- typeExpression prog env e return {- if not (isSubtype prog ety tc) && not (isSubtype prog tc ety) then tc {- STUPID WARNING -} else -} (tc, Cast (Just tc) tc e') typeExpression _prog _env _ = Nothing forgetTypeAnnotations :: Prog -> Prog forgetTypeAnnotations = transformBi (\(e :: Expr) -> e { exprType = Nothing }) -- Pretty Printing prettyProg :: Prog -> Doc prettyProg = vcat . map prettyClass . classes prettyClass :: Class -> Doc prettyClass (Class cn sn fs ctor ms) = text "class" <+> text (unName cn) <+> text "extends" <+> text (unName sn) <+> lbrace $+$ nest 2 (vcat (map prettyField fs ++ [prettyConstructor cn ctor fs] ++ map prettyMethod ms)) $+$ rbrace prettyField :: Field -> Doc prettyField (Field cn fn) = text (unName cn) <+> text (unName fn) <> semi prettyConstructor :: ClassName -> Constructor -> [Field] -> Doc prettyConstructor cn (Constructor args superargs) fs = text (unName cn) <> parens (sep $ punctuate comma (map prettyArg args)) <+> lbrace $+$ nest 2 (vcat $ (text "super" <> parens (sep $ punctuate comma (map (text . unName . fieldName) superargs)) <> semi) : map prettyInitialize fs) $+$ rbrace where prettyArg :: Field -> Doc prettyArg (Field cn fn) = text (unName cn) <+> text (unName fn) prettyInitialize :: Field -> Doc prettyInitialize (Field cn fn) = text "this" <> text "." <> text (unName fn) <+> equals <+> text (unName fn) <> semi prettyMethod :: Method -> Doc prettyMethod (Method rty mnm pars body) = text (unName rty) <+> text (unName mnm) <> parens (sep $ punctuate comma (map prettyPar pars)) <+> lbrace $+$ nest 2 (text "return" <+> prettyExpr body <> semi) $+$ rbrace where prettyPar :: (ClassName, Name) -> Doc prettyPar (cn, n) = text (unName cn) <+> text (unName n) prettyExpr :: Expr -> Doc prettyExpr (Var _ nm) = text (unName nm) prettyExpr (FieldAccess _ e f) = prettyExpr e <> text "." <> text (unName f) prettyExpr (MethodCall _ e0 m es) = prettyExpr e0 <> text "." <> text (unName m) <> parens (sep $ punctuate comma (map prettyExpr es)) prettyExpr (New _ c es) = text "new" <+> text (unName c) <> parens (sep $ punctuate comma (map prettyExpr es)) prettyExpr (Cast _ c e) = parens (text (unName c)) <> prettyExpr e -- Refactorings findClass :: (MonadError String m) => Prog -> ClassName -> m Class findClass prog classnm = fromMaybe (throwError $ "Unknown class: " ++ unName classnm) (return <$> find ((== classnm) . className) (classes prog)) renameFieldPrecondition :: (MonadError String m) => CachedProg -> ClassName -> FieldName -> FieldName -> m () renameFieldPrecondition prog classnm oldfieldnm newfieldnm = do class' <- findClass (cchProg prog) classnm unless (any ((== oldfieldnm) . fieldName) $ fields class') $ throwError ("Class " ++ unName classnm ++ "does not have field " ++ unName oldfieldnm) when (any (any ((== newfieldnm) . fieldName)) $ fieldsOf prog classnm) $ throwError ("Class " ++ unName classnm ++ "or one of its superclasses already have field " ++ unName newfieldnm) renameField :: (MonadError String m) => CachedProg -> ClassName -> FieldName -> FieldName -> m Prog renameField prog classnm oldfieldnm newfieldnm = do renameFieldPrecondition prog classnm oldfieldnm newfieldnm let prog' = rewriteBi (\(c :: Class) -> if className c == classnm then do oldField <- find ((== oldfieldnm) . fieldName) (fields c) return c { fields = Field (fieldType oldField) newfieldnm : delete oldField (fields c), constructor = (constructor c) { constructorArguments = map (\a -> if fieldName a == oldfieldnm then oldField { fieldName = newfieldnm } else a) $ constructorArguments (constructor c) } } else Nothing) (cchProg prog) return $ rewriteBi (\(e :: Expr) -> case e of FieldAccess (Just c) e f -> if isSubtype prog c classnm && f == oldfieldnm then return $ FieldAccess (Just c) e newfieldnm else Nothing _ -> Nothing) prog' extractSuperPrecondition :: (MonadError String m) => CachedProg -> ClassName -> ClassName -> ClassName -> m (Class, Class) extractSuperPrecondition prog class1nm class2nm newsupernm = do class1 <- findClass (cchProg prog) class1nm class2 <- findClass (cchProg prog) class2nm unless (superclass class1 == superclass class2) $ throwError $ "The provided classes " ++ unName class1nm ++ " and " ++ unName class2nm ++ " do not have the same supertype" when (Set.member newsupernm . Map.keysSet $ cchSupertypes prog) $ throwError $ "Target superclass name, " ++ unName newsupernm ++ " is already in use" return (class1, class2) extractSuper :: (MonadError String m) => CachedProg -> ClassName -> ClassName -> ClassName -> m Prog extractSuper prog class1nm class2nm newsupernm = do (class1, class2) <- extractSuperPrecondition prog class1nm class2nm newsupernm let commonFields = fields class1 `intersect` fields class2 let commonMethods = methods class1 `intersect` methods class2 let prevsupernm = superclass class1 prevsuperfields <- fromMaybe (throwError $ "Can not find fields of " ++ unName prevsupernm) (return <$> fieldsOf prog prevsupernm) let prog' = rewriteBi (\(c :: Class) -> if (className c == class1nm || className c == class2nm) && superclass c /= newsupernm then let newfields = fields c \\ commonFields newmethods = methods c \\ commonMethods newsuperfields = prevsuperfields ++ commonFields in return c { fields = newfields, methods = newmethods, constructor = Constructor (newsuperfields ++ newfields) newsuperfields, superclass = newsupernm } else Nothing) (cchProg prog) let prog'' = prog' { classes = Class newsupernm prevsupernm commonFields (Constructor (prevsuperfields ++ commonFields) prevsuperfields) commonMethods : classes prog' } -- TODO Extend extract superclass to handle generalization of function parameters and other local variables where possible return prog'' replaceDelegationWithInheritancePrecondition :: (MonadError String m) => CachedProg -> ClassName -> FieldName -> m (Class, Field) replaceDelegationWithInheritancePrecondition prog classnm fieldnm = do class' <- findClass (cchProg prog) classnm unless (superclass class' == Name "Object") $ throwError $ "Class " ++ unName classnm ++ " already has a superclass " ++ unName (superclass class') field <- fromMaybe (throwError $ "Class " ++ unName classnm ++ " does not contain field " ++ unName fieldnm) (return <$> find ((== fieldnm) . fieldName) (fields class')) when (isSubtype prog (fieldType field) (className class')) $ throwError $ "Target type of field " ++ unName (fieldName field) ++ " must not be a subtype of target class" ++ unName (className class') return (class', field) replaceDelegationWithInheritance :: (MonadError String m) => CachedProg -> ClassName -> FieldName -> m Prog replaceDelegationWithInheritance prog classnm fieldnm = do (class', field) <- replaceDelegationWithInheritancePrecondition prog classnm fieldnm let fty = fieldType field ftyfields <- fromMaybe (throwError $ "Can not find fields of " ++ unName fty) (return <$> fieldsOf prog fty) ftymethods <- fromMaybe (throwError $ "Can not find methods of " ++ unName fty) (return <$> methodsOf prog fty) let prog' = rewriteBi (\(c :: Class) -> if className c == classnm && elem field (fields c) then let delegatedmethods = filter (\(m :: Method) -> any ((== methodName m) . methodName) ftymethods && case methodBodyExpr m of (MethodCall (Just _cm) (FieldAccess (Just _cf) (Var (Just _ct) (Name "this")) fn) mn es) -> methodName m == mn && fieldnm == fn _ -> False ) (universeBi c) newfields = delete field (fields c) c' = c { methods = methods c \\ delegatedmethods, fields = newfields, constructor = Constructor (ftyfields ++ newfields) ftyfields, superclass = fty } c'' = rewriteBi (\(e :: Expr) -> case e of FieldAccess (Just _cf) v@(Var (Just _ct) (Name "this")) fn | fieldnm == fn -> return v _ -> Nothing) c' in return c'' else Nothing) (cchProg prog) let prog'' = rewriteBi (\(e :: Expr) -> case e of FieldAccess (Just _tc) e fn | Just ety <- exprType e, isSubtype prog ety classnm && fieldnm == fn -> return e _ -> Nothing) prog' return prog'' -- Example Programs animalProg :: Prog animalProg = Prog [ Class (Name "Animal") (Name "Object") [Field (Name "Object") (Name "happiness")] (Constructor [Field (Name "Object") (Name "happiness")] []) [Method (Name "Object") (Name "friend") [(Name "Animal", Name "other")] (FieldAccess Nothing (Var Nothing (Name "other")) (Name "happiness"))] ] renamedHappiness :: Prog renamedHappiness = let Just animalProgCached = makeCached animalProg Just animalProgTyped = checkTypes animalProgCached Right animalProgRenamed = renameField animalProgTyped (Name "Animal") (Name "happiness") (Name "excitement") in animalProgRenamed accountProg :: Prog accountProg = Prog [ Class (Name "SuperSavingsAccount") (Name "Object") [Field (Name "Object") (Name "interest"), Field (Name "Object") (Name "balance")] (Constructor [Field (Name "Object") (Name "interest"), Field (Name "Object") (Name "balance")] []) [Method (Name "SuperSavingsAccount") (Name "updateInterest") [(Name "Object", Name "newInterest")] (New Nothing (Name "SuperSavingsAccount") [Var Nothing (Name "newInterest"), FieldAccess Nothing (Var Nothing (Name "this")) (Name "balance")])] , Class (Name "BasicAccount") (Name "Object") [Field (Name "Object") (Name "balance")] (Constructor [Field (Name "Object") (Name "balance")] []) [] ] extractAccountSuperProg :: Prog extractAccountSuperProg = let Just accountProgCached = makeCached accountProg Just accountProgTyped = checkTypes accountProgCached Right accountProgSuperExtracted = extractSuper accountProgTyped (Name "SuperSavingsAccount") (Name "BasicAccount") (Name "Account") in accountProgSuperExtracted teacherProg :: Prog teacherProg = Prog [ Class (Name "Person") (Name "Object") [Field (Name "Object") (Name "name")] (Constructor [Field (Name "Object") (Name "name")] []) [Method (Name "Object") (Name "getName") [] (FieldAccess Nothing (Var Nothing (Name "this")) (Name "name"))], Class (Name "Teacher") (Name "Object") [Field (Name "Person") (Name "person")] (Constructor [Field (Name "Person") (Name "person")] []) [Method (Name "Object") (Name "getName") [] (MethodCall Nothing (FieldAccess Nothing (Var Nothing (Name "this")) (Name "person")) (Name "getName") [])] ] teacherInheritanceProg :: Prog teacherInheritanceProg = let Just teacherProgCached = makeCached teacherProg Just teacherProgTyped = checkTypes teacherProgCached Right teacherProgInheritance = replaceDelegationWithInheritance teacherProgTyped (Name "Teacher") (Name "person") in teacherProgInheritance -- Interface data TransformationInput a = TransformationInput { tiProg :: CachedProg , tiAux :: a } deriving (Show, Eq) data Transformation a = Transformation { tInputGen :: Gen (Maybe $ TransformationInput a) , tPrecond :: TransformationInput a -> Bool , tTrans :: TransformationInput a -> Maybe Prog } -- Properties renameFieldInputGen :: Gen (Maybe Prog) -> MaybeT Gen (TransformationInput (ClassName, FieldName, FieldName)) renameFieldInputGen progGen = do prog <- MaybeT . fmap join $ progGen `suchThatMaybe` (\(pM :: Maybe Prog) -> any (\p -> any (\cp -> any (\c -> not (null $ fields c)) (classes . cchProg $ cp)) (makeCached p)) pM) let Just cp = makeCached prog class' <- Trans.lift $ elements (filter (\c -> not (null $ fields c)) (classes . cchProg $ cp)) oldfield <- Trans.lift (fieldName <$> elements (fields class')) newfield <- (Name . getReadable) <$> (MaybeT $ arbitrary `suchThatMaybe` (\(Readable n) -> any (Name n `notElem`) $ fmap (map fieldName) (fieldsOf cp (className class')))) return $ TransformationInput cp (className class', oldfield, newfield) renameFieldTransformation :: Transformation (ClassName, FieldName, FieldName) renameFieldTransformation = Transformation { tInputGen = runMaybeT $ renameFieldInputGen (sized genProgramTyped) , tPrecond = \(TransformationInput prog (cn, ofn, nfn)) -> isRight (renameFieldPrecondition prog cn ofn nfn) , tTrans = \(TransformationInput prog (cn, ofn, nfn)) -> either (const Nothing) Just $ renameField prog cn ofn nfn } extractSuperInputGen :: Gen (Maybe Prog) -> MaybeT Gen (TransformationInput (ClassName, ClassName, ClassName)) extractSuperInputGen progGen = do prog <- MaybeT . fmap join $ progGen `suchThatMaybe` (\(pM :: Maybe Prog) -> any (\p -> isJust (makeCached p) && any (\(c1, c2) -> superclass c1 == superclass c2) [(c1, c2) | c1 <- classes p, c2 <- classes p, className c1 /= className c2 ]) pM) (c1,c2) <- Trans.lift $ elements [(c1, c2) | c1 <- classes prog , c2 <- classes prog , className c1 /= className c2 , superclass c1 == superclass c2] csuper <- (Name . getReadable) <$> (MaybeT $ arbitrary `suchThatMaybe` (\(Readable n) -> Name n `notElem` map className (classes prog))) return $ TransformationInput (fromJust . makeCached $ prog) (className c1, className c2, csuper) extractSuperTransformation :: Transformation (ClassName, ClassName, ClassName) extractSuperTransformation = Transformation { tInputGen = runMaybeT $ extractSuperInputGen (sized genProgramTyped) , tPrecond = \(TransformationInput prog (cn1, cn2, cnsuper)) -> isRight (extractSuperPrecondition prog cn1 cn2 cnsuper) , tTrans = \(TransformationInput prog (cn1, cn2, cnsuper)) -> either (const Nothing) Just $ extractSuper prog cn1 cn2 cnsuper } replaceDelegationWithInheritanceInputGen :: Gen (Maybe Prog) -> MaybeT Gen (TransformationInput (ClassName, FieldName)) replaceDelegationWithInheritanceInputGen progGen = do prog <- MaybeT . fmap join $ progGen `suchThatMaybe` (\(pM :: Maybe Prog) -> any (\p -> let cp = makeCached p in isJust cp && any (\c -> any (isRight . replaceDelegationWithInheritancePrecondition (fromJust cp) (className c) . fieldName) (fields c)) (classes . cchProg $ fromJust cp)) pM) let Just cprog = makeCached prog class' <- Trans.lift $ elements (filter (\c -> any (isRight . replaceDelegationWithInheritancePrecondition cprog (className c) . fieldName) (fields c)) (classes . cchProg $ cprog)) field <- Trans.lift $ elements (filter (isRight . replaceDelegationWithInheritancePrecondition cprog (className class') . fieldName) $ fields class') return $ TransformationInput cprog (className class', fieldName field) replaceDelegationWithInheritanceTransformation :: Transformation (ClassName, FieldName) replaceDelegationWithInheritanceTransformation = Transformation { tInputGen = runMaybeT $ replaceDelegationWithInheritanceInputGen (sized genProgramTyped) , tPrecond = \(TransformationInput prog (cn, fn)) -> isRight (replaceDelegationWithInheritancePrecondition prog cn fn) , tTrans = \(TransformationInput prog (cn, fn)) -> either (const Nothing) Just $ replaceDelegationWithInheritance prog cn fn } inputGenPrecondProperty :: Show a => Transformation a -> Property inputGenPrecondProperty tran = forAll (tInputGen tran) (\minp -> isJust minp ==> tPrecond tran (fromJust minp)) wellTypednessProperty :: Show a => Transformation a -> Property wellTypednessProperty tran = forAll (tInputGen tran) (\input -> let progTy = checkTypes =<< (tiProg <$> input) in isJust input && isJust progTy ==> let progOut = tTrans tran (fromJust input) { tiProg = fromJust progTy } in isJust (checkTypes <$> (makeCached =<< (forgetTypeAnnotations <$> progOut)))) wellTypednessPropertySC :: Transformation a -> (Prog, a) -> LSC.Property wellTypednessPropertySC tran (prog, aux) = let cprog = makeCached prog progTy = checkTypes =<< cprog tinput = TransformationInput (fromJust cprog) aux in LSC.lift (isJust progTy) LSC.*&* LSC.lift (tPrecond tran tinput) LSC.*=>* let progOut = tTrans tran tinput in LSC.lift (isJust (checkTypes <$> (makeCached =<< (forgetTypeAnnotations <$> progOut)))) -- Sampling from Generators sampleProgGen :: Gen (Maybe Prog) -> IO () sampleProgGen progGen = do vs <- sample' progGen let welltyped = filter (\v -> isJust (v >>= makeCached >>= checkTypes)) vs mapM_ (putStrLn . (++ "\n\n\n------------------------------") . show) welltyped putStrLn ("Generated program count total: " ++ show (length vs) ++ "\n" ++ "Generated program count well-typed: " ++ show (length welltyped))
ahmadsalim/micro-dsl-properties
src/FJ.hs
gpl-3.0
41,560
0
32
12,469
14,104
7,283
6,821
645
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AndroidDeviceProvisioning.Customers.Configurations.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the details of a configuration. -- -- /See:/ <https://developers.google.com/zero-touch/ Android Device Provisioning Partner API Reference> for @androiddeviceprovisioning.customers.configurations.get@. module Network.Google.Resource.AndroidDeviceProvisioning.Customers.Configurations.Get ( -- * REST Resource CustomersConfigurationsGetResource -- * Creating a Request , customersConfigurationsGet , CustomersConfigurationsGet -- * Request Lenses , ccgXgafv , ccgUploadProtocol , ccgAccessToken , ccgUploadType , ccgName , ccgCallback ) where import Network.Google.AndroidDeviceProvisioning.Types import Network.Google.Prelude -- | A resource alias for @androiddeviceprovisioning.customers.configurations.get@ method which the -- 'CustomersConfigurationsGet' request conforms to. type CustomersConfigurationsGetResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Configuration -- | Gets the details of a configuration. -- -- /See:/ 'customersConfigurationsGet' smart constructor. data CustomersConfigurationsGet = CustomersConfigurationsGet' { _ccgXgafv :: !(Maybe Xgafv) , _ccgUploadProtocol :: !(Maybe Text) , _ccgAccessToken :: !(Maybe Text) , _ccgUploadType :: !(Maybe Text) , _ccgName :: !Text , _ccgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CustomersConfigurationsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccgXgafv' -- -- * 'ccgUploadProtocol' -- -- * 'ccgAccessToken' -- -- * 'ccgUploadType' -- -- * 'ccgName' -- -- * 'ccgCallback' customersConfigurationsGet :: Text -- ^ 'ccgName' -> CustomersConfigurationsGet customersConfigurationsGet pCcgName_ = CustomersConfigurationsGet' { _ccgXgafv = Nothing , _ccgUploadProtocol = Nothing , _ccgAccessToken = Nothing , _ccgUploadType = Nothing , _ccgName = pCcgName_ , _ccgCallback = Nothing } -- | V1 error format. ccgXgafv :: Lens' CustomersConfigurationsGet (Maybe Xgafv) ccgXgafv = lens _ccgXgafv (\ s a -> s{_ccgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ccgUploadProtocol :: Lens' CustomersConfigurationsGet (Maybe Text) ccgUploadProtocol = lens _ccgUploadProtocol (\ s a -> s{_ccgUploadProtocol = a}) -- | OAuth access token. ccgAccessToken :: Lens' CustomersConfigurationsGet (Maybe Text) ccgAccessToken = lens _ccgAccessToken (\ s a -> s{_ccgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ccgUploadType :: Lens' CustomersConfigurationsGet (Maybe Text) ccgUploadType = lens _ccgUploadType (\ s a -> s{_ccgUploadType = a}) -- | Required. The configuration to get. An API resource name in the format -- \`customers\/[CUSTOMER_ID]\/configurations\/[CONFIGURATION_ID]\`. ccgName :: Lens' CustomersConfigurationsGet Text ccgName = lens _ccgName (\ s a -> s{_ccgName = a}) -- | JSONP ccgCallback :: Lens' CustomersConfigurationsGet (Maybe Text) ccgCallback = lens _ccgCallback (\ s a -> s{_ccgCallback = a}) instance GoogleRequest CustomersConfigurationsGet where type Rs CustomersConfigurationsGet = Configuration type Scopes CustomersConfigurationsGet = '[] requestClient CustomersConfigurationsGet'{..} = go _ccgName _ccgXgafv _ccgUploadProtocol _ccgAccessToken _ccgUploadType _ccgCallback (Just AltJSON) androidDeviceProvisioningService where go = buildClient (Proxy :: Proxy CustomersConfigurationsGetResource) mempty
brendanhay/gogol
gogol-androiddeviceprovisioning/gen/Network/Google/Resource/AndroidDeviceProvisioning/Customers/Configurations/Get.hs
mpl-2.0
4,850
0
15
1,030
695
406
289
99
1
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } func = do let x = 13 stmt x
lspitzner/brittany
data/Test443.hs
agpl-3.0
146
1
9
24
25
10
15
3
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveDataTypeable, ScopedTypeVariables #-} -------------------------------------------------------------------------------- {-| Module : Classes Copyright : (c) Daan Leijen 2003 License : wxWindows Maintainer : wxhaskell-devel@lists.sourceforge.net Stability : provisional Portability : portable This modules defines attributes common to many widgets and organizes them into Haskell classes. Look at the instance definitions to see what kind of widgets support the attributes. Sometimes it is hard to find what attributes a certain widget supports since the instance definitions might be on some class higher in the hierarchy. For example, many instances are defined for 'Window' @a@ -- this means that all those attributes are applicable to any kind of 'Window', i.e. frames, buttons, panels etc. However, these attributes will not be explicitly listed at the type definitions of those classes. -} -------------------------------------------------------------------------------- module Graphics.UI.WX.Classes ( -- * Data types Border(..) -- * Text , Textual(text,appendText) , Literate(font ,fontFamily, fontFace, fontSize, fontWeight, fontUnderline, fontShape ,textColor,textBgcolor) -- * Rendering , Dimensions(..) , Colored(..) , Visible(..) , Bordered(..) -- * Hierarchy , Child(..) , Parent(..) , Closeable(..) -- * Containers , Selection( selection ) , Selections( selections ) , Items( itemCount, item, items, itemAppend, itemDelete, itemsDelete ) -- * Misc. , Able( enabled ) -- , enable , Help( help ) , Tipped( tooltip ) , Identity( identity ) , Styled( style ) , Framed( resizeable, maximizeable, minimizeable, closeable ) , Checkable( checkable, checked ) , Dockable( dockable ) , Pictured( picture ) , Valued( value ) , Sized( size ) , HasDefault( unsafeDefaultItem, defaultButton ) ) where import Data.Dynamic import Graphics.UI.WXCore import Graphics.UI.WX.Types import Graphics.UI.WX.Attributes import Graphics.UI.WX.Layout -- | Widgets with a label or text field. class Textual w where -- | The text of a widget. It is interpreted differently for -- for different widgets, for example, the title of a frame or the content of a -- static text control. text :: Attr w String appendText :: w -> String -> IO () appendText w s = set w [text :~ (++s)] -- | Widgets with a picture. class Pictured w where -- | The image of a widget. picture :: Attr w FilePath -- | Widgets with a font. class Literate w where -- | The font of the widget. font :: Attr w FontStyle -- | The font size. fontSize :: Attr w Int -- | The font weight. fontWeight :: Attr w FontWeight -- | The font family. fontFamily :: Attr w FontFamily -- | The font style. fontShape :: Attr w FontShape -- | The font /face/: determines a platform dependent font. fontFace :: Attr w String -- | Is the font underlined? fontUnderline :: Attr w Bool -- | Text color. textColor :: Attr w Color -- | Text background color textBgcolor:: Attr w Color fontSize = mapAttr _fontSize (\finfo x -> finfo{ _fontSize = x }) font fontWeight = mapAttr _fontWeight (\finfo x -> finfo{ _fontWeight = x }) font fontFamily = mapAttr _fontFamily (\finfo x -> finfo{ _fontFamily = x }) font fontShape = mapAttr _fontShape (\finfo x -> finfo{ _fontShape = x }) font fontFace = mapAttr _fontFace (\finfo x -> finfo{ _fontFace = x }) font fontUnderline = mapAttr _fontUnderline (\finfo x -> finfo{ _fontUnderline = x }) font -- | Widgets that have a size. class Dimensions w where -- | The outer size of a widget (in pixels). outerSize :: Attr w Size -- | The (relative) position of a widget. position :: Attr w Point -- | The occupied area. area :: Attr w Rect -- | The preferred size of a widget. bestSize :: ReadAttr w Size -- | The area available for client use (i.e. without the border etc). clientSize :: Attr w Size -- | The virtual size of a widget (ie. the total scrolling area) virtualSize :: Attr w Size -- defaults outerSize = mapAttr rectSize (\r sz -> rect (rectTopLeft r) sz) area position = mapAttr rectTopLeft (\r pt -> rect pt (rectSize r)) area area = newAttr "area" getArea setArea where getArea w = do sz <- get w outerSize pt <- get w position return (rect pt sz) setArea w rect = set w [outerSize := rectSize rect, position := rectTopLeft rect] clientSize = outerSize bestSize = outerSize virtualSize = clientSize class Colored w where -- | The background color. bgcolor :: Attr w Color -- | The (foreground) color color :: Attr w Color bgcolor = nullAttr "bgcolor" color = nullAttr "color" -- | Visible widgets. class Visible w where -- | Is the widget visible? -- -- If you hide a widget, its space will not immediately -- be filled by other widgets. -- Vice versa if you make a widget visible -- it will not have space to be rendered into. -- That is, when changing the visibility state -- it is advised to update the layout -- using 'Graphics.UI.WX.Layout.windowReFit'. -- -- Example: -- -- > do set w [ visible := False ] -- > windowReFit w visible :: Attr w Bool -- | Refresh the widget explicitly. refresh :: w -> IO () -- | Should the widget be fully repainted on resize? This attribute only -- has effect when set at creation. If 'False', you will have to repaint -- the new window area manually at a resize, but flickering caused by -- background redraws can be prevented in this way. ('False' by default) fullRepaintOnResize :: Attr w Bool fullRepaintOnResize = nullAttr "fullRepaintOnResize" -- defaults visible = nullAttr "visible" refresh w = return () -- | Parent widgets. class Parent w where -- | Get the child widgets of a window. children :: ReadAttr w [Window ()] children = nullAttr "window" -- | Reduce flicker by not redrawing the background under child controls. -- This attribute has to be set at creation time. ('True' by default) clipChildren :: Attr w Bool clipChildren = nullAttr "clipChildren" -- | Window borders data Border = BorderSimple -- ^ Displays a thin border around the window. | BorderDouble -- ^ Displays a double border. Windows only. | BorderSunken -- ^ Displays a sunken border. | BorderRaised -- ^ Displays a raised border. | BorderStatic -- ^ Displays a border suitable for a static control. Windows only | BorderNone -- ^ No border deriving (Eq,Show,Read,Typeable) instance BitMask Border where assocBitMask = [(BorderSimple, wxBORDER) ,(BorderDouble, wxDOUBLE_BORDER) ,(BorderSunken, wxSUNKEN_BORDER) ,(BorderRaised, wxRAISED_BORDER) ,(BorderStatic, wxSTATIC_BORDER) ,(BorderNone, 0)] -- | Widgets with a border. class Bordered w where -- | Specify the border of a widget. border :: Attr w Border border = nullAttr "border" -- | Widgets that are part of a hierarchical order. class Child w where -- | The parent widget. parent :: ReadAttr w (Window ()) -- defaults parent = readAttr "parent" (\w -> return objectNull) -- | Widgets that can be closed. class Closeable w where -- | Close the widget. close :: w -> IO () -- | Widgets that have a system frame around them. class Framed w where -- | Make the widget user resizeable? This attribute must be set at creation time. resizeable :: Attr w Bool resizeable = nullAttr "resizeable" -- | Can the widget be minimized? This attribute must be set at creation time. minimizeable :: Attr w Bool minimizeable = nullAttr "minimizeable" -- | Can the widget be maximized? This attribute must be set at creation time -- and is normally used together with 'resizeable'. maximizeable :: Attr w Bool maximizeable = nullAttr "maximizeable" -- | Can the widget be closed by the user? This attribute must be set at creation time. closeable :: Attr w Bool closeable = nullAttr "closeable" -- | Widgets that can be enabled or disabled. class Able w where -- | Enable, or disable, the widget. enabled :: Attr w Bool {-# DEPRECATED enable "Use enabled instead" #-} -- | Deprecated: use 'enabled' instead enable :: Able w => Attr w Bool enable = enabled -- | Widgets with help text. class Help w where -- | Short help text, normally displayed in the status bar or popup balloon. help :: Attr w String -- | Checkable widgets class Checkable w where -- | Is the widget checkable? checkable :: Attr w Bool -- | Is the widget checked? checked :: Attr w Bool -- | The identity determines the wxWindows ID of a widget. class Identity w where -- | The identity determines the wxWindows ID of a widget. identity :: Attr w Int -- | The style is a bitmask that determines various properties of a widget. class Styled w where -- | The windows style. style :: Attr w Int -- | Dockable widgets. class Dockable w where -- | Is the widget dockable? dockable :: Attr w Bool -- | Widgets that have a tooltip class Tipped w where -- | The tooltip information tooltip :: Attr w String -- | Widgets with a single selection (radio group or listbox) class Selection w where -- | The current selection as a zero-based index. -- Certain widgets return -1 when no item is selected. selection :: Attr w Int -- | Widget with zero or more selections (multi select list boxes) class Selections w where -- | The currently selected items in zero-based indices. selections :: Attr w [Int] -- | Widgets containing certain items (like strings in a listbox) class Items w a | w -> a where -- | Number of items. itemCount :: ReadAttr w Int -- | All the items as a list. This attribute might not be writable for some widgets (like radioboxes) items :: Attr w [a] -- | An item by zero-based index. item :: Int -> Attr w a -- | Delete an item. Only valid for writeable items. itemDelete :: w -> Int -> IO () -- | Delete all items. Only valid for writeable items. itemsDelete :: w -> IO () -- | Append an item. Only valid for writeable items. itemAppend :: w -> a -> IO () items = newAttr "items" getter setter where getter :: w -> IO [a] getter w = do n <- get w itemCount mapM (\i -> get w (item i)) [0..n-1] setter :: w -> [a] -> IO () setter w xs = do itemsDelete w mapM_ (\x -> itemAppend w x) xs itemAppend w x = do xs <- get w items set w [items := xs ++ [x]] itemsDelete w = do count <- get w itemCount sequence_ (replicate count (itemDelete w 0)) {-------------------------------------------------------------------------- Values --------------------------------------------------------------------------} -- | Items with a value. class Valued w where -- | The value of an object. value :: Attr (w a) a {-------------------------------------------------------------------------- Size --------------------------------------------------------------------------} -- | Sized objects (like bitmaps) class Sized w where -- | The size of an object. (is 'outerSize' for 'Dimensions' widgets). size :: Attr w Size {-------------------------------------------------------------------------- HasDefault --------------------------------------------------------------------------} -- | Objects which activate a 'Window' by default keypress class HasDefault w where -- | Define a default item as any type deriving from 'Window'. Great care -- is required when using this option as you will have to cast the item -- to/from Window() using 'objectCast'. -- For the common use case where the window in question is a 'Button', -- please use 'defaultButton' as it is typesafe. unsafeDefaultItem :: Attr w (Window ()) -- | Define the default button for a 'TopLevelWindow'. This is recommended -- for most use cases as the most common default control is a 'Button'. defaultButton :: Attr w (Button ())
thielema/wxhaskell
wx/src/Graphics/UI/WX/Classes.hs
lgpl-2.1
12,404
0
16
2,953
2,072
1,174
898
225
1
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module TutorialD.Interpreter.TransGraphRelationalOperator where import ProjectM36.TransGraphRelationalExpression import ProjectM36.TransactionGraph import TutorialD.Interpreter.Types import qualified ProjectM36.Client as C import TutorialD.Interpreter.Base import TutorialD.Interpreter.RelationalExpr import qualified Data.Text as T instance RelationalMarkerExpr TransactionIdLookup where parseMarkerP = string "@" *> transactionIdLookupP newtype TransGraphRelationalOperator = ShowTransGraphRelation TransGraphRelationalExpr deriving Show transactionIdLookupP :: Parser TransactionIdLookup transactionIdLookupP = (TransactionIdLookup <$> uuidP) <|> (TransactionIdHeadNameLookup <$> identifier <*> many transactionIdHeadBacktrackP) transactionIdHeadBacktrackP :: Parser TransactionIdHeadBacktrack transactionIdHeadBacktrackP = (string "~" *> (TransactionIdHeadParentBacktrack <$> backtrackP)) <|> (string "^" *> (TransactionIdHeadBranchBacktrack <$> backtrackP)) <|> (string "@" *> (TransactionStampHeadBacktrack <$> utcTimeP)) backtrackP :: Parser Int backtrackP = fromIntegral <$> integer <|> pure 1 transGraphRelationalOpP :: Parser TransGraphRelationalOperator transGraphRelationalOpP = showTransGraphRelationalOpP showTransGraphRelationalOpP :: Parser TransGraphRelationalOperator showTransGraphRelationalOpP = do reservedOp ":showtransgraphexpr" ShowTransGraphRelation <$> relExprP evalTransGraphRelationalOp :: C.SessionId -> C.Connection -> TransGraphRelationalOperator -> IO TutorialDOperatorResult evalTransGraphRelationalOp sessionId conn (ShowTransGraphRelation expr) = do res <- C.executeTransGraphRelationalExpr sessionId conn expr case res of Left err -> pure $ DisplayErrorResult $ T.pack (show err) Right rel -> pure $ DisplayRelationResult rel
agentm/project-m36
src/bin/TutorialD/Interpreter/TransGraphRelationalOperator.hs
unlicense
2,097
0
13
426
366
194
172
35
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ImpredicativeTypes #-} {-# OPTIONS_HADDOCK hide #-} module Text.HTML.Scalpel.Internal.Select.Types ( Selector (..) , AttributePredicate (..) , checkPred , AttributeName (..) , matchKey , anyAttrPredicate , TagName (..) , SelectNode (..) , tagSelector , anySelector , textSelector , toSelectNode , SelectSettings (..) , defaultSelectSettings ) where import Data.Char (toLower) import Data.String (IsString, fromString) import qualified Text.HTML.TagSoup as TagSoup import qualified Text.StringLike as TagSoup import qualified Data.Text as T -- | The 'AttributeName' type can be used when creating 'Selector's to specify -- the name of an attribute of a tag. data AttributeName = AnyAttribute | AttributeString String matchKey :: TagSoup.StringLike str => AttributeName -> str -> Bool matchKey (AttributeString s) = ((TagSoup.fromString $ map toLower s) ==) matchKey AnyAttribute = const True instance IsString AttributeName where fromString = AttributeString -- | An 'AttributePredicate' is a method that takes a 'TagSoup.Attribute' and -- returns a 'Bool' indicating if the given attribute matches a predicate. data AttributePredicate = MkAttributePredicate (forall str. TagSoup.StringLike str => [TagSoup.Attribute str] -> Bool) checkPred :: TagSoup.StringLike str => AttributePredicate -> [TagSoup.Attribute str] -> Bool checkPred (MkAttributePredicate p) = p -- | Creates an 'AttributePredicate' from a predicate function of a single -- attribute that matches if any one of the attributes matches the predicate. anyAttrPredicate :: (forall str. TagSoup.StringLike str => (str, str) -> Bool) -> AttributePredicate anyAttrPredicate p = MkAttributePredicate $ any p -- | 'Selector' defines a selection of an HTML DOM tree to be operated on by -- a web scraper. The selection includes the opening tag that matches the -- selection, all of the inner tags, and the corresponding closing tag. newtype Selector = MkSelector [(SelectNode, SelectSettings)] -- | 'SelectSettings' defines additional criteria for a Selector that must be -- satisfied in addition to the SelectNode. This includes criteria that are -- dependent on the context of the current node, for example the depth in -- relation to the previously matched SelectNode. data SelectSettings = SelectSettings { -- | The required depth of the current select node in relation to the -- previously matched SelectNode. selectSettingsDepth :: Maybe Int } defaultSelectSettings :: SelectSettings defaultSelectSettings = SelectSettings { selectSettingsDepth = Nothing } tagSelector :: String -> Selector tagSelector tag = MkSelector [ (toSelectNode (TagString tag) [], defaultSelectSettings) ] -- | A selector which will match any node (including tags and bare text). anySelector :: Selector anySelector = MkSelector [(SelectAny [], defaultSelectSettings)] -- | A selector which will match all text nodes. textSelector :: Selector textSelector = MkSelector [(SelectText, defaultSelectSettings)] instance IsString Selector where fromString = tagSelector data SelectNode = SelectNode !T.Text [AttributePredicate] | SelectAny [AttributePredicate] | SelectText -- | The 'TagName' type is used when creating a 'Selector' to specify the name -- of a tag. data TagName = AnyTag | TagString String instance IsString TagName where fromString = TagString toSelectNode :: TagName -> [AttributePredicate] -> SelectNode toSelectNode AnyTag = SelectAny toSelectNode (TagString str) = SelectNode . TagSoup.fromString $ map toLower str
fimad/scalpel
scalpel-core/src/Text/HTML/Scalpel/Internal/Select/Types.hs
apache-2.0
3,755
0
13
706
635
373
262
66
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} module Brainfuck.Machine ( Machine (..) , blank , cellPtr , jumpStack , pc , pred , program , initProgram , tape ) where import ClassyPrelude import Control.Lens (makeLenses, (&), (.~)) import Brainfuck.Pointer (Pointer) import Brainfuck.Program (Program) import Brainfuck.Tape (Tape) data Machine = Machine { _program :: Program , _pc :: Pointer , _tape :: Tape , _cellPtr :: Pointer , _jumpStack :: [Pointer] } deriving Show makeLenses ''Machine initProgram :: Program -> Machine initProgram pgm = blank & program .~ pgm blank :: Machine blank = Machine { _pc = 0 , _cellPtr = 0 , _jumpStack = [] , _program = empty , _tape = replicate 30000 0 }
expede/brainfucker
src/Brainfuck/Machine.hs
apache-2.0
859
0
9
261
221
137
84
34
1
-- Copyright (c) 2010 - Seweryn Dynerowicz -- 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 -- imitations under the License. module Policy.ShortestPathNeg ( ShortestPathNeg(..) ) where import LaTeX import Algebra.Semiring data ShortestPathNeg = SPN Int | Inf deriving (Eq) instance Show ShortestPathNeg where show (SPN x) = show x show Inf = "∞" instance LaTeX ShortestPathNeg where toLaTeX (SPN x) = "\\mpzc{" ++ show x ++ "}" toLaTeX Inf = "\\infty" instance Semiring (ShortestPathNeg) where add Inf x = x add x Inf = x add (SPN x) (SPN y) = SPN (min x y) zero = Inf mul (SPN x) (SPN y) = SPN (x + y) mul _ _ = Inf unit = (SPN 0)
sdynerow/SemiringsLibrary
Policy/ShortestPathNeg.hs
apache-2.0
1,136
0
8
227
250
136
114
20
0
-- Derived from the llvm in haskell tutorial. -------------------------------------------------------------------- -- | -- Module : Lexer -- Copyright : (c) Stephen Diehl 2013 -- License : MIT -- Maintainer: stephen.m.diehl@gmail.com -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------- module Lexer where import Text.Parsec.String (Parser) import Text.Parsec.Language (emptyDef) import Text.Parsec.Prim (many) import qualified Text.Parsec.Token as Tok lexer :: Tok.TokenParser () lexer = Tok.makeTokenParser style where ops = ["+","*","-","/",";","=",",","<",">","|",":"] names = ["def","extern","if","then","else","in","for" ,"binary", "unary", "var" ] style = emptyDef { Tok.commentLine = "#" , Tok.reservedOpNames = ops , Tok.reservedNames = names } integer = Tok.integer lexer float = Tok.float lexer parens = Tok.parens lexer commaSep = Tok.commaSep lexer semiSep = Tok.semiSep lexer identifier = Tok.identifier lexer whitespace = Tok.whiteSpace lexer reserved = Tok.reserved lexer reservedOp = Tok.reservedOp lexer operator :: Parser String operator = do c <- Tok.opStart emptyDef cs <- many $ Tok.opLetter emptyDef return (c:cs)
piotrm0/planar
Lexer.hs
artistic-2.0
1,347
0
10
279
329
191
138
28
1
module Main where import System.Console.CmdArgs import HEP.Parser.SLHAParser.ProgType import HEP.Parser.SLHAParser.Command main :: IO () main = do putStrLn "SLHAParser" param <- cmdArgs mode commandLineProcess param
wavewave/SLHAParser
exe/slhaparser.hs
bsd-2-clause
227
0
8
35
61
33
28
9
1
{-| Converts a configuration state into a Ssconf map. As TemplateHaskell require that splices be defined in a separate module, we combine all the TemplateHaskell functionality that HTools needs in this module (except the one for unittests). -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.WConfd.Ssconf ( SSConf(..) , emptySSConf , mkSSConf ) where import Control.Arrow ((&&&)) import Data.Foldable (Foldable(..), toList) import Data.List (partition) import Data.Maybe (mapMaybe) import qualified Data.Map as M import Ganeti.BasicTypes import Ganeti.Config import Ganeti.Constants import Ganeti.JSON import Ganeti.Objects import Ganeti.Ssconf import Ganeti.Utils import Ganeti.Types mkSSConf :: ConfigData -> SSConf mkSSConf cdata = SSConf $ M.fromList [ (SSClusterName, return $ clusterClusterName cluster) , (SSClusterTags, toList $ tagsOf cluster) , (SSFileStorageDir, return $ clusterFileStorageDir cluster) , (SSSharedFileStorageDir, return $ clusterSharedFileStorageDir cluster) , (SSGlusterStorageDir, return $ clusterGlusterStorageDir cluster) , (SSMasterCandidates, mapLines nodeName mcs) , (SSMasterCandidatesIps, mapLines nodePrimaryIp mcs) , (SSMasterCandidatesCerts, mapLines eqPair . toPairs . clusterCandidateCerts $ cluster) , (SSMasterIp, return $ clusterMasterIp cluster) , (SSMasterNetdev, return $ clusterMasterNetdev cluster) , (SSMasterNetmask, return . show $ clusterMasterNetmask cluster) , (SSMasterNode, return . genericResult (const "NO MASTER") nodeName . getNode cdata $ clusterMasterNode cluster) , (SSNodeList, mapLines nodeName nodes) , (SSNodePrimaryIps, mapLines (spcPair . (nodeName &&& nodePrimaryIp)) nodes ) , (SSNodeSecondaryIps, mapLines (spcPair . (nodeName &&& nodeSecondaryIp)) nodes ) , (SSNodeVmCapable, mapLines (eqPair . (nodeName &&& show . nodeVmCapable)) nodes) , (SSOfflineNodes, mapLines nodeName offline ) , (SSOnlineNodes, mapLines nodeName online ) , (SSPrimaryIpFamily, return . show . ipFamilyToRaw . clusterPrimaryIpFamily $ cluster) , (SSInstanceList, niceSort . mapMaybe instName . toList . configInstances $ cdata) , (SSReleaseVersion, return releaseVersion) , (SSHypervisorList, mapLines hypervisorToRaw . clusterEnabledHypervisors $ cluster) , (SSMaintainNodeHealth, return . show . clusterMaintainNodeHealth $ cluster) , (SSUidPool, mapLines formatUidRange . clusterUidPool $ cluster) , (SSNodegroups, mapLines (spcPair . (groupUuid &&& groupName)) nodeGroups) , (SSNetworks, mapLines (spcPair . (networkUuid &&& (fromNonEmpty . networkName))) . configNetworks $ cdata) , (SSEnabledUserShutdown, return . show . clusterEnabledUserShutdown $ cluster) ] where mapLines :: (Foldable f) => (a -> String) -> f a -> [String] mapLines f = map f . toList eqPair (x, y) = x ++ "=" ++ y spcPair (x, y) = x ++ " " ++ y toPairs = M.assocs . fromContainer cluster = configCluster cdata mcs = getMasterOrCandidates cdata nodes = niceSortKey nodeName . toList $ configNodes cdata (offline, online) = partition nodeOffline nodes nodeGroups = niceSortKey groupName . toList $ configNodegroups cdata
dimara/ganeti
src/Ganeti/WConfd/Ssconf.hs
bsd-2-clause
4,874
0
17
1,151
893
500
393
-1
-1
module Main where import System.Posix.Signals (installHandler, Handler(Catch), sigINT, sigTERM) import Control.Concurrent.MVar (modifyMVar_, newMVar, withMVar, MVar) import System.ZMQ handler :: MVar Int -> IO () handler s_interrupted = modifyMVar_ s_interrupted (return . (+1)) main :: IO () main = withContext 1 $ \context -> do withSocket context Rep $ \socket -> do bind socket "tcp://*:5555" s_interrupted <- newMVar 0 installHandler sigINT (Catch $ handler s_interrupted) Nothing installHandler sigTERM (Catch $ handler s_interrupted) Nothing recvFunction s_interrupted socket recvFunction :: (Ord a, Num a) => MVar a -> Socket b -> IO () recvFunction mi sock = do receive sock [] withMVar mi (\val -> if val > 0 then putStrLn "W: Interrupt Received. Killing Server" else recvFunction mi sock)
krattai/noo-ebs
docs/zeroMQ-guide2/examples/Haskell/interrupt.hs
bsd-2-clause
868
0
16
185
299
152
147
20
2
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wwarn #-} module Parser ( parseExpr , parseModule ) where import Data.Maybe (fromMaybe) import qualified Data.Text.Lazy as L import Data.Time (parseTime) import Data.Time.Locale.Compat (defaultTimeLocale) import Text.Parsec import qualified Text.Parsec.Expr as EX import Text.Parsec.Text.Lazy (Parser) import qualified Text.Parsec.Token as Tok import Error import LitCust import Lexer import Syntax import Type getMyPosition :: Parser Pos getMyPosition = fmap fromSourcePos getPosition addLocation :: Parser (Expr' Pos) -> Parser Expr addLocation ex = do (Pos start _, e, Pos _ end) <- located ex return (at start end e) where at s e = Expr (Pos s e) located :: Parser a -> Parser (Pos, a, Pos) located par = do start <- getMyPosition value <- par end <- getMyPosition return (start, value, end) natOrFloat :: Parser (Either Integer Double) natOrFloat = Tok.naturalOrFloat lexer data Sign = Positive | Negative sign :: Parser Sign sign = (char '-' >> return Negative) <|> (char '+' >> return Positive) <|> return Positive number :: Parser Expr number = addLocation $ do s <- sign num <- natOrFloat return . Lit . LNum $ either (apSign s . fromIntegral) (apSign s) num where apSign Positive = id apSign Negative = negate stringLit :: Parser String stringLit = Tok.stringLiteral lexer commaSep :: Parser a -> Parser [a] commaSep = Tok.commaSep lexer text :: Parser Expr text = addLocation $ do x <- stringLit return (Lit (LText x)) list :: Parser Expr list = addLocation $ do _ <- char '[' xs <- commaSep expr _ <- char ']' return $ List xs variable :: Parser Expr variable = addLocation $ do x <- identifier return (Var x) isoDate :: Parser Expr isoDate = addLocation $ do reserved "ISODate" t <- stringLit parDate "%FT%T%Z" t <|> parDate "%F" t archDate :: Parser Expr archDate = addLocation $ do reserved "ArDate" t <- stringLit parDate "%-m/%-d/%Y %-H:%-M:%-S %p" t <|> parDate "%-m/%-d/%Y %-H:%-M %p" t <|> parDate "%-m/%-d/%Y %-H:%-M:%-S" t <|> parDate "%-m/%-d/%Y %-H:%-M" t <|> parDate "%-m/%-d/%Y" t parDate :: String -> String -> Parser (Expr' Pos) parDate x d = case parseTime defaultTimeLocale x d of Just y -> return (Lit (LDate y)) Nothing -> unexpected "date format" date :: Parser Expr date = isoDate <|> archDate bool :: Parser Expr bool = addLocation $ (reserved "True" >> return (Lit (LBool True))) <|> (reserved "False" >> return (Lit (LBool False))) timeUnit :: Parser Expr timeUnit = addLocation $ (reserved "Day" >> return (Lit (LTimUn Day))) <|> (reserved "Hour" >> return (Lit (LTimUn Hour))) <|> (reserved "Minute" >> return (Lit (LTimUn Min))) weekStart :: Parser Expr weekStart = addLocation $ (reserved "Sunday" >> return (Lit (LWkSt Sunday))) <|> (reserved "Monday" >> return (Lit (LWkSt Monday))) foldEx :: (a -> Expr -> Expr' Pos) -> Expr -> [a] -> Expr foldEx _ z [] = z foldEx f z@(Expr p _) (x:xs) = Expr p $ f x (foldEx f z xs) lambda :: Parser Expr lambda = do reservedOp "\\" args <- many identifier reservedOp "->" body <- expr return $ foldEx Lam body args letin :: Parser Expr letin = addLocation $ do reserved "let" x <- identifier reservedOp "=" e1 <- expr reserved "in" e2 <- expr return (Let x e1 e2) field :: Parser Expr field = addLocation $ do reserved "field" fld <- stringLit reservedOp ":" <?> "a type declaration" typ <- fieldType e <- optionMaybe $ do reserved "as" expr return $ Field fld e typ fieldType :: Parser Type fieldType = (reserved "Bool" >> return typeBool) <|> (reserved "Date" >> return typeDate) <|> (reserved "Num" >> return typeNum) <|> (reserved "Text" >> return typeText) <|> (reserved "List" >> fmap typeList fieldType) ifthen :: Parser Expr ifthen = addLocation $ do reserved "if" cond <- aexp reservedOp "then" tr <- aexp reserved "else" fl <- aexp return (If cond tr fl) aexp :: Parser Expr aexp = parens expr <|> date <|> bool <|> timeUnit <|> weekStart <|> number <|> text <|> ifthen <|> field <|> letin <|> lambda <|> list <|> variable term :: Parser Expr term = EX.buildExpressionParser opTable aexp infixOp :: String -> (a -> a -> a) -> EX.Assoc -> Op a infixOp x f = EX.Infix (reservedOp x >> return f) opTable :: Operators Expr opTable = [ [ infixOp "^" (exOp Exp) EX.AssocLeft ] , [ infixOp "*" (exOp Mul) EX.AssocLeft , infixOp "/" (exOp Div) EX.AssocLeft ] , [ infixOp "+" (exOp Add) EX.AssocLeft , infixOp "-" (exOp Sub) EX.AssocLeft ] , [ infixOp "&" (exOp Cat) EX.AssocLeft ] , [ infixOp "==" (exOp Eql) EX.AssocLeft , infixOp ">" (exOp Gt) EX.AssocLeft , infixOp ">=" (exOp Gte) EX.AssocLeft , infixOp "<" (exOp Lt) EX.AssocLeft , infixOp "<=" (exOp Lte) EX.AssocLeft , infixOp "<>" (exOp Neq) EX.AssocLeft ] , [ infixOp "&&" (exOp And) EX.AssocLeft , infixOp "||" (exOp Or) EX.AssocLeft ] ] where exOp :: Binop -> Expr -> Expr -> Expr exOp o a@(Expr (Pos s _) _) b@(Expr (Pos _ e) _) = Expr (Pos s e) (Op o a b) expr :: Parser Expr expr = do es <- many1 term return $ fold1Ex App es where fold1Ex :: (Expr -> Expr -> Expr' Pos) -> [Expr] -> Expr fold1Ex f xs = fromMaybe (error "fold1Ex: empty structure") (foldl mf Nothing xs) where mf m y@(Expr (Pos _ e) _) = Just $ case m of Nothing -> y Just x@(Expr (Pos s _) _) -> Expr (Pos s e) (f x y) type Binding = (String, Expr) letdecl :: Parser Binding letdecl = do reserved "let" name <- identifier <?> "name" args <- many identifier reservedOp "=" body <- expr <?> "an expression" return (name, foldEx Lam body args) val :: Parser Binding val = do ex <- expr return ("it", ex) decl :: Parser Binding decl = letdecl <|> val top :: Parser Binding top = do x <- decl optional semi return x modl :: Parser [Binding] modl = many top parseExpr :: L.Text -> Either ParseError Expr parseExpr input = parse (contents expr) "<stdin>" input parseModule :: FilePath -> L.Text -> Either ParseError [(String, Expr)] parseModule fname input = parse (contents modl) fname input
ahodgen/archer-calc
src/Parser.hs
bsd-2-clause
6,772
0
18
1,950
2,564
1,262
1,302
213
2
module ExplosiveSum where import Data.Maybe import Data.Map.Lazy as Map hiding (foldl) type MyMap = Map (Int, Int) Int lkup :: Int -> Int -> MyMap -> Maybe Int lkup n m mp | m == 0 = Just 0 | n == 0 = Just 1 | n < 0 = Just 0 | otherwise = Map.lookup (n, m) mp buildMap :: Int -> Int -> MyMap -> MyMap buildMap n m mp = case lkup n m mp of Just v -> mp Nothing -> let (n1, m1) = (n - m, m) (n2, m2) = (n, m - 1) mp2 = buildMap n2 m2 $ buildMap n1 m1 mp r1 = fromJust $ lkup n1 m1 mp2 r2 = fromJust $ lkup n2 m2 mp2 in Map.insert (n, m) (r1 + r2) mp2 esum :: Int -> Int esum n | n < 0 = 0 | n == 0 = 1 | n == 1 = 1 | otherwise = let mp = buildMap n n Map.empty in mp ! (n, n) explosiveSum :: Integer -> Integer explosiveSum = fromIntegral . esum . fromIntegral
lisphacker/codewars
ExplosiveSum.hs
bsd-2-clause
1,083
0
13
511
433
221
212
28
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QDirModel_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QDirModel_h where import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QDirModel ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDirModel_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QDirModel_unSetUserMethod" qtc_QDirModel_unSetUserMethod :: Ptr (TQDirModel a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QDirModelSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDirModel_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QDirModel ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDirModel_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QDirModelSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDirModel_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QDirModel ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDirModel_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QDirModelSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDirModel_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QDirModel ()) (QDirModel x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDirModel setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDirModel_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDirModel_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setUserMethod" qtc_QDirModel_setUserMethod :: Ptr (TQDirModel a) -> CInt -> Ptr (Ptr (TQDirModel x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QDirModel :: (Ptr (TQDirModel x0) -> IO ()) -> IO (FunPtr (Ptr (TQDirModel x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QDirModel_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDirModelSc a) (QDirModel x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDirModel setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDirModel_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDirModel_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QDirModel ()) (QDirModel x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDirModel setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDirModel_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDirModel_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setUserMethodVariant" qtc_QDirModel_setUserMethodVariant :: Ptr (TQDirModel a) -> CInt -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QDirModel :: (Ptr (TQDirModel x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QDirModel_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDirModelSc a) (QDirModel x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDirModel setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDirModel_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDirModel_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QDirModel ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDirModel_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QDirModel_unSetHandler" qtc_QDirModel_unSetHandler :: Ptr (TQDirModel a) -> CWString -> IO (CBool) instance QunSetHandler (QDirModelSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDirModel_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QDirModel ()) (QDirModel x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler1" qtc_QDirModel_setHandler1 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel1 :: (Ptr (TQDirModel x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQDirModel x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDirModel1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler2" qtc_QDirModel_setHandler2 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel2 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CInt)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDirModel2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QcolumnCount_h (QDirModel ()) (()) where columnCount_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_columnCount cobj_x0 foreign import ccall "qtc_QDirModel_columnCount" qtc_QDirModel_columnCount :: Ptr (TQDirModel a) -> IO CInt instance QcolumnCount_h (QDirModelSc a) (()) where columnCount_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_columnCount cobj_x0 instance QcolumnCount_h (QDirModel ()) ((QModelIndex t1)) where columnCount_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_columnCount1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_columnCount1" qtc_QDirModel_columnCount1 :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO CInt instance QcolumnCount_h (QDirModelSc a) ((QModelIndex t1)) where columnCount_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_columnCount1 cobj_x0 cobj_x1 instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler3" qtc_QDirModel_setHandler3 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel3 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> Int -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> CInt -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let x2int = fromCInt x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj x2int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler4" qtc_QDirModel_setHandler4 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> CInt -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel4 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> CInt -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> CInt -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> Int -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> CInt -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let x2int = fromCInt x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj x2int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qqdata_h (QDirModel ()) ((QModelIndex t1)) where qdata_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_data cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_data" qtc_QDirModel_data :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQVariant ())) instance Qqdata_h (QDirModelSc a) ((QModelIndex t1)) where qdata_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_data cobj_x0 cobj_x1 instance Qqdata_h (QDirModel ()) ((QModelIndex t1, Int)) where qdata_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_data1 cobj_x0 cobj_x1 (toCInt x2) foreign import ccall "qtc_QDirModel_data1" qtc_QDirModel_data1 :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> CInt -> IO (Ptr (TQVariant ())) instance Qqdata_h (QDirModelSc a) ((QModelIndex t1, Int)) where qdata_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_data1 cobj_x0 cobj_x1 (toCInt x2) instance QsetHandler (QDirModel ()) (QDirModel x0 -> QObject t1 -> DropAction -> Int -> Int -> QModelIndex t5 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> CLong -> CInt -> CInt -> Ptr (TQModelIndex t5) -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 x4 x5 = do x0obj <- qDirModelFromPtr x0 x1obj <- qObjectFromPtr x1 let x2enum = qEnum_fromInt $ fromCLong x2 let x3int = fromCInt x3 let x4int = fromCInt x4 x5obj <- objectFromPtr_nf x5 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum x3int x4int x5obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler5" qtc_QDirModel_setHandler5 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> CLong -> CInt -> CInt -> Ptr (TQModelIndex t5) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel5 :: (Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> CLong -> CInt -> CInt -> Ptr (TQModelIndex t5) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> CLong -> CInt -> CInt -> Ptr (TQModelIndex t5) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QObject t1 -> DropAction -> Int -> Int -> QModelIndex t5 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> CLong -> CInt -> CInt -> Ptr (TQModelIndex t5) -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 x4 x5 = do x0obj <- qDirModelFromPtr x0 x1obj <- qObjectFromPtr x1 let x2enum = qEnum_fromInt $ fromCLong x2 let x3int = fromCInt x3 let x4int = fromCInt x4 x5obj <- objectFromPtr_nf x5 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum x3int x4int x5obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QdropMimeData_h (QDirModel ()) ((QMimeData t1, DropAction, Int, Int, QModelIndex t5)) where dropMimeData_h x0 (x1, x2, x3, x4, x5) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QDirModel_dropMimeData cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCInt x3) (toCInt x4) cobj_x5 foreign import ccall "qtc_QDirModel_dropMimeData" qtc_QDirModel_dropMimeData :: Ptr (TQDirModel a) -> Ptr (TQMimeData t1) -> CLong -> CInt -> CInt -> Ptr (TQModelIndex t5) -> IO CBool instance QdropMimeData_h (QDirModelSc a) ((QMimeData t1, DropAction, Int, Int, QModelIndex t5)) where dropMimeData_h x0 (x1, x2, x3, x4, x5) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x5 $ \cobj_x5 -> qtc_QDirModel_dropMimeData cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCInt x3) (toCInt x4) cobj_x5 instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> IO (ItemFlags)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CLong) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj x1obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler6" qtc_QDirModel_setHandler6 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel6 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CLong)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CLong))) foreign import ccall "wrapper" wrapSetHandler_QDirModel6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> IO (ItemFlags)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CLong) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj x1obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qflags_h (QDirModel ()) ((QModelIndex t1)) where flags_h x0 (x1) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_flags cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_flags" qtc_QDirModel_flags :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO CLong instance Qflags_h (QDirModelSc a) ((QModelIndex t1)) where flags_h x0 (x1) = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_flags cobj_x0 cobj_x1 instance QsetHandler (QDirModel ()) (QDirModel x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler7" qtc_QDirModel_setHandler7 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel7 :: (Ptr (TQDirModel x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler8" qtc_QDirModel_setHandler8 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel8 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QhasChildren_h (QDirModel ()) (()) where hasChildren_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_hasChildren cobj_x0 foreign import ccall "qtc_QDirModel_hasChildren" qtc_QDirModel_hasChildren :: Ptr (TQDirModel a) -> IO CBool instance QhasChildren_h (QDirModelSc a) (()) where hasChildren_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_hasChildren cobj_x0 instance QhasChildren_h (QDirModel ()) ((QModelIndex t1)) where hasChildren_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_hasChildren1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_hasChildren1" qtc_QDirModel_hasChildren1 :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO CBool instance QhasChildren_h (QDirModelSc a) ((QModelIndex t1)) where hasChildren_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_hasChildren1 cobj_x0 cobj_x1 instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> QtOrientation -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler9" qtc_QDirModel_setHandler9 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel9 :: (Ptr (TQDirModel x0) -> CInt -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> QtOrientation -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> QtOrientation -> Int -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> CInt -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 let x3int = fromCInt x3 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2enum x3int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler10" qtc_QDirModel_setHandler10 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CLong -> CInt -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel10 :: (Ptr (TQDirModel x0) -> CInt -> CLong -> CInt -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CLong -> CInt -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> QtOrientation -> Int -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> CInt -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 let x3int = fromCInt x3 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2enum x3int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheaderData_h (QDirModel ()) ((Int, QtOrientation)) where headerData_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_headerData cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QDirModel_headerData" qtc_QDirModel_headerData :: Ptr (TQDirModel a) -> CInt -> CLong -> IO (Ptr (TQVariant ())) instance QheaderData_h (QDirModelSc a) ((Int, QtOrientation)) where headerData_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_headerData cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) instance QheaderData_h (QDirModel ()) ((Int, QtOrientation, Int)) where headerData_h x0 (x1, x2, x3) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_headerData1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) (toCInt x3) foreign import ccall "qtc_QDirModel_headerData1" qtc_QDirModel_headerData1 :: Ptr (TQDirModel a) -> CInt -> CLong -> CInt -> IO (Ptr (TQVariant ())) instance QheaderData_h (QDirModelSc a) ((Int, QtOrientation, Int)) where headerData_h x0 (x1, x2, x3) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_headerData1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) (toCInt x3) instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> Int -> IO (QModelIndex t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> IO (Ptr (TQModelIndex t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler11" qtc_QDirModel_setHandler11 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CInt -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel11 :: (Ptr (TQDirModel x0) -> CInt -> CInt -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CInt -> IO (Ptr (TQModelIndex t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> Int -> IO (QModelIndex t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> IO (Ptr (TQModelIndex t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> Int -> QModelIndex t3 -> IO (QModelIndex t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (Ptr (TQModelIndex t0)) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 x3obj <- objectFromPtr_nf x3 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2int x3obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler12" qtc_QDirModel_setHandler12 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel12 :: (Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (Ptr (TQModelIndex t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> Int -> QModelIndex t3 -> IO (QModelIndex t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (Ptr (TQModelIndex t0)) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 x3obj <- objectFromPtr_nf x3 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2int x3obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qindex_h (QDirModel ()) ((Int, Int)) where index_h x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_index2 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDirModel_index2" qtc_QDirModel_index2 :: Ptr (TQDirModel a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ())) instance Qindex_h (QDirModelSc a) ((Int, Int)) where index_h x0 (x1, x2) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_index2 cobj_x0 (toCInt x1) (toCInt x2) instance Qindex_h (QDirModel ()) ((Int, Int, QModelIndex t3)) where index_h x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_index3 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QDirModel_index3" qtc_QDirModel_index3 :: Ptr (TQDirModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (Ptr (TQModelIndex ())) instance Qindex_h (QDirModelSc a) ((Int, Int, QModelIndex t3)) where index_h x0 (x1, x2, x3) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_index3 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> IO (QModelIndex t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex t0)) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler13" qtc_QDirModel_setHandler13 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel13 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> IO (QModelIndex t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex t0)) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qparent_h (QDirModel ()) ((QModelIndex t1)) where parent_h x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_parent1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_parent1" qtc_QDirModel_parent1 :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex ())) instance Qparent_h (QDirModelSc a) ((QModelIndex t1)) where parent_h x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_parent1 cobj_x0 cobj_x1 instance QrowCount_h (QDirModel ()) (()) where rowCount_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_rowCount cobj_x0 foreign import ccall "qtc_QDirModel_rowCount" qtc_QDirModel_rowCount :: Ptr (TQDirModel a) -> IO CInt instance QrowCount_h (QDirModelSc a) (()) where rowCount_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_rowCount cobj_x0 instance QrowCount_h (QDirModel ()) ((QModelIndex t1)) where rowCount_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_rowCount1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_rowCount1" qtc_QDirModel_rowCount1 :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO CInt instance QrowCount_h (QDirModelSc a) ((QModelIndex t1)) where rowCount_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_rowCount1 cobj_x0 cobj_x1 instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> QVariant t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler14" qtc_QDirModel_setHandler14 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel14 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> QVariant t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> QVariant t2 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 let x3int = fromCInt x3 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj x3int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler15" qtc_QDirModel_setHandler15 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> CInt -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel15 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> CInt -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> CInt -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> QVariant t2 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 let x3int = fromCInt x3 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj x3int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetData_h (QDirModel ()) ((QModelIndex t1, QVariant t2)) (IO (Bool)) where setData_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDirModel_setData cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDirModel_setData" qtc_QDirModel_setData :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> IO CBool instance QsetData_h (QDirModelSc a) ((QModelIndex t1, QVariant t2)) (IO (Bool)) where setData_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDirModel_setData cobj_x0 cobj_x1 cobj_x2 instance QsetData_h (QDirModel ()) ((QModelIndex t1, QVariant t2, Int)) (IO (Bool)) where setData_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDirModel_setData1 cobj_x0 cobj_x1 cobj_x2 (toCInt x3) foreign import ccall "qtc_QDirModel_setData1" qtc_QDirModel_setData1 :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> Ptr (TQVariant t2) -> CInt -> IO CBool instance QsetData_h (QDirModelSc a) ((QModelIndex t1, QVariant t2, Int)) (IO (Bool)) where setData_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDirModel_setData1 cobj_x0 cobj_x1 cobj_x2 (toCInt x3) instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel16 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel16_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler16" qtc_QDirModel_setHandler16 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel16 :: (Ptr (TQDirModel x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDirModel16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel16 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel16_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> SortOrder -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel17 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel17_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> IO () setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 if (objectIsNull x0obj) then return () else _handler x0obj x1int x2enum setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler17" qtc_QDirModel_setHandler17 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel17 :: (Ptr (TQDirModel x0) -> CInt -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CLong -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDirModel17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> SortOrder -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel17 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel17_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> IO () setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 if (objectIsNull x0obj) then return () else _handler x0obj x1int x2enum setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qsort_h (QDirModel ()) ((Int)) where sort_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_sort cobj_x0 (toCInt x1) foreign import ccall "qtc_QDirModel_sort" qtc_QDirModel_sort :: Ptr (TQDirModel a) -> CInt -> IO () instance Qsort_h (QDirModelSc a) ((Int)) where sort_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_sort cobj_x0 (toCInt x1) instance Qsort_h (QDirModel ()) ((Int, SortOrder)) where sort_h x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_sort1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QDirModel_sort1" qtc_QDirModel_sort1 :: Ptr (TQDirModel a) -> CInt -> CLong -> IO () instance Qsort_h (QDirModelSc a) ((Int, SortOrder)) where sort_h x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_sort1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) instance QsetHandler (QDirModel ()) (QDirModel x0 -> IO (DropActions)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel18 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel18_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler18" qtc_QDirModel_setHandler18 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> IO (CLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel18 :: (Ptr (TQDirModel x0) -> IO (CLong)) -> IO (FunPtr (Ptr (TQDirModel x0) -> IO (CLong))) foreign import ccall "wrapper" wrapSetHandler_QDirModel18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> IO (DropActions)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel18 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel18_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsupportedDropActions_h (QDirModel ()) (()) where supportedDropActions_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_supportedDropActions cobj_x0 foreign import ccall "qtc_QDirModel_supportedDropActions" qtc_QDirModel_supportedDropActions :: Ptr (TQDirModel a) -> IO CLong instance QsupportedDropActions_h (QDirModelSc a) (()) where supportedDropActions_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_supportedDropActions cobj_x0 instance Qbuddy_h (QDirModel ()) ((QModelIndex t1)) where buddy_h x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_buddy cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_buddy" qtc_QDirModel_buddy :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQModelIndex ())) instance Qbuddy_h (QDirModelSc a) ((QModelIndex t1)) where buddy_h x0 (x1) = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_buddy cobj_x0 cobj_x1 instance QcanFetchMore_h (QDirModel ()) ((QModelIndex t1)) where canFetchMore_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_canFetchMore cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_canFetchMore" qtc_QDirModel_canFetchMore :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO CBool instance QcanFetchMore_h (QDirModelSc a) ((QModelIndex t1)) where canFetchMore_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_canFetchMore cobj_x0 cobj_x1 instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel19 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel19_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler19" qtc_QDirModel_setHandler19 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel19 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO ()) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDirModel19_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel19 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel19_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QfetchMore_h (QDirModel ()) ((QModelIndex t1)) where fetchMore_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_fetchMore cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_fetchMore" qtc_QDirModel_fetchMore :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO () instance QfetchMore_h (QDirModelSc a) ((QModelIndex t1)) where fetchMore_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_fetchMore cobj_x0 cobj_x1 instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel20 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel20_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler20" qtc_QDirModel_setHandler20 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CInt -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel20 :: (Ptr (TQDirModel x0) -> CInt -> CInt -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CInt -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel20_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel20 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel20_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> Int -> QModelIndex t3 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel21 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel21_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 x3obj <- objectFromPtr_nf x3 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2int x3obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler21" qtc_QDirModel_setHandler21 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel21 :: (Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel21_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> Int -> QModelIndex t3 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel21 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel21_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2int = fromCInt x2 x3obj <- objectFromPtr_nf x3 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2int x3obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QinsertColumns_h (QDirModel ()) ((Int, Int)) where insertColumns_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_insertColumns cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDirModel_insertColumns" qtc_QDirModel_insertColumns :: Ptr (TQDirModel a) -> CInt -> CInt -> IO CBool instance QinsertColumns_h (QDirModelSc a) ((Int, Int)) where insertColumns_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_insertColumns cobj_x0 (toCInt x1) (toCInt x2) instance QinsertColumns_h (QDirModel ()) ((Int, Int, QModelIndex t3)) where insertColumns_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_insertColumns1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QDirModel_insertColumns1" qtc_QDirModel_insertColumns1 :: Ptr (TQDirModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QinsertColumns_h (QDirModelSc a) ((Int, Int, QModelIndex t3)) where insertColumns_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_insertColumns1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QinsertRows_h (QDirModel ()) ((Int, Int)) where insertRows_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_insertRows cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDirModel_insertRows" qtc_QDirModel_insertRows :: Ptr (TQDirModel a) -> CInt -> CInt -> IO CBool instance QinsertRows_h (QDirModelSc a) ((Int, Int)) where insertRows_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_insertRows cobj_x0 (toCInt x1) (toCInt x2) instance QinsertRows_h (QDirModel ()) ((Int, Int, QModelIndex t3)) where insertRows_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_insertRows1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QDirModel_insertRows1" qtc_QDirModel_insertRows1 :: Ptr (TQDirModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QinsertRows_h (QDirModelSc a) ((Int, Int, QModelIndex t3)) where insertRows_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_insertRows1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QremoveColumns_h (QDirModel ()) ((Int, Int)) where removeColumns_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_removeColumns cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDirModel_removeColumns" qtc_QDirModel_removeColumns :: Ptr (TQDirModel a) -> CInt -> CInt -> IO CBool instance QremoveColumns_h (QDirModelSc a) ((Int, Int)) where removeColumns_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_removeColumns cobj_x0 (toCInt x1) (toCInt x2) instance QremoveColumns_h (QDirModel ()) ((Int, Int, QModelIndex t3)) where removeColumns_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_removeColumns1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QDirModel_removeColumns1" qtc_QDirModel_removeColumns1 :: Ptr (TQDirModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QremoveColumns_h (QDirModelSc a) ((Int, Int, QModelIndex t3)) where removeColumns_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_removeColumns1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QremoveRows_h (QDirModel ()) ((Int, Int)) where removeRows_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_removeRows cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDirModel_removeRows" qtc_QDirModel_removeRows :: Ptr (TQDirModel a) -> CInt -> CInt -> IO CBool instance QremoveRows_h (QDirModelSc a) ((Int, Int)) where removeRows_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_removeRows cobj_x0 (toCInt x1) (toCInt x2) instance QremoveRows_h (QDirModel ()) ((Int, Int, QModelIndex t3)) where removeRows_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_removeRows1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QDirModel_removeRows1" qtc_QDirModel_removeRows1 :: Ptr (TQDirModel a) -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO CBool instance QremoveRows_h (QDirModelSc a) ((Int, Int, QModelIndex t3)) where removeRows_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_removeRows1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 instance QsetHandler (QDirModel ()) (QDirModel x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel22 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel22_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler22 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO () setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler22" qtc_QDirModel_setHandler22 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel22 :: (Ptr (TQDirModel x0) -> IO ()) -> IO (FunPtr (Ptr (TQDirModel x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDirModel22_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel22 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel22_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler22 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> IO () setHandlerWrapper x0 = do x0obj <- qDirModelFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qrevert_h (QDirModel ()) (()) where revert_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_revert cobj_x0 foreign import ccall "qtc_QDirModel_revert" qtc_QDirModel_revert :: Ptr (TQDirModel a) -> IO () instance Qrevert_h (QDirModelSc a) (()) where revert_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_revert cobj_x0 instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> QtOrientation -> QVariant t3 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel23 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel23_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler23 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 x3obj <- objectFromPtr_nf x3 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2enum x3obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler23" qtc_QDirModel_setHandler23 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel23 :: (Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel23_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> QtOrientation -> QVariant t3 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel23 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel23_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler23 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 x3obj <- objectFromPtr_nf x3 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2enum x3obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QDirModel ()) (QDirModel x0 -> Int -> QtOrientation -> QVariant t3 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel24 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel24_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler24 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 x4 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 x3obj <- objectFromPtr_nf x3 let x4int = fromCInt x4 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2enum x3obj x4int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler24" qtc_QDirModel_setHandler24 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> CInt -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel24 :: (Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> CInt -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> CInt -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel24_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> Int -> QtOrientation -> QVariant t3 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel24 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel24_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler24 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> CInt -> CLong -> Ptr (TQVariant t3) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 x2 x3 x4 = do x0obj <- qDirModelFromPtr x0 let x1int = fromCInt x1 let x2enum = qEnum_fromInt $ fromCLong x2 x3obj <- objectFromPtr_nf x3 let x4int = fromCInt x4 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int x2enum x3obj x4int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHeaderData_h (QDirModel ()) ((Int, QtOrientation, QVariant t3)) where setHeaderData_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_setHeaderData cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 foreign import ccall "qtc_QDirModel_setHeaderData" qtc_QDirModel_setHeaderData :: Ptr (TQDirModel a) -> CInt -> CLong -> Ptr (TQVariant t3) -> IO CBool instance QsetHeaderData_h (QDirModelSc a) ((Int, QtOrientation, QVariant t3)) where setHeaderData_h x0 (x1, x2, x3) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_setHeaderData cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 instance QsetHeaderData_h (QDirModel ()) ((Int, QtOrientation, QVariant t3, Int)) where setHeaderData_h x0 (x1, x2, x3, x4) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_setHeaderData1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 (toCInt x4) foreign import ccall "qtc_QDirModel_setHeaderData1" qtc_QDirModel_setHeaderData1 :: Ptr (TQDirModel a) -> CInt -> CLong -> Ptr (TQVariant t3) -> CInt -> IO CBool instance QsetHeaderData_h (QDirModelSc a) ((Int, QtOrientation, QVariant t3, Int)) where setHeaderData_h x0 (x1, x2, x3, x4) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QDirModel_setHeaderData1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) cobj_x3 (toCInt x4) instance QsetHandler (QDirModel ()) (QDirModel x0 -> QModelIndex t1 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel25 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel25_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler25 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler25" qtc_QDirModel_setHandler25 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel25 :: (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QDirModel25_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QModelIndex t1 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel25 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel25_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler25 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qqspan_h (QDirModel ()) ((QModelIndex t1)) where qspan_h x0 (x1) = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_span cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_span" qtc_QDirModel_span :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQSize ())) instance Qqspan_h (QDirModelSc a) ((QModelIndex t1)) where qspan_h x0 (x1) = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_span cobj_x0 cobj_x1 instance Qspan_h (QDirModel ()) ((QModelIndex t1)) where span_h x0 (x1) = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_span_qth cobj_x0 cobj_x1 csize_ret_w csize_ret_h foreign import ccall "qtc_QDirModel_span_qth" qtc_QDirModel_span_qth :: Ptr (TQDirModel a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> IO () instance Qspan_h (QDirModelSc a) ((QModelIndex t1)) where span_h x0 (x1) = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_span_qth cobj_x0 cobj_x1 csize_ret_w csize_ret_h instance Qsubmit_h (QDirModel ()) (()) where submit_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_submit cobj_x0 foreign import ccall "qtc_QDirModel_submit" qtc_QDirModel_submit :: Ptr (TQDirModel a) -> IO CBool instance Qsubmit_h (QDirModelSc a) (()) where submit_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDirModel_submit cobj_x0 instance QsetHandler (QDirModel ()) (QDirModel x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel26 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel26_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler26 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler26" qtc_QDirModel_setHandler26 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel26 :: (Ptr (TQDirModel x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel26_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel26 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel26_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler26 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDirModelFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QDirModel ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_event cobj_x0 cobj_x1 foreign import ccall "qtc_QDirModel_event" qtc_QDirModel_event :: Ptr (TQDirModel a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QDirModelSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDirModel_event cobj_x0 cobj_x1 instance QsetHandler (QDirModel ()) (QDirModel x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel27 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel27_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler27 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDirModel_setHandler27" qtc_QDirModel_setHandler27 :: Ptr (TQDirModel a) -> CWString -> Ptr (Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDirModel27 :: (Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDirModel27_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDirModelSc a) (QDirModel x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDirModel27 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDirModel27_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDirModel_setHandler27 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDirModel x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDirModelFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QDirModel ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDirModel_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDirModel_eventFilter" qtc_QDirModel_eventFilter :: Ptr (TQDirModel a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QDirModelSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDirModel_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Gui/QDirModel_h.hs
bsd-2-clause
121,969
0
19
29,244
42,160
20,144
22,016
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | The Codec monad provides functions for encoding and decoding -- complex data structures with unique integer numbers. In the -- simplest case the entire sturecture can be transformed to unique -- atom (see 'example1' below). When it is not sufficient to encode -- the input object with one codec, more complex codec structure can -- be used (see 'example2' below). The library relies on a 'data-lens' -- package which provides types and functions for codec manipulations. -- -- Example: -- -- > example1 = evalCodec empty $ do -- > let xs = "abcabd" -- > ys <- mapM (encode idLens) xs -- > zs <- mapM (decode idLens) ys -- > return $ zip zs ys -- -- >>> example1 -- >>> [('a',0),('b',1),('c',2),('a',0),('b',1),('d',3)] -- -- > example2 = evalCodec (empty, empty) $ do -- > let xs = zip "abcabd" [1, 34342, 5435, 34342, 124, 1] -- > ys <- forM xs $ \(x, y) -> -- > (,) <$> encode fstLens x <*> encode sndLens y -- > zs <- forM ys $ \(i, j) -> -- > (,) <$> decode fstLens i <*> decode sndLens j -- > return (zs, ys) -- -- >>> fst example2 -- >>> [('a',1),('b',34342),('c',5435),('a',34342),('b',124),('d',1)] -- >>> snd example2 -- >>> [(0,0),(1,1),(2,2),(0,1),(1,3),(3,0)] module Control.Monad.Codec ( Codec () , AtomCodec (..) , empty , AtomLens , maybeEncode , encode , encode' , maybeDecode , decode , runCodec , evalCodec , execCodec , idLens ) where import Control.Applicative (Applicative, (<$>), (<*>)) import Data.Lens.Common (Lens, getL, setL, iso) import Data.Binary (Binary, put, get) import qualified Control.Monad.State.Strict as S import qualified Data.Map as M import qualified Data.IntMap as I -- | A Codec monad preserves mappings between objects and respective -- codec components. newtype Codec c a = Codec (S.State c a) deriving (Functor, Applicative, Monad) -- | Get codec structure from the Codec monad. getCodec :: Codec c c getCodec = Codec S.get {-# INLINE getCodec #-} -- | Set codec structure within the Codec monad. setCodec :: c -> Codec c () setCodec codec = Codec (S.put codec) {-# INLINE setCodec #-} -- | Atomic Codec component, which represents to and fro mapping -- between 'a' objects and unique intergers. data AtomCodec a = AtomCodec { to :: !(M.Map a Int) , from :: !(I.IntMap a) } instance (Ord a, Binary a) => Binary (AtomCodec a) where put atom = put (to atom) >> put (from atom) get = AtomCodec <$> get <*> get -- | Empty codec component. empty :: AtomCodec a empty = AtomCodec M.empty I.empty -- | Update the map with the given element and increase the counter. If the -- element has not been previously in the map it will be assigned a new unique -- integer number. updateMap :: Ord a => M.Map a Int -> a -> M.Map a Int updateMap mp x = case M.lookup x mp of Just _k -> mp Nothing -> M.insert x n mp where !n = M.size mp -- | Just a type synonym for a lens between codec and codec component. type AtomLens c a = Lens c (AtomCodec a) -- | Encode the object with codec component identified by the lens. -- Return Nothing if the object is not present in the atomic -- codec component. maybeEncode :: Ord a => AtomLens c a -> a -> Codec c (Maybe Int) maybeEncode lens x = M.lookup x . to . getL lens <$> getCodec -- | Encode the object with codec component identified by the lens. encode :: Ord a => AtomLens c a -> a -> Codec c Int encode lens x = do codec <- getCodec let atomCodec = getL lens codec m' = updateMap (to atomCodec) x y = m' M.! x r' = I.insert y x (from atomCodec) !atom = AtomCodec m' r' codec' = setL lens atom codec setCodec codec' return y -- | Version of encode which doesn't update the return componenent -- of the atom codec. It is useful when we know that particular -- value (e.g. value of a condition observation) won't be decoded -- afterwards so there is no need to store it and waste memory. encode' :: Ord a => AtomLens c a -> a -> Codec c Int encode' lens x = do codec <- getCodec let atomCodec = getL lens codec m' = updateMap (to atomCodec) x y = m' M.! x !atom = atomCodec { to = m' } codec' = setL lens atom codec setCodec codec' return y -- | Decode the number with codec component identified by the lens. -- Return Nothing if the object is not present in the atomic -- codec component. maybeDecode :: Ord a => AtomLens c a -> Int -> Codec c (Maybe a) maybeDecode lens i = I.lookup i . from . getL lens <$> getCodec -- | Decode the number with codec component identified by the lens. -- Report error when the number is not present in the codec component. decode :: Ord a => AtomLens c a -> Int -> Codec c a decode lens i = maybeDecode lens i >>= \mx -> case mx of Just x -> return x Nothing -> error $ "decode: no " ++ show i ++ " key" -- | Run the Codec monad with the initial codec value. -- Return both the result and the final codec state. -- The obtained codec can be used next to perform subsequent -- decoding or encoding. runCodec :: c -> Codec c a -> (a, c) runCodec codec (Codec state) = S.runState state codec -- | Evaluate the Codec monad with the initial codec value. -- Only the monad result will be returned. evalCodec :: c -> Codec c a -> a evalCodec codec (Codec state) = S.evalState state codec -- | Execute the Codec monad with the initial codec value. -- Only the final codec state will be returned. execCodec :: c -> Codec c a -> c execCodec codec (Codec state) = S.execState state codec -- | Identity lenses should be used whenever the structure of the codec -- is simple, i.e. only one atomic codec is used. idLens :: Lens a a idLens = iso id id
kawu/monad-codec
Control/Monad/Codec.hs
bsd-2-clause
5,768
0
12
1,289
1,187
640
547
91
2
module Bugs.Bug6 (main) where import Test.HUnit hiding (Test) import Test.Framework import Test.Framework.Providers.HUnit import Text.Megaparsec import Text.Megaparsec.String import Util main :: Test main = testCase "Look-ahead preserving error location (#6)" $ parseErrors variable "return" @?= ["'return' is a reserved keyword"] variable :: Parser String variable = do x <- lookAhead (some letterChar) if x == "return" then fail "'return' is a reserved keyword" else string x
tulcod/megaparsec
old-tests/Bugs/Bug6.hs
bsd-2-clause
514
0
10
101
127
70
57
17
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} import Control.Applicative import Control.Concurrent import Control.Lens import Control.Monad.Reader import Control.Monad.State import Data.Acid import qualified Data.Aeson as J import qualified Data.ByteString.Char8 as BS import Data.Function (on) import qualified Data.IntMap.Strict as IM import Data.List import qualified Data.Map.Strict as M import Data.Maybe import Data.SafeCopy import qualified Data.Text as T import Data.Time.Clock import Data.Typeable import qualified Data.Vector as V import qualified Network.Http.Client as H import System.Environment (getArgs) import qualified Text.Feed.Import as F import qualified Text.Feed.Query as F import qualified Text.Feed.Types as F import qualified Web.Scotty as W ---------------------------------------------------------------------------------------------------- type Url = String type Tag = String type Flag = String type Id = Int data Article = Article { _storyId :: !String , _title :: !String , _link :: !Url , _content :: !String , _pubDate :: !String , _readStatus :: !Bool , _flags :: ![Flag] } deriving Typeable $(makeLenses ''Article) data Articles = Articles !(M.Map Url Article) deriving Typeable data Feed = Feed { _feedId :: !Int , _feedTitle :: !String , _feedLink :: !Url , _tags :: ![Tag] , _stories :: !Articles} $(makeLenses ''Feed) -- This is an IntMap and not a vector since we might want to delete, insert feeds at a later point, -- while keeping original feed ids. data Feeds = Feeds !(IM.IntMap Feed) deriving Typeable $(deriveSafeCopy 0 'base ''Article) $(deriveSafeCopy 0 'base ''Articles) $(deriveSafeCopy 0 'base ''Feed) $(deriveSafeCopy 0 'base ''Feeds) instance J.ToJSON Articles where toJSON (Articles as) = J.object [("stories", J.Array $ V.fromList $ map J.toJSON $ M.elems as)] instance J.ToJSON Article where toJSON a = J.object [ ("id", J.String $ T.pack $ a^.storyId) , ("story_title", J.String $ T.pack $ a^.title) , ("story_permalink", J.String $ T.pack $ a^.link) , ("story_content", J.String $ T.pack $ a^.content) , ("story_date", J.String $ T.pack $ a^.pubDate) , ("read_status", J.Bool $ a^.readStatus)] instance J.ToJSON Feeds where toJSON (Feeds fs) = J.object [("feeds", J.object xs)] where xs = map (\f -> (T.pack $ show (f^.feedId), J.object [("feed_title", J.String $ T.pack $ f^.feedTitle), ("feed_link", J.String $ T.pack $ f^.feedLink)])) (IM.elems fs) markAllRead :: Id -> Update Feeds () markAllRead i = modify $ \(Feeds fs) -> Feeds $ IM.adjust (stories %~ \(Articles as) -> Articles (M.map (readStatus .~ True) as)) i fs markArticleRead :: Id -> Url -> Bool -> Update Feeds () markArticleRead i url r = modify $ \(Feeds fs) -> Feeds $ IM.adjust (stories %~ \(Articles as) -> Articles (M.adjust (readStatus .~ r) url as)) i fs updateArticleFlags :: Id -> Url -> [Flag] -> Update Feeds () updateArticleFlags i url fls = modify $ \(Feeds fs) -> Feeds $ IM.adjust (stories %~ \(Articles as) -> Articles (M.adjust (flags .~ fls) url as)) i fs subscribedUrls :: Query Feeds [(Id, Url)] subscribedUrls = ask >>= \(Feeds m) -> return $ map (\(i, f) -> (i, f^.feedLink)) (IM.toList m) fetchFeed :: Id -> Query Feeds Articles fetchFeed i = do Feeds m <- ask return $ (m IM.! i) ^. stories ask_ :: Query Feeds Feeds ask_ = ask ---------------------------------------------------------------------------------------------------- newKey :: IM.IntMap a -> Int newKey fs | IM.null fs = 1 newKey fs = fst (IM.findMax fs) + 1 importUrls :: [(Url, [Tag])] -> Update Feeds () importUrls urls = do Feeds fs <- get let urls' = nubBy ((==) `on` fst) urls present = map (_feedLink . snd) $ IM.toList fs newFeed j url ts = Feed j url url ts (Articles M.empty) put $ Feeds $ foldr (\(url, ts) f -> if url `elem` present then f else IM.insert (newKey f) (newFeed (newKey f) url ts) f) fs urls' getFeed :: Url -> IO (Maybe F.Feed) getFeed url = do x <- H.get (BS.pack url) H.concatHandler return $ F.parseFeedString $ BS.unpack x getFeeds :: Feeds -> IO Feeds getFeeds (Feeds fs) = Feeds <$> IM.foldrWithKey (\i f m -> do xs <- m mf <- getFeed (f^.feedLink) return $ IM.update (const (fmap (parseFeed i (f^.tags)) mf)) i xs ) (return fs) fs put_ :: Feeds -> Update Feeds () put_ = put parseFeed :: Id -> [Tag] -> F.Feed -> Feed parseFeed i ts f = Feed i (F.getFeedTitle f) (fromMaybe "No feed url" $ F.getFeedHome f) ts (parseArticles (F.getFeedItems f)) parseArticles :: [F.Item] -> Articles parseArticles = Articles . M.fromList . mapMaybe h where h item = F.getItemLink item >>= \aLink -> Just (aLink, Article aLink (fromMaybe "No title" (F.getItemTitle item)) aLink (fromMaybe "No description" (F.getItemDescription item)) (case F.getItemPublishDate item of Nothing -> "No publisher date" Just t -> case t of Nothing -> fromMaybe "No publisher date" $ F.getItemPublishDateString item Just t1 -> show (t1 :: UTCTime)) False []) $(makeAcidic ''Feeds ['markAllRead , 'markArticleRead , 'updateArticleFlags , 'subscribedUrls , 'fetchFeed , 'importUrls , 'put_ , 'ask_]) ---------------------------------------------------------------------------------------------------- every :: Int -> IO a -> IO ThreadId every m action = forkIO $ forever $ action >> threadDelay (m * 60 * 1000000) parseFeedId :: String -> Id parseFeedId = read parseStoryId :: String -> Url parseStoryId = id ---------------------------------------------------------------------------------------------------- main :: IO () main = do args <- getArgs acidFeeds <- openLocalState $ Feeds IM.empty unless (null args) $ do urls <- map (\l -> (head $ words l, tail $ words l)) <$> lines <$> readFile (head args) update acidFeeds (ImportUrls urls) xs <- query acidFeeds SubscribedUrls fs <- query acidFeeds Ask_ let ids = map fst xs _ <- every 5 $ do fs' <- getFeeds fs update acidFeeds (Put_ fs') W.scotty 3000 $ do W.post "/api/login" $ -- dummy authentication W.json $ J.object [("authenticated", J.Bool True)] W.post "/api/logout" $ -- dummy authentication W.json $ J.object [("authenticated", J.Bool False)] W.get "/reader/feeds" $ do feeds <- lift $ query acidFeeds Ask_ W.json feeds W.post "/reader/mark_feed_as_read" $ do i <- W.param "feed_id" let url = parseFeedId i _ <- lift $ update acidFeeds (MarkAllRead url) W.html "" let updateReadFlag b = do i <- W.param "feed_id" sid <- W.param "story_id" let url = parseFeedId i sid' = parseStoryId sid _ <- lift $ update acidFeeds (MarkArticleRead url sid' b) W.html "" W.post "/reader/mark_story_as_read" $ updateReadFlag False W.post "/reader/mark_story_as_unread" $ updateReadFlag True mapM_ (\i -> W.get (W.capture ("/reader/feed/" ++ show i)) $ do as <- lift $ query acidFeeds (FetchFeed i) W.json as) ids closeAcidState acidFeeds
RobinKrom/rssd
rssd.hs
bsd-3-clause
8,702
0
21
2,933
2,741
1,418
1,323
200
3
module Mapnik.Bindings.VectorTile ( RenderSettings , MVTile (..) , XYZ (..) , render , renderSettings , layerDatasources , module Mapnik.Bindings.VectorTile.Lens ) where import Mapnik.Bindings.VectorTile.Render import Mapnik.Bindings.VectorTile.Types import Mapnik.Bindings.VectorTile.Lens import Mapnik.Bindings.VectorTile.Datasource
albertov/hs-mapnik
vectortile/src/Mapnik/Bindings/VectorTile.hs
bsd-3-clause
338
0
5
32
71
50
21
12
0
module Graphomania.Utils.ByteString ( unsafePutBuilder ) where import Control.Exception import qualified Data.ByteString as BS import Data.ByteString.Builder import Data.ByteString.Builder.Extra import Data.ByteString.Internal import Data.Word import Foreign.ForeignPtr import Foreign.Marshal.Array import Foreign.Ptr {-# NOINLINE moduleError #-} moduleError :: String -> String -> a moduleError fun msg = error (moduleErrorMsg fun msg) {-# NOINLINE moduleErrorIO #-} moduleErrorIO :: String -> String -> IO a moduleErrorIO fun msg = throwIO . userError $ moduleErrorMsg fun msg moduleErrorMsg :: String -> String -> String moduleErrorMsg fun msg = "Graphomania.Utils.ByteString." ++ fun ++ ':':' ':msg -- | Write builder content to specified bytestring and return unused part of string. -- Since bytestring content consideted immutable this is unsafe operation. unsafePutBuilder :: Builder -> ByteString -> IO ByteString unsafePutBuilder b s = withForeignPtr fptr $ \ptr -> go (runBuilder b) (ptr `plusPtr` off) len where (fptr, off, len) = toForeignPtr s go writter ptr size = do (written, next) <- writter ptr size let remains = size - written newPos = ptr `plusPtr` written :: Ptr Word8 case next of Done -> return $ fromForeignPtr fptr (off + len - remains) remains More minSize nextWritter -> if minSize <= remains then go nextWritter newPos remains else moduleErrorIO "unsafePutBuilder" "Writer has requested more space than available in buffer." Chunk chunk nextWritter -> do let (cfptr, coff, clen) = toForeignPtr chunk if clen <= remains then do withForeignPtr cfptr $ \cptr -> moveArray newPos (cptr `plusPtr` coff) clen go nextWritter (newPos `plusPtr` clen) remains else moduleErrorIO "unsafePutBuilder" "Writer has retuned chunk which size exceeded buffer size."
schernichkin/BSPM
graphomania/src/Graphomania/Utils/ByteString.hs
bsd-3-clause
2,057
0
21
534
494
262
232
39
5
module Module1.Task11 where seqA :: Integer -> Integer seqA n | n == 0 = 1 | n == 1 = 2 | n == 2 = 3 | otherwise = let iter a0 a1 a2 (-1) = a2 iter a0 a1 a2 n = iter a1 a2 (a2 + a1 - 2 * a0) (n - 1) in iter 1 2 3 (n - 3)
dstarcev/stepic-haskell
src/Module1/Task11.hs
bsd-3-clause
266
0
14
111
154
76
78
11
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE CPP #-} #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 1 #endif #ifndef MIN_VERSION_array #define MIN_VERSION_array(x,y,z) 1 #endif -- | IEEE-754 parsing, as described in this stack-overflow article: -- -- <http://stackoverflow.com/questions/6976684/converting-ieee-754-floating-point-in-haskell-word32-64-to-and-from-haskell-float/7002812#7002812> module Data.Serialize.IEEE754 ( -- * IEEE-754 reads getFloat32le , getFloat32be , getFloat64le , getFloat64be -- * IEEE-754 writes , putFloat32le , putFloat32be , putFloat64le , putFloat64be ) where import Control.Monad.ST ( runST, ST ) import Data.Array.ST ( newArray, readArray, MArray, STUArray ) import Data.Word ( Word32, Word64 ) import Data.Serialize.Get import Data.Serialize.Put #if !(MIN_VERSION_base(4,8,0)) import Control.Applicative ( (<$>) ) #endif #if MIN_VERSION_array(0,4,0) import Data.Array.Unsafe (castSTUArray) #else import Data.Array.ST (castSTUArray) #endif -- | Read a Float in little endian IEEE-754 format getFloat32le :: Get Float getFloat32le = wordToFloat <$> getWord32le -- | Read a Float in big endian IEEE-754 format getFloat32be :: Get Float getFloat32be = wordToFloat <$> getWord32be -- | Read a Double in little endian IEEE-754 format getFloat64le :: Get Double getFloat64le = wordToDouble <$> getWord64le -- | Read a Double in big endian IEEE-754 format getFloat64be :: Get Double getFloat64be = wordToDouble <$> getWord64be -- | Write a Float in little endian IEEE-754 format putFloat32le :: Float -> Put putFloat32le = putWord32le . floatToWord -- | Write a Float in big endian IEEE-754 format putFloat32be :: Float -> Put putFloat32be = putWord32be . floatToWord -- | Write a Double in little endian IEEE-754 format putFloat64le :: Double -> Put putFloat64le = putWord64le . doubleToWord -- | Write a Double in big endian IEEE-754 format putFloat64be :: Double -> Put putFloat64be = putWord64be . doubleToWord {-# INLINE wordToFloat #-} wordToFloat :: Word32 -> Float wordToFloat x = runST (cast x) {-# INLINE floatToWord #-} floatToWord :: Float -> Word32 floatToWord x = runST (cast x) {-# INLINE wordToDouble #-} wordToDouble :: Word64 -> Double wordToDouble x = runST (cast x) {-# INLINE doubleToWord #-} doubleToWord :: Double -> Word64 doubleToWord x = runST (cast x) {-# INLINE cast #-} cast :: (MArray (STUArray s) a (ST s), MArray (STUArray s) b (ST s)) => a -> ST s b cast x = newArray (0 :: Int, 0) x >>= castSTUArray >>= flip readArray 0
glguy/cereal
src/Data/Serialize/IEEE754.hs
bsd-3-clause
2,578
0
8
441
486
283
203
50
1
{-# OPTIONS_GHC -w #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Haskell.Exts.Pretty -- Original : Language.Haskell.Pretty -- Copyright : (c) Niklas Broberg 2004, -- (c) The GHC Team, Noel Winstanley 1997-2000 -- License : BSD-style (see the file LICENSE.txt) -- -- Maintainer : Niklas Broberg, d00nibro@dtek.chalmers.se -- Stability : experimental -- Portability : portable -- -- Pretty printer for Haskell with extensions. -- ----------------------------------------------------------------------------- module Language.Haskell.Exts.Pretty ( -- * Pretty printing Pretty, prettyPrintStyleMode, prettyPrintWithMode, prettyPrint, -- * Pretty-printing styles (from "Text.PrettyPrint.HughesPJ") P.Style(..), P.style, P.Mode(..), -- * Haskell formatting modes PPHsMode(..), Indent, PPLayout(..), defaultMode) where import Language.Haskell.Exts.Syntax import qualified Text.PrettyPrint as P infixl 5 $$$ ----------------------------------------------------------------------------- -- | Varieties of layout we can use. data PPLayout = PPOffsideRule -- ^ classical layout | PPSemiColon -- ^ classical layout made explicit | PPInLine -- ^ inline decls, with newlines between them | PPNoLayout -- ^ everything on a single line deriving Eq type Indent = Int -- | Pretty-printing parameters. -- -- /Note:/ the 'onsideIndent' must be positive and less than all other indents. data PPHsMode = PPHsMode { -- | indentation of a class or instance classIndent :: Indent, -- | indentation of a @do@-expression doIndent :: Indent, -- | indentation of the body of a -- @case@ expression caseIndent :: Indent, -- | indentation of the declarations in a -- @let@ expression letIndent :: Indent, -- | indentation of the declarations in a -- @where@ clause whereIndent :: Indent, -- | indentation added for continuation -- lines that would otherwise be offside onsideIndent :: Indent, -- | blank lines between statements? spacing :: Bool, -- | Pretty-printing style to use layout :: PPLayout, -- | add GHC-style @LINE@ pragmas to output? linePragmas :: Bool, -- | not implemented yet comments :: Bool } -- | The default mode: pretty-print using the offside rule and sensible -- defaults. defaultMode :: PPHsMode defaultMode = PPHsMode{ classIndent = 8, doIndent = 3, caseIndent = 4, letIndent = 4, whereIndent = 6, onsideIndent = 2, spacing = True, layout = PPOffsideRule, linePragmas = False, comments = True } -- | Pretty printing monad newtype DocM s a = DocM (s -> a) instance Functor (DocM s) where fmap f xs = do x <- xs; return (f x) instance Monad (DocM s) where (>>=) = thenDocM (>>) = then_DocM return = retDocM {-# INLINE thenDocM #-} {-# INLINE then_DocM #-} {-# INLINE retDocM #-} {-# INLINE unDocM #-} {-# INLINE getPPEnv #-} thenDocM :: DocM s a -> (a -> DocM s b) -> DocM s b thenDocM m k = DocM $ (\s -> case unDocM m $ s of a -> unDocM (k a) $ s) then_DocM :: DocM s a -> DocM s b -> DocM s b then_DocM m k = DocM $ (\s -> case unDocM m $ s of _ -> unDocM k $ s) retDocM :: a -> DocM s a retDocM a = DocM (\_s -> a) unDocM :: DocM s a -> (s -> a) unDocM (DocM f) = f -- all this extra stuff, just for this one function. getPPEnv :: DocM s s getPPEnv = DocM id -- So that pp code still looks the same -- this means we lose some generality though -- | The document type produced by these pretty printers uses a 'PPHsMode' -- environment. type Doc = DocM PPHsMode P.Doc -- | Things that can be pretty-printed, including all the syntactic objects -- in "Language.Haskell.Syntax". class Pretty a where -- | Pretty-print something in isolation. pretty :: a -> Doc -- | Pretty-print something in a precedence context. prettyPrec :: Int -> a -> Doc pretty = prettyPrec 0 prettyPrec _ = pretty -- The pretty printing combinators empty :: Doc empty = return P.empty nest :: Int -> Doc -> Doc nest i m = m >>= return . P.nest i -- Literals text, ptext :: String -> Doc text = return . P.text ptext = return . P.text char :: Char -> Doc char = return . P.char int :: Int -> Doc int = return . P.int integer :: Integer -> Doc integer = return . P.integer float :: Float -> Doc float = return . P.float double :: Double -> Doc double = return . P.double rational :: Rational -> Doc rational = return . P.rational -- Simple Combining Forms parens, brackets, braces,quotes,doubleQuotes :: Doc -> Doc parens d = d >>= return . P.parens brackets d = d >>= return . P.brackets braces d = d >>= return . P.braces quotes d = d >>= return . P.quotes doubleQuotes d = d >>= return . P.doubleQuotes parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id -- Constants semi,comma,colon,space,equals :: Doc semi = return P.semi comma = return P.comma colon = return P.colon space = return P.space equals = return P.equals lparen,rparen,lbrack,rbrack,lbrace,rbrace :: Doc lparen = return P.lparen rparen = return P.rparen lbrack = return P.lbrack rbrack = return P.rbrack lbrace = return P.lbrace rbrace = return P.rbrace -- Combinators (<>),(<+>),($$),($+$) :: Doc -> Doc -> Doc aM <> bM = do{a<-aM;b<-bM;return (a P.<> b)} aM <+> bM = do{a<-aM;b<-bM;return (a P.<+> b)} aM $$ bM = do{a<-aM;b<-bM;return (a P.$$ b)} aM $+$ bM = do{a<-aM;b<-bM;return (a P.$+$ b)} hcat,hsep,vcat,sep,cat,fsep,fcat :: [Doc] -> Doc hcat dl = sequence dl >>= return . P.hcat hsep dl = sequence dl >>= return . P.hsep vcat dl = sequence dl >>= return . P.vcat sep dl = sequence dl >>= return . P.sep cat dl = sequence dl >>= return . P.cat fsep dl = sequence dl >>= return . P.fsep fcat dl = sequence dl >>= return . P.fcat -- Some More hang :: Doc -> Int -> Doc -> Doc hang dM i rM = do{d<-dM;r<-rM;return $ P.hang d i r} -- Yuk, had to cut-n-paste this one from Pretty.hs punctuate :: Doc -> [Doc] -> [Doc] punctuate _ [] = [] punctuate p (d1:ds) = go d1 ds where go d [] = [d] go d (e:es) = (d <> p) : go e es -- | render the document with a given style and mode. renderStyleMode :: P.Style -> PPHsMode -> Doc -> String renderStyleMode ppStyle ppMode d = P.renderStyle ppStyle . unDocM d $ ppMode -- | render the document with a given mode. renderWithMode :: PPHsMode -> Doc -> String renderWithMode = renderStyleMode P.style -- | render the document with 'defaultMode'. render :: Doc -> String render = renderWithMode defaultMode -- | pretty-print with a given style and mode. prettyPrintStyleMode :: Pretty a => P.Style -> PPHsMode -> a -> String prettyPrintStyleMode ppStyle ppMode = renderStyleMode ppStyle ppMode . pretty -- | pretty-print with the default style and a given mode. prettyPrintWithMode :: Pretty a => PPHsMode -> a -> String prettyPrintWithMode = prettyPrintStyleMode P.style -- | pretty-print with the default style and 'defaultMode'. prettyPrint :: Pretty a => a -> String prettyPrint = prettyPrintWithMode defaultMode fullRenderWithMode :: PPHsMode -> P.Mode -> Int -> Float -> (P.TextDetails -> a -> a) -> a -> Doc -> a fullRenderWithMode ppMode m i f fn e mD = P.fullRender m i f fn e $ (unDocM mD) ppMode fullRender :: P.Mode -> Int -> Float -> (P.TextDetails -> a -> a) -> a -> Doc -> a fullRender = fullRenderWithMode defaultMode ------------------------- Pretty-Print a Module -------------------- instance Pretty HsModule where pretty (HsModule pos m mbExports imp decls) = markLine pos $ topLevel (ppHsModuleHeader m mbExports) (map pretty imp ++ map pretty decls) -------------------------- Module Header ------------------------------ ppHsModuleHeader :: Module -> Maybe [HsExportSpec] -> Doc ppHsModuleHeader m mbExportList = mySep [ text "module", pretty m, maybePP (parenList . map pretty) mbExportList, text "where"] instance Pretty Module where pretty (Module modName) = text modName instance Pretty HsExportSpec where pretty (HsEVar name) = pretty name pretty (HsEAbs name) = pretty name pretty (HsEThingAll name) = pretty name <> text "(..)" pretty (HsEThingWith name nameList) = pretty name <> (parenList . map pretty $ nameList) pretty (HsEModuleContents m) = text "module" <+> pretty m instance Pretty HsImportDecl where pretty (HsImportDecl pos m qual mbName mbSpecs) = markLine pos $ mySep [text "import", if qual then text "qualified" else empty, pretty m, maybePP (\m' -> text "as" <+> pretty m') mbName, maybePP exports mbSpecs] where exports (b,specList) = if b then text "hiding" <+> specs else specs where specs = parenList . map pretty $ specList instance Pretty HsImportSpec where pretty (HsIVar name) = pretty name pretty (HsIAbs name) = pretty name pretty (HsIThingAll name) = pretty name <> text "(..)" pretty (HsIThingWith name nameList) = pretty name <> (parenList . map pretty $ nameList) ------------------------- Declarations ------------------------------ instance Pretty HsDecl where pretty (HsTypeDecl loc name nameList htype) = blankline $ markLine loc $ mySep ( [text "type", pretty name] ++ map pretty nameList ++ [equals, pretty htype]) pretty (HsDataDecl loc don context name nameList constrList derives) = blankline $ markLine loc $ mySep ( [pretty don, ppHsContext context, pretty name] ++ map pretty nameList) <+> (myVcat (zipWith (<+>) (equals : repeat (char '|')) (map pretty constrList)) $$$ ppHsDeriving derives) pretty (HsGDataDecl loc don context name nameList optkind gadtList) = blankline $ markLine loc $ mySep ( [pretty don, ppHsContext context, pretty name] ++ map pretty nameList ++ ppOptKind optkind ++ [text "where"]) $$$ ppBody classIndent (map pretty gadtList) pretty (HsTypeFamDecl loc name nameList optkind) = blankline $ markLine loc $ mySep ([text "type", text "family", pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (HsDataFamDecl loc context name nameList optkind) = blankline $ markLine loc $ mySep ( [text "data", text "family", ppHsContext context, pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (HsTypeInsDecl loc ntype htype) = blankline $ markLine loc $ mySep [text "type", text "instance", pretty ntype, equals, pretty htype] pretty (HsDataInsDecl loc don ntype constrList derives) = blankline $ markLine loc $ mySep [pretty don, text "instance", pretty ntype] <+> (myVcat (zipWith (<+>) (equals : repeat (char '|')) (map pretty constrList)) $$$ ppHsDeriving derives) pretty (HsGDataInsDecl loc don ntype optkind gadtList) = blankline $ markLine loc $ mySep ( [pretty don, text "instance", pretty ntype] ++ ppOptKind optkind ++ [text "where"]) $$$ ppBody classIndent (map pretty gadtList) {- pretty (HsNewTypeDecl pos context name nameList constr derives) = blankline $ markLine pos $ mySep ( [text "newtype", ppHsContext context, pretty name] ++ map pretty nameList) <+> equals <+> (pretty constr $$$ ppHsDeriving derives) -} --m{spacing=False} -- special case for empty class declaration pretty (HsClassDecl pos context name nameList fundeps []) = blankline $ markLine pos $ mySep ( [text "class", ppHsContext context, pretty name] ++ map pretty nameList ++ [ppFunDeps fundeps]) pretty (HsClassDecl pos context name nameList fundeps declList) = blankline $ markLine pos $ mySep ( [text "class", ppHsContext context, pretty name] ++ map pretty nameList ++ [ppFunDeps fundeps, text "where"]) $$$ ppBody classIndent (map pretty declList) -- m{spacing=False} -- special case for empty instance declaration pretty (HsInstDecl pos context name args []) = blankline $ markLine pos $ mySep ( [text "instance", ppHsContext context, pretty name] ++ map ppHsAType args) pretty (HsInstDecl pos context name args declList) = blankline $ markLine pos $ mySep ( [text "instance", ppHsContext context, pretty name] ++ map ppHsAType args ++ [text "where"]) $$$ ppBody classIndent (map pretty declList) pretty (HsDerivDecl pos context name args) = blankline $ markLine pos $ mySep ( [text "deriving", text "instance", ppHsContext context, pretty name] ++ map ppHsAType args) pretty (HsDefaultDecl pos htypes) = blankline $ markLine pos $ text "default" <+> parenList (map pretty htypes) pretty (HsSpliceDecl pos splice) = blankline $ markLine pos $ pretty splice pretty (HsTypeSig pos nameList qualType) = blankline $ markLine pos $ mySep ((punctuate comma . map pretty $ nameList) ++ [text "::", pretty qualType]) pretty (HsFunBind matches) = foldr ($$$) empty (map pretty matches) pretty (HsPatBind pos pat rhs whereBinds) = markLine pos $ myFsep [pretty pat, pretty rhs] $$$ ppWhere whereBinds pretty (HsInfixDecl pos assoc prec opList) = blankline $ markLine pos $ mySep ([pretty assoc, int prec] ++ (punctuate comma . map pretty $ opList)) pretty (HsForImp pos cconv saf str name typ) = blankline $ markLine pos $ mySep [text "foreign import", pretty cconv, pretty saf, text (show str), pretty name, text "::", pretty typ] pretty (HsForExp pos cconv str name typ) = blankline $ markLine pos $ mySep [text "foreign export", pretty cconv, text (show str), pretty name, text "::", pretty typ] instance Pretty DataOrNew where pretty DataType = text "data" pretty NewType = text "newtype" instance Pretty HsAssoc where pretty HsAssocNone = text "infix" pretty HsAssocLeft = text "infixl" pretty HsAssocRight = text "infixr" instance Pretty HsMatch where pretty (HsMatch pos f ps rhs whereBinds) = markLine pos $ myFsep (lhs ++ [pretty rhs]) $$$ ppWhere whereBinds where lhs = case ps of l:r:ps' | isSymbolName f -> let hd = [pretty l, ppHsName f, pretty r] in if null ps' then hd else parens (myFsep hd) : map (prettyPrec 2) ps' _ -> pretty f : map (prettyPrec 2) ps ppWhere :: HsBinds -> Doc ppWhere (HsBDecls []) = empty ppWhere (HsBDecls l) = nest 2 (text "where" $$$ ppBody whereIndent (map pretty l)) ppWhere (HsIPBinds b) = nest 2 (text "where" $$$ ppBody whereIndent (map pretty b)) instance Pretty HsClassDecl where pretty (HsClsDecl decl) = pretty decl pretty (HsClsDataFam loc context name nameList optkind) = markLine loc $ mySep ( [text "data", ppHsContext context, pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (HsClsTyFam loc name nameList optkind) = markLine loc $ mySep ( [text "type", pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (HsClsTyDef loc ntype htype) = markLine loc $ mySep [text "type", pretty ntype, equals, pretty htype] instance Pretty HsInstDecl where pretty (HsInsDecl decl) = pretty decl pretty (HsInsType loc ntype htype) = markLine loc $ mySep [text "type", pretty ntype, equals, pretty htype] pretty (HsInsData loc don ntype constrList derives) = markLine loc $ mySep [pretty don, pretty ntype] <+> (myVcat (zipWith (<+>) (equals : repeat (char '|')) (map pretty constrList)) $$$ ppHsDeriving derives) pretty (HsInsGData loc don ntype optkind gadtList) = markLine loc $ mySep ( [pretty don, pretty ntype] ++ ppOptKind optkind ++ [text "where"]) $$$ ppBody classIndent (map pretty gadtList) ------------------------- FFI stuff ------------------------------------- instance Pretty HsSafety where pretty PlayRisky = text "unsafe" pretty (PlaySafe b) = text $ if b then "threadsafe" else "safe" instance Pretty HsCallConv where pretty StdCall = text "stdcall" pretty CCall = text "ccall" ------------------------- Data & Newtype Bodies ------------------------- instance Pretty HsQualConDecl where pretty (HsQualConDecl _pos tvs ctxt con) = myFsep [ppForall (Just tvs), ppHsContext ctxt, pretty con] instance Pretty HsGadtDecl where pretty (HsGadtDecl _pos name ty) = myFsep [pretty name, text "::", pretty ty] instance Pretty HsConDecl where pretty (HsRecDecl name fieldList) = pretty name <> (braceList . map ppField $ fieldList) pretty (HsConDecl name@(HsSymbol _) [l, r]) = myFsep [prettyPrec prec_btype l, ppHsName name, prettyPrec prec_btype r] pretty (HsConDecl name typeList) = mySep $ ppHsName name : map (prettyPrec prec_atype) typeList ppField :: ([HsName],HsBangType) -> Doc ppField (names, ty) = myFsepSimple $ (punctuate comma . map pretty $ names) ++ [text "::", pretty ty] instance Pretty HsBangType where prettyPrec _ (HsBangedTy ty) = char '!' <> ppHsAType ty prettyPrec p (HsUnBangedTy ty) = prettyPrec p ty ppHsDeriving :: [HsQName] -> Doc ppHsDeriving [] = empty ppHsDeriving [d] = text "deriving" <+> ppHsQName d ppHsDeriving ds = text "deriving" <+> parenList (map ppHsQName ds) ------------------------- Types ------------------------- {- instance Pretty HsQualType where pretty (HsQualType context htype) = myFsep [ppHsContext context, pretty htype] -} ppHsBType :: HsType -> Doc ppHsBType = prettyPrec prec_btype ppHsAType :: HsType -> Doc ppHsAType = prettyPrec prec_atype -- precedences for types prec_btype, prec_atype :: Int prec_btype = 1 -- left argument of ->, -- or either argument of an infix data constructor prec_atype = 2 -- argument of type or data constructor, or of a class instance Pretty HsType where prettyPrec p (HsTyForall mtvs ctxt htype) = parensIf (p > 0) $ myFsep [ppForall mtvs, ppHsContext ctxt, pretty htype] prettyPrec p (HsTyFun a b) = parensIf (p > 0) $ myFsep [ppHsBType a, text "->", pretty b] prettyPrec _ (HsTyTuple bxd l) = let ds = map pretty l in case bxd of Boxed -> parenList ds Unboxed -> hashParenList ds prettyPrec p (HsTyApp a b) | a == list_tycon = brackets $ pretty b -- special case | otherwise = parensIf (p > prec_btype) $ myFsep [pretty a, ppHsAType b] prettyPrec _ (HsTyVar name) = pretty name prettyPrec _ (HsTyCon name) = pretty name prettyPrec _ (HsTyPred asst) = pretty asst prettyPrec _ (HsTyInfix a op b) = parens (myFsep [pretty op, pretty a, pretty b]) prettyPrec _ (HsTyKind t k) = parens (myFsep [pretty t, text "::", pretty k]) instance Pretty HsTyVarBind where pretty (HsKindedVar var kind) = myFsep [pretty var, text "::", pretty kind] pretty (HsUnkindedVar var) = pretty var ppForall :: Maybe [HsTyVarBind] -> Doc ppForall Nothing = empty ppForall (Just []) = empty ppForall (Just vs) = myFsep (text "forall" : map pretty vs ++ [char '.']) ---------------------------- Kinds ---------------------------- instance Pretty HsKind where pretty HsKindStar = text "*" pretty HsKindBang = text "!" pretty (HsKindFn a b) = myFsep [pretty a, text "->", pretty b] ppOptKind :: Maybe HsKind -> [Doc] ppOptKind Nothing = [] ppOptKind (Just k) = [text "::", pretty k] ------------------- Functional Dependencies ------------------- instance Pretty HsFunDep where pretty (HsFunDep from to) = myFsep $ map pretty from ++ [text "->"] ++ map pretty to ppFunDeps :: [HsFunDep] -> Doc ppFunDeps [] = empty ppFunDeps fds = myFsep $ (char '|':) . punctuate comma . map pretty $ fds ------------------------- Expressions ------------------------- instance Pretty HsRhs where pretty (HsUnGuardedRhs e) = equals <+> pretty e pretty (HsGuardedRhss guardList) = myVcat . map pretty $ guardList instance Pretty HsGuardedRhs where pretty (HsGuardedRhs _pos guards ppBody) = myFsep $ [char '|'] ++ (punctuate comma . map pretty $ guards) ++ [equals, pretty ppBody] instance Pretty HsLiteral where pretty (HsInt i) = integer i pretty (HsChar c) = text (show c) pretty (HsString s) = text (show s) pretty (HsFrac r) = double (fromRational r) -- GHC unboxed literals: pretty (HsCharPrim c) = text (show c) <> char '#' pretty (HsStringPrim s) = text (show s) <> char '#' pretty (HsIntPrim i) = integer i <> char '#' pretty (HsFloatPrim r) = float (fromRational r) <> char '#' pretty (HsDoublePrim r) = double (fromRational r) <> text "##" instance Pretty HsExp where pretty (HsLit l) = pretty l -- lambda stuff pretty (HsInfixApp a op b) = myFsep [pretty a, pretty op, pretty b] pretty (HsNegApp e) = myFsep [char '-', pretty e] pretty (HsApp a b) = myFsep [pretty a, pretty b] pretty (HsLambda _loc expList ppBody) = myFsep $ char '\\' : map pretty expList ++ [text "->", pretty ppBody] -- keywords -- two cases for lets pretty (HsLet (HsBDecls declList) letBody) = ppLetExp declList letBody pretty (HsLet (HsIPBinds bindList) letBody) = ppLetExp bindList letBody pretty (HsDLet bindList letBody) = myFsep [text "dlet" <+> ppBody letIndent (map pretty bindList), text "in", pretty letBody] pretty (HsWith exp bindList) = pretty exp $$$ ppWith bindList pretty (HsIf cond thenexp elsexp) = myFsep [text "if", pretty cond, text "then", pretty thenexp, text "else", pretty elsexp] pretty (HsCase cond altList) = myFsep [text "case", pretty cond, text "of"] $$$ ppBody caseIndent (map pretty altList) pretty (HsDo stmtList) = text "do" $$$ ppBody doIndent (map pretty stmtList) pretty (HsMDo stmtList) = text "mdo" $$$ ppBody doIndent (map pretty stmtList) -- Constructors & Vars pretty (HsVar name) = pretty name pretty (HsIPVar ipname) = pretty ipname pretty (HsCon name) = pretty name pretty (HsTuple expList) = parenList . map pretty $ expList -- weird stuff pretty (HsParen e) = parens . pretty $ e pretty (HsLeftSection e op) = parens (pretty e <+> pretty op) pretty (HsRightSection op e) = parens (pretty op <+> pretty e) pretty (HsRecConstr c fieldList) = pretty c <> (braceList . map pretty $ fieldList) pretty (HsRecUpdate e fieldList) = pretty e <> (braceList . map pretty $ fieldList) -- patterns -- special case that would otherwise be buggy pretty (HsAsPat name (HsIrrPat e)) = myFsep [pretty name <> char '@', char '~' <> pretty e] pretty (HsAsPat name e) = hcat [pretty name, char '@', pretty e] pretty HsWildCard = char '_' pretty (HsIrrPat e) = char '~' <> pretty e -- Lists pretty (HsList list) = bracketList . punctuate comma . map pretty $ list pretty (HsEnumFrom e) = bracketList [pretty e, text ".."] pretty (HsEnumFromTo from to) = bracketList [pretty from, text "..", pretty to] pretty (HsEnumFromThen from thenE) = bracketList [pretty from <> comma, pretty thenE, text ".."] pretty (HsEnumFromThenTo from thenE to) = bracketList [pretty from <> comma, pretty thenE, text "..", pretty to] pretty (HsListComp e stmtList) = bracketList ([pretty e, char '|'] ++ (punctuate comma . map pretty $ stmtList)) pretty (HsExpTypeSig _pos e ty) = myFsep [pretty e, text "::", pretty ty] -- Template Haskell -- pretty (HsReifyExp r) = pretty r pretty (HsBracketExp b) = pretty b pretty (HsSpliceExp s) = pretty s pretty (HsTypQuote t) = text "\'\'" <> pretty t pretty (HsVarQuote x) = text "\'" <> pretty x -- regular patterns pretty (HsSeqRP rs) = myFsep $ text "(/" : map pretty rs ++ [text "/)"] pretty (HsEitherRP r1 r2) = parens . myFsep $ [pretty r1, char '|', pretty r2] pretty (HsGuardRP r gs) = myFsep $ text "(|" : pretty r : char '|' : map pretty gs ++ [text "|)"] -- special case that would otherwise be buggy pretty (HsCAsRP n (HsIrrPat e)) = myFsep [pretty n <> text "@:", char '~' <> pretty e] pretty (HsCAsRP n r) = hcat [pretty n, text "@:", pretty r] -- Hsx pretty (HsXTag _ n attrs mattr cs) = let ax = maybe [] (return . pretty) mattr in hcat $ (myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']): map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']] pretty (HsXETag _ n attrs mattr) = let ax = maybe [] (return . pretty) mattr in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [text "/>"] pretty (HsXPcdata s) = text s pretty (HsXExpTag e) = myFsep $ [text "<%", pretty e, text "%>"] pretty (HsXRPats es) = myFsep $ text "<[" : map pretty es ++ [text "]>"] instance Pretty HsXAttr where pretty (HsXAttr n v) = myFsep [pretty n, char '=', pretty v] instance Pretty HsXName where pretty (HsXName n) = text n pretty (HsXDomName d n) = text d <> char ':' <> text n --ppLetExp :: [HsDecl] -> HsExp -> Doc ppLetExp l b = myFsep [text "let" <+> ppBody letIndent (map pretty l), text "in", pretty b] ppWith binds = nest 2 (text "with" $$$ ppBody withIndent (map pretty binds)) withIndent = whereIndent --------------------- Template Haskell ------------------------- {- instance Pretty HsReify where pretty (HsReifyDecl name) = ppReify "reifyDecl" name pretty (HsReifyType name) = ppReify "reifyType" name pretty (HsReifyFixity name) = ppReify "reifyFixity" name ppReify t n = myFsep [text t, pretty n] --} instance Pretty HsBracket where pretty (HsExpBracket e) = ppBracket "[|" e pretty (HsPatBracket p) = ppBracket "[p|" p pretty (HsTypeBracket t) = ppBracket "[t|" t pretty (HsDeclBracket d) = myFsep $ text "[d|" : map pretty d ++ [text "|]"] ppBracket o x = myFsep [text o, pretty x, text "|]"] instance Pretty HsSplice where pretty (HsIdSplice s) = char '$' <> text s pretty (HsParenSplice e) = myFsep [text "$(", pretty e, char ')'] ------------------------- Patterns ----------------------------- instance Pretty HsPat where prettyPrec _ (HsPVar name) = pretty name prettyPrec _ (HsPLit lit) = pretty lit prettyPrec _ (HsPNeg p) = myFsep [char '-', pretty p] prettyPrec p (HsPInfixApp a op b) = parensIf (p > 0) $ myFsep [pretty a, pretty (HsQConOp op), pretty b] prettyPrec p (HsPApp n ps) = parensIf (p > 1) $ myFsep (pretty n : map pretty ps) prettyPrec _ (HsPTuple ps) = parenList . map pretty $ ps prettyPrec _ (HsPList ps) = bracketList . punctuate comma . map pretty $ ps prettyPrec _ (HsPParen p) = parens . pretty $ p prettyPrec _ (HsPRec c fields) = pretty c <> (braceList . map pretty $ fields) -- special case that would otherwise be buggy prettyPrec _ (HsPAsPat name (HsPIrrPat pat)) = myFsep [pretty name <> char '@', char '~' <> pretty pat] prettyPrec _ (HsPAsPat name pat) = hcat [pretty name, char '@', pretty pat] prettyPrec _ HsPWildCard = char '_' prettyPrec _ (HsPIrrPat pat) = char '~' <> pretty pat prettyPrec _ (HsPatTypeSig _pos pat ty) = myFsep [pretty pat, text "::", pretty ty] -- HaRP prettyPrec _ (HsPRPat rs) = bracketList . punctuate comma . map pretty $ rs -- Hsx prettyPrec _ (HsPXTag _ n attrs mattr cp) = let ap = maybe [] (return . pretty) mattr in hcat $ -- TODO: should not introduce blanks (myFsep $ (char '<' <> pretty n): map pretty attrs ++ ap ++ [char '>']): map pretty cp ++ [myFsep $ [text "</" <> pretty n, char '>']] prettyPrec _ (HsPXETag _ n attrs mattr) = let ap = maybe [] (return . pretty) mattr in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ap ++ [text "/>"] prettyPrec _ (HsPXPcdata s) = text s prettyPrec _ (HsPXPatTag p) = myFsep $ [text "<%", pretty p, text "%>"] prettyPrec _ (HsPXRPats ps) = myFsep $ text "<[" : map pretty ps ++ [text "%>"] {- prettyChildren :: HsPat -> [Doc] prettyChildren p = case p of HsPList ps -> map prettyChild ps HsPRPat _ _ -> [pretty p] _ -> error "The pattern representing the children of an xml pattern \ \ should always be a list." prettyChild :: HsPat -> Doc prettyChild p = case p of HsPXTag _ _ _ _ _ -> pretty p HsPXETag _ _ _ _ -> pretty p HsPXPatTag _ -> pretty p HsPXPcdata _ -> pretty p _ -> pretty $ HsPXPatTag p -} instance Pretty HsPXAttr where pretty (HsPXAttr n p) = myFsep [pretty n, char '=', pretty p] instance Pretty HsPatField where pretty (HsPFieldPat name pat) = myFsep [pretty name, equals, pretty pat] --------------------- Regular Patterns ------------------------- instance Pretty HsRPat where pretty (HsRPOp r op) = pretty r <> pretty op pretty (HsRPEither r1 r2) = parens . myFsep $ [pretty r1, char '|', pretty r2] pretty (HsRPSeq rs) = myFsep $ text "(/" : map pretty rs ++ [text "/)"] pretty (HsRPGuard r gs) = myFsep $ text "(|" : pretty r : char '|' : map pretty gs ++ [text "|)"] -- special case that would otherwise be buggy pretty (HsRPCAs n (HsRPPat (HsPIrrPat p))) = myFsep [pretty n <> text "@:", char '~' <> pretty p] pretty (HsRPCAs n r) = hcat [pretty n, text "@:", pretty r] -- special case that would otherwise be buggy pretty (HsRPAs n (HsRPPat (HsPIrrPat p))) = myFsep [pretty n <> text "@:", char '~' <> pretty p] pretty (HsRPAs n r) = hcat [pretty n, char '@', pretty r] pretty (HsRPPat p) = pretty p pretty (HsRPParen rp) = parens . pretty $ rp instance Pretty HsRPatOp where pretty HsRPStar = char '*' pretty HsRPStarG = text "*!" pretty HsRPPlus = char '+' pretty HsRPPlusG = text "+!" pretty HsRPOpt = char '?' pretty HsRPOptG = text "?!" ------------------------- Case bodies ------------------------- instance Pretty HsAlt where pretty (HsAlt _pos e gAlts binds) = pretty e <+> pretty gAlts $$$ ppWhere binds instance Pretty HsGuardedAlts where pretty (HsUnGuardedAlt e) = text "->" <+> pretty e pretty (HsGuardedAlts altList) = myVcat . map pretty $ altList instance Pretty HsGuardedAlt where pretty (HsGuardedAlt _pos guards body) = myFsep $ char '|': (punctuate comma . map pretty $ guards) ++ [text "->", pretty body] ------------------------- Statements in monads, guards & list comprehensions ----- instance Pretty HsStmt where pretty (HsGenerator _loc e from) = pretty e <+> text "<-" <+> pretty from pretty (HsQualifier e) = pretty e -- two cases for lets pretty (HsLetStmt (HsBDecls declList)) = ppLetStmt declList pretty (HsLetStmt (HsIPBinds bindList)) = ppLetStmt bindList ppLetStmt l = text "let" $$$ ppBody letIndent (map pretty l) ------------------------- Record updates instance Pretty HsFieldUpdate where pretty (HsFieldUpdate name e) = myFsep [pretty name, equals, pretty e] ------------------------- Names ------------------------- instance Pretty HsQOp where pretty (HsQVarOp n) = ppHsQNameInfix n pretty (HsQConOp n) = ppHsQNameInfix n ppHsQNameInfix :: HsQName -> Doc ppHsQNameInfix name | isSymbolName (getName name) = ppHsQName name | otherwise = char '`' <> ppHsQName name <> char '`' instance Pretty HsQName where pretty name = case name of UnQual (HsSymbol ('#':_)) -> char '(' <+> ppHsQName name <+> char ')' _ -> parensIf (isSymbolName (getName name)) (ppHsQName name) ppHsQName :: HsQName -> Doc ppHsQName (UnQual name) = ppHsName name ppHsQName (Qual m name) = pretty m <> char '.' <> ppHsName name ppHsQName (Special sym) = text (specialName sym) instance Pretty HsOp where pretty (HsVarOp n) = ppHsNameInfix n pretty (HsConOp n) = ppHsNameInfix n ppHsNameInfix :: HsName -> Doc ppHsNameInfix name | isSymbolName name = ppHsName name | otherwise = char '`' <> ppHsName name <> char '`' instance Pretty HsName where pretty name = case name of HsSymbol ('#':_) -> char '(' <+> ppHsName name <+> char ')' _ -> parensIf (isSymbolName name) (ppHsName name) ppHsName :: HsName -> Doc ppHsName (HsIdent s) = text s ppHsName (HsSymbol s) = text s instance Pretty HsIPName where pretty (HsIPDup s) = char '?' <> text s pretty (HsIPLin s) = char '%' <> text s instance Pretty HsIPBind where pretty (HsIPBind _loc ipname exp) = myFsep [pretty ipname, equals, pretty exp] instance Pretty HsCName where pretty (HsVarName n) = pretty n pretty (HsConName n) = pretty n isSymbolName :: HsName -> Bool isSymbolName (HsSymbol _) = True isSymbolName _ = False getName :: HsQName -> HsName getName (UnQual s) = s getName (Qual _ s) = s getName (Special HsCons) = HsSymbol ":" getName (Special HsFunCon) = HsSymbol "->" getName (Special s) = HsIdent (specialName s) specialName :: HsSpecialCon -> String specialName HsUnitCon = "()" specialName HsListCon = "[]" specialName HsFunCon = "->" specialName (HsTupleCon n) = "(" ++ replicate (n-1) ',' ++ ")" specialName HsCons = ":" ppHsContext :: HsContext -> Doc ppHsContext [] = empty ppHsContext context = mySep [parenList (map pretty context), text "=>"] -- hacked for multi-parameter type classes instance Pretty HsAsst where pretty (HsClassA a ts) = myFsep $ ppHsQName a : map ppHsAType ts pretty (HsIParam i t) = myFsep $ [pretty i, text "::", pretty t] pretty (HsEqualP t1 t2) = myFsep $ [pretty t1, text "~", pretty t2] ------------------------- pp utils ------------------------- maybePP :: (a -> Doc) -> Maybe a -> Doc maybePP pp Nothing = empty maybePP pp (Just a) = pp a parenList :: [Doc] -> Doc parenList = parens . myFsepSimple . punctuate comma hashParenList :: [Doc] -> Doc hashParenList = hashParens . myFsepSimple . punctuate comma where hashParens = parens . hashes hashes = \doc -> char '#' <> doc <> char '#' braceList :: [Doc] -> Doc braceList = braces . myFsepSimple . punctuate comma bracketList :: [Doc] -> Doc bracketList = brackets . myFsepSimple -- Wrap in braces and semicolons, with an extra space at the start in -- case the first doc begins with "-", which would be scanned as {- flatBlock :: [Doc] -> Doc flatBlock = braces . (space <>) . hsep . punctuate semi -- Same, but put each thing on a separate line prettyBlock :: [Doc] -> Doc prettyBlock = braces . (space <>) . vcat . punctuate semi -- Monadic PP Combinators -- these examine the env blankline :: Doc -> Doc blankline dl = do{e<-getPPEnv;if spacing e && layout e /= PPNoLayout then space $$ dl else dl} topLevel :: Doc -> [Doc] -> Doc topLevel header dl = do e <- fmap layout getPPEnv case e of PPOffsideRule -> header $$ vcat dl PPSemiColon -> header $$ prettyBlock dl PPInLine -> header $$ prettyBlock dl PPNoLayout -> header <+> flatBlock dl ppBody :: (PPHsMode -> Int) -> [Doc] -> Doc ppBody f dl = do e <- fmap layout getPPEnv case e of PPOffsideRule -> indent PPSemiColon -> indentExplicit _ -> flatBlock dl where indent = do{i <-fmap f getPPEnv;nest i . vcat $ dl} indentExplicit = do {i <- fmap f getPPEnv; nest i . prettyBlock $ dl} ($$$) :: Doc -> Doc -> Doc a $$$ b = layoutChoice (a $$) (a <+>) b mySep :: [Doc] -> Doc mySep = layoutChoice mySep' hsep where -- ensure paragraph fills with indentation. mySep' [x] = x mySep' (x:xs) = x <+> fsep xs mySep' [] = error "Internal error: mySep" myVcat :: [Doc] -> Doc myVcat = layoutChoice vcat hsep myFsepSimple :: [Doc] -> Doc myFsepSimple = layoutChoice fsep hsep -- same, except that continuation lines are indented, -- which is necessary to avoid triggering the offside rule. myFsep :: [Doc] -> Doc myFsep = layoutChoice fsep' hsep where fsep' [] = empty fsep' (d:ds) = do e <- getPPEnv let n = onsideIndent e nest n (fsep (nest (-n) d:ds)) layoutChoice :: (a -> Doc) -> (a -> Doc) -> a -> Doc layoutChoice a b dl = do e <- getPPEnv if layout e == PPOffsideRule || layout e == PPSemiColon then a dl else b dl -- Prefix something with a LINE pragma, if requested. -- GHC's LINE pragma actually sets the current line number to n-1, so -- that the following line is line n. But if there's no newline before -- the line we're talking about, we need to compensate by adding 1. markLine :: SrcLoc -> Doc -> Doc markLine loc doc = do e <- getPPEnv let y = srcLine loc let line l = text ("{-# LINE " ++ show l ++ " \"" ++ srcFilename loc ++ "\" #-}") if linePragmas e then layoutChoice (line y $$) (line (y+1) <+>) doc else doc
abuiles/turbinado-blog
tmp/dependencies/haskell-src-exts-0.3.9/Language/Haskell/Exts/Pretty.hs
bsd-3-clause
42,507
0
18
14,255
12,686
6,348
6,338
757
4
module LogAnalysis where import Log parseMessagehelper::String->[String] parseMessagehelper a = words a parseMessagehelper2:: [String]->String parseMessagehelper2 a = unwords a charToString :: Char -> String charToString c = [c] errormessagetypes::[String]->MessageType errormessagetypes (a:rest) | a!!0 == 'I' = Info | a!!0 == 'W' = Warning | a!!0 == 'E' && b<100 = Error b where b = read (rest!!0) checkmessagemessagetype::[String]->String checkmessagemessagetype (c:cs) | errormessagetypes(c:cs) == Info = cs!!0 | errormessagetypes(c:cs) == Warning = cs!!0 | otherwise = cs!!1 dropthisamount::[String]->Int dropthisamount (c:cs) = case errormessagetypes(c:cs) of Error b -> 3 otherwise ->2 parseMessage :: String -> LogMessage parseMessage a = LogMessage (errormessagetypes(untranslatederror)) (read (checkmessagemessagetype(untranslatederror))) (parseMessagehelper2 (drop (dropthisamount(untranslatederror)) untranslatederror)) where untranslatederror = (parseMessagehelper a) parse :: String -> [LogMessage] parse a = map (parseMessage) (lines a) findtimestamp::LogMessage->Int findtimestamp (LogMessage _ time _ ) = time insert :: LogMessage -> MessageTree -> MessageTree insert (Unknown _) (Leaf) = Leaf insert (Unknown _) (Node leftbranch b rightbranch) = Node leftbranch b rightbranch insert a (Leaf) = Node Leaf a Leaf insert a (Node Leaf b Leaf)= Node Leaf a Leaf insert a (Node leftbranch b rightbranch) | findtimestamp(a)>findtimestamp(b) = Node leftbranch b (insert a rightbranch) | findtimestamp(a)<=findtimestamp(b) = Node (insert a leftbranch) b rightbranch build :: [LogMessage] -> MessageTree build a = foldr insert (Leaf) a inOrder :: MessageTree -> [LogMessage] inOrder a@(Leaf) = [] inOrder a@(Node Leaf b Leaf) = [b] inOrder a@(Node leftbranch b rightbranch) = inOrder leftbranch ++ [b] ++ inOrder rightbranch
marc-woolley/cs2-adts-logging
LogAnalysis.hs
bsd-3-clause
1,942
0
12
347
797
407
390
41
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskellQuotes #-} {-# LANGUAGE TypeFamilies #-} -- | -- An abstract interface for maps from JSON keys to values. module Data.Aeson.KeyMap ( -- * Map Type KeyMap, -- * Query null, lookup, size, member, -- * Construction empty, singleton, -- ** Insertion insert, -- * Deletion delete, -- * Update alterF, -- * Combine difference, union, unionWith, unionWithKey, intersection, intersectionWith, intersectionWithKey, alignWith, alignWithKey, -- * Lists fromList, fromListWith, toList, toAscList, -- * Maps fromHashMap, toHashMap, fromHashMapText, toHashMapText, coercionToHashMap, fromMap, toMap, fromMapText, toMapText, coercionToMap, -- * Traversal -- ** Map map, mapKeyVal, traverse, traverseWithKey, -- * Folds foldr, foldr', foldl, foldl', foldMapWithKey, foldrWithKey, -- * Conversions keys, -- * Filter filter, filterWithKey, mapMaybe, mapMaybeWithKey, ) where -- Import stuff from Prelude explicitly import Prelude (Eq(..), Ord((>)), Int, Bool(..), Maybe(..)) import Prelude ((.), ($)) import Prelude (Functor(fmap), Monad(..)) import Prelude (Show, showsPrec, showParen, shows, showString) import Control.Applicative (Applicative) import Control.DeepSeq (NFData(..)) import Data.Aeson.Key (Key) import Data.Bifunctor (first) import Data.Data (Data) import Data.Hashable (Hashable(..)) import Data.HashMap.Strict (HashMap) import Data.Map (Map) import Data.Monoid (Monoid(mempty, mappend)) import Data.Semigroup (Semigroup((<>))) import Data.Text (Text) import Data.These (These (..)) import Data.Type.Coercion (Coercion (..)) import Data.Typeable (Typeable) import Text.Read (Read (..), Lexeme(..), readListPrecDefault, prec, lexP, parens) import qualified Data.Aeson.Key as Key import qualified Data.Foldable as F import qualified Data.Traversable as T import qualified Data.HashMap.Strict as H import qualified Data.List as L import qualified Data.Map.Strict as M import qualified Language.Haskell.TH.Syntax as TH import qualified Data.Foldable.WithIndex as WI (FoldableWithIndex (..)) import qualified Data.Functor.WithIndex as WI (FunctorWithIndex (..)) import qualified Data.Traversable.WithIndex as WI (TraversableWithIndex (..)) import qualified Data.Semialign as SA import qualified Data.Semialign.Indexed as SAI import qualified GHC.Exts import qualified Witherable as W #ifdef USE_ORDEREDMAP ------------------------------------------------------------------------------- -- Map ------------------------------------------------------------------------------- -- | A map from JSON key type 'Key' to 'v'. newtype KeyMap v = KeyMap { unKeyMap :: Map Key v } deriving (Eq, Ord, Typeable, Data, Functor) -- | Construct an empty map. empty :: KeyMap v empty = KeyMap M.empty -- | Is the map empty? null :: KeyMap v -> Bool null = M.null . unKeyMap -- | Return the number of key-value mappings in this map. size :: KeyMap v -> Int size = M.size . unKeyMap -- | Construct a map with a single element. singleton :: Key -> v -> KeyMap v singleton k v = KeyMap (M.singleton k v) -- | Is the key a member of the map? member :: Key -> KeyMap a -> Bool member t (KeyMap m) = M.member t m -- | Remove the mapping for the specified key from this map if present. delete :: Key -> KeyMap v -> KeyMap v delete k (KeyMap m) = KeyMap (M.delete k m) -- | 'alterF' can be used to insert, delete, or update a value in a map. alterF :: Functor f => (Maybe v -> f (Maybe v)) -> Key -> KeyMap v -> f (KeyMap v) #if MIN_VERSION_containers(0,5,8) alterF f k = fmap KeyMap . M.alterF f k . unKeyMap #else alterF f k m = fmap g (f mv) where g r = case r of Nothing -> case mv of Nothing -> m Just _ -> delete k m Just v' -> insert k v' m mv = lookup k m #endif -- | Return the value to which the specified key is mapped, -- or Nothing if this map contains no mapping for the key. lookup :: Key -> KeyMap v -> Maybe v lookup t tm = M.lookup t (unKeyMap tm) -- | Associate the specified value with the specified key -- in this map. If this map previously contained a mapping -- for the key, the old value is replaced. insert :: Key -> v -> KeyMap v -> KeyMap v insert k v tm = KeyMap (M.insert k v (unKeyMap tm)) -- | Map a function over all values in the map. map :: (a -> b) -> KeyMap a -> KeyMap b map = fmap -- | Map a function over all values in the map. mapWithKey :: (Key -> a -> b) -> KeyMap a -> KeyMap b mapWithKey f (KeyMap m) = KeyMap (M.mapWithKey f m) foldMapWithKey :: Monoid m => (Key -> a -> m) -> KeyMap a -> m foldMapWithKey f (KeyMap m) = M.foldMapWithKey f m foldr :: (a -> b -> b) -> b -> KeyMap a -> b foldr f z (KeyMap m) = M.foldr f z m foldr' :: (a -> b -> b) -> b -> KeyMap a -> b foldr' f z (KeyMap m) = M.foldr' f z m foldl :: (b -> a -> b) -> b -> KeyMap a -> b foldl f z (KeyMap m) = M.foldl f z m foldl' :: (b -> a -> b) -> b -> KeyMap a -> b foldl' f z (KeyMap m) = M.foldl' f z m -- | Reduce this map by applying a binary operator to all -- elements, using the given starting value (typically the -- right-identity of the operator). foldrWithKey :: (Key -> v -> a -> a) -> a -> KeyMap v -> a foldrWithKey f a = M.foldrWithKey f a . unKeyMap -- | Perform an Applicative action for each key-value pair -- in a 'KeyMap' and produce a 'KeyMap' of all the results. traverse :: Applicative f => (v1 -> f v2) -> KeyMap v1 -> f (KeyMap v2) traverse f = fmap KeyMap . T.traverse f . unKeyMap -- | Perform an Applicative action for each key-value pair -- in a 'KeyMap' and produce a 'KeyMap' of all the results. traverseWithKey :: Applicative f => (Key -> v1 -> f v2) -> KeyMap v1 -> f (KeyMap v2) traverseWithKey f = fmap KeyMap . M.traverseWithKey f . unKeyMap -- | Construct a map from a list of elements. Uses the -- provided function, f, to merge duplicate entries with -- (f newVal oldVal). fromListWith :: (v -> v -> v) -> [(Key, v)] -> KeyMap v fromListWith op = KeyMap . M.fromListWith op -- | Construct a map with the supplied mappings. If the -- list contains duplicate mappings, the later mappings take -- precedence. fromList :: [(Key, v)] -> KeyMap v fromList = KeyMap . M.fromList -- | Return a list of this map's elements. -- -- The order is not stable. Use 'toAscList' for stable ordering. toList :: KeyMap v -> [(Key, v)] toList = M.toList . unKeyMap -- | Return a list of this map's elements in ascending order -- based of the textual key. toAscList :: KeyMap v -> [(Key, v)] toAscList = M.toAscList . unKeyMap -- | Difference of two maps. Return elements of the first -- map not existing in the second. difference :: KeyMap v -> KeyMap v' -> KeyMap v difference tm1 tm2 = KeyMap (M.difference (unKeyMap tm1) (unKeyMap tm2)) -- The (left-biased) union of two maps. It prefers the first map when duplicate -- keys are encountered, i.e. ('union' == 'unionWith' 'const'). union :: KeyMap v -> KeyMap v -> KeyMap v union (KeyMap x) (KeyMap y) = KeyMap (M.union x y) -- | The union with a combining function. unionWith :: (v -> v -> v) -> KeyMap v -> KeyMap v -> KeyMap v unionWith f (KeyMap x) (KeyMap y) = KeyMap (M.unionWith f x y) -- | The union with a combining function. unionWithKey :: (Key -> v -> v -> v) -> KeyMap v -> KeyMap v -> KeyMap v unionWithKey f (KeyMap x) (KeyMap y) = KeyMap (M.unionWithKey f x y) -- | The (left-biased) intersection of two maps (based on keys). intersection :: KeyMap a -> KeyMap b -> KeyMap a intersection (KeyMap x) (KeyMap y) = KeyMap (M.intersection x y) -- | The intersection with a combining function. intersectionWith :: (a -> b -> c) -> KeyMap a -> KeyMap b -> KeyMap c intersectionWith f (KeyMap x) (KeyMap y) = KeyMap (M.intersectionWith f x y) -- | The intersection with a combining function. intersectionWithKey :: (Key -> a -> b -> c) -> KeyMap a -> KeyMap b -> KeyMap c intersectionWithKey f (KeyMap x) (KeyMap y) = KeyMap (M.intersectionWithKey f x y) -- | Return a list of this map's keys. keys :: KeyMap v -> [Key] keys = M.keys . unKeyMap -- | Convert a 'KeyMap' to a 'HashMap'. toHashMap :: KeyMap v -> HashMap Key v toHashMap = H.fromList . toList -- | Convert a 'HashMap' to a 'KeyMap'. fromHashMap :: HashMap Key v -> KeyMap v fromHashMap = fromList . H.toList -- | Convert a 'KeyMap' to a 'Map'. toMap :: KeyMap v -> Map Key v toMap = unKeyMap -- | Convert a 'Map' to a 'KeyMap'. fromMap :: Map Key v -> KeyMap v fromMap = KeyMap coercionToHashMap :: Maybe (Coercion (HashMap Key v) (KeyMap v)) coercionToHashMap = Nothing {-# INLINE coercionToHashMap #-} coercionToMap :: Maybe (Coercion (Map Key v) (KeyMap v)) coercionToMap = Just Coercion {-# INLINE coercionToMap #-} -- | Transform the keys and values of a 'KeyMap'. mapKeyVal :: (Key -> Key) -> (v1 -> v2) -> KeyMap v1 -> KeyMap v2 mapKeyVal fk kv = foldrWithKey (\k v -> insert (fk k) (kv v)) empty {-# INLINE mapKeyVal #-} -- | Filter all keys/values that satisfy some predicate. filter :: (v -> Bool) -> KeyMap v -> KeyMap v filter f (KeyMap m) = KeyMap (M.filter f m) -- | Filter all keys/values that satisfy some predicate. filterWithKey :: (Key -> v -> Bool) -> KeyMap v -> KeyMap v filterWithKey f (KeyMap m) = KeyMap (M.filterWithKey f m) -- | Map values and collect the Just results. mapMaybe :: (a -> Maybe b) -> KeyMap a -> KeyMap b mapMaybe f (KeyMap m) = KeyMap (M.mapMaybe f m) -- | Map values and collect the Just results. mapMaybeWithKey :: (Key -> v -> Maybe u) -> KeyMap v -> KeyMap u mapMaybeWithKey f (KeyMap m) = KeyMap (M.mapMaybeWithKey f m) #else ------------------------------------------------------------------------------- -- HashMap ------------------------------------------------------------------------------- import Data.List (sortBy) import Data.Ord (comparing) import Prelude (fst) -- | A map from JSON key type 'Key' to 'v'. newtype KeyMap v = KeyMap { unKeyMap :: HashMap Key v } deriving (Eq, Ord, Typeable, Data, Functor) -- | Construct an empty map. empty :: KeyMap v empty = KeyMap H.empty -- | Is the map empty? null :: KeyMap v -> Bool null = H.null . unKeyMap -- | Return the number of key-value mappings in this map. size :: KeyMap v -> Int size = H.size . unKeyMap -- | Construct a map with a single element. singleton :: Key -> v -> KeyMap v singleton k v = KeyMap (H.singleton k v) -- | Is the key a member of the map? member :: Key -> KeyMap a -> Bool member t (KeyMap m) = H.member t m -- | Remove the mapping for the specified key from this map if present. delete :: Key -> KeyMap v -> KeyMap v delete k (KeyMap m) = KeyMap (H.delete k m) -- | 'alterF' can be used to insert, delete, or update a value in a map. alterF :: Functor f => (Maybe v -> f (Maybe v)) -> Key -> KeyMap v -> f (KeyMap v) alterF f k = fmap KeyMap . H.alterF f k . unKeyMap -- | Return the value to which the specified key is mapped, -- or Nothing if this map contains no mapping for the key. lookup :: Key -> KeyMap v -> Maybe v lookup t tm = H.lookup t (unKeyMap tm) -- | Associate the specified value with the specified key -- in this map. If this map previously contained a mapping -- for the key, the old value is replaced. insert :: Key -> v -> KeyMap v -> KeyMap v insert k v tm = KeyMap (H.insert k v (unKeyMap tm)) -- | Map a function over all values in the map. map :: (a -> b) -> KeyMap a -> KeyMap b map = fmap -- | Map a function over all values in the map. mapWithKey :: (Key -> a -> b) -> KeyMap a -> KeyMap b mapWithKey f (KeyMap m) = KeyMap (H.mapWithKey f m) foldMapWithKey :: Monoid m => (Key -> a -> m) -> KeyMap a -> m foldMapWithKey f (KeyMap m) = H.foldMapWithKey f m foldr :: (a -> b -> b) -> b -> KeyMap a -> b foldr f z (KeyMap m) = H.foldr f z m foldr' :: (a -> b -> b) -> b -> KeyMap a -> b foldr' f z (KeyMap m) = H.foldr' f z m foldl :: (b -> a -> b) -> b -> KeyMap a -> b foldl f z (KeyMap m) = H.foldl f z m foldl' :: (b -> a -> b) -> b -> KeyMap a -> b foldl' f z (KeyMap m) = H.foldl' f z m -- | Reduce this map by applying a binary operator to all -- elements, using the given starting value (typically the -- right-identity of the operator). foldrWithKey :: (Key -> v -> a -> a) -> a -> KeyMap v -> a foldrWithKey f a = H.foldrWithKey f a . unKeyMap -- | Perform an Applicative action for each key-value pair -- in a 'KeyMap' and produce a 'KeyMap' of all the results. traverse :: Applicative f => (v1 -> f v2) -> KeyMap v1 -> f (KeyMap v2) traverse f = fmap KeyMap . T.traverse f . unKeyMap -- | Perform an Applicative action for each key-value pair -- in a 'KeyMap' and produce a 'KeyMap' of all the results. traverseWithKey :: Applicative f => (Key -> v1 -> f v2) -> KeyMap v1 -> f (KeyMap v2) traverseWithKey f = fmap KeyMap . H.traverseWithKey f . unKeyMap -- | Construct a map from a list of elements. Uses the -- provided function, f, to merge duplicate entries with -- (f newVal oldVal). fromListWith :: (v -> v -> v) -> [(Key, v)] -> KeyMap v fromListWith op = KeyMap . H.fromListWith op -- | Construct a map with the supplied mappings. If the -- list contains duplicate mappings, the later mappings take -- precedence. fromList :: [(Key, v)] -> KeyMap v fromList = KeyMap . H.fromList -- | Return a list of this map's elements. -- -- The order is not stable. Use 'toAscList' for stable ordering. toList :: KeyMap v -> [(Key, v)] toList = H.toList . unKeyMap -- | Return a list of this map's elements in ascending order -- based of the textual key. toAscList :: KeyMap v -> [(Key, v)] toAscList = sortBy (comparing fst) . toList -- | Difference of two maps. Return elements of the first -- map not existing in the second. difference :: KeyMap v -> KeyMap v' -> KeyMap v difference tm1 tm2 = KeyMap (H.difference (unKeyMap tm1) (unKeyMap tm2)) -- The (left-biased) union of two maps. It prefers the first map when duplicate -- keys are encountered, i.e. ('union' == 'unionWith' 'const'). union :: KeyMap v -> KeyMap v -> KeyMap v union (KeyMap x) (KeyMap y) = KeyMap (H.union x y) -- | The union with a combining function. unionWith :: (v -> v -> v) -> KeyMap v -> KeyMap v -> KeyMap v unionWith f (KeyMap x) (KeyMap y) = KeyMap (H.unionWith f x y) -- | The union with a combining function. unionWithKey :: (Key -> v -> v -> v) -> KeyMap v -> KeyMap v -> KeyMap v unionWithKey f (KeyMap x) (KeyMap y) = KeyMap (H.unionWithKey f x y) -- | The (left-biased) intersection of two maps (based on keys). intersection :: KeyMap a -> KeyMap b -> KeyMap a intersection (KeyMap x) (KeyMap y) = KeyMap (H.intersection x y) -- | The intersection with a combining function. intersectionWith :: (a -> b -> c) -> KeyMap a -> KeyMap b -> KeyMap c intersectionWith f (KeyMap x) (KeyMap y) = KeyMap (H.intersectionWith f x y) -- | The intersection with a combining function. intersectionWithKey :: (Key -> a -> b -> c) -> KeyMap a -> KeyMap b -> KeyMap c intersectionWithKey f (KeyMap x) (KeyMap y) = KeyMap (H.intersectionWithKey f x y) -- | Return a list of this map's keys. keys :: KeyMap v -> [Key] keys = H.keys . unKeyMap -- | Convert a 'KeyMap' to a 'HashMap'. toHashMap :: KeyMap v -> HashMap Key v toHashMap = unKeyMap -- | Convert a 'HashMap' to a 'KeyMap'. fromHashMap :: HashMap Key v -> KeyMap v fromHashMap = KeyMap -- | Convert a 'KeyMap' to a 'Map'. toMap :: KeyMap v -> Map Key v toMap = M.fromList . toList -- | Convert a 'Map' to a 'KeyMap'. fromMap :: Map Key v -> KeyMap v fromMap = fromList . M.toList coercionToHashMap :: Maybe (Coercion (HashMap Key v) (KeyMap v)) coercionToHashMap = Just Coercion {-# INLINE coercionToHashMap #-} coercionToMap :: Maybe (Coercion (Map Key v) (KeyMap v)) coercionToMap = Nothing {-# INLINE coercionToMap #-} -- | Transform the keys and values of a 'KeyMap'. mapKeyVal :: (Key -> Key) -> (v1 -> v2) -> KeyMap v1 -> KeyMap v2 mapKeyVal fk kv = foldrWithKey (\k v -> insert (fk k) (kv v)) empty {-# INLINE mapKeyVal #-} -- | Filter all keys/values that satisfy some predicate. filter :: (v -> Bool) -> KeyMap v -> KeyMap v filter f (KeyMap m) = KeyMap (H.filter f m) -- | Filter all keys/values that satisfy some predicate. filterWithKey :: (Key -> v -> Bool) -> KeyMap v -> KeyMap v filterWithKey f (KeyMap m) = KeyMap (H.filterWithKey f m) -- | Map values and collect the Just results. mapMaybe :: (a -> Maybe b) -> KeyMap a -> KeyMap b mapMaybe f (KeyMap m) = KeyMap (H.mapMaybe f m) -- | Map values and collect the Just results. mapMaybeWithKey :: (Key -> v -> Maybe u) -> KeyMap v -> KeyMap u mapMaybeWithKey f (KeyMap m) = KeyMap (H.mapMaybeWithKey f m) #endif ------------------------------------------------------------------------------- -- combinators using existing abstractions ------------------------------------------------------------------------------- -- | Generalized union with combining function. alignWith :: (These a b -> c) -> KeyMap a -> KeyMap b -> KeyMap c alignWith f (KeyMap x) (KeyMap y) = KeyMap (SA.alignWith f x y) -- | Generalized union with combining function. alignWithKey :: (Key -> These a b -> c) -> KeyMap a -> KeyMap b -> KeyMap c alignWithKey f (KeyMap x) (KeyMap y) = KeyMap (SAI.ialignWith f x y) -- | Convert a 'KeyMap' to a @'HashMap' 'Text'@. toHashMapText :: KeyMap v -> HashMap Text v toHashMapText = H.fromList . L.map (first Key.toText) . toList -- | Convert a @'HashMap' 'Text'@to a 'KeyMap'. fromHashMapText :: HashMap Text v -> KeyMap v fromHashMapText = fromList . L.map (first Key.fromText) . H.toList -- | Convert a 'KeyMap' to a @'Map' 'Text'@. -- -- @since 2.0.2.0 toMapText :: KeyMap v -> Map Text v toMapText = M.fromList . L.map (first Key.toText) . toList -- | Convert a @'Map' 'Text'@to a 'KeyMap'. -- -- @since 2.0.2.0 fromMapText :: Map Text v -> KeyMap v fromMapText = fromList . L.map (first Key.fromText) . M.toList ------------------------------------------------------------------------------- -- Instances ------------------------------------------------------------------------------- -- This are defined using concrete combinators above. instance Read v => Read (KeyMap v) where readPrec = parens $ prec 10 $ do Ident "fromList" <- lexP xs <- readPrec return (fromList xs) readListPrec = readListPrecDefault instance Show v => Show (KeyMap v) where showsPrec d m = showParen (d > 10) $ showString "fromList " . shows (toAscList m) instance F.Foldable KeyMap where foldMap f = foldMapWithKey (\ _k v -> f v) {-# INLINE foldMap #-} foldr = foldr foldr' = foldr' foldl = foldl foldl' = foldl' null = null length = size instance T.Traversable KeyMap where traverse = traverse instance Semigroup (KeyMap v) where (<>) = union instance Monoid (KeyMap v) where mempty = empty mappend = (<>) -- | @since 2.0.2.0 instance GHC.Exts.IsList (KeyMap v) where type Item (KeyMap v) = (Key, v) fromList = fromList toList = toAscList ------------------------------------------------------------------------------- -- template-haskell ------------------------------------------------------------------------------- instance TH.Lift v => TH.Lift (KeyMap v) where lift m = [| fromList m' |] where m' = toList m #if MIN_VERSION_template_haskell(2,17,0) liftTyped = TH.unsafeCodeCoerce . TH.lift #elif MIN_VERSION_template_haskell(2,16,0) liftTyped = TH.unsafeTExpCoerce . TH.lift #endif ------------------------------------------------------------------------------- -- hashable ------------------------------------------------------------------------------- instance Hashable v => Hashable (KeyMap v) where #ifdef USE_ORDEREDMAP hashWithSalt salt (KeyMap m) = M.foldlWithKey' (\acc k v -> acc `hashWithSalt` k `hashWithSalt` v) (hashWithSalt salt (M.size m)) m #else hashWithSalt salt (KeyMap hm) = hashWithSalt salt hm #endif ------------------------------------------------------------------------------- -- deepseq ------------------------------------------------------------------------------- instance NFData v => NFData (KeyMap v) where rnf (KeyMap hm) = rnf hm ------------------------------------------------------------------------------- -- indexed-traversable ------------------------------------------------------------------------------- instance WI.FunctorWithIndex Key KeyMap where imap = mapWithKey instance WI.FoldableWithIndex Key KeyMap where ifoldr = foldrWithKey instance WI.TraversableWithIndex Key KeyMap where itraverse = traverseWithKey ------------------------------------------------------------------------------- -- semialign ------------------------------------------------------------------------------- instance SA.Zip KeyMap where zipWith = intersectionWith instance SAI.ZipWithIndex Key KeyMap where izipWith = intersectionWithKey instance SA.Semialign KeyMap where alignWith = alignWith instance SAI.SemialignWithIndex Key KeyMap where ialignWith = alignWithKey instance SA.Align KeyMap where nil = empty ------------------------------------------------------------------------------- -- witherable ------------------------------------------------------------------------------- instance W.Filterable KeyMap where filter = filter mapMaybe = mapMaybe instance W.Witherable KeyMap where instance W.FilterableWithIndex Key KeyMap where ifilter = filterWithKey imapMaybe = mapMaybeWithKey instance W.WitherableWithIndex Key KeyMap where
dmjio/aeson
src/Data/Aeson/KeyMap.hs
bsd-3-clause
21,709
0
11
4,242
3,874
2,112
1,762
-1
-1